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-18T22:21:49.084475+00:00
2020-02-04T20:06:57
51ca3268330f2fd438215d48518f56fc0872bfe3
{ "blob_id": "51ca3268330f2fd438215d48518f56fc0872bfe3", "branch_name": "refs/heads/master", "committer_date": "2020-02-04T20:06:57", "content_id": "d46aff7c1d7faff873bd9cd6e6ccdd0b931295d3", "detected_licenses": [ "MIT" ], "directory_id": "c5c71d44ae35aabbcfc63b2ba5faee9796542832", "extension": "c", "filename": "E4.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 238285587, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 489, "license": "MIT", "license_type": "permissive", "path": "/Lista 06 - Caracteres/E4.c", "provenance": "stackv2-0123.json.gz:6531", "repo_name": "vitordutra/algoritmos-programacao-ufsm-2018-2", "revision_date": "2020-02-04T20:06:57", "revision_id": "721fe06da40a0b667098b5121ca1dfe0379e6f16", "snapshot_id": "fb75e6533955e51165e85ce35abe71848ceafd0f", "src_encoding": "ISO-8859-1", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vitordutra/algoritmos-programacao-ufsm-2018-2/721fe06da40a0b667098b5121ca1dfe0379e6f16/Lista 06 - Caracteres/E4.c", "visit_date": "2020-12-28T10:20:22.124441" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> /* 4) Faça um algoritmo para ler uma string e retorne o número de palavras da mesma; */ int main(int argc, char *argv[]) { char texto[50]; int i, c, cont = 0; fgets(texto, 150, stdin); c = strlen(texto); printf("Numero de letras = %d", c); for (i = 0; texto[i] != '\0'; i++) { if (texto[i] == ' ') { cont++; } } printf("\nNumero de palavras = %d", cont+1); return 0; }
3.71875
4
2024-11-18T22:21:49.149495+00:00
2016-02-17T01:04:54
90831985c7bff9026739c0611d204b09402b39c1
{ "blob_id": "90831985c7bff9026739c0611d204b09402b39c1", "branch_name": "refs/heads/master", "committer_date": "2016-02-17T01:04:54", "content_id": "e146bbc467c57f120b0812ca554e1705857b1800", "detected_licenses": [ "MIT" ], "directory_id": "95a798aabefb28aec56041b4386443d2d35ede92", "extension": "h", "filename": "cj_cdev.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 48629711, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 688, "license": "MIT", "license_type": "permissive", "path": "/chardev/cj_cdev.h", "provenance": "stackv2-0123.json.gz:6661", "repo_name": "cjackie/linux-kernel-modules", "revision_date": "2016-02-17T01:04:54", "revision_id": "68cfb28430aea842b0c5944fa789cdab37999d94", "snapshot_id": "50adf735a47e51f68a573cf9337b4b72835188b3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cjackie/linux-kernel-modules/68cfb28430aea842b0c5944fa789cdab37999d94/chardev/cj_cdev.h", "visit_date": "2021-01-10T13:41:45.369721" }
stackv2
#ifndef MY_CDEV_H #define MY_CDEV_H // uncomment to enable dubug info #define CJ_DEBUG struct cj_list { struct cj_list *next; /* pointing to the next element */ long dsize; /* max size of the data */ long cdsize; /* space that has been filled up */ char *data; /* data pointer */ }; struct cj_cdev { struct cj_list *head; /* link list */ long dsize; /* max size of the data content in each list */ long total_size; /* total data in memory */ struct semaphore sem; /* mutual exclusion semaphore */ struct cdev cdev; /* Char device structure */ }; #endif /* MY_CDEV_H */
2.015625
2
2024-11-18T22:21:49.269361+00:00
2019-07-05T21:04:28
caa503558027e00c242520cd23f9e56752a1906c
{ "blob_id": "caa503558027e00c242520cd23f9e56752a1906c", "branch_name": "refs/heads/master", "committer_date": "2019-07-05T21:04:28", "content_id": "7e4b39b2e1c7bd315c11d1d95aa3d290d2b00a4d", "detected_licenses": [ "MIT" ], "directory_id": "8e2a09d45dac8d17a2714219460f58190cdd86f5", "extension": "c", "filename": "Kleingaerten_Jan_Groeneveld.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 195466871, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7999, "license": "MIT", "license_type": "permissive", "path": "/Aufgabe_4/Kleingaerten_Jan_Groeneveld.c", "provenance": "stackv2-0123.json.gz:6789", "repo_name": "jannikgro/37_BwInf_Runde_1", "revision_date": "2019-07-05T21:04:28", "revision_id": "2320fe69f2cb31ac469199c164d1c06585c8e01e", "snapshot_id": "60009131b13570895ba9202c03f59b0f917e991b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jannikgro/37_BwInf_Runde_1/2320fe69f2cb31ac469199c164d1c06585c8e01e/Aufgabe_4/Kleingaerten_Jan_Groeneveld.c", "visit_date": "2020-06-16T03:29:15.606803" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <math.h> #define MAXKANTE 100 // Hier wird die maximale Kantenlaenge fuer das auszuprobierende Gebiet definiert. #define MAXGRUND 10 // Hier wird die maximale Zahl an setzbaren Grundstuecken festgelegt #define true 't' // Weil es in C keine standardmaessigen Booleans gibt, muss dieser Datentyp erst definiert werden. #define false 'f' typedef char bool; int flaeche[MAXKANTE][MAXKANTE]; // Hier wird der 2D-Array definiert, in dem die Grundstuecke angeordnet werden. int anzahlgrund; int xkante; int ykante; int gesamtflaeche; typedef struct Wunschstueck { int x; int y; int grundstuecksflaeche; } Wunschstueck; Wunschstueck *liste[MAXGRUND]; Wunschstueck *new_stueck(int ux, int uy) // In dieser Struktur werden die wichtigen Eigenschaften der Grundstuecke gespeichert. Der Array in der oberen Zeile speichert die Zeiger auf diese Grundstuecke. { Wunschstueck *mystueck = (Wunschstueck *)malloc(sizeof(Wunschstueck)); mystueck->x = ux; mystueck->y = uy; mystueck->grundstuecksflaeche = ux * uy; return mystueck; } void init_flaeche() // Diese Funktion bereitet die Flaeche so vor, dass sie fuer das Ausprobieren nutzbar ist, indem ueberall -1 hineingeschrieben wird { for (int i = 0; i < MAXKANTE; i++) { for (int j = 0; j < MAXKANTE; j++) flaeche[i][j] = -1; } } void calc_total_area() // Diese Funktion summiert die Einzelflaechen der Grundstuecke { for (int i = 0; i < anzahlgrund; i++) gesamtflaeche += liste[i]->grundstuecksflaeche; } void printflaeche() // Diese Funktion stellt die Anordnung grafisch dar. { for (int i = 0; i < ykante; i++) { for (int j = 0; j < xkante; j++) { if (flaeche[j][i] == -1) printf(" ."); else printf("%2d", flaeche[j][i]); } printf("\n"); } } bool reserve(int depth, int x, int y) // Dise Funktion reserviert den Platz fuer ein Grundstueck { if (x + liste[depth]->x > xkante || y + liste[depth]->y > ykante) // Wenn das Grundstueck den benutzbaren Bereich verlaesst, ist dieser Platz fuer diesen Garten ungueltig. return false; for (int i = 0; i < liste[depth]->y; i++) { for (int j = 0; j < liste[depth]->x; j++) { if (flaeche[x + j][y + i] != -1) // Wenn an einer Stelle, an der der Platz reserviert werden soll, bereits ein Garten geplant wird, ist der Platz ebenfalls ungueltig. return false; } } for (int i = 0; i < liste[depth]->y; i++) { for (int j = 0; j < liste[depth]->x; j++) flaeche[x + j][y + i] = depth; // Hier wird der Platz reserviert. } return true; } void reset(int depth, int x, int y) // Diese Funktion loescht das Grundstueck der Nummer "depth" wieder von der Flaeche { for (int i = 0; i < liste[depth]->y; i++) { for (int j = 0; j < liste[depth]->x; j++) { flaeche[x + j][y + i] = -1; } } } bool ausprobieren(int depth) { for (int i = 0; i < xkante; i++) // Diese verschachtelte Zaehlschleife probiert alle denkbaren Positionen auf dem Feld aus. { for (int j = 0; j < ykante; j++) { for (int z = 0; z < 2; z++) { if (z == 1) // Anhand des Wertes der inneren Zaehlschleife wird bestimmt, ob das Grundstueck gedreht wird, um diese Moeglichkeiten auch zu beruecksichtigen. { int hilf = liste[depth]->x; liste[depth]->x = liste[depth]->y; liste[depth]->y = hilf; } if (reserve(depth, j, i) == true) // Der Platz fuer das Grundstueck wird reserviert. { if (depth + 1 < anzahlgrund) // Falls noch nicht alle Grundstuecke verteilt wurden, wird mit den Grundstueck der naechsten Stufe fortgefahren { if (ausprobieren(depth + 1) == true) { reset(depth, j, i); return true; } } else // Andernfalls wurden bereits alle Grundstuecke gueltig verteilt. Dann ist die Aufgabe geloest! { printflaeche(); reset(depth, j, i); return true; } reset(depth, j, i); // Nach Abschluss des Durchlaufes muss die Reservierung wieder geloescht werden. } } } } return false; } int teilersuchen() { int teiler[MAXKANTE]; // In diesem Array wird die Anzahl der Grundstuecksausmasse gefuehrt, die durch den Wert des jeweiligen Elements teilbar sind. for (int i = 0; i < MAXKANTE; i++) teiler[i] = 0; for (int i = 0; i < anzahlgrund; i++) // Die aeussere Zaehlschleife prueft zaehlt alle Grundstuecke durch. { for (int j = 0; j < 2; j++) // Diese Zaehlschleife zaehlt nur von 0 bis 1. { int test = (j == 0) ? liste[i]->x : liste[i]->y; // Mit den Werten aus dieser mittleren Zaehlschleife wird bestimmt, ob die x- oder y-Variable auf Teilbarkeit geprueft wird. for (int k = 2; k <= test; k++) // Alle Zahlen ab zwei bis zum Wert werden auf Teilbarkeit geprueft { if (test % k == 0) teiler[k]++; } } } int groessterteiler = 1; for (int i = 2; i < MAXKANTE; i++) { if (teiler[i] == anzahlgrund * 2) groessterteiler = i; } return groessterteiler; } void teilen(int teiler) // Diese Funktion teilt die Kantenlaengen der Grundstuecke durch ihren gemeinsamen Teiler, falls dieser ungleich 1 ist. { for (int i = 0; i < anzahlgrund; i++) { liste[i]->x /= teiler; liste[i]->y /= teiler; liste[i]->grundstuecksflaeche = liste[i]->x * liste[i]->y; } } bool flaechen_ausprobieren() { for (int i = gesamtflaeche; i < (MAXKANTE * MAXKANTE); i++) // Diese aeussere Zaehlschleife erhoeht die Flaeche immer um 1, falls zuvor keine gueltige Anordnung erreicht werden konnte. { for (int j = (int)sqrt(i); j > 0; j--) // Diese innere Zaehlschleife beginnt bei der Wurzel der Flaeche, um Teilerpaare zu suchen. { if (i % j == 0) // Fuer die auszuprobierende Flaeche werden ganzzahlige Teiler benoetigt. Nur wenn die Division { // der Flaeche mit dem ersten Teiler keinen Rest uebrig laesst, ist das Wertepaar geeignet. xkante = j; ykante = i / j; if (ausprobieren(0) == true) // Mit dem Wertepaar fuer die Flaeche soll eine Kombination ausprobiert werden. { // Wenn eine Kombination moeglich ist, wurde in der Funktion bereits das Ergebnis ausgedruckt. Die Daten folgen hier: printf("Diese Loesung hat eine Flaeche von %d bei Kantenlaengen von %d und %d. Das bedeutet eine Effizienz von %3.2lf%c, weil die minimale Flaeche %d gewesen waere.\n", i, xkante, ykante, ((double)gesamtflaeche / (double)i) * 100, (char)37, gesamtflaeche); return true; } } } } return false; } int main() { // Anzahl und Abmessungen der Gaerten werden erfragt printf("Wie viele Gaerten sollen angelegt weden? (maximal %d)\n", MAXGRUND); scanf("%d", &anzahlgrund); for (int i = 0; i < anzahlgrund; i++) { printf("Welche Abmessungen soll der naechste Garten mit der Nummer %d haben? (x*y)\n", i); int x = 0; int y = 0; scanf("%d*%d", &x, &y); liste[i] = new_stueck(x, y); } int groessterteiler = teilersuchen(); // Groessten gemeinsamen Teiler suchen, teilen und Meldung ausgeben if (groessterteiler != 1) { printf("Man kann diese Gaertenlaengen durch %d dividieren, damit weniger zu rechnen ist.\nDer Ausdruck ist um diesen Maßstabsfaktor verkleinert.\nBitte beachten Sie, dass sich die Angaben ueber die Flaeche zum Quadrat dieses Faktors verkleinern.\n", groessterteiler); teilen(groessterteiler); } init_flaeche(); // globaler 2D-Array der fuer das Ausprobieren wichtigen Flaeche wird so initialisiert, dass ueberall -1, also frei eingetragen wird. calc_total_area(); // Gesamtflaeche wird als Summe der Einzelflaechen berechnet und in die globale Variable "gesamtflaeche" geschrieben. bool test = flaechen_ausprobieren(); // fuer Funktionsweise: siehe Funktion printf("%s", (test == true) ? "Das Programm ist beendet.\n" : "Es ist ein Fehler aufgetreten"); return 0; }
3.078125
3
2024-11-18T22:21:49.463249+00:00
2021-05-25T20:02:44
21bb1c0a6a71db0af0f1e356c448d80ed1c0eb14
{ "blob_id": "21bb1c0a6a71db0af0f1e356c448d80ed1c0eb14", "branch_name": "refs/heads/main", "committer_date": "2021-05-25T20:02:44", "content_id": "9726c460ce9215d5640dc4c93d0ff6f52a8ec745", "detected_licenses": [ "MIT" ], "directory_id": "c216d89c418e998513d0bccbe308f46be9222dd4", "extension": "c", "filename": "typedef2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 359409672, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 204, "license": "MIT", "license_type": "permissive", "path": "/adv_datatypes/typedef2.c", "provenance": "stackv2-0123.json.gz:7046", "repo_name": "liangcorp/learning_c", "revision_date": "2021-05-25T20:02:44", "revision_id": "5d77d0beec5557d7f077fc0760e6c8513d820403", "snapshot_id": "8235b00a776864eaeef6c4bddd9271e993ce1134", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/liangcorp/learning_c/5d77d0beec5557d7f077fc0760e6c8513d820403/adv_datatypes/typedef2.c", "visit_date": "2023-05-06T09:11:26.263777" }
stackv2
#include <stdio.h> #define int_pointer int * int_pointer chalk, cheese; // same as int *chalk, cheese; NOT RIGHT! typedef char * char_ptr; char_ptr Bently, Rolls_Royce; int main() { return 0; }
2.015625
2
2024-11-18T22:21:49.559575+00:00
2020-08-28T07:49:37
1c65a15dd0b0c9836ac2dc08480595bf936e46ae
{ "blob_id": "1c65a15dd0b0c9836ac2dc08480595bf936e46ae", "branch_name": "refs/heads/master", "committer_date": "2020-08-28T07:49:37", "content_id": "4ff0571b90fcd060e7901e070dc6708542542143", "detected_licenses": [ "MIT" ], "directory_id": "44527130af87cb62e062b1716779fb1eab99da53", "extension": "c", "filename": "client.c", "fork_events_count": 1, "gha_created_at": "2020-08-29T01:42:56", "gha_event_created_at": "2020-08-29T01:42:57", "gha_language": null, "gha_license_id": "MIT", "github_id": 291180121, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5199, "license": "MIT", "license_type": "permissive", "path": "/计算机网络/socketChat/source/client/client.c", "provenance": "stackv2-0123.json.gz:7175", "repo_name": "LucyLiszt/ZJU-CS-GIS-ClassNotes", "revision_date": "2020-08-28T07:49:37", "revision_id": "f169cd8268593fdd29805df5d3fa7bcd6466603a", "snapshot_id": "b7cadfcde6db63a103b312d361321516173fd584", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LucyLiszt/ZJU-CS-GIS-ClassNotes/f169cd8268593fdd29805df5d3fa7bcd6466603a/计算机网络/socketChat/source/client/client.c", "visit_date": "2022-12-10T23:27:49.569407" }
stackv2
#include "../socketChat.h" sem_t bin_sem; struct Message m; int connectedState=0; void *thread_sender(void *arg); void *thread_accepter(void *arg); int testConnection(){ if(!connectedState){ printf("not connected!\n"); return 1; } return 0; } int connectServer(char *serAddress,int port){ int sockfd, len, result; struct sockaddr_in address; /* Create a socket for the client. */ sockfd = socket(AF_INET, SOCK_STREAM, 0); /* Name the socket, as agreed with the server. */ address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(serAddress); address.sin_port = htons(port); len = sizeof(address); /* connect our socket to the server's socket. */ result = connect(sockfd, (struct sockaddr *)&address, len); if(result == -1) { perror("oops: client3\n"); return -1; } printf("connected\n"); connectedState=1; return sockfd; } pthread_t newAcceptT(int sockfd, void *(*thread_function)(void *)){ int res; pthread_t a_thread; res = pthread_create(&a_thread, NULL, thread_function, (void *)sockfd); if (res != 0) { perror("Thread creation failed\n"); exit(EXIT_FAILURE); } return a_thread; } int main(int argc, char *argv[]) { if(argc!=2){ printf("usage: ./cli IPaddress"); exit(0); } int i; void *thread_result; int sockfd; pthread_t accepterT; pthread_t senderT; while(1){ printf("the client start:\n 0-> exit \n 1-> connect \n 2-> disconnect \n 3-> getTime \n 4-> getName \n 5-> sendMessage to \n 6-> get all clients\n"); scanf("%d",&i); switch(i){ case 0: if(testConnection()) exit(0); else printf("must disconnect first!\n"); case 1: if(connectedState){ printf("connected!"); continue; } m.type = 1; sockfd = connectServer(argv[1],2760); if(sockfd==-1) continue; accepterT = newAcceptT(sockfd,thread_accepter); senderT = newAcceptT(sockfd,thread_sender); int res = sem_init(&bin_sem, 0, 0); if (res != 0) { perror("Semaphore initialization failed"); exit(EXIT_FAILURE); } break; case 2: if(testConnection()) continue; m.type='q'; m.content[0]=0; sem_post(&bin_sem); res = pthread_join(accepterT, &thread_result); if (res != 0) { perror("Thread join failed"); exit(EXIT_FAILURE); } res = pthread_join(senderT, &thread_result); if (res != 0) { perror("Thread join failed"); exit(EXIT_FAILURE); } sem_destroy(&bin_sem); close(sockfd); exit(0); break; case 3: if(testConnection()) continue; m.type='t'; m.content[0]=0; sem_post(&bin_sem); break; case 4: if(testConnection()) continue; m.type='n'; m.content[0]=0; sem_post(&bin_sem); break; case 5: if(testConnection()) continue; printf("enter message: "); scanf("\n"); fgets(m.content,BUFFER_SIZE,stdin); printf("enter the client id you want to send to: "); scanf("%d",&m.des); m.type='m'; sem_post(&bin_sem); break; case 6: if(testConnection()) continue; m.type='g'; m.content[0]=0; sem_post(&bin_sem); break; default: printf("wrong enter, again\n"); break; } } } /* the thread to receive message */ void *thread_accepter(void *arg) { int sockfd = (int)arg; while(1){ struct Message m1; if(!getMessage(&m1,sockfd)) exit(-1); if(m1.type=='q') pthread_exit(NULL); } } /* the thread to send message */ void *thread_sender(void *arg) { int sockfd = (int)arg; sem_wait(&bin_sem); while(1){ sendMessage(&m,sockfd); if(m.type=='q') pthread_exit(NULL); sem_wait(&bin_sem); } }
2.65625
3
2024-11-18T22:21:50.361037+00:00
2023-04-11T18:42:10
0b54796cf59e1a8e0567cb4ab286d4c00b72cf02
{ "blob_id": "0b54796cf59e1a8e0567cb4ab286d4c00b72cf02", "branch_name": "refs/heads/master", "committer_date": "2023-04-11T18:42:10", "content_id": "712bb2dbad39f2a94d8413d30203151d58250c24", "detected_licenses": [ "MIT" ], "directory_id": "2ea83bf2ce1ca79e046e9fa3cb1afd201cee4654", "extension": "c", "filename": "epoll-test.c", "fork_events_count": 23, "gha_created_at": "2016-02-27T17:49:05", "gha_event_created_at": "2023-02-05T07:37:56", "gha_language": "C", "gha_license_id": "MIT", "github_id": 52680190, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 55090, "license": "MIT", "license_type": "permissive", "path": "/test/epoll-test.c", "provenance": "stackv2-0123.json.gz:7305", "repo_name": "jiixyj/epoll-shim", "revision_date": "2023-04-11T18:42:10", "revision_id": "538cf422ee062eca456c5455f666ae5c41c3c519", "snapshot_id": "069ab842a51f986de569b478b2ae55276f8c53c5", "src_encoding": "UTF-8", "star_events_count": 78, "url": "https://raw.githubusercontent.com/jiixyj/epoll-shim/538cf422ee062eca456c5455f666ae5c41c3c519/test/epoll-test.c", "visit_date": "2023-04-13T00:11:50.732876" }
stackv2
#define _GNU_SOURCE #include <atf-c.h> #include <errno.h> #include <signal.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/eventfd.h> #include <sys/param.h> #include <sys/signalfd.h> #include <sys/timerfd.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/time.h> #include <arpa/inet.h> #include <netinet/in.h> #include <err.h> #include <fcntl.h> #include <limits.h> #include <poll.h> #include <pthread.h> #include <time.h> #include <unistd.h> #ifndef __linux__ #include <epoll-shim/detail/poll.h> #endif #include "atf-c-leakcheck.h" #ifdef USE_EPOLLRDHUP_LINUX_DEFINITION #undef EPOLLRDHUP #define EPOLLRDHUP 0x2000 #endif static void fd_pipe(int fds[3]) { fds[2] = -1; ATF_REQUIRE(pipe2(fds, O_CLOEXEC) == 0); } static void fd_domain_socket(int fds[3]) { fds[2] = -1; ATF_REQUIRE(socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) == 0); } static int connector_epfd = -1; static void * connector_client(void *arg) { (void)arg; int sock = socket(PF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); ATF_REQUIRE(sock >= 0); if (connector_epfd >= 0) { int ep = connector_epfd; struct epoll_event event; event.events = EPOLLOUT | EPOLLIN; event.data.fd = sock; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, sock, &event) == 0); int ret; for (int i = 0; i < 3; ++i) { ret = epoll_wait(ep, &event, 1, 300); #ifndef EV_FORCEONESHOT if (ret == 0) { continue; } #endif ATF_REQUIRE(ret == 1); ATF_REQUIRE(event.events == (EPOLLOUT | EPOLLHUP)); } } struct sockaddr_in addr = { 0 }; addr.sin_family = AF_INET; addr.sin_port = htons(1337); ATF_REQUIRE(inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) == 1); ATF_REQUIRE( connect(sock, (struct sockaddr const *)&addr, sizeof(addr)) == 0); return (void *)(intptr_t)sock; } static int create_bound_socket() { int sock = socket(PF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); ATF_REQUIRE(sock >= 0); int enable = 1; ATF_REQUIRE(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, /**/ &enable, sizeof(int)) == 0); struct sockaddr_in addr = { 0 }; addr.sin_family = AF_INET; addr.sin_port = htons(1337); ATF_REQUIRE(inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) == 1); ATF_REQUIRE(bind(sock, /**/ (struct sockaddr const *)&addr, sizeof(addr)) == 0); return sock; } static void fd_tcp_socket(int fds[3]) { int sock = create_bound_socket(); ATF_REQUIRE(listen(sock, 5) == 0); pthread_t client_thread; ATF_REQUIRE( pthread_create(&client_thread, NULL, connector_client, NULL) == 0); #ifdef __APPLE__ int conn = accept(sock, NULL, NULL); #else int conn = accept4(sock, NULL, NULL, SOCK_CLOEXEC); #endif ATF_REQUIRE(conn >= 0); void *client_socket = NULL; ATF_REQUIRE(pthread_join(client_thread, &client_socket) == 0); fds[0] = conn; fds[1] = (int)(intptr_t)client_socket; fds[2] = sock; } ATF_TC_WITHOUT_HEAD(epoll__simple); ATF_TC_BODY_FD_LEAKCHECK(epoll__simple, tc) { int fd; ATF_REQUIRE_MSG((fd = epoll_create1(EPOLL_CLOEXEC)) >= 0, "errno: %d/%s", errno, strerror(errno)); ATF_REQUIRE(close(fd) == 0); ATF_REQUIRE_ERRNO(EINVAL, epoll_create(0) < 0); ATF_REQUIRE(epoll_create(1) >= 0); ATF_REQUIRE(close(fd) == 0); ATF_REQUIRE_ERRNO(EINVAL, epoll_create1(42) < 0); } ATF_TC_WITHOUT_HEAD(epoll__poll_flags); ATF_TC_BODY_FD_LEAKCHECK(epoll__poll_flags, tc) { ATF_REQUIRE(POLLIN == EPOLLIN); ATF_REQUIRE(POLLPRI == EPOLLPRI); ATF_REQUIRE(POLLOUT == EPOLLOUT); ATF_REQUIRE(POLLERR == EPOLLERR); ATF_REQUIRE(POLLHUP == EPOLLHUP); #ifdef EPOLLNVAL ATF_REQUIRE(POLLNVAL == EPOLLNVAL); #endif #ifdef POLLRDHUP ATF_REQUIRE(POLLRDHUP == EPOLLRDHUP); #endif } ATF_TC_WITHOUT_HEAD(epoll__leakcheck); ATF_TC_BODY_FD_LEAKCHECK(epoll__leakcheck, tc) { int fd; ATF_REQUIRE((fd = epoll_create1(EPOLL_CLOEXEC)) >= 0); atf_tc_expect_fail("Test that the leak check works"); } ATF_TC_WITHOUT_HEAD(epoll__fd_exhaustion); ATF_TC_BODY_FD_LEAKCHECK(epoll__fd_exhaustion, tc) { struct rlimit lim = { 512, 512 }; ATF_REQUIRE(setrlimit(RLIMIT_NOFILE, &lim) == 0); size_t nr_fds = 1000; int *fds = malloc(nr_fds * sizeof(int)); ATF_REQUIRE(fds != NULL); size_t i = 0; for (i = 0; i < nr_fds; ++i) { if ((fds[i] = epoll_create1(EPOLL_CLOEXEC)) >= 0) { continue; } ATF_REQUIRE(errno == EMFILE); break; } while (i > 0) { --i; ATF_REQUIRE(close(fds[i]) == 0); } free(fds); } ATF_TC_WITHOUT_HEAD(epoll__invalid_op); ATF_TC_BODY_FD_LEAKCHECK(epoll__invalid_op, tc) { int fd; int fd2; int const invalid_fd = 0xbeef; struct epoll_event event; event.events = EPOLLIN; event.data.fd = 0; ATF_REQUIRE((fd = epoll_create1(EPOLL_CLOEXEC)) >= 0); ATF_REQUIRE_ERRNO(EINVAL, epoll_ctl(fd, EPOLL_CTL_ADD, fd, &event) < 0); ATF_REQUIRE_ERRNO(EINVAL, epoll_ctl(fd, EPOLL_CTL_DEL, fd, &event) < 0); ATF_REQUIRE_ERRNO(EINVAL, epoll_ctl(fd, EPOLL_CTL_MOD, fd, &event) < 0); ATF_REQUIRE_ERRNO(EINVAL, /**/ epoll_ctl(fd, 42, fd, &event) < 0); ATF_REQUIRE_ERRNO(EFAULT, /**/ epoll_ctl(fd, EPOLL_CTL_ADD, fd, NULL) < 0); ATF_REQUIRE_ERRNO(EINVAL, /**/ epoll_ctl(fd, EPOLL_CTL_DEL, fd, NULL) < 0); ATF_REQUIRE_ERRNO(EFAULT, /**/ epoll_ctl(fd, EPOLL_CTL_MOD, fd, NULL) < 0); ATF_REQUIRE_ERRNO(EFAULT, /**/ epoll_ctl(fd, 42, fd, NULL) < 0); ATF_REQUIRE(close(fd) == 0); ATF_REQUIRE((fd = epoll_create1(EPOLL_CLOEXEC)) >= 0); ATF_REQUIRE_ERRNO(EBADF, epoll_ctl(fd, EPOLL_CTL_ADD, invalid_fd, &event) < 0); ATF_REQUIRE_ERRNO(EBADF, epoll_ctl(fd, EPOLL_CTL_DEL, invalid_fd, &event) < 0); ATF_REQUIRE_ERRNO(EBADF, epoll_ctl(fd, EPOLL_CTL_MOD, invalid_fd, &event) < 0); ATF_REQUIRE_ERRNO(EBADF, /**/ epoll_ctl(fd, 42, invalid_fd, &event) < 0); ATF_REQUIRE_ERRNO(EFAULT, epoll_ctl(fd, EPOLL_CTL_ADD, invalid_fd, NULL) < 0); ATF_REQUIRE_ERRNO(EBADF, epoll_ctl(fd, EPOLL_CTL_DEL, invalid_fd, NULL) < 0); ATF_REQUIRE_ERRNO(EFAULT, epoll_ctl(fd, EPOLL_CTL_MOD, invalid_fd, NULL) < 0); ATF_REQUIRE_ERRNO(EFAULT, /**/ epoll_ctl(fd, 42, invalid_fd, NULL) < 0); ATF_REQUIRE(close(fd) == 0); ATF_REQUIRE((fd = epoll_create1(EPOLL_CLOEXEC)) >= 0); ATF_REQUIRE((fd2 = epoll_create1(EPOLL_CLOEXEC)) >= 0); ATF_REQUIRE_ERRNO(ENOENT, epoll_ctl(fd, EPOLL_CTL_DEL, fd2, &event) < 0); ATF_REQUIRE_ERRNO(ENOENT, epoll_ctl(fd, EPOLL_CTL_MOD, fd2, &event) < 0); ATF_REQUIRE_ERRNO(EINVAL, /**/ epoll_ctl(fd, 42, fd2, &event) < 0); ATF_REQUIRE_ERRNO(EFAULT, /**/ epoll_ctl(fd, EPOLL_CTL_ADD, fd2, NULL) < 0); ATF_REQUIRE_ERRNO(ENOENT, /**/ epoll_ctl(fd, EPOLL_CTL_DEL, fd2, NULL) < 0); ATF_REQUIRE_ERRNO(EFAULT, /**/ epoll_ctl(fd, EPOLL_CTL_MOD, fd2, NULL) < 0); ATF_REQUIRE_ERRNO(EFAULT, /**/ epoll_ctl(fd, 42, fd2, NULL) < 0); { struct epoll_event ev = { .events = POLLIN }; ATF_REQUIRE(epoll_ctl(fd, EPOLL_CTL_ADD, fd2, &ev) == 0); } { struct epoll_event ev = { .events = ~(uint32_t)0 }; ATF_REQUIRE(epoll_ctl(fd, EPOLL_CTL_DEL, fd2, &ev) == 0); } ATF_REQUIRE(close(fd2) == 0); ATF_REQUIRE(close(fd) == 0); /**/ ATF_REQUIRE_ERRNO(EFAULT, /**/ epoll_ctl(fd, EPOLL_CTL_ADD, fd2, NULL) < 0); ATF_REQUIRE_ERRNO(EBADF, epoll_ctl(fd, EPOLL_CTL_ADD, fd2, &event) < 0); struct epoll_event ev; ATF_REQUIRE_ERRNO(EINVAL, epoll_wait(fd, &ev, -1, 0) < 0); ATF_REQUIRE_ERRNO(EINVAL, epoll_wait(fd, &ev, 0, 0) < 0); ATF_REQUIRE_ERRNO(EBADF, epoll_wait(fd, &ev, 1, 0) < 0); } ATF_TC_WITHOUT_HEAD(epoll__invalid_op2); ATF_TC_BODY_FD_LEAKCHECK(epoll__invalid_op2, tc) { int fd; ATF_REQUIRE((fd = epoll_create1(EPOLL_CLOEXEC)) >= 0); ATF_REQUIRE(close(fd) == 0); struct epoll_event *evs = malloc( INT_MAX / sizeof(struct epoll_event) * sizeof(struct epoll_event)); if (evs == NULL) { atf_tc_skip("could not alloc enough memory for test"); } ATF_REQUIRE_ERRNO(EBADF, epoll_wait(fd, evs, /**/ INT_MAX / sizeof(struct epoll_event), 0) < 0); free(evs); ATF_REQUIRE_ERRNO(EINVAL, epoll_wait(fd, evs, /**/ INT_MAX / sizeof(struct epoll_event) + 1, 0) < 0); } ATF_TC_WITHOUT_HEAD(epoll__rdhup_linux); ATF_TC_BODY_FD_LEAKCHECK(epoll__rdhup_linux, tcptr) { if (EPOLLRDHUP == 0x2000) { return; } int fds[3]; fd_tcp_socket(fds); int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); // It is not allowed to specify both 0x2000 and EPOLLRDHUP on // systems where 0x2000 and EPOLLRDHUP differ by value (for // example on FreeBSD). On those systems it is allowed to use 0x2000 // instead of EPOLLRDHUP for Linux compatibility, but you have // to choose for each fd which value to use. struct epoll_event event = { .events = EPOLLIN | EPOLLRDHUP | 0x2000 | EPOLLPRI | EPOLLET, }; ATF_REQUIRE_ERRNO(EINVAL, epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) < 0); ATF_REQUIRE(close(ep) == 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(close(fds[2]) == 0); } ATF_TC_WITHOUT_HEAD(epoll__simple_wait); ATF_TC_BODY_FD_LEAKCHECK(epoll__simple_wait, tc) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); struct epoll_event event; ATF_REQUIRE(epoll_wait(ep, &event, 1, 1) == 0); ATF_REQUIRE(epoll_wait(ep, &event, 1, 0) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__event_size); ATF_TC_BODY_FD_LEAKCHECK(epoll__event_size, tc) { struct epoll_event event; // this check works on 32bit _and_ 64bit, since // sizeof(epoll_event) == sizeof(uint32_t) + sizeof(uint64_t) ATF_REQUIRE(sizeof(event) == 12); } ATF_TC_WITHOUT_HEAD(epoll__recursive_register); ATF_TC_BODY_FD_LEAKCHECK(epoll__recursive_register, tcptr) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int ep_inner = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep_inner >= 0); { struct epoll_event event = { .events = EPOLLOUT }; ATF_REQUIRE(epoll_ctl(ep, /**/ EPOLL_CTL_ADD, ep_inner, &event) == 0); } { struct epoll_event event = { .events = EPOLLIN }; ATF_REQUIRE(epoll_ctl(ep, /**/ EPOLL_CTL_MOD, ep_inner, &event) == 0); } ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_DEL, ep_inner, NULL) == 0); ATF_REQUIRE_ERRNO(ENOENT, epoll_ctl(ep, EPOLL_CTL_DEL, ep_inner, NULL) < 0); ATF_REQUIRE(close(ep_inner) == 0); ATF_REQUIRE(close(ep) == 0); } static void simple_epollin_impl(void (*fd_fun)(int fds[3])) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_fun(fds); struct epoll_event event; event.events = EPOLLIN; event.data.fd = fds[0]; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) >= 0); uint8_t data = '\0'; write(fds[1], &data, 1); struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); ATF_REQUIRE(event_result.data.fd == fds[0]); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC(epoll__simple_epollin); ATF_TC_HEAD(epoll__simple_epollin, tc) { atf_tc_set_md_var(tc, "X-ctest.properties", "RUN_SERIAL TRUE"); } ATF_TC_BODY_FD_LEAKCHECK(epoll__simple_epollin, tc) { simple_epollin_impl(fd_pipe); simple_epollin_impl(fd_domain_socket); simple_epollin_impl(fd_tcp_socket); } static void * sleep_then_write(void *arg) { usleep(100000); uint8_t data = '\0'; write((int)(intptr_t)arg, &data, 1); return NULL; } static void sleep_argument_impl(int sleep) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); struct epoll_event event; event.events = EPOLLIN; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) >= 0); pthread_t writer_thread; ATF_REQUIRE(pthread_create(&writer_thread, NULL, sleep_then_write, (void *)(intptr_t)(fds[1])) == 0); ATF_REQUIRE(epoll_wait(ep, &event, 1, sleep) == 1); ATF_REQUIRE(pthread_join(writer_thread, NULL) == 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__sleep_argument); ATF_TC_BODY_FD_LEAKCHECK(epoll__sleep_argument, tc) { sleep_argument_impl(-1); sleep_argument_impl(-2); } ATF_TC_WITHOUT_HEAD(epoll__remove_nonexistent); ATF_TC_BODY_FD_LEAKCHECK(epoll__remove_nonexistent, tc) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); ATF_REQUIRE_ERRNO(ENOENT, epoll_ctl(ep, EPOLL_CTL_DEL, fds[0], NULL) < 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__add_remove); ATF_TC_BODY_FD_LEAKCHECK(epoll__add_remove, tc) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); struct epoll_event event; event.events = EPOLLIN; event.data.fd = fds[0]; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_DEL, fds[0], NULL) == 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } static void add_existing_impl(bool change_udata) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); struct epoll_event event; event.events = EPOLLIN; event.data.u32 = 42; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); if (change_udata) { event.data.u32 = 43; } ATF_REQUIRE_ERRNO(EEXIST, epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) < 0); ATF_REQUIRE_ERRNO(EEXIST, epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) < 0); uint8_t data = '\0'; write(fds[1], &data, 1); struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); ATF_REQUIRE(event_result.data.u32 == 42); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__add_existing); ATF_TC_BODY_FD_LEAKCHECK(epoll__add_existing, tc) { add_existing_impl(true); add_existing_impl(false); } ATF_TC_WITHOUT_HEAD(epoll__modify_existing); ATF_TC_BODY_FD_LEAKCHECK(epoll__modify_existing, tc) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); struct epoll_event event; event.events = EPOLLIN; event.data.fd = fds[0]; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); event.events = 0; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_MOD, fds[0], &event) == 0); uint8_t data = '\0'; write(fds[1], &data, 1); struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, 50) == 0); event.events = EPOLLIN; event.data.fd = 42; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_MOD, fds[0], &event) == 0); ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); ATF_REQUIRE(event_result.data.fd == 42); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__modify_nonexisting); ATF_TC_BODY_FD_LEAKCHECK(epoll__modify_nonexisting, tc) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); struct epoll_event event; event.events = EPOLLIN; event.data.fd = fds[0]; ATF_REQUIRE_ERRNO(ENOENT, epoll_ctl(ep, EPOLL_CTL_MOD, fds[0], &event) < 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } static void * poll_only_fd_thread_fun(void *arg) { int ep = *(int *)arg; struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); return NULL; } ATF_TC_WITHOUT_HEAD(epoll__poll_only_fd); ATF_TC_BODY_FD_LEAKCHECK(epoll__poll_only_fd, tc) { #ifdef __linux__ atf_tc_skip("Test hangs on Linux"); #elif defined(__APPLE__) atf_tc_skip("/dev/random not pollable under macOS"); #endif int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fd1 = open("/dev/random", O_RDONLY | O_CLOEXEC); int fd2 = open("/dev/random", O_RDONLY | O_CLOEXEC); if (fd1 < 0 || fd2 < 0) { atf_tc_skip("This test needs /dev/random"); } struct epoll_event event = { .events = 0 }; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fd1, &event) == 0); ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fd2, &event) == 0); pthread_t threads[16]; for (int i = 0; i < 16; ++i) { ATF_REQUIRE(pthread_create(&threads[i], NULL, &poll_only_fd_thread_fun, &ep) == 0); } /* * Racy way of making sure that all threads are waiting in epoll_wait. */ usleep(200000); event.events = EPOLLIN | EPOLLRDHUP | EPOLLOUT; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_MOD, fd1, &event) == 0); for (int i = 0; i < 16; ++i) { ATF_REQUIRE(pthread_join(threads[i], NULL) == 0); } ATF_REQUIRE(close(fd1) == 0); struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, 0) == 0); ATF_REQUIRE_ERRNO(EBADF, /**/ epoll_ctl(ep, EPOLL_CTL_DEL, fd1, NULL) < 0); ATF_REQUIRE(close(fd2) == 0); ATF_REQUIRE(close(ep) == 0); } static void no_epollin_on_closed_empty_pipe_impl(bool do_write_data) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); struct epoll_event event; event.events = EPOLLIN | EPOLLRDHUP; event.data.fd = fds[0]; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); uint8_t data = '\0'; if (do_write_data) { write(fds[1], &data, 1); } close(fds[1]); struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); ATF_REQUIRE_MSG(event_result.events == (EPOLLHUP | (do_write_data ? EPOLLIN : 0)), "%x", event_result.events); ATF_REQUIRE(read(fds[0], &data, 1) >= 0); ATF_REQUIRE(event_result.data.fd == fds[0]); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__no_epollin_on_closed_empty_pipe); ATF_TC_BODY_FD_LEAKCHECK(epoll__no_epollin_on_closed_empty_pipe, tcptr) { no_epollin_on_closed_empty_pipe_impl(false); no_epollin_on_closed_empty_pipe_impl(true); } ATF_TC_WITHOUT_HEAD(epoll__write_to_pipe_until_full); ATF_TC_BODY_FD_LEAKCHECK(epoll__write_to_pipe_until_full, tcptr) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); ATF_REQUIRE(fcntl(fds[1], F_SETFL, O_NONBLOCK) == 0); struct epoll_event event; event.events = EPOLLOUT; event.data.fd = fds[1]; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[1], &event) == 0); struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); ATF_REQUIRE(event_result.data.fd == fds[1]); ATF_REQUIRE(event_result.events == EPOLLOUT); uint8_t data[512] = { 0 }; while (write(fds[1], &data, sizeof(data)) >= 0) { } ATF_REQUIRE(errno == EAGAIN || errno == EWOULDBLOCK); ATF_REQUIRE(epoll_wait(ep, &event_result, 1, 300) == 0); event.events = EPOLLIN; event.data.fd = fds[0]; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); ATF_REQUIRE(event_result.data.fd == fds[0]); ATF_REQUIRE(event_result.events == EPOLLIN); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__realtime_timer); ATF_TC_BODY_FD_LEAKCHECK(epoll__realtime_timer, tcptr) { struct timespec now; ATF_REQUIRE(clock_gettime(CLOCK_REALTIME, &now) == 0); int fd = timerfd_create(CLOCK_REALTIME, 0); ATF_REQUIRE(fd >= 0); ATF_REQUIRE(timerfd_settime(fd, TFD_TIMER_ABSTIME, &(struct itimerspec) { .it_value.tv_sec = now.tv_sec + 1, .it_value.tv_nsec = now.tv_nsec, .it_interval.tv_sec = 0, .it_interval.tv_nsec = 100000000, }, NULL) == 0); int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); struct epoll_event event; event.events = EPOLLIN | EPOLLOUT; event.data.fd = fd; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fd, &event) == 0); struct epoll_event event_result; for (uint64_t tot_exp = 0; tot_exp < 3;) { ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); ATF_REQUIRE(event_result.events == EPOLLIN); ATF_REQUIRE(event_result.data.fd == fd); uint64_t exp; ssize_t s = read(fd, &exp, sizeof(uint64_t)); ATF_REQUIRE(s == sizeof(uint64_t)); tot_exp += exp; printf("read: %llu; total=%llu\n", (unsigned long long)exp, (unsigned long long)tot_exp); } ATF_REQUIRE(close(ep) == 0); ATF_REQUIRE(close(fd) == 0); } ATF_TC_WITHOUT_HEAD(epoll__simple_signalfd); ATF_TC_BODY_FD_LEAKCHECK(epoll__simple_signalfd, tcptr) { sigset_t mask; int sfd; struct signalfd_siginfo fdsi; ssize_t s; sigemptyset(&mask); sigaddset(&mask, SIGINT); ATF_REQUIRE(sigprocmask(SIG_BLOCK, &mask, NULL) == 0); sfd = signalfd(-1, &mask, 0); ATF_REQUIRE(sfd >= 0); kill(getpid(), SIGINT); int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); struct epoll_event event; event.events = EPOLLIN | EPOLLOUT; event.data.fd = sfd; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, sfd, &event) == 0); struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); ATF_REQUIRE(event_result.events == EPOLLIN); ATF_REQUIRE(event_result.data.fd == sfd); s = read(sfd, &fdsi, sizeof(struct signalfd_siginfo)); ATF_REQUIRE(s == sizeof(struct signalfd_siginfo)); ATF_REQUIRE(fdsi.ssi_signo == SIGINT); ATF_REQUIRE(close(ep) == 0); ATF_REQUIRE(close(sfd) == 0); } ATF_TC_WITHOUT_HEAD(epoll__signalfd_poll_sigusr1); ATF_TC_BODY_FD_LEAKCHECK(epoll__signalfd_poll_sigusr1, tcptr) { /* This test is a simplified version of wayland's event_loop_signal() */ sigset_t mask; int sfd; struct signalfd_siginfo fdsi; ssize_t s; int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); sigemptyset(&mask); sigaddset(&mask, SIGUSR1); sfd = signalfd(-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK); ATF_REQUIRE(sfd >= 0); ATF_REQUIRE(sigprocmask(SIG_BLOCK, &mask, NULL) == 0); struct signal_event_source { int fd; int signum; void *data; } event_data = { .fd = sfd, .signum = SIGUSR1, .data = (void *)(intptr_t)0x12345678, }; struct epoll_event event; event.events = EPOLLIN; event.data.ptr = &event_data; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, sfd, &event) == 0); struct epoll_event event_results[32]; for (int i = 0; i < 100; ++i) { ATF_REQUIRE(epoll_wait(ep, event_results, 32, 0) == 0); ATF_REQUIRE(kill(getpid(), SIGUSR1) == 0); int r = epoll_wait(ep, event_results, 32, i == 0 ? -1 : 0); if (i != 0 && r == 0) { atf_tc_skip("EVFILT_SIGNAL might not immediately " "trigger after the kill(2)"); } ATF_REQUIRE(r == 1); ATF_REQUIRE(event_results[0].events == EPOLLIN); ATF_REQUIRE(event_results[0].data.ptr == &event_data); struct signal_event_source *event_data_ptr = event_results[0].data.ptr; ATF_REQUIRE(event_data_ptr->fd == sfd); s = read(sfd, &fdsi, sizeof(struct signalfd_siginfo)); ATF_REQUIRE(s == sizeof(struct signalfd_siginfo)); ATF_REQUIRE(fdsi.ssi_signo == SIGUSR1); } ATF_REQUIRE(close(ep) == 0); ATF_REQUIRE(close(sfd) == 0); } static void * signalfd_thread(void *arg) { int ep = *(int *)arg; struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, 0) == 0); return NULL; } static void signalfd_in_thread_test(int which) { sigset_t mask; struct signalfd_siginfo fdsi; ssize_t s; sigemptyset(&mask); sigaddset(&mask, SIGINT); ATF_REQUIRE(sigprocmask(SIG_BLOCK, &mask, NULL) == 0); int sfd = signalfd(-1, &mask, 0); ATF_REQUIRE(sfd >= 0); int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); struct epoll_event event; event.events = EPOLLIN; event.data.fd = sfd; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, sfd, &event) == 0); struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, 0) == 0); ATF_REQUIRE(pthread_kill(pthread_self(), SIGINT) == 0); { struct pollfd pfd = { .fd = ep, .events = POLLIN }; #if defined(__DragonFly__) || defined(__APPLE__) ATF_REQUIRE(poll(&pfd, 1, 0) == 0); atf_tc_skip("signals sent to threads won't trigger " "EVFILT_SIGNAL on DragonFly/macOS"); #endif ATF_REQUIRE(poll(&pfd, 1, -1) == 1); ATF_REQUIRE(pfd.revents == POLLIN); } pthread_t thread; ATF_REQUIRE(pthread_create(&thread, NULL, signalfd_thread, &ep) == 0); ATF_REQUIRE(pthread_join(thread, NULL) == 0); if (which) { struct pollfd pfd = { .fd = sfd, .events = POLLIN }; ATF_REQUIRE(poll(&pfd, 1, -1) == 1); ATF_REQUIRE(pfd.revents == POLLIN); } else { struct pollfd pfd = { .fd = ep, .events = POLLIN }; ATF_REQUIRE(poll(&pfd, 1, 0) == 0); ATF_REQUIRE(epoll_wait(ep, &event_result, 1, 0) == 0); ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_DEL, sfd, NULL) == 0); ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, sfd, &event) == 0); ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); ATF_REQUIRE(event_result.events == EPOLLIN); ATF_REQUIRE(event_result.data.fd == sfd); } s = read(sfd, &fdsi, sizeof(struct signalfd_siginfo)); ATF_REQUIRE(s == sizeof(struct signalfd_siginfo)); ATF_REQUIRE(sigprocmask(SIG_UNBLOCK, &mask, NULL) == 0); ATF_REQUIRE(close(ep) == 0); ATF_REQUIRE(close(sfd) == 0); } ATF_TC_WITHOUT_HEAD(epoll__signalfd_in_thread); ATF_TC_BODY_FD_LEAKCHECK(epoll__signalfd_in_thread, tcptr) { signalfd_in_thread_test(0); signalfd_in_thread_test(1); } static void socket_shutdown_impl(bool specify_rdhup) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_tcp_socket(fds); uint32_t rdhup_flag = specify_rdhup ? EPOLLRDHUP : 0; struct epoll_event event; event.events = EPOLLOUT | EPOLLIN | (specify_rdhup ? 0 : EPOLLRDHUP); event.data.fd = fds[0]; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); event.events = EPOLLOUT | EPOLLIN | rdhup_flag; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_MOD, fds[0], &event) == 0); ATF_REQUIRE(shutdown(fds[1], SHUT_WR) == 0); for (;;) { ATF_REQUIRE(epoll_wait(ep, &event, 1, -1) == 1); fprintf(stderr, "got event: %x\n", (int)event.events); if (event.events == EPOLLOUT) { /* skip spurious event generated by EVFILT_WRITE */ /* TODO(jan): find a better solution */ continue; } if (event.events == (EPOLLOUT | EPOLLIN | rdhup_flag)) { uint8_t buf; ssize_t ret = read(fds[0], &buf, 1); ATF_REQUIRE(ret == 0); ATF_REQUIRE(shutdown(fds[0], SHUT_WR) == 0); shutdown(fds[0], SHUT_RDWR); } else if (event.events == (EPOLLOUT | EPOLLIN | rdhup_flag | EPOLLHUP)) { /* close() may fail here! Don't check return code. */ close(fds[0]); break; #ifdef __NetBSD__ } else if (event.events == (EPOLLIN | rdhup_flag)) { continue; #endif } else { ATF_REQUIRE(false); } } ATF_REQUIRE(epoll_wait(ep, &event, 1, 300) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC(epoll__socket_shutdown); ATF_TC_HEAD(epoll__socket_shutdown, tc) { atf_tc_set_md_var(tc, "X-ctest.properties", "RUN_SERIAL TRUE"); } ATF_TC_BODY_FD_LEAKCHECK(epoll__socket_shutdown, tcptr) { socket_shutdown_impl(true); socket_shutdown_impl(false); } ATF_TC_WITHOUT_HEAD(epoll__epollhup_on_fresh_socket); ATF_TC_BODY_FD_LEAKCHECK(epoll__epollhup_on_fresh_socket, tcptr) { int sock = socket(PF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); ATF_REQUIRE(sock >= 0); int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); struct epoll_event event; event.events = EPOLLIN | EPOLLRDHUP | EPOLLOUT; event.data.fd = sock; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, sock, &event) == 0); for (int i = 0; i < 3; ++i) { int ret = epoll_wait(ep, &event, 1, 1000); if (ret == 0) { atf_tc_skip("BSD's don't return POLLHUP on " "not yet connected sockets"); } ATF_REQUIRE(ret == 1); ATF_REQUIRE(event.events == (EPOLLOUT | EPOLLHUP)); usleep(100000); } ATF_REQUIRE(close(ep) == 0); ATF_REQUIRE(close(sock) == 0); } ATF_TC(epoll__epollout_on_connecting_socket); ATF_TC_HEAD(epoll__epollout_on_connecting_socket, tc) { atf_tc_set_md_var(tc, "X-ctest.properties", "RUN_SERIAL TRUE"); } ATF_TC_BODY_FD_LEAKCHECK(epoll__epollout_on_connecting_socket, tcptr) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); for (;;) { bool success = false; int sock = socket(PF_INET, /**/ SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); ATF_REQUIRE(sock >= 0); struct epoll_event event = { .events = EPOLLIN | EPOLLRDHUP | EPOLLOUT }; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, sock, &event) == 0); int server_sock = create_bound_socket(); ATF_REQUIRE(server_sock >= 0); { struct sockaddr_in addr = { 0 }; addr.sin_family = AF_INET; addr.sin_port = htons(1337); ATF_REQUIRE(inet_pton(AF_INET, "127.0.0.1", /**/ &addr.sin_addr) == 1); ATF_REQUIRE( connect(sock, (struct sockaddr const *)&addr, sizeof(addr)) < 0); if (errno == ECONNREFUSED) { goto next; } ATF_REQUIRE(errno == EINPROGRESS); } usleep(100000); ATF_REQUIRE(close(server_sock) == 0); for (int i = 0; i < 3; ++i) { ATF_REQUIRE(epoll_wait(ep, &event, 1, -1) == 1); ATF_REQUIRE_MSG(event.events == (EPOLLIN | EPOLLRDHUP | EPOLLOUT | /**/ EPOLLERR | EPOLLHUP), "%04x", event.events); usleep(100000); } success = true; next: if (!success) { ATF_REQUIRE(close(server_sock) == 0); } ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_DEL, sock, NULL) == 0); ATF_REQUIRE(close(sock) == 0); if (success) { break; } } ATF_REQUIRE(close(ep) == 0); } static void * epollpri_thread_fun(void *arg) { int ep = *(int *)arg; struct epoll_event event_result; int r = epoll_wait(ep, &event_result, 1, 1000); if (r == 0) { atf_tc_skip("OOB data not efficiently supported without using " "SO_OOBINLINE or EVFILT_EXCEPT"); } ATF_REQUIRE(r == 1); return NULL; } ATF_TC(epoll__epollpri); ATF_TC_HEAD(epoll__epollpri, tc) { atf_tc_set_md_var(tc, "X-ctest.properties", "RUN_SERIAL TRUE"); } ATF_TC_BODY_FD_LEAKCHECK(epoll__epollpri, tcptr) { int fds[3]; fd_tcp_socket(fds); ATF_REQUIRE(fcntl(fds[0], F_SETFL, O_NONBLOCK) == 0); ATF_REQUIRE(fcntl(fds[1], F_SETFL, O_NONBLOCK) == 0); int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); struct epoll_event event = { .events = EPOLLIN | EPOLLRDHUP | EPOLLPRI | EPOLLET, }; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); char c = 'o'; ATF_REQUIRE(send(fds[1], &c, 1, MSG_OOB) == 1); c = 'n'; ATF_REQUIRE(send(fds[1], &c, 1, 0) == 1); for (;;) { ATF_REQUIRE(epoll_wait(ep, &event, 1, -1) == 1); ATF_REQUIRE(event.events == (EPOLLIN | EPOLLPRI) || event.events == EPOLLPRI); if (event.events == EPOLLPRI) { continue; } break; } { int r = epoll_wait(ep, &event, 1, 0); if (r == 1) { /* This can happen if the first event was triggered * only by a EVFILT_EXCEPT and the EVFILT_READ has not * arrived yet. */ ATF_REQUIRE(event.events == (EPOLLIN | EPOLLPRI)); } else { ATF_REQUIRE(r == 0); } } ATF_REQUIRE(recv(fds[0], &c, 1, MSG_OOB) == 1); ATF_REQUIRE(recv(fds[0], &c, 1, MSG_OOB) < 0); ATF_REQUIRE(c == 'o'); ATF_REQUIRE(recv(fds[0], &c, 1, 0) == 1); ATF_REQUIRE(recv(fds[0], &c, 1, 0) < 0); ATF_REQUIRE(c == 'n'); ATF_REQUIRE(epoll_wait(ep, &event, 1, 0) == 0); event.events = EPOLLIN | EPOLLRDHUP | EPOLLET; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_MOD, fds[0], &event) == 0); ATF_REQUIRE(epoll_wait(ep, &event, 1, 0) == 0); pthread_t thread; ATF_REQUIRE(pthread_create(&thread, /**/ NULL, &epollpri_thread_fun, &ep) == 0); usleep(200000); event.events = EPOLLIN | EPOLLRDHUP | EPOLLPRI | EPOLLET; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_MOD, fds[0], &event) == 0); c = 'o'; ATF_REQUIRE(send(fds[1], &c, 1, MSG_OOB) == 1); ATF_REQUIRE(pthread_join(thread, NULL) == 0); c = 'n'; ATF_REQUIRE(send(fds[1], &c, 1, 0) == 1); ATF_REQUIRE(recv(fds[0], &c, 1, MSG_OOB) == 1); ATF_REQUIRE(recv(fds[0], &c, 1, MSG_OOB) < 0); while (recv(fds[0], &c, 1, 0) != 1) { } ATF_REQUIRE(recv(fds[0], &c, 1, 0) < 0); ATF_REQUIRE(errno == EAGAIN || errno == EWOULDBLOCK); c = 'n'; ATF_REQUIRE(send(fds[1], &c, 1, 0) == 1); ATF_REQUIRE(epoll_wait(ep, &event, 1, -1) == 1); ATF_REQUIRE_MSG(event.events == EPOLLIN, "%04x", event.events); ATF_REQUIRE(close(ep) == 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(close(fds[2]) == 0); } ATF_TC(epoll__epollpri_oobinline); ATF_TC_HEAD(epoll__epollpri_oobinline, tc) { atf_tc_set_md_var(tc, "X-ctest.properties", "RUN_SERIAL TRUE"); } ATF_TC_BODY_FD_LEAKCHECK(epoll__epollpri_oobinline, tcptr) { int fds[3]; fd_tcp_socket(fds); ATF_REQUIRE(fcntl(fds[0], F_SETFL, O_NONBLOCK) == 0); ATF_REQUIRE(fcntl(fds[1], F_SETFL, O_NONBLOCK) == 0); { int enable = 1; setsockopt(fds[0], SOL_SOCKET, SO_OOBINLINE, /**/ &enable, sizeof(enable)); setsockopt(fds[1], SOL_SOCKET, SO_OOBINLINE, /**/ &enable, sizeof(enable)); } int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); struct epoll_event event = { .events = EPOLLIN | EPOLLRDHUP | EPOLLPRI | EPOLLET, }; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); char c = 'o'; ATF_REQUIRE(send(fds[1], &c, 1, MSG_OOB) == 1); usleep(200000); ATF_REQUIRE(epoll_wait(ep, &event, 1, -1) == 1); ATF_REQUIRE(event.events == (EPOLLIN | EPOLLPRI)); ATF_REQUIRE(epoll_wait(ep, &event, 1, 0) == 0); c = 'n'; ATF_REQUIRE(send(fds[1], &c, 1, 0) == 1); ATF_REQUIRE(recv(fds[0], &c, 1, 0) == 1); ATF_REQUIRE(c == 'o'); ATF_REQUIRE(epoll_wait(ep, &event, 1, -1) == 1); ATF_REQUIRE(event.events == EPOLLIN); ATF_REQUIRE(epoll_wait(ep, &event, 1, 0) == 0); ATF_REQUIRE(recv(fds[0], &c, 1, 0) == 1); ATF_REQUIRE(c == 'n'); ATF_REQUIRE(recv(fds[0], &c, 1, 0) < 0); ATF_REQUIRE(errno == EAGAIN || errno == EWOULDBLOCK); ATF_REQUIRE(epoll_wait(ep, &event, 1, 0) == 0); ATF_REQUIRE(close(ep) == 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(close(fds[2]) == 0); } ATF_TC(epoll__epollpri_oobinline_lt); ATF_TC_HEAD(epoll__epollpri_oobinline_lt, tc) { atf_tc_set_md_var(tc, "X-ctest.properties", "RUN_SERIAL TRUE"); } ATF_TC_BODY_FD_LEAKCHECK(epoll__epollpri_oobinline_lt, tcptr) { int fds[3]; fd_tcp_socket(fds); ATF_REQUIRE(fcntl(fds[0], F_SETFL, O_NONBLOCK) == 0); ATF_REQUIRE(fcntl(fds[1], F_SETFL, O_NONBLOCK) == 0); { int enable = 1; setsockopt(fds[0], SOL_SOCKET, SO_OOBINLINE, /**/ &enable, sizeof(enable)); setsockopt(fds[1], SOL_SOCKET, SO_OOBINLINE, /**/ &enable, sizeof(enable)); } int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); struct epoll_event event = { .events = EPOLLPRI, }; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); char c = 'o'; ATF_REQUIRE(send(fds[1], &c, 1, MSG_OOB) == 1); ATF_REQUIRE(epoll_wait(ep, &event, 1, -1) == 1); ATF_REQUIRE(event.events == EPOLLPRI); ATF_REQUIRE(epoll_wait(ep, &event, 1, -1) == 1); ATF_REQUIRE(event.events == EPOLLPRI); ATF_REQUIRE(epoll_wait(ep, &event, 1, -1) == 1); ATF_REQUIRE(event.events == EPOLLPRI); ATF_REQUIRE(recv(fds[0], &c, 1, 0) == 1); ATF_REQUIRE(c == 'o'); ATF_REQUIRE(recv(fds[0], &c, 1, 0) < 0); ATF_REQUIRE(errno == EAGAIN || errno == EWOULDBLOCK); ATF_REQUIRE(epoll_wait(ep, &event, 1, 0) == 0); c = 'n'; ATF_REQUIRE(send(fds[1], &c, 1, 0) == 1); usleep(200000); int n; ATF_REQUIRE_MSG((n = epoll_wait(ep, &event, 1, 0)) == 0, "%d 0x%x errno: %d", n, event.events, errno); ATF_REQUIRE(close(ep) == 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(close(fds[2]) == 0); } ATF_TC(epoll__timeout_on_listening_socket); ATF_TC_HEAD(epoll__timeout_on_listening_socket, tc) { atf_tc_set_md_var(tc, "X-ctest.properties", "RUN_SERIAL TRUE"); } ATF_TC_BODY_FD_LEAKCHECK(epoll__timeout_on_listening_socket, tcptr) { int sock = socket(PF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); ATF_REQUIRE(sock >= 0); int enable = 1; ATF_REQUIRE(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, /**/ &enable, sizeof(int)) == 0); struct sockaddr_in addr = { 0 }; addr.sin_family = AF_INET; addr.sin_port = htons(1337); ATF_REQUIRE(inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) == 1); ATF_REQUIRE(bind(sock, /**/ (struct sockaddr const *)&addr, sizeof(addr)) == 0); ATF_REQUIRE(listen(sock, 5) == 0); int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); struct epoll_event event; event.events = EPOLLIN; event.data.fd = sock; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, sock, &event) == 0); int ret; for (int i = 0; i < 3; ++i) { ret = epoll_wait(ep, &event, 1, 100); ATF_REQUIRE(ret == 0); usleep(100000); } ATF_REQUIRE(close(ep) == 0); ATF_REQUIRE(close(sock) == 0); } ATF_TC_WITHOUT_HEAD(epoll__epollerr_on_closed_pipe); ATF_TC_BODY_FD_LEAKCHECK(epoll__epollerr_on_closed_pipe, tcptr) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); struct epoll_event event; event.events = EPOLLOUT; event.data.fd = fds[1]; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[1], &event) == 0); for (;;) { struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); ATF_REQUIRE(event_result.data.fd == fds[1]); if (event_result.events == EPOLLOUT) { // continue } else if (event_result.events == (EPOLLOUT | EPOLLERR)) { break; #ifndef __linux__ } else if (event_result.events == EPOLLERR) { /* kqueue based emulation may * return just POLLERR here */ break; #endif } else { ATF_REQUIRE(false); } uint8_t data[512] = { 0 }; write(fds[1], &data, sizeof(data)); ATF_REQUIRE(close(fds[0]) == 0); } ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } static void shutdown_behavior_impl(void (*fd_fun)(int fds[3])) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); connector_epfd = ep; int fds[3]; fd_fun(fds); connector_epfd = -1; int counter = 0; char c = 42; write(fds[0], &c, 1); struct epoll_event event; event.events = EPOLLOUT | EPOLLIN; event.data.fd = fds[1]; epoll_ctl(ep, EPOLL_CTL_ADD, fds[1], &event); errno = 0; for (;;) { struct epoll_event event_result; int n; ATF_REQUIRE((n = epoll_wait(ep, &event_result, 1, -1)) == 1); ATF_REQUIRE(event_result.data.fd == fds[1]); // fprintf(stderr, "got event: %x %d\n", // (int)event_result.events, // (int)event_result.events); if (event_result.events & EPOLLIN) { ATF_REQUIRE((n = (int)read(fds[1], &c, 1)) == 1); ++counter; if (counter <= 5) { send(fds[0], &c, 1, MSG_NOSIGNAL); } else if (counter == 6) { send(fds[0], &c, 1, MSG_NOSIGNAL); shutdown(fds[0], SHUT_WR); usleep(100000); } else { uint8_t data[512] = { 0 }; send(fds[1], &data, sizeof(data), MSG_NOSIGNAL); close(fds[0]); event.events = EPOLLOUT; event.data.fd = fds[1]; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_MOD, /**/ fds[1], &event) == 0); usleep(100000); } } else if (event_result.events == EPOLLOUT) { send(event.data.fd, &c, 1, MSG_NOSIGNAL); // continue } else if (fd_fun == fd_domain_socket && (event_result.events & (EPOLLOUT | EPOLLHUP)) == (EPOLLOUT | EPOLLHUP)) { // TODO(jan): Linux sets EPOLLERR in addition { int error = 0; socklen_t errlen = sizeof(error); getsockopt(fds[1], SOL_SOCKET, SO_ERROR, (void *)&error, &errlen); fprintf(stderr, "socket error: %d (%s)\n", error, strerror(error)); } break; } else if (fd_fun == fd_tcp_socket && event_result.events == (EPOLLOUT | EPOLLERR | EPOLLHUP)) { { int error = 0; socklen_t errlen = sizeof(error); getsockopt(fds[1], SOL_SOCKET, SO_ERROR, (void *)&error, &errlen); fprintf(stderr, "socket error: %d (%s)\n", error, strerror(error)); } break; } else if (fd_fun == fd_tcp_socket && event_result.events == (EPOLLOUT | EPOLLHUP)) { /* * Rarely, we get here (no EPOLLERR). But don't fail * the test. There is some non-determinism involved... */ fprintf(stderr, "no socket error\n"); break; } else { ATF_REQUIRE_MSG(false, "%p(%p/%p): events %x", (void *)fd_fun, (void *)fd_domain_socket, (void *)fd_tcp_socket, event_result.events); } } ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC(epoll__shutdown_behavior); ATF_TC_HEAD(epoll__shutdown_behavior, tc) { atf_tc_set_md_var(tc, "X-ctest.properties", "RUN_SERIAL TRUE"); } ATF_TC_BODY_FD_LEAKCHECK(epoll__shutdown_behavior, tcptr) { shutdown_behavior_impl(fd_tcp_socket); shutdown_behavior_impl(fd_domain_socket); } static void * datagram_connector(void *arg) { (void)arg; int sock = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); ATF_REQUIRE(sock >= 0); struct sockaddr_in addr = { 0 }; addr.sin_family = AF_INET; addr.sin_port = htons(1337); ATF_REQUIRE(inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) == 1); ATF_REQUIRE( connect(sock, (struct sockaddr const *)&addr, sizeof(addr)) == 0); fprintf(stderr, "got client\n"); uint8_t data = '\0'; write(sock, &data, 0); usleep(500000); close(sock); return NULL; } ATF_TC(epoll__datagram_connection); ATF_TC_HEAD(epoll__datagram_connection, tc) { atf_tc_set_md_var(tc, "X-ctest.properties", "RUN_SERIAL TRUE"); } ATF_TC_BODY_FD_LEAKCHECK(epoll__datagram_connection, tcptr) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int sock = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); ATF_REQUIRE(sock >= 0); int enable = 1; ATF_REQUIRE(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, /**/ &enable, sizeof(int)) == 0); struct sockaddr_in addr = { 0 }; addr.sin_family = AF_INET; addr.sin_port = htons(1337); ATF_REQUIRE(inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) == 1); ATF_REQUIRE(bind(sock, /**/ (struct sockaddr const *)&addr, sizeof(addr)) == 0); pthread_t client_thread; pthread_create(&client_thread, NULL, datagram_connector, NULL); int fds[2]; fds[0] = sock; struct epoll_event event; event.events = EPOLLIN | EPOLLRDHUP; event.data.fd = fds[0]; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); fprintf(stderr, "got event: %x %d\n", (int)event_result.events, (int)event_result.events); ATF_REQUIRE(event_result.events == EPOLLIN); uint8_t data = '\0'; ATF_REQUIRE(read(fds[0], &data, 1) >= 0); ATF_REQUIRE(event_result.data.fd == fds[0]); pthread_join(client_thread, NULL); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC(epoll__epollout_on_own_shutdown); ATF_TC_HEAD(epoll__epollout_on_own_shutdown, tc) { atf_tc_set_md_var(tc, "X-ctest.properties", "RUN_SERIAL TRUE"); } ATF_TC_BODY_FD_LEAKCHECK(epoll__epollout_on_own_shutdown, tcptr) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_tcp_socket(fds); struct epoll_event event; event.events = EPOLLOUT; event.data.fd = fds[0]; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); shutdown(fds[0], SHUT_WR); usleep(100000); struct epoll_event event_result; ATF_REQUIRE(epoll_wait(ep, &event_result, 1, -1) == 1); ATF_REQUIRE(event_result.data.fd == fds[0]); fprintf(stderr, "got events: %x\n", (unsigned)event_result.events); ATF_REQUIRE(event_result.events == EPOLLOUT); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(fds[2] == -1 || close(fds[2]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__remove_closed); ATF_TC_BODY_FD_LEAKCHECK(epoll__remove_closed, tcptr) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); struct epoll_event event = { 0 }; event.events = EPOLLIN; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); // Trying to delete an event that was already deleted by closing the // associated fd should fail. ATF_REQUIRE_ERRNO(EBADF, epoll_ctl(ep, EPOLL_CTL_DEL, fds[0], &event) < 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__remove_closed_when_same_fd_open); ATF_TC_BODY_FD_LEAKCHECK(epoll__remove_closed_when_same_fd_open, tcptr) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); struct epoll_event event = { 0 }; event.events = EPOLLIN; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); int p[2]; ATF_REQUIRE(pipe2(p, O_CLOEXEC) == 0); ATF_REQUIRE(fds[0] == p[0]); ATF_REQUIRE(fds[1] == p[1]); // Trying to delete an event that was already deleted by closing the // associated fd should fail. ATF_REQUIRE_ERRNO(ENOENT, epoll_ctl(ep, EPOLL_CTL_DEL, fds[0], &event) < 0); ATF_REQUIRE(close(p[0]) == 0); ATF_REQUIRE(close(p[1]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__add_different_file_with_same_fd_value); ATF_TC_BODY_FD_LEAKCHECK(epoll__add_different_file_with_same_fd_value, tcptr) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); struct epoll_event event = { 0 }; event.events = EPOLLIN; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); // Note: This wouldn't be needed under Linux as the close() calls above // properly removes the descriptor from the epoll instance. However, in // our epoll emulation we cannot (yet?) reliably detect if a descriptor // has been closed before it is deleted from the epoll instance. // See also: https://github.com/jiixyj/epoll-shim/pull/7 ATF_REQUIRE_ERRNO(EBADF, epoll_ctl(ep, EPOLL_CTL_DEL, fds[0], &event) < 0); // Creating new pipe. The file descriptors will have the same numerical // values as the previous ones. fd_pipe(fds); // If status of closed fds would not be cleared, adding an event with // the fd that has the same numerical value as the closed one would // fail. int ret; struct epoll_event event2 = { 0 }; event2.events = EPOLLIN; ATF_REQUIRE((ret = epoll_ctl(ep, /**/ EPOLL_CTL_ADD, fds[0], &event2)) == 0); pthread_t writer_thread; pthread_create(&writer_thread, NULL, sleep_then_write, (void *)(intptr_t)(fds[1])); ATF_REQUIRE((ret = epoll_wait(ep, &event, 1, 300)) == 1); pthread_join(writer_thread, NULL); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__invalid_writes); ATF_TC_BODY_FD_LEAKCHECK(epoll__invalid_writes, tcptr) { sigset_t mask; int fd; sigemptyset(&mask); sigaddset(&mask, SIGINT); ATF_REQUIRE(sigprocmask(SIG_BLOCK, &mask, NULL) == 0); char dummy = 0; { fd = signalfd(-1, &mask, 0); ATF_REQUIRE(fd >= 0); ATF_REQUIRE(write(fd, &dummy, 1) < 0); /* * FreeBSD's native write returns EOPNOTSUPP. write is not * shimmed when using native eventfds. * * NetBSD's native write return ENXIO. */ ATF_REQUIRE_MSG(errno == EINVAL || errno == EOPNOTSUPP || errno == ENXIO, "%d", errno); ATF_REQUIRE(close(fd) == 0); } { fd = timerfd_create(CLOCK_MONOTONIC, 0); ATF_REQUIRE(fd >= 0); ATF_REQUIRE(write(fd, &dummy, 1) < 0); /* * NetBSD's native write return EBADF. */ ATF_REQUIRE_MSG(errno == EINVAL || errno == EOPNOTSUPP || errno == EBADF, "%d", errno); #ifndef __linux__ ATF_REQUIRE(write(fd, &dummy, (size_t)SSIZE_MAX + 1) < 0); ATF_REQUIRE_MSG(errno == EINVAL || errno == EBADF, "%d", errno); #endif ATF_REQUIRE(close(fd) == 0); } { fd = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(fd >= 0); ATF_REQUIRE(write(fd, &dummy, 1) < 0); ATF_REQUIRE_MSG(errno == EINVAL || errno == EOPNOTSUPP || errno == ENXIO /* NetBSD */, "%d", errno); ATF_REQUIRE_ERRNO(EINVAL, read(fd, &dummy, 1) < 0); #ifndef __linux__ ATF_REQUIRE_ERRNO(EINVAL, read(fd, &dummy, (size_t)SSIZE_MAX + 1) < 0); #endif ATF_REQUIRE(close(fd) == 0); } } ATF_TC_WITHOUT_HEAD(epoll__using_real_close); ATF_TC_BODY_FD_LEAKCHECK(epoll__using_real_close, tcptr) { int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); int fds[3]; fd_pipe(fds); struct epoll_event event = { 0 }; event.events = EPOLLIN; ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); // This closes the underlying kqueue fd directly, without going through // our epoll_shim_close wrapper. It shouldn't blow up too badly. extern int real_close_for_test(int fd); ATF_REQUIRE(real_close_for_test(ep) == 0); ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); ATF_REQUIRE(epoll_ctl(ep, EPOLL_CTL_ADD, fds[0], &event) == 0); ATF_REQUIRE(close(fds[0]) == 0); ATF_REQUIRE(close(fds[1]) == 0); ATF_REQUIRE(close(ep) == 0); } static sig_atomic_t volatile epoll_pwait_got_signal = 0; static void epoll_pwait_sighandler(int sig) { epoll_pwait_got_signal = 1; (void)sig; } ATF_TC_WITHOUT_HEAD(epoll__epoll_pwait); ATF_TC_BODY_FD_LEAKCHECK(epoll__epoll_pwait, tcptr) { sigset_t emptyset; sigset_t blockset; sigemptyset(&blockset); sigaddset(&blockset, SIGINT); sigprocmask(SIG_BLOCK, &blockset, NULL); struct sigaction sa = { .sa_handler = epoll_pwait_sighandler }; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, NULL); kill(getpid(), SIGINT); sigemptyset(&emptyset); int ep = epoll_create1(EPOLL_CLOEXEC); ATF_REQUIRE(ep >= 0); struct epoll_event ev; ATF_REQUIRE(epoll_pwait(ep, &ev, 1, 0, &emptyset) == 0); ATF_REQUIRE(epoll_pwait_got_signal == 0); ATF_REQUIRE_ERRNO(EINTR, epoll_pwait(ep, &ev, 1, 1000, &emptyset) < 0); ATF_REQUIRE(epoll_pwait_got_signal == 1); epoll_pwait_got_signal = 0; kill(getpid(), SIGINT); { struct pollfd pfd = { .fd = ep, .events = POLLIN }; ATF_REQUIRE(poll(&pfd, 1, 0) == 0); ATF_REQUIRE(epoll_pwait_got_signal == 0); #ifdef __NetBSD__ int n = pollts( #else int n = ppoll( #endif &pfd, 1, &(struct timespec) { 0, #if defined(__DragonFly__) 1 #else 0 #endif }, &emptyset); ATF_REQUIRE(n == 0 || (n < 0 && errno == EINTR)); ATF_REQUIRE(epoll_pwait_got_signal == 1); #ifdef __APPLE__ n = ppoll(&pfd, 1, &(struct timespec) { 0, 500000000 }, NULL); ATF_REQUIRE(n == 0); #endif } ATF_REQUIRE(close(ep) == 0); } ATF_TC_WITHOUT_HEAD(epoll__cloexec); ATF_TC_BODY_FD_LEAKCHECK(epoll__cloexec, tcptr) { int fd; int r; #define CLOEXEC_TEST(fun, cmp, ...) \ do { \ fd = fun(__VA_ARGS__); \ ATF_REQUIRE(fd >= 0); \ r = fcntl(fd, F_GETFD); \ ATF_REQUIRE(r >= 0); \ ATF_REQUIRE_MSG((r & FD_CLOEXEC) cmp 0, "%d", r); \ ATF_REQUIRE(close(fd) == 0); \ } while (0) CLOEXEC_TEST(epoll_create1, !=, EPOLL_CLOEXEC); CLOEXEC_TEST(epoll_create1, ==, 0); CLOEXEC_TEST(timerfd_create, !=, CLOCK_MONOTONIC, TFD_CLOEXEC); CLOEXEC_TEST(timerfd_create, ==, CLOCK_MONOTONIC, 0); sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGINT); CLOEXEC_TEST(signalfd, !=, -1, &mask, SFD_CLOEXEC); CLOEXEC_TEST(signalfd, ==, -1, &mask, 0); CLOEXEC_TEST(eventfd, !=, 0, EFD_CLOEXEC); CLOEXEC_TEST(eventfd, ==, 0, 0); } ATF_TC_WITHOUT_HEAD(epoll__fcntl_fl); ATF_TC_BODY_FD_LEAKCHECK(epoll__fcntl_fl, tcptr) { int fd; int r; #define FCNTL_FL_TEST(fun, expected, ...) \ do { \ fd = fun(__VA_ARGS__); \ ATF_REQUIRE(fd >= 0); \ r = fcntl(fd, F_GETFL, 0); \ ATF_REQUIRE_MSG(r == (expected), "%04x", r); \ ATF_REQUIRE(close(fd) == 0); \ } while (0) FCNTL_FL_TEST(epoll_create1, O_RDWR, 0); { fd = epoll_create1(0); ATF_REQUIRE(fd >= 0); r = fcntl(fd, F_GETFL, 0); ATF_REQUIRE(r >= 0); r = fcntl(fd, F_SETFL, r | O_NONBLOCK); ATF_REQUIRE_MSG(r >= 0, "%s", strerror(errno)); r = fcntl(fd, F_GETFL, 0); ATF_REQUIRE(r == (O_RDWR | O_NONBLOCK)); ATF_REQUIRE(close(fd) == 0); } sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGINT); FCNTL_FL_TEST(signalfd, O_RDWR, -1, &mask, 0); FCNTL_FL_TEST(signalfd, O_RDWR | O_NONBLOCK, -1, &mask, SFD_NONBLOCK); FCNTL_FL_TEST(eventfd, O_RDWR, 0, 0); FCNTL_FL_TEST(eventfd, O_RDWR | O_NONBLOCK, 0, EFD_NONBLOCK); #if defined(__NetBSD__) && __NetBSD_Version__ >= 999009100 FCNTL_FL_TEST(timerfd_create, 0, CLOCK_MONOTONIC, 0); FCNTL_FL_TEST(timerfd_create, 0 | O_NONBLOCK, CLOCK_MONOTONIC, TFD_NONBLOCK); #else FCNTL_FL_TEST(timerfd_create, O_RDWR, CLOCK_MONOTONIC, 0); FCNTL_FL_TEST(timerfd_create, O_RDWR | O_NONBLOCK, CLOCK_MONOTONIC, TFD_NONBLOCK); #endif } ATF_TP_ADD_TCS(tp) { ATF_TP_ADD_TC(tp, epoll__simple); #ifndef USE_EPOLLRDHUP_LINUX_DEFINITION ATF_TP_ADD_TC(tp, epoll__poll_flags); #endif ATF_TP_ADD_TC(tp, epoll__leakcheck); ATF_TP_ADD_TC(tp, epoll__fd_exhaustion); ATF_TP_ADD_TC(tp, epoll__invalid_op); ATF_TP_ADD_TC(tp, epoll__invalid_op2); ATF_TP_ADD_TC(tp, epoll__rdhup_linux); ATF_TP_ADD_TC(tp, epoll__simple_wait); ATF_TP_ADD_TC(tp, epoll__event_size); ATF_TP_ADD_TC(tp, epoll__recursive_register); ATF_TP_ADD_TC(tp, epoll__simple_epollin); ATF_TP_ADD_TC(tp, epoll__sleep_argument); ATF_TP_ADD_TC(tp, epoll__remove_nonexistent); ATF_TP_ADD_TC(tp, epoll__add_remove); ATF_TP_ADD_TC(tp, epoll__add_existing); ATF_TP_ADD_TC(tp, epoll__modify_existing); ATF_TP_ADD_TC(tp, epoll__modify_nonexisting); ATF_TP_ADD_TC(tp, epoll__poll_only_fd); ATF_TP_ADD_TC(tp, epoll__no_epollin_on_closed_empty_pipe); ATF_TP_ADD_TC(tp, epoll__write_to_pipe_until_full); ATF_TP_ADD_TC(tp, epoll__realtime_timer); ATF_TP_ADD_TC(tp, epoll__simple_signalfd); ATF_TP_ADD_TC(tp, epoll__signalfd_poll_sigusr1); ATF_TP_ADD_TC(tp, epoll__signalfd_in_thread); ATF_TP_ADD_TC(tp, epoll__socket_shutdown); ATF_TP_ADD_TC(tp, epoll__epollhup_on_fresh_socket); ATF_TP_ADD_TC(tp, epoll__epollout_on_connecting_socket); ATF_TP_ADD_TC(tp, epoll__epollpri); ATF_TP_ADD_TC(tp, epoll__epollpri_oobinline); ATF_TP_ADD_TC(tp, epoll__epollpri_oobinline_lt); ATF_TP_ADD_TC(tp, epoll__timeout_on_listening_socket); ATF_TP_ADD_TC(tp, epoll__epollerr_on_closed_pipe); ATF_TP_ADD_TC(tp, epoll__shutdown_behavior); ATF_TP_ADD_TC(tp, epoll__datagram_connection); ATF_TP_ADD_TC(tp, epoll__epollout_on_own_shutdown); ATF_TP_ADD_TC(tp, epoll__remove_closed); ATF_TP_ADD_TC(tp, epoll__remove_closed_when_same_fd_open); ATF_TP_ADD_TC(tp, epoll__add_different_file_with_same_fd_value); ATF_TP_ADD_TC(tp, epoll__invalid_writes); ATF_TP_ADD_TC(tp, epoll__using_real_close); ATF_TP_ADD_TC(tp, epoll__epoll_pwait); ATF_TP_ADD_TC(tp, epoll__cloexec); ATF_TP_ADD_TC(tp, epoll__fcntl_fl); return atf_no_error(); }
2.15625
2
2024-11-18T22:21:50.566736+00:00
2018-03-15T16:04:49
21d9eb8fd8f6dffaf7051707386df7449d0f56c1
{ "blob_id": "21d9eb8fd8f6dffaf7051707386df7449d0f56c1", "branch_name": "refs/heads/master", "committer_date": "2018-03-15T16:04:49", "content_id": "7a5e49fb6545c30383ba02dc4cdae78ed0e8e366", "detected_licenses": [ "Apache-2.0" ], "directory_id": "16233fd0efea54f950bd3e30cef84d9bc4986506", "extension": "c", "filename": "mystring.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 125238633, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1786, "license": "Apache-2.0", "license_type": "permissive", "path": "/QT-code/MyString/mystring.c", "provenance": "stackv2-0123.json.gz:7434", "repo_name": "LianWence/Self-Study-C", "revision_date": "2018-03-15T16:04:49", "revision_id": "bb931868e991fe6ffefe9d832f1e9c6a564d6e34", "snapshot_id": "5980e46ec4a2f3a184e629aecee28717449f597c", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LianWence/Self-Study-C/bb931868e991fe6ffefe9d832f1e9c6a564d6e34/QT-code/MyString/mystring.c", "visit_date": "2021-04-06T10:50:43.761006" }
stackv2
#include <stdio.h> #include "mystring.h" int myStrlen(const char *src) { int length = 0; while(*src++) length++; return length; } char * myStrcpy(char *dst, const char *src) { char *temp = dst; // while(*src) // { // *temp++ = *src++; // } // *temp = '\0'; //表达式是有返回值的,通常是指代赋值表达式的返回值 while(*temp++ = *src++);//当表达式的返回值为'\0';循坏结束 return dst; } char * myStrcat(char *dst, const char *src) { char *temp = dst; // while(*temp++); // temp--; while(*temp) temp++; while(*temp++ = *src++); return dst; } int myStrcmp(const char *str1, const char *str2) { for(; (*str1 && *str2) && (*str1 == *str2); str1++, str2++); return *str1 - *str2; } char * myStrstr(char *str, char *subStr) { if(*subStr) { while(*str) { for(int n = 0; *(str + n) == *(subStr + n); n++) { if(*(subStr + n + 1) == '\0') return str; } str++; } return NULL; } else return str; } void trimLeftSpace(char *str) { while(*str) str++; while(*(--str) == ' ') *str = '\0'; } void trimRightSpace(char *str) { char *temp = str; while(*temp == ' ') temp++; while(*str++ = *temp++); } void trimSpace(char *str) { char *temp = str; while(*temp) { if(*temp != ' ') *str++ = *temp; temp++; } *str = '\0'; } void reverseStr(const char *str, char *revStr) { if(!*str) *revStr = if(*str) { reverseStr(str + 1, revStr + 1); *revStr = *str; } else *++revStr = '\0'; }
3.078125
3
2024-11-18T22:21:50.714354+00:00
2023-06-28T10:59:39
29e51df799a7a2e4d8ecee946475ca9b77664653
{ "blob_id": "29e51df799a7a2e4d8ecee946475ca9b77664653", "branch_name": "refs/heads/main", "committer_date": "2023-06-28T10:59:39", "content_id": "9f9f75d9f6758b26e168752d154f243da3444be3", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f4d68689561ef4a26c8b7ab35e67f1dc72bec45a", "extension": "c", "filename": "DV_Framework.c", "fork_events_count": 22, "gha_created_at": "2019-02-15T09:58:57", "gha_event_created_at": "2023-06-28T10:59:40", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 170842577, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4538, "license": "Apache-2.0", "license_type": "permissive", "path": "/Source/DV_Framework.c", "provenance": "stackv2-0123.json.gz:7562", "repo_name": "ARM-software/CMSIS-Driver_Validation", "revision_date": "2023-06-28T10:59:39", "revision_id": "9d3b8086e1999729c7bcecf5a9c1b3048ee6d34a", "snapshot_id": "79da70ad1c4f8c9a2ed53fe1ac919326fe884004", "src_encoding": "UTF-8", "star_events_count": 15, "url": "https://raw.githubusercontent.com/ARM-software/CMSIS-Driver_Validation/9d3b8086e1999729c7bcecf5a9c1b3048ee6d34a/Source/DV_Framework.c", "visit_date": "2023-09-02T00:12:21.092226" }
stackv2
/* * Copyright (c) 2015-2020 Arm Limited. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * 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 * * 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. * * ----------------------------------------------------------------------------- * * Project: CMSIS-Driver Validation * Title: Test framework * * ----------------------------------------------------------------------------- */ #include "cmsis_dv.h" #include "DV_Framework.h" /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/ /** \defgroup dv_framework Framework \brief Framework configuration and functions \details \defgroup framework_funcs Functions \ingroup dv_framework @{ */ /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/ /** \brief Close the debug session. \details Debug session dead end - debug script should close session here. This function is called by \ref cmsis_dv. */ void closeDebug(void); #ifndef __DOXYGEN__ // Exclude form the documentation void __attribute__((noinline)) closeDebug(void){ __NOP(); // Test completed } #endif /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/ /** \brief This is the entry point of the test framework. \details Program flow: -# Test report is initialized -# For each test group following steps are executed: -# Test group initialization is called (custom test group initialization) -# Test group header is written to standard output -# All tests in a group are executed as follows: - Test statistics are initialized - Test report header is written to the standard output - Test function is executed - Test results are written to the standard output - Test report footer is written to the standard output -# Test group footer is written to standard output -# Test group uninitialization is called (custom test group uninitialization) -# Debug session ends when closeDebug function is reached */ void cmsis_dv (void *argument) { const char *fn; uint32_t i, tc, no; (void)argument; if (tg_cnt != 0U) { /* If at least 1 test is enabled */ ritf.tr_Init (); /* Init test report */ for (i = 0U; i < tg_cnt; i++) { /* Init test group report */ ritf.tg_Init(ts[i].ReportTitle, /* Write test group title */ ts[i].Date, /* Write test group compilation date */ ts[i].Time, /* Write test group compilation time */ ts[i].FileName); /* Write test group module file name */ if (ts[i].Init != NULL) { ts[i].Init(); /* Init test group (group setup) */ } ritf.tg_InfoDone(); /* Test group info done */ /* Execute all tests in a group */ for (tc = 0U; tc < ts[i].NumOfTC; tc++) { no = tc + 1U; /* Test number */ fn = ts[i].TC[tc].TFName; /* Test function name string */ ritf.tc_Init (no, fn); /* Init test report #(Base + TC) */ if (ts[i].TC[tc].TestFunc != NULL) { ts[i].TC[tc].TestFunc(); /* Execute test func if enabled */ } ritf.tc_Uninit (); /* Uninit test report */ } ritf.tg_Uninit (); /* Uninit test group report */ if (ts[i].Uninit != NULL) { ts[i].Uninit(); /* Uninit test group (group teardown) */ } } ritf.tr_Uninit(); /* Uninit test report */ } closeDebug(); /* Close debug session */ } /** @} */ // end of group framework_funcs
2.125
2
2024-11-18T22:21:50.849180+00:00
2017-02-08T14:25:01
3fb2eae143257c24e07fd4506066b084c122f12b
{ "blob_id": "3fb2eae143257c24e07fd4506066b084c122f12b", "branch_name": "refs/heads/master", "committer_date": "2017-02-08T14:25:01", "content_id": "975a60cbd14c97dd8605116904e447aec54c900c", "detected_licenses": [ "MIT" ], "directory_id": "3af00eee373fad4b688e38d1854bd8d49cf97dc6", "extension": "c", "filename": "DateUtils.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 81331942, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20242, "license": "MIT", "license_type": "permissive", "path": "/DateUtils.c", "provenance": "stackv2-0123.json.gz:7692", "repo_name": "ardax/Pellet", "revision_date": "2017-02-08T14:25:01", "revision_id": "d3397908c3ee0c8e5e5ecbbfa997455d9abcffe2", "snapshot_id": "a39a50446785c3b865945e7fb79923f4eb759473", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ardax/Pellet/d3397908c3ee0c8e5e5ecbbfa997455d9abcffe2/DateUtils.c", "visit_date": "2021-01-13T06:56:46.042032" }
stackv2
#include "DateUtils.h" #include "Utils.h" #include "TextUtils.h" #include <stdio.h> int* yrsize(int y) { if((y%4) == 0 && ((y%100) != 0 || (y%400) == 0)) return ldmsize; else return dmsize; } long tm2sec(struct tm *tm) { long secs; int i, yday, year, *d2m; secs = 0; if( tm->tm_year > 2100 || tm->tm_mon > 11 || tm->tm_mon < 0 || tm->tm_mday > 31 ) return 0; if( tm->tm_year < 1900 ) year = tm->tm_year + 1900; else year = tm->tm_year; /* * seconds per year */ for(i = 1970; i < year; i++){ d2m = yrsize(i); secs += d2m[0] * SEC2DAY; } /* * if mday is set, use mon and mday to compute yday */ if(tm->tm_mday){ yday = 0; d2m = yrsize(year); for(i=0; i<tm->tm_mon; i++) yday += d2m[i+1]; yday += tm->tm_mday-1; }else{ yday = tm->tm_yday; } secs += yday * SEC2DAY; /* * hours, minutes, seconds */ secs += tm->tm_hour * SEC2HOUR; secs += tm->tm_min * SEC2MIN; secs += tm->tm_sec; /* * Only handles zones mentioned in /env/timezone, * but things get too ambiguous otherwise. if(strcmp(tm->zone, timezone.stname) == 0) secs -= timezone.stdiff; else if(strcmp(tm->zone, timezone.dlname) == 0) secs -= timezone.dldiff; */ if(secs < 0) secs = 0; return secs; } long convertToDateTime(const char* pDate, TM* pTM) { if( strlen(pDate) > 0 ) { int iTimeZoneDifferenceHour = 0; int iTimeZoneDifferenceMin = 0; bool bNegativeDifference = TRUE; int iDay, iMonth, iYear, iHour, iMin = 0, iSec = 0; string sMonth; char month[2048]; char sDummy[2048]; int iTry = -1, rc; int iMethodCount = 24; do { if( iTry == -1 ) { rc = sscanf(pDate, "%d-%d-%d %d:%d:%d", &iYear, &iMonth, &iDay, &iHour, &iMin, &iSec); if( rc == 6 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 0 ) { int rc = sscanf(pDate, "%s %d %s %d %d:%d:%d %s", sDummy, &iDay, &month, &iYear, &iHour, &iMin, &iSec, sDummy); sMonth = string(month); if( rc == 8 ) { int iH, iM; sscanf(sDummy, "%d:%d", &iH, &iM); iMonth = getMonth(sMonth); if( iYear < 100 ) iYear += 2000; /* Make sure that day-month match*/ if( iMonth > 12 && iMonth < 32 && iDay < 13 && iDay > 0 ) { int iTmp = iMonth; iMonth = iDay; iDay = iTmp; } //cout << "iDay=" << iDay << " Month=" << month << " iYear=" << iYear << " iHour=" << iHour << endl; getTimeZoneInfo(sDummy, &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); if( iYear > 1900 && iMonth > 0 ) break; } } else if( iTry == 1 ) { rc = sscanf(pDate, "%s %d %s %d %d:%d %s", sDummy, &iDay, &month, &iYear, &iHour, &iMin, sDummy); int iH, iM; sscanf(sDummy, "%d:%d", &iH, &iM); iMonth = getMonth(sMonth); if( iYear < 100 ) { iYear += 2000; } /* Make sure that day-month match*/ if( iMonth > 12 && iMonth < 32 && iDay < 13 && iDay > 0 ) { int iTmp = iMonth; iMonth = iDay; iDay = iTmp; } getTimeZoneInfo(sDummy, &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); if( rc == 7 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 2 ) { rc = sscanf(pDate, "%d-%d-%dT%d:%d:%d%s", &iYear, &iMonth, &iDay, &iHour, &iMin, &iSec, sDummy); if( rc == 7 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 3 ) { int iDum1, iDum2; rc = sscanf(pDate, "%d-%d-%dT%d:%d:%d-%d:%d", &iYear, &iMonth, &iDay, &iHour, &iMin, &iSec, &iDum1, &iDum2); // iDum1 : Hour, iDum2 : Min iTimeZoneDifferenceHour = iDum1; iTimeZoneDifferenceMin = iDum2; bNegativeDifference = TRUE; if( rc == 8 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 4 ) { rc = sscanf(pDate, "%d %s %d %d:%d:%d %s", &iDay, &month, &iYear, &iHour, &iMin, &iSec, sDummy); sMonth = string(month); iMonth = getMonth(sMonth); getTimeZoneInfo(sDummy, &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); if( rc == 7 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 5 ) { rc = sscanf(pDate, "%d/%d/%d @%d:%d", &iMonth, &iDay, &iYear, &iHour, &iMin); iSec = 0; if( iYear < 100 ) iYear += 2000; if( rc == 5 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 6 ) { rc = sscanf(pDate, "%d/%d/%d %d:%d %s", &iMonth, &iDay, &iYear, &iHour, &iMin, sDummy); getTimeZoneInfo(sDummy, &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); if( rc == 6 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 7 ) { rc = sscanf(pDate, "%d-%d-%dT%d:%d%s", &iYear, &iMonth, &iDay, &iHour, &iMin, sDummy); getTimeZoneInfo(sDummy, &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); if( rc == 6 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 8 ) { rc = sscanf(pDate, "%s %s %d, %d @ %d:%d", sDummy, month, &iDay, &iYear, &iHour, &iMin); sMonth = string(month); iMonth = getMonth(sMonth); if( rc == 6 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 9 ) { rc = sscanf(pDate, "%d %s %d %d:%d %s", &iDay, month, &iYear, &iHour, &iMin, sDummy); sMonth = string(month); iMonth = getMonth(sMonth); if( iYear < 100 ) iYear += 2000; getTimeZoneInfo(sDummy, &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); if( rc == 6 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 10 ) { rc = sscanf(pDate, "%s %s %d %d %d:%d:%d %s", sDummy, month, &iDay, &iYear, &iHour, &iMin, &iSec, sDummy); int iH, iM; sscanf(sDummy, "%d:%d", &iH, &iM); iMonth = getMonth(sMonth); if( iYear < 100 ) iYear += 2000; /* Make sure that day-month match*/ if( iMonth > 12 && iMonth < 32 && iDay < 13 && iDay > 0 ) { int iTmp = iMonth; iMonth = iDay; iDay = iTmp; } getTimeZoneInfo(sDummy, &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); if( rc == 8 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 11 ) { rc = sscanf(pDate, "%s %s %d %d:%d %s %d", sDummy, month, &iDay, &iHour, &iMin, sDummy, &iYear); getTimeZoneInfo(sDummy, &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); sMonth = string(month); if( rc == 7 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 12 ) { rc = sscanf(pDate, "%s %s %d %d:%d:%d %s %d", sDummy, month, &iDay, &iHour, &iMin, &iSec, sDummy, &iYear); sMonth = string(month); getTimeZoneInfo(sDummy, &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); if( rc == 8 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 13 ) { rc = sscanf(pDate, "%d-%d-%d %d:%d:%d %s", &iYear, &iMonth, &iDay, &iHour, &iMin, &iSec, sDummy); getTimeZoneInfo(sDummy, &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); if( rc == 7 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 14 ) { rc = sscanf(pDate, "%d-%d-%d %d:%d:%d.0", &iYear, &iMonth, &iDay, &iHour, &iMin, &iSec); getTimeZoneInfo("GMT", &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); if( rc == 6 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 15 ) { rc = sscanf(pDate, "%d %s %d", &iDay, month, &iYear); sMonth = string(month); iMonth = getMonth(sMonth); if( rc == 3 && iYear > 1900 && iDay > 0 && iMonth > 0 ) break; } else if( iTry == 16 ) { rc = sscanf(pDate, "%d-%d-%d", &iYear, &iMonth, &iDay); iHour = 0; iMin = 0; iSec = 0; if( rc == 3 && iYear > 1900 && iMonth > 0 && iDay > 0 ) break; } else if( iTry == 17 ) { rc = sscanf(pDate, "%s %d %d", month, &iDay, &iYear); sMonth = string(month); iMonth = getMonth(sMonth); if( rc == 3 && iYear > 1900 && iDay > 0 && iMonth > 0 ) break; } else if( iTry == 18 ) { rc = sscanf(pDate, "%d/%d/%d", &iDay, &iMonth, &iYear); /* Make sure that day-month match*/ if( iMonth > 12 && iMonth < 32 && iDay < 13 && iDay > 0 ) { int iTmp = iMonth; iMonth = iDay; iDay = iTmp; } if( rc == 3 && iYear > 1900 && iDay > 0 && iMonth > 0 ) break; } else if( iTry == 19 ) { rc = sscanf(pDate, "%d-%d-%d", &iDay, &iMonth, &iYear); iHour = 0; iMin = 0; iSec = 0; if( rc == 3 && iYear > 1900 && iMonth > 0 && iDay > 0 ) break; } else if( iTry == 20 ) { rc = sscanf(pDate, "%s %s %d, %d", sDummy, month, &iDay, &iYear); sMonth = string(month); iMonth = getMonth(sMonth); iHour = 0; iMin = 0; iSec = 0; if( rc == 4 && iYear > 1900 && iMonth > 0 && iDay > 0 ) break; } else if( iTry == 21 ) { rc = sscanf(pDate, "%s %d, %d %d:%d %s", month, &iDay, &iYear, &iHour, &iMin, sDummy); iSec = 0; if( stricmp(sDummy, "PM") == 0 ) { if( iHour < 12 ) iHour += 12; } if( rc == 6 && iYear > 1900 && iMonth > 0 ) break; } else if( iTry == 22 ) { rc = sscanf(pDate, "%s %d %s %d", sDummy, &iDay, month, &iYear); sMonth = string(month); iMonth = getMonth(sMonth); iHour = 0; iMin = 0; iSec = 0; if( rc == 4 && iYear > 1900 && iMonth > 0 && iDay > 0 ) break; } else if( iTry == 23 ) { char sDummy2[2048]; rc = sscanf(pDate, "%s %d, %d %d:%d %s %s", month, &iDay, &iYear, &iHour, &iMin, sDummy2, sDummy); iSec = 0; sMonth = string(month); iMonth = getMonth(sMonth); if( stricmp(sDummy2, "PM") == 0 ) { if( iHour < 12 ) iHour += 12; } getTimeZoneInfo(sDummy, &iTimeZoneDifferenceHour, &iTimeZoneDifferenceMin, &bNegativeDifference); if( rc == 7 && iYear > 1900 && iMonth > 0 ) break; } iTry += 1; } while(iTry < iMethodCount); if( iYear < 100 && iYear > 9 ) iYear += 1900; else if( iYear < 100 && iYear < 10 ) iYear += 2000; /* Make sure that day-month match*/ if( iMonth > 12 && iMonth < 32 && iDay < 13 && iDay > 0 ) { int iTmp = iMonth; iMonth = iDay; iDay = iTmp; } if( iMonth > 0 && iMonth < 13 && iDay > 0 && iDay < 32 && iYear > 1900 && iHour > -1 && iHour < 24 && iMin > -1 && iMin < 60 && iSec > -1 && iSec < 60) { TM tm; if( pTM == NULL ) pTM = &tm; pTM->tm_year = iYear; pTM->tm_mon = iMonth-1; pTM->tm_mday = iDay; pTM->tm_hour = iHour; pTM->tm_min = iMin; pTM->tm_sec = iSec; if( iTimeZoneDifferenceHour > 0 || iTimeZoneDifferenceMin > 0 ) { //printf("Zone Difference(%s) : %d hours, %d minutes (%d) (%d)\n", pDate, iTimeZoneDifferenceHour, iTimeZoneDifferenceMin, bNegativeDifference, iTry); long lSeconds = tm2sec(pTM); if( bNegativeDifference ) lSeconds += (iTimeZoneDifferenceHour*60*60+iTimeZoneDifferenceMin*60); else lSeconds -= (iTimeZoneDifferenceHour*60*60+iTimeZoneDifferenceMin*60); return lSeconds; } return tm2sec(pTM); } //printf("Failed to process [%s]\n", pDate); } return 0; } void getTimeZoneInfo(char *sTimeZoneStr, int *TZHour, int *TZMin, bool *bNegative) { if( !sTimeZoneStr || strlen(sTimeZoneStr) == 3 ) { if( !sTimeZoneStr || stricmp(sTimeZoneStr, "GMT") == 0 ) { *TZHour = 0; *bNegative = FALSE; return; } else if( stricmp(sTimeZoneStr, "CET") == 0 ) { *TZHour = 1; *bNegative = FALSE; return; } else if( stricmp(sTimeZoneStr, "AST") == 0 || stricmp(sTimeZoneStr, "EDT") == 0 ) { *TZHour = 4; *bNegative = TRUE; return; } else if( stricmp(sTimeZoneStr, "EST") == 0 || stricmp(sTimeZoneStr, "CDT") == 0 ) { *TZHour = 5; *bNegative = TRUE; return; } else if( stricmp(sTimeZoneStr, "CST") == 0 || stricmp(sTimeZoneStr, "MDT") == 0 ) { *TZHour = 6; *bNegative = TRUE; return; } else if( stricmp(sTimeZoneStr, "MST") == 0 || stricmp(sTimeZoneStr, "PDT") == 0 ) { *TZHour = 7; *bNegative = TRUE; return; } else if( stricmp(sTimeZoneStr, "PST") == 0 || stricmp(sTimeZoneStr, "AKDT") == 0 ) { *TZHour = 8; *bNegative = TRUE; return; } else if( stricmp(sTimeZoneStr, "EET") == 0 ) { *TZHour = 2; *bNegative = FALSE; return; } else if( stricmp(sTimeZoneStr, "MSK") == 0 ) { *TZHour = 3; *bNegative = FALSE; return; } else if( stricmp(sTimeZoneStr, "IST") == 0 ) { *TZHour = 5; *TZMin = 30; *bNegative = FALSE; return; } else if( stricmp(sTimeZoneStr, "AWST") == 0 ) { *TZHour = 8; *bNegative = FALSE; return; } else if( stricmp(sTimeZoneStr, "JST") == 0 ) { *TZHour = 9; *bNegative = FALSE; return; } else if( stricmp(sTimeZoneStr, "ACST") == 0 ) { *TZHour = 9; *TZMin = 30; *bNegative = FALSE; return; } else if( stricmp(sTimeZoneStr, "AEST") == 0 ) { *TZHour = 10; *bNegative = FALSE; return; } else if( stricmp(sTimeZoneStr, "AKST") == 0 ) { *TZHour = 9; *bNegative = TRUE; return; } else if( stricmp(sTimeZoneStr, "GST") == 0 ) { *TZHour = 10; *bNegative = FALSE; return; } else if( stricmp(sTimeZoneStr, "WAT") == 0 ) { *TZHour = 1; *bNegative = TRUE; return; } else if( stricmp(sTimeZoneStr, "YST") == 0 ) { *TZHour = 8; *bNegative = TRUE; return; } else if( stricmp(sTimeZoneStr, "ADT") == 0 ) { *TZHour = 3; *bNegative = TRUE; return; } else if( stricmp(sTimeZoneStr, "NST") == 0 ) { *TZHour = 3; *TZMin = 30; *bNegative = TRUE; return; } else if( stricmp(sTimeZoneStr, "HST") == 0 || stricmp(sTimeZoneStr, "CAT") == 0) { *TZHour = 10; *bNegative = TRUE; return; } } if( stricmp(sTimeZoneStr, "Z") == 0 ) { // Dont do anything return; } else if( stricmp(sTimeZoneStr, "AT") == 0 ) { *TZHour = 9; *bNegative = TRUE; return; } else { int iH, iM; int rc = sscanf(sTimeZoneStr, "-%d:%d", &iH, &iM); if( rc == 2 ) { *TZHour = iH; *TZMin = iM; *bNegative = TRUE; } else { rc = sscanf(sTimeZoneStr, "GMT+%d", &iH); if( rc == 1 ) { *TZHour = iH; *bNegative = FALSE; } else { rc = sscanf(sTimeZoneStr, "GMT-%d", &iH); if( rc == 1 ) { *TZHour = iH; *bNegative = TRUE; } else { rc = sscanf(sTimeZoneStr, "+%d:%d", &iH, &iM); if( rc == 2 ) { *TZHour = iH; *TZMin = iM; *bNegative = FALSE; } else { rc = sscanf(sTimeZoneStr, "%d:%d", &iH, &iM); if( rc == 2 ) { *TZHour = iH; *TZMin = iM; *bNegative = FALSE; } else { rc = sscanf(sTimeZoneStr, "+%d", &iH); if( rc == 1 ) { *TZHour = iH; *TZMin = 0; *bNegative = FALSE; } else { /* Check this +0900 */ if( strlen(sTimeZoneStr) == 5 && (sTimeZoneStr[0] == '+' || sTimeZoneStr[0] == '-') ) { *bNegative = (sTimeZoneStr[0] == '-'); sTimeZoneStr++; int iHour1, iHour2, iMin1, iMin2; iHour1 = sTimeZoneStr[0]-48; iHour2 = sTimeZoneStr[1]-48; iMin1 = sTimeZoneStr[2]-48; iMin2 = sTimeZoneStr[3]-48; //rc = sscanf(sTimeZoneStr, "%d%d%d%d", &iHour1, &iHour2, &iMin1, &iMin2); if( iHour1+iHour2 > 0 || iMin1+iMin2 > 0 ) { *TZHour = iHour1*10+iHour2; *TZMin = iMin1*10+iMin2; } } } } } } } } } } int getMonth(string sMonth) { int iMonth = -1; if( sMonth.length() < 3 ) return -1; sMonth[0] = tolower(sMonth[0]); sMonth[1] = tolower(sMonth[1]); sMonth[2] = tolower(sMonth[2]); if( sMonth.find("jan") == 0 ) iMonth = 1; else if( sMonth.find("feb") == 0 ) iMonth = 2; else if( sMonth.find("mar") == 0 ) iMonth = 3; else if( sMonth.find("apr") == 0 ) iMonth = 4; else if( sMonth.find("may") == 0 ) iMonth = 5; else if( sMonth.find("jun") == 0 ) iMonth = 6; else if( sMonth.find("jul") == 0 ) iMonth = 7; else if( sMonth.find("aug") == 0 ) iMonth = 8; else if( sMonth.find("sep") == 0 ) iMonth = 9; else if( sMonth.find("oct") == 0 ) iMonth = 10; else if( sMonth.find("nov") == 0 ) iMonth = 11; else if( sMonth.find("dec") == 0 ) iMonth = 12; return iMonth; } string tm2str(TM* pTM, bool bDateTime) { if( pTM->tm_year > 0 ) { char cFormatedDate[100]; if( pTM->tm_year > 1970 ) { if( bDateTime ) sprintf(cFormatedDate, "%d-%d-%d %d:%d:%d", pTM->tm_year, (pTM->tm_mon+1), pTM->tm_mday, pTM->tm_hour, pTM->tm_min, pTM->tm_sec); else sprintf(cFormatedDate, "%d-%d-%d", pTM->tm_year, (pTM->tm_mon+1), pTM->tm_mday); } else { if( bDateTime ) sprintf(cFormatedDate, "%d-%d-%d %d:%d:%d", (1970+pTM->tm_year), (pTM->tm_mon+1), pTM->tm_mday, pTM->tm_hour, pTM->tm_min, pTM->tm_sec); else sprintf(cFormatedDate, "%d-%d-%d", (1970+pTM->tm_year), (pTM->tm_mon+1), pTM->tm_mday); } return string(cFormatedDate); } return ""; } string getTodayDateTime() { time_t rawtime; tm* ptm; char cDate[1024]; time(&rawtime); ptm = gmtime(&rawtime); sprintf(cDate, "%d-%d-%d %d:%d:%d", (1900+ptm->tm_year), (1+ptm->tm_mon), ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); return string(cDate); } void getTodayDate(char* pDate) { time_t rawtime; tm* ptm; time(&rawtime); ptm = gmtime(&rawtime); sprintf(pDate, "%d-%d-%d", (1900+ptm->tm_year), (1+ptm->tm_mon), ptm->tm_mday); } long getTodayInSeconds(bool bLocal) { time_t rawtime; time(&rawtime); if( bLocal ) return tm2sec(localtime(&rawtime)); return tm2sec(gmtime(&rawtime)); } void getNowInRFCFormat(char* pBuffer, int iBufferSize, bool bLocal) { time_t t; struct tm *tmp; t = time(NULL); if( bLocal ) tmp = localtime(&t); else tmp = gmtime(&t); if (strftime(pBuffer, iBufferSize, "%a, %d %b %Y %H:%M:%S %Z\0", tmp) == 0) { // error occured; zero p pBuffer[0] = '\0'; } } unsigned long int tvdiff2ms(struct timeval *a, struct timeval *b) { return ((a->tv_sec-b->tv_sec)*1000) + ((a->tv_usec-b->tv_usec)/1000); } void convertLong2DateTime(long lDate, char* pDate) { if( lDate == 0 ) { pDate[0] = '\0'; return; } time_t time = (time_t)lDate; struct tm* t = gmtime(&time); if( t ) { sprintf(pDate, "%d-%02d-%02d %02d:%02d:%02d", (1900+t->tm_year), (1+t->tm_mon), t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); } else sprintf(pDate, "0000-00-00 00:00:00"); } void convertLong2Date(long lDate, char* pDate) { if( lDate == 0 ) { pDate[0] = '\0'; return; } time_t time = (time_t)lDate; struct tm* t = gmtime(&time); if( t ) { sprintf(pDate, "%d-%02d-%02d", (1900+t->tm_year), (1+t->tm_mon), t->tm_mday); } else sprintf(pDate, "0000-00-00"); } void getNow(char* pBuffer, int iBufferSize, bool bLocal) { time_t rawtime; tm* ptm; time(&rawtime); if( bLocal ) ptm = localtime(&rawtime); else ptm = gmtime(&rawtime); sprintf(pBuffer, "%d-%d-%d %d:%d:%d\0", (1900+ptm->tm_year), (1+ptm->tm_mon), ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); } bool startsAfter(tm* pTM1, tm* pTM2) { if( pTM1->tm_year > pTM2->tm_year ) return TRUE; else if( pTM1->tm_year < pTM2->tm_year ) return FALSE; if( pTM1->tm_mon > pTM2->tm_mon ) return TRUE; else if( pTM1->tm_mon < pTM2->tm_mon ) return FALSE; if( pTM1->tm_mday > pTM2->tm_mday ) return TRUE; else if( pTM1->tm_mday < pTM2->tm_mday ) return FALSE; if( pTM1->tm_hour > pTM2->tm_hour ) return TRUE; else if( pTM1->tm_hour < pTM2->tm_hour ) return FALSE; if( pTM1->tm_min > pTM2->tm_min ) return TRUE; else if( pTM1->tm_min < pTM2->tm_min ) return FALSE; if( pTM1->tm_sec > pTM2->tm_sec ) return TRUE; else if( pTM1->tm_sec < pTM2->tm_sec ) return FALSE; return FALSE; } bool isSame(tm* pTM1, tm* pTM2) { if( pTM1->tm_year == pTM2->tm_year && pTM1->tm_mon == pTM2->tm_mon && pTM1->tm_mday == pTM2->tm_mday && pTM1->tm_hour == pTM2->tm_hour && pTM1->tm_min == pTM2->tm_min && pTM1->tm_sec == pTM2->tm_sec ) return TRUE; return FALSE; }
2.34375
2
2024-11-18T22:21:50.939236+00:00
2022-09-26T22:56:20
e4f487f978ed9d2c53e2cfb18a1aca60301b7b75
{ "blob_id": "e4f487f978ed9d2c53e2cfb18a1aca60301b7b75", "branch_name": "refs/heads/master", "committer_date": "2022-09-26T22:56:20", "content_id": "66681799e8cc0aaa080e6e4d79e684234317e541", "detected_licenses": [ "Apache-2.0" ], "directory_id": "73ea5311653dc8796d2a5fd493a64c8b0ed01966", "extension": "c", "filename": "string_concat_sprintf.c", "fork_events_count": 37, "gha_created_at": "2009-10-24T00:08:37", "gha_event_created_at": "2012-06-28T18:51:49", "gha_language": "C", "gha_license_id": null, "github_id": 347931, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2523, "license": "Apache-2.0", "license_type": "permissive", "path": "/string/string_concat_sprintf.c", "provenance": "stackv2-0123.json.gz:7823", "repo_name": "ryd/chaosvpn", "revision_date": "2022-09-26T22:56:20", "revision_id": "4d7fbe90b71e83cd8182932f577fa97b3dc82265", "snapshot_id": "7779625f3210d260aee894f13787de06f7000c34", "src_encoding": "UTF-8", "star_events_count": 113, "url": "https://raw.githubusercontent.com/ryd/chaosvpn/4d7fbe90b71e83cd8182932f577fa97b3dc82265/string/string_concat_sprintf.c", "visit_date": "2022-10-22T08:16:38.431778" }
stackv2
#include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include "string.h" #define STRING_CFS_SIZE 32 static bool defprintf(struct string* s, const char* fmt, va_list exactlyonearg) { char buf[4096]; int len; len = vsnprintf(buf, 4096, fmt, exactlyonearg); return string_concatb(s, buf, len); } bool string_concat_sprintf(struct string* s, const char *msg, ...) { va_list args; char* a_s; struct string* a_S; char curchar; int a_i; char cfs[STRING_CFS_SIZE]; /* complex format string */ int cfsptr; /* reserve one byte for the format char, one for the terminating zero */ int cfsmaxlen = STRING_CFS_SIZE - 2; *cfs = '%'; cfs[cfsmaxlen] = 0; va_start(args, msg); for (;*msg;msg++) { if (*msg == '%') { cfsptr = 1; switch((curchar = *++msg)) { case '\0': goto finished; case 's': a_s = va_arg(args, char*); if (!string_concat(s, a_s)) return false; break; case 'S': a_S = va_arg(args, struct string*); if (!string_concats(s, a_S)) return false; break; case 'd': a_i = va_arg(args, int); if (!string_putint(s, a_i)) return false; break; case '0' ... '9': case '.': case ' ': case '#': case '+': case '-': case '\'': do { if (cfsptr == cfsmaxlen) { (void)fprintf(stderr, "Debug: Format string \"%s\" exceeds maximum length!\n", cfs); exit(1); } cfs[cfsptr++] = curchar; } while ((curchar = *++msg), ((curchar >= '0') && (curchar <= '9')) || (curchar == '.') || (curchar == ' ') || (curchar == '#') || (curchar == '+') || (curchar == '-') || (curchar == '\'')); /* fallthrough */ default: /* guaranteed to have two bytes left */ cfs[cfsptr++] = curchar; cfs[cfsptr] = 0; if (!defprintf(s, cfs, args)) return false; } } else { if (!string_putc(s, *msg)) return false; } } finished: va_end(args); if (!string_putc(s, 0)) return false; --s->length; return true; }
2.859375
3
2024-11-18T22:21:51.610497+00:00
2020-05-07T15:21:53
86e1554821cba443f64bf9988d3f5720e4c58dc0
{ "blob_id": "86e1554821cba443f64bf9988d3f5720e4c58dc0", "branch_name": "refs/heads/master", "committer_date": "2020-05-07T15:21:53", "content_id": "9df3868d8a84c4f71d4cbd9166acc6f0b942c6a8", "detected_licenses": [ "MIT" ], "directory_id": "e697a425c3ff7709552297d1dd7c630affcc9326", "extension": "c", "filename": "dynarray_int_example.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 262007331, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 627, "license": "MIT", "license_type": "permissive", "path": "/src/01_dynamic_array_int/dynarray_int_example.c", "provenance": "stackv2-0123.json.gz:8603", "repo_name": "jabbalaci/C-Utils", "revision_date": "2020-05-07T15:21:53", "revision_id": "84c2ea1d3a2102568adb29aee4f7d5ee86614c32", "snapshot_id": "9d6e5beee1915a78df83767e4cece17b2cbc97c5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jabbalaci/C-Utils/84c2ea1d3a2102568adb29aee4f7d5ee86614c32/src/01_dynamic_array_int/dynarray_int_example.c", "visit_date": "2022-06-19T07:21:10.352676" }
stackv2
#include <stdio.h> #include "dynarray_int.h" /* A simple example that demonstrates how to use our dynamic array. DynArrayInt can only store integers, it's not generic. */ int main() { DynArrayInt *li = da_create(); for (int i = 1; i <= 5; ++i) { da_append(li, i); } da_print(li); da_clear(li); puts("------------"); for (int i = 10; i <= 15; ++i) { da_append(li, i); } for (int i = 1; i <= 5; ++i) { da_append(li, i); } da_print(li); da_sort(li); puts("------------"); da_print(li); li = da_destroy(li); return 0; }
3
3
2024-11-18T22:21:51.978579+00:00
2017-08-16T22:36:03
93d1bf6a2b4f2074e5b27e85bf63b1ba539ec471
{ "blob_id": "93d1bf6a2b4f2074e5b27e85bf63b1ba539ec471", "branch_name": "refs/heads/master", "committer_date": "2017-08-16T22:36:03", "content_id": "b5d75e4b4b583cef3e0c0a409100511c11ca7de1", "detected_licenses": [ "MIT" ], "directory_id": "be3b61a2233e344eacd5c1517c2b52f506f6d8d5", "extension": "c", "filename": "teleporter.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 97986313, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3182, "license": "MIT", "license_type": "permissive", "path": "/game/src/teleporter.c", "provenance": "stackv2-0123.json.gz:8733", "repo_name": "Acknex/LotterVersusTheWorld", "revision_date": "2017-08-16T22:36:03", "revision_id": "022d0c67eb65c7d9c12c467860da5d2a44c30408", "snapshot_id": "3960b89b2f7c07a0099d574984b72980d086786d", "src_encoding": "ISO-8859-1", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Acknex/LotterVersusTheWorld/022d0c67eb65c7d9c12c467860da5d2a44c30408/game/src/teleporter.c", "visit_date": "2021-01-01T17:03:05.880950" }
stackv2
#include "init.h" ENTITY * teleporterEntity = NULL; ENTITY * teleporterSocket = NULL; SOUND * sndTeleport = "teleport_loop.wav"; void teleporter_enable() { reset(teleporterEntity, INVISIBLE); teleporterSocket->type = TypeTeleporterEnabled; } void teleporter_disable() { set(teleporterEntity, INVISIBLE); teleporterSocket->type = TypeTeleporterDisabled; } function teleport_effect(PARTICLE * p) { p->flags = BEAM | BRIGHT | MOVE; vec_set(p->vel_x, vector(0, 0, 2 + random(5))); vec_set(p->blue, COLOR_WHITE); vec_add(p->x, vec_rotate(vector(60,0,0), vector(random(360), 0, 0))); p->lifespan = 100; p->event = NULL; } STRING * teleporter_message = "#128"; action teleporter_out() { teleporterEntity = me; teleporterSocket = ent_create("Teleport.mdl", my.x, NULL); teleporterSocket.type = TypeTeleporterDisabled; teleporterSocket.material = ObjectMaterial; teleporterSocket.skill41 = floatv(29); set(me, PASSABLE | FLAG2 | INVISIBLE); my.material = TeleporterEffectMaterial; set(teleporterSocket, PASSABLE | FLAG2); while(!player) wait(1); proc_mode = PROC_LATE; var sndHandle = 0; var sndVolume = 0; var portloader = 0; while(1) { if(hex_isDead) { str_cpy(teleporter_message, "GUARDIAN:\n Shut down\n"); } else { str_cpy(teleporter_message, "GUARDIAN:\n Active\n"); } if(is(me, INVISIBLE)) { str_cat(teleporter_message, "TELEPORT:\n Disabled"); } else { str_cat(teleporter_message, "TELEPORT:\n Enabled"); } MARKER_setText(teleporterSocket, teleporter_message); var dist = vec_dist(vector(player.x, player.y, 0), vector(me.x, me.y, 0)); if(!is(me, INVISIBLE) && dist < 70) // ist höhenabhängig! { if(sndHandle == 0) { sndHandle = ent_playloop2(me, sndTeleport, 0, 100000); } else if(sndVolume < 100) { sndVolume = minv(100, sndVolume + 5*time_step); snd_tune(sndHandle, sndVolume, 0, 0); } if(dist > 5) { var force = 10 * pow(dist / 50, 1); VECTOR dir; vec_diff(dir, my.x, player.x); dir.z = 0; vec_normalize(dir, force * time_step); vec_add(player.x, dir); } player.near_teleport = 1; player.z += time_step; player.pan += 0.1 * portloader * time_step; portloader += time_step; if(portloader >= 75) { player.pan += 0.1 * portloader * time_step; player.pause_control = 1; var alpha = (portloader - 75) * 4; draw_quad( NULL, NULL, NULL, screen_size, NULL, COLOR_BLACK, alpha, 0); } if(portloader >= 100) { INIT_levelEnd(0); snd_stop(sndHandle); return; } effect(teleport_effect, 3 + time_frame, my.x, vector(0,0,0)); } else { if(sndHandle != 0) { if(sndVolume > 0) { sndVolume = maxv(0, sndVolume - 5*time_step); snd_tune(sndHandle, sndVolume, 0, 0); } else { snd_stop(sndHandle); sndHandle = 0; } } player.near_teleport = 0; portloader = maxv(0, portloader - 10 * time_step); } my->skill41 = floatv(0.001 + 0.001 * portloader); wait(1); } }
2.03125
2
2024-11-18T22:21:52.255282+00:00
2017-04-13T23:56:50
13b2364c4e5ee39764aec55f8a8c47f93e710cc8
{ "blob_id": "13b2364c4e5ee39764aec55f8a8c47f93e710cc8", "branch_name": "refs/heads/master", "committer_date": "2017-04-13T23:56:50", "content_id": "cb536ca62cc5a820fd624f71e83f6c59d004b122", "detected_licenses": [ "MIT" ], "directory_id": "1e5fc5a14d9a35430adc97610810d4eafc515b51", "extension": "c", "filename": "block.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 82503931, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2577, "license": "MIT", "license_type": "permissive", "path": "/src/block.c", "provenance": "stackv2-0123.json.gz:9250", "repo_name": "nicoaw/fatfs", "revision_date": "2017-04-13T23:56:50", "revision_id": "46ee7d28596b54e0e33ed4070a454d8bfd43a010", "snapshot_id": "04ca30db4abe023fb7a4cfa6e24960b82247e399", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/nicoaw/fatfs/46ee7d28596b54e0e33ed4070a454d8bfd43a010/src/block.c", "visit_date": "2021-01-20T11:41:13.240018" }
stackv2
#include "block.h" #include <stdlib.h> #include <syslog.h> block block_alloc(disk disk, block next) { syslog(LOG_DEBUG, "allocating block before %u", next); // Next must be valid or BLOCK_LAST if(next != BLOCK_LAST && !BLOCK_VALID(next)) { syslog(LOG_ERR, "invalid block %u", next); return BLOCK_INVALID; } const struct superblock *sb = disk_superblock(disk); block *fat_buffer = malloc(sb->block_size); // Find a free block using FAT for(uint32_t i = 0; i < sb->fat_block_count; ++i) { // Read FAT const block fat = BLOCK_FAT + i; if(block_read(disk, fat, fat_buffer) != 0) { free(fat_buffer); return BLOCK_INVALID; } for(uint32_t j = 0; j < BLOCK_FAT_ENTRY_COUNT(sb); ++j) { // Found free block if(fat_buffer[j] == BLOCK_FREE) { const block allocated = j + i * BLOCK_FAT_ENTRY_COUNT(sb); fat_buffer[j] = next; // Write updated FAT if(block_write(disk, fat, fat_buffer) != 0) { free(fat_buffer); return BLOCK_INVALID; } free(fat_buffer); syslog(LOG_DEBUG, "allocated block before %u", next); return allocated; } } } free(fat_buffer); syslog(LOG_ERR, "failed to allocate block"); return BLOCK_INVALID; } int block_free(disk disk, block head) { syslog(LOG_DEBUG, "freeing block %u", head); // Head must be valid if(!BLOCK_VALID(head)) { syslog(LOG_ERR, "invalid block %u", head); return -1; } const struct superblock *sb = disk_superblock(disk); const block fat = BLOCK_FAT_BLOCK(sb, head); block *fat_buffer = malloc(sb->block_size); // Read FAT if(block_read(disk, fat, fat_buffer) != 0) { free(fat_buffer); return -1; } fat_buffer[BLOCK_FAT_ENTRY(sb, head)] = BLOCK_FREE; // Write updated FAT if(block_write(disk, fat, fat_buffer) != 0) { free(fat_buffer); return -1; } free(fat_buffer); syslog(LOG_DEBUG, "freed block %u", head); return 0; } block block_next(disk disk, block previous) { syslog(LOG_DEBUG, "retreiving block after %u", previous); // Previous must be valid if(!BLOCK_VALID(previous)) { syslog(LOG_ERR, "invalid block %u", previous); return BLOCK_INVALID; } const struct superblock *sb = disk_superblock(disk); const block fat = BLOCK_FAT_BLOCK(sb, previous); block *fat_buffer = malloc(sb->block_size); // Read FAT if(block_read(disk, fat, fat_buffer) != 0) { free(fat_buffer); return BLOCK_INVALID; } // Get next block according to FAT block next = fat_buffer[BLOCK_FAT_ENTRY(sb, previous)]; free(fat_buffer); syslog(LOG_DEBUG, "retreived block %u after %u", next, previous); return next; }
3.25
3
2024-11-18T22:21:52.388699+00:00
2019-09-09T13:16:30
57cad505a6426a943740fa20aa2ac9a47c10b1a3
{ "blob_id": "57cad505a6426a943740fa20aa2ac9a47c10b1a3", "branch_name": "refs/heads/master", "committer_date": "2019-09-09T13:16:30", "content_id": "7769db9d5069e149dafb7bd7bdaeaf5534da0aa2", "detected_licenses": [ "MIT" ], "directory_id": "4619776a2a2623932f0b8cd447953dbe818aeab5", "extension": "c", "filename": "Ponteiros2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 207312147, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 255, "license": "MIT", "license_type": "permissive", "path": "/Prova1/Ponteiro/Ponteiros2.c", "provenance": "stackv2-0123.json.gz:9380", "repo_name": "JoezerSmaniotto/Estrutura-De-Dados", "revision_date": "2019-09-09T13:16:30", "revision_id": "6b389ee2fe8f6668cf39ffc047e5238f787d9efa", "snapshot_id": "ef3d4e412740a7230cef6d5dd895078035bbcaca", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/JoezerSmaniotto/Estrutura-De-Dados/6b389ee2fe8f6668cf39ffc047e5238f787d9efa/Prova1/Ponteiro/Ponteiros2.c", "visit_date": "2020-07-22T20:01:04.391900" }
stackv2
#include <stdio.h> int main(){ int x=10; int *p=&x; int **p2=&p; // Endereço p2 printf("p2: %d\n",p2); //&p //Conteudo do endereço printf("*p2: %d\n",*p2); //Conteudo do endereço do endereço printf("**p2: %d\n",**p2); return 0; }
2.96875
3
2024-11-18T22:21:52.719891+00:00
2023-05-01T23:26:05
91faf19700bf9ae320a211595306bf4dd9327ac8
{ "blob_id": "91faf19700bf9ae320a211595306bf4dd9327ac8", "branch_name": "refs/heads/main", "committer_date": "2023-05-01T23:26:05", "content_id": "910b2378826dfb899a849a445569aa7e795fa63f", "detected_licenses": [ "MIT" ], "directory_id": "951f42c24c08d1e7267c1cc5d1efb2b44a63db2e", "extension": "c", "filename": "downgrade_test.c", "fork_events_count": 41, "gha_created_at": "2020-08-17T19:50:33", "gha_event_created_at": "2023-05-01T23:26:06", "gha_language": "HTML", "gha_license_id": "MIT", "github_id": 288272839, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2537, "license": "MIT", "license_type": "permissive", "path": "/sources/upgrade/downgrade_test.c", "provenance": "stackv2-0123.json.gz:9511", "repo_name": "facebookincubator/CG-SQL", "revision_date": "2023-05-01T23:26:05", "revision_id": "c32ca40310a322e82ec4d6d863d77eed1633ef02", "snapshot_id": "a4c0dc2089aab9d2379317ce25e695669eb01531", "src_encoding": "UTF-8", "star_events_count": 392, "url": "https://raw.githubusercontent.com/facebookincubator/CG-SQL/c32ca40310a322e82ec4d6d863d77eed1633ef02/sources/upgrade/downgrade_test.c", "visit_date": "2023-05-11T07:28:28.189974" }
stackv2
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <sqlite3.h> #include <stdio.h> // All versions have the same signatures, include them all! // If we screwed this up the compiler will complain! // // Note that the downgrade test of course uses the upgrader but with a bad setup // there is no such thing as a generated downgrader... #include "generated_upgrade0.h" #include "generated_upgrade1.h" #include "generated_upgrade2.h" #include "generated_upgrade3.h" int downgrade(sqlite3* db, test_result_set_ref* result_set) { return test_fetch_results(db, result_set); } int validate(sqlite3* db, test_result_set_ref result_set) { cql_int32 count = test_result_count(result_set); if (count != 1) { printf("Expected 1 facet for database downgrade, got %d\n", count); return SQLITE_ERROR; } cql_string_ref expected_facet = cql_string_ref_new("downgrade detected"); cql_string_ref actual_facet = test_get_facet(result_set, 0); if (!cql_string_equal(expected_facet, actual_facet)) { cql_alloc_cstr(actual_facet_c, actual_facet); printf("Expected 'downgrade detected' facet, got '%s'\n", actual_facet_c); cql_free_cstr(actual_facet_c, actual_facet); cql_string_release(expected_facet); return SQLITE_ERROR; } const char* sql = "DROP VIEW test_view"; if (sqlite3_exec(db, sql, NULL, NULL, NULL) != SQLITE_OK) { printf("Expected 'test_view' to remain in the DB\n"); return SQLITE_ERROR; } return SQLITE_OK; } int main(int argc, char* argv[]) { if (argc != 2) { printf("Expected usage: ./downgrade_test /path/to/db/\n"); return SQLITE_ERROR; } sqlite3* db; if (sqlite3_open_v2( argv[1], &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL)) { printf("Unable to open DB.\n"); return SQLITE_ERROR; } test_result_set_ref result_set; if (downgrade(db, &result_set)) { printf("Unable to downgrade DB.\n"); return SQLITE_ERROR; } if (validate(db, result_set)) { printf("Unable to validate that the downgrade was detected.\n"); cql_result_set_release(result_set); return SQLITE_ERROR; } if (sqlite3_close_v2(db)) { printf("Unable to close DB.\n"); cql_result_set_release(result_set); return SQLITE_ERROR; } cql_result_set_release(result_set); return SQLITE_OK; } cql_code mockable_sqlite3_step(sqlite3_stmt *stmt) { return sqlite3_step(stmt); }
2.296875
2
2024-11-18T22:21:52.801866+00:00
2018-01-19T11:57:43
3da2a9d12106544d5d1abe4c7fd1298d551c570b
{ "blob_id": "3da2a9d12106544d5d1abe4c7fd1298d551c570b", "branch_name": "refs/heads/master", "committer_date": "2018-01-19T11:57:43", "content_id": "70283e559aaf85a9045ae1609dffad7e7ed44cd2", "detected_licenses": [ "MIT-Modern-Variant" ], "directory_id": "a80a72588c556125579f6581022d37837628dd8f", "extension": "c", "filename": "network_test_3_snd.c", "fork_events_count": 0, "gha_created_at": "2017-12-12T07:19:00", "gha_event_created_at": "2018-01-19T11:57:46", "gha_language": "C++", "gha_license_id": null, "github_id": 113957032, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 710, "license": "MIT-Modern-Variant", "license_type": "permissive", "path": "/code/test/network_test_3_snd.c", "provenance": "stackv2-0123.json.gz:9639", "repo_name": "korkmazkadir/sysproj-team-e", "revision_date": "2018-01-19T11:57:43", "revision_id": "15f6ba40a7c5ebf7a5dcd325c710c2455f6b22dd", "snapshot_id": "38f3a713d882e08d08b53ed378544f449a30175d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/korkmazkadir/sysproj-team-e/15f6ba40a7c5ebf7a5dcd325c710c2455f6b22dd/code/test/network_test_3_snd.c", "visit_date": "2021-09-04T14:18:34.914403" }
stackv2
#include "syscall.h" #include "utility.h" int main() { int connId = NetworkConnectAsServer(0); SynchPutString("Conn ID: "); SynchPutInt(connId); PutChar('\n'); const char *data = "Hello world"; NetworkSendToByConnId(connId, data, strlen(data)); int status = NetworkCloseConnection(connId); SynchPutString("Conn closed with status: "); SynchPutInt(status); PutChar('\n'); connId = NetworkConnectAsServer(0); SynchPutString("Conn ID: "); SynchPutInt(connId); PutChar('\n'); NetworkSendToByConnId(connId, data, strlen(data)); status = NetworkCloseConnection(connId); SynchPutString("Conn closed with status: "); SynchPutInt(status); PutChar('\n'); return 0; }
2.265625
2
2024-11-18T22:21:52.907853+00:00
2016-10-25T15:41:38
318e7a2e5bf70ce339fb3dc2b1441f97e9012fb0
{ "blob_id": "318e7a2e5bf70ce339fb3dc2b1441f97e9012fb0", "branch_name": "refs/heads/master", "committer_date": "2016-10-25T15:41:38", "content_id": "10ff7b4a08a2f4d2eb6a8c6917cd18f520ebcd4e", "detected_licenses": [ "MIT" ], "directory_id": "1184eab54804e15236274035128dfea0f123a558", "extension": "c", "filename": "week5.2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 71912325, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 928, "license": "MIT", "license_type": "permissive", "path": "/Solutions/week5.2.c", "provenance": "stackv2-0123.json.gz:9767", "repo_name": "AaronAnthonyByrne/C-Code", "revision_date": "2016-10-25T15:41:38", "revision_id": "31e8ec3ba029efef23aad36a35d3361d896201ee", "snapshot_id": "e71bbccb7b8a702c3e963b05d71af9e45a23183d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AaronAnthonyByrne/C-Code/31e8ec3ba029efef23aad36a35d3361d896201ee/Solutions/week5.2.c", "visit_date": "2021-01-10T18:08:10.443510" }
stackv2
/* solution to labs display 1-10 in reverse order(seperate line) 21/10/2015 */ #include <stdio.h> main() { int num= 0; int steps= 0; while (num < 1) { printf("Enter a number \n"); scanf("%d", &num); } do { //check if even if (num % 2 == 0) { num = num /2; printf("\n Value of num is %d",num); }//end if else { num=(num*3)+1; printf("\n Value of num is %d",num); } steps++; }//end while while(num !=1); printf("\nThe final value i is %d. \nThe number of steps taken is %d",num, steps); getchar(); getchar(); }//end main
3.53125
4
2024-11-18T22:21:56.107379+00:00
2016-12-07T05:14:34
edc8299879bb1746743f1c90e8e0291a81a2f24c
{ "blob_id": "edc8299879bb1746743f1c90e8e0291a81a2f24c", "branch_name": "refs/heads/master", "committer_date": "2016-12-07T05:14:34", "content_id": "ab07c2f58201f3c8fd7e63b8f24bcd69db5975ff", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "d58a7a0d9ad2057e594ce137a783333d4a43fb14", "extension": "h", "filename": "map.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": 1919, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/map.h", "provenance": "stackv2-0123.json.gz:9898", "repo_name": "kevinpt/uniset", "revision_date": "2016-12-07T05:14:34", "revision_id": "a5fac4a091857dd5429cc2de48c7a93407f7dedd", "snapshot_id": "8a96666bc5b88402c130de5718a53a7bddd324fe", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kevinpt/uniset/a5fac4a091857dd5429cc2de48c7a93407f7dedd/src/map.h", "visit_date": "2022-02-07T17:01:08.087385" }
stackv2
struct set; struct maprange { unsigned int first, last; unsigned int value; }; struct map { unsigned int length; struct maprange r[]; }; struct mapbuilder { unsigned int alloc; unsigned int size; unsigned int defaultv; unsigned int cfirst, clast, cvalue; struct map *map; }; struct map * map_resize(struct map *m, unsigned int size); void mapbuilder_init(struct mapbuilder *restrict m, unsigned int defaultv); void mapbuilder_destroy(struct mapbuilder *restrict m); struct map * mapbuilder_finish(struct mapbuilder *restrict m); static inline void mapbuilder_insert(struct mapbuilder *restrict m, unsigned int first, unsigned int last, unsigned int value) { if (value == m->cvalue && (m->clast == first - 1 || value == m->defaultv)) { m->clast = last; } else { if (m->cvalue != (unsigned int)-1 || m->clast != first - 1) { if (m->cvalue == m->defaultv) m->clast = first - 1; struct maprange *restrict r; if (m->size + 2 > m->alloc) { unsigned int nalloc = m->alloc ? m->alloc * 2 : 16; m->map = map_resize(m->map, nalloc); m->alloc = nalloc; } r = m->map->r + m->size; if (m->cvalue != (unsigned int)-1) { r->first = m->cfirst; r->last = m->clast; r->value = m->cvalue; r++; m->size++; } if (m->clast != first - 1) { r->first = m->clast + 1; r->last = first - 1; r->value = m->defaultv; r++; m->size++; } } m->cfirst = first; m->clast = last; m->cvalue = value; } } struct set * map_preimage(struct map *restrict m, unsigned int bitset);
2.109375
2
2024-11-18T22:22:04.381481+00:00
2022-11-26T15:23:02
d0565863d33be3c811458ec230221dcf715767cc
{ "blob_id": "d0565863d33be3c811458ec230221dcf715767cc", "branch_name": "refs/heads/master", "committer_date": "2022-11-26T15:23:02", "content_id": "9129fc2a93507868dfc3b4d41e5c71ffb09d9651", "detected_licenses": [ "MIT" ], "directory_id": "015200ae3983d097668fd3f944fc89a407cc48e4", "extension": "h", "filename": "log.h", "fork_events_count": 6, "gha_created_at": "2020-04-03T20:18:36", "gha_event_created_at": "2022-12-08T16:51:53", "gha_language": "C", "gha_license_id": "MIT", "github_id": 252832018, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 777, "license": "MIT", "license_type": "permissive", "path": "/log.h", "provenance": "stackv2-0123.json.gz:11058", "repo_name": "rfjakob/systembus-notify", "revision_date": "2022-11-26T15:23:02", "revision_id": "a31e8291444c787c5c05d39bbab70bde0b1f6d4d", "snapshot_id": "cb6cdc7345a9e588d029f0b4468f0ccbfb888341", "src_encoding": "UTF-8", "star_events_count": 48, "url": "https://raw.githubusercontent.com/rfjakob/systembus-notify/a31e8291444c787c5c05d39bbab70bde0b1f6d4d/log.h", "visit_date": "2022-12-22T16:03:51.929874" }
stackv2
/* SPDX-License-Identifier: MIT */ #ifndef LOG_H #define LOG_H extern int quiet; /* From https://gcc.gnu.org/onlinedocs/gcc-9.2.0/gcc/Common-Function-Attributes.html : * The format attribute specifies that a function takes printf * style arguments that should be type-checked against a format string. */ void debug(const char* fmt, ...) __attribute__((format(printf, 1, 2))); // Exit codes enum { FATAL_USAGE = 2, // Usage error FATAL_SYSTEM_BUS = 3, // Problem connecting to system d-bus FATAL_USER_BUS = 4, // Problem connecting to user d-bus FATAL_SYSTEM_BUS_PROCESS = 5, // Problem processing d-bus signals from system d-bus FATAL_EVENT = 6, // Problem in event loop FATAL_SEND_NOTIFY = 7, // problem calling notify on the user bus }; #endif
2.140625
2
2024-11-18T22:22:04.509367+00:00
2015-03-02T07:39:23
619fa6169f4f27251c00f7582a54e76531b9a56a
{ "blob_id": "619fa6169f4f27251c00f7582a54e76531b9a56a", "branch_name": "refs/heads/master", "committer_date": "2015-03-02T07:39:23", "content_id": "e03f5ed5043416b4827280acda97c41749c1c464", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f37c3546f39d7ebc4236c043e740d68bf826e8c1", "extension": "c", "filename": "FskAnimation.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": 22136, "license": "Apache-2.0", "license_type": "permissive", "path": "/core/graphics/FskAnimation.c", "provenance": "stackv2-0123.json.gz:11187", "repo_name": "sandy-slin/kinomajs", "revision_date": "2015-03-02T07:39:23", "revision_id": "567b52be74ec1482e0bab2d370781a7188aeb0ab", "snapshot_id": "f08f60352b63f1d3fad3f6b0e9a5e4bc8025f082", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sandy-slin/kinomajs/567b52be74ec1482e0bab2d370781a7188aeb0ab/core/graphics/FskAnimation.c", "visit_date": "2020-12-24T22:21:05.506599" }
stackv2
/* Copyright (C) 2010-2015 Marvell International Ltd. Copyright (C) 2002-2010 Kinoma, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "FskAnimation.h" #include "FskUtilities.h" #include "FskFixedMath.h" /******************************************************************************** ******************************************************************************** ******************************************************************************** ***** macros and typedefs ***** ******************************************************************************** ******************************************************************************** ********************************************************************************/ #define FRACT_ONE 0x40000000 //#define BITS_OF_ACCURACY 27 /* 7.45058e-9 */ //#define BITS_OF_ACCURACY 26 /* 1.49012e-8 */ //#define BITS_OF_ACCURACY 25 /* 2.98023e-8 */ #define BITS_OF_ACCURACY 24 /* 5.96046e-8 */ /* Here we declare that the accuracy of single-precision floating-point is OK */ //#define BITS_OF_ACCURACY 23 /* 1.19209e-7 */ //#define BITS_OF_ACCURACY 22 /* 2.38419e-7 */ //#define BITS_OF_ACCURACY 21 /* 4.76837e-7 */ //#define BITS_OF_ACCURACY 20 /* 9.53674e-7 */ #define ALMOST_FLAT (1 << (30 - BITS_OF_ACCURACY)) typedef struct FskFixedPoint2D FskFractPoint2D; typedef struct TimingKey { FskFract ti; FskFract to; FskFractVector2D c0; FskFractVector2D c1; } TimingKey; /******************************************************************************** ******************************************************************************** ******************************************************************************** ***** Key Spline Utilities ***** ******************************************************************************** ******************************************************************************** ********************************************************************************/ /******************************************************************************** * CopyCubicBezier2D ********************************************************************************/ struct _bz4x2 { FskFractPoint2D p[4]; }; #define CopyCubicBezier2D(fr, to) *((struct _bz4x2*)(void*)(&to[0])) = *((struct _bz4x2*)(void*)(&fr[0])) /******************************************************************************** * FskEvaluateFractKeySplineSegment ********************************************************************************/ FskFract FskEvaluateFractKeySplineSegment(FskFract cx0, FskFract cy0, FskFract cx1, FskFract cy1, FskFract x) { FskFractPoint2D B[4], *b; FskFract t; if ((cx0 | cy0 | (cx1 ^ FRACT_ONE) | (cy1 ^ FRACT_ONE)) == 0) return x; /* control(0,0,1,1) --> default --> identity */ if (x <= 0) return 0; /* 0 --> 0 */ if (x >= FRACT_ONE) return FRACT_ONE; /* 1 --> 1 */ /* Solve by bisection (we should sometime try Newton) */ #ifndef BEZIER_BISECTION_CAN_OVERFLOW /* No need to do this if AVOID_DECASTELJAU_OVERFLOW is #defined in FskFixedMath.c */ B[0].x = 0; B[0].y = 0; B[1].x = cx0; B[1].y = cy0; B[2].x = cx1; B[2].y = cy1; B[3].x = FRACT_ONE; B[3].y = FRACT_ONE; #else /* BEZIER_BISECTION_CAN_OVERFLOW */ /* Need to do this if AVOID_DECASTELJAU_OVERFLOW is not #defined in FskFixedMath.c */ B[0].x = 0 >> 1; B[0].y = 0 >> 1; /* Insert extra headroom to avoid bisection overflow */ B[1].x = cx0 >> 1; B[1].y = cy0 >> 1; B[2].x = cx1 >> 1; B[2].y = cy1 >> 1; B[3].x = FRACT_ONE >> 1; B[3].y = FRACT_ONE >> 1; x >>= 1; #endif /* BEZIER_BISECTION_CAN_OVERFLOW */ while (FskFixedDeviationOfBezierControlPoints2D(B, 4) > ALMOST_FLAT) { /* If not flat enough, split Bezier */ FskFractPoint2D L[4], R[4]; FskFixedBisectBezier(&B[0].x, 4, 2, &L[0].x, &R[0].x); /* Bisect Bezier, diminishing variation quadratically */ if (x > R[0].x) CopyCubicBezier2D(R, B); /* Since the curve is monotonic, we can easily choose the proper half */ else CopyCubicBezier2D(L, B); } if (x >= B[1].x) { if (x <= B[2].x) b = &B[1]; /* The usual case: middle segment */ else b = &B[2]; /* Last segment */ } else b = &B[0]; /* First segment */ if ((t = b[1].x - b[0].x) > 0) { #ifdef BEZIER_BISECTION_CAN_OVERFLOW b[0].y <<= 1; b[1].y <<= 1; /* Remove computational headroom */ #endif /* BEZIER_BISECTION_CAN_OVERFLOW */ t = FskFixedRatio(b[1].y - b[0].y, x - b[0].x, t) + b[0].y; /* Interpolate on non-null domain */ } else { #ifdef BEZIER_BISECTION_CAN_OVERFLOW t = b[1].y + b[0].y; /* Average on null domain, remembering that the values have already been halved */ #else /* BEZIER_BISECTION_CAN_OVERFLOW */ t = ((b[1].y - b[0].y) >> 1) + b[0].y; /* Average on null domain, avoiding overflow */ #endif /* BEZIER_BISECTION_CAN_OVERFLOW */ } return t; } /******************************************************************************** * FskEvaluateASegmentOfAKeySpline * This is accurate to 30 fractional bits, * which is more than the 24 bits of single-precision floating-point, * but less than the 53 of double-precision floating-point ********************************************************************************/ double FskEvaluateASegmentOfAKeySpline(double cx0, double cy0, double cx1, double cy1, double x) { if (x <= 0) return 0; /* Return the closest if x is out of the domain */ if (x >= 1) return 1; return FskFractToFloat(FskEvaluateFractKeySplineSegment( FskRoundAndSaturateFloatToUnityFract(cx0), FskRoundAndSaturateFloatToUnityFract(cy0), FskRoundAndSaturateFloatToUnityFract(cx1), FskRoundAndSaturateFloatToUnityFract(cy1), FskRoundAndSaturateFloatToUnityFract(x) )); } /******************************************************************************** * IsFractable ********************************************************************************/ #define IsFractable(f) ((f >= 0) && (f <= 1)) /******************************************************************************** * IsMonotonicAndFractableArray ********************************************************************************/ static int IsMonotonicAndFractableArray(register const double *f, int n) { register double g; for (n--; n--; f++) { g = f[0]; if (!( IsFractable(g) /* This checks the first N-1 and will work with NaN's */ && (g <= f[1]) )) return 0; } g = f[0]; if (!IsFractable(g)) /* This checks the first 1 and will work with NaN's */ return 0; return 1; } /******************************************************************************** * IsFractableArray ********************************************************************************/ static int IsFractableArray(const double *f, int n) { register double g; for ( ; n--; f++) { g = *f; if (!IsFractable(g)) return 0; } return 1; } /******************************************************************************** ******************************************************************************** ******************************************************************************** ***** FskKeySplineSegment ***** ******************************************************************************** ******************************************************************************** ********************************************************************************/ /* This data structure is opaque from the API */ typedef struct FskKeySplineSegmentRecord { FskFract x0, y0, x1, y1; } FskKeySplineSegmentRecord; /******************************************************************************** * FskKeySplineSegmentNew ********************************************************************************/ FskErr FskKeySplineSegmentNew(double x0, double y0, double x1, double y1, FskKeySplineSegment *seg) { FskErr err; FskKeySplineSegment s; BAIL_IF_FALSE(( IsFractable(x0) && IsFractable(y0) && IsFractable(x1) && IsFractable(y1) ), err, kFskErrBadData); BAIL_IF_ERR(err = FskMemPtrNew(sizeof(FskKeySplineSegmentRecord), (FskMemPtr*)seg)); s = *seg; s->x0 = FskRoundPositiveFloatToFract(x0); s->y0 = FskRoundPositiveFloatToFract(y0); s->x1 = FskRoundPositiveFloatToFract(x1); s->y1 = FskRoundPositiveFloatToFract(y1); bail: return err; } /******************************************************************************** * FskKeySplineSegmentDispose ********************************************************************************/ void FskKeySplineSegmentDispose(FskKeySplineSegment seg) { FskMemPtrDispose(seg); } /******************************************************************************** * FskKeySplineSegmentEvaluate ********************************************************************************/ double FskKeySplineSegmentEvaluate(FskKeySplineSegment seg, double t) { return FskFractToFloat(FskEvaluateFractKeySplineSegment(seg->x0, seg->y0, seg->x1, seg->y1, FskRoundAndSaturateFloatToUnityFract(t))); } /******************************************************************************** ******************************************************************************** ******************************************************************************** ***** Key Animation ***** ******************************************************************************** ******************************************************************************** ********************************************************************************/ struct FskKeyAnimationRecord { UInt32 calcMode; /* kFskAnimationDiscreteInterpolation, kFskAnimationLinearInterpolation, kFskAnimationPacedInterpolation, kFskAnimationSplineInterpolation */ UInt32 numKeys; /* The number of keys */ TimingKey *timingKeys; /* timingKeys[numValues] */ }; typedef struct FskKeyAnimationRecord FskKeyAnimationRecord; /******************************************************************************** * KeyAnimationInit ********************************************************************************/ static FskErr KeyAnimationInit( UInt32 calcMode, /* kFskDiscreteInterpolation, kFskLinearInterpolation, kFskPacedInterpolation, kFskSplineInterpolation */ UInt32 numKeys, /* The number of values */ const double *keyTimes, /* keyTimes[numValues] */ const double *keyValues, /* keyValues[numValues] */ const double *keySplines, /* keySplines[numValues-1][4] */ FskKeyAnimation anim ) { FskErr err = kFskErrNone; anim->calcMode = calcMode; if ((anim->numKeys = numKeys) != 0) { TimingKey *key; UInt32 i, j; if (keyTimes != NULL) { BAIL_IF_FALSE(IsMonotonicAndFractableArray(keyTimes, numKeys), err, kFskErrOutOfSequence); for (i = numKeys, key = anim->timingKeys; i--; key++, keyTimes++) key->ti = FskRoundPositiveFloatToFract(*keyTimes); /* Copy key times */ } else { if (calcMode == kFskAnimationDiscreteInterpolation) { for (i = 0, j = numKeys, key = anim->timingKeys; i < numKeys; i++, key++) key->ti = FskFracDiv(i, j); /* Equal intervals */ } else { for (i = 0, j = numKeys - 1, key = anim->timingKeys; i < numKeys; i++, key++) key->ti = FskFracDiv(i, j); /* Equal intervals */ } } if (keyValues != NULL) { BAIL_IF_FALSE(IsFractableArray(keyValues, numKeys), err, kFskErrBadData); for (i = numKeys, key = anim->timingKeys; i--; key++, keyValues++) key->to = FskRoundPositiveFloatToFract(*keyValues); /* Copy key points */ } else if (keyTimes != NULL) { for (i = numKeys, key = anim->timingKeys; i--; key++) key->to = key->ti; /* to = ti */ } else { for (i = 0, j = numKeys - 1, key = anim->timingKeys; i < numKeys; i++, key++) key->to = FskFracDiv(i, j); /* Equal intervals */ } if (keySplines != NULL) { BAIL_IF_FALSE(IsFractableArray(keySplines, (numKeys - 1) * 4), err, kFskErrBadData); for (i = numKeys - 1, key = anim->timingKeys; i--; key++) { /* Copy key splines */ key->c0.x = FskRoundPositiveFloatToFract(*keySplines++); key->c0.y = FskRoundPositiveFloatToFract(*keySplines++); key->c1.x = FskRoundPositiveFloatToFract(*keySplines++); key->c1.y = FskRoundPositiveFloatToFract(*keySplines++); } } else { for (i = numKeys - 1, key = anim->timingKeys; i--; key++) { /* Set to identity */ key->c0.x = 0; key->c0.y = 0; key->c1.x = FRACT_ONE; key->c1.y = FRACT_ONE; } } } bail: return err; } /******************************************************************************** * KeyAnimationAdjustPace ********************************************************************************/ static FskFract KeyAnimationAdjustPace(FskConstKeyAnimation anim, FskFract s) { TimingKey *key = NULL; UInt32 i; if (anim->timingKeys != NULL) { for (i = anim->numKeys - 1, key = anim->timingKeys; i--; key++) if ((s >= key[0].ti) && (s < key[1].ti)) break; switch (anim->calcMode) { case kFskAnimationDiscreteInterpolation: s = key->to; break; case kFskAnimationLinearInterpolation: s = FskFixedRatio(key[1].to - key[0].to, s - key[0].ti, key[1].ti - key[0].ti) + key[0].to; break; case kFskAnimationPacedInterpolation: /* s = s */ break; case kFskAnimationSplineInterpolation: s = FskFracDiv(s - key[0].ti, key[1].ti - key[0].ti); s = FskEvaluateFractKeySplineSegment(key->c0.x, key->c0.y, key->c1.x, key->c1.y, s); s = FskFracMul(s, key[1].to - key[0].to) + key[0].to; break; } } return s; } /******************************************************************************** * FskKeyAnimationDispose ********************************************************************************/ void FskKeyAnimationDispose(FskKeyAnimation anim) { FskMemPtrDispose(anim); } /******************************************************************************** * FskKeyAnimationNew ********************************************************************************/ FskErr FskKeyAnimationNew( UInt32 calcMode, /* kFskDiscreteInterpolation, kFskLinearInterpolation, kFskPacedInterpolation, kFskSplineInterpolation */ UInt32 numKeys, /* The number of values */ const double *keyTimes, /* keyTimes[numValues] */ const double *keyValues, /* keyValues[numValues] */ const double *keySplines, /* keySplines[numValues-1][4] */ FskKeyAnimation *anim ) { FskErr err; if ((err = FskMemPtrNewClear(sizeof(FskKeyAnimationRecord)+(numKeys+1)*sizeof(TimingKey), (FskMemPtr*)anim)) == kFskErrNone) { (**anim).timingKeys = (TimingKey*)(*anim + 1); KeyAnimationInit(calcMode, numKeys, keyTimes, keyValues, keySplines, *anim); } return err; } /******************************************************************************** * FskKeyAnimationEvaluate ********************************************************************************/ double FskKeyAnimationEvaluate(FskConstKeyAnimation anim, double t) { return FskFractToFloat(KeyAnimationAdjustPace(anim, FskRoundAndSaturateFloatToUnityFract(t))); } /******************************************************************************** ******************************************************************************** ******************************************************************************** ***** Path Animation ***** ******************************************************************************** ******************************************************************************** ********************************************************************************/ struct FskPathAnimationRecord { FskKeyAnimationRecord keyAnim; FskConstPath path; FskArcLengthTable arcLengthTab; }; typedef struct FskPathAnimationRecord FskPathAnimationRecord; /******************************************************************************** * FskPathAnimationDispose ********************************************************************************/ void FskPathAnimationDispose(FskPathAnimation anim) { if (anim != NULL) { if (anim->arcLengthTab != NULL) FskPathArcLengthTableDispose(anim->arcLengthTab); FskMemPtrDispose(anim); } } /******************************************************************************** * FskKeyPathAnimationNew ********************************************************************************/ FskErr FskKeyPathAnimationNew( FskConstPath path, /* Not copied!!! */ UInt32 calcMode, /* kFskDiscreteInterpolation, kFskLinearInterpolation, kFskPacedInterpolation, kFskSplineInterpolation */ UInt32 numKeys, /* The number of keys */ const double *keyTimes, /* keyTimes[numKeys] */ const double *keyPoints, /* keyPoints[numKeys] */ const double *keySplines, /* keySplines[numKeys-1][4] */ FskPathAnimation *anim /* The result */ ) { FskErr err; FskArcLengthTable arcTab = NULL; double *defaultKeyPoints = NULL; *anim = NULL; BAIL_IF_NULL(path, err, kFskErrInvalidParameter); BAIL_IF_ERR(err = FskPathArcLengthTableNew(path, &arcTab, NULL)); /* Generate arc length table in case we need it for the default keys */ if ( ((numKeys == 0) || (keyPoints == NULL)) /* Check for keyPoints ... */ && (FskPathGetVisibleSegmentDistances(path, arcTab, &numKeys, &defaultKeyPoints) == kFskErrNone) /* ... or allocate some defaults */ ) { keyTimes = NULL; /* This triggers a default uniform interval between key times */ keyPoints = defaultKeyPoints; /* Normalized segment distances */ } BAIL_IF_ERR(err = FskMemPtrNewClear(sizeof(FskPathAnimationRecord)+(numKeys+1)*sizeof(TimingKey), (FskMemPtr*)anim)); /* Allocate anim */ (**anim).path = path; /* Initialize anim */ (**anim).keyAnim.timingKeys = (TimingKey*)(*anim + 1); (**anim).arcLengthTab = arcTab; /* Transfer ownership of arcTab to *anim, ... */ arcTab = NULL; /* ... and indicate that we no longer look after it */ KeyAnimationInit(calcMode, numKeys, keyTimes, keyPoints, keySplines, &((**anim).keyAnim)); bail: FskMemPtrDispose(defaultKeyPoints); FskMemPtrDispose(arcTab); return err; } /******************************************************************************** * FskPathAnimationNew ********************************************************************************/ FskErr FskPathAnimationNew( FskConstPath path, /* Not copied!!! */ FskPathAnimation *anim /* The result */ ) { return FskKeyPathAnimationNew(path, kFskAnimationPacedInterpolation, 0, NULL, NULL, NULL, anim); } /******************************************************************************** * FskPathAnimationCountPathSegments ********************************************************************************/ UInt32 FskPathAnimationCountPathSegments(FskConstPathAnimation anim) { return FskPathGetSegmentCount(anim->path); } /******************************************************************************** * ConvertFractFractFixedToDoubleMatrices ********************************************************************************/ static void ConvertFractFractFixedToDoubleMatrices(const FskFixedMatrix3x2 *M, double *Mtrn, double *Mrot) { if (Mtrn != NULL) { Mtrn[0*2+0] = 1; Mtrn[0*2+1] = 0; Mtrn[1*2+0] = 0; Mtrn[1*2+1] = 1; Mtrn[2*2+0] = FskFixedToFloat(M->M[2][0]); Mtrn[2*2+1] = FskFixedToFloat(M->M[2][1]); } if (Mrot != NULL) { Mrot[0*2+0] = FskFractToFloat(M->M[0][0]); Mrot[0*2+1] = FskFractToFloat(M->M[0][1]); Mrot[1*2+0] = FskFractToFloat(M->M[1][0]); Mrot[1*2+1] = FskFractToFloat(M->M[1][1]); Mrot[2*2+0] = 0; Mrot[2*2+1] = 0; } } /******************************************************************************** * FskPathAnimationEvaluate ********************************************************************************/ FskErr FskPathAnimationEvaluate(FskConstPathAnimation anim, double s, double *Mtrn, double *Mrot) { FskErr err; FskFixedMatrix3x2 M; FskFract f; f = FskRoundAndSaturateFloatToUnityFract(s); f = KeyAnimationAdjustPace(&anim->keyAnim, f); err = FskPathEvaluate(anim->path, anim->arcLengthTab, f, &M); ConvertFractFractFixedToDoubleMatrices(&M, Mtrn, Mrot); return err; } /******************************************************************************** * FskPathAnimationEvaluateSegment ********************************************************************************/ FskErr FskPathAnimationEvaluateSegment(FskConstPathAnimation anim, UInt32 segIndex, double s, double *Mtrn, double *Mrot) { FskErr err; FskFixedMatrix3x2 M; FskFract f; f = FskRoundAndSaturateFloatToUnityFract(s); err = FskPathEvaluateSegment(anim->path, anim->arcLengthTab, segIndex, f, &M); ConvertFractFractFixedToDoubleMatrices(&M, Mtrn, Mrot); return err; } /******************************************************************************** * FskPathAnimationGetSegmentDistances ********************************************************************************/ FskErr FskPathAnimationGetSegmentDistances(FskConstPathAnimation anim, UInt32 seg, double startEnd[2]) { FskErr err = kFskErrNone; UInt32 numSegs; FskFract dist[2]; BAIL_IF_FALSE( ( ((numSegs = FskPathGetSegmentCount(anim->path)) > 0) && (seg < numSegs) ), err, kFskErrUnknownElement ); FskPathArcLengthTableGetDistancesOfSegment(anim->arcLengthTab, seg, dist); startEnd[0] = FskFractToFloat(dist[0]); startEnd[1] = FskFractToFloat(dist[1]); bail: return err; }
2.03125
2
2024-11-18T22:22:04.774727+00:00
2019-02-16T15:24:58
eae650cdda4167f34923379276a1df401332fe0a
{ "blob_id": "eae650cdda4167f34923379276a1df401332fe0a", "branch_name": "refs/heads/master", "committer_date": "2019-02-16T15:24:58", "content_id": "0e5f4be844841066417475e19842a4a40a3403ce", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c51be5e684db2cc4450656603047d8db118e401f", "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": 125849959, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1298, "license": "Apache-2.0", "license_type": "permissive", "path": "/switch语句/switch语句/main.c", "provenance": "stackv2-0123.json.gz:11446", "repo_name": "HowardLei/C", "revision_date": "2019-02-16T15:24:58", "revision_id": "717716238ff12eeb0f11041778a6cbd01d34340c", "snapshot_id": "11a771553126a549a31cb8fb6a01feda87e45f85", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/HowardLei/C/717716238ff12eeb0f11041778a6cbd01d34340c/switch语句/switch语句/main.c", "visit_date": "2021-04-12T08:02:44.708483" }
stackv2
//需求:输入一个是数,显示他的大写 //如果运用if - else结构,代码会很丑陋 //需要用switch语句 //switch语句语法 // switch (expression(表达式内容)) { // case constant(常量): // statements(需要做的事情) // break; // // default:(执行上面无法做的事情) // break; // } #include <stdio.h> int main(int argc, const char * argv[]) { int a; printf("请输入一个数,将会显示他的大写汉字\n"); scanf("%d",&a); switch (a) { case 1: printf("壹\n"); break; case 2: printf("贰\n"); break; case 3: printf("叁\n"); break; case 4: printf("肆\n"); break; case 5: printf("伍\n"); break; case 6: printf("陆\n"); break; case 7: printf("柒\n"); break; case 8: printf("捌\n"); break; case 9: printf("玖\n"); break; case 0: printf("零\n"); break; default: printf("您所输入的数值不符合规则"); break; } }
3.90625
4
2024-11-18T22:22:04.868587+00:00
2021-04-21T21:52:43
66a43a17b0d48118bfc9139ad4bab03183c89c23
{ "blob_id": "66a43a17b0d48118bfc9139ad4bab03183c89c23", "branch_name": "refs/heads/main", "committer_date": "2021-04-21T21:52:43", "content_id": "d62716044a926dac708302bc329b6a404b7c25a2", "detected_licenses": [ "MIT" ], "directory_id": "a3687607bcd67a5e18093ab7354c58615470ebbb", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 350750931, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1305, "license": "MIT", "license_type": "permissive", "path": "/rpl/Exercises/D - Árboles Binarios, ABB, AVL, Árbol B/00 - Obtener mayores/test.c", "provenance": "stackv2-0123.json.gz:11574", "repo_name": "ilitteri/7541-Algo2", "revision_date": "2021-04-21T21:52:43", "revision_id": "6835e40818b9f84fd0271b6341f6fd3aaa46df5e", "snapshot_id": "cef7f0dfbbd42920502d92af8f35455b4842dfe4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ilitteri/7541-Algo2/6835e40818b9f84fd0271b6341f6fd3aaa46df5e/rpl/Exercises/D - Árboles Binarios, ABB, AVL, Árbol B/00 - Obtener mayores/test.c", "visit_date": "2023-04-13T04:15:15.778082" }
stackv2
#include <criterion/criterion.h> // No borrar esto! #include <string.h> #include "abb.h" // Modificar con el nombre de la api que se le entrega al alumno! Test(misc, test_1_mayor) { abb_t* abb = abb_crear(strcmp, NULL); abb_guardar(abb, "A", NULL); abb_guardar(abb, "D", NULL); abb_guardar(abb, "C", NULL); abb_guardar(abb, "B", NULL); abb_guardar(abb, "E", NULL); lista_t* lista = abb_mayores(abb, "D"); cr_assert(lista_largo(lista) == 1); abb_destruir(abb); lista_destruir(lista, NULL); } Test(misc, test_clave_no_presente) { abb_t* abb = abb_crear(strcmp, NULL); abb_guardar(abb, "A", NULL); abb_guardar(abb, "D", NULL); abb_guardar(abb, "C", NULL); abb_guardar(abb, "B", NULL); abb_guardar(abb, "E", NULL); lista_t* lista = abb_mayores(abb, "BA"); cr_assert(lista_largo(lista) == 3); abb_destruir(abb); lista_destruir(lista, NULL); } Test(misc, test_sin_mayores) { abb_t* abb = abb_crear(strcmp, NULL); abb_guardar(abb, "A", NULL); abb_guardar(abb, "D", NULL); abb_guardar(abb, "C", NULL); abb_guardar(abb, "B", NULL); abb_guardar(abb, "E", NULL); lista_t* lista = abb_mayores(abb, "Z"); cr_assert(lista_largo(lista) == 0); abb_destruir(abb); lista_destruir(lista, NULL); }
2.1875
2
2024-11-18T22:22:04.932448+00:00
2015-10-25T02:02:48
5e0e4fa66774e5d09736839ab5b9bd92cb0e2c90
{ "blob_id": "5e0e4fa66774e5d09736839ab5b9bd92cb0e2c90", "branch_name": "refs/heads/master", "committer_date": "2015-10-25T02:02:48", "content_id": "86c781a9b037363a724cf39ba27e6f4f09faadf6", "detected_licenses": [ "MIT" ], "directory_id": "cd24487d467a5bcb351631d7ad85dea141df7ed8", "extension": "c", "filename": "libffi-test.c", "fork_events_count": 0, "gha_created_at": "2015-10-26T08:15:39", "gha_event_created_at": "2015-10-26T08:15:39", "gha_language": null, "gha_license_id": null, "github_id": 44954735, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 616, "license": "MIT", "license_type": "permissive", "path": "/src/libffi-test.c", "provenance": "stackv2-0123.json.gz:11705", "repo_name": "mcanthony/mxe", "revision_date": "2015-10-25T02:02:48", "revision_id": "03a941bfc4111b7f3880ff9f0828950a8c77105b", "snapshot_id": "c60e6a242159da92902bc261f190871e28cc6bbd", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/mcanthony/mxe/03a941bfc4111b7f3880ff9f0828950a8c77105b/src/libffi-test.c", "visit_date": "2021-01-22T17:48:49.107844" }
stackv2
/* * This file is part of MXE. * See index.html for further information. */ #include <stdio.h> #include <ffi.h> int main(int argc, char *argv[]) { ffi_cif cif; ffi_type *args[1]; void *values[1]; char *s; int rc; (void)argc; (void)argv; args[0] = &ffi_type_pointer; values[0] = &s; if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, &ffi_type_uint, args) == FFI_OK) { s = "Hello World!"; ffi_call(&cif, FFI_FN(puts), &rc, values); s = "Goodbye!"; ffi_call(&cif, FFI_FN(puts), &rc, values); } return 0; }
2.515625
3
2024-11-18T22:22:05.224527+00:00
2019-05-08T07:29:14
b3b2beb8fd6c281f0cd5e4b4a40886ac45ee1945
{ "blob_id": "b3b2beb8fd6c281f0cd5e4b4a40886ac45ee1945", "branch_name": "refs/heads/master", "committer_date": "2019-05-08T07:29:14", "content_id": "370d0b6fb06ebfe640a7c3c399914b0ab9e0462b", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "eeceb7584bfd1553b28ade22021da308fed2f301", "extension": "c", "filename": "load.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 23902302, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8460, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/map/load.c", "provenance": "stackv2-0123.json.gz:11961", "repo_name": "mtmiron/lich", "revision_date": "2019-05-08T07:29:14", "revision_id": "a74761b12705ca82c6b92b8db9266df91bcdb0e1", "snapshot_id": "afe029e400304ece79fdb264464a625e974922d1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mtmiron/lich/a74761b12705ca82c6b92b8db9266df91bcdb0e1/map/load.c", "visit_date": "2020-05-20T13:03:52.742155" }
stackv2
#include "map.h" /* used to calculate offset of struct members */ static mapnode_t nodemap; extern int reconstruct_node_coords; /* as above */ static struct { char *s; void *d; } stringmap[] = { { "id", &nodemap.id}, { "title", &nodemap.title }, { "area", &nodemap.area }, { "geo", &nodemap.area }, { "x", &nodemap.x }, { "y", &nodemap.y }, { NULL, NULL }, }; /* * This is where we actually calc the offset of struct data. * * It's a confusing hack-job method of supporting arbitrary * text to assign to the corresponding struct members; still, * it's surprisingly smooth while executing. * * Basic principle is that each structure member gets a * text string and a memory pointer of itself stored * (this is done directly above). When a matching text * string is found on a line in the file being loaded, * the memory offset of the struct member in question * is calculated by subtracting the base static-global * RAM addr of the `struct mapnode_st' identifier from * this file from the memory pointer tied to the text * (which was assigned directly above this comment). * * Strings should be in standard .ini file format, with * the notable exception of hash-symbols denoting comments; * e.g.: * * [1] # ID * id = 1 # no harm in assigning it again * title = Town Square Central # room title * area=Wehnimer's Landing # room area * x=3 # x-axis value * y = 4 # y-axis value * * (etc.) * */ mapnode_t * string_to_value(char *str, mapnode_t *nd) { int i = 0, valpos; char *sav, *ptr, lhs[1024]={'\0'}, buf[65536]={'\0'}, rhs[65536]={'\0'}; int idx; if (!str) return NULL; else if (! (sav = strchr(str, '=')) ) return NULL; /* strip out comments */ if ((ptr = strchr(str, '#'))) while (*ptr != '\0') *ptr++ = '\0'; ptr = sav; /* strip off leading whitespace from left-hand side */ while ((*str == ' ') || (*str == '\t')) str++; snprintf(buf, sizeof(buf), "%s", str); ptr = (buf + (ptr - str)); /* strip off leading whitespace from right-hand side */ while ((*ptr == ' ') || (*ptr == '\t') || (*ptr == '=')) ptr++, i++; /* strip off trailing whitespace from right-hand side */ snprintf(rhs, sizeof(rhs), "%s", ptr); sav = ptr; for (ptr = (rhs + strlen(rhs) - 1); *ptr == '\n' || *ptr == '\r' || *ptr == ' ' || *ptr == '\0'; ptr--) *ptr = '\0'; ptr = (sav - i); /* strip off trailing whitespace from left-hand side */ while ((*ptr == '=') || (*ptr == ' ')) *ptr-- = '\0'; snprintf(lhs, sizeof(lhs), "%s", buf); /* if this is the specially-handled "adj" string, push the rhs ID to the lhs' adj stack */ if (strcasecmp(lhs, "adj") == 0) { ptr = strchr(rhs, ','); if (!ptr) return NULL; *ptr++ = '\0'; return push_adj(nd, lookup_node_by_id(atoi(rhs)), ptr); } /* iterative string comparisons to look for a match */ for (i = 0; stringmap[i].s != NULL; i++) { /* continue from top if not a match */ if (strcasecmp(stringmap[i].s, lhs) != 0) continue; if (debugging) fprintf(stderr, "lhs: %s, buf: %s, rhs: %s. changing ID from %d to %d\n", lhs, buf, rhs, nd->id, atoi(rhs)); /* matching strings: store the memory offset of the struct member in question */ for (idx = 0; (((void*)&nodemap) + idx) < ((void*)(stringmap[i].d)); idx++) /* we need to be certain we can't run amok scanning all addressable RAM */ if ( (((void*)&nodemap) + idx) > ((void*)stringmap[i].d) ) ERROR_EXIT(); /* does this look like a numeric value? */ if (isdigit(rhs[0]) || (rhs[0] == '-')) /* if so, assign it as an int */ *((int*)(((void*)nd) + idx)) = atoi(rhs); else /* if not, assign it as a string */ *( (char**)(((void*)nd) + idx) ) = strdup(rhs); /* the `struct mapnode_st *' passed as an argument has been assigned to -- now we return it */ return nd; } /* we were unable to find a recognized match for this string's left-hand side; return NULL to indicate failure */ return NULL; } void free_mapnode_list(vector_t *list) { if (list) { vector_foreach(list, free_mapnode_st); free(list); } max_id = min_id = 0; } vector_t * new_mapnode_list(vector_t *list) { free_mapnode_list(list); list = vector_new(); if (!list) ERROR_EXIT(); return list; } static void pad_coords(void *vnode, int *xpad, int *ypad) { mapnode_t *node; const int padding = rect_len * 3; node = (mapnode_t*)vnode; node->x = node->x + padding * ++(*xpad); node->y = node->y + padding * (*xpad); } static void reconstruct_coordinates(vector_t *nodes) { int qnt = rect_len*3; /* quantum (minimum space between nodes) */ int i, j, len = vector_len(nodes); int xpad = 0, ypad = 0; mapnode_t *nd, *adj_nd; for (i = 0; i < len; i++) { nd = vector_aref(nodes, i); if (!nd || nd->touch) continue; nd->touch = 1; for (j = 0; nd->adj[j].nodeptr != NULL; j++) { adj_nd = nd->adj[j].nodeptr; if (adj_nd->touch) // continue; // adj_nd->touch = 1; switch (*nd->adj[j].movestr) { case 'n': adj_nd->y = nd->y+qnt; if (nd->adj[j].movestr[1] == 'e') adj_nd->x = nd->x+qnt; else if (nd->adj[j].movestr[1] == 'w') adj_nd->x = nd->x-qnt; break; case 'e': adj_nd->x = nd->x+qnt; break; case 's': adj_nd->y = nd->y-qnt; if (nd->adj[j].movestr[1] == 'e') adj_nd->x = nd->x+qnt; else if (nd->adj[j].movestr[1] == 'w') adj_nd->x = nd->x-qnt; break; case 'w': adj_nd->x = nd->x-qnt; break; default: adj_nd->x = nd->x+qnt; adj_nd->y = nd->y+qnt; break; } } } } vector_t * load_file(char *fname) { int i, sel_id, lineno = 0, ln = 1, tot = 0, prcnt = 0; int xpad = 0, ypad = 0; FILE *file; char buf[65536]; mapnode_t *nd, *cur_node; /* setup variables */ file = fopen(fname, "r"); if (!file) ERROR_EXIT(); if (selected_node) sel_id = selected_node->id; else sel_id = 0; if (!nodelist) nodelist = new_mapnode_list((vector_t *)nodelist); /* Get the total number of bytes (for percentage loaded display) */ while (fgets(buf, sizeof(buf), file)) ln += strlen(buf); tot = ln; ln = 1; rewind(file); /* read lines until EOF, setting values as specified */ while (fgets(buf, sizeof(buf), file)) { lineno++; if (*buf == '[') { if (!isdigit(buf[1])) { allegro_message("parse error:%s:%d:\n%s", fname, lineno, buf); if (fclose(file) == EOF) allegro_message("error closing file: %s", strerror(errno)); return (vector_t *)nodelist; } cur_node = lookup_node_by_id(atoi(&buf[1])); if (cur_node) continue; cur_node = mapnode_new(); cur_node->id = atoi(&buf[1]); vector_push((vector_t *)nodelist, (void*)cur_node); } /* parse this line and assign a value, if recognized */ string_to_value(buf, cur_node); /* Display the current completion percentage */ ln += strlen(buf); prcnt = (int)(100 / (tot / (float)ln)); textprintf_ex(screen, font, 2, 2, 255, 0, "Loading: %d%%", prcnt); } /* ensure min_id and max_id are updated/accurate */ for (i = 0; i < vector_len((vector_t *)nodelist); i++) { pad_coords(vector_aref((vector_t *)nodelist, i), &xpad, &ypad); cur_node = vector_aref((vector_t *)nodelist, i); if (cur_node->id > max_id) max_id = cur_node->id; if (cur_node->id < min_id) min_id = cur_node->id; } /* if there was previously a highlighted node, highlight any node w/ the same ID value as the old one (if the new list has such an ID) */ if (sel_id) selected_node = lookup_node_by_id(sel_id); if (fclose(file) == EOF) allegro_message("error closing file: %s", strerror(errno)); if (reconstruct_node_coords) { reconstruct_coordinates((vector_t *)nodelist); } strncpy(last_file, fname, sizeof(last_file)); return (vector_t *)nodelist; } void prompt_to_load_file() { char msg[] = "Please select the map file you wish to load"; char path[FILENAME_MAX * 6] = { "\0" }; int result; mouse_callback = NULL; result = file_select_ex(msg, path, "txt", sizeof(path), 0, 0); if (!result) { if (nodelist != NULL && vector_len((vector_t*)nodelist) > 0) return; allegro_message("You did not select a file to load: there's nothing for the program to do. Exiting."); exit(0); } if (debugging) fprintf(stderr, "%s\n", path); nodelist = load_file(path); render_image(screen); render_image(backbuffer); render_info(screen); render_info(backbuffer); strncpy(last_file, path, sizeof(last_file)); mouse_callback = mouse_cb; }
2.484375
2
2024-11-18T22:22:05.333682+00:00
2018-05-04T08:42:44
53c9b1bcbb63e7ced9e69290186553dcaa87dddc
{ "blob_id": "53c9b1bcbb63e7ced9e69290186553dcaa87dddc", "branch_name": "refs/heads/master", "committer_date": "2018-05-04T08:42:44", "content_id": "779875f77ae8203b442ada97579eb55cb40ea90c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "857ff877aebd73f4aa30bcd11a92ae47aa3de36b", "extension": "c", "filename": "currentSensor.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 123536178, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10042, "license": "Apache-2.0", "license_type": "permissive", "path": "/Code/Microcontroller Code/esp-idf/Hornbill-Industrial-Data-Logger/main/currentSensor.c", "provenance": "stackv2-0123.json.gz:12091", "repo_name": "deepmodh1996/Automated-Retail-Store-Using-Embedded-Systems", "revision_date": "2018-05-04T08:42:44", "revision_id": "9b63dbde469659c05ce43eb28038448657a73472", "snapshot_id": "dd97ea29ace5d30f6bd28837a1c7d6ba6e821134", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/deepmodh1996/Automated-Retail-Store-Using-Embedded-Systems/9b63dbde469659c05ce43eb28038448657a73472/Code/Microcontroller Code/esp-idf/Hornbill-Industrial-Data-Logger/main/currentSensor.c", "visit_date": "2021-01-25T13:11:12.817724" }
stackv2
/* Emon.cpp - Library for openenergymonitor Created by Trystan Lea, April 27 2010 GNU GPL modified to use up to 12 bits ADC resolution (ex. Arduino Due) by boredman@boredomprojects.net 26.12.2013 Low Pass filter for offset removal replaces HP filter 1/1/2015 - RW */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "driver/adc.h" #include "currentSensor.h" #include "math.h" #define millis() (xTaskGetTickCount()*portTICK_PERIOD_MS) #define SupplyVoltage (3300) //3300mv = 3.3v //Useful value variables currentSensor_values_t cs_values; //Set Voltage and current input pins unsigned int inPinV; unsigned int inPinI; //Calibration coefficients //These need to be set in order to obtain accurate results double VCAL; double ICAL; double PHASECAL; //-------------------------------------------------------------------------------------- // Variable declaration for emon_calc procedure //-------------------------------------------------------------------------------------- int sampleV; //sample_ holds the raw analog read value int sampleI; double lastFilteredV,filteredV; //Filtered_ is the raw analog value minus the DC offset double filteredI; double offsetV; //Low-pass filter output double offsetI; //Low-pass filter output double phaseShiftedV; //Holds the calibrated phase shifted voltage. double sqV,sumV,sqI,sumI,instP,sumP; //sq = squared, sum = Sum, inst = instantaneous int startV; //Instantaneous voltage at start of sample window. int lastVCross, checkVCross; //Used to measure number of times threshold is crossed. //-------------------------------------------------------------------------------------- // Sets the pins to be used for voltage and current sensors //-------------------------------------------------------------------------------------- void currentSensor_voltagePin(unsigned int _inPinV, double _VCAL, double _PHASECAL) { inPinV = _inPinV; VCAL = _VCAL; // Voltage calibration value ~230 PHASECAL = _PHASECAL; //Phase calibration offsetV = ADC_COUNTS>>1; } void currentSensor_currentPin(unsigned int _inPinI, double _ICAL) { inPinI = _inPinI; ICAL = _ICAL; offsetI = ADC_COUNTS>>1; adc1_config_width(ADC_WIDTH_12Bit); adc1_config_channel_atten(_inPinI,ADC_ATTEN_11db); } //-------------------------------------------------------------------------------------- // emon_calc procedure // Calculates realPower,cs_values.apparentPower ,cs_values.powerFactor,cs_values.Vrms,cs_values.Irms,kWh increment // From a sample window of the mains AC voltage and current. // The Sample window length is defined by the number of half wavelengths or crossings we choose to measure. //-------------------------------------------------------------------------------------- void currentSensor_calcVI(unsigned int crossings, unsigned int timeout) { unsigned int crossCount = 0; //Used to measure number of times threshold is crossed. unsigned int numberOfSamples = 0; //This is now incremented //------------------------------------------------------------------------------------------------------------------------- // 1) Waits for the waveform to be close to 'zero' (mid-scale adc) part in sin curve. //------------------------------------------------------------------------------------------------------------------------- int st=false; //an indicator to exit the while loop unsigned long start = millis(); //millis()-start makes sure it doesnt get stuck in the loop if there is an error. while(st==false) //the while loop... { startV = adc1_get_voltage(inPinV); //using the voltage waveform if ((startV < (ADC_COUNTS*0.55)) && (startV > (ADC_COUNTS*0.45))) st=true; //check its within range if ((millis()-start)>timeout) st = true; } //------------------------------------------------------------------------------------------------------------------------- // 2) Main measurement loop //------------------------------------------------------------------------------------------------------------------------- start = millis(); while ((crossCount < crossings) && ((millis()-start)<timeout)) { numberOfSamples++; //Count number of times looped. lastFilteredV = filteredV; //Used for delay/phase compensation //----------------------------------------------------------------------------- // A) Read in raw voltage and current samples //----------------------------------------------------------------------------- sampleV = adc1_get_voltage(inPinV); //Read in raw voltage signal sampleI = adc1_get_voltage(inPinI); //Read in raw current signal //----------------------------------------------------------------------------- // B) Apply digital low pass filters to extract the 2.5 V or 1.65 V dc offset, // then subtract this - signal is now centred on 0 counts. //----------------------------------------------------------------------------- offsetV = offsetV + ((sampleV-offsetV)/4096); filteredV = sampleV - offsetV; offsetI = offsetI + ((sampleI-offsetI)/4096); filteredI = sampleI - offsetI; //----------------------------------------------------------------------------- // C) Root-mean-square method voltage //----------------------------------------------------------------------------- sqV= filteredV * filteredV; //1) square voltage values sumV += sqV; //2) sum //----------------------------------------------------------------------------- // D) Root-mean-square method current //----------------------------------------------------------------------------- sqI = filteredI * filteredI; //1) square current values sumI += sqI; //2) sum //----------------------------------------------------------------------------- // E) Phase calibration //----------------------------------------------------------------------------- phaseShiftedV = lastFilteredV + PHASECAL * (filteredV - lastFilteredV); //----------------------------------------------------------------------------- // F) Instantaneous power calc //----------------------------------------------------------------------------- instP = phaseShiftedV * filteredI; //Instantaneous Power sumP +=instP; //Sum //----------------------------------------------------------------------------- // G) Find the number of times the voltage has crossed the initial voltage // - every 2 crosses we will have sampled 1 wavelength // - so this method allows us to sample an integer number of half wavelengths which increases accuracy //----------------------------------------------------------------------------- lastVCross = checkVCross; if (sampleV > startV) checkVCross = true; else checkVCross = false; if (numberOfSamples==1) lastVCross = checkVCross; if (lastVCross != checkVCross) crossCount++; } //------------------------------------------------------------------------------------------------------------------------- // 3) Post loop calculations //------------------------------------------------------------------------------------------------------------------------- //Calculation of the root of the mean of the voltage and current squared (rms) //Calibration coefficients applied. double V_RATIO = VCAL *((SupplyVoltage/1000.0) / (ADC_COUNTS)); cs_values.Vrms = V_RATIO * sqrt(sumV / numberOfSamples); double I_RATIO = ICAL *((SupplyVoltage/1000.0) / (ADC_COUNTS)); cs_values.Irms = I_RATIO * sqrt(sumI / numberOfSamples); //Calculation power values cs_values.realPower = V_RATIO * I_RATIO * sumP / numberOfSamples; cs_values.apparentPower = cs_values.Vrms * cs_values.Irms; cs_values.powerFactor=cs_values.realPower / cs_values.apparentPower ; //Reset accumulators sumV = 0; sumI = 0; sumP = 0; //-------------------------------------------------------------------------------------- } //-------------------------------------------------------------------------------------- double currentSensor_calcIrms(unsigned int Number_of_Samples) { for (unsigned int n = 0; n < Number_of_Samples; n++) { sampleI = adc1_get_voltage(inPinI); // Digital low pass filter extracts the 2.5 V or 1.65 V dc offset, // then subtract this - signal is now centered on 0 counts. offsetI = (offsetI + (sampleI-offsetI)/4096); filteredI = sampleI - offsetI; // Root-mean-square method current // 1) square current values sqI = filteredI * filteredI; // 2) sum sumI += sqI; } double I_RATIO = ICAL *((SupplyVoltage/1000.0) / (ADC_COUNTS)); cs_values.Irms = I_RATIO * sqrt(sumI / Number_of_Samples); //Reset accumulators sumI = 0; //-------------------------------------------------------------------------------------- return cs_values.Irms; } void currentSensor_printAll() { printf("\n\rRealPower:%f cs_values.apparentPower :%f cs_values.Vrms:%f cs_values.Irms:%f PowerFactor:%f",cs_values.realPower,cs_values.apparentPower,cs_values.Vrms,cs_values.Irms,cs_values.powerFactor); } void currentSensor_readAll(currentSensor_values_t *sensor_values_ptr) { *sensor_values_ptr = cs_values; } //thanks to http://hacking.majenko.co.uk/making-accurate-adc-readings-on-arduino //and Jérôme who alerted us to http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/
2.53125
3
2024-11-18T22:22:05.412753+00:00
2020-06-01T05:24:34
5553b1c42d985d25e4909208fed396f3abf65183
{ "blob_id": "5553b1c42d985d25e4909208fed396f3abf65183", "branch_name": "refs/heads/master", "committer_date": "2020-06-01T05:24:34", "content_id": "a72f29d250454b30b7f65850d91e2bbd68eadc8a", "detected_licenses": [ "MIT" ], "directory_id": "192bd70c616232c7054173069d5354e4d6d52c62", "extension": "c", "filename": "keygen.c", "fork_events_count": 1, "gha_created_at": "2017-04-15T08:24:23", "gha_event_created_at": "2020-06-01T05:24:36", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 88334238, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 533, "license": "MIT", "license_type": "permissive", "path": "/util/backdoor/keygen.c", "provenance": "stackv2-0123.json.gz:12221", "repo_name": "zh-explorer/patchkit", "revision_date": "2020-06-01T05:24:34", "revision_id": "832575645e340503623d558ad97df92594bfd93a", "snapshot_id": "a37254aa674e6057142d7aecf8a172ae9bd84bfc", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/zh-explorer/patchkit/832575645e340503623d558ad97df92594bfd93a/util/backdoor/keygen.c", "visit_date": "2021-01-19T17:36:19.112581" }
stackv2
#include <stdio.h> #include <stdint.h> #include "tweetnacl.h" void _cdump(uint8_t *msg, uint64_t len) { printf("{"); for (int i = 0; i < len; i++) { printf("%d", msg[i]); if (i < len - 1) printf(", "); } printf("};\n"); } #define cdump(c) _cdump(c, sizeof(c)) int main() { uint8_t pk[crypto_sign_PUBLICKEYBYTES]; uint8_t sk[crypto_sign_SECRETKEYBYTES]; crypto_sign_keypair(pk, sk); printf("uint8_t pubkey[] = "); cdump(pk); printf("uint8_t privkey[] = "); cdump(sk); }
2.359375
2
2024-11-18T22:22:05.482652+00:00
2021-06-04T19:26:17
9ff9b81084030c632fae9d7466f9b69b135a20ee
{ "blob_id": "9ff9b81084030c632fae9d7466f9b69b135a20ee", "branch_name": "refs/heads/master", "committer_date": "2021-06-04T19:26:17", "content_id": "cfdd4350ebff4d3b7ad57a6713566047fcb387d5", "detected_licenses": [ "MIT" ], "directory_id": "2edc954687da8761f0ad6b8ee76343c4c46c42cc", "extension": "c", "filename": "cactusMetaSequenceTest.c", "fork_events_count": 0, "gha_created_at": "2020-03-27T00:34:39", "gha_event_created_at": "2020-09-08T18:00:01", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 250404640, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5741, "license": "MIT", "license_type": "permissive", "path": "/api/tests/cactusMetaSequenceTest.c", "provenance": "stackv2-0123.json.gz:12350", "repo_name": "Robin-Rounthwaite/cactus", "revision_date": "2021-06-04T19:26:17", "revision_id": "3c612779b83b75cb42e08dc143b9cb81c257cf80", "snapshot_id": "c6cc40041c524e6150f8af0266c88c3a05103c01", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Robin-Rounthwaite/cactus/3c612779b83b75cb42e08dc143b9cb81c257cf80/api/tests/cactusMetaSequenceTest.c", "visit_date": "2023-05-09T12:38:25.495816" }
stackv2
/* * Copyright (C) 2009-2011 by Benedict Paten (benedictpaten@gmail.com) * * Released under the MIT license, see LICENSE.txt */ #include "cactusGlobalsPrivate.h" static CactusDisk *cactusDisk; Name eventName = 10; static MetaSequence *metaSequence; static const char *sequenceString = "ACTGGCACTG"; static const char *headerString = ">one"; static bool nestedTest = 0; static void cactusMetaSequenceTestTeardown(CuTest* testCase) { if(!nestedTest && cactusDisk != NULL) { testCommon_deleteTemporaryCactusDisk(testCase->name, cactusDisk); cactusDisk = NULL; metaSequence = NULL; } } static void cactusMetaSequenceTestSetup(CuTest* testCase) { if(!nestedTest) { cactusMetaSequenceTestTeardown(testCase); cactusDisk = testCommon_getTemporaryCactusDisk(testCase->name); metaSequence = metaSequence_construct(1, 10, sequenceString, headerString, eventName, cactusDisk); } } void testMetaSequence_getName(CuTest* testCase) { cactusMetaSequenceTestSetup(testCase); CuAssertTrue(testCase, metaSequence_getName(metaSequence) != NULL_NAME); CuAssertTrue(testCase, cactusDisk_getMetaSequence(cactusDisk, metaSequence_getName(metaSequence)) == metaSequence); cactusMetaSequenceTestTeardown(testCase); } void testMetaSequence_getStart(CuTest* testCase) { cactusMetaSequenceTestSetup(testCase); CuAssertIntEquals(testCase, 1, metaSequence_getStart(metaSequence)); cactusMetaSequenceTestTeardown(testCase); } void testMetaSequence_getLength(CuTest* testCase) { cactusMetaSequenceTestSetup(testCase); CuAssertIntEquals(testCase, 10, metaSequence_getLength(metaSequence)); cactusMetaSequenceTestTeardown(testCase); } void testMetaSequence_getEventName(CuTest* testCase) { cactusMetaSequenceTestSetup(testCase); CuAssertTrue(testCase, metaSequence_getEventName(metaSequence) == eventName); cactusMetaSequenceTestTeardown(testCase); } void testMetaSequence_getString(CuTest* testCase) { for(int64_t i=0; i<10; i++) { cactusMetaSequenceTestSetup(testCase); //String is ACTGGCACTG CuAssertStrEquals(testCase, sequenceString, metaSequence_getString(metaSequence, 1, 10, 1)); //complete sequence CuAssertStrEquals(testCase, "TGGC", metaSequence_getString(metaSequence, 3, 4, 1)); //sub range CuAssertStrEquals(testCase, "", metaSequence_getString(metaSequence, 3, 0, 1)); //zero length sub range CuAssertStrEquals(testCase, "CAGTGCCAGT", metaSequence_getString(metaSequence, 1, 10, 0)); //reverse complement CuAssertStrEquals(testCase, "GCCA", metaSequence_getString(metaSequence, 3, 4, 0)); //sub range, reverse complement CuAssertStrEquals(testCase, "", metaSequence_getString(metaSequence, 3, 0, 0)); //zero length sub range on reverse strand cactusMetaSequenceTestTeardown(testCase); } } void testMetaSequence_getHeader(CuTest* testCase) { cactusMetaSequenceTestSetup(testCase); CuAssertStrEquals(testCase, headerString, metaSequence_getHeader(metaSequence)); cactusMetaSequenceTestTeardown(testCase); } void testMetaSequence_isTrivialSequence(CuTest* testCase) { cactusMetaSequenceTestSetup(testCase); CuAssertTrue(testCase, !metaSequence_isTrivialSequence(metaSequence)); MetaSequence *metaSequence2 = metaSequence_construct3(1, 10, sequenceString, headerString, eventName, 1, cactusDisk); CuAssertTrue(testCase, metaSequence_isTrivialSequence(metaSequence2)); metaSequence_destruct(metaSequence2); cactusMetaSequenceTestTeardown(testCase); } void testMetaSequence_serialisation(CuTest* testCase) { cactusMetaSequenceTestSetup(testCase); int64_t i; Name name = metaSequence_getName(metaSequence); CuAssertTrue(testCase, cactusDisk_getMetaSequence(cactusDisk, name) == metaSequence); void *vA = binaryRepresentation_makeBinaryRepresentation(metaSequence, (void (*)(void *, void (*)(const void *, size_t, size_t)))metaSequence_writeBinaryRepresentation, &i); CuAssertTrue(testCase, i > 0); metaSequence_destruct(metaSequence); CuAssertTrue(testCase, cactusDisk_getMetaSequence(cactusDisk, name) == NULL); void *vA2 = vA; metaSequence = metaSequence_loadFromBinaryRepresentation(&vA2, cactusDisk); CuAssertTrue(testCase, name == metaSequence_getName(metaSequence)); CuAssertStrEquals(testCase, headerString, metaSequence_getHeader(metaSequence)); CuAssertTrue(testCase, cactusDisk_getMetaSequence(cactusDisk, name) == metaSequence); cactusDisk_write(cactusDisk); metaSequence_destruct(metaSequence); CuAssertTrue(testCase, cactusDisk_getMetaSequence(cactusDisk, name) != NULL); metaSequence = cactusDisk_getMetaSequence(cactusDisk, name); nestedTest = 1; testMetaSequence_getName(testCase); testMetaSequence_getStart(testCase); testMetaSequence_getLength(testCase); testMetaSequence_getEventName(testCase); testMetaSequence_getString(testCase); testMetaSequence_getHeader(testCase); testMetaSequence_isTrivialSequence(testCase); nestedTest = 0; cactusMetaSequenceTestTeardown(testCase); } CuSuite* cactusMetaSequenceTestSuite(void) { CuSuite* suite = CuSuiteNew(); SUITE_ADD_TEST(suite, testMetaSequence_getName); SUITE_ADD_TEST(suite, testMetaSequence_getStart); SUITE_ADD_TEST(suite, testMetaSequence_getLength); SUITE_ADD_TEST(suite, testMetaSequence_getEventName); SUITE_ADD_TEST(suite, testMetaSequence_getString); SUITE_ADD_TEST(suite, testMetaSequence_isTrivialSequence); SUITE_ADD_TEST(suite, testMetaSequence_serialisation); SUITE_ADD_TEST(suite, testMetaSequence_getHeader); return suite; }
2.25
2
2024-11-18T22:22:05.627191+00:00
2016-10-20T08:36:10
096a2aecb68d3af343e1c9efa4d521a876fdf1ec
{ "blob_id": "096a2aecb68d3af343e1c9efa4d521a876fdf1ec", "branch_name": "refs/heads/master", "committer_date": "2016-10-20T08:36:10", "content_id": "50f1a6b8c719c8dbf0f8b292a037258387bc866c", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "03bec2e87b6d04cd7b6f8ea7c30ce30e93111e6e", "extension": "c", "filename": "camio_ostream_log.c", "fork_events_count": 2, "gha_created_at": "2015-02-28T17:35:34", "gha_event_created_at": "2017-08-08T11:37:41", "gha_language": "C", "gha_license_id": null, "github_id": 31470253, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7006, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/ostreams/camio_ostream_log.c", "provenance": "stackv2-0123.json.gz:12481", "repo_name": "mgrosvenor/camio1.0", "revision_date": "2016-10-20T08:36:10", "revision_id": "18d8e9d1531e6ff3f9006a62f8f35fbcac498274", "snapshot_id": "990e278ae8da609188821386c5a519d4c71fb16c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mgrosvenor/camio1.0/18d8e9d1531e6ff3f9006a62f8f35fbcac498274/ostreams/camio_ostream_log.c", "visit_date": "2021-01-18T23:08:26.238765" }
stackv2
/* * Copyright (C) Matthew P. Grosvenor, 2012, All Rights Reserved * * Fe2+ log (newline separated) output stream * */ #include <errno.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include "../camio_util.h" #include "../camio_errors.h" #include "camio_ostream_log.h" #define CAMIO_OSTREAM_LOG_BUFF_INIT (4 * 1024 * 1024) //4MB int camio_ostream_log_open(camio_ostream_t* this, const camio_descr_t* descr ){ camio_ostream_log_t* priv = this->priv; if(unlikely((size_t)descr->opt_head)){ if(!strcmp("escape",descr->opt_head->name)){ if(descr->opt_head->value[0] == '1'){ priv->escape = 1; } else if(descr->opt_head->value[0] == '0'){ priv->escape = 0; } else{ eprintf_exit(CAMIO_ERR_UNKNOWN_OPT, "Unknown option value supplied \"s\". Valid values are \"1\" or \"0\"\n", descr->opt_head->value); } } else{ eprintf_exit(CAMIO_ERR_UNKNOWN_OPT, "Unknown option supplied \"s\". Valid options for this stream are: \"escape\"\n", descr->opt_head->name); } } priv->buffer = malloc(CAMIO_OSTREAM_LOG_BUFF_INIT); if(!priv->buffer){ eprintf_exit(CAMIO_ERR_NULL_PTR, "Could not allocate output buffer\n"); } priv->buffer_size = CAMIO_OSTREAM_LOG_BUFF_INIT; //If we have a file descriptor from the outside world, then use it! if(priv->params){ if(priv->params->fd > -1){ this->fd = priv->params->fd; priv->is_closed = 0; return CAMIO_ERR_NONE; } } //Grab a file descriptor and rock on if(!descr->query){ eprintf_exit(CAMIO_ERR_NULL_PTR, "No filename supplied\n"); } this->fd = open(descr->query, O_WRONLY | O_CREAT | O_TRUNC, (mode_t)(0666)); if(this->fd == -1){ eprintf_exit(CAMIO_ERR_FILE_OPEN, "Could not open file \"%s\"\n", descr->query); } priv->is_closed = 0; return CAMIO_ERR_NONE; } void camio_ostream_log_close(camio_ostream_t* this){ camio_ostream_log_t* priv = this->priv; close(this->fd); priv->is_closed = 1; } //Returns a pointer to a space of size len, ready for data uint8_t* camio_ostream_log_start_write(camio_ostream_t* this, size_t len ){ camio_ostream_log_t* priv = this->priv; len += 1; //Add space for a newline //Grow the buffer if it's not big enough if(len > priv->buffer_size){ priv->buffer = realloc(priv->buffer, len); if(!priv->buffer){ eprintf_exit(CAMIO_ERR_NULL_PTR, "Could not grow line buffer\n"); } priv->buffer_size = len; } return priv->buffer; } //Returns non-zero if a call to start_write will be non-blocking int camio_ostream_log_ready(camio_ostream_t* this){ //Not implemented eprintf_exit(CAMIO_ERR_NOT_IMPL, "\n"); return 0; } //Commit the data that's now in the buffer that was previously allocated //Len must be equal to or less than len called with start_write uint8_t* camio_ostream_log_end_write(camio_ostream_t* this, size_t len){ camio_ostream_log_t* priv = this->priv; int result = 0; if(!priv->escape){ //The simple (fast) case if(priv->assigned_buffer){ result = write(this->fd,priv->assigned_buffer,len); result += write(this->fd,"\n",1); //Hmmm don't like this... priv->assigned_buffer = NULL; priv->assigned_buffer_sz = 0; return NULL; } priv->buffer[len] = '\n'; result = write(this->fd,priv->buffer,len+1); return NULL; } const uint8_t* buffer = priv->assigned_buffer ? priv->assigned_buffer : priv->buffer; size_t i = 0; size_t begin = 0; char escaped_hex[5]; for(; i < len; i++){ if(buffer[i] < 0x20 || buffer[i] > 0x7E ){ if( (i > 0) && (i - begin > 0) ){ result += write(this->fd,buffer + begin, i - begin); } snprintf(escaped_hex,5,"\\x%02X",(uint8_t)buffer[i]); result += write(this->fd,escaped_hex,4); begin = i+1; } } result += write(this->fd,"\n",1); if(priv->assigned_buffer){ priv->assigned_buffer = NULL; priv->assigned_buffer_sz = 0; return NULL; } return NULL; } void camio_ostream_log_delete(camio_ostream_t* ostream){ ostream->close(ostream); camio_ostream_log_t* priv = ostream->priv; free(priv); } //Is this stream capable of taking over another stream buffer int camio_ostream_log_can_assign_write(camio_ostream_t* this){ return 1; } //Assign the write buffer to the stream int camio_ostream_log_assign_write(camio_ostream_t* this, uint8_t* buffer, size_t len){ camio_ostream_log_t* priv = this->priv; if(!buffer){ eprintf_exit(CAMIO_ERR_NULL_PTR,"Assigned buffer is null."); } priv->assigned_buffer = buffer; priv->assigned_buffer_sz = len; return 0; } /* **************************************************** * Construction heavy lifting */ camio_ostream_t* camio_ostream_log_construct(camio_ostream_log_t* priv, const camio_descr_t* descr, camio_ostream_log_params_t* params){ if(!priv){ eprintf_exit(CAMIO_ERR_NULL_PTR,"log stream supplied is null\n"); } //Initialize the local variables priv->is_closed = 1; priv->escape = 0; //Off for the moment until the istream works //Escape by default priv->buffer_size = 0; priv->buffer = NULL; priv->assigned_buffer = NULL; priv->assigned_buffer_sz = 0; priv->params = params; //Populate the function members priv->ostream.priv = priv; //Lets us access private members from public functions priv->ostream.open = camio_ostream_log_open; priv->ostream.close = camio_ostream_log_close; priv->ostream.start_write = camio_ostream_log_start_write; priv->ostream.end_write = camio_ostream_log_end_write; priv->ostream.ready = camio_ostream_log_ready; priv->ostream.delete = camio_ostream_log_delete; priv->ostream.can_assign_write = camio_ostream_log_can_assign_write; priv->ostream.assign_write = camio_ostream_log_assign_write; priv->ostream.fd = -1; //Call open, because its the obvious thing to do now... priv->ostream.open(&priv->ostream, descr); //Return the generic ostream interface for the outside world return &priv->ostream; } camio_ostream_t* camio_ostream_log_new( const camio_descr_t* descr, camio_ostream_log_params_t* params){ camio_ostream_log_t* priv = malloc(sizeof(camio_ostream_log_t)); if(!priv){ eprintf_exit(CAMIO_ERR_NULL_PTR,"No memory available for ostream log creation\n"); } return camio_ostream_log_construct(priv, descr, params); }
2.671875
3
2024-11-18T22:22:05.923292+00:00
2017-08-05T03:03:11
f94f8b84e345660443dcb72f41d8f5e973eb606b
{ "blob_id": "f94f8b84e345660443dcb72f41d8f5e973eb606b", "branch_name": "refs/heads/master", "committer_date": "2017-08-05T03:03:11", "content_id": "4c63ea5e31a12ea0c67c9e51d28b83ee6744d036", "detected_licenses": [ "MIT" ], "directory_id": "2349f4e5ad4adf2566f487e30caae046cacb88ba", "extension": "c", "filename": "led.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 89644991, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2260, "license": "MIT", "license_type": "permissive", "path": "/test/xbee/src/led.c", "provenance": "stackv2-0123.json.gz:12738", "repo_name": "dannyp11/han-gps", "revision_date": "2017-08-05T03:03:11", "revision_id": "7bd34edcd4c69682223a2b8ca464e2bb6d99592d", "snapshot_id": "53a208ae5220a8978c16dfe35b1ac4c210d3aa8a", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/dannyp11/han-gps/7bd34edcd4c69682223a2b8ca464e2bb6d99592d/test/xbee/src/led.c", "visit_date": "2021-01-20T04:08:59.585075" }
stackv2
#include "led.h" /* initializes all LEDs to OFF */ extern void LEDinit(void); /* Sends '__led_state' pattern to LEDs */ extern void output_led_state(unsigned int __led_state); /* Turns on all the LEDs */ extern void LEDall(void); /* Turns off all the LEDs */ extern void LEDclear(void); /* Turns on the NORTH LED. It stays on until another LED is turned on or they are all cleared. */ extern void LEDnorth(void); /* Turns on the EAST LED. It stays on until another LED is turned on or they are all cleared. */ extern void LEDeast(void); /* Turns on the SOUTH LED. It stays on until another LED is turned on or they are all cleared. */ extern void LEDsouth(void); /* Turns on the WEST LED. It stays on until another LED is turned on or they are all cleared. */ extern void LEDwest(void); /* Turns on the NORTHEAST LED. It stays on until another LED is turned on or they are all cleared. */ extern void LEDnortheast(void); /* Turns on the SOUTHEAST LED. It stays on until another LED is turned on or they are all cleared. */ extern void LEDsoutheast(void); /* Turns on the NORTHWEST LED. It stays on until another LED is turned on or they are all cleared. */ extern void LEDnorthwest(void); /* Turns on the SOUTHWEST LED. It stays on until another LED is turned on or they are all cleared. */ extern void LEDsouthwest(void); void led_demo(void) { while (1) { LEDall(); chThdSleepMilliseconds(300); LEDclear(); chThdSleepMilliseconds(300); LEDall(); chThdSleepMilliseconds(300); LEDclear(); chThdSleepMilliseconds(300); LEDall(); chThdSleepMilliseconds(300); LEDclear(); chThdSleepMilliseconds(300); LEDnorth(); chThdSleepMilliseconds(300); LEDnortheast(); chThdSleepMilliseconds(300); LEDeast(); chThdSleepMilliseconds(300); LEDsoutheast(); chThdSleepMilliseconds(300); LEDsouth(); chThdSleepMilliseconds(300); LEDsouthwest(); chThdSleepMilliseconds(300); LEDwest(); chThdSleepMilliseconds(300); LEDnorthwest(); chThdSleepMilliseconds(300); } } THD_WORKING_AREA(waTdLED, LED_WA_SIZE); THD_FUNCTION(tdLED, arg) { (void)arg; LEDinit(); //Setup IO pins and defaults while (true) { led_demo(); chThdSleepSeconds(1); } }
2.515625
3
2024-11-18T22:22:06.007741+00:00
2018-07-19T23:34:07
e507f7dfb8eea83931b166b5077e167f7736a554
{ "blob_id": "e507f7dfb8eea83931b166b5077e167f7736a554", "branch_name": "refs/heads/master", "committer_date": "2018-07-19T23:34:07", "content_id": "cf2971a5da9860c0660618fe8be8c5ea3d931bec", "detected_licenses": [ "MIT" ], "directory_id": "14a0b78ce199a94f01b8defca7b2af77dc8a5987", "extension": "c", "filename": "programming.c", "fork_events_count": 0, "gha_created_at": "2019-02-11T06:47:54", "gha_event_created_at": "2019-02-11T06:47:56", "gha_language": "C", "gha_license_id": "MIT", "github_id": 170081220, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1958, "license": "MIT", "license_type": "permissive", "path": "/programming.c", "provenance": "stackv2-0123.json.gz:12867", "repo_name": "pvinis/PostBot", "revision_date": "2018-07-19T23:34:07", "revision_id": "2126a7d2c2ce7fb2809065af9311a38c78e6e8ba", "snapshot_id": "d19faf64d051cbc804563c00d7cfefcc3d707feb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pvinis/PostBot/2126a7d2c2ce7fb2809065af9311a38c78e6e8ba/programming.c", "visit_date": "2020-04-22T03:16:53.803332" }
stackv2
void draw_instructions() { //16 is first arrow tile in 'background.tiles' //programming[19] = 16; //20x18 unsigned char first_tile_location = 12; int counter = 0; for (; counter < 20; counter++) { int col = counter % 5; int row = counter / 5; int base_tile = first_tile_location + (program[counter] * 4); int topleft = ((col * 3) + 63) + (row * 60); int topright = topleft + 1; int bottomleft = topleft + 20; int bottomright = bottomleft + 1; if (counter >= 10) { topleft += 20; topright += 20; bottomleft += 20; bottomright += 20; } if (counter >= 15) { topleft += 20; topright += 20; bottomleft += 20; bottomright += 20; } if (program[counter] == 0) { current_level[topleft] = 0; current_level[topright] = 0; current_level[bottomleft] = 0; current_level[bottomright] = 0; } else { current_level[topleft] = base_tile; current_level[topright] = base_tile + 1; current_level[bottomleft] = base_tile + 2; current_level[bottomright] = base_tile + 3; } } //update background set_bkg_tiles(0, 0, 20, 18, current_level); } void update_programming() { if(cursor_update()) draw_instructions(); } void init_programming() { DISPLAY_OFF; screen = 3; reset_sprites(); display_programming(); draw_instructions(); cursor_init(); DISPLAY_ON; } void set_command(int row, int col, char dir) { int program_location = (row * 5) + col; //cycling if (program[program_location] == 6 && dir > 0) program[program_location] = 0; else if (program[program_location] == 0 && dir < 0) program[program_location] = 6; else program[program_location] = program[program_location] + dir; } /* 0 empty 1 forward 2 turnleft 3 turnright 4 transmit 5 function 1 6 function 2 */ /* 0-09 main program 10-14 function 1 15-19 function 2 */
2.546875
3
2024-11-18T22:22:06.068125+00:00
2019-12-19T16:24:43
0ef1e15dd7732c285573c7fdb26a4fa3b3bc8bc1
{ "blob_id": "0ef1e15dd7732c285573c7fdb26a4fa3b3bc8bc1", "branch_name": "refs/heads/master", "committer_date": "2019-12-19T16:24:43", "content_id": "ceacc0dbafb85ea39fe2ac8e7457e8c91a12247b", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "feb0092c70367912ffb3bd01b825724cebd1a6c4", "extension": "c", "filename": "flashdrv.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": 3754, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/storage/imxrt-flash/flashdrv.c", "provenance": "stackv2-0123.json.gz:12995", "repo_name": "moneytech/phoenix-rtos-devices", "revision_date": "2019-12-19T16:24:43", "revision_id": "64b5aa15a357c9fbe2208a9ce6b68787527ac3ee", "snapshot_id": "d33e8568d91a8865c9c4d4f5056169d643a878d3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/moneytech/phoenix-rtos-devices/64b5aa15a357c9fbe2208a9ce6b68787527ac3ee/storage/imxrt-flash/flashdrv.c", "visit_date": "2020-12-01T22:34:17.608565" }
stackv2
/* * Phoenix-RTOS * * i.MX RT Flash driver * * Copyright 2019 Phoenix Systems * Author: Hubert Buczynski * * This file is part of Phoenix-RTOS. * * %LICENSE% */ #include <errno.h> #include <stdlib.h> #include <string.h> #include <phoenix/arch/imxrt.h> #include "flashdrv.h" #include "rom_api.h" #include "flash_config.h" #define QSPI_FREQ_133MHZ 0xc0000008 static int flash_defineFlexSPI(flash_context_t *context) { switch (context->address) { case FLEXSPI_DATA_ADDRESS : context->instance = 0; context->option.option0 = QSPI_FREQ_133MHZ; break; case FLEXSPI2_DATA_ADDRESS : context->instance = 1; context->option.option0 = QSPI_FREQ_133MHZ; break; default: return -ENODEV; } return EOK; } static int flash_isValidAddress(flash_context_t *context, uint32_t addr, size_t size) { if ((addr + size) <= context->properties.size) return 0; return 1; } size_t flash_readData(flash_context_t *context, uint32_t offset, char *buff, size_t size) { if (flash_isValidAddress(context, offset, size)) return 0; if (flexspi_norFlashRead(context->instance, &context->config, (uint32_t *)buff, offset, size) < 0) return 0; return size; } size_t flash_writeDataPage(flash_context_t *context, uint32_t offset, const char *buff, size_t size) { uint32_t pageAddr; uint16_t sector_id; size_t savedBytes = 0; if (size % context->properties.page_size) return 0; if (flash_isValidAddress(context, offset, size)) return 0; while (savedBytes < size) { pageAddr = offset + savedBytes; sector_id = pageAddr / context->properties.sector_size; /* If sector_id has changed, data from previous sector have to be saved and new sector is read. */ if (sector_id != context->sectorID) { flash_sync(context); if (flash_readData(context, context->properties.sector_size * sector_id, context->buff, context->properties.sector_size) <= 0) return savedBytes; if (flexspi_norFlashErase(context->instance, &context->config, context->properties.sector_size * sector_id, context->properties.sector_size) != 0) return savedBytes; context->sectorID = sector_id; context->counter = offset - context->properties.sector_size * context->sectorID; } memcpy(context->buff + context->counter, buff + savedBytes, context->properties.page_size); savedBytes += context->properties.page_size; context->counter += context->properties.page_size; /* Save filled buffer */ if (context->counter >= context->properties.sector_size) flash_sync(context); } return size; } void flash_sync(flash_context_t *context) { int i; uint32_t dstAddr; const uint32_t *src; const uint32_t pagesNumber = context->properties.sector_size / context->properties.page_size; if (context->counter == 0) return; for (i = 0; i < pagesNumber; ++i) { dstAddr = context->sectorID * context->properties.sector_size + i * context->properties.page_size; src = (const uint32_t *)(context->buff + i * context->properties.page_size); flexspi_norFlashPageProgram(context->instance, &context->config, dstAddr, src); } context->counter = 0; context->sectorID = -1; } int flash_init(flash_context_t *context) { int res = EOK; if ((res = flash_defineFlexSPI(context)) < 0) return res; if (flexspi_norGetConfig(context->instance, &context->config, &context->option) != 0) return -ENXIO; if (flexspi_norFlashInit(context->instance, &context->config) != 0) return -ENXIO; if (flexspi_getVendorID(context->instance, &context->flashID) != 0) return -ENXIO; if (flash_getConfig(context) != 0) return -ENXIO; context->sectorID = -1; context->counter = 0; return res; } void flash_contextDestroy(flash_context_t *context) { flash_sync(context); free(context->buff); }
2.421875
2
2024-11-18T22:22:06.255299+00:00
2018-09-28T21:05:10
5abb2e23b7dd956684e5e343f0c185c783f6a102
{ "blob_id": "5abb2e23b7dd956684e5e343f0c185c783f6a102", "branch_name": "refs/heads/master", "committer_date": "2018-09-28T21:05:10", "content_id": "608fd079d90b4fb050e04d0a002d08cc18ee4589", "detected_licenses": [ "Apache-2.0" ], "directory_id": "68df0eb78f3a849b0a7e3bf807d1f5606ea0fb2b", "extension": "h", "filename": "dsm_msg_io.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": 1254, "license": "Apache-2.0", "license_type": "permissive", "path": "/include/dsm_msg_io.h", "provenance": "stackv2-0123.json.gz:13253", "repo_name": "potatogim/libdsm", "revision_date": "2018-09-28T21:05:10", "revision_id": "6c6f19c8924cf5743554cc6436ba6cb4f40a5d81", "snapshot_id": "63e09f768650d989879d3cb12a8cda1c6668b32c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/potatogim/libdsm/6c6f19c8924cf5743554cc6436ba6cb4f40a5d81/include/dsm_msg_io.h", "visit_date": "2020-09-12T17:36:47.954415" }
stackv2
#if !defined (DSM_MSG_IO_H) #define DSM_MSG_IO_H #include "dsm_msg.h" /* ******************************************************************************* * Function Declarations * ******************************************************************************* */ /* * [NON-REENTRANT] Receives message from socket and unpacks it. The message * pointer is then configured. This function is non-reentrant, meaning that it * cannot be called recursively or in parallel without all but the latest * invoker losing information. This specifically affects messages of type * DSM_MSG_WRT_DATA, where the data is stored in a static buffer within * the function. */ void dsm_recv_msg (int fd, dsm_msg *m); /* * Packs message and writes it to the given socket. All messages have a * standard size of DSM_MSG_SIZE bytes, with a potential extension in the * case of DSM_MSG_WRT_DATA. In DSM_MSG_WRT_DATA, the buffer is appended to * the end of the message (at an offset of DSM_MSG_SIZE bytes). Data size is * capped at DSM_MAX_DATA_SIZE. If a larger size is specified, then it is * automatically chunked and sent in a sequence of messages. */ void dsm_send_msg (int fd, dsm_msg *mp); #endif
2.125
2
2024-11-18T22:22:06.491440+00:00
2018-06-18T23:06:51
89306820ce49560419a9858798a3d26acffbf3f8
{ "blob_id": "89306820ce49560419a9858798a3d26acffbf3f8", "branch_name": "refs/heads/master", "committer_date": "2018-06-18T23:06:51", "content_id": "6c4688aad26fa6d3ecf50ed041e529000944fbb5", "detected_licenses": [ "MIT" ], "directory_id": "865baaab01f10c2b69e744916fbda8df8623731b", "extension": "c", "filename": "namco.c", "fork_events_count": 0, "gha_created_at": "2018-02-01T23:16:57", "gha_event_created_at": "2018-02-01T23:16:57", "gha_language": null, "gha_license_id": null, "github_id": 119905423, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9286, "license": "MIT", "license_type": "permissive", "path": "/mapper/namco.c", "provenance": "stackv2-0123.json.gz:13512", "repo_name": "jackoalan/fixNES", "revision_date": "2018-06-18T23:06:51", "revision_id": "7893e89abed4d16ba6b194613bc972cd46ceb235", "snapshot_id": "e0dcb45c0c22b8a797284d69446aed2e6c1d6ff5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jackoalan/fixNES/7893e89abed4d16ba6b194613bc972cd46ceb235/mapper/namco.c", "visit_date": "2021-05-08T11:37:20.473347" }
stackv2
/* * Copyright (C) 2017 FIX94 * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include <stdio.h> #include <inttypes.h> #include <stdbool.h> #include <string.h> #include "../apu.h" #include "../cpu.h" #include "../ppu.h" #include "../mapper.h" #include "../audio_n163.h" enum { T_N163 = 0, T_N175, T_N340, T_UNK, }; static uint8_t *namco_prgROM; static uint8_t *namco_prgRAM; static uint8_t *namco_chrROM; static uint32_t namco_prgROMsize; static uint32_t namco_prgRAMsize; static uint32_t namco_chrROMsize; static uint32_t namco_curPRGBank0; static uint32_t namco_curPRGBank1; static uint32_t namco_curPRGBank2; static uint32_t namco_lastPRGBank; static uint32_t namco_CHRBank[8]; static uint8_t namco_VRAM[0x800]; static bool namco_CHRBankIsNT0; static bool namco_CHRBankIsNT1; static uint32_t namco_NTAddr[4]; static uint16_t namco_irqCtr; static bool namco_irqEnable; extern uint8_t interrupt; static uint8_t namco_type; //used externally uint32_t namco_prgROMand; uint32_t namco_chrROMand; void namco_init(uint8_t *prgROMin, uint32_t prgROMsizeIn, uint8_t *prgRAMin, uint32_t prgRAMsizeIn, uint8_t *chrROMin, uint32_t chrROMsizeIn) { namco_prgROM = prgROMin; namco_prgROMsize = prgROMsizeIn; namco_prgRAM = prgRAMin; namco_prgRAMsize = prgRAMsizeIn; namco_prgROMand = mapperGetAndValue(prgROMsizeIn); namco_curPRGBank0 = 0; namco_curPRGBank1 = 0x2000; namco_curPRGBank2 = 0x4000; namco_lastPRGBank = (prgROMsizeIn - 0x2000); namco_chrROM = chrROMin; namco_chrROMsize = chrROMsizeIn; namco_chrROMand = mapperGetAndValue(chrROMsizeIn); memset(namco_CHRBank,0,8*sizeof(uint32_t)); memset(namco_VRAM,0,0x800); namco_CHRBankIsNT0 = false; namco_CHRBankIsNT1 = false; memset(namco_NTAddr,0,4*sizeof(uint32_t)); namco_irqCtr = 0; namco_irqEnable = false; namco_type = T_UNK; ppuBackUpTbl(); printf("Namco Mapper inited\n"); } static void namcoSetN163() { if(namco_type != T_N163) { printf("Should be Namco N163\n"); namco_type = T_N163; n163AudioInit(); ppuSetNameTbl4Screen(); } } static void namcoGuessN175() { if((namco_type == T_N340) || (namco_type == T_UNK)) { printf("Guessing Namco N175\n"); namco_type = T_N175; ppuRestoreTbl(); } } static void namcoGuessN340() { if(namco_type == T_UNK) { printf("Guessing Namco N340\n"); namco_type = T_N340; } } uint8_t namco_get8(uint16_t addr, uint8_t val) { if(addr >= 0x4800 && addr < 0x6000) { namcoSetN163(); if(addr < 0x5000) return n163AudioGet8(addr, val); else if(addr < 0x5800) return namco_irqCtr&0xFF; else //if addr < 0x6000 return (((namco_irqCtr>>8)&0x7F)|(namco_irqEnable<<7)); } else if(addr >= 0x6000 && addr < 0x8000) { namcoGuessN175(); return namco_prgRAM[addr&0x1FFF]; } else if(addr >= 0x8000) { if(addr < 0xA000) return namco_prgROM[((namco_curPRGBank0<<13)|(addr&0x1FFF))&namco_prgROMand]; else if(addr < 0xC000) return namco_prgROM[((namco_curPRGBank1<<13)|(addr&0x1FFF))&namco_prgROMand]; else if(addr < 0xE000) return namco_prgROM[((namco_curPRGBank2<<13)|(addr&0x1FFF))&namco_prgROMand]; return namco_prgROM[(namco_lastPRGBank+(addr&0x1FFF))&namco_prgROMand]; } return val; } void namco_set8(uint16_t addr, uint8_t val) { //printf("namco_set8 %04x %02x\n", addr, val); if(addr >= 0x4800 && addr < 0x6000) { namcoSetN163(); if(addr < 0x5000) n163AudioSet8(addr, val); else if(addr < 0x5800) { namco_irqCtr &= ~0xFF; namco_irqCtr |= val; interrupt &= ~MAPPER_IRQ; } else //if addr < 0x6000 { namco_irqCtr &= 0xFF; namco_irqCtr |= (val&0x7F)<<8; namco_irqEnable = (val&0x80)!=0; interrupt &= ~MAPPER_IRQ; } } else if(addr >= 0x6000 && addr < 0x8000) { namcoGuessN175(); namco_prgRAM[addr&0x1FFF] = val; } else if(addr >= 0x8000) { if(addr < 0xE000) { if(addr >= 0xC000) { if(addr >= 0xC800) namcoSetN163(); else if(addr < 0xC800) namcoGuessN175(); //set these always just in case if(addr < 0xC800) namco_NTAddr[0] = val; else if(addr < 0xD000) namco_NTAddr[1] = val; else if(addr < 0xD800) namco_NTAddr[2] = val; else //if addr < 0xE000 namco_NTAddr[3] = val; } else namco_CHRBank[(addr>>11)&7] = val; } else if(addr < 0xE800) { namco_curPRGBank0 = val&0x3F; if((val&0xC0) != 0) namcoGuessN340(); if(namco_type == T_N340) { switch((val>>6)&3) { case 0: ppuSetNameTblSingleLower(); break; case 1: ppuSetNameTblVertical(); break; case 2: ppuSetNameTblSingleUpper(); break; case 3: ppuSetNameTblHorizontal(); break; } } } else if(addr < 0xF000) { namco_curPRGBank1 = val&0x3F; namco_CHRBankIsNT0 = (val&0x40) == 0; namco_CHRBankIsNT1 = (val&0x80) == 0; } else if(addr < 0xF800) namco_curPRGBank2 = val&0x3F; else if(addr >= 0xF800) { //cant use this set, dream master writes //0x40 into this reg on bootup... //namcoSetN163(); n163AudioSet8(addr, val); } } } uint8_t namco_chrGet8(uint16_t addr) { //printf("%04x\n",addr); addr &= 0x1FFF; if(namco_type == T_N163) { if(addr < 0x1000 && namco_CHRBankIsNT0) { if(addr < 0x400) { if(namco_CHRBank[0] >= 0xE0) return namco_VRAM[((namco_CHRBank[0]&1)?0x400:0)|(addr&0x3FF)]; } else if(addr < 0x800) { if(namco_CHRBank[1] >= 0xE0) return namco_VRAM[((namco_CHRBank[1]&1)?0x400:0)|(addr&0x3FF)]; } else if(addr < 0xC00) { if(namco_CHRBank[2] >= 0xE0) return namco_VRAM[((namco_CHRBank[2]&1)?0x400:0)|(addr&0x3FF)]; } else if(addr < 0x1000) { if(namco_CHRBank[3] >= 0xE0) return namco_VRAM[((namco_CHRBank[3]&1)?0x400:0)|(addr&0x3FF)]; } } else if(addr >= 0x1000 && namco_CHRBankIsNT1) { if(addr < 0x1400) { if(namco_CHRBank[4] >= 0xE0) return namco_VRAM[((namco_CHRBank[4]&1)?0x400:0)|(addr&0x3FF)]; } else if(addr < 0x1800) { if(namco_CHRBank[5] >= 0xE0) return namco_VRAM[((namco_CHRBank[5]&1)?0x400:0)|(addr&0x3FF)]; } else if(addr < 0x1C00) { if(namco_CHRBank[6] >= 0xE0) return namco_VRAM[((namco_CHRBank[6]&1)?0x400:0)|(addr&0x3FF)]; } else if(addr < 0x2000) { if(namco_CHRBank[7] >= 0xE0) return namco_VRAM[((namco_CHRBank[7]&1)?0x400:0)|(addr&0x3FF)]; } } } if(addr < 0x400) return namco_chrROM[((namco_CHRBank[0]<<10)|(addr&0x3FF))&namco_chrROMand]; else if(addr < 0x800) return namco_chrROM[((namco_CHRBank[1]<<10)|(addr&0x3FF))&namco_chrROMand]; else if(addr < 0xC00) return namco_chrROM[((namco_CHRBank[2]<<10)|(addr&0x3FF))&namco_chrROMand]; else if(addr < 0x1000) return namco_chrROM[((namco_CHRBank[3]<<10)|(addr&0x3FF))&namco_chrROMand]; else if(addr < 0x1400) return namco_chrROM[((namco_CHRBank[4]<<10)|(addr&0x3FF))&namco_chrROMand]; else if(addr < 0x1800) return namco_chrROM[((namco_CHRBank[5]<<10)|(addr&0x3FF))&namco_chrROMand]; else if(addr < 0x1C00) return namco_chrROM[((namco_CHRBank[6]<<10)|(addr&0x3FF))&namco_chrROMand]; return namco_chrROM[((namco_CHRBank[7]<<10)|(addr&0x3FF))&namco_chrROMand]; } void namco_chrSet8(uint16_t addr, uint8_t val) { //printf("namco_chrSet8 %04x %02x\n", addr, val); (void)addr; (void)val; } uint8_t namco_vramGet8(uint16_t addr) { if(namco_type == T_N163) { if(addr < 0x400) { if(namco_NTAddr[0] >= 0xE0) return namco_VRAM[((namco_NTAddr[0]&1)?0x400:0)|(addr&0x3FF)]; else return namco_chrROM[((namco_NTAddr[0]<<10)|(addr&0x3FF))&namco_chrROMand]; } else if(addr < 0x800) { if(namco_NTAddr[1] >= 0xE0) return namco_VRAM[((namco_NTAddr[1]&1)?0x400:0)|(addr&0x3FF)]; else return namco_chrROM[((namco_NTAddr[1]<<10)|(addr&0x3FF))&namco_chrROMand]; } else if(addr < 0xC00) { if(namco_NTAddr[2] >= 0xE0) return namco_VRAM[((namco_NTAddr[2]&1)?0x400:0)|(addr&0x3FF)]; else return namco_chrROM[((namco_NTAddr[2]<<10)|(addr&0x3FF))&namco_chrROMand]; } else if(addr < 0x1000) { if(namco_NTAddr[3] >= 0xE0) return namco_VRAM[((namco_NTAddr[3]&1)?0x400:0)|(addr&0x3FF)]; else return namco_chrROM[((namco_NTAddr[3]<<10)|(addr&0x3FF))&namco_chrROMand]; } } return namco_VRAM[addr&0x7FF]; } void namco_vramSet8(uint16_t addr, uint8_t val) { if(namco_type == T_N163) { if(addr < 0x400) { if(namco_NTAddr[0] >= 0xE0) namco_VRAM[((namco_NTAddr[0]&1)?0x400:0)|(addr&0x3FF)] = val; } else if(addr < 0x800) { if(namco_NTAddr[1] >= 0xE0) namco_VRAM[((namco_NTAddr[1]&1)?0x400:0)|(addr&0x3FF)] = val; } else if(addr < 0xC00) { if(namco_NTAddr[2] >= 0xE0) namco_VRAM[((namco_NTAddr[2]&1)?0x400:0)|(addr&0x3FF)] = val; } else if(addr < 0x1000) { if(namco_NTAddr[3] >= 0xE0) namco_VRAM[((namco_NTAddr[3]&1)?0x400:0)|(addr&0x3FF)] = val; } } else namco_VRAM[addr&0x7FF] = val; } extern uint8_t audioExpansion; void namco_cycle() { if(audioExpansion&EXP_N163) n163AudioClockTimers(); if(namco_irqEnable) { if(namco_irqCtr < 0x7FFF) namco_irqCtr++; if(namco_irqCtr >= 0x7FFF) { namco_irqEnable = false; if(!(interrupt&MAPPER_IRQ)) { interrupt |= MAPPER_IRQ; //printf("Namco Interrupt\n"); } } } }
2.65625
3
2024-11-18T22:22:07.223726+00:00
2020-08-24T02:08:12
214e044c0abe7a6525b300d1ec3088a30ba6321f
{ "blob_id": "214e044c0abe7a6525b300d1ec3088a30ba6321f", "branch_name": "refs/heads/master", "committer_date": "2020-08-24T02:08:12", "content_id": "d8608cb1ece33cf7dbbc6a21c8404e38da2dfeef", "detected_licenses": [ "MIT" ], "directory_id": "698b99ccb3f038f7e94ee90a8afc5e3119861c64", "extension": "c", "filename": "drv_spi.c", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 284174942, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1050, "license": "MIT", "license_type": "permissive", "path": "/Silverware/src/drv_spi.c", "provenance": "stackv2-0123.json.gz:13640", "repo_name": "konstantint/Silverware-H345", "revision_date": "2020-08-24T02:08:12", "revision_id": "bacb26b16474be593fe223122007788a9c4a7c7d", "snapshot_id": "0c0143daaea6a03c053805345ded86ab56b1033b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/konstantint/Silverware-H345/bacb26b16474be593fe223122007788a9c4a7c7d/Silverware/src/drv_spi.c", "visit_date": "2022-12-04T23:07:02.009612" }
stackv2
#include "project.h" #include "drv_spi.h" #include "binary.h" #include "config.h" #ifdef SOFTSPI_4WIRE void spi_init(void) { SYS->P0_MFP |= SYS_MFP_P01_GPIO; // SPI CS SYS->P0_MFP |= SYS_MFP_P07_SPI0_CLK|SYS_MFP_P05_SPI0_MOSI|SYS_MFP_P06_SPI0_MISO; SYS->P5_MFP |= SYS_MFP_P52_GPIO; GPIO_SetMode(P0, BIT1, GPIO_MODE_OUTPUT);// SPI CS GPIO_SetMode(P5, BIT2, GPIO_MODE_INPUT); // SPI IRQ CLK_EnableModuleClock(SPI0_MODULE); CLK_SetModuleClock(SPI0_MODULE,CLK_CLKSEL1_SPISEL_HCLK,1); SPI_Open(SPI0, SPI_MASTER, SPI_MODE_0, 8, 2000000); SPI_DisableAutoSS(SPI0); SPI_WRITE_TX(SPI0, 0); } void spi_cson( ) { P01 = 0; } void spi_csoff( ) { P01 = 1; } void spi_sendbyte ( int data) { SPI_WRITE_TX(SPI0, data); SPI_TRIGGER(SPI0); while(SPI_IS_BUSY(SPI0)); return; } int spi_sendrecvbyte( int data) { SPI_WRITE_TX(SPI0, data); SPI_TRIGGER(SPI0); while(SPI_IS_BUSY(SPI0)); return SPI0->RX; } int spi_sendzerorecvbyte( ) { return spi_sendrecvbyte(0); } #endif
2.140625
2
2024-11-18T22:22:07.305702+00:00
2017-10-20T01:18:36
b1347b075e05a7f30522cff11a38549024e90bef
{ "blob_id": "b1347b075e05a7f30522cff11a38549024e90bef", "branch_name": "refs/heads/master", "committer_date": "2017-11-05T21:12:31", "content_id": "2ca0105bc4fe3f6449ae884173d28c4c5bb2779c", "detected_licenses": [ "MIT" ], "directory_id": "f4fad85937a7843a0ae5602918168f6617f8c1a4", "extension": "c", "filename": "mkdir.c", "fork_events_count": 0, "gha_created_at": "2016-11-25T07:44:48", "gha_event_created_at": "2017-11-05T21:12:33", "gha_language": "C", "gha_license_id": null, "github_id": 74736601, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3390, "license": "MIT", "license_type": "permissive", "path": "/src/common/mkdir.c", "provenance": "stackv2-0123.json.gz:13769", "repo_name": "glines/ttoy", "revision_date": "2017-10-20T01:18:36", "revision_id": "f403ec89731a90f250f05c5a6d498452fe361ad8", "snapshot_id": "4dcceddbc60f14751c5d2f50c90256f8b4b14e46", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/glines/ttoy/f403ec89731a90f250f05c5a6d498452fe361ad8/src/common/mkdir.c", "visit_date": "2021-08-06T12:15:33.399506" }
stackv2
/* * Copyright (c) 2016-2017 Jonathan Glines * Jonathan Glines <jonathan@glines.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include "../logging.h" #include "mkdir.h" ttoy_ErrorCode ttoy_mkdir( const char *workingDir, const char *dir) { char *path; int dirLen, workingDirLen, len; int i, j; int result; struct stat sbuf; workingDirLen = strlen(workingDir); dirLen = strlen(dir); len = workingDirLen + 1 + dirLen; /* Concatenate the directory paths into a temporary buffer */ path = (char *)malloc(len + 1); if (path == NULL) { return TTOY_ERROR_OUT_OF_MEMORY; } strcpy(path, workingDir); path[workingDirLen] = '/'; strcpy(path + workingDirLen + 1, dir); /* Split temporary dir path, creating directories along the way */ i = workingDirLen + 1; while (path[i] == '/') { i += 1; /* Ignore leading slashes */ } while (i < len) { /* Search for the next directory slash */ for (j = i; j < len; ++j) { if (path[j] == '/') { path[j] = '\0'; break; } } /* Attempt to create the directory */ result = mkdir(path, 0755); if (result < 0) { if (errno == EEXIST) { /* Check for an existing file/directory */ result = stat(path, &sbuf); if (result < 0) { TTOY_LOG_ERROR( "Failed to create '%s' directory: %s", path, strerror(EEXIST)); return TTOY_ERROR_FAILED_TO_CREATE_DIRECTORY; } else if (!S_ISDIR(sbuf.st_mode)) { TTOY_LOG_ERROR( "Tried to create '%s' directory because '%s' is not a directory", dir, path); return TTOY_ERROR_FAILED_TO_CREATE_DIRECTORY; } /* The directory already existed */ } else { TTOY_LOG_ERROR( "Failed to create '%s' directory: %s", path, strerror(errno)); return TTOY_ERROR_FAILED_TO_CREATE_DIRECTORY; } } if (j < len) { /* Restore the directory slash */ path[j] = '/'; } /* Continue to the next directory in the path hierarchy */ i = j; while (path[i] == '/') { i += 1; /* Ignore repeated slashes */ } } free(path); return TTOY_NO_ERROR; }
2.71875
3
2024-11-18T22:22:08.851758+00:00
2020-11-13T12:23:26
06c32ddbf0abf4b0b78c1c1fe87055308cd02669
{ "blob_id": "06c32ddbf0abf4b0b78c1c1fe87055308cd02669", "branch_name": "refs/heads/master", "committer_date": "2020-11-13T12:23:26", "content_id": "660436608dcd38048ab9e52a9c8eef9b146c06ed", "detected_licenses": [ "MIT" ], "directory_id": "28691fa09af0052abaf0a315cebadb0da81f5c8a", "extension": "c", "filename": "jet_thread.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 252082074, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 280, "license": "MIT", "license_type": "permissive", "path": "/core/jet_thread.c", "provenance": "stackv2-0123.json.gz:13900", "repo_name": "Jinchenyuan/Jet", "revision_date": "2020-11-13T12:23:26", "revision_id": "205c54f15acea06ec1ebd7bad1335badce453687", "snapshot_id": "62cc4a6d7bce867dd6bd8812e05390f1e530f414", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Jinchenyuan/Jet/205c54f15acea06ec1ebd7bad1335badce453687/core/jet_thread.c", "visit_date": "2021-05-19T19:24:19.279004" }
stackv2
#include "jet_define.h" #include "jet_thread.h" #include "jet_lock.h" void create_thread(pthread_t *t, void *(*start_routine)(void *), void *arg) { if (pthread_create(t, NULL, start_routine, arg)) { fprintf(stderr, "create thread failed.\n"); exit(1); } }
2.078125
2
2024-11-18T22:22:08.904365+00:00
2019-12-02T12:09:21
44833ff56befff7797ec1df4df2eb4c473e431c4
{ "blob_id": "44833ff56befff7797ec1df4df2eb4c473e431c4", "branch_name": "refs/heads/master", "committer_date": "2019-12-02T12:09:21", "content_id": "e978721946a005f66a4fd73d5561550c9fc1ee09", "detected_licenses": [ "Unlicense" ], "directory_id": "471729fbc387fd0baf66787cde19882a2e1b8e24", "extension": "c", "filename": "vertice.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 225366164, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6638, "license": "Unlicense", "license_type": "permissive", "path": "/Exe8/src/vertice.c", "provenance": "stackv2-0123.json.gz:14030", "repo_name": "HenriqueBuzin/graph-chained-list", "revision_date": "2019-12-02T12:09:21", "revision_id": "9009aa28eacc0ed57328209e764c027cf4a5f346", "snapshot_id": "da6098120d135e9101c665f8f301a4f58fdc7ae9", "src_encoding": "ISO-8859-1", "star_events_count": 0, "url": "https://raw.githubusercontent.com/HenriqueBuzin/graph-chained-list/9009aa28eacc0ed57328209e764c027cf4a5f346/Exe8/src/vertice.c", "visit_date": "2020-09-23T01:27:34.878824" }
stackv2
/* * vertice.c * * Created on: Jul 5, 2016 * Author: Renan Augusto Starke */ #include <stdlib.h> #include <stdio.h> #include "vertice.h" #include "lista_enc.h" struct vertices { int id; /*!< Identificação numérica do vértice */ lista_enc_t *arestas; /*!< Listas encadeada das arestas pertencentes ao vértice */ /* Informações para componentes conexos */ int id_grupo; vertice_t* pai; int dist; int visitado; }; int get_dist(vertice_t * v){ return v->dist; } int get_visitado(vertice_t * v){ return v->visitado; } vertice_t * get_pai(vertice_t * v){ return v->pai; } void set_dist(vertice_t * v, int dist){ v->dist = dist; } void set_visitado(vertice_t * v, int visitado){ v->visitado = visitado; } struct arestas { int peso; /*!< Identificação numérica da aresta */ vertice_t *fonte; /*!< Vértice fonte. Geralmente vértice pertencente a lista de arestas do vértice */ vertice_t *dest; /*!< Vértice destino */ status_aresta_t status; /*!< Estado de exportação. Utilizado na função de exportação para dot. */ }; /** * @brief Cria uma novo vértice * @param id: Identificação numérica do vértice * * @retval vertice_t: ponteiro para um novo vértice */ vertice_t *cria_vertice(int id) { vertice_t *p = NULL; p = malloc(sizeof(vertice_t)); if (p == NULL) { perror("cria_vertice:"); exit(EXIT_FAILURE); } p->id = id; p->arestas = cria_lista_enc(); p->id_grupo = -1; p->pai = NULL; return p; } /** * @brief Obtém o identificador numérico do vértice * @param vertice: ponteiro do vértice * * @retval int: identificador numérico do vértice */ int vertice_get_id(vertice_t *vertice) { if (vertice == NULL) { fprintf(stderr, "vertice_obter_id: vertice invalido!\n"); exit(EXIT_FAILURE); } return vertice->id; } /** * @brief Cria uma aresta entre dois vértices * @param fonte: ponteiro do vértice fonte * @param destino: ponteiro do vértice destino * @param peso: peso da aresta * * @retval arestas_t: ponteiro da nova aresta criada */ arestas_t *cria_aresta(vertice_t *fonte, vertice_t *destino, int peso) { arestas_t *p; p = (arestas_t*)malloc(sizeof(arestas_t)); if (p == NULL) { perror("cria_aresta:"); exit(EXIT_FAILURE); } p->peso = peso; p->fonte = fonte; p->dest = destino; return p; } /** * @brief Adiciona uma nova aresta na lista de arestas de um vértice * @param vertice: ponteiro do vértice * @param aresta: ponteiro da aresta * * @retval Nenhum */ void adiciona_aresta(vertice_t *vertice, arestas_t *aresta) { no_t *no; if (vertice == NULL || aresta == NULL) { fprintf(stderr, "adiciona_aresta: dados invalidos\n"); exit(EXIT_FAILURE); } no = cria_no(aresta); add_cauda(vertice->arestas, no); } /** * @brief Obtém a lista encadadeada de arestas: útil para obter todos vértices adjacentes * @param vertice: ponteiro do vértice * * @retval lista_enc_t: lista encadeada contendas as arestas */ lista_enc_t *vertice_get_arestas(vertice_t *vertice) { if (vertice == NULL){ fprintf(stderr, "vertice_get_arestas: vertice invalido\n"); exit(EXIT_FAILURE); } return vertice->arestas; } /** * @brief Obtém o peso se uma aresta * @param aresta: ponteiro da aresta * * @retval int: peso numérico da aresta */ int aresta_get_peso (arestas_t *aresta) { if (aresta == NULL){ fprintf(stderr, "aresta_get_peso: aresta invalido\n"); exit(EXIT_FAILURE); } return aresta->peso; } /** * @brief Obtém o vértice adjacente de um aresta * @param aresta: ponteiro da aresta * * @retval vertice_t: vértice adjacente ou destino */ vertice_t *aresta_get_adjacente(arestas_t *aresta) { if (aresta == NULL){ fprintf(stderr, "aresta_get_adjacente: aresta invalido\n"); exit(EXIT_FAILURE); } return aresta->dest; } /** * @brief Retorna uma aresta se um vértice for adjacente a outro: busca linear na lista de arestas * @param vertice: vértice de referência * @param adjacente: vértice que se deseja verificar se é adjacente à referência * * @retval arestas_t: aresta adjacente. NULL se não for adjacente */ arestas_t *procurar_adjacente(vertice_t *vertice, vertice_t *adjacente) { no_t *no; arestas_t *aresta; if (vertice == NULL){ fprintf(stderr, "procurar_adjacente: aresta invalido\n"); exit(EXIT_FAILURE); } no = obter_cabeca(vertice->arestas); while (no){ aresta = obter_dado(no); if (aresta->dest == adjacente || aresta->fonte == adjacente) return aresta; no = obtem_proximo(no); } return NULL; } /** * @brief Retorna o estado de exportação de uma aresta. Utilizada para geração do dot * @param aresta: aresta em questão * * @retval status_aresta_t: estado atual: conforme status_aresta_t */ status_aresta_t aresta_get_status (arestas_t *aresta) { if (aresta == NULL){ fprintf(stderr, "aresta_get_status: aresta invalida\n"); exit(EXIT_FAILURE); } return aresta->status; } /** * @brief Altera o de exportação de uma aresta. Utilizada para geração do dot * @param aresta: aresta em questão * @param status: novo estado: conforme status_aresta_t * * @retval Nenhum */ void aresta_set_status(arestas_t *aresta, status_aresta_t status) { if (aresta == NULL){ fprintf(stderr, "aresta_set_status: aresta invalida\n"); exit(EXIT_FAILURE); } aresta->status = status; } /** * @brief Altera a propriedade grupo de um vértice * @param vertice: vértice em questão * @param grupo: novo grupo * * @retval Nenhum */ void vertice_set_grupo(vertice_t *vertice, int grupo) { if (vertice == NULL){ fprintf(stderr, "vertice_set_grupo: vertice invalido\n"); exit(EXIT_FAILURE); } vertice->id_grupo = grupo; } /** * @brief Obtém a propriedade grupo de um vértice * @param vertice: vértice em questão * * @retval int: grupo da aresta */ int vertice_get_grupo(vertice_t *vertice) { if (vertice == NULL){ fprintf(stderr, "vertice_get_grupo: vertice invalido\n"); exit(EXIT_FAILURE); } return vertice->id_grupo; } /** * @brief Altera a propriedade pai de um vértice * @param vertice: vértice em questão * @param pai: novo vértice adjacente e pai * * @retval Nenhum */ void vertice_set_pai(vertice_t *vertice, vertice_t *pai) { if (vertice == NULL){ fprintf(stderr, "vertice_set_pai: vertice invalido\n"); exit(EXIT_FAILURE); } vertice->pai = pai; } void vertice_imprimi(vertice_t * v){ printf("ID: %d, Distância: %d, Visitado: %d, Pai: %d\n", v->id, v->dist, v->visitado, v->pai == NULL ? -1 : v->pai->id ); }
3.09375
3
2024-11-18T22:22:09.132045+00:00
2021-02-28T09:25:45
0a3ecba6ddc24e09f25c58220d7ec2d07dd36f1f
{ "blob_id": "0a3ecba6ddc24e09f25c58220d7ec2d07dd36f1f", "branch_name": "refs/heads/main", "committer_date": "2021-02-28T09:25:45", "content_id": "89d43fd127fc3e7c0a2d590bf77c52385c8c4d97", "detected_licenses": [ "MIT" ], "directory_id": "447321c6bf3dd5351f50e3e6d47b617b6614129c", "extension": "h", "filename": "registers.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 317131610, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 591, "license": "MIT", "license_type": "permissive", "path": "/libs/instructions/include/instructions/registers.h", "provenance": "stackv2-0123.json.gz:14418", "repo_name": "tiaanl/eighty-eighty-six", "revision_date": "2021-02-28T09:25:45", "revision_id": "832c73ca58ab14eb1dfbeae1920de84955e377f7", "snapshot_id": "663198db073555da78bc4f5cf77770eb5153e7e1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tiaanl/eighty-eighty-six/832c73ca58ab14eb1dfbeae1920de84955e377f7/libs/instructions/include/instructions/registers.h", "visit_date": "2023-03-20T20:05:12.127229" }
stackv2
#ifndef REGISTERS_H_ #define REGISTERS_H_ enum register_8 { #if 0 // big-endian AH, AL, CH, CL, DH, DL, BH, BL, #else AL, AH, CL, CH, DL, DH, BL, BH, #endif register_8_count, }; enum register_16 { AX, CX, DX, BX, SP, BP, SI, DI, register_16_count, }; enum segment_register { ES, CS, SS, DS, segment_register_count, }; const char *register_8_to_string(enum register_8 reg); const char *register_16_to_string(enum register_16 reg); const char *segment_register_to_string(enum segment_register reg); #endif // REGISTERS_H_
2.046875
2
2024-11-18T22:22:09.571758+00:00
2023-02-16T11:27:40
19fbf8bfb4f557d4dbc1f3001f0405dfe406c1d4
{ "blob_id": "19fbf8bfb4f557d4dbc1f3001f0405dfe406c1d4", "branch_name": "refs/heads/main", "committer_date": "2023-02-16T14:59:16", "content_id": "b71886013998237667a9a850b4a617b928f9e783", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493", "extension": "c", "filename": "ps2_npcx_channel.c", "fork_events_count": 32, "gha_created_at": "2016-08-05T22:14:50", "gha_event_created_at": "2022-04-05T17:14:07", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 65052293, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3733, "license": "Apache-2.0", "license_type": "permissive", "path": "/drivers/ps2/ps2_npcx_channel.c", "provenance": "stackv2-0123.json.gz:14678", "repo_name": "intel/zephyr", "revision_date": "2023-02-16T11:27:40", "revision_id": "06d5bc51b580777079bb0b7e769e4127598ea5ee", "snapshot_id": "819362089aa44ae378a5558f3b222197aaa811f7", "src_encoding": "UTF-8", "star_events_count": 32, "url": "https://raw.githubusercontent.com/intel/zephyr/06d5bc51b580777079bb0b7e769e4127598ea5ee/drivers/ps2/ps2_npcx_channel.c", "visit_date": "2023-09-04T00:20:35.217393" }
stackv2
/* * Copyright (c) 2021 Nuvoton Technology Corporation. * * SPDX-License-Identifier: Apache-2.0 */ #define DT_DRV_COMPAT nuvoton_npcx_ps2_channel /** * @file * @brief Nuvoton NPCX PS/2 driver * * This file contains the driver of PS/2 buses (channels) which provides the * connection between Zephyr PS/2 API functions and NPCX PS/2 controller driver * to support PS/2 transactions. * */ #include <zephyr/drivers/clock_control.h> #include <zephyr/drivers/pinctrl.h> #include <zephyr/drivers/ps2.h> #include <soc.h> #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(ps2_npcx_channel, CONFIG_PS2_LOG_LEVEL); #include "ps2_npcx_controller.h" /* Device config */ struct ps2_npcx_ch_config { /* Indicate the channel's number of the PS/2 channel device */ uint8_t channel_id; const struct device *ps2_ctrl; /* pinmux configuration */ const struct pinctrl_dev_config *pcfg; }; /* PS/2 api functions */ static int ps2_npcx_ch_configure(const struct device *dev, ps2_callback_t callback_isr) { const struct ps2_npcx_ch_config *const config = dev->config; int ret; ret = ps2_npcx_ctrl_configure(config->ps2_ctrl, config->channel_id, callback_isr); if (ret != 0) { return ret; } return ps2_npcx_ctrl_enable_interface(config->ps2_ctrl, config->channel_id, 1); } static int ps2_npcx_ch_write(const struct device *dev, uint8_t value) { const struct ps2_npcx_ch_config *const config = dev->config; return ps2_npcx_ctrl_write(config->ps2_ctrl, config->channel_id, value); } static int ps2_npcx_ch_enable_interface(const struct device *dev) { const struct ps2_npcx_ch_config *const config = dev->config; return ps2_npcx_ctrl_enable_interface(config->ps2_ctrl, config->channel_id, 1); } static int ps2_npcx_ch_inhibit_interface(const struct device *dev) { const struct ps2_npcx_ch_config *const config = dev->config; return ps2_npcx_ctrl_enable_interface(config->ps2_ctrl, config->channel_id, 0); } /* PS/2 driver registration */ static int ps2_npcx_channel_init(const struct device *dev) { const struct ps2_npcx_ch_config *const config = dev->config; int ret; if (!device_is_ready(config->ps2_ctrl)) { LOG_ERR("%s device not ready", config->ps2_ctrl->name); return -ENODEV; } /* Configure pin-mux for PS/2 device */ ret = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT); if (ret < 0) { LOG_ERR("PS2 pinctrl setup failed (%d)", ret); return ret; } return 0; } static const struct ps2_driver_api ps2_channel_npcx_driver_api = { .config = ps2_npcx_ch_configure, .read = NULL, .write = ps2_npcx_ch_write, .disable_callback = ps2_npcx_ch_inhibit_interface, .enable_callback = ps2_npcx_ch_enable_interface, }; /* PS/2 channel initialization macro functions */ #define NPCX_PS2_CHANNEL_INIT(inst) \ \ PINCTRL_DT_INST_DEFINE(inst); \ \ static const struct ps2_npcx_ch_config ps2_npcx_ch_cfg_##inst = { \ .channel_id = DT_INST_PROP(inst, channel), \ .ps2_ctrl = DEVICE_DT_GET(DT_INST_PARENT(inst)), \ .pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(inst), \ }; \ \ DEVICE_DT_INST_DEFINE(inst, ps2_npcx_channel_init, NULL, NULL, \ &ps2_npcx_ch_cfg_##inst, POST_KERNEL, \ CONFIG_PS2_CHANNEL_INIT_PRIORITY, \ &ps2_channel_npcx_driver_api); DT_INST_FOREACH_STATUS_OKAY(NPCX_PS2_CHANNEL_INIT) /* PS/2 channel driver must be initialized after PS/2 controller driver */ BUILD_ASSERT(CONFIG_PS2_CHANNEL_INIT_PRIORITY > CONFIG_PS2_INIT_PRIORITY);
2.40625
2
2024-11-18T22:22:09.648577+00:00
2023-02-22T04:31:37
b103b7170916ca67484a2333723dd1e00fda4dd9
{ "blob_id": "b103b7170916ca67484a2333723dd1e00fda4dd9", "branch_name": "refs/heads/main", "committer_date": "2023-02-22T04:31:37", "content_id": "b815aa4703bd3783fd9afdbce9182426f3803ff5", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "c078aaf13845d41f8d547bad0b4a464b6a52e387", "extension": "c", "filename": "cssparse.c", "fork_events_count": 0, "gha_created_at": "2010-10-05T17:00:35", "gha_event_created_at": "2023-02-22T04:31:38", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 964116, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1156, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/tests/cssparse.c", "provenance": "stackv2-0123.json.gz:14806", "repo_name": "chimara/Chimara", "revision_date": "2023-02-22T04:31:37", "revision_id": "2571f797c1e4e20d0a147931c725275343405c3e", "snapshot_id": "d7b7cbaf7e2c49b6d1fdefc50231e1cbe455326c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/chimara/Chimara/2571f797c1e4e20d0a147931c725275343405c3e/tests/cssparse.c", "visit_date": "2023-03-06T21:26:40.105684" }
stackv2
#include <glib.h> #include <gtk/gtk.h> #include <libchimara/chimara-glk.h> static GtkWidget *glk; static void test_font_size_one_digit(void) { chimara_glk_set_css_from_string(CHIMARA_GLK(glk), "buffer { font-size: 8; }"); } static void test_font_size_no_unit(void) { chimara_glk_set_css_from_string(CHIMARA_GLK(glk), "buffer { font-size: 12; }"); } static void test_font_size_unit_pt(void) { chimara_glk_set_css_from_string(CHIMARA_GLK(glk), "buffer { font-size: 11pt; }"); } static void test_font_size_unit_other(void) { g_test_expect_message("Chimara", G_LOG_LEVEL_WARNING, "*px*"); chimara_glk_set_css_from_string(CHIMARA_GLK(glk), "buffer { font-size: 11px; }"); g_test_assert_expected_messages(); } int main(int argc, char *argv[]) { gtk_test_init(&argc, &argv); glk = chimara_glk_new(); g_test_add_func("/css/font-size/one-digit", test_font_size_one_digit); g_test_add_func("/css/font-size/no-unit", test_font_size_no_unit); g_test_add_func("/css/font-size/unit-pt", test_font_size_unit_pt); g_test_add_func("/css/font-size/unit-other", test_font_size_unit_other); return g_test_run(); }
2
2
2024-11-18T22:22:09.730429+00:00
2014-01-14T17:40:15
b44019f6dc2e99888004cabe3c5ae788fccf8513
{ "blob_id": "b44019f6dc2e99888004cabe3c5ae788fccf8513", "branch_name": "refs/heads/master", "committer_date": "2014-01-14T17:40:15", "content_id": "b8a7ae0b6b639a00fc8492cf47c2dac9925f4e52", "detected_licenses": [ "MIT" ], "directory_id": "3efd0765bf780d57c976444f2ce44a570f6bacf9", "extension": "h", "filename": "readBedTrack.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": 881, "license": "MIT", "license_type": "permissive", "path": "/predictors/NMFpredictor/readBedTrack.h", "provenance": "stackv2-0123.json.gz:14934", "repo_name": "christopherszeto/hgClassifications", "revision_date": "2014-01-14T17:40:15", "revision_id": "30b48519c31e7f795ea1809b74585354f7766118", "snapshot_id": "c4c18f1770b29b4081d7de835a7a0b6757154f32", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/christopherszeto/hgClassifications/30b48519c31e7f795ea1809b74585354f7766118/predictors/NMFpredictor/readBedTrack.h", "visit_date": "2016-08-05T11:13:46.103865" }
stackv2
#ifndef _readBedTrack_ #define _readBedTrack_ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #define MAX_TOKEN 100 #define MAXLINE 30000 /*************************************************** ** cszeto Aug 2009 ** ** Defines a DLL bedEntry structure, and how to ** extract the distances to and from each probe to their ** neighbours. ***************************************************/ struct bedEntry{ int chr; int start; int end; int isValid; struct bedEntry *next; struct bedEntry *last; }; struct bedEntry * init_bedEntry(int chr, int start, int end); void pushBedEntry(struct bedEntry *dest, int chr, int start, int end); void chrom_intToString(char *string, int chr); int chrom_stringToInt(char *string); struct bedEntry * readBedFile(FILE *fp); void calculate_distances(struct bedEntry *b,int * distances, int number); #endif
2.015625
2
2024-11-18T22:22:09.995165+00:00
2021-07-17T15:39:08
8ad0ecabb7df4f0e805e3b91d01466405b440a8f
{ "blob_id": "8ad0ecabb7df4f0e805e3b91d01466405b440a8f", "branch_name": "refs/heads/main", "committer_date": "2021-07-18T22:28:51", "content_id": "a8c8fe67ae81df92c94a39e69f8b6c23c092c505", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8e44bd7ee3aca3671e0778c0c8ceea0ebbb09ffb", "extension": "h", "filename": "dpdk_primitives_impl.h", "fork_events_count": 0, "gha_created_at": "2021-05-19T10:20:27", "gha_event_created_at": "2021-05-19T10:20:27", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 368828059, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8636, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/hardware_dep/dpdk/includes/dpdk_primitives_impl.h", "provenance": "stackv2-0123.json.gz:15323", "repo_name": "rst0git/t4p4s", "revision_date": "2021-07-17T15:39:08", "revision_id": "996a25f5138b5c8f97c4886c4819328cdfaaca82", "snapshot_id": "baba3f610e66d995d73a14630b0591e527eae97c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rst0git/t4p4s/996a25f5138b5c8f97c4886c4819328cdfaaca82/src/hardware_dep/dpdk/includes/dpdk_primitives_impl.h", "visit_date": "2023-07-20T03:43:00.238854" }
stackv2
// SPDX-License-Identifier: Apache-2.0 // Copyright 2020 Eotvos Lorand University, Budapest, Hungary // this file is directly included from dpdk_primitives.h, no need for a "#pragma once" #include <rte_byteorder.h> #include "dataplane.h" #include "util_packet.h" #ifdef T4P4S_DEBUG #include <assert.h> #endif /******************************************************************************* Auxiliary *******************************************************************************/ #define FLDINFOS(fld) (hdr_infos[fld_infos[fld].header_instance]) #define FLD_IS_FIXED_WIDTH(fld) (fld != FLDINFOS(fld).var_width_field) #define FLD_IS_FIXED_POS(fld) (FLDINFOS(fld).var_width_field == -1 || fld <= FLDINFOS(fld).var_width_field) #define FLD_BITWIDTH(hdesc, fld) (FLD_IS_FIXED_WIDTH(fld) ? fld_infos[fld].bit_width : hdesc.var_width_field_bitwidth) #define FLD_BYTEOFFSET(hdesc, fld) (fld_infos[fld].byte_offset + (FLD_IS_FIXED_POS(fld) ? 0 : (hdesc.var_width_field_bitwidth / 8))) #define handle(hdesc, fld) \ ((bitfield_handle_t) \ { \ .byte_addr = (((uint8_t*)hdesc.pointer)+(FLD_BYTEOFFSET(hdesc, fld))), \ .meta = FLDINFOS(fld).is_metadata, \ .bitwidth = FLD_BITWIDTH(hdesc, fld), \ .bytewidth = (FLD_BITWIDTH(hdesc, fld) + 7) / 8, \ .bitcount = FLD_BITWIDTH(hdesc, fld) + fld_infos[fld].bit_offset, /* bitwidth + bitoffset */ \ .bytecount = ((FLD_BITWIDTH(hdesc, fld) + 7 + fld_infos[fld].bit_offset) / 8), \ .bitoffset = fld_infos[fld].bit_offset, \ .byteoffset = FLD_BYTEOFFSET(hdesc, fld), \ .mask = fld_infos[fld].mask, \ .fixed_width = FLD_IS_FIXED_WIDTH(fld), \ }) #define header_desc_buf(buf, w) ((header_descriptor_t) { -1, buf, -1, w }) #define header_desc_ins(pd, h) ((pd)->headers[h]) /******************************************************************************/ #define FLD_MASK(fd) (fd.fixed_width ? fd.mask : \ rte_cpu_to_be_32((~0 << (32 - fd.bitcount)) & (~0 >> fd.bitoffset))) #define FLD_BYTES(fd) ( fd.bytecount == 1 ? (*(uint8_t*) fd.byte_addr) : \ ( fd.bytecount == 2 ? (*(uint16_t*) fd.byte_addr) : \ (*(uint32_t*) fd.byte_addr) ) ) #define FLD_MASKED_BYTES(fd) (FLD_BYTES(fd) & FLD_MASK(fd)) #define BYTECOUNT(fd) ((fd.bitcount - 1) / 8) #define MASK_LOW(fd) (FLD_MASK(fd) & 0xff) #define MASK_MID(fd) (FLD_MASK(fd) & (~0 >> ((4 - BYTECOUNT(fd)) * 8)) & ~0xff) #define MASK_TOP(fd) (FLD_MASK(fd) & (0xff << (BYTECOUNT(fd) * 8))) /******************************************************************************* Modify - statement - bytebuf *******************************************************************************/ // Modifies a field in the packet by the given source and length [ONLY BYTE ALIGNED] #define MODIFY_BYTEBUF_BYTEBUF(dst_fd, src, srclen) { \ /*TODO: If the src contains a signed negative value, than the following memset is incorrect*/ \ memset(dst_fd.byte_addr, 0, dst_fd.bytewidth - srclen); \ memcpy(dst_fd.byte_addr + (dst_fd.bytewidth - srclen), src, srclen); \ } /******************************************************************************* Modify - statement - int32 *******************************************************************************/ // Modifies a field in the packet by the given source and length (byte conversion when necessary) [MAX 4 BYTES] // assuming `uint32_t value32' is in the scope #define MODIFY_INT32_BYTEBUF(dst_fd, src, srclen) { \ value32 = 0; \ memcpy(&value32, src, srclen); \ MODIFY_INT32_INT32_AUTO(dst_fd, value32); \ } #define MASK_AT(value32,mask,bitcount) ((value32 & ((mask) >> (bitcount))) << (bitcount)) // Modifies a field in the packet by a uint32_t value (no byteorder conversion) [MAX 4 BYTES] // assuming `uint32_t res32' is in the scope #define MODIFY_INT32_INT32_BITS(dst_fd, value32) { \ { \ uint32_t res32 = (FLD_BYTES(dst_fd) & ~FLD_MASK(dst_fd)); \ if (dst_fd.bytecount == 1) { \ res32 |= (value32 << (8 - dst_fd.bitcount) & FLD_MASK(dst_fd)); \ } else if (dst_fd.bytecount == 2) { \ res32 |= MASK_AT(value32, MASK_LOW(dst_fd), 0); \ res32 |= MASK_AT(value32, MASK_TOP(dst_fd), 16 - dst_fd.bitwidth); \ } else { \ res32 |= MASK_AT(value32, MASK_LOW(dst_fd), 0); \ res32 |= MASK_AT(value32, MASK_MID(dst_fd), dst_fd.bitoffset); \ res32 |= MASK_AT(value32, MASK_TOP(dst_fd), dst_fd.bytecount * 8 - dst_fd.bitwidth); \ } \ memcpy(dst_fd.byte_addr, &res32, dst_fd.bytecount); \ } \ } // Modifies a field in the packet by a uint32_t value with byte conversion (always) [MAX 4 BYTES] // assuming `uint32_t res32' is in the scope #define MODIFY_INT32_INT32_HTON(dst_fd, value32) { \ { \ uint32_t res32 = (FLD_BYTES(dst_fd) & ~FLD_MASK(dst_fd)); \ if (dst_fd.bytecount == 1) \ res32 |= (value32 << (8 - dst_fd.bitcount)) & FLD_MASK(dst_fd); \ else if (dst_fd.bytecount == 2) \ res32 |= rte_cpu_to_be_16(value32 << (16 - dst_fd.bitcount)) & FLD_MASK(dst_fd); \ else \ res32 |= rte_cpu_to_be_32(value32 << (32 - dst_fd.bitcount)) & FLD_MASK(dst_fd); \ memcpy(dst_fd.byte_addr, &res32, dst_fd.bytecount); \ } \ } // Modifies a field in the packet by a uint32_t value with byte conversion when necessary [MAX 4 BYTES] // assuming `uint32_t res32' is in the scope #define MODIFY_INT32_INT32_AUTO(dst_fd, value32) { \ if (dst_fd.meta) { MODIFY_INT32_INT32_BITS(dst_fd, value32) } else { MODIFY_INT32_INT32_HTON(dst_fd, value32) } \ } /******************************************************************************* Extract - expression (unpack value and return it) *******************************************************************************/ //TODO: This should be simplified or separated into multiple macros // Gets the value of a field #define GET_INT32_AUTO(fd) (fd.meta ? \ (fd.bytecount == 1 ? (FLD_MASKED_BYTES(fd) >> (8 - fd.bitcount)) : \ ((FLD_BYTES(fd) & MASK_LOW(fd)) | \ ((FLD_BYTES(fd) & MASK_MID(fd)) >> fd.bitoffset) | \ ((FLD_BYTES(fd) & MASK_TOP(fd)) >> (fd.bytecount * 8 - fd.bitwidth)))) :\ (fd.bytecount == 1 ? (FLD_MASKED_BYTES(fd) >> (8 - fd.bitcount)) : \ (fd.bytecount == 2 ? (rte_be_to_cpu_16(FLD_MASKED_BYTES(fd)) >> (16 - fd.bitcount)) : \ (rte_be_to_cpu_32(FLD_MASKED_BYTES(fd)) >> (32 - fd.bitcount))))) /******************************************************************************* Extract - statement (unpack value to a destination variable) *******************************************************************************/ // Extracts a field to the given uint32_t variable with byte conversion (always) [MAX 4 BYTES] #define EXTRACT_INT32_NTOH(fd, dst) { \ if (fd.bytecount == 1) \ dst = FLD_MASKED_BYTES(fd) >> (8 - fd.bitcount); \ else if (fd.bytecount == 2) \ dst = rte_be_to_cpu_16(FLD_MASKED_BYTES(fd)) >> (16 - fd.bitcount); \ else \ dst = rte_be_to_cpu_32(FLD_MASKED_BYTES(fd)) >> (32 - fd.bitcount); \ } // Extracts a field to the given uint32_t variable (no byteorder conversion) [MAX 4 BYTES] #define EXTRACT_INT32_BITS(fd, dst) { \ if (fd.bytecount == 1) \ dst = FLD_MASKED_BYTES(fd) >> (8 - fd.bitcount); \ else if (fd.bytecount == 2) \ dst = (FLD_BYTES(fd) & MASK_LOW(fd)) | \ ((FLD_BYTES(fd) & MASK_TOP(fd)) >> (16 - fd.bitwidth)); \ else \ dst = (FLD_BYTES(fd) & MASK_LOW(fd)) | \ ((FLD_BYTES(fd) & MASK_MID(fd)) >> fd.bitoffset) | \ ((FLD_BYTES(fd) & MASK_TOP(fd)) >> (fd.bytecount * 8 - fd.bitwidth)); \ } // Extracts a field to the given uint32_t variable with byte conversion when necessary [MAX 4 BYTES] #define EXTRACT_INT32_AUTO(fd, dst) { \ if (fd.meta) { EXTRACT_INT32_BITS(fd, dst) } else { EXTRACT_INT32_NTOH(fd, dst) } \ } // Extracts a field to the given destination [ONLY BYTE ALIGNED] #define EXTRACT_BYTEBUF(fd, dst) { \ memcpy(dst, fd.byte_addr, fd.bytewidth); \ } /*******************************************************************************/ void set_field(fldT f[], bufT b[], uint32_t value32, int bit_width); void MODIFY_INT32_INT32_AUTO_PACKET(packet_descriptor_t* pd, header_instance_t h, field_instance_t f, uint32_t value32);
2.21875
2
2024-11-18T22:22:10.071778+00:00
2021-03-02T11:49:49
4e69aeb671972de209c083a2ebcc90dc24fac7f9
{ "blob_id": "4e69aeb671972de209c083a2ebcc90dc24fac7f9", "branch_name": "refs/heads/master", "committer_date": "2021-03-02T11:49:49", "content_id": "956e252cc70245055460db59bd5feefedb557ae3", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "359710c5738b764648343784e23f43514ddb0f2b", "extension": "c", "filename": "spindump_eventformatter_json.c", "fork_events_count": 0, "gha_created_at": "2019-11-11T15:41:27", "gha_event_created_at": "2019-11-11T15:41:28", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 221013671, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3188, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/spindump_eventformatter_json.c", "provenance": "stackv2-0123.json.gz:15451", "repo_name": "fabiobulgarella/spindump", "revision_date": "2021-03-02T11:49:49", "revision_id": "74e65286f2b28c671d1381606a652da9a3a82d85", "snapshot_id": "0d4406b1fc3eef0faa2d1483c7b934887884a0a8", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/fabiobulgarella/spindump/74e65286f2b28c671d1381606a652da9a3a82d85/src/spindump_eventformatter_json.c", "visit_date": "2021-07-01T06:13:07.066559" }
stackv2
// // // //////////////////////////////////////////////////////////////////////////////////// // ///////// /////////// // ////// SSS PPPP I N N DDDD U U M M PPPP ////// // // S P P I NN N D D U U MM MM P P // // / SSS PPPP I N NN N D D U U M M M PPPP / // // S P I N NN D D U U M M P // // //// SSS P I N N DDDD UUU M M P ////// // ///////// /////////// // //////////////////////////////////////////////////////////////////////////////////// // // SPINDUMP (C) 2018-2019 BY ERICSSON RESEARCH // AUTHOR: JARI ARKKO // // // // Includes ----------------------------------------------------------------------------------- // #include <stdio.h> #include <string.h> #include <stdlib.h> #include "spindump_util.h" #include "spindump_eventformatter.h" #include "spindump_eventformatter_json.h" #include "spindump_event.h" #include "spindump_event_parser_json.h" // // Actual code -------------------------------------------------------------------------------- // // // Return the length of the preamble // unsigned long spindump_eventformatter_measurement_beginlength_json(struct spindump_eventformatter* formatter) { return(2); } // // Print what is needed as a preface to the actual records // const uint8_t* spindump_eventformatter_measurement_begin_json(struct spindump_eventformatter* formatter) { return((uint8_t*)"[\n"); } // // Return the length of the postamble // unsigned long spindump_eventformatter_measurement_midlength_json(struct spindump_eventformatter* formatter) { return(2); } // // Print what is needed as an end after the actual records // const uint8_t* spindump_eventformatter_measurement_mid_json(struct spindump_eventformatter* formatter) { return((uint8_t*)",\n"); } // // Return the length of the postamble // unsigned long spindump_eventformatter_measurement_endlength_json(struct spindump_eventformatter* formatter) { return(3); } // // Print what is needed as an end after the actual records // const uint8_t* spindump_eventformatter_measurement_end_json(struct spindump_eventformatter* formatter) { return((uint8_t*)"\n]\n"); } // // Print out one --textual measurement event, when the format is set // to --format json // void spindump_eventformatter_measurement_one_json(struct spindump_eventformatter* formatter, spindump_analyze_event event, const struct spindump_event* eventobj, struct spindump_connection* connection) { char buf[400]; size_t consumed; spindump_event_parser_json_print(eventobj,buf,sizeof(buf)-1,&consumed); spindump_assert(consumed < sizeof(buf)); buf[consumed] = 0; // // Print the buffer out // spindump_eventformatter_deliverdata(formatter,strlen(buf),(uint8_t*)buf); }
2
2
2024-11-18T22:22:10.443033+00:00
2021-09-21T12:44:43
81e4f4a5471c480ca532f1f2c16b2c055007ae98
{ "blob_id": "81e4f4a5471c480ca532f1f2c16b2c055007ae98", "branch_name": "refs/heads/main", "committer_date": "2021-09-21T12:44:43", "content_id": "a40348c2b517fc1111a71638d4990ee23149347f", "detected_licenses": [ "MIT" ], "directory_id": "4ba22ac9ff4dbf3b23a5191c6551f93383c188b2", "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": 2898, "license": "MIT", "license_type": "permissive", "path": "/boiler_controller_loop/src/main.c", "provenance": "stackv2-0123.json.gz:15580", "repo_name": "mfkiwl/real-time-systems", "revision_date": "2021-09-21T12:44:43", "revision_id": "7972dd5fdd0d4429d929ac68370b0e5302d03596", "snapshot_id": "a94a2bae386cf594fb3b29d3eef3953be2974a8c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mfkiwl/real-time-systems/7972dd5fdd0d4429d929ac68370b0e5302d03596/boiler_controller_loop/src/main.c", "visit_date": "2023-08-01T06:39:28.214876" }
stackv2
/** * \brief Main loop implementation. * * \date 2021/08/07 * * \addtogroup main * \{ */ #include <stdio.h> #include "controller.h" #include "udp_client.h" #include "timer.h" #include "logger.h" void task_init(void); void task_controller(void); void task_user_info(void); void task_logger_file(void); /* Cycle counter variable to keep track of periodic events */ int cycle; /* Variables to */ float boiler_water_temp, input_water_temp; /* Variables to hold the controller structures for each control loop */ float control_na, control_q, control_ni; /* Boiler controllers initialization */ controller_t na_control; controller_t ni_control; controller_t q_control; void main(void) { task_init(); /* Main loop (cyclic executive) */ while(1) { /* 30ms, each cycle: Periodically run the controllers */ task_controller(); /* 1s, each TICKS_TO_1_SECOND cycles: Periodically prints user information */ if(!(cycle%TICKS_TO_1_SECOND)) { task_user_info(); } /* 30s, after buffer size achieved: Periodically save the logger session */ if((cycle%FILE_BUFFER_SIZE+1) >= FILE_BUFFER_SIZE) { task_logger_file(); } /* Increment cycle counter variable */ cycle++; /* Delay until next system loop cycle (system tick: 30ms) */ timer_delay(SYS_TICK); } } void task_init(void) { /* Boiler controllers initialization */ na_control = controller_init("Na", "temperature", 10.0, 0.0, 500.0, 0.5); ni_control = controller_init("Ni", "temperature", 100.0, 0.0, -500.0, 0.5); q_control = controller_init("Q", "temperature", 1000000.0, 0.0, 10000000.0, 0.5); /* UDP interface initialization */ udp_init(SERVER_ADDRESS, SERVER_PORT); /* Timer initialization */ timer_init(); } void task_controller(void) { /* Start controller response time timer */ logger_set_entry(); /* Get sensor values */ boiler_water_temp = get_sensor(BOILER_WATER_TEMP_SENSOR); input_water_temp = get_sensor(INPUT_SUPPLY_WATER_TEMP_SENSOR); /* Get control action */ control_na = pi_algorithm(&na_control, TEMP_SET_POINT, boiler_water_temp); control_q = pi_algorithm(&q_control, TEMP_SET_POINT, boiler_water_temp); if(input_water_temp < boiler_water_temp){ control_ni = pi_algorithm(&ni_control, TEMP_SET_POINT, boiler_water_temp); } else { control_ni = 0; } /* Set actuators based on the control action */ set_actuator(control_na, INPUT_SUPPLY_HOT_WATER_FLOW_ACTUATOR); set_actuator(control_q, INPUT_HEAT_FLOW_ACTUATOR); set_actuator(control_ni, INPUT_SUPPLY_WATER_FLOW_ACTUATOR); /* Finish controller response time timer */ logger_get_entry(); } void task_user_info(void) { printf("Loop cycle: %d \n", cycle/TICKS_TO_1_SECOND); printf("Boiler water temperature: %f \n", boiler_water_temp); printf("Boiler water height: %f \n", get_sensor(BOILER_WATER_HEIGHT_SENSOR)); } void task_logger_file(void) { logger_save_file(); } /** \} End of main group */
3.03125
3
2024-11-18T22:22:10.508579+00:00
2021-05-12T13:41:36
1917f828c49051babf789073142ad0473a959e63
{ "blob_id": "1917f828c49051babf789073142ad0473a959e63", "branch_name": "refs/heads/main", "committer_date": "2021-05-12T13:41:36", "content_id": "2bc210d9686300d383846af1e3c35e46674b392b", "detected_licenses": [ "MIT" ], "directory_id": "201a6a7c792c25cccfd0865cbadbed7af1a72c56", "extension": "c", "filename": "font.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": 3460, "license": "MIT", "license_type": "permissive", "path": "/src/font.c", "provenance": "stackv2-0123.json.gz:15710", "repo_name": "ShaynaCodes/gameframework2d", "revision_date": "2021-05-12T13:41:36", "revision_id": "67f3b7b305b71e900c8a9186f56a4b50664b1c32", "snapshot_id": "c69e8ebe68923018333415cc891c2491bde6723f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ShaynaCodes/gameframework2d/67f3b7b305b71e900c8a9186f56a4b50664b1c32/src/font.c", "visit_date": "2023-08-21T12:02:46.093759" }
stackv2
#include "simple_logger.h" #include "gf2d_graphics.h" #include "font.h" typedef struct { Font *fontList; Uint32 maxFonts; }FontManager; static FontManager font_manager = { 0 }; void font_delete(Font *font) { if (!font)return; if (font->font != NULL)TTF_CloseFont(font->font); memset(font, 0, sizeof(Font)); } void font_manager_close() { int i; if (font_manager.fontList != NULL) { for (i = 0; i < font_manager.maxFonts; i++) { font_delete(&font_manager.fontList[i]); } } free(font_manager.fontList); memset(&font_manager, 0, sizeof(FontManager)); } void font_init(Uint32 maxFonts) { if (!maxFonts) { slog("cannot allocate for 0 fonts"); return; } if ((!TTF_WasInit()) && (TTF_Init() == -1)) { slog("TTF_Init: %s\n", TTF_GetError()); return; } font_manager_close(); font_manager.maxFonts = maxFonts; font_manager.fontList = (Font *)gfc_allocate_array(sizeof(Font), maxFonts); atexit(font_manager_close); } Font *font_new() { int i; for (i = 0; i < font_manager.maxFonts; i++) { if (font_manager.fontList[i]._refCount == 0) { font_manager.fontList[i]._refCount = 1; return &font_manager.fontList[i]; } } return NULL; } Font *font_get_by_file_point(const char *filename, int ptsize) { int i; for (i = 0; i < font_manager.maxFonts; i++) { if (font_manager.fontList[i]._refCount == 0)continue; if (gfc_line_cmp(font_manager.fontList[i].filename, filename) != 0)continue; if (font_manager.fontList[i].ptsize != ptsize)continue; return &font_manager.fontList[i]; } return NULL; } Font *font_load(const char *filename, int ptsize) { Font *font; font = font_get_by_file_point(filename, ptsize); if (font != NULL) {// we have this in memory already, increase the refCount and return it font->_refCount++; return font; } font = font_new(); if (!font) { slog("we failed to get a new font slot!"); return NULL; } font->ptsize = ptsize; gfc_line_cpy(font->filename, filename); font->font = TTF_OpenFont(filename, ptsize); if (font->font == NULL) { slog("failed to open font %s!, re: %s", filename, TTF_GetError()); font_delete(font); return NULL; } return font; } void font_free(Font * font) { if (!font)return; font->_refCount--; if (font->_refCount == 0)font_delete(font); } void font_render(Font *font, char *text, Vector2D position, Color color) { SDL_Surface *surface; SDL_Texture *texture; SDL_Rect rect; if ((!font) || (!font->font)) { slog("no font provided to render!"); return; } if (!text) { slog("no text provided to render!"); } surface = TTF_RenderText_Blended(font->font, (const char *)text, gfc_color_to_sdl(color)); if (!surface) { slog("failed to render font text %s", text); return; } surface = gf2d_graphics_screen_convert(&surface); if (!surface) { slog("failed to convert rendered text to graphics format: %s", text); return; } texture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surface); if (!texture) { slog("failed to convert surface text to texture %s", text); SDL_FreeSurface(surface); return; } SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); rect = gfc_sdl_rect((Sint32)position.x, (Sint32)position.y, surface->w, surface->h); SDL_UpdateTexture(texture, NULL, surface->pixels, surface->pitch); SDL_RenderCopyEx(gf2d_graphics_get_renderer(), texture, NULL, &rect, 0, NULL, 0); SDL_FreeSurface(surface); SDL_DestroyTexture(texture); }
2.46875
2
2024-11-18T22:22:10.857326+00:00
2020-02-26T16:19:28
f72f71a68d864d5bf8e75aead067600a769daadb
{ "blob_id": "f72f71a68d864d5bf8e75aead067600a769daadb", "branch_name": "refs/heads/master", "committer_date": "2020-02-26T16:19:28", "content_id": "2b50482a53ef698dcf8da6e01fbc75ec6dad1034", "detected_licenses": [ "Unlicense" ], "directory_id": "57f942d0168ee05469c85b92eb7ff8a636641155", "extension": "c", "filename": "oslcal.c", "fork_events_count": 0, "gha_created_at": "2020-03-24T08:52:34", "gha_event_created_at": "2020-03-24T08:52:34", "gha_language": null, "gha_license_id": null, "github_id": 249657353, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7849, "license": "Unlicense", "license_type": "permissive", "path": "/Src/analyzer/window/oslcal.c", "provenance": "stackv2-0123.json.gz:15966", "repo_name": "LZ5ZI/Antenna_Analyzer_EU1KY_var_DH1AKF", "revision_date": "2020-02-26T16:19:28", "revision_id": "4b8929ec148a165bca47894fc8511952b06a27d4", "snapshot_id": "6084b1288624fb234122336bfc0719aeb6fb09c5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LZ5ZI/Antenna_Analyzer_EU1KY_var_DH1AKF/4b8929ec148a165bca47894fc8511952b06a27d4/Src/analyzer/window/oslcal.c", "visit_date": "2021-04-20T05:12:33.313317" }
stackv2
/* * (c) Yury Kuchura * kuchura@gmail.com * * This code can be used on terms of WTFPL Version 2 (http://www.wtfpl.net/). */ #include <stdio.h> #include <string.h> #include "config.h" #include "LCD.h" #include "font.h" #include "touch.h" #include "hit.h" #include "textbox.h" #include "oslfile.h" extern void Sleep(uint32_t); static uint32_t rqExit = 0; static uint32_t shortScanned = 0; static uint32_t loadScanned = 0; static uint32_t openScanned = 0; static char progresstxt[16]; static int progressval; static TEXTBOX_t hbEx; static TEXTBOX_t hbScanShort; static uint32_t hbScanShortIdx; static TEXTBOX_t hbScanOpen; static TEXTBOX_t hbScanLoad; static TEXTBOX_t hbScanProgress; static uint32_t hbScanProgressId; static TEXTBOX_t hbSave; static TEXTBOX_CTX_t osl_ctx = {0}; static int percents = 0; extern volatile uint32_t autosleep_timer; static void _hit_ex(void) { if (shortScanned || openScanned || loadScanned) OSL_Select(OSL_GetSelected()); //Reload OSL file rqExit = 1; } static void progress_cb(uint32_t new_percent) { if (new_percent == progressval || new_percent > 100) return; progressval = new_percent; sprintf(progresstxt, "%u%%", (unsigned int)progressval); TEXTBOX_SetText(&osl_ctx, hbScanProgressId, progresstxt); autosleep_timer = 30000; //CFG_GetParam(CFG_PARAM_LOWPWR_TIME); } static void _hb_scan_short(void) { progressval = 100; progress_cb(0); hbScanShort.bgcolor = LCD_RGB(128, 128, 0); TEXTBOX_DrawContext(&osl_ctx); OSL_ScanShort(progress_cb); shortScanned = 1; hbScanShort.bgcolor = LCD_RGB(0, 128, 0); if (shortScanned && openScanned && loadScanned) hbSave.bgcolor = LCD_RGB(0, 128, 0); progresstxt[0] = '\0'; TEXTBOX_SetText(&osl_ctx, hbScanProgressId, progresstxt); TEXTBOX_DrawContext(&osl_ctx); } static void _hb_scan_open(void) { progressval = 100; progress_cb(0); hbScanOpen.bgcolor = LCD_RGB(128, 128, 0); TEXTBOX_DrawContext(&osl_ctx); OSL_ScanOpen(progress_cb); openScanned = 1; hbScanOpen.bgcolor = LCD_RGB(0, 128, 0); if (shortScanned && openScanned && loadScanned) hbSave.bgcolor = LCD_RGB(0, 128, 0); progresstxt[0] = '\0'; TEXTBOX_SetText(&osl_ctx, hbScanProgressId, progresstxt); TEXTBOX_DrawContext(&osl_ctx); } static void _hb_scan_load(void) { progressval = 100; progress_cb(0); hbScanLoad.bgcolor = LCD_RGB(128, 128, 0); TEXTBOX_DrawContext(&osl_ctx); OSL_ScanLoad(progress_cb); loadScanned = 1; hbScanLoad.bgcolor = LCD_RGB(0, 128, 0); if (shortScanned && openScanned && loadScanned) hbSave.bgcolor = LCD_RGB(0, 128, 0); progresstxt[0] = '\0'; TEXTBOX_SetText(&osl_ctx, hbScanProgressId, progresstxt); TEXTBOX_DrawContext(&osl_ctx); } static void _hit_save(void) { if (!(shortScanned && openScanned && loadScanned)) return; OSL_Calculate(); Sleep(500); rqExit = 1; } //OSL calibration window ********************************************************************************************** void OSL_CalWnd(void) { if (-1 == OSL_GetSelected()) return; rqExit = 0; shortScanned = 0; openScanned = 0; loadScanned = 0; progresstxt[0] = '\0'; LCD_FillAll(LCD_BLACK); while (TOUCH_IsPressed()); FONT_Print(FONT_FRANBIG, LCD_WHITE, LCD_BLACK, 110, 0, "OSL Calibration, file %s", OSL_GetSelectedName()); TEXTBOX_InitContext(&osl_ctx); static char shortvalue[50]; sprintf(shortvalue, " Scan short: %d Ohm ", (int)CFG_GetParam(CFG_PARAM_OSL_RSHORT)); static char loadvalue[50]; sprintf(loadvalue, " Scan load: %d Ohm ", (int)CFG_GetParam(CFG_PARAM_OSL_RLOAD)); static char openvalue[50]; if (CFG_GetParam(CFG_PARAM_OSL_ROPEN) < 10000) sprintf(openvalue, " Scan open: %d Ohm ", (int)CFG_GetParam(CFG_PARAM_OSL_ROPEN)); else strcpy(openvalue, " Scan open: infinite "); hbEx = (TEXTBOX_t){.x0 = 10, .y0 = 220, .text = " Cancel and exit ", .font = FONT_FRANBIG, .fgcolor = LCD_BLUE, .bgcolor = LCD_YELLOW, .cb = _hit_ex }; hbScanShort = (TEXTBOX_t){.x0 = 10, .y0 = 50, .text = shortvalue, .font = FONT_FRANBIG, .fgcolor = LCD_BLUE, .bgcolor = LCD_RGB(64,64,64), .cb = _hb_scan_short }; hbScanLoad = (TEXTBOX_t){.x0 = 10, .y0 = 100, .text = loadvalue, .font = FONT_FRANBIG, .fgcolor = LCD_BLUE, .bgcolor = LCD_RGB(64,64,64), .cb = _hb_scan_load }; hbScanOpen = (TEXTBOX_t){.x0 = 10, .y0 = 150, .text = openvalue, .font = FONT_FRANBIG, .fgcolor = LCD_BLUE, .bgcolor = LCD_RGB(64,64,64), .cb = _hb_scan_open }; hbSave = (TEXTBOX_t){.x0 = 300, .y0 = 220, .text = " Save and exit ", .font = FONT_FRANBIG, .fgcolor = LCD_RGB(128,128,128), .bgcolor = LCD_RGB(64,64,64), .cb = _hit_save }; hbScanProgress = (TEXTBOX_t){.x0 = 350, .y0 = 50, .text = progresstxt, .font = FONT_FRANBIG, .nowait = 1, .fgcolor = LCD_WHITE, .bgcolor = LCD_BLACK }; TEXTBOX_Append(&osl_ctx, &hbEx); TEXTBOX_Append(&osl_ctx, &hbScanShort); TEXTBOX_Append(&osl_ctx, &hbScanLoad); TEXTBOX_Append(&osl_ctx, &hbScanOpen); TEXTBOX_Append(&osl_ctx, &hbSave); hbScanProgressId = TEXTBOX_Append(&osl_ctx, &hbScanProgress); TEXTBOX_DrawContext(&osl_ctx); for(;;) { if (TEXTBOX_HitTest(&osl_ctx)) { if (rqExit) { CFG_Init(); return; } Sleep(50); } autosleep_timer = 30000; //CFG_GetParam(CFG_PARAM_LOWPWR_TIME); Sleep(0); } } static void _hit_err_scan(void) // ************************************************************************ { progressval = 100; progress_cb(0); hbScanShort.bgcolor = LCD_RGB(128, 128, 0); TEXTBOX_DrawContext(&osl_ctx); OSL_ScanErrCorr(progress_cb); hbScanShort.bgcolor = LCD_RGB(0, 128, 0); TEXTBOX_SetText(&osl_ctx, hbScanShortIdx, " Success "); progresstxt[0] = '\0'; TEXTBOX_SetText(&osl_ctx, hbScanProgressId, progresstxt); TEXTBOX_DrawContext(&osl_ctx); } //Hardware error calibration window ********************************************************************** void OSL_CalErrCorr(void) { rqExit = 0; shortScanned = 0; //To prevent OSL file reloading at exit openScanned = 0; //To prevent OSL file reloading at exit loadScanned = 0; //To prevent OSL file reloading at exit progresstxt[0] = '\0'; LCD_FillAll(LCD_BLACK); while (TOUCH_IsPressed()); FONT_Write(FONT_FRANBIG, LCD_WHITE, LCD_BLACK, 80, 0, "HW Error Correction Calibration"); FONT_Write(FONT_FRAN, LCD_RED, LCD_BLACK, 0, 50, "Set jumper to HW calibration position and hit Start button"); TEXTBOX_InitContext(&osl_ctx); TEXTBOX_t hbEx = {.x0 = 10, .y0 = 220, .text = " Exit ", .font = FONT_FRANBIG, .fgcolor = LCD_BLUE, .bgcolor = LCD_YELLOW, .cb = _hit_ex }; TEXTBOX_Append(&osl_ctx, &hbEx); //Reusing hbScanShort hbScanShort = (TEXTBOX_t){.x0 = 100, .y0 = 120, .text = " Start HW calibration ", .font = FONT_FRANBIG, .fgcolor = LCD_RED, .bgcolor = LCD_RGB(64, 64, 64), .cb = _hit_err_scan }; hbScanShortIdx = TEXTBOX_Append(&osl_ctx, &hbScanShort); hbScanProgress = (TEXTBOX_t){.x0 = 350, .y0 = 50, .text = progresstxt, .font = FONT_FRANBIG, .nowait = 1, .fgcolor = LCD_WHITE, .bgcolor = LCD_BLACK }; hbScanProgressId = TEXTBOX_Append(&osl_ctx, &hbScanProgress); TEXTBOX_DrawContext(&osl_ctx); for(;;) { if (TEXTBOX_HitTest(&osl_ctx)) { if (rqExit) return; Sleep(50); } Sleep(0); } }
2.140625
2
2024-11-18T22:22:10.921513+00:00
2017-04-10T16:18:54
fade911e85327155909f5a17c45bc9585f8ed2d4
{ "blob_id": "fade911e85327155909f5a17c45bc9585f8ed2d4", "branch_name": "refs/heads/master", "committer_date": "2017-04-12T17:19:14", "content_id": "02ddcbec32a33af7973a786ee30b9a5bcc1e0556", "detected_licenses": [ "MIT" ], "directory_id": "1de3d0f95ec8a0725f00ad36db7bb86f9d250a12", "extension": "c", "filename": "network_disconnect.c", "fork_events_count": 1, "gha_created_at": "2017-04-11T20:26:24", "gha_event_created_at": "2017-04-11T20:26:24", "gha_language": null, "gha_license_id": null, "github_id": 87976353, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1806, "license": "MIT", "license_type": "permissive", "path": "/network_e2e/tests/iothubclient_badnetwork_e2e/network_disconnect.c", "provenance": "stackv2-0123.json.gz:16095", "repo_name": "thyssenkruppElevator/azure-iot-sdk-c", "revision_date": "2017-04-10T16:18:54", "revision_id": "d6bea25dade6bbc4a1b15f4b5edaead95dcf2475", "snapshot_id": "f264072381a7c5eb18d0f718901a60caa37d9ff5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/thyssenkruppElevator/azure-iot-sdk-c/d6bea25dade6bbc4a1b15f4b5edaead95dcf2475/network_e2e/tests/iothubclient_badnetwork_e2e/network_disconnect.c", "visit_date": "2021-01-19T11:34:19.745382" }
stackv2
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #ifdef __cplusplus #include <cstdlib> #else #include <stdlib.h> #endif #include "testrunnerswitcher.h" #include "network_disconnect.h" extern const char *g_host; int network_disconnect() { int result = __FAILURE__; printf("**** disconnecting from network ****\n"); #if defined(WIN32) // TODO #elif defined(__linux__) result = system("docker network disconnect YoYoNet ${HOSTNAME}"); if (result != 0) { printf("docker network disconnect returned %d\n",result); } bool connected = is_network_connected(); ASSERT_IS_FALSE_WITH_MSG(connected, "ping succeeded even though we should be disconnected"); #else ASSERT_FAIL("Network disconnect not implemented on this OS\n"); #endif return result; } int network_reconnect() { int result = __FAILURE__; printf("**** connecting to network ****\n"); #if defined(WIN32) // TODO #elif defined(__linux__) result = system("docker network connect YoYoNet ${HOSTNAME}"); if (result != 0) { printf("docker network connect returned %d\n",result); } bool connected = is_network_connected(); ASSERT_IS_TRUE_WITH_MSG(connected, "ping failed even though we should be connected"); #else ASSERT_FAIL("Network connecting not implemented on this OS\n"); #endif return result; } bool is_network_connected() { bool connected = true; #if defined(WIN32) // TODO #elif defined(__linux__) int result = system("ping -c 1 www.microsoft.com"); if (result != 0) { connected = false; } #else ASSERT_FAIL("Network connecting not implemented on this OS\n"); #endif return connected; }
2.296875
2
2024-11-18T22:22:11.105293+00:00
2019-12-07T12:32:09
068dbc402c88774fc4fdb6a4dd582dd19a276a94
{ "blob_id": "068dbc402c88774fc4fdb6a4dd582dd19a276a94", "branch_name": "refs/heads/master", "committer_date": "2019-12-07T12:32:09", "content_id": "538b1a88f3406bd743158e63e39f90d6b087f50a", "detected_licenses": [ "MIT" ], "directory_id": "e7c79409a8e936c1913f7c2a73f7f55e5d3fc5e4", "extension": "c", "filename": "BST.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": 7592, "license": "MIT", "license_type": "permissive", "path": "/ED1 2019-2/AVL/BST.c", "provenance": "stackv2-0123.json.gz:16353", "repo_name": "manifaco/Repositorio-Geral", "revision_date": "2019-12-07T12:32:09", "revision_id": "27aac0093fadb3f76766a57fe11a9c7a6ed86e2d", "snapshot_id": "7ecf7f8e0c4f46f58d27c72c1202a368a4c839f8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/manifaco/Repositorio-Geral/27aac0093fadb3f76766a57fe11a9c7a6ed86e2d/ED1 2019-2/AVL/BST.c", "visit_date": "2020-09-30T06:11:06.308010" }
stackv2
#include "BST.h" info* createInfoKey(int value) { info* newInfo = (info*)calloc(1, sizeof(info)); if (!newInfo) return newInfo; newInfo->value = value; return newInfo; } key* createKey(info inf) { key* newKey = (key*)calloc(1, sizeof(key)); if (!newKey) return newKey; newKey->info = createInfoKey(inf.value); newKey->left = NULL; newKey->right = NULL; if (!newKey->info) return newKey; newKey->info->value = inf.value; return newKey; } key* leftBST(key* key) { return key->left; } key* rightBST(key* key) { return key->right; } void listPreOrder(key* bst, node** first, node** last) { if (!bst) return; if (bst) { *first = insertE(bst->info->value , *first, last); } listPreOrder(bst->left, first, last); listPreOrder(bst->right, first, last); } key* rebuildTree(node** preListFirst, node* inListFirst, node** preListLast, node** inListLast) { if(!(*preListFirst)) return NULL; if(!(*preListFirst) && !inListFirst) return NULL; node* aux = inListFirst, * aux2 = NULL; info inf; inf.value = (*preListFirst)->info->value; key* newKey = createKey(inf); if(inListFirst && inListFirst->info->value == (*preListFirst)->info->value){ (*preListFirst) = (*preListFirst)->next; return newKey; } if (aux) if (aux->next) while (aux->next->info->value != (*preListFirst)->info->value) { aux = aux->next; } (*preListFirst) = (*preListFirst)->next; aux2 = aux->next; if(aux2) if(aux2->next) aux2 = aux2->next; aux->next = NULL; newKey->left = rebuildTree(preListFirst, inListFirst, preListLast, inListLast); newKey->right = rebuildTree(preListFirst,aux2, preListLast, inListLast); return newKey; } void listInOrder(key* bst, node** first, node** last) { if (!bst) return; listInOrder(bst->left, first, last); if (bst) { *first = insertE(bst->info->value, *first, last); } listInOrder(bst->right, first, last); } void listPosOrder(key* bst, node** first, node** last) { if (!bst) return; listPosOrder(bst->left, first, last); listPosOrder(bst->right, first, last); if (bst) { *first = insertE(bst->info->value, *first, last); } } void printPreOrder(key* bst) { if (!bst) return; printf("[%i] \n", bst->info->value); printPreOrder(bst->left); printPreOrder(bst->right); } int nFolhas(key* bst) { static int i=0; if (!bst) return 0; if(!bst->right && !bst->left) i++; nFolhas(bst->left); nFolhas(bst->right); return i; } void printInOrder(key* bst) { if (!bst) return; printInOrder(bst->left); printf("[%i] \n", bst->info->value); printInOrder(bst->right); } void printPosOrder(key* bst) { if (!bst) return; printPosOrder(bst->left); printPosOrder(bst->right); printf("[%i] \n", bst->info->value); } void fixBalance(key* avl) { if (!avl) return; int hLeft = heightBST(avl->left), hRight = heightBST(avl->right); avl->balance = hLeft - hRight; fixBalance(avl->left); fixBalance(avl->right); } key* RRRotation(key* pivot) { key* aux = pivot->right; pivot->right = pivot->right->right; aux->right = pivot->right->left; pivot->right->left = aux; fixBalance(pivot); } key* LLRotation(key* pivot){ key* aux = pivot->left; pivot->left = pivot->left->left; aux->left = pivot->left->right; pivot->left->right = aux; fixBalance(pivot); } key* LRRotation(key* pivot) { key* aux = pivot; pivot = pivot->left->right; pivot->right = aux; pivot->left = aux->left; aux->left->right = aux->left->right->right; aux->left = NULL; fixBalance(pivot); } key* RLRotation(key* pivot) { key* aux = pivot; pivot = pivot->right->left; pivot->left = aux; pivot->right = aux->right; aux->right->left = aux->right->left->left; aux->right = NULL; fixBalance(pivot); } int insertBST(key** bst, info info) { int insert = 0; int side = 0; static int succes = 0; key** bst2; key* newKey = createKey(info); if (!newKey) return 0; if (!(newKey->info)) return 0; if (!(*bst)) { *bst = newKey; succes = 1; return 1; } if ((*bst)->info->value < newKey->info->value) {//caso da direita insert = insertBST(&((*bst)->right), info); if ((*bst)->balance <= 0 && succes) grow = 1; if (succes) {//caso do no Pai if ((*bst)->balance > 0) (*bst)->balance -= 1; } if (grow) side = 1; } if ((*bst)->info->value > newKey->info->value) {//caso da esquerda insert = insertBST(&((*bst)->left), info); if ((*bst)->balance >= 0 && succes) grow = 1; if (succes) {//caso do no Pai if ((*bst)->balance < 0) (*bst)->balance += 1; } if (grow) side = 2; } if (side == 1) (*bst)->balance -= 1; if (side == 2) (*bst)->balance += 1; succes = 0; if ((*bst)->balance > 1 || (*bst)->balance < -1) balanceAVL(*bst); return insert; } key* balanceAVL(key* avl) { while(avl->balance > 1 || avl->balance < -1){ if (avl->balance > 1) { if (avl->left->balance > 1) avl = LLRotation(avl); else avl = LRRotation(avl); } if (avl->balance < 1) { if (avl->left->balance < 1) avl = RRRotation(avl); else avl = RLRotation(avl); } } } /* se balanco >1 ou menor q <1 : se(filho da esquerda tem filho pela esquerda){ } */ key* searchBST(key* bst, info info) { if (!bst) return NULL; if (bst->info->value == info.value) return bst; if (bst->info->value < info.value) return searchBST(bst->right, info); if (bst->info->value > info.value) return searchBST(bst->left, info); } int searchBSTFather(key* bst, info info, key** father) { if (!bst) return -1; if (bst->info->value == info.value) return 0; if (!bst->left && !bst->right) return 0; if (bst->right && bst->right->info->value == info.value) { *father = bst; return 1;//1 = filho a direita } if (bst->left && bst->left->info->value == info.value) { *father = bst; return 2;// 2 = filho a esquerda } if (bst->info->value < info.value) return searchBSTFather(bst->right, info, father); if (bst->info->value > info.value) return searchBSTFather(bst->left, info, father); } key* smaller(key* bst) { if (!bst) return NULL; if (!bst->left) return bst; if (bst->left) return smaller(bst->left); } key* larger(key* bst) { if (!bst) return NULL; if (!bst->right) return bst; if (bst->right) return smaller(bst->left); } int heightBST(key* bst) { int height = 0, left = 0, right = 0; if (!bst) return 0; left = 1 + heightBST(bst->left); right = 1 + heightBST(bst->right); height = left > right ? left : right; return height; } key* removeCurrent(key* bst, key* current) { key* aux, * aux2; aux = current; //Os casos de remocao dessa implementacao trabalham juntos. if (!aux->left) { aux2 = current->right; free(aux); return aux2; } aux2 = current->left; if (aux2) while (aux2->right) { aux = aux2; aux2 = aux2->right; } if (aux != current) { aux->right = aux2->left; aux2->left = current->left; } if (aux2) aux2->right = current->right; free(current); return aux2; } int removeBST(key** bst, info info) { key* father = NULL, * current = (*bst), * subTree = NULL; int side; if (!(*bst)) return 0; side = searchBSTFather((*bst), info, &father); if (side == -1) return 0; if (side == 1) if (father) current = father->right; if (side == 2) if (father) current = father->left; subTree = removeCurrent((*bst), current); if (side && father) { //Se o pai nao existir significa que a arvore possui apenas um no, que e a propria raiz if (side == 2) father->left = subTree; else father->right = subTree; } else (*bst) = subTree; return 1; } void printBST(key* bst) { static int i; int j; if (!bst) { return; } printf("Key:[%i]\n", bst->info->value); printf("Balance:[%i]", bst->balance); puts(""); printBST(bst->left); printBST(bst->right); }
3.125
3
2024-11-18T22:22:11.313495+00:00
2019-12-05T06:28:59
5e8a925ea45fa1395d4912083cf69952f625fd81
{ "blob_id": "5e8a925ea45fa1395d4912083cf69952f625fd81", "branch_name": "refs/heads/master", "committer_date": "2019-12-05T06:28:59", "content_id": "995dce794f954f17023592f7439ffecf3caf9cfd", "detected_licenses": [ "Apache-2.0" ], "directory_id": "42dc54936911979dabbd3308d4c6901ffe95c82d", "extension": "h", "filename": "xbee_packet_parser.h", "fork_events_count": 0, "gha_created_at": "2019-10-03T08:18:31", "gha_event_created_at": "2019-10-03T08:18:32", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 212529089, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1199, "license": "Apache-2.0", "license_type": "permissive", "path": "/lab_104/1_rtos_xbee_rx_and_tx_parsing/inc/xbee_packet_parser.h", "provenance": "stackv2-0123.json.gz:16612", "repo_name": "mayo231/embedded-computer-networks", "revision_date": "2019-12-05T06:28:59", "revision_id": "a97b4d0f45712438da16c86a3af3f94fe32d334a", "snapshot_id": "9ad1f2abef5d5eaec316b154aa9d079ee960ab54", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mayo231/embedded-computer-networks/a97b4d0f45712438da16c86a3af3f94fe32d334a/lab_104/1_rtos_xbee_rx_and_tx_parsing/inc/xbee_packet_parser.h", "visit_date": "2022-02-27T06:59:58.735190" }
stackv2
/* * xbee_packet_parser.h * * this is where we take the data stream from the xbee and actually extract the * data into packets (using the xbee state machine) * * author: Alex Shenfield * date: 10/11/2017 */ // define to prevent recursive inclusion #ifndef __XBEE_PARSER_H #define __XBEE_PARSER_H // include the basic headers #include "stm32f7xx.h" // if we've not defined RING_SIZE elsewhere ... #ifndef RING_SIZE // make the buffer size 1024 (buffer sizes that are a power of two make code // much more efficient as compilers can optimise better) #define RING_SIZE 1024 #endif // define a uart buffer type that implements a ring buffer implementation // of a fifo queue to store sent and received data typedef struct { uint8_t data[RING_SIZE]; uint16_t ring_head; uint16_t ring_tail; uint16_t num_bytes; } buffer_typedef; // states for the xbee parser typedef enum state { INIT, PACKETLENGTH_HI, PACKETLENGTH_LO, DATAFIELD, CHECKSUM, COMPLETE } parse_state; // // global methods: // void init_parser(void); int xbee_parse_packet(uint8_t c); void get_packet(uint8_t * packet_buffer); void xbee_send_packet(uint8_t * packet, int length); #endif // XBEE_PARSER_H
2.40625
2
2024-11-18T22:22:11.598681+00:00
2018-04-02T18:44:41
27e648a59ee983349af999b45410f9a3c59e0555
{ "blob_id": "27e648a59ee983349af999b45410f9a3c59e0555", "branch_name": "refs/heads/master", "committer_date": "2018-04-02T18:44:41", "content_id": "c0b15b605fe1f47442ea6c732ba5888b43a7d6e2", "detected_licenses": [ "MIT" ], "directory_id": "bae8a5e4b4c4bf0c2a020c4f5db0b726f72913e7", "extension": "c", "filename": "w_io.c", "fork_events_count": 1, "gha_created_at": "2017-10-14T14:40:35", "gha_event_created_at": "2018-04-06T22:15:09", "gha_language": "C", "gha_license_id": null, "github_id": 106935446, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2105, "license": "MIT", "license_type": "permissive", "path": "/src/io/w_io.c", "provenance": "stackv2-0123.json.gz:16869", "repo_name": "vaporstack/wsh", "revision_date": "2018-04-02T18:44:41", "revision_id": "f5aedeb24d535dcb8bd80d6faa3b247cb226cb4c", "snapshot_id": "c935d82b8e93024852f7d6789bc12968ef47125c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/vaporstack/wsh/f5aedeb24d535dcb8bd80d6faa3b247cb226cb4c/src/io/w_io.c", "visit_date": "2022-02-12T14:17:27.623268" }
stackv2
// // r_io.c // r4 // // Created by vs on 2/17/17. // Copyright © 2017 vaporstack. All rights reserved. // #include "w_io.h" #include <stdlib.h> #include <stdio.h> #include <string.h> // TODO unify the various stupid file reading functions void* w_read_file_as_bin(const char* path, long* len) { FILE* fileptr; // char *buffer; // long filelen; long l; fileptr = fopen(path, "rb"); // Open the file in binary mode if (!fileptr) { return NULL; } fseek(fileptr, 0, SEEK_END); // Jump to the end of the file l = ftell(fileptr); // Get the current byte offset in the file rewind(fileptr); // Jump back to the beginning of the file printf("%lu\n", *len); long sz = (l + 1) * sizeof(char); void* buf = malloc(sz); // Enough memory for file + \0 memset(buf, 0, sz); fread(buf, l, 1, fileptr); // Read in the entire file fclose(fileptr); // Close the file *len = l; return 0; } const char* w_read_file_as_text(const char* path) { FILE* f; f = fopen(path, "r"); if (!f) { char buf[256]; sprintf(buf, "Failed to open file: %s\n", path); printf("%s\n", buf); return NULL; } fseek(f, 0, SEEK_END); long fsize = ftell(f); fseek(f, 0, SEEK_SET); // same as rewind(f); char* data = malloc(fsize + 1); fread(data, fsize, 1, f); fclose(f); data[fsize] = 0; return data; } char* w_read_file_as_text_nc(const char* path) { FILE* f; f = fopen(path, "r"); if (!f) { char buf[256]; sprintf(buf, "Failed to open file: %s\n", path); printf("%s\n", buf); return NULL; } fseek(f, 0, SEEK_END); long fsize = ftell(f); fseek(f, 0, SEEK_SET); // same as rewind(f); char* data = malloc(fsize + 1); fread(data, fsize, 1, f); fclose(f); data[fsize] = 0; return data; } int w_write_text_to_file(const char* path, const char* data) { FILE* f; f = fopen(path, "w"); if (!data) { printf("Data was null!\n"); return 1; } if (!f) { char buf[256]; sprintf(buf, "Failed to open file: %s\n", path); printf("%s\n", buf); // printf("Failed to open file: %s\n", path); return 1; } fprintf(f, "%s", data); fclose(f); return 0; }
2.765625
3
2024-11-18T22:22:12.534053+00:00
2020-04-02T15:04:05
e9aff162f1575a69fc1273aaa9176859ef990ef4
{ "blob_id": "e9aff162f1575a69fc1273aaa9176859ef990ef4", "branch_name": "refs/heads/master", "committer_date": "2020-04-02T15:04:05", "content_id": "6baa2862035637da7eaf6af87b3c7d6c2a0bda63", "detected_licenses": [ "BSD-3-Clause", "ISC" ], "directory_id": "ce101360c51550a85cf90d0ef52428b1da6d690c", "extension": "c", "filename": "serie_int32.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 245434672, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5975, "license": "BSD-3-Clause,ISC", "license_type": "permissive", "path": "/src/serie_int32.c", "provenance": "stackv2-0123.json.gz:17515", "repo_name": "murilobsd/capybara", "revision_date": "2020-04-02T15:04:05", "revision_id": "68753a4698dd50cd85313ac99cf8d6cc7497479e", "snapshot_id": "14617e378cf20d043f5bd1d418db6bbcda115994", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/murilobsd/capybara/68753a4698dd50cd85313ac99cf8d6cc7497479e/src/serie_int32.c", "visit_date": "2021-02-24T15:30:18.988616" }
stackv2
/* * Copyright (c) 2019 Murilo Ijanc' <mbsd@m0x.ru> * * 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 THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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. */ #include <err.h> #include <math.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "capybara/serie_int32.h" #include "capybara/utils.h" #define SERIE ((struct serie_int32_impl *)s) #define N(x) (sizeof(x) / sizeof(x[0])) /* implementation */ struct serie_int32_impl { serie_int32_ops *ops; /* internal */ char *name; int32_t *data; size_t size; size_t capacity; }; static const char *set_name(serie_int32_t *, const char *); static char *get_name(serie_int32_t *); static void free_serie(serie_int32_t *); static cap_error_t resize(struct serie_int32_impl *); static cap_error_t add(serie_int32_t *, int32_t); static size_t size(serie_int32_t *); static int32_t *get(serie_int32_t *, size_t); static int set(serie_int32_t *, size_t, int32_t); static int delete(serie_int32_t *, size_t); static int32_t *min(serie_int32_t *); static int32_t *max(serie_int32_t *); static double mean(serie_int32_t *); static long double sum(serie_int32_t *); static double variance(serie_int32_t *); static double std_dev(serie_int32_t *); static void sort(serie_int32_t *); static int cmp(const void *, const void *); static double median(serie_int32_t *); static serie_int32_ops int32_ops = { set_name, get_name, free_serie, add, size, get, set, delete, min, max, mean, sum, variance, std_dev, sort, median, }; static double median(serie_int32_t *s) { double median = 0.0; const size_t sz = size(s); const size_t lhs = (sz - 1) / 2 ; const size_t rhs = sz / 2 ; if (sz == 0) return 0.0; sort(s); if (lhs == rhs) median = (double)*get(s, lhs); else median = (double)((*get(s, lhs) + *get(s, rhs)) / 2.0); return median; } static void sort(serie_int32_t *s) { const size_t sz = size(s); const size_t szint = sizeof(int32_t); qsort(SERIE->data, sz, szint, cmp); } static int cmp(const void *a, const void *b) { const int32_t *ia = (const int32_t *)a; const int32_t *ib = (const int32_t *)b; return *ia - *ib; } static double std_dev(serie_int32_t *s) { const double vr = variance(s); const double s_dev = sqrt(vr); return s_dev; } static double variance(serie_int32_t *s) { size_t i; double variance = 0; const size_t sz = size(s); int32_t *x; long double delta = 0; const double mn = mean(s); if (sz == 0) return (0); for (i = 0; i < sz; i++) { x = get(s, i); delta = (long double)*x - mn; variance += (delta * delta - variance) / (i + 1); } return variance; } static long double sum(serie_int32_t *s) { size_t i; long double sum = 0; const size_t sz = size(s); int32_t *x; if (sz == 0) return (0); for (i = 0; i < sz; i++) { x = get(s, i); sum += (long double)*x; } return sum; } static double mean(serie_int32_t *s) { size_t i; double mean = 0; const size_t sz = size(s); int32_t *x; if (sz == 0) return (0); for (i = 0; i < sz; i++) { x = get(s, i); mean += ((double)*x - mean) / (i + 1); } return mean; } static int32_t * max(serie_int32_t *s) { size_t i; int32_t *max; int32_t *x; const size_t sz = size(s); if (sz == 0) return (0); max = get(s, 0); for (i = 0; i < sz; i++) { x = get(s, i); if (*x > *max) max = x; } return max; } static int32_t * min(serie_int32_t *s) { size_t i; int32_t *min; int32_t *x; const size_t sz = size(s); if (sz == 0) return (0); min = get(s, 0); for (i = 0; i < sz; i++) { x = get(s, i); if (*x < *min) min = x; } return min; } static int delete(serie_int32_t *s, size_t index) { memmove(&SERIE->data[index], &SERIE->data[index+1], SERIE->size - index - 1); SERIE->size--; return (0); } static int set(serie_int32_t *s, size_t index, int32_t v) { SERIE->data[index] = v; return (0); } static int32_t * get(serie_int32_t *s, size_t index) { return &SERIE->data[index]; } static size_t size(serie_int32_t *s) { return SERIE->size; } static cap_error_t resize(struct serie_int32_impl *s) { int32_t *data; size_t nsize; /* new size */ nsize = SERIE->size * 2; /* first time size = 0 */ if (nsize == 0) nsize = 4; /* TODO: check xrealloc return */ data = xrealloc(SERIE->data, nsize + sizeof(int32_t)); SERIE->data = data; SERIE->capacity = nsize; return (CAPY_ERROR_OK); } static cap_error_t add(serie_int32_t *s, int32_t v) { cap_error_t err; if (SERIE->size == SERIE->capacity) if ((err = resize(SERIE)) != CAPY_ERROR_OK) { free_serie(s); return err; } SERIE->data[SERIE->size++] = v; return (CAPY_ERROR_OK); } static void free_serie(serie_int32_t *s) { if (SERIE == NULL) return; if (SERIE->name != NULL) free(SERIE->name); if (SERIE->data != NULL) free(SERIE->data); free(SERIE); } static char * get_name(serie_int32_t *s) { return SERIE->name; } static const char * set_name(serie_int32_t *s, const char *name) { char *n; if (name == NULL) { SERIE->name = NULL; return NULL; } n = xstrdup(name); SERIE->name = n; return NULL; } serie_int32_t * serie_int32_new(void) { struct serie_int32_impl *s; s = xcalloc(1, sizeof(struct serie_int32_impl)); s->ops = &int32_ops; return (serie_int32_t *)s; }
2.484375
2
2024-11-18T22:22:12.710257+00:00
2018-04-26T15:07:45
602b04a3f6df24e9c0ad504bee9496bcffdc7ca8
{ "blob_id": "602b04a3f6df24e9c0ad504bee9496bcffdc7ca8", "branch_name": "refs/heads/master", "committer_date": "2018-04-26T15:07:45", "content_id": "b37e8a19665f839b3dcc464af4984f528bd5cafb", "detected_licenses": [ "MIT" ], "directory_id": "5342f11d6e76c780793985e21f040968170b3566", "extension": "c", "filename": "BodyStaging.c", "fork_events_count": 0, "gha_created_at": "2018-04-26T14:32:58", "gha_event_created_at": "2018-04-26T14:32:59", "gha_language": null, "gha_license_id": "MIT", "github_id": 131168416, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1447, "license": "MIT", "license_type": "permissive", "path": "/scripts/3_Game/tools/Component/BodyStaging.c", "provenance": "stackv2-0123.json.gz:17643", "repo_name": "Da0ne/DayZCommunityOfflineMode", "revision_date": "2018-04-26T15:07:45", "revision_id": "77ebd221a877270e704c75bcc529a7b97c918f2e", "snapshot_id": "31b4ee298f754fb49788a8e39dcf51c672e542cc", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Da0ne/DayZCommunityOfflineMode/77ebd221a877270e704c75bcc529a7b97c918f2e/scripts/3_Game/tools/Component/BodyStaging.c", "visit_date": "2020-03-13T14:57:50.786995" }
stackv2
//----------------------------- // BODY STAGING //----------------------------- /* Every dead body will have this component which will control its various states. Read "Dead bodies staging" design on Confluence. */ class ComponentBodyStaging : Component { bool m_IsSkinned; void ComponentBodyStaging() { m_IsSkinned = false; } void ~ComponentBodyStaging() { } void SetAsSkinned() { m_IsSkinned = true; // Temporal! Body is moved into ground so we can see if it was already skinned or not until necesarry assets are developed. /* if ( !m_ThisEntityAI.IsKindOf("Animal_GallusGallusDomesticus") && !m_ThisEntityAI.IsKindOf("Animal_GallusGallusDomesticusF") ) { vector body_new_pos = m_ThisEntityAI.GetPosition() - "0 0.2 0"; m_ThisEntityAI.SetPosition(body_new_pos); } else { vector body_new_pos2 = m_ThisEntityAI.GetPosition() - "0 0.08 0"; m_ThisEntityAI.SetPosition(body_new_pos2); } */ SynchSkinnedState(); } bool IsSkinned() { return m_IsSkinned; } void SetAsSkinnedClient() { m_IsSkinned = true; } /*==================================== SERVER --> CLIENT SYNCHRONIZATION ====================================*/ // Synchronizes properties protected void SynchSkinnedState() { if ( GetGame().IsServer() ) { Param1<bool> p = new Param1<bool>( IsSkinned() ); GetGame().RPCSingleParam( m_ThisEntityAI, ERPCs.RPC_BS_SKINNED_STATE, p, true ); } } }
2.015625
2
2024-11-18T22:22:12.973939+00:00
2018-06-27T09:21:54
5c063e2b507b4f46d184a9e8015b349e52c8b033
{ "blob_id": "5c063e2b507b4f46d184a9e8015b349e52c8b033", "branch_name": "refs/heads/master", "committer_date": "2018-06-27T09:21:54", "content_id": "75f1b1e704653b6c7043b3c3bcb56dd38e77c619", "detected_licenses": [ "MIT" ], "directory_id": "0b90d18bf8e2000d3c47a17f3403be51b4a8ecd8", "extension": "c", "filename": "getcols.c", "fork_events_count": 0, "gha_created_at": "2020-01-13T20:09:13", "gha_event_created_at": "2020-01-13T20:09:14", "gha_language": null, "gha_license_id": null, "github_id": 233683375, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10243, "license": "MIT", "license_type": "permissive", "path": "/src/Externals/vispack/packages/fits/getcols.c", "provenance": "stackv2-0123.json.gz:17901", "repo_name": "merced317/scirun4plus", "revision_date": "2018-06-27T09:21:54", "revision_id": "f29630e03d3cf13c0ce8b327676ad202e3981af0", "snapshot_id": "c3d8d65dd68f9d119b43cf084ea8b9d94921ce33", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/merced317/scirun4plus/f29630e03d3cf13c0ce8b327676ad202e3981af0/src/Externals/vispack/packages/fits/getcols.c", "visit_date": "2020-12-10T19:20:18.401161" }
stackv2
/* This file, getcols.c, contains routines that read data elements from */ /* a FITS image or table, with a character string datatype. */ /* The FITSIO software was written by William Pence at the High Energy */ /* Astrophysic Science Archive Research Center (HEASARC) at the NASA */ /* Goddard Space Flight Center. Users shall not, without prior written */ /* permission of the U.S. Government, establish a claim to statutory */ /* copyright. The Government and others acting on its behalf, shall have */ /* a royalty-free, non-exclusive, irrevocable, worldwide license for */ /* Government purposes to publish, distribute, translate, copy, exhibit, */ /* and perform such material. */ #include <stdlib.h> #include <string.h> #include "fitsio2.h" /*--------------------------------------------------------------------------*/ int ffgcvs( fitsfile *fptr, /* I - FITS file pointer */ int colnum, /* I - number of column to read (1 = 1st col) */ long firstrow, /* I - first row to read (1 = 1st row) */ long firstelem, /* I - first vector element to read (1 = 1st) */ long nelem, /* I - number of strings to read */ char *nulval, /* I - string for null pixels */ char **array, /* O - array of values that are read */ int *anynul, /* O - set to 1 if any values are null; else 0 */ int *status) /* IO - error status */ /* Read an array of string values from a column in the current FITS HDU. Any undefined pixels will be set equal to the value of 'nulval' unless nulval = null in which case no checks for undefined pixels will be made. */ { char cdummy[2]; ffgcls(fptr, colnum, firstrow, firstelem, nelem, 1, nulval, array, cdummy, anynul, status); return(*status); } /*--------------------------------------------------------------------------*/ int ffgcfs( fitsfile *fptr, /* I - FITS file pointer */ int colnum, /* I - number of column to write (1 = 1st col) */ long firstrow, /* I - first row to write (1 = 1st row) */ long firstelem, /* I - first vector element to write (1 = 1st) */ long nelem, /* I - number of strings to write */ char **array, /* O - array of values that are read */ char *nularray, /* O - array of flags = 1 if nultyp = 2 */ int *anynul, /* O - set to 1 if any values are null; else 0 */ int *status) /* IO - error status */ /* Read an array of string values from a column in the current FITS HDU. Nularray will be set = 1 if the corresponding array pixel is undefined, otherwise nularray will = 0. */ { char dummy[2]; ffgcls(fptr, colnum, firstrow, firstelem, nelem, 2, dummy, array, nularray, anynul, status); return(*status); } /*--------------------------------------------------------------------------*/ int ffgcls( fitsfile *fptr, /* I - FITS file pointer */ int colnum, /* I - number of column to write (1 = 1st col) */ long firstrow, /* I - first row to write (1 = 1st row) */ long firstelem, /* I - first vector element to write (1 = 1st) */ long nelem, /* I - number of strings to write */ int nultyp, /* I - null value handling code: */ /* 1: set undefined pixels = nulval */ /* 2: set nularray=1 for undefined pixels */ char *nulval, /* I - value for null pixels if nultyp = 1 */ char **array, /* O - array of values that are read */ char *nularray, /* O - array of flags = 1 if nultyp = 2 */ int *anynul, /* O - set to 1 if any values are null; else 0 */ int *status) /* IO - error status */ /* Read an array of string values from a column in the current FITS HDU. */ { size_t nullen; int tcode, maxelem, hdutype, nulcheck; long twidth, offset, incre, repeat, rowlen, rownum, elemnum; long ii, jj, ntodo, tnull, startpos, readptr, remain, next; double scale, zero; char tform[20]; char message[FLEN_ERRMSG]; char snull[20]; /* the FITS null value */ tcolumn *colptr; double cbuff[DBUFFSIZE / sizeof(double)]; /* align cbuff on word boundary */ char *buffer, *arrayptr; if (*status > 0) /* inherit input status value if > 0 */ return(*status); *anynul = 0; if (nultyp == 2) memset(nularray, 0, nelem); /* initialize nullarray */ /*---------------------------------------------------*/ /* Check input and get parameters about the column: */ /*---------------------------------------------------*/ if (colnum < 1 || colnum > fptr->tfield) { sprintf(message, "Specified column number is out of range: %d", colnum); ffpmsg(message); return(*status = BAD_COL_NUM); } colptr = fptr->tableptr; /* point to first column */ colptr += (colnum - 1); /* offset to correct column structure */ tcode = colptr->tdatatype; if (tcode == -TSTRING) /* variable length column in a binary table? */ { /* only read a single string; ignore value of firstelem */ if (ffgcpr( fptr, colnum, firstrow, 1, 1, 0, &scale, &zero, tform, &twidth, &tcode, &maxelem, &startpos, &elemnum, &incre, &repeat, &rowlen, &hdutype, &tnull, snull, status) > 0) return(*status); remain = 1; twidth = repeat; } else if (tcode == TSTRING) { if (ffgcpr( fptr, colnum, firstrow, firstelem, nelem, 0, &scale, &zero, tform, &twidth, &tcode, &maxelem, &startpos, &elemnum, &incre, &repeat, &rowlen, &hdutype, &tnull, snull, status) > 0) return(*status); remain = nelem; } else return(*status = NOT_ASCII_COL); nullen = strlen(snull); /* length of the undefined pixel string */ if (nullen == 0) nullen = 1; /*------------------------------------------------------------------*/ /* Decide whether to check for null values in the input FITS file: */ /*------------------------------------------------------------------*/ nulcheck = nultyp; /* by default check for null values in the FITS file */ if (nultyp == 1 && nulval[0] == 0) nulcheck = 0; /* calling routine does not want to check for nulls */ else if (snull[0] == ASCII_NULL_UNDEFINED) nulcheck = 0; /* null value string in ASCII table not defined */ else if (nullen > twidth) nulcheck = 0; /* null value string is longer than width of column */ /* thus impossible for any column elements to = null */ /*---------------------------------------------------------------------*/ /* Now read the strings one at a time from the FITS column. */ /*---------------------------------------------------------------------*/ next = 0; /* next element in array to be read */ rownum = 0; /* row number, relative to firstrow */ while (remain) { /* limit the number of pixels to process a one time to the number that will fit in the buffer space or to the number of pixels that remain in the current vector, which ever is smaller. */ ntodo = minvalue(remain, maxelem); ntodo = minvalue(ntodo, (repeat - elemnum)); readptr = startpos + (rownum * rowlen) + (elemnum * incre); ffmbyt(fptr, readptr, REPORT_EOF, status); /* move to read position */ /* read the array of strings from the FITS file into the buffer */ if (incre == twidth) ffgbyt(fptr, ntodo * twidth, cbuff, status); else ffgbytoff(fptr, twidth, ntodo, incre - twidth, cbuff, status); /* copy from the buffer into the user's array of strings */ /* work backwards from last char of last string to 1st char of 1st */ buffer = ((char *) cbuff) + (ntodo * twidth) - 1; for (ii = next + ntodo - 1; ii >= next; ii--) { arrayptr = array[ii] + twidth - 1; for (jj = twidth - 1; jj > 0; jj--) /* ignore trailing blanks */ { if (*buffer == ' ') { buffer--; arrayptr--; } else break; } *(arrayptr + 1) = 0; /* write the string terminator */ for (; jj >= 0; jj--) /* copy the string itself */ { *arrayptr = *buffer; buffer--; arrayptr--; } /* check if null value is defined, and if the */ /* column string is identical to the null string */ if (nulcheck && !strncmp(snull, array[ii], nullen) ) { *anynul = 1; /* this is a null value */ if (nultyp == 1) strcpy(array[ii], nulval); else nularray[ii] = 1; } } if (*status > 0) /* test for error during previous read operation */ { sprintf(message, "Error reading elements %ld thru %ld of data array (ffpcls).", next+1, next+ntodo); ffpmsg(message); return(*status); } /*--------------------------------------------*/ /* increment the counters for the next loop */ /*--------------------------------------------*/ next += ntodo; remain -= ntodo; if (remain) { elemnum += ntodo; if (elemnum == repeat) /* completed a row; start on next row */ { elemnum = 0; rownum++; } } } /* End of main while Loop */ return(*status); }
2.296875
2
2024-11-18T22:22:13.556697+00:00
2023-07-02T17:43:25
04e72316f07efa1827453e0c13223b3e36898def
{ "blob_id": "04e72316f07efa1827453e0c13223b3e36898def", "branch_name": "refs/heads/master", "committer_date": "2023-07-28T13:26:17", "content_id": "45cb6b5ff7e7f591fc8eca9819ffc5b98c11ac61", "detected_licenses": [ "BSD-3-Clause", "CC0-1.0", "MIT" ], "directory_id": "538c0655fc1fe95e6211b0faabb24457ebb762c3", "extension": "c", "filename": "main.c", "fork_events_count": 90, "gha_created_at": "2015-12-22T10:43:15", "gha_event_created_at": "2023-08-11T08:15:37", "gha_language": "C", "gha_license_id": null, "github_id": 48426404, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7763, "license": "BSD-3-Clause,CC0-1.0,MIT", "license_type": "permissive", "path": "/samples/gamma-fade/main.c", "provenance": "stackv2-0123.json.gz:18032", "repo_name": "XboxDev/nxdk", "revision_date": "2023-07-02T17:43:25", "revision_id": "e955705ad7e5f59cdad456d0bd6680083d03758f", "snapshot_id": "9151adf0450915335bfd6e1aec72c4adf0f82a2a", "src_encoding": "UTF-8", "star_events_count": 311, "url": "https://raw.githubusercontent.com/XboxDev/nxdk/e955705ad7e5f59cdad456d0bd6680083d03758f/samples/gamma-fade/main.c", "visit_date": "2023-09-01T19:37:29.013295" }
stackv2
#include <stdint.h> #include <stdbool.h> #include <string.h> #include <math.h> #include <hal/video.h> #include <hal/debug.h> #include <windows.h> static float remap(float in_low, float in_high, float out_low, float out_high, float value) { /* [in_low; in_high] */ value -= in_low; /* [0.0; in_high-in_low] */ value /= in_high - in_low; /* [0.0; 1.0] */ value *= out_high - out_low; /* [0.0; out_high-out_low] */ value += out_low; /* [out_low; out_high] */ return value; } /* This is also known as `lerp(a, b, t)` */ static float mix(float a, float b, float t) { return a * (1.0f - t) + b * t; } /* This is also known as `mix(0.0, 1.0, x)` */ static float linear(float x) { return x; } /* This is also known as `smoothstep(0.0, 1.0, x)` */ static float smooth(float x) { return x * x * (3.0f - 2.0f * x); } static void set_mix_fade(float red, float green, float blue, float t) { GAMMA_RAMP_ENTRY entries[256]; for(int i = 0; i < 256; i++) { float f = i / (float)0xFF; entries[i].red = 0xFF * mix(f, red, t); entries[i].green = 0xFF * mix(f, green, t); entries[i].blue = 0xFF * mix(f, blue, t); } XVideoSetGammaRamp(0, entries, 256); } static void set_cinematic_fade(float a_black_input, float a_white_input, float a_black_output, float a_white_output, float b_black_input, float b_white_input, float b_black_output, float b_white_output, float t) { GAMMA_RAMP_ENTRY entries[256]; for(int i = 0; i < 256; i++) { float f = i / (float)0xFF; /* Interpolate the input and output levels */ float black_input = mix(a_black_input, b_black_input, t); float white_input = mix(a_white_input, b_white_input, t); float black_output = mix(a_black_output, b_black_output, t); float white_output = mix(a_white_output, b_white_output, t); /* Remap our brightness */ if (f < black_input) { f = black_input; } if (f > white_input) { f = white_input; } f = remap(black_input, white_input, black_output, white_output, f); if (f < black_output) { f = black_output; } if (f > white_output) { f = white_output; } entries[i].red = 0xFF * f; entries[i].green = 0xFF * f; entries[i].blue = 0xFF * f; } XVideoSetGammaRamp(0, entries, 256); } static float animate_frame(DWORD ts_start, DWORD ts, float duration) { /* Wait for the next frame */ XVideoWaitForVBlank(); /* Update timestamp */ DWORD ts_delta = ts - ts_start; float t = remap(0.0f, duration, 0.0f, 1.0f, ts_delta); /* Signal completion */ if (t >= 1.0f) { return 1.0f; } /* Return time in range [0.0; 1.0[ */ return t; } static void do_mix_fade(float red, float green, float blue, float(*interpolator)(float), float duration) { DWORD ts_start; float t; /* Fade to color */ ts_start = GetTickCount(); do { t = animate_frame(ts_start, GetTickCount(), duration / 2.0f); set_mix_fade(red, green, blue, interpolator(t)); } while(t < 1.0f); /* Fade to image */ ts_start = GetTickCount(); do { t = animate_frame(ts_start, GetTickCount(), duration / 2.0f); set_mix_fade(red, green, blue, interpolator(1.0f - t)); } while(t < 1.0f); } static void do_cinematic_fade(float a_black_input, float a_white_input, float a_black_output, float a_white_output, float b_black_input, float b_white_input, float b_black_output, float b_white_output, float(*interpolator)(float), float duration) { DWORD ts_start; float t; /* Fade to color */ ts_start = GetTickCount(); do { t = animate_frame(ts_start, GetTickCount(), duration / 2.0f); set_cinematic_fade(a_black_input, a_white_input, a_black_output, a_white_output, b_black_input, b_white_input, b_black_output, b_white_output, interpolator(t)); } while(t < 1.0f); /* Fade to image */ ts_start = GetTickCount(); do { t = animate_frame(ts_start, GetTickCount(), duration / 2.0f); set_cinematic_fade(a_black_input, a_white_input, a_black_output, a_white_output, b_black_input, b_white_input, b_black_output, b_white_output, interpolator(1.0f - t)); } while(t < 1.0f); } static void draw_title(const char* title) { extern int nextCol; extern int nextRow; nextCol = 25; nextRow = 25; debugPrint("%s", title); for(int i = strlen(title); i < 60; i++) { debugPrint(" "); } } int main(void) { float duration = 2000.0f; XVideoSetMode(640, 480, 32, REFRESH_DEFAULT); /* Create test image in framebuffer */ volatile uint32_t *rgbx = (uint32_t*)XVideoGetFB(); for(unsigned int y = 0; y < 480; y++) { unsigned int stripe = y / (480/3); /* Border left */ for(unsigned int x = 0; x < (640-512)/2; x++) { *rgbx++ = 0x808080; } /* 512 pixels gradient */ for(unsigned int x = 0; x < 256; x++) { *rgbx++ = x << (16 - stripe * 8); *rgbx++ = x << (16 - stripe * 8); } /* Border right */ for(unsigned int x = 0; x < (640-512)/2; x++) { *rgbx++ = 0x808080; } } while(1) { draw_title("Mix fade to black (Linear)"); do_mix_fade(0.0f, 0.0f, 0.0f, linear, duration); Sleep(1000); draw_title("Mix fade to black (Smooth)"); do_mix_fade(0.0f, 0.0f, 0.0f, smooth, duration); Sleep(1000); draw_title("Mix fade to white (Linear)"); do_mix_fade(1.0f, 1.0f, 1.0f, linear, duration); Sleep(1000); draw_title("Mix fade to white (Smooth)"); do_mix_fade(1.0f, 1.0f, 1.0f, smooth, duration); Sleep(1000); draw_title("Mix fade to pink (Linear)"); do_mix_fade(1.0f, 0.0f, 1.0f, linear, duration); Sleep(1000); draw_title("Mix fade to pink (Smooth)"); do_mix_fade(1.0f, 0.0f, 1.0f, smooth, duration); Sleep(1000); draw_title("Cinematic fade to black (Linear)"); do_cinematic_fade(0.0f, 1.0f, 0.0f, 1.0f, 0.7f, 1.0f, 0.0f, 0.0f, linear, duration); Sleep(1000); draw_title("Cinematic fade to black (Smooth)"); do_cinematic_fade(0.0f, 1.0f, 0.0f, 1.0f, 0.7f, 1.0f, 0.0f, 0.0f, smooth, duration); Sleep(1000); draw_title("Cinematic fade to white (Linear)"); do_cinematic_fade(0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.3f, 1.0f, 1.0f, linear, duration); Sleep(1000); draw_title("Cinematic fade to white (Smooth)"); do_cinematic_fade(0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.3f, 1.0f, 1.0f, smooth, duration); Sleep(1000); } /* Unreachable */ return 0; }
2.828125
3
2024-11-18T22:22:13.803323+00:00
2022-07-07T15:06:55
fbd5fc949e4f82399c48188344f87587cbba7dc7
{ "blob_id": "fbd5fc949e4f82399c48188344f87587cbba7dc7", "branch_name": "refs/heads/master", "committer_date": "2022-07-07T15:06:55", "content_id": "75f3d9f977a0e4b3e9211fa2996cb71ecf69d37d", "detected_licenses": [ "MIT" ], "directory_id": "5f79ecc086b9612ee41087a8a64121dc7c83dae7", "extension": "c", "filename": "ft_printf_hex.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 226744592, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1345, "license": "MIT", "license_type": "permissive", "path": "/libraries/FT_SimpleSDL/libft/ft_printf/ft_printf_hex.c", "provenance": "stackv2-0123.json.gz:18288", "repo_name": "KernelOverseer/KSICARDOOM", "revision_date": "2022-07-07T15:06:55", "revision_id": "63c1eaa3cc32c0021e138bc1af19e845aea94369", "snapshot_id": "ec3edc10880f0d8f92c17b3ad3baa832d503e8a1", "src_encoding": "UTF-8", "star_events_count": 55, "url": "https://raw.githubusercontent.com/KernelOverseer/KSICARDOOM/63c1eaa3cc32c0021e138bc1af19e845aea94369/libraries/FT_SimpleSDL/libft/ft_printf/ft_printf_hex.c", "visit_date": "2022-07-23T03:40:06.714901" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf_hex.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: abiri <kerneloverseer@protonmail> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/07 19:44:35 by abiri #+# #+# */ /* Updated: 2018/11/07 21:09:16 by abiri ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" char *ft_puthex(long long nb, t_print *data) { if (ft_strchr(data->arg, 'b')) return (ft_itob((unsigned int)nb, BINARY)); if (ft_strchr(data->flags, '#') && ft_strchr(data->flags, '0') && !(ft_strchr(data->flags, '-'))) data->fieldw -= 2; if (ft_strequ(data->arg, "x")) return (ft_itob((unsigned int)nb, HEX)); if (ft_strchr(data->arg, 'X')) return (ft_itob((unsigned int)nb, HEX2)); return (ft_itob(nb, HEX)); }
2.59375
3
2024-11-18T22:22:14.068296+00:00
2013-04-25T18:26:49
a4ab9f4a2f4d25665c8ba9e36d7795a628c2fad7
{ "blob_id": "a4ab9f4a2f4d25665c8ba9e36d7795a628c2fad7", "branch_name": "refs/heads/master", "committer_date": "2013-04-25T18:26:49", "content_id": "c768af854559764773903ad54771d6125a4228b3", "detected_licenses": [ "Apache-2.0" ], "directory_id": "db41112ad8cc9c8e63e4114d724c365a4c77e6be", "extension": "c", "filename": "cmonary.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": 17662, "license": "Apache-2.0", "license_type": "permissive", "path": "/monary/cmonary.c", "provenance": "stackv2-0123.json.gz:18545", "repo_name": "kvaggelakos/monary", "revision_date": "2013-04-25T18:26:49", "revision_id": "2b8ff49cbb608d99ae33c09cb9ab974ebe543dae", "snapshot_id": "30943fdbf7f9ade1957ab06b5c73203073c2cc3d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kvaggelakos/monary/2b8ff49cbb608d99ae33c09cb9ab974ebe543dae/monary/cmonary.c", "visit_date": "2021-05-27T20:13:38.604986" }
stackv2
// Monary - Copyright 2011-2013 David J. C. Beach // Please see the included LICENSE.TXT and NOTICE.TXT for licensing information. #include <stdlib.h> #include <stdio.h> #include <string.h> #include "mongo.h" #include "bson.h" #ifndef NDEBUG #define DEBUG(format, ...) \ fprintf(stderr, "[DEBUG] %s:%i " format "\n", __FILE__, __LINE__, ##__VA_ARGS__) #else #define DEBUG(...) #endif #define DEFAULT_MONGO_HOST "127.0.0.1" #define DEFAULT_MONGO_PORT 27017 enum { TYPE_UNDEFINED = 0, TYPE_OBJECTID = 1, TYPE_BOOL = 2, TYPE_INT8 = 3, TYPE_INT16 = 4, TYPE_INT32 = 5, TYPE_INT64 = 6, TYPE_UINT8 = 7, TYPE_UINT16 = 8, TYPE_UINT32 = 9, TYPE_UINT64 = 10, TYPE_FLOAT32 = 11, TYPE_FLOAT64 = 12, TYPE_DATE = 13, // BSON date (uint64 storage) TYPE_TIMESTAMP = 14, // BSON timestamp (uint64 storage) TYPE_STRING = 15, // each record is (type_arg) chars in length TYPE_BINARY = 16, // each record is (type_arg) bytes in length TYPE_BSON = 17, // get BSON (sub-)document as binary (each record is type_arg bytes) TYPE_TYPE = 18, // BSON type code (uint8 storage) TYPE_SIZE = 19, // data size of a string, symbol, binary, or bson object (uint32) TYPE_LENGTH = 20, // length of string (character count) or num elements in BSON (uint32) LAST_TYPE = 20, }; typedef bson_oid_t OBJECTID; #ifndef WIN32 typedef char BOOL; typedef char INT8; #endif typedef short INT16; typedef int INT32; typedef int64_t INT64; typedef unsigned char UINT8; typedef unsigned short UINT16; typedef unsigned int UINT32; typedef uint64_t UINT64; typedef float FLOAT32; typedef double FLOAT64; mongo_connection* monary_connect(const char* host, int port) { if(host == NULL) { host = DEFAULT_MONGO_HOST; } if(port == 0) { port = DEFAULT_MONGO_PORT; } mongo_connection* conn = (mongo_connection*) malloc(sizeof(mongo_connection)); DEBUG("attempting connection to: '%s' port %i", options.host, options.port); mongo_conn_return conn_result = mongo_connect(conn, host, port); if(conn_result == mongo_conn_success) { DEBUG("connected successfully"); return conn; } else { DEBUG("received mongo_connect error code: %i\n", conn_result); return NULL; } } int monary_authenticate(mongo_connection* connection, const char* db, const char* user, const char* pass) { return mongo_cmd_authenticate(connection, db, user, pass); } void monary_disconnect(mongo_connection* connection) { mongo_destroy(connection); } typedef struct monary_column_item monary_column_item; struct monary_column_item { char* field; unsigned int type; unsigned int type_arg; void* storage; unsigned char* mask; }; typedef struct monary_column_data { unsigned int num_columns; unsigned int num_rows; monary_column_item* columns; } monary_column_data; typedef struct monary_cursor { mongo_cursor* mcursor; monary_column_data* coldata; } monary_cursor; monary_column_data* monary_alloc_column_data(unsigned int num_columns, unsigned int num_rows) { if(num_columns > 1024) { return NULL; } monary_column_data* result = (monary_column_data*) malloc(sizeof(monary_column_data)); monary_column_item* columns = (monary_column_item*) calloc(num_columns, sizeof(monary_column_item)); result->num_columns = num_columns; result->num_rows = num_rows; result->columns = columns; return result; } int monary_free_column_data(monary_column_data* coldata) { if(coldata == NULL || coldata->columns == NULL) { return 0; } for(int i = 0; i < coldata->num_columns; i++) { monary_column_item* col = coldata->columns + i; if(col->field != NULL) { free(col->field); } } free(coldata->columns); free(coldata); return 1; } int monary_set_column_item(monary_column_data* coldata, unsigned int colnum, const char* field, unsigned int type, unsigned int type_arg, void* storage, unsigned char* mask) { if(coldata == NULL) { return 0; } if(colnum >= coldata->num_columns) { return 0; } if(type == TYPE_UNDEFINED || type > LAST_TYPE) { return 0; } if(storage == NULL) { return 0; } if(mask == NULL) { return 0; } int len = strlen(field); if(len > 1024) { return 0; } monary_column_item* col = coldata->columns + colnum; col->field = (char*) malloc(len + 1); strcpy(col->field, field); col->type = type; col->type_arg = type_arg; col->storage = storage; col->mask = mask; return 1; } inline int monary_load_objectid_value(bson_iterator* bsonit, bson_type type, monary_column_item* citem, int idx) { if(type == bson_oid) { OBJECTID* oid = bson_iterator_oid(bsonit); OBJECTID* oidloc = ((OBJECTID*) citem->storage) + idx; oidloc->ints[0] = oid->ints[0]; oidloc->ints[1] = oid->ints[1]; oidloc->ints[2] = oid->ints[2]; return 1; } else { return 0; } } inline int monary_load_bool_value(bson_iterator* bsonit, bson_type type, monary_column_item* citem, int idx) { BOOL value = bson_iterator_bool(bsonit); ((BOOL*) citem->storage)[idx] = value; return 1; } #define MONARY_DEFINE_NUM_LOADER(FUNCNAME, NUMTYPE, BSONFUNC) \ inline int FUNCNAME (bson_iterator* bsonit, \ bson_type type, \ monary_column_item* citem, \ int idx) \ { \ if(type == bson_int || type == bson_long || type == bson_double) { \ NUMTYPE value = BSONFUNC(bsonit); \ ((NUMTYPE*)citem->storage)[idx] = value; \ return 1; \ } else { \ return 0; \ } \ } MONARY_DEFINE_NUM_LOADER(monary_load_int8_value, INT8, bson_iterator_int) MONARY_DEFINE_NUM_LOADER(monary_load_int16_value, INT16, bson_iterator_int) MONARY_DEFINE_NUM_LOADER(monary_load_int32_value, INT32, bson_iterator_int) MONARY_DEFINE_NUM_LOADER(monary_load_int64_value, INT64, bson_iterator_long) MONARY_DEFINE_NUM_LOADER(monary_load_uint8_value, UINT8, bson_iterator_int) MONARY_DEFINE_NUM_LOADER(monary_load_uint16_value, UINT16, bson_iterator_int) MONARY_DEFINE_NUM_LOADER(monary_load_uint32_value, UINT32, bson_iterator_int) MONARY_DEFINE_NUM_LOADER(monary_load_uint64_value, UINT64, bson_iterator_long) MONARY_DEFINE_NUM_LOADER(monary_load_float32_value, FLOAT32, bson_iterator_double) MONARY_DEFINE_NUM_LOADER(monary_load_float64_value, FLOAT64, bson_iterator_double) inline int monary_load_date_value(bson_iterator* bsonit, bson_type type, monary_column_item* citem, int idx) { if(type == bson_date) { bson_date_t value = bson_iterator_date(bsonit); ((UINT64*) citem->storage)[idx] = value; return 1; } else { return 0; } } inline int monary_load_timestamp_value(bson_iterator* bsonit, bson_type type, monary_column_item* citem, int idx) { if(type == bson_timestamp) { bson_timestamp_t value = bson_iterator_timestamp(bsonit); ((UINT64*) citem->storage)[idx] = *((INT64*) &value); return 1; } else { return 0; } } inline int monary_load_string_value(bson_iterator* bsonit, bson_type type, monary_column_item* citem, int idx) { if(type == bson_string || type == bson_symbol || type == bson_code) { size_t size = citem->type_arg; const char* src = bson_iterator_string(bsonit); char* dest = ((char*) citem->storage) + (idx * size); strncpy(dest, src, size); return 1; } else { return 0; } } inline int monary_load_binary_value(bson_iterator* bsonit, bson_type type, monary_column_item* citem, int idx) { if(type == bson_bindata) { int size = citem->type_arg; int binlen = bson_iterator_bin_len(bsonit); if(binlen > size) { binlen = size; } const char* src = bson_iterator_bin_data(bsonit); char* dest = ((char*) citem->storage) + (idx * size); memcpy(dest, src, binlen); return 1; } else { return 0; } } inline int monary_load_bson_value(bson_iterator* bsonit, bson_type type, monary_column_item* citem, int idx) { if(type == bson_object || type == bson_array) { bson subobj; bson_iterator_subobject(bsonit, &subobj); int size = citem->type_arg; int binlen = bson_size(&subobj); if(binlen > size) { binlen = size; } char* src = subobj.data; char* dest = ((char*) citem->storage) + (idx * size); memcpy(dest, src, binlen); return 1; } else { return 0; } } inline int monary_load_type_value(bson_iterator* bsonit, bson_type type, monary_column_item* citem, int idx) { ((UINT8*) citem->storage)[idx] = type; return 1; } inline int monary_load_size_value(bson_iterator* bsonit, bson_type type, monary_column_item* citem, int idx) { UINT32 size = 0; if(type == bson_string || type == bson_code || type == bson_symbol) { // NOTE: Binary size of string includes terminating '\0' character. size = bson_iterator_string_len(bsonit); } else if(type == bson_bindata) { size = bson_iterator_bin_len(bsonit); } else if(type == bson_array || type == bson_object) { bson subobj; bson_iterator_subobject(bsonit, &subobj); size = bson_size(&subobj); } else { return 0; } ((UINT32*) citem->storage)[idx] = size; return 1; } inline int monary_load_length_value(bson_iterator* bsonit, bson_type type, monary_column_item* citem, int idx) { UINT32 length = 0; if(type == bson_string || type == bson_code || type == bson_symbol) { // The length of the string is the character count. Since the string // is UTF-8 encoded, we must count characters appropriately... const char* s = bson_iterator_string(bsonit); length = mbstowcs(NULL, s, 0); } else if(type == bson_array || type == bson_object) { // The length of a BSON object is the number of elements (i.e. key-value pairs) // it contains. We count these by iterating over the elements. bson_iterator subiter; bson_iterator_subiterator(bsonit, &subiter); while(bson_iterator_next(&subiter) != 0) { ++length; } } else { // Other objects are not considered to have a length. return 0; } ((UINT32*) citem->storage)[idx] = length; return 1; } #define MONARY_DISPATCH_TYPE(TYPENAME, TYPEFUNC) \ case TYPENAME: \ success = TYPEFUNC(bsonit, type, citem, offset); \ break; int monary_load_item(bson_iterator* bsonit, bson_type type, monary_column_item* citem, int offset) { int success = 0; switch(citem->type) { MONARY_DISPATCH_TYPE(TYPE_OBJECTID, monary_load_objectid_value) MONARY_DISPATCH_TYPE(TYPE_BOOL, monary_load_bool_value) MONARY_DISPATCH_TYPE(TYPE_INT8, monary_load_int8_value) MONARY_DISPATCH_TYPE(TYPE_INT16, monary_load_int16_value) MONARY_DISPATCH_TYPE(TYPE_INT32, monary_load_int32_value) MONARY_DISPATCH_TYPE(TYPE_INT64, monary_load_int64_value) MONARY_DISPATCH_TYPE(TYPE_UINT8, monary_load_uint8_value) MONARY_DISPATCH_TYPE(TYPE_UINT16, monary_load_uint16_value) MONARY_DISPATCH_TYPE(TYPE_UINT32, monary_load_uint32_value) MONARY_DISPATCH_TYPE(TYPE_UINT64, monary_load_uint64_value) MONARY_DISPATCH_TYPE(TYPE_FLOAT32, monary_load_float32_value) MONARY_DISPATCH_TYPE(TYPE_FLOAT64, monary_load_float64_value) MONARY_DISPATCH_TYPE(TYPE_DATE, monary_load_date_value) MONARY_DISPATCH_TYPE(TYPE_TIMESTAMP, monary_load_timestamp_value) MONARY_DISPATCH_TYPE(TYPE_STRING, monary_load_string_value) MONARY_DISPATCH_TYPE(TYPE_BINARY, monary_load_binary_value) MONARY_DISPATCH_TYPE(TYPE_BSON, monary_load_bson_value) MONARY_DISPATCH_TYPE(TYPE_TYPE, monary_load_type_value) MONARY_DISPATCH_TYPE(TYPE_SIZE, monary_load_size_value) MONARY_DISPATCH_TYPE(TYPE_LENGTH, monary_load_length_value) } return success; } int monary_bson_to_arrays(monary_column_data* coldata, unsigned int row, bson* bson_data) { int num_masked = 0; bson_iterator bsonit; for(int i = 0; i < coldata->num_columns; i++) { monary_column_item* citem = coldata->columns + i; bson_type found_type = bson_find(&bsonit, bson_data, citem->field); int success = 0; int offset = row; // dispatch to appropriate column handler (inlined) if(found_type) { success = monary_load_item(&bsonit, found_type, citem, offset); } // record success result in mask, if applicable if(citem->mask != NULL) { citem->mask[offset] = !success; } // tally number of masked (unsuccessful) loads if(!success) { ++num_masked; } } return num_masked; } long monary_query_count(mongo_connection* connection, const char* db_name, const char* coll_name, const char* query) { // build BSON query data bson query_bson; bson_init(&query_bson, (char*) query, 0); long total_count = mongo_count(connection, db_name, coll_name, &query_bson); bson_destroy(&query_bson); return total_count; } void monary_get_bson_fields_list(monary_column_data* coldata, bson* fields_bson) { bson_buffer fields_builder; bson_buffer_init(&fields_builder); for(int i = 0; i < coldata->num_columns; i++) { monary_column_item* col = coldata->columns + i; bson_append_int(&fields_builder, col->field, 1); } bson_from_buffer(fields_bson, &fields_builder); } monary_cursor* monary_init_query(mongo_connection* connection, const char* ns, const char* query, int limit, int offset, monary_column_data* coldata, int select_fields) { // build BSON query data bson query_bson; bson_init(&query_bson, (char*) query, 0); // build BSON fields list (if necessary) bson query_fields; if(select_fields) { monary_get_bson_fields_list(coldata, &query_fields); } // create query cursor bson* fields_ptr = select_fields ? &query_fields : NULL; mongo_cursor* mcursor = mongo_find(connection, ns, &query_bson, fields_ptr, limit, offset, 0); // destroy BSON fields bson_destroy(&query_bson); if(select_fields) { bson_destroy(&query_fields); } monary_cursor* cursor = (monary_cursor*) malloc(sizeof(monary_cursor)); cursor->mcursor = mcursor; cursor->coldata = coldata; return cursor; } int monary_load_query(monary_cursor* cursor) { mongo_cursor* mcursor = cursor->mcursor; monary_column_data* coldata = cursor->coldata; // read result values int row = 0; int num_masked = 0; while(row < coldata->num_rows && mongo_cursor_next(mcursor)) { #ifndef NDEBUG if(row % 500000 == 0) { DEBUG("...%i rows loaded", row); } #endif num_masked += monary_bson_to_arrays(coldata, row, &(mcursor->current)); ++row; } int total_values = row * coldata->num_columns; DEBUG("%i rows loaded; %i / %i values were masked", row, num_masked, total_values); return row; } void monary_close_query(monary_cursor* cursor) { mongo_cursor_destroy(cursor->mcursor); free(cursor); }
2.21875
2
2024-11-18T22:22:14.367660+00:00
2018-11-27T08:31:33
f6951b82d5a8d9b92ca08dd3b0fb8615a590168d
{ "blob_id": "f6951b82d5a8d9b92ca08dd3b0fb8615a590168d", "branch_name": "refs/heads/master", "committer_date": "2018-11-27T08:31:33", "content_id": "78f841df051d6b53814b12115ca6f6b546fee619", "detected_licenses": [ "MIT" ], "directory_id": "c2cb646ff55c1617f8a16c6620126737881a0acc", "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": 159300929, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6678, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0123.json.gz:18675", "repo_name": "grypesc/C-database", "revision_date": "2018-11-27T08:31:33", "revision_id": "d3e7255890d0954f79228485f6366a1db1091c53", "snapshot_id": "c47a78deaed445d8d3309ae89c9e52c0585b0179", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/grypesc/C-database/d3e7255890d0954f79228485f6366a1db1091c53/main.c", "visit_date": "2020-04-08T11:18:32.252676" }
stackv2
#include "main.h" #include "zapis_odczyt.h" #include "edycja.h" #include "sortowanie.h" ///////////////////////////////////////////////// void wypisz_rekord (int numer, struct t_pole_listy *aktualny) { if(numer>=10) printf("%d. " , numer); else printf(" %d. " , numer); int i=0; while((aktualny->imie)[i]!=' ') { printf("%c", (aktualny->imie)[i]); i++; } for(i=MAX_IMIE-i+2;i>=1;i--) printf(" "); while((aktualny->nazwisko)[i]!=' ') { printf("%c", (aktualny->nazwisko)[i]); i++; } for(i=MAX_NAZWISKO-i+2;i>=1;i--) printf(" "); while((aktualny->ugrupowanie)[i]!=' ') { printf("%c", (aktualny->ugrupowanie)[i]); i++; } for(i=MAX_UGRUPOWANIE-i+2;i>=1;i--) printf(" "); while((aktualny->liczba_glosow)[i]!=' ') { printf("%c", (aktualny->liczba_glosow)[i]); i++; } for(i=MAX_LICZBA_GLOSOW-i+2;i>=1;i--) printf(" "); while((aktualny->wiek)[i]!=' ') { printf("%c", (aktualny->wiek)[i]); i++; } for(i=MAX_WIEK-i+2;i>=1;i--) printf(" "); while((aktualny->okreg_wyborczy)[i]!=' ') { printf("%c", (aktualny->okreg_wyborczy)[i]); i++; } for(i=MAX_OKREG_WYBORCZY-i+2;i>=1;i--) printf(" "); printf("\n"); } void wypisz_baze () { if (liczba_wierszy_bazy==0) { puts("Baza jest pusta"); return;} puts("Imie Nazwisko Ugrupowanie Liczba glosow Wiek Okreg wyborczy\n"); struct t_pole_listy *aktualny; int i=1; for (aktualny=poczatek; aktualny!=NULL; aktualny=aktualny->nastepny) { wypisz_rekord(i, aktualny); i++; } puts(""); } int pobierz_komende() { char pom; int i=0; while(1) { scanf("%c", &pom); if (pom=='\n') { komenda[i]='\0'; return 0; } if (i>=MAX_KOMENDA) return -1; komenda[i]=pom; i++; } } void czysc_ekran() { printf("\033[2J"); printf("\033[0;0f"); } int main() { int pom; liczba_wierszy_bazy=0; poczatek=NULL; czysc_ekran(); puts("Grzegorz Rypesc Grupa 2\nProjekt nr 3\nDynamiczna baza danych - Lista Wyborcza"); wczytaj_ugrupowanie(); //////////////////////////////////////////////////////////////////////////// while(1) { if(pobierz_komende()==-1) while(getchar()!='\n'); //////////////////////////////////////////////////////////////////////////// if(strcmp(komenda, "pomoc" )==0) { czysc_ekran(); puts("Dostepne komendy:\n\nwczytaj zapisz\ndodaj usun edytuj\nsortuj wyczysc\nwyswietl rozmiar\nwyjdz\n"); continue; } //////////////////////////////////////////////////////////////////////////// if(strcmp(komenda, "wczytaj" )==0) { puts("Podaj sciezke do pliku txt zawierajacego nowa baze, stara baza zostanie wymazana z pamieci"); pobierz_komende(); wczytaj_baze(komenda)?puts("Pliku nie udalo sie otworzyc, lub zawiera on niepoprawne dane."), wyczysc():puts("Baze wczytano pomyslnie"); continue; } /////////////////////////////////////////////////////////////////////////// if(strcmp(komenda, "wyswietl")==0) { czysc_ekran(); wypisz_baze(); continue; } /////////////////////////////////////////////////////////////////////////// if(strcmp(komenda, "usun")==0) { puts("Podaj numer rekordu, ktory chcesz usunac"); if (scanf("%d", &pom)==1 && usun_rekord(pom)==0) puts("Rekord usuniety"); else puts ("Wprowadzono zla liczbe"); while(getchar()!='\n'); continue; } //////////////////////////////////////////////////////////////////////////// if(strcmp(komenda, "wyjdz")==0) return 0; //////////////////////////////////////////////////////////////////////////// if(strcmp(komenda, "wyczysc")==0) { wyczysc(); puts ("Baza usunieta z pamieci"); continue; } //////////////////////////////////////////////////////////////////////////// if(strcmp(komenda, "rozmiar")==0) { printf("Baza ma %d rekordow\n", liczba_wierszy_bazy); continue; } //////////////////////////////////////////////////////////////////////////// if(strcmp(komenda, "dodaj")==0) { puts("Wpisz tresc rekordu"); if(dodaj_rekord()==0) puts("Wiersz dodany do bazy"); else puts ("Podany wiersz nie jest poprawny i nie zostal dodany do bazy"); continue; } ///////////////////////////////////////////////////////////////////////////// if(strcmp(komenda, "sortuj")==0) { puts("Wpisz wg. jakiego klucza chcesz posortowac rekordy"); if(pobierz_komende()==-1) { while(getchar()!='\n'); puts("Podano zly ciag znakow"); continue; } if(posortuj(komenda)==0) puts("Baze posortowano"); if(posortuj(komenda)==-1) puts("Podana komenda nie jest kluczem"); if(posortuj(komenda)==-2) puts("Baza jest pusta, nie mozna posortowac"); continue; } ///////////////////////////////////////////////////////////////////////////// if(strcmp(komenda, "edytuj")==0) { puts("Ktory rekord chcesz edytowac?"); if(scanf ("%d", &pom)!=1) { while(getchar()!='\n'); puts("Podano zly numer"); continue; } while(getchar()!='\n'); puts("Ktore pole?"); if(pobierz_komende()==-1) { while(getchar()!='\n'); puts ("Podane pole nie istnieje, rekord nie zostanie zmieniony"); } else { switch(edytuj_rekord(komenda, pom)) { case 0: puts("Rekord zostal zmieniony"); break; case 1: puts("Nowe ugrupowanie dodane"); break; case -1: puts("Podano zly ciag znakow"); break; case -2: puts("Podane pole nie istnieje"); break; case 2: puts("Ugrupowanie usuniete"); break; case -10: puts("Baza jest pusta. Nie mozna edytowac"); break; case -4: puts("Nie ma ugrupowan do usuniecia "); break; } } continue; } ///////////////////////////////////////////////////////////////////////////// if(strcmp(komenda, "zapisz")==0) { puts("Podaj sciezke do pliku, w ktorym baza zostanie zapisana"); if(pobierz_komende()==-1) { while(getchar()!='\n'); puts ("Bledna nazwa"); } zapisz(komenda); puts("Zapisano"); continue; } //////////////////////////////////////////////////////////////////////////// puts("Niewlasciwa komenda, wpisz pomoc, aby wyswietlic dostepne komendy"); } return 0; }
2.84375
3
2024-11-18T22:22:14.763750+00:00
2018-07-05T00:23:34
d1bfe1a7d6ea00c7d893c6621b529967a7acbab5
{ "blob_id": "d1bfe1a7d6ea00c7d893c6621b529967a7acbab5", "branch_name": "refs/heads/master", "committer_date": "2018-07-05T00:23:34", "content_id": "c14d30a5367b14981c49a3d114e6925de7ef239d", "detected_licenses": [ "MIT" ], "directory_id": "a248757dadddc9d465f568420dca030162186099", "extension": "c", "filename": "Untitled 11.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": 239, "license": "MIT", "license_type": "permissive", "path": "/Untitled 11.c", "provenance": "stackv2-0123.json.gz:19191", "repo_name": "Preciousomonze/c-programs", "revision_date": "2018-07-05T00:23:34", "revision_id": "8872fb557d7c9db4ca31b3f77e6f342d7194adbb", "snapshot_id": "7b8186b507c5641fbc4aa5f7464736301ec2d626", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Preciousomonze/c-programs/8872fb557d7c9db4ca31b3f77e6f342d7194adbb/Untitled 11.c", "visit_date": "2020-03-22T08:35:04.888654" }
stackv2
#include <stdio.h> /*PROGRAM TO USE A WHILE LOOP*/ int main(){ int a = 30; while(a < 20){ printf("The value of a is %d\n\n",a); a++;//KEEP INCREMENTING } if(a==30){ printf("The value of a you supplied is 30"); } return 0; }
3.28125
3
2024-11-18T22:22:14.830158+00:00
2021-05-28T12:51:54
dbc479ae63300e81b64d295f2c4b779022325a37
{ "blob_id": "dbc479ae63300e81b64d295f2c4b779022325a37", "branch_name": "refs/heads/main", "committer_date": "2021-05-28T12:51:54", "content_id": "4d08ca5d62a35cf5b3a2f8adf8760f10fdcd6a55", "detected_licenses": [ "MIT" ], "directory_id": "265a0474c845129f3aeed35c314af5071131b1e5", "extension": "h", "filename": "register.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 371623700, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1397, "license": "MIT", "license_type": "permissive", "path": "/include/register.h", "provenance": "stackv2-0123.json.gz:19321", "repo_name": "afairon/expr-eval", "revision_date": "2021-05-28T12:51:54", "revision_id": "5f5100564fbd266384d6c8f9c54c2d0f8438b8ce", "snapshot_id": "11ebd6aabf5650738d52bdc395399f1da7be8edf", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/afairon/expr-eval/5f5100564fbd266384d6c8f9c54c2d0f8438b8ce/include/register.h", "visit_date": "2023-05-06T02:43:20.361480" }
stackv2
#ifndef REGISTER_H #define REGISTER_H #include <stddef.h> #include <AST.h> typedef struct { NodeConst *reg; size_t size; } Register; Register *create_set_registers(size_t n); void resize_registers(Register *src, size_t n); void register_load_constant(NodeConst *dst, NodeConst *n); void register_load_identifier(NodeConst *dst, NodeID *n); void register_convert_int_to_float(NodeConst *dst, NodeConst *src); void register_convert_float_to_int(NodeConst *dst, NodeConst *src); void register_gt(NodeConst *dst, NodeConst *src1, NodeConst *src2); void register_gteq(NodeConst *dst, NodeConst *src1, NodeConst *src2); void register_lt(NodeConst *dst, NodeConst *src1, NodeConst *src2); void register_lteq(NodeConst *dst, NodeConst *src1, NodeConst *src2); void register_eq(NodeConst *dst, NodeConst *src1, NodeConst *src2); void register_nteq(NodeConst *dst, NodeConst *src1, NodeConst *src2); void register_addition(NodeConst *dst, NodeConst *src1, NodeConst *src2); void register_subtraction(NodeConst *dst, NodeConst *src1, NodeConst *src2); void register_multiplication(NodeConst *dst, NodeConst *src1, NodeConst *src2); void register_division(NodeConst *dst, NodeConst *src1, NodeConst *src2); void register_intdivision(NodeConst *dst, NodeConst *src1, NodeConst *src2); void register_exponent(NodeConst *dst, NodeConst *src1, NodeConst *src2); void free_register(Register *r); #endif
2.09375
2
2024-11-18T22:22:14.934955+00:00
2020-01-27T07:08:38
d0bfeba350c236c991f61730a8e54c484904f705
{ "blob_id": "d0bfeba350c236c991f61730a8e54c484904f705", "branch_name": "refs/heads/master", "committer_date": "2020-01-27T07:08:38", "content_id": "1a859ad46048116f9a573142877518a4840cddc0", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "ce982295d56cfd6f42de94eb8149f7adec7707c5", "extension": "c", "filename": "main.c", "fork_events_count": 1, "gha_created_at": "2019-05-01T20:25:09", "gha_event_created_at": "2020-01-27T07:08:40", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 184476975, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 852, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/apps/exchangestring/components/Server/src/main.c", "provenance": "stackv2-0123.json.gz:19578", "repo_name": "ikuz/camkes", "revision_date": "2020-01-27T07:08:38", "revision_id": "a0f3d0d15a99cd18f308dbffc9fc857754ad7872", "snapshot_id": "6421a333e9a8e19c5598e71f3dc8087834757273", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ikuz/camkes/a0f3d0d15a99cd18f308dbffc9fc857754ad7872/apps/exchangestring/components/Server/src/main.c", "visit_date": "2021-09-24T07:28:00.751816" }
stackv2
/* * Copyright 2017, Data61 * Commonwealth Scientific and Industrial Research Organisation (CSIRO) * ABN 41 687 119 230. * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(DATA61_BSD) */ #include <assert.h> #include <camkes.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char *a_exchange(const char *input, char **output, char **joint) { char *reply = strdup("This is a string from server."); *output = malloc(30); strncpy(*output, reply, 30); (*output)[29] = '\0'; printf("Server input: %s\n", input); printf("Server joint: %s\n", *joint); free(*joint); *joint = malloc(50); strcpy(*joint, input); strcpy(*joint + strlen(input), reply); return reply; }
2.15625
2
2024-11-18T22:22:15.132610+00:00
2023-01-07T04:10:36
39c55636837dd8a6e977089206073b4265db3e50
{ "blob_id": "39c55636837dd8a6e977089206073b4265db3e50", "branch_name": "refs/heads/master", "committer_date": "2023-01-07T04:10:36", "content_id": "6e4e61a9797e36421fb8b697ba65bb4a7c357066", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e3f659f13c70d8a650c13b978fb0981798ae7c27", "extension": "c", "filename": "sbrk.c", "fork_events_count": 8, "gha_created_at": "2019-10-20T04:15:21", "gha_event_created_at": "2023-09-07T05:00:18", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 216306253, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1559, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/GD32VF103_Firmware_Library/RISCV/stubs/sbrk.c", "provenance": "stackv2-0123.json.gz:19837", "repo_name": "QQxiaoming/gd32vf103_freertos", "revision_date": "2023-01-07T04:10:36", "revision_id": "233d612ee265f821fea09b1f51eadc9ccb9c987b", "snapshot_id": "f557918f78079db5cc05aeed013db3dc9f0a4592", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/QQxiaoming/gd32vf103_freertos/233d612ee265f821fea09b1f51eadc9ccb9c987b/GD32VF103_Firmware_Library/RISCV/stubs/sbrk.c", "visit_date": "2023-01-12T05:28:58.390011" }
stackv2
/* See LICENSE of license details. */ #include <stddef.h> #include <errno.h> #include "FreeRTOS.h" #include "task.h" extern char heap_start, heap_end; static int heapBytesRemaining = -1; char *sbrk(int incr) { static char *currentHeapEnd = &heap_start; vTaskSuspendAll(); if(heapBytesRemaining == -1) { heapBytesRemaining = ((int)&heap_end)-((int)&heap_start); } char *previousHeapEnd = currentHeapEnd; if(currentHeapEnd + incr >= &heap_end) { _impure_ptr->_errno = ENOMEM; xTaskResumeAll(); return (char *)-1; } currentHeapEnd += incr; heapBytesRemaining -= incr; xTaskResumeAll(); return (char *)previousHeapEnd; } int get_heap_bytes_remaining_size(void) { if(heapBytesRemaining == -1) { heapBytesRemaining = ((int)&heap_end)-((int)&heap_start); } return heapBytesRemaining; } char *_sbrk(int incr) { return sbrk(incr); } void __malloc_lock(struct _reent *p) { vTaskSuspendAll(); } void __malloc_unlock(struct _reent *p) { (void)xTaskResumeAll(); } void __env_lock() { vTaskSuspendAll(); } void __env_unlock() { (void)xTaskResumeAll(); } void *__wrap_malloc(size_t nbytes) { extern void *__real_malloc(size_t nbytes); void *p = __real_malloc(nbytes); return p; } void *__wrap__malloc_r(void *reent, size_t nbytes) { extern void *__real__malloc_r(size_t nbytes); void *p = __real__malloc_r(nbytes); return p; }
2.671875
3
2024-11-18T22:22:15.208520+00:00
2015-11-02T02:24:25
f2a11c8b178a8ead70d8fa9fb7c4d45395b26879
{ "blob_id": "f2a11c8b178a8ead70d8fa9fb7c4d45395b26879", "branch_name": "refs/heads/master", "committer_date": "2015-11-02T02:24:25", "content_id": "7034f7c6bff896873eafc72f03b5679d5f394536", "detected_licenses": [ "MIT" ], "directory_id": "47363bfb48cc82b19ea73b4797d89928f19fa347", "extension": "c", "filename": "depositor.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 45367420, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 892, "license": "MIT", "license_type": "permissive", "path": "/depositor.c", "provenance": "stackv2-0123.json.gz:19966", "repo_name": "BillyBarbaro/SavingsAccount", "revision_date": "2015-11-02T02:24:25", "revision_id": "ac3106a49a9f4cd8fb038166718f617c6fbfe2ed", "snapshot_id": "ed4cb85b6f7d96d95b07c4ad23acee5ac6469870", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BillyBarbaro/SavingsAccount/ac3106a49a9f4cd8fb038166718f617c6fbfe2ed/depositor.c", "visit_date": "2021-01-11T10:06:38.086365" }
stackv2
#include "main.h" void print_deposit_info(int amount, int balance) { printf("Depositing %d dollars.\n", amount); printf("Current balance %d dollars.\n", balance); } int main(int argc, char *argv[]) { int semid; struct common *shared; int deposit_amount; struct customer *first_customer; if (argc != 2) { perror("Please enter only one argument"); exit(EXIT_FAILURE); } deposit_amount = atoi(argv[1]); semid = get_semid(); shared = get_shared(); // wait(mutex) P(semid, SEM_MUTEX); first_customer = get_first_customer(shared->front_of_line); shared->balance = shared->balance + deposit_amount; print_deposit_info(deposit_amount, shared->balance); if (shared->wait_count == 0 || first_customer_amount(first_customer) > shared->balance) { // signal(mutex) V(semid, SEM_MUTEX); } else { //signal(wait_list) V(semid, SEM_WAITLIST); } return EXIT_SUCCESS; }
2.484375
2
2024-11-18T22:22:15.316434+00:00
2019-07-20T14:19:49
5fa7a342a10c75a954bec76c934ab673587cdfd5
{ "blob_id": "5fa7a342a10c75a954bec76c934ab673587cdfd5", "branch_name": "refs/heads/master", "committer_date": "2019-07-20T14:19:49", "content_id": "9daaecb6441a7f88987ab9f0e9ef56d895d0e252", "detected_licenses": [ "Unlicense" ], "directory_id": "a58358f41ac6cb4cdc934016541a86996f1cca56", "extension": "c", "filename": "array_common.c", "fork_events_count": 0, "gha_created_at": "2019-07-15T08:21:00", "gha_event_created_at": "2019-07-15T08:21:00", "gha_language": null, "gha_license_id": "Unlicense", "github_id": 196955880, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13946, "license": "Unlicense", "license_type": "permissive", "path": "/src/array_common.c", "provenance": "stackv2-0123.json.gz:20096", "repo_name": "snmsts/npt", "revision_date": "2019-07-20T14:19:49", "revision_id": "2896d7ac1924ba63e864e2813e66936a2a46707f", "snapshot_id": "204e10891dda8a77006bc0b5b76335b654674e5a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/snmsts/npt/2896d7ac1924ba63e864e2813e66936a2a46707f/src/array_common.c", "visit_date": "2020-06-20T02:12:03.418379" }
stackv2
#include "array.h" #include "array_common.h" #include "array_copy.h" #include "array_object.h" #include "bit.h" #include "condition.h" #include "sequence.h" #include "type_upgraded.h" static void array_bitcalc_struct(addr pos, addr src) { struct array_struct *str1; const struct array_struct *str2; addr type; str1 = ArrayInfoStruct(pos); str2 = ArrayInfoStruct(src); str1->simple = 1; str1->adjustable = 0; str1->fillpointer = 0; str1->displaced = 0; str1->type = str2->type; str1->element = str2->element; str1->bytesize = str2->bytesize; str1->size = str2->front; str1->front = str2->front; str1->dimension = str2->dimension; str1->offset = 0; str1->refer = str2->front; GetArrayInfo(src, ARRAY_INDEX_TYPE, &type); SetArrayInfo(pos, ARRAY_INDEX_TYPE, type); } static void array_bitcalc_size(addr pos, addr src) { struct array_struct *str; const size_t *data2; addr temp; size_t size, i, *data1; str = ArrayInfoStruct(src); data2 = array_ptrsize(src); size = str->dimension; if (2 <= size) { arraysize_alloc(NULL, &temp, size); data1 = arraysize_ptr(temp); for (i = 0; i < size; i++) data1[i] = data2[i]; SetArrayInfo(pos, ARRAY_INDEX_DIMENSION, temp); } } static void array_bitcalc_make(addr src, addr *ret) { struct array_struct *str; addr pos; /* object */ array_empty_heap(&pos); /* element-type */ array_bitcalc_struct(pos, src); /* dimension */ array_bitcalc_size(pos, src); /* allocate */ str = ArrayInfoStruct(pos); array_allocate_bit(NULL, pos, str); /* result */ *ret = pos; } static int array_bitvector_type(addr pos) { switch (GetType(pos)) { case LISPTYPE_BITVECTOR: return 0; case LISPTYPE_ARRAY: return 1; default: fmte("Argument ~S must be a bit-array type.", pos, NULL); return -1; } } static int array_bitvector_size_equal(addr pos1, addr pos2) { int check1, check2; check1 = array_bitvector_type(pos1); check2 = array_bitvector_type(pos2); if (check1 && check2) { return array_dimension_equal(pos1, pos2); } if (check1) { if (ArrayInfoStruct(pos1)->dimension != 1) return 0; GetArrayInfo(pos1, ARRAY_INDEX_MEMORY, &pos1); return bitmemory_equal_length(pos1, pos2); } if (check2) { if (ArrayInfoStruct(pos2)->dimension != 1) return 0; GetArrayInfo(pos2, ARRAY_INDEX_MEMORY, &pos2); return bitmemory_equal_length(pos1, pos2); } else { return bitmemory_equal_length(pos1, pos2); } } static void array_bitcalc_aa(addr *ret, addr pos1, addr pos2, addr opt, bitcalc_call call) { struct array_struct *str; if (! array_bitvector_size_equal(pos1, pos2)) fmte("Dimension don't match ~S and ~S.", pos1, pos2, NULL); if (opt == Nil) { array_bitcalc_make(pos1, &opt); *ret = opt; GetArrayInfo(opt, ARRAY_INDEX_MEMORY, &opt); } else if (opt == T) { *ret = opt = pos1; GetArrayInfo(opt, ARRAY_INDEX_MEMORY, &opt); } else { if (! array_bitvector_size_equal(pos1, opt)) fmte("Length don't match ~S and optional ~S", pos1, opt, NULL); *ret = opt; if (arrayp(opt)) GetArrayInfo(opt, ARRAY_INDEX_MEMORY, &opt); } str = ArrayInfoStruct(pos1); if (str->type != ARRAY_TYPE_BIT) fmte("Array ~S must be a bit type.", pos1, NULL); str = ArrayInfoStruct(pos2); if (str->type != ARRAY_TYPE_BIT) fmte("Array ~S must be a bit type.", pos2, NULL); if (! bitvectorp(*ret)) fmte("Array ~S must be a bit type.", *ret, NULL); GetArrayInfo(pos1, ARRAY_INDEX_MEMORY, &pos1); GetArrayInfo(pos2, ARRAY_INDEX_MEMORY, &pos2); bitmemory_bitcalc(opt, pos1, pos2, call); } static void array_bitcalc_ab(addr *ret, addr pos1, addr pos2, addr opt, bitcalc_call call) { struct array_struct *str; size_t size; if (! array_bitvector_size_equal(pos1, pos2)) fmte("Length don't match ~S and ~S", pos1, pos2, NULL); if (opt == Nil) { bitmemory_length(pos2, &size); bitmemory_heap(&opt, size); *ret = opt; } else if (opt == T) { *ret = pos1; GetArrayInfo(pos1, ARRAY_INDEX_MEMORY, &opt); } else { if (! array_bitvector_size_equal(pos1, opt)) fmte("Length don't match ~S and optional ~S", pos1, opt, NULL); *ret = opt; if (arrayp(opt)) GetArrayInfo(opt, ARRAY_INDEX_MEMORY, &opt); } str = ArrayInfoStruct(pos1); if (str->type != ARRAY_TYPE_BIT) fmte("Array ~S must be a bit type.", pos1, NULL); if (! bitvectorp(*ret)) fmte("Array ~S must be a bit type.", *ret, NULL); GetArrayInfo(pos1, ARRAY_INDEX_MEMORY, &pos1); bitmemory_bitcalc(opt, pos1, pos2, call); } static void array_bitcalc_ba(addr *ret, addr pos1, addr pos2, addr opt, bitcalc_call call) { struct array_struct *str; size_t size; if (! array_bitvector_size_equal(pos1, pos2)) fmte("Length don't match ~S and ~S", pos1, pos2, NULL); if (opt == Nil) { bitmemory_length(pos1, &size); bitmemory_heap(&opt, size); *ret = opt; } else if (opt == T) { *ret = opt = pos1; } else { if (! array_bitvector_size_equal(pos1, opt)) fmte("Length don't match ~S and optional ~S", pos1, opt, NULL); *ret = opt; if (arrayp(opt)) GetArrayInfo(opt, ARRAY_INDEX_MEMORY, &opt); } str = ArrayInfoStruct(pos2); if (str->type != ARRAY_TYPE_BIT) fmte("Array ~S must be a bit type.", pos2, NULL); if (! bitvectorp(*ret)) fmte("Array ~S must be a bit type.", *ret, NULL); GetArrayInfo(pos2, ARRAY_INDEX_MEMORY, &pos2); bitmemory_bitcalc(opt, pos1, pos2, call); } static void array_bitcalc_bb(addr *ret, addr pos1, addr pos2, addr opt, bitcalc_call call) { size_t size; if (! bitmemory_equal_length(pos1, pos2)) fmte("Length don't match ~S and ~S", pos1, pos2, NULL); if (opt == Nil) { bitmemory_length(pos1, &size); bitmemory_heap(&opt, size); *ret = opt; } else if (opt == T) { *ret = opt = pos1; } else { if (! array_bitvector_size_equal(pos1, opt)) fmte("Length don't match ~S and optional ~S", pos1, opt, NULL); *ret = opt; if (arrayp(opt)) GetArrayInfo(opt, ARRAY_INDEX_MEMORY, &opt); } if (! bitvectorp(*ret)) fmte("Array ~S must be a bit type.", *ret, NULL); bitmemory_bitcalc(opt, pos1, pos2, call); } _g void array_bitcalc(addr *ret, addr pos1, addr pos2, addr opt, bitcalc_call call) { int check1, check2; check1 = array_bitvector_type(pos1); check2 = array_bitvector_type(pos2); if (check1 && check2) { array_bitcalc_aa(ret, pos1, pos2, opt, call); return; } if (check1) { array_bitcalc_ab(ret, pos1, pos2, opt, call); return; } if (check2) { array_bitcalc_ba(ret, pos1, pos2, opt, call); return; } else { array_bitcalc_bb(ret, pos1, pos2, opt, call); return; } } _g void array_bitnot_array(addr *ret, addr pos, addr opt) { struct array_struct *str; if (opt == Nil) { array_bitcalc_make(pos, &opt); *ret = opt; GetArrayInfo(opt, ARRAY_INDEX_MEMORY, &opt); } else if (opt == T) { *ret = opt = pos; GetArrayInfo(opt, ARRAY_INDEX_MEMORY, &opt); } else { if (! array_bitvector_size_equal(pos, opt)) fmte("Length don't match ~S and optional ~S", pos, opt, NULL); *ret = opt; if (arrayp(opt)) GetArrayInfo(opt, ARRAY_INDEX_MEMORY, &opt); } str = ArrayInfoStruct(pos); if (str->type != ARRAY_TYPE_BIT) fmte("Array ~S must be a bit type.", pos, NULL); if (! bitvectorp(*ret)) fmte("Array ~S must be a bit type.", *ret, NULL); GetArrayInfo(pos, ARRAY_INDEX_MEMORY, &pos); bitmemory_bitnot(opt, pos); } _g void array_bitnot_bitmemory(addr *ret, addr pos, addr opt) { size_t size; if (opt == Nil) { bitmemory_length(pos, &size); bitmemory_heap(&opt, size); *ret = opt; } else if (opt == T) { *ret = opt = pos; } else { if (! array_bitvector_size_equal(pos, opt)) fmte("Length don't match ~S and optional ~S", pos, opt, NULL); *ret = opt; if (arrayp(opt)) GetArrayInfo(opt, ARRAY_INDEX_MEMORY, &opt); } if (! bitvectorp(*ret)) fmte("Array ~S must be a bit type.", *ret, NULL); bitmemory_bitnot(opt, pos); } _g void array_bitnot(addr *ret, addr pos, addr opt) { if (array_bitvector_type(pos)) array_bitnot_array(ret, pos, opt); else array_bitnot_bitmemory(ret, pos, opt); } _g void array_fill(addr pos, addr item, addr start, addr end) { size_t index1, index2; struct array_struct *str; /* argument */ str = ArrayInfoStruct(pos); sequence_start_end(start, end, str->size, &index1, &index2); /* fill */ for (; index1 < index2; index1++) array_set(pos, index1, item); } static void array_subseq_general(addr *ret, addr pos, size_t index1, size_t index2) { addr root, temp; size_t i; Check(index2 < index1, "index error"); vector_heap(&root, index2 - index1); for (i = 0; index1 < index2; index1++, i++) { if (array_get_t(pos, index1, &temp)) { fmte("Invalid array object.", NULL); return; } setarray(root, i, temp); } *ret = root; } static void array_subseq_specialized_make(addr *ret, addr array, size_t size) { struct array_struct *str; addr pos; /* object */ array_empty_heap(&pos); /* element-type */ array_bitcalc_struct(pos, array); str = ArrayInfoStruct(pos); str->size = str->front = str->refer = size; /* allocate */ Check(str->dimension != 1, "dimension error"); array_allocate_size(NULL, pos, str); /* result */ *ret = pos; } static void array_subseq_specialized(addr *ret, addr array, size_t index1, size_t index2) { byte *data1; const byte *data2; addr pos, mem1, mem2; size_t element, diff; /* make array */ Check(index2 < index1, "index error"); diff = index2 - index1; array_subseq_specialized_make(&pos, array, diff); /* subseq */ GetArrayInfo(pos, ARRAY_INDEX_MEMORY, &mem1); GetArrayInfo(array, ARRAY_INDEX_MEMORY, &mem2); data1 = (byte *)arrayspec_ptr(mem1); data2 = (const byte *)arrayspec_ptr(mem2); element = ArrayInfoStruct(pos)->element; memcpy(data1, data2 + index1 * element, diff * element); *ret = pos; } static void array_subseq_type(addr *ret, addr pos, size_t index1, size_t index2) { struct array_struct *str; str = ArrayInfoStruct(pos); switch (str->type) { case ARRAY_TYPE_BIT: GetArrayInfo(pos, ARRAY_INDEX_MEMORY, &pos); bitmemory_subseq_index(ret, pos, index1, index2); break; case ARRAY_TYPE_CHARACTER: GetArrayInfo(pos, ARRAY_INDEX_MEMORY, &pos); strvect_subseq_index(ret, pos, index1, index2); break; case ARRAY_TYPE_SIGNED: case ARRAY_TYPE_UNSIGNED: case ARRAY_TYPE_SINGLE_FLOAT: case ARRAY_TYPE_DOUBLE_FLOAT: case ARRAY_TYPE_LONG_FLOAT: array_subseq_specialized(ret, pos, index1, index2); break; default: array_subseq_general(ret, pos, index1, index2); break; } } _g void array_subseq(addr *ret, addr pos, addr start, addr end) { size_t index1, index2; struct array_struct *str; str = ArrayInfoStruct(pos); sequence_start_end(start, end, str->size, &index1, &index2); array_subseq_type(ret, pos, index1, index2); } _g void array_reverse_t(LocalRoot local, addr *ret, addr pos) { addr one, temp; size_t size, x, y; size = length_sequence(pos, 1); vector_alloc(local, &one, size); for (x = 0; x < size; x++) { y = size - x - 1; if (array_get_t(pos, x, &temp)) { fmte("Invalid array ~S.", pos, NULL); return; } setarray(one, y, temp); } *ret = one; } _g void array_reverse_bit(LocalRoot local, addr *ret, addr pos) { int temp; addr one; size_t size, x, y; size = length_sequence(pos, 1); bitmemory_unsafe(local, &one, size); for (x = 0; x < size; x++) { y = size - x - 1; if (array_get_bit(pos, x, &temp)) fmte("Invalid array ~S.", pos, NULL); bitmemory_setint(one, y, temp); } *ret = one; } _g void array_reverse_character(LocalRoot local, addr *ret, addr pos) { unicode temp; addr one; size_t size, x, y; size = length_sequence(pos, 1); strvect_alloc(local, &one, size); for (x = 0; x < size; x++) { y = size - x - 1; if (array_get_unicode(pos, x, &temp)) { fmte("Invalid array ~S.", pos, NULL); return; } strvect_setc(one, y, temp); } *ret = one; } static void array_type_simple_vector(addr pos, enum ARRAY_TYPE type, unsigned size) { struct array_struct *str; str = ArrayInfoStruct(pos); str->type = type; str->bytesize = size; array_settype(pos); } static void array_make_simple_vector(LocalRoot local, addr *ret, size_t size, enum ARRAY_TYPE type, unsigned bytesize) { struct array_struct *str; addr pos; /* object */ array_empty_alloc(local, &pos); /* element-type */ array_type_simple_vector(pos, type, bytesize); array_element_size(pos); /* dimension */ str = ArrayInfoStruct(pos); str->dimension = 1; str->size = str->front = str->refer = size; /* allocate */ array_memory_make(local, pos, Nil, Nil, Nil, Nil); /* initial value */ array_initial_make(local, pos, Unbound, Unbound); /* result */ *ret = pos; } _g void array_reverse_size(LocalRoot local, addr *ret, addr pos) { struct array_struct *str; addr one; size_t size, x, y; struct array_value value; str = ArrayInfoStruct(pos); size = str->size; array_make_simple_vector(local, &one, size, str->type, str->bytesize); for (x = 0; x < size; x++) { y = size - x - 1; array_get_inplace(pos, x, &value); if (array_set_inplace(one, y, &value)) fmte("Invalid array ~S.", pos, NULL); } *ret = one; } _g void array_reverse(LocalRoot local, addr *ret, addr pos) { struct array_struct *str; str = ArrayInfoStruct(pos); Check(str->dimension != 1, "dimension error"); switch (str->type) { case ARRAY_TYPE_T: array_reverse_t(local, ret, pos); break; case ARRAY_TYPE_BIT: array_reverse_bit(local, ret, pos); break; case ARRAY_TYPE_CHARACTER: array_reverse_character(local, ret, pos); break; default: array_reverse_size(local, ret, pos); break; } } _g void array_nreverse(addr *ret, addr pos) { size_t size, x, y; struct array_value a, b; Check(ArrayInfoStruct(pos)->dimension != 1, "dimension error"); size = length_sequence(pos, 1); if (size <= 1) return; x = 0; y = size - 1; while (x < y) { array_get_inplace(pos, x, &a); array_get_inplace(pos, y, &b); array_set_inplace(pos, x, &b); array_set_inplace(pos, y, &a); x++; y--; } *ret = pos; }
2.453125
2
2024-11-18T22:22:15.461612+00:00
2013-07-26T13:47:36
0f4e27dc3c8e33735f1428d8c105b8e0d6c5165f
{ "blob_id": "0f4e27dc3c8e33735f1428d8c105b8e0d6c5165f", "branch_name": "refs/heads/master", "committer_date": "2013-07-26T13:47:36", "content_id": "d8be6ac0bd5a9a0919883289b013fa2fba401dcc", "detected_licenses": [ "MIT" ], "directory_id": "9aebdad983c42f373490293370635f136d3230fd", "extension": "c", "filename": "prim.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 9619124, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1600, "license": "MIT", "license_type": "permissive", "path": "/mrbgems/mruby-bin-hpcmrb/tools/hpcmrb/prim.c", "provenance": "stackv2-0123.json.gz:20228", "repo_name": "tomykaira/hpc-mruby", "revision_date": "2013-07-26T13:47:36", "revision_id": "5b417a9ee258a965323c3e9106729540131daea0", "snapshot_id": "d71f10c02021a4e9b54b359af4fcefecb65e0a56", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/tomykaira/hpc-mruby/5b417a9ee258a965323c3e9106729540131daea0/mrbgems/mruby-bin-hpcmrb/tools/hpcmrb/prim.c", "visit_date": "2023-06-19T18:47:58.368789" }
stackv2
#include "hpcmrb.h" #include "mruby.h" #include "mruby/class.h" #include "mruby/khash.h" #include "mruby/proc.h" #include "mruby/variable.h" /* Abstrac interpreters for builtin methods. */ #define ptr_hash_func(mrb,key) (khint_t)(((intptr_t)key)>>33^((intptr_t)key)^((intptr_t)key)<<11) #define ptr_hash_equal(mrb,a, b) (a == b) KHASH_DECLARE(interp, struct RProc*, struct RProc*, 1) KHASH_DEFINE(interp, struct RProc*, struct RProc*, 1, ptr_hash_func, ptr_hash_equal) static khash_t(interp) *interp_tbl; static mrb_value prim_printstr(mrb_state *mrb, mrb_value self) { mrb_value argv; mrb_get_args(mrb, "o", &argv); return argv; } static void add_interp_id(mrb_state *mrb, struct RClass *c, mrb_sym mid, mrb_func_t func, mrb_aspec aspec) { struct RProc *p, *q; khiter_t k; int ai = mrb_gc_arena_save(mrb); p = mrb_method_search_vm(mrb, &c, mid); hpc_assert(p); q = mrb_proc_new_cfunc(mrb, func); q->target_class = c; k = kh_put(interp, interp_tbl, p); kh_value(interp_tbl, k) = q; mrb_gc_arena_restore(mrb, ai); } struct RProc* get_interp(struct RProc *key) { khiter_t k; k = kh_get(interp, interp_tbl, key); if (k != kh_end(interp_tbl)) return kh_value(interp_tbl, k); return 0; } static void add_interp(mrb_state *mrb, struct RClass *c, const char *name, mrb_func_t func, mrb_aspec aspec) { add_interp_id(mrb, c, mrb_intern(mrb, name), func, aspec); } void init_prim_interpreters(hpc_state *p) { mrb_state *mrb = p->mrb; interp_tbl = kh_init(interp, mrb); add_interp(mrb, mrb->kernel_module, "__printstr__", prim_printstr, ARGS_REQ(1)); }
2.140625
2
2024-11-18T22:22:16.331360+00:00
2021-03-11T08:22:27
dbba2f5a32236661d2740e747477b7a9320e3b4f
{ "blob_id": "dbba2f5a32236661d2740e747477b7a9320e3b4f", "branch_name": "refs/heads/main", "committer_date": "2021-03-11T08:22:27", "content_id": "1dd33ea757870babee99b9f46a85aea0ee0e1425", "detected_licenses": [ "MIT" ], "directory_id": "9cd167bea67ada9b5ab201e05ee4d878963f0f47", "extension": "c", "filename": "init.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 322533014, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3602, "license": "MIT", "license_type": "permissive", "path": "/srcs/init.c", "provenance": "stackv2-0123.json.gz:20743", "repo_name": "raja-moukhass/RTV1", "revision_date": "2021-03-11T08:22:27", "revision_id": "3c69fe859aa692c0dbf121e341d228ec3369c943", "snapshot_id": "89d27ca0b735f1c163c5580a60a3f9ccdc7b54a2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/raja-moukhass/RTV1/3c69fe859aa692c0dbf121e341d228ec3369c943/srcs/init.c", "visit_date": "2023-03-17T15:10:54.444296" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* init.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ramoukha <ramoukha@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/02/27 15:13:37 by ramoukha #+# #+# */ /* Updated: 2021/03/03 15:28:14 by ramoukha ### ########.fr */ /* */ /* ************************************************************************** */ #include "rtv1.h" void init_data(t_data **data, char *av) { int i; char **tab; int count; int fd; i = 0; fd = open(av, O_RDONLY); count = ft_lines(fd); fd = open(av, O_RDONLY); tab = (char **)malloc(sizeof(char *) * (count + 1)); while (get_next_line(fd, &tab[i])) i++; close(fd); tab[i] = NULL; (*data) = (t_data *)malloc(sizeof(t_data)); (*data)->tab = tab; (*data)->camera = (t_camera *)malloc(sizeof(t_camera)); (*data)->obj = malloc(sizeof(t_obj)); (*data)->obj = NULL; (*data)->light = malloc(sizeof(t_light)); (*data)->camera->look_from = (t_vec){0, 5, 0}; (*data)->camera->cam_dir = (t_vec){0, 0, 0}; (*data)->camera->up = (t_vec){0, 1, 1e-6}; (*data)->camera->fov = 20; } t_vec get_camera_direction(t_camera cam, t_vec get_ray) { t_vec ray; cam.low_left_corner = vec_add(cam.look_from, get_ray); ray = vec_sub(cam.low_left_corner, cam.look_from); return (ray); } double ft_min_ray(double t1, double t2, double t) { if (t2 <= 0 && t1 <= 0) return (-1); else if (t1 >= 0 && t2 <= 0) t = t1; else if (t2 >= 0 && t1 <= 0) t = t2; else t = fmin(t1, t2); return (t); } t_ray get_ray(double u, double v, t_camera *camera) { t_get_ray r; u = 2 * (u + 2) / (HEIGHT) - 1; v = 1 - 2 * (v + 2) / (HEIGHT); r.new.o = camera->look_from; r.half_h = 2.0 * tan((camera->fov * M_PI / 180) / 2); r.half_w = r.half_h; r.cam_w = normalize(vec_sub(camera->look_from, camera->cam_dir)); r.cam_u = normalize(vec_cross(camera->up, r.cam_w)); r.cam_v = vec_cross(r.cam_w, r.cam_u); r.horizontal = vec_product(r.cam_u, r.half_w); r.vertical = vec_product(r.cam_v, r.half_h); camera->low_left_corner = vec_sub(camera->look_from, r.cam_w); camera->low_left_corner = vec_sub(camera->low_left_corner, vec_product(r.horizontal, 1 / 2)); camera->low_left_corner = vec_sub(camera->low_left_corner, vec_product(r.vertical, 1 / 2)); r.new.dir = vec_sub(camera->low_left_corner, r.new.o); r.new.dir = vec_sub(r.new.dir, vec_product(r.horizontal, u)); r.new.dir = vec_add(r.new.dir, vec_product(r.vertical, v)); r.new.dir = normalize(r.new.dir); return (r.new); } int init_obj(t_obj *temp, int i, t_data *data, int id) { temp->id = id; temp->pos = split_data(data, data->tab[++i]); temp->trans = split_data(data, data->tab[++i]); temp->rot = split_data(data, data->tab[++i]); temp->color = split_data(data, data->tab[++i]); if (id != 4) { i++; if (str_isnum(data->tab[i])) temp->an_ra = ft_atof(ft_strdup(data->tab[i])); else call_error(data); } if (id != 1) { temp->axis = split_data(data, data->tab[++i]); temp->axis = ft_transform_ray(temp); } if (id == 1) { temp->pos = ft_translate(temp->pos, temp->trans); } return (i); }
2.34375
2
2024-11-18T22:22:16.448944+00:00
2017-06-01T09:23:08
118886224ef5d22880e19c1c222eede57f236578
{ "blob_id": "118886224ef5d22880e19c1c222eede57f236578", "branch_name": "refs/heads/master", "committer_date": "2017-06-01T09:23:08", "content_id": "dfdecf1f3d07d9de3672ddd24ca792c8d14395e9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "50d2d927de15c1717e91c684d02ae9bb74900f87", "extension": "c", "filename": "unlink.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 92487805, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 634, "license": "Apache-2.0", "license_type": "permissive", "path": "/unlink.c", "provenance": "stackv2-0123.json.gz:20871", "repo_name": "scorsi/my-linked-list", "revision_date": "2017-06-01T09:23:08", "revision_id": "3653927b6dbf92738d98bd2b025b208f339328e6", "snapshot_id": "5ab011a9670019a9db13bfaf147e39e515d71119", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/scorsi/my-linked-list/3653927b6dbf92738d98bd2b025b208f339328e6/unlink.c", "visit_date": "2021-01-22T05:42:33.993271" }
stackv2
/* ** unlink.c for myll in /home/sylvain/Travail/Perso/myll/unlink.c ** ** Made by Sylvain CORSINI ** Login <sylvain.corsini@epitech.eu> ** ** Started on Wed May 31 16:15:52 2017 Sylvain CORSINI ** Last update Wed May 31 16:15:52 2017 Sylvain CORSINI */ #include <stddef.h> #include "myll.h" t_my_llist *myll_unlink(t_my_llist *llist) { t_my_llist *ret; ret = NULL; if (llist->right != NULL) { llist->right->left = llist->left; ret = llist->right; } if (llist->left != NULL) { llist->left->right = llist->right; ret = llist->left; } llist->right = NULL; llist->left = NULL; return (ret); }
2.578125
3
2024-11-18T22:22:17.969898+00:00
2014-08-18T10:58:07
6d6644ba9b8f8a3ea5c7b2e32447ae6ae68494f3
{ "blob_id": "6d6644ba9b8f8a3ea5c7b2e32447ae6ae68494f3", "branch_name": "refs/heads/master", "committer_date": "2014-08-18T10:58:07", "content_id": "b6f5e2317c0f8c373fbe6d04b078073b96924107", "detected_licenses": [ "MIT" ], "directory_id": "810db4af41ce83b20b3e2cdb7480cf8afebb7c0d", "extension": "c", "filename": "single_byte_xor_cipher.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": 3429, "license": "MIT", "license_type": "permissive", "path": "/set1/single_byte_xor_cipher.c", "provenance": "stackv2-0123.json.gz:21387", "repo_name": "lenormf/matasano", "revision_date": "2014-08-18T10:58:07", "revision_id": "a771c31b9e32887599a33dd024afcbc6fb52907d", "snapshot_id": "4a39de1763791c51495c0938c66dc64d8ecbd109", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lenormf/matasano/a771c31b9e32887599a33dd024afcbc6fb52907d/set1/single_byte_xor_cipher.c", "visit_date": "2020-05-17T20:58:11.667901" }
stackv2
/* * single_byte_xor_cipher.c for matasano * by lenormf */ #include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #include "error.h" #include "macro.h" #include "utils.h" typedef enum { LTR_E, LTR_T, LTR_A, LTR_O, LTR_I, LTR_SPC, } eScoreLetter; typedef struct cipher_score_s { uint8_t key; unsigned int scores[6]; unsigned int total_score; } cipher_score_t; eMatasanoError single_byte_xor_cipher(cipher_score_t *best_score, char const *cipher, size_t sz) { size_t text_n8_sz; uint8_t *text_n8; uint8_t c; if (!best_score || !cipher || !sz) { return ERR_INVALID_ARGUMENT; } else if (sz % 1) { return ERR_ALIGN_ERROR; } text_n8 = (uint8_t*)strndup(cipher, sz); if (!text_n8) { return ERR_ALLOC_ERROR; } text_n8_sz = sz / 2; if (str_hex_to_n8(text_n8)) { return ERR_NOT_HEXADECIMAL; } BZERO(best_score, sizeof(cipher_score_t)); for (c = 0; c < 0xFF; c++) { cipher_score_t score; unsigned int i; uint8_t *buffer; buffer = malloc(text_n8_sz); if (!buffer) { return ERR_ALLOC_ERROR; } memcpy(buffer, text_n8, text_n8_sz); BZERO(&score, sizeof(cipher_score_t)); score.key = c; for (i = 0; i < (unsigned int)text_n8_sz; i++) { buffer[i] ^= c; if (!PRINTABLE(buffer[i])) { break; } else { switch (LOWERCASE(buffer[i])) { case 'e': score.scores[LTR_E]++; break; case 't': score.scores[LTR_T]++; break; case 'a': score.scores[LTR_A]++; break; case 'o': score.scores[LTR_O]++; break; case 'i': score.scores[LTR_I]++; break; case 0x20: score.scores[LTR_SPC]++; break; default: break; } } } if (i >= (unsigned int)text_n8_sz) { uint8_t ign; ign = 0; for (i = 0; i < ARRAY_SIZE(score.scores) - 1; i++) { if (score.scores[i] >= text_n8_sz / 2) { ign = 1; break; } score.total_score += score.scores[i]; } if (!ign && score.scores[LTR_SPC]) { if (score.total_score > best_score->total_score) { memcpy(best_score, &score, sizeof(cipher_score_t)); } } } free(buffer); } free(text_n8); return ERR_NO_ERROR; } #ifndef STRIP_TEST_MAIN // ref: key=0x58, text="Cooking MC's like a pound of bacon" int main(void) { char const cipher[] = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"; uint8_t text[sizeof(cipher)]; cipher_score_t score; eMatasanoError err; unsigned int i; memcpy(text, cipher, sizeof(cipher)); if (str_hex_to_n8(text)) { return 1; } text[sizeof(text) / 2] = 0; err = single_byte_xor_cipher(&score, cipher, sizeof(cipher) - 1); if (ERR_NO_ERROR != err) { fprintf(stderr, "Error: %s\n", error_to_str(err)); return 1; } for (i = 0; i < sizeof(cipher) / 2; i++) { text[i] ^= score.key; } printf("key: %hhX, text: %s\n", score.key, (char*)text); return 0; } #endif
2.9375
3
2024-11-18T22:22:18.074637+00:00
2020-08-30T12:25:49
25e5c1011d58e6761851a9e4f073a3bff3242819
{ "blob_id": "25e5c1011d58e6761851a9e4f073a3bff3242819", "branch_name": "refs/heads/master", "committer_date": "2020-08-30T12:25:49", "content_id": "f699725cd63ea1795b52d1a98261fd42919f4fb2", "detected_licenses": [ "MIT" ], "directory_id": "436523490685fe56b21a4524248a8df68a7aa879", "extension": "c", "filename": "lib.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 291464406, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4971, "license": "MIT", "license_type": "permissive", "path": "/lib.c", "provenance": "stackv2-0123.json.gz:21516", "repo_name": "Silur/tlswrap", "revision_date": "2020-08-30T12:25:49", "revision_id": "ad92d7126d5bdb044f76f247bb1a97f607291760", "snapshot_id": "9d456df91ac53da0449d40efbf747b76b20e2b7b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Silur/tlswrap/ad92d7126d5bdb044f76f247bb1a97f607291760/lib.c", "visit_date": "2022-12-09T19:03:44.444734" }
stackv2
/* compile with * gcc -o libtlswrap.so tlswrap.c -ldl -lcrypto -lssl * Usage: LD_PRELOAD=./libtlswrap.so yourexec */ #define _GNU_SOURCE #include <stdio.h> #include <unistd.h> #include <string.h> #include <dlfcn.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <openssl/ssl.h> #include <openssl/err.h> int (*accept_orig)(int socket, struct sockaddr *address, socklen_t *address_len); int (*connect_orig)(int socket, const struct sockaddr *address, socklen_t address_len); ssize_t (*send_orig)(int socket, const void *buffer, size_t length, int flags); ssize_t (*write_orig)(int fd, const void *buffer, size_t length); ssize_t (*read_orig)(int fd, const void *buffer, size_t length); ssize_t (*recv_orig)(int socket, const void *buffer, size_t length, int flags); int (*close_orig)(int flides); SSL **sessions = 0; size_t sessions_len = 0; size_t sessions_count = 16; SSL_CTX *server_ctx = 0; SSL_CTX *client_ctx = 0; int init_done = 0; static int read_lock = 0; static int write_lock = 0; static void cleanup_openssl() { EVP_cleanup(); size_t i; for(i=0; i<sessions_len; i++) SSL_free(sessions[i]); if(server_ctx) SSL_CTX_free(server_ctx); if(client_ctx) SSL_CTX_free(client_ctx); } static SSL_CTX* create_server_ctx() { const SSL_METHOD *method; SSL_CTX *ctx; method = SSLv23_server_method(); ctx = SSL_CTX_new(method); if (!ctx) { perror("Unable to create SSL context"); ERR_print_errors_fp(stderr); exit(1); } SSL_CTX_set_ecdh_auto(ctx, 1); if (SSL_CTX_use_certificate_file(ctx, "cert.pem", SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); exit(1); } if (SSL_CTX_use_PrivateKey_file(ctx, "key.pem", SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); exit(1); } return ctx; } static SSL_CTX* create_client_ctx() { return 0; } static int get_ssl_id(int tfd) { size_t i; for(i=0; i<sessions_count; i++) { int cfd = SSL_get_fd(sessions[i]); if(cfd == tfd) return i; } return -1; } static void init() { SSL_load_error_strings(); ERR_load_crypto_strings(); OpenSSL_add_ssl_algorithms(); server_ctx = create_server_ctx(); client_ctx = create_server_ctx(); accept_orig = dlsym(RTLD_NEXT,"accept"); send_orig = dlsym(RTLD_NEXT,"send"); recv_orig = dlsym(RTLD_NEXT,"recv"); close_orig = dlsym(RTLD_NEXT,"close"); read_orig = dlsym(RTLD_NEXT,"read"); write_orig = dlsym(RTLD_NEXT,"write"); sessions_len = 16; sessions_count = 0; sessions = malloc(sessions_len*sizeof(SSL*)); } int accept(int sock, struct sockaddr *addr, socklen_t *len) { if(!init_done) init(); if(!server_ctx) server_ctx = create_server_ctx(); SSL *ssl; int client = accept_orig(sock, (struct sockaddr*)addr, len); if (client < 0) { perror("Unable to accept"); exit(1); } ssl = SSL_new(server_ctx); SSL_set_fd(ssl, client); if (SSL_accept(ssl) <= 0) { ERR_print_errors_fp(stderr); } if(sessions_count+1 > sessions_len) { sessions = realloc(sessions, (sessions_len+16)*sizeof(SSL*)); sessions_len+=16; } sessions[sessions_count++] = ssl; printf("ACCEPT client %d\n", client); fflush(stdout); return client; } ssize_t send(int socket, const void *buffer, size_t length, int flags) { int id = get_ssl_id(socket); if(id == -1) { fprintf(stderr, "SSL socket closed unexpectedly!\n"); exit(1); } write_lock = 1; return SSL_write(sessions[id], buffer, length); } ssize_t write(int fd, const void *buffer, size_t length) { if(write_lock) { return write_orig(fd, buffer, length); } int id = get_ssl_id(fd); if(id == -1) { return write_orig(fd, buffer, length); } SSL *ssl = sessions[id]; int ret; write_lock = 1; write_again: ret = SSL_write(ssl, buffer, length); switch(SSL_get_error(ssl, ret)) { case SSL_ERROR_NONE: read_lock = 0; return ret; case SSL_ERROR_WANT_WRITE: goto write_again; } } ssize_t recv(int socket, void *buffer, size_t length, int flags) { int id = get_ssl_id(socket); if(id == -1) { fprintf(stderr, "SSL socket closed unexpectedly!\n"); exit(1); } read_lock=1; return SSL_read(sessions[id], buffer, length); } ssize_t read(int fd, void *buffer, size_t length) { if(read_lock) { return read_orig(fd, buffer, length); } int id = get_ssl_id(fd); if(id == -1) { printf("calling original read\n"); fflush(stdout); return read_orig(fd, buffer, length); } SSL *ssl = sessions[id]; int ret; read_lock = 1; read_again: ret = SSL_read(ssl, buffer, length); switch(SSL_get_error(ssl, ret)) { case SSL_ERROR_NONE: read_lock = 0; return ret; case SSL_ERROR_WANT_READ: goto read_again; } } int close(int fd) { int id = get_ssl_id(fd); if(id == -1) return close_orig(fd); SSL *ssl = sessions[id]; if(ssl) { SSL_shutdown(ssl); SSL_free(ssl); } size_t i; for(i=id; i<sessions_count-1; i++) { sessions[i] = sessions[i+1]; } sessions[id] = 0; sessions_count--; return close_orig(fd); }
2.4375
2
2024-11-18T22:22:18.375627+00:00
2017-11-19T15:51:41
f31f835598cb1da07925b79d93c7c872fee3c4df
{ "blob_id": "f31f835598cb1da07925b79d93c7c872fee3c4df", "branch_name": "refs/heads/master", "committer_date": "2017-11-19T15:51:41", "content_id": "6c7fc341ebd85104ce6287020300d5a1101ff9ed", "detected_licenses": [ "MIT" ], "directory_id": "0523208bbec86a0ac565cc2657efd63ec9dd6d4e", "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": 111208018, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2392, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0123.json.gz:21774", "repo_name": "Felipeandradee/polynomial-equation-calculator", "revision_date": "2017-11-19T15:51:41", "revision_id": "4ea35d30bc1413283f7c804a4e3eee500bf02961", "snapshot_id": "21a7638081e96d9f413d18a617336e799e112690", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Felipeandradee/polynomial-equation-calculator/4ea35d30bc1413283f7c804a4e3eee500bf02961/main.c", "visit_date": "2021-08-16T10:30:28.140994" }
stackv2
#include <stdio.h> #include <string.h> #include "AnaSint.h" int main() { int option; while (TRUE) { system("cls"); printf("\n\t###########################################"); printf("\n\t###########################################"); printf("\n\t## ##"); printf("\n\t## -=|Polynomial Calculator|=- ##"); printf("\n\t## ##"); printf("\n\t###########################################"); printf("\n\t## ##"); printf("\n\t## |OPTIONS| ##"); printf("\n\t## ##"); printf("\n\t## 1. Insert a Polynomial ##"); printf("\n\t## 2. Print all Polynomials ##"); printf("\n\t## 3. Make Operations with Polynomials ##"); printf("\n\t## 0. Exit ##"); printf("\n\t## ##"); printf("\n\t###########################################"); printf("\n\t###########################################"); printf("\n"); printf("\tOPTION: "); scanf("%d", &option); switch (option){ case 1: { printf("\nDigite uma expressao: \n"); scanf("\n%s", string_entrada); equacao(); printf("\nExpressao esta correta.\n"); adiciona_funcao(); p_string = 0; memset(&Token, 0, sizeof(Token)); memset(&funcaoAux, 0, sizeof(funcaoAux)); system("pause"); break; } case 2: { imprime_funcoes(); printf("\n"); system("pause"); break; } case 3: { //TODO: functions to make calculations printf("\n\t\t!NOT IMPLEMENTED!\n\n"); system("pause"); break; } case 0: { exit(1); } default: { printf("\n\t\t!INVALID OPTION!\n\n"); system("pause"); } } } }
2.78125
3
2024-11-18T22:22:18.444728+00:00
2014-06-17T00:21:20
334b5b96f29378bca7871f001895da1fffb62a2f
{ "blob_id": "334b5b96f29378bca7871f001895da1fffb62a2f", "branch_name": "refs/heads/master", "committer_date": "2014-06-17T00:21:20", "content_id": "368be764bb716e95018a753a6232f14d4be111dd", "detected_licenses": [ "MIT" ], "directory_id": "9d20bbf0c37c081ee890a98b9231a216cfb85c84", "extension": "c", "filename": "env.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": 1567, "license": "MIT", "license_type": "permissive", "path": "/src/env.c", "provenance": "stackv2-0123.json.gz:21902", "repo_name": "tywkeene/Shell", "revision_date": "2014-06-17T00:21:20", "revision_id": "614b7de547308acb83b3adee490f3247f8555200", "snapshot_id": "1623cdc54dd9be966cc3dfd5ebc318b278c2b7c1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tywkeene/Shell/614b7de547308acb83b3adee490f3247f8555200/src/env.c", "visit_date": "2020-04-11T04:25:49.491785" }
stackv2
#include <stdio.h> #include <errno.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <shell.h> #include <env.h> extern shell_t sh_status; env_var_t *alloc_env_var(char *name, char *new) { env_var_t *var = calloc(1, sizeof(env_var_t)); var->name = copy_string(name); var->var = copy_string(new); var->next = NULL; return var; } environ_t *initialize_environ(void) { environ_t *env = calloc(1, sizeof(environ_t)); env->vars = NULL; return env; } void add_env_var(char *name, char *var) { env_var_t *p = sh_status.env->vars; env_var_t *new = alloc_env_var(name, var); if(p == NULL){ p = new; p->next = NULL; sh_status.env->vars = p; }else{ sh_status.env->vars = p; while(p->next != NULL) p = p->next; p->next = new; p = new; p->next = NULL; } } int set_env_var(char *name, char *set) { env_var_t *p = sh_status.env->vars; while(p != NULL){ if(strncmp(p->name, name, strlen(p->name) + 1) == 0) break; p = p->next; } if(p){ free(p->var); p->var = copy_string(set); }else return -1; return 0; } char *get_env_var(char *name) { env_var_t *p = sh_status.env->vars; while(p != NULL){ if(strncmp(p->name, name, strlen(p->name) + 1) == 0) break; p = p->next; } return p->var; } void free_env_var(env_var_t *var) { free(var->name); free(var->var); free(var); } void free_environ(void) { env_var_t *p; env_var_t *next; for (p = sh_status.env->vars; p != NULL; p = next) { next = p->next; free_env_var(p); } }
2.671875
3
2024-11-18T22:22:18.783367+00:00
2020-02-17T02:59:40
0c8cc8651a0e25c9d32b777e28c02582d523d527
{ "blob_id": "0c8cc8651a0e25c9d32b777e28c02582d523d527", "branch_name": "refs/heads/master", "committer_date": "2020-02-17T02:59:40", "content_id": "6a394cad8824084041d5fee6d0c702cf7a7c431b", "detected_licenses": [ "MIT" ], "directory_id": "bef1a80543314e65f5be9cd091647a212c8aa2b1", "extension": "c", "filename": "HouseLoanCal.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 228204851, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12673, "license": "MIT", "license_type": "permissive", "path": "/C/HouseLoanCal.c", "provenance": "stackv2-0123.json.gz:22160", "repo_name": "YiGeeker/HouseLoanCal", "revision_date": "2020-02-17T02:59:40", "revision_id": "2b0f302869b134f5e196337bf3a8231c8d93ad05", "snapshot_id": "58f95719cc09955a883842e57ac6e9a253e698a9", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/YiGeeker/HouseLoanCal/2b0f302869b134f5e196337bf3a8231c8d93ad05/C/HouseLoanCal.c", "visit_date": "2020-11-24T14:58:57.638978" }
stackv2
#include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* Get input as string to prevent overstep the boundary */ int GetInputAsString(char *lpszInput, unsigned int uSize) { int iResult; char szFormat[5] = "%"; char szSize[3]; itoa(uSize - 1, szSize, 10); strcat(szFormat, szSize); strcat(szFormat, "s"); /* Get the format string "%ns", n indicates the number of characters to read */ iResult = scanf(szFormat, lpszInput); fflush(stdin); return iResult; } /* Check the input is a valid integer or floating number */ bool CheckNumValid(char *lpszInputstring, bool bIsInt) { unsigned int uLength = strlen(lpszInputstring); unsigned int i; bool bDotExist = false; if (bIsInt) { /* for integer */ for (i = 0; i < uLength; i++) { if (lpszInputstring[i] < '0' || lpszInputstring[i] > '9') return false; } } else { /* for floating number */ for (i = 0; i < uLength; i++) { if (lpszInputstring[i] < '0' || lpszInputstring[i] > '9') { if (!bDotExist && lpszInputstring[i] == '.') /* decimal point can only appear once */ bDotExist = true; else return false; } } } return true; } /* Read the loan method */ char GetLoanMethod() { char szLoanMethod[3]; printf("请选择您的贷款方式\n\t1、商业贷款\n\t2、公积金贷款\n\t3、组合贷款\n请输入对应序号(1-3):"); GetInputAsString(szLoanMethod, sizeof szLoanMethod); /* Make sure that the input is 1, 2 or 3 */ while (1) { if (strlen(szLoanMethod) == 1) { if (szLoanMethod[0] >= '1' && szLoanMethod[0] <= '3') break; } printf("请输入有效对应序号(1-3):"); GetInputAsString(szLoanMethod, sizeof szLoanMethod); fflush(stdin); } if (szLoanMethod[0] == '1') printf("您选择的贷款方式为商业贷款\n>>>>>>>>>>>>>>>\n"); else if (szLoanMethod[0] == '2') printf("您选择的贷款方式为公积金贷款\n>>>>>>>>>>>>>>>\n"); else printf("您选择的贷款方式为组合贷款\n>>>>>>>>>>>>>>>\n"); return szLoanMethod[0]; } /* Get total loan according to loan method */ double *GetTotalLoan(char loanMethod) { char szTotalLoan[16]; static double fTotalLoan[2]; if (loanMethod == '1' || loanMethod == '2') { printf("请输入您的贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); /* Make sure that the input is a number above 0 */ while (1) { if (CheckNumValid(szTotalLoan, false)) { fTotalLoan[0] = atof(szTotalLoan); if (fTotalLoan[0] > 0) break; } printf("请输入有效贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); } printf("您的总贷款金额为%f万元\n>>>>>>>>>>>>>>>\n", fTotalLoan[0]); fTotalLoan[0] = fTotalLoan[0] * 10000; fTotalLoan[1] = 0; } else { printf("请输入您的商业贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); while (1) { if (CheckNumValid(szTotalLoan, sizeof szTotalLoan)) { fTotalLoan[0] = atof(szTotalLoan); if (fTotalLoan[0] > 0) break; } printf("请输入有效商业贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); } printf("请输入您的公积金贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); while (1) { if (CheckNumValid(szTotalLoan, sizeof szTotalLoan)) { fTotalLoan[1] = atof(szTotalLoan); if (fTotalLoan[1] > 0) break; } printf("请输入有效公积金贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); } printf("您的商业贷款金额为%f万元\n您的公积金贷款金额为%f万元\n总贷款金额为%f万元\n>>>>>>>>>>>>>>>\n", fTotalLoan[0], fTotalLoan[1], (fTotalLoan[0] + fTotalLoan[1])); fTotalLoan[0] = fTotalLoan[0] * 10000; /* bank total loan */ fTotalLoan[1] = fTotalLoan[1] * 10000; /* provident total loan */ } return fTotalLoan; } /* Read payment method */ char GetPaymentMethod() { char szPaymentMethod[3]; printf("请选择您的还款方式\n\t1、等额本息(每月等额还款)\n\t2、等额本金(每月递减还款)\n请输入对应序号(1-2):"); GetInputAsString(szPaymentMethod, sizeof szPaymentMethod); /* Make sure that the input is 1 or 2 */ while (1) { if (strlen(szPaymentMethod) == 1) if (szPaymentMethod[0] == '1' || szPaymentMethod[0] == '2') break; printf("请输入有效对应序号(1-2):"); GetInputAsString(szPaymentMethod, sizeof szPaymentMethod); } if (szPaymentMethod[0] == '1') printf("您选择的还款方式为等额本息\n>>>>>>>>>>>>>>>\n"); else printf("您选择的还款方式为等额本金\n>>>>>>>>>>>>>>>\n"); return szPaymentMethod[0]; } /* Get payment months */ unsigned int GetPaymentMonths() { char szPaymentYears[4]; unsigned int uPaymentYears; printf("请输入还款年数(1-30):"); GetInputAsString(szPaymentYears, sizeof szPaymentYears); /* Make sure that the input is a integer and between 1 and 30 */ while (1) { if (CheckNumValid(szPaymentYears, true)) { uPaymentYears = (unsigned int)atoi(szPaymentYears); if (uPaymentYears >= 1 && uPaymentYears <= 30) break; } printf("请输入有效还款年数(1-30):"); GetInputAsString(szPaymentYears, sizeof szPaymentYears); } printf("您的还款年数为%u年,共%u个月\n>>>>>>>>>>>>>>>\n", uPaymentYears, uPaymentYears * 12); return uPaymentYears * 12; } /* Read loan interest rate according to the loan method */ float *GetLoanInterestRate(char cLoanMethod) { char szLoanInterestRate[8]; static float fLoanInterestRate[2]; if (cLoanMethod == '1') { printf("请输入贷款利率,截止2019年末,银行贷款利率如下\n\t7折(3.43%%)\n\t8折(3.92%%)\n\t8.3折(4.067%%)\n\t8.5折(4.165%%)\n\t8.8折(4.312%%)\n\t9折(4.41%%)\n\t9.5折(4.655%%)\n\t基准利率(4.9%%)\n\t1.05倍(5.145%%)\n\t1.1倍(5.39%%)\n\t1.15倍(5.635%%)\n\t1.2倍(5.88%%)\n\t1.25倍(6.125%%)\n\t1.3倍(6.37%%)\n\t1.35倍(6.615%%)\n\t1.4倍(6.86%%)\n请输入具体数值(%%):"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); /* make sure that the input is a number above 0 below 100 */ while (1) { if (CheckNumValid(szLoanInterestRate, false)) { fLoanInterestRate[0] = atof(szLoanInterestRate); if (fLoanInterestRate[0] > 0 && fLoanInterestRate[0] < 100) break; } printf("请输入有效贷款利率:"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); } printf("您的贷款利率为%.3f%%\n>>>>>>>>>>>>>>>\n", fLoanInterestRate[0]); fLoanInterestRate[0] /= 100; fLoanInterestRate[1] = 0; } else if (cLoanMethod == '2') { printf("请输入公积金贷款利率,截止2019年末,公积金贷款利率如下\n\t基准利率(3.25%%)\n\t1.1倍(3.575%%)\n\t1.2倍(3.9%%)\n请输入具体数值(%%):"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); while (1) { if (CheckNumValid(szLoanInterestRate, false)) { fLoanInterestRate[0] = atof(szLoanInterestRate); if (fLoanInterestRate[0] > 0 && fLoanInterestRate[0] < 100) break; } printf("请输入有效公积金贷款利率:"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); } printf("您的公积金贷款利率为%.3f%%\n>>>>>>>>>>>>>>>\n", fLoanInterestRate[0]); fLoanInterestRate[0] /= 100; fLoanInterestRate[1] = 0; } else if (cLoanMethod == '3') { printf("请输入贷款利率,截止2019年末,银行贷款利率如下\n\t7折(3.43%%)\n\t8折(3.92%%)\n\t8.3折(4.067%%)\n\t8.5折(4.165%%)\n\t8.8折(4.312%%)\n\t9折(4.41%%)\n\t9.5折(4.655%%)\n\t基准利率(4.9%%)\n\t1.05倍(5.145%%)\n\t1.1倍(5.39%%)\n\t1.15倍(5.635%%)\n\t1.2倍(5.88%%)\n\t1.25倍(6.125%%)\n\t1.3倍(6.37%%)\n\t1.35倍(6.615%%)\n\t1.4倍(6.86%%)\n请输入具体数值(%%):"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); while (1) { if (CheckNumValid(szLoanInterestRate, false)) { fLoanInterestRate[0] = atof(szLoanInterestRate); if (fLoanInterestRate[0] > 0 && fLoanInterestRate[0] < 100) break; } printf("请输入有效银行贷款利率:"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); } printf("请输入公积金贷款利率,截止2019年末,公积金贷款利率如下\n\t基准利率(3.25%%)\n\t1.1倍(3.575%%)\n\t1.2倍(3.9%%)\n请输入具体数值(%%):"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); while (1) { if (CheckNumValid(szLoanInterestRate, false)) { fLoanInterestRate[1] = atof(szLoanInterestRate); if (fLoanInterestRate[1] > 0 && fLoanInterestRate[1] < 100) break; } printf("请输入有效公积金贷款利率:"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); } printf("您的银行贷款利率为%.3f%%,公积金贷款利率为%.3f%%\n>>>>>>>>>>>>>>>\n",fLoanInterestRate[0], fLoanInterestRate[1]); fLoanInterestRate[0] /= 100; /* bank loan interest rate */ fLoanInterestRate[1] /= 100; /* provident fund loan interest rate */ } return fLoanInterestRate; } /* Get payment every month by the way of average captial plus interest */ float AverageCaptialPlusInterest(double fTotalLoan, unsigned int uMonths, float fInterestRate) { float fMonthRate = fInterestRate / 12; return fTotalLoan * fMonthRate * pow(1 + fMonthRate, uMonths) / (pow(1 + fMonthRate, uMonths) - 1); } /* Get payment of uMonth month by the way of average captial */ float AverageCaptial(double fTotalLoan, unsigned int uMonths, float fInterestRate, unsigned int uMonth) { float fMonthRate = fInterestRate / 12; return fTotalLoan / uMonths * (1 + (uMonths - uMonth) * fMonthRate); } int main(int argc, char *argv[]) { char cLoanMethod, cPaymentMethod; float *lpfLoanInterestRate; double *lpfTotalLoan; unsigned int uPaymentMonths, m; float fMonthPayment[2] = {0, 0}; double fTotalPayment = 0, fTotalInterest; cLoanMethod = GetLoanMethod(); lpfTotalLoan = GetTotalLoan(cLoanMethod); cPaymentMethod = GetPaymentMethod(); uPaymentMonths = GetPaymentMonths(); lpfLoanInterestRate = GetLoanInterestRate(cLoanMethod); if (cPaymentMethod == '1') { /* for average capital plus interest method */ if (cLoanMethod == '1' || cLoanMethod == '2') { /* for commercial or provident fund loan method */ fMonthPayment[0] = AverageCaptialPlusInterest(lpfTotalLoan[0], uPaymentMonths, lpfLoanInterestRate[0]); fTotalPayment = fMonthPayment[0] * uPaymentMonths; fTotalInterest = fTotalPayment - lpfTotalLoan[0]; printf("每月需还款%.2f元\n\t还款总额%.6f万\n\t支付利息%.6f万\n\t贷款总额%.6f万\n", fMonthPayment[0], fTotalPayment / 10000, fTotalInterest / 10000, lpfTotalLoan[0] / 10000); } else { /* for syndicated loan method */ fMonthPayment[0] = AverageCaptialPlusInterest(lpfTotalLoan[0], uPaymentMonths, lpfLoanInterestRate[0]); /* bank payment every month */ fMonthPayment[1] = AverageCaptialPlusInterest(lpfTotalLoan[1], uPaymentMonths, lpfLoanInterestRate[1]); /* provident fund payment every month */ fTotalPayment = (fMonthPayment[0] + fMonthPayment[1]) * uPaymentMonths; fTotalInterest = fTotalPayment - (lpfTotalLoan[0] + lpfTotalLoan[1]); printf("每月需还款%.2f元\n\t还款总额%.6f万\n\t支付利息%.6f万\n\t贷款总额%.6f万\n", (fMonthPayment[0] + fMonthPayment[1]), fTotalPayment / 10000, fTotalInterest / 10000, (lpfTotalLoan[0] + lpfTotalLoan[1]) / 10000); } } else { /* for average capital method */ if (cLoanMethod == '1' || cLoanMethod == '2') { /* for commercial or provident fund loan method */ for (m = 0; m < uPaymentMonths; m++) { fTotalPayment += AverageCaptial(lpfTotalLoan[0], uPaymentMonths, lpfLoanInterestRate[0], m); } fTotalInterest = fTotalPayment - lpfTotalLoan[0]; printf("还款总额%.6f万\n支付利息%.6f万\n贷款总额%.6f万\n", fTotalPayment / 10000, fTotalInterest / 10000, lpfTotalLoan[0] / 10000); } else { /* for syndicated loan method */ for (m = 0; m < uPaymentMonths; m++) { fTotalPayment += (AverageCaptial(lpfTotalLoan[0], uPaymentMonths, lpfLoanInterestRate[0], m) + AverageCaptial(lpfTotalLoan[1], uPaymentMonths, lpfLoanInterestRate[1], m)); } fTotalInterest = fTotalPayment - (lpfTotalLoan[0] + lpfTotalLoan[1]); printf("还款总额%.6f万\n支付利息%.6f万\n贷款总额%.6f万\n", fTotalPayment / 10000, fTotalInterest / 10000, (lpfTotalLoan[0] + lpfTotalLoan[1]) / 10000); } } system("pause"); return 0; }
3.453125
3
2024-11-18T22:22:18.982390+00:00
2016-04-12T15:49:05
23dfffe71f7f5415a21cb09d65f38d42fc852dd1
{ "blob_id": "23dfffe71f7f5415a21cb09d65f38d42fc852dd1", "branch_name": "refs/heads/master", "committer_date": "2016-04-12T15:49:05", "content_id": "a941c2f2613de0a62b19193212d94f0fbbfeb2cc", "detected_licenses": [ "MIT" ], "directory_id": "6ab3aa11e24aa45d2199cc2248be220f87a0a895", "extension": "c", "filename": "xml_test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 53248890, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 291, "license": "MIT", "license_type": "permissive", "path": "/v2/xml_test.c", "provenance": "stackv2-0123.json.gz:22418", "repo_name": "tkorays/CodeXML", "revision_date": "2016-04-12T15:49:05", "revision_id": "503b5686f33c6649d7f8a87821e3b071a1f21b3b", "snapshot_id": "a15804b6349de32ba8ca8a2f860ebb7ff3b91a8c", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/tkorays/CodeXML/503b5686f33c6649d7f8a87821e3b071a1f21b3b/v2/xml_test.c", "visit_date": "2021-01-10T02:39:33.730471" }
stackv2
#include "ixml.h" #include <stdio.h> int main(){ XML_RET ret = XML_SUCCESS; XML_Doc_t* doc = 0; ret = XML_ParseFile("xml/a.xml",doc); if(ret != XML_SUCCESS){ printf("Error: %s\n",XML_GetErrorInfo(ret)); return 0; } XML_Destroy(&doc); return 0; }
2.015625
2
2024-11-18T22:22:19.306740+00:00
2018-10-15T01:22:04
4c6dfbf6a70c3315017b728f8ce1168f37c58400
{ "blob_id": "4c6dfbf6a70c3315017b728f8ce1168f37c58400", "branch_name": "refs/heads/master", "committer_date": "2018-10-15T01:22:04", "content_id": "066ccc22d725cbed3a2fa7d9ef8d0c1990b32501", "detected_licenses": [ "MIT" ], "directory_id": "81648d5a916707fbe1fc9abfb7d290bd55d8d92a", "extension": "h", "filename": "player_frame.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": 914, "license": "MIT", "license_type": "permissive", "path": "/src/player_frame.h", "provenance": "stackv2-0123.json.gz:22548", "repo_name": "aberlee/wordsmith", "revision_date": "2018-10-15T01:22:04", "revision_id": "82c506ae811edefe9b88c2065b5e4aaa625a7740", "snapshot_id": "eddc5289f4a12c9d3931bfb681ca0b5372af91d0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aberlee/wordsmith/82c506ae811edefe9b88c2065b5e4aaa625a7740/src/player_frame.h", "visit_date": "2020-04-02T12:15:39.942181" }
stackv2
#ifndef _PLAYER_FRAME_H_ #define _PLAYER_FRAME_H_ typedef enum { TEAM_MENU_STATE_MAIN, } TEAM_MENU_STATE; typedef struct { PLAYER *player; float scroll; TEAM_MENU_STATE state; // Selection int boxSelect; int teamSelect; int column; } TEAM_MENU; typedef enum { TEAM_MENU_CANCEL, TEAM_MENU_LEFT, TEAM_MENU_RIGHT, TEAM_MENU_UP, TEAM_MENU_DOWN, TEAM_MENU_NEUTRAL, TEAM_MENU_SELECT, } TEAM_MENU_ACTION; static void playerFrame_CreateTeam(TEAM_MENU *menu, PLAYER *player) { menu->player = player; menu->scroll = 0.0; menu->boxSelect = 0; menu->teamSelect = 0; menu->column = 0; menu->state = TEAM_MENU_STATE_MAIN; } extern void playerFrame_DrawTeam(const TEAM_MENU *menu); extern void playerFrame_UpdateTeam(TEAM_MENU *menu, float dt); extern void playerFrame_InteractTeam(TEAM_MENU *menu, TEAM_MENU_ACTION action); #endif
2.203125
2
2024-11-18T22:22:19.370897+00:00
2022-10-03T19:40:05
6e865210bd9ca3227e026d4bb9ad4e909624f008
{ "blob_id": "6e865210bd9ca3227e026d4bb9ad4e909624f008", "branch_name": "refs/heads/master", "committer_date": "2022-10-03T19:40:05", "content_id": "44b8a26720c2e9d3daff2b5aa246b514a5e5e637", "detected_licenses": [ "MIT" ], "directory_id": "1885ce333f6980ab6aad764b3f8caf42094d9f7d", "extension": "h", "filename": "version.h", "fork_events_count": 26, "gha_created_at": "2014-02-08T12:20:01", "gha_event_created_at": "2023-06-26T13:44:32", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 16642636, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1096, "license": "MIT", "license_type": "permissive", "path": "/test/e2e/test_input/wxWidgets/interface/wx/version.h", "provenance": "stackv2-0123.json.gz:22677", "repo_name": "satya-das/cppparser", "revision_date": "2022-10-03T19:40:05", "revision_id": "f9a4cfac1a3af7286332056d7c661d86b6c35eb3", "snapshot_id": "1dbccdeed4287c36c61edc30190c82de447e415b", "src_encoding": "UTF-8", "star_events_count": 194, "url": "https://raw.githubusercontent.com/satya-das/cppparser/f9a4cfac1a3af7286332056d7c661d86b6c35eb3/test/e2e/test_input/wxWidgets/interface/wx/version.h", "visit_date": "2023-07-06T00:55:23.382303" }
stackv2
///////////////////////////////////////////////////////////////////////////// // Name: version.h // Purpose: wxWidgets version numbers // Author: wxWidgets team // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// /** @addtogroup group_funcmacro_version */ //@{ /** This is a macro which evaluates to @true if the current wxWidgets version is at least major.minor.release. For example, to test if the program is compiled with wxWidgets 2.2 or higher, the following can be done: @code wxString s; #if wxCHECK_VERSION(2, 2, 0) if ( s.StartsWith("foo") ) #else // replacement code for old version if ( strncmp(s, "foo", 3) == 0 ) #endif { ... } @endcode @header{wx/version.h} */ #define wxCHECK_VERSION( major, minor, release ) /** Same as wxCHECK_VERSION() but also checks that wxSUBRELEASE_NUMBER is at least subrel. @header{wx/version.h} */ #define wxCHECK_VERSION_FULL( major, minor, release, subrel ) //@}
2.125
2
2024-11-18T22:22:19.539699+00:00
2018-04-23T21:23:41
c98f74820dad35319c83616e2cace0f07a92a6c7
{ "blob_id": "c98f74820dad35319c83616e2cace0f07a92a6c7", "branch_name": "refs/heads/develop", "committer_date": "2018-04-23T21:23:41", "content_id": "29fe3340549d7dad179e9cc3365c57f050d33586", "detected_licenses": [ "BSL-1.0" ], "directory_id": "d8860eb725a51fd0ef814bebfb8abaa8a807996d", "extension": "c", "filename": "idxnichr.c", "fork_events_count": 0, "gha_created_at": "2013-12-31T23:10:07", "gha_event_created_at": "2018-04-23T21:52:16", "gha_language": "C", "gha_license_id": null, "github_id": 15558048, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4263, "license": "BSL-1.0", "license_type": "permissive", "path": "/strfuncs/source/idxnichr.c", "provenance": "stackv2-0123.json.gz:22805", "repo_name": "mlbrock/MlbDevOld", "revision_date": "2018-04-23T21:23:41", "revision_id": "d31005dbe8ec05f59557e189e7194ee952ab64ff", "snapshot_id": "31c9809c8cbf8a2066c139d712a5ff0f758bbc39", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mlbrock/MlbDevOld/d31005dbe8ec05f59557e189e7194ee952ab64ff/strfuncs/source/idxnichr.c", "visit_date": "2021-01-20T03:53:21.763387" }
stackv2
/* *********************************************************************** */ /* *********************************************************************** */ /* STRFUNCS String and Memory Functions Library Module */ /* *********************************************************************** */ /* File Name : %M% File Version : %I% Last Extracted : %D% %T% Last Updated : %E% %U% File Description : Find first occurrence of a character in a string, ignoring case. Revision History : 1986-10-27 --- Creation Michael L. Brock Copyright Michael L. Brock 1986 - 2018. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ /* *********************************************************************** */ /* *********************************************************************** */ /* *********************************************************************** */ /* Necessary include files . . . */ /* *********************************************************************** */ #include <string.h> #include "strfunci.h" /* *********************************************************************** */ /* *********************************************************************** */ /* *********************************************************************** */ /* BOH NAME : idxnichr SYNOPSIS : int idxnichr(search_string, target_char, search_length); const char *search_string; int target_char; size_t search_length; DESCRIPTION : Locates the first occurrence of the character ``target_char`` in the string ``search_string`` within the first ``search_length`` characters of ``search_string``. Comparisons necessary to locate ``target_char`` are performed in a case-insensitive fashion. PARAMETERS : Parameters to this function are as follow: (.) ``search_string`` is the string in which the search is to be performed. (.) ``target_char`` is the character for which the search is to be performed. (.) ``search_length`` is the maximum number of characters to search within ``search_string``. Regardless of the value of ``search_length``, however, no more than the length of ``search_string`` (plus one for the terminating ASCII null character) will be searched. RETURNS : If found, the index of the first occurrence of the character ``target_char`` in the string ``search_string``. Otherwise, this function returns ''-1'' --- but refer to the notes in the ''Caveats'' section. NOTES : This function is a permutation of the functionality embodied in the standard C library function ``strchr``. Per the ISO C Standard 9899:1990 (section 7.11.5.2) definition of ``strchr``, the terminating ASCII null character in ``search_string`` is considered to be part of the string. CAVEATS : This function returns a signed int and therefore cannot accurately represent offsets greater than that defined by the manifest constant ''INT_MAX''. You have been warned. SEE ALSO : idxichr strnichr idxnistr EXAMPLES : AUTHOR : Michael L. Brock COPYRIGHT : Copyright 1986 - 2018 Michael L. Brock OUTPUT INDEX: idxnichr Character Search Functions/Index:idxnichr STRFUNCS:Character Search Functions/Index:idxnichr String Functions:See STRFUNCS PUBLISH XREF: idxnichr PUBLISH NAME: idxnichr ENTRY CLASS : Character Search Functions/Index EOH */ /* *********************************************************************** */ #ifndef NARGS int idxnichr(const char *search_string, int target_char, size_t search_length) #else int idxnichr(search_string, target_char, search_length) const char *search_string; int target_char; size_t search_length; #endif /* #ifndef NARGS */ { int found_index = -1; char *found_ptr; if ((found_ptr = strnichr(search_string, target_char, search_length)) != NULL) found_index = ((int) (found_ptr - ((char *) search_string))); return(found_index); } /* *********************************************************************** */
2.359375
2
2024-11-18T23:13:36.243004+00:00
2016-02-06T12:52:24
af9f77c1401e0e90bf5edbd0ab7daafb5f373772
{ "blob_id": "af9f77c1401e0e90bf5edbd0ab7daafb5f373772", "branch_name": "refs/heads/master", "committer_date": "2016-02-06T12:52:24", "content_id": "0cc2095e2fc8a776ff87b4354fbff881e605a95d", "detected_licenses": [ "MIT" ], "directory_id": "af4ccb0fa431324695099b56abe2ec02fd86908a", "extension": "c", "filename": "test-read-map.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 43892125, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 585, "license": "MIT", "license_type": "permissive", "path": "/src/tests/test-read-map.c", "provenance": "stackv2-0126.json.gz:308199", "repo_name": "super7ramp/Leonard", "revision_date": "2016-02-06T12:52:24", "revision_id": "9ce862e0692573b7fca6da191035822aa45266a6", "snapshot_id": "9914860e24049a38508ac8b08976ee186a699b27", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/super7ramp/Leonard/9ce862e0692573b7fca6da191035822aa45266a6/src/tests/test-read-map.c", "visit_date": "2021-01-10T03:06:32.375129" }
stackv2
#include <stdio.h> #include <stdlib.h> #include "../map/map_reader.h" /** To compile this (since Makefile is not up-to-date): * gcc -Wall -lm ../map/map_common.c ../map/map_reader.c test-read-map.c -o test-read-map * To run this: * ./test-read-map map.csv */ int main(int argc, char *argv[]) { if(argc < 2) { printf("Syntax: %s map.csv\n", argv[0]); return 1; } FILE* file = fopen(argv[1], "r"); graph_t *myTestGraph = createGraph(file); printGraph(myTestGraph); freeGraph(myTestGraph); fclose(file); return 0; }
2.265625
2
2024-11-18T23:13:36.305774+00:00
2017-05-31T05:38:26
cedba34a6ab574d77c006e413d9211d0b13c3c89
{ "blob_id": "cedba34a6ab574d77c006e413d9211d0b13c3c89", "branch_name": "refs/heads/master", "committer_date": "2017-05-31T05:38:26", "content_id": "b84dbab017479fedc4f0b43698399a255c140879", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3fd81edabe08b37f53eb9a3b1702a54ee2c1f301", "extension": "c", "filename": "hal_wifi.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 92479921, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1734, "license": "Apache-2.0", "license_type": "permissive", "path": "/components/hal/hal_wifi.c", "provenance": "stackv2-0126.json.gz:308328", "repo_name": "zengfu/esp32_weigher", "revision_date": "2017-05-31T05:38:26", "revision_id": "39b453779f00e8c023efe88156f14ca454cda27b", "snapshot_id": "8f7ff9b38e9ce49ef252eb3295f4e865b287d757", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zengfu/esp32_weigher/39b453779f00e8c023efe88156f14ca454cda27b/components/hal/hal_wifi.c", "visit_date": "2021-01-22T05:34:14.812454" }
stackv2
#include "esp_wifi.h" #include "hal_wifi.h" #include <string.h> static void hal_wifi_sta() { ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA)); } SemaphoreHandle_t wifi_done; static void hal_smartconfig_callback(smartconfig_status_t status, void *pdata) { switch(status) { case SC_STATUS_WAIT:{ printf("SC_STATUS_WAIT\n"); break; } case SC_STATUS_FIND_CHANNEL:{ printf("Find Channel\n"); break; } case SC_STATUS_GETTING_SSID_PSWD:{ smartconfig_type_t *a=pdata; if (*a==SC_TYPE_ESPTOUCH) printf("SC_TYPE:SC_TYPE_ESPTOUCH"); else if(*a==SC_TYPE_AIRKISS) printf("SC_TYPE:SC_TYPE_ESPAIRKISS"); break; } case SC_STATUS_LINK:{ printf("SC_STATUS_LINK\n"); wifi_config_t wifi_config; wifi_config.sta=*((wifi_sta_config_t *)pdata); ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config)); esp_wifi_disconnect(); esp_wifi_connect(); //ESP_ERROR_CHECK(esp_wifi_start()); break; } case SC_STATUS_LINK_OVER:{ gpio_set_level(GPIO_OUTPUT_IO_1,1); printf("LINK OVER\n"); if(pdata!=NULL){ uint8_t addr[4]; memcpy(addr,pdata,4); printf("phone ip addr:%02X.%02x.%02x.%02x\n",addr[0],addr[1],addr[2],addr[3]); } esp_smartconfig_stop(); xSemaphoreGive(wifi_done); } default:break; } } void hal_smartconfig_start() { esp_smartconfig_set_type(SC_TYPE_ESPTOUCH_AIRKISS); ESP_ERROR_CHECK(esp_smartconfig_start(hal_smartconfig_callback)); } void hal_wifi_init() { wifi_init_config_t cfg=WIFI_INIT_CONFIG_DEFAULT(); wifi_done=xSemaphoreCreateBinary(); //xSemaphoreGive(wifi_done); //xSemaphoreTake(wifi_done,(portTickType)portMAX_DELAY); ESP_ERROR_CHECK(esp_wifi_init(&cfg)); hal_wifi_sta(); esp_wifi_start(); }
2.25
2
2024-11-18T23:13:36.689439+00:00
2022-08-30T09:20:06
825bb0904b55bbd5197a3ac323f5c2ad3863cf23
{ "blob_id": "825bb0904b55bbd5197a3ac323f5c2ad3863cf23", "branch_name": "refs/heads/master", "committer_date": "2022-08-30T09:20:06", "content_id": "99f85620d37d4fdf603dd8afb679fb6816d80cbc", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "578a154fcdbebf1bb54f03d56edf85791e48ab3b", "extension": "c", "filename": "mod_cipwap_wtp.c", "fork_events_count": 28, "gha_created_at": "2014-07-11T20:01:20", "gha_event_created_at": "2016-03-26T08:56:49", "gha_language": "C", "gha_license_id": null, "github_id": 21749555, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1472, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/mod/cipwap/mod_cipwap_wtp.c", "provenance": "stackv2-0126.json.gz:308724", "repo_name": "7u83/actube", "revision_date": "2022-08-30T09:20:06", "revision_id": "34ee5537a4f2052bb1d7e7a5a428091945b99a18", "snapshot_id": "02252994adb0c1bdadc955c35df01408d4732099", "src_encoding": "UTF-8", "star_events_count": 35, "url": "https://raw.githubusercontent.com/7u83/actube/34ee5537a4f2052bb1d7e7a5a428091945b99a18/src/mod/cipwap/mod_cipwap_wtp.c", "visit_date": "2022-09-28T21:39:05.170517" }
stackv2
#include "../modload.h" #include "cw/mod.h" #include "cw/log.h" #include "cw/dbg.h" #include "mod_cipwap.h" int cipwap_init() { return 0; } static int detect(struct conn *conn,const uint8_t *rawmsg, int rawlen,int elems_len, struct sockaddr *from, int mode) { if (mode == CW_MOD_MODE_CAPWAP) return 1; return 0; } static int register_actions(struct cw_actiondef *actions, int mode) { switch (mode) { case CW_MOD_MODE_CAPWAP: { struct cw_Mod *cmod = modload_wtp("capwap"); if (!cmod) { cw_log(LOG_ERR, "Can't initialize mod_cisco, failed to load base mod mod_capwap"); return 1; } cmod->register_actions(actions, CW_MOD_MODE_CAPWAP); int rc = cipwap_register_actions_ac(actions); cw_dbg(DBG_INFO, "Initialized mod_cisco with %d actions", rc); return rc; } /* case MOD_MODE_BINDINGS: { struct mod_ac *cmod = modload_ac("capwap80211"); if (!cmod) { cw_log(LOG_ERR, "Can't initialize mod_cisco, failed to load base mod mod_capwap80211"); return 1; } cmod->register_actions(actions, MOD_MODE_BINDINGS); int rc = cipwap_register_actions80211_ac(actions); cw_dbg(DBG_INFO, "Initialized mod_cisco 80211 with %d actions", rc); return 0; } */ } return 0; } static struct cw_Mod cipwap_wtp = { .name ="cipwap", .init = cipwap_init, .detect = detect, .register_actions=register_actions }; struct cw_Mod * mod_cipwap_wtp(){ return &cipwap_wtp; };
2.140625
2
2024-11-18T23:13:37.052671+00:00
2023-08-30T22:52:10
86acfa74b27e95f0b20d354713e34a16cdfe5c59
{ "blob_id": "86acfa74b27e95f0b20d354713e34a16cdfe5c59", "branch_name": "refs/heads/master", "committer_date": "2023-08-30T22:52:10", "content_id": "a637671acbc6464db7dce04a6adc990535166659", "detected_licenses": [ "Apache-2.0" ], "directory_id": "55e64b2d9adbd60cd17ba95721347239f8a5c1b7", "extension": "h", "filename": "util.h", "fork_events_count": 6, "gha_created_at": "2016-12-09T18:10:10", "gha_event_created_at": "2022-08-20T13:48:31", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 76059025, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4809, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/surgescript/util/util.h", "provenance": "stackv2-0126.json.gz:308857", "repo_name": "alemart/surgescript", "revision_date": "2023-08-30T22:52:10", "revision_id": "2e1ae53ff0baabe1768a4722cb7b8ef532be4619", "snapshot_id": "a2c7d1d8b817526fcf07c26423b93a1326c4b6b0", "src_encoding": "UTF-8", "star_events_count": 53, "url": "https://raw.githubusercontent.com/alemart/surgescript/2e1ae53ff0baabe1768a4722cb7b8ef532be4619/src/surgescript/util/util.h", "visit_date": "2023-08-31T04:45:21.285344" }
stackv2
/* * SurgeScript * A scripting language for games * Copyright 2016-2023 Alexandre Martins <alemartf(at)gmail(dot)com> * * 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. * * util/util.h * SurgeScript utilities */ #ifndef _SURGESCRIPT_UTIL_H #define _SURGESCRIPT_UTIL_H #include <stdio.h> #include <stdlib.h> #include <stdint.h> /* macros */ #define ssmin(a, b) ((a) < (b) ? (a) : (b)) #define ssmax(a, b) ((a) >= (b) ? (a) : (b)) #define ssclamp(x, min, max) ssmax(ssmin((x), (max)), (min)) #define sssign(x) ((x) >= 0 ? 1 : -1) #define sstok(x) #x #define ssstr(x) sstok(x) #define ssassert(expr) do { if(!(expr)) ssfatal("In %s:%d: %s", __FILE__, __LINE__, ": assertion `" sstok(expr) "` failed."); } while(0) /* common aliases */ #define ssmalloc(n) surgescript_util_malloc((n), __FILE__, __LINE__) #define ssrealloc(p, n) surgescript_util_realloc((p), (n), __FILE__, __LINE__) #define ssfree surgescript_util_free #define sslog surgescript_util_log #define ssfatal surgescript_util_fatal #define ssstrdup(str) surgescript_util_strdup((str), __FILE__, __LINE__) #define ssatof(str) surgescript_util_strtod((str), NULL) /* constants */ #define SS_NAMEMAX 63 /* names can't be larger than this (computes hashes quickly) */ /* inlining hints */ #if defined(__GNUC__) || defined(__clang__) #define SS_FORCE_INLINE inline __attribute__((always_inline)) #define SS_NO_INLINE __attribute__((noinline)) #elif defined(_MSC_VER) #define SS_FORCE_INLINE __forceinline /* MSVC */ #define SS_NO_INLINE __declspec(noinline) #else #define SS_FORCE_INLINE inline #define SS_NO_INLINE #endif /* public routines */ int surgescript_util_versioncode(const char* version); /* converts a version string to a comparable number */ const char* surgescript_util_version(); /* compiled version of SurgeScript */ const char* surgescript_util_year(); /* year string of the SurgeScript runtime */ const char* surgescript_util_website(); /* project website */ const char* surgescript_util_authors(); /* project authors */ void* surgescript_util_malloc(size_t bytes, const char* file, int line); /* memory allocation */ void* surgescript_util_realloc(void* ptr, size_t bytes, const char* file, int line); /* memory reallocation */ void* surgescript_util_free(void* ptr); /* memory deallocation */ void surgescript_util_log(const char* fmt, ...); /* logs a message */ void surgescript_util_fatal(const char* fmt, ...); /* logs a message and kills the app */ void surgescript_util_set_log_function(void (*fn)(const char*,void*), void* context); /* set a custom log function */ void surgescript_util_set_crash_function(void (*fn)(const char*,void*), void* context); /* set a custom crash function */ void surgescript_util_set_error_functions(void (*log)(const char*), void (*crash)(const char*)); /* (obsolete) set custom log & crash functions */ char* surgescript_util_strncpy(char* dst, const char* src, size_t n); /* strcpy */ char* surgescript_util_strdup(const char* str, const char* file, int line); /* strdup */ double surgescript_util_strtod(const char* str, char** endptr); /* convert a string to a floating-point number in a locale-independent manner */ const char* surgescript_util_basename(const char* path); /* basename */ char* surgescript_util_accessorfun(const char* prefix, const char* text); /* getter/setter prefixing function */ unsigned surgescript_util_htob(unsigned x); /* host to big-endian */ unsigned surgescript_util_btoh(unsigned x); /* big to host-endian */ void surgescript_util_srand(uint64_t seed); /* sets the seed of the pseudo-random number generator */ uint64_t surgescript_util_random64(); /* generates a pseudo-random 64-bit unsigned integer */ double surgescript_util_random(); /* generates a pseudo-random double in the [0,1) range */ uint64_t surgescript_util_gettickcount(); /* number of milliseconds since some arbitrary zero */ FILE* surgescript_util_fopen_utf8(const char* filepath, const char* mode); /* fopen() with UTF-8 support for filenames */ #endif
2.25
2
2024-11-18T23:13:37.272708+00:00
2021-03-19T12:16:20
438afce49e5eb91026ce9adbfab9029b18c8bc5c
{ "blob_id": "438afce49e5eb91026ce9adbfab9029b18c8bc5c", "branch_name": "refs/heads/main", "committer_date": "2021-03-19T12:16:20", "content_id": "155a9c94839710ed4d8d179250895b54366a7349", "detected_licenses": [ "MIT" ], "directory_id": "7cd2c969be3145b617050222213af8f143041d2c", "extension": "c", "filename": "4.5.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 315095034, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 387, "license": "MIT", "license_type": "permissive", "path": "/Chapter 4/Practice/4.5.c", "provenance": "stackv2-0126.json.gz:308985", "repo_name": "YIHONG-JIN/Solution-for-C-Primer-Plus-6th", "revision_date": "2021-03-19T12:16:20", "revision_id": "6446da5d39ae64c5409cbd1413bb33635bba108e", "snapshot_id": "7daa7828e08326cf4a37a2ed84b040f237406169", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/YIHONG-JIN/Solution-for-C-Primer-Plus-6th/6446da5d39ae64c5409cbd1413bb33635bba108e/Chapter 4/Practice/4.5.c", "visit_date": "2023-03-17T17:42:01.596430" }
stackv2
#include <stdio.h> int main(void) { float speed, size, time; printf("Please input the net speed(megabits per second): "); scanf("%f", &speed); printf("Please input the file size(megabyte): "); scanf("%f", &size); time = size*8/speed; printf("At %.2f megabits per second, a file of %.2f megabytes download in %.2f seconds.", speed, size, time); return 0; }
3.03125
3
2024-11-18T23:13:38.953523+00:00
2021-04-27T13:05:55
10bead19925dd6f3562b23a9a0a55b09ddbbc4fb
{ "blob_id": "10bead19925dd6f3562b23a9a0a55b09ddbbc4fb", "branch_name": "refs/heads/master", "committer_date": "2021-04-27T13:05:55", "content_id": "a0be1a91766aa71ba9832458034fe9a43350f4b8", "detected_licenses": [ "MIT" ], "directory_id": "719b192cf3a5a62b8913b57e89bf303d18b1c7df", "extension": "c", "filename": "001-TwoSum.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 247275242, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 833, "license": "MIT", "license_type": "permissive", "path": "/C/001-TwoSum.c", "provenance": "stackv2-0126.json.gz:309378", "repo_name": "Yu-Zhuang/LeetCode", "revision_date": "2021-04-27T13:05:55", "revision_id": "6b26a6c20a14bb7c5c57333984cc5cd27983cf53", "snapshot_id": "4bdcc2abe7855b4d1a22d57146569b6b737ace29", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Yu-Zhuang/LeetCode/6b26a6c20a14bb7c5c57333984cc5cd27983cf53/C/001-TwoSum.c", "visit_date": "2023-04-17T05:39:45.355384" }
stackv2
// 1. Two Sum /* Question: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. */ int* twoSum(int* nums, int numsSize, int target, int* returnSize){ *returnSize=2; int *ret=(int*)malloc(sizeof(int)*2); int list[10000]={0}, flag=1; for(int i=0;i<numsSize&&flag;i++){ for(int j=0;j<i;j++) if(list[j] == nums[i]) { ret[0]=j; ret[1]=i; flag=0; break; } list[i]=target-nums[i]; } return ret; } /* result: Runtime: 68 ms, faster than 80.59% of C online submissions for Two Sum. Memory Usage: 6 MB, less than 100.00% of C online submissions for Two Sum. */
3.484375
3
2024-11-18T23:13:39.089850+00:00
2017-05-13T02:14:27
ec9f3094097a0eade1d15dfa46c36cabdd3225cd
{ "blob_id": "ec9f3094097a0eade1d15dfa46c36cabdd3225cd", "branch_name": "refs/heads/master", "committer_date": "2017-05-13T02:14:27", "content_id": "6e5355d34a57fb9e56810b44eddf9c4cbdb02281", "detected_licenses": [ "MIT" ], "directory_id": "ab82f7f4e58c4c083ddca1742e502456e2b821b1", "extension": "c", "filename": "mult.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 80882128, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 392, "license": "MIT", "license_type": "permissive", "path": "/cpu/ops/mult.c", "provenance": "stackv2-0126.json.gz:309509", "repo_name": "georgemorgan/ns4", "revision_date": "2017-05-13T02:14:27", "revision_id": "c981a1d124b957a4a60fae2a441bf9d3e4a4ad34", "snapshot_id": "c78f1e337de5db0fd9f51342c5a9429a9ff9be21", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/georgemorgan/ns4/c981a1d124b957a4a60fae2a441bf9d3e4a4ad34/cpu/ops/mult.c", "visit_date": "2021-01-19T10:11:38.004031" }
stackv2
/* mult.c - MULTiply word */ #include <vr4300i.h> /* MULT rs, rt multiply 32-bit signed integers. LO = low( rs*rt ); HI = high( rs*rt ) */ #define OPCODE 0x0 void ns4_vr4300i_mult(struct _vr4300i *vr) { uint32_t rs = (vr -> op >> 0x15) & 0x1f; uint32_t rt = (vr -> op >> 0x10) & 0x1f; LO = low(rs*rt); HI = high(rs*rt); ns4_debug("mult %s, %s", regstrs[rs], regstrs[rt]); }
2.5
2
2024-11-18T23:13:39.242348+00:00
2016-07-18T11:30:50
99640228b6849f1b29645e88bfa9506e4e4f8b5a
{ "blob_id": "99640228b6849f1b29645e88bfa9506e4e4f8b5a", "branch_name": "refs/heads/master", "committer_date": "2016-07-18T11:30:50", "content_id": "c240f352652f6b77485ab6e04caf0ab791e3354c", "detected_licenses": [ "MIT" ], "directory_id": "3d8abc7043f2c4b7e1183129dab300f53de79ea0", "extension": "c", "filename": "alloc.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 32922512, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6013, "license": "MIT", "license_type": "permissive", "path": "/src/alloc.c", "provenance": "stackv2-0126.json.gz:309771", "repo_name": "llafuente/string.c", "revision_date": "2016-07-18T11:30:50", "revision_id": "9e6f4d06b89915867dd5b00067040db908a6d29e", "snapshot_id": "2d1cf19937f3725669b0853d8edab366f9b5ccca", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/llafuente/string.c/9e6f4d06b89915867dd5b00067040db908a6d29e/src/alloc.c", "visit_date": "2021-01-17T08:11:06.967208" }
stackv2
/* * Copyright 2015 Luis Lafuente <llafuente@noboxout.com> * 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 AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /// @file #include "stringc.h" string* st_new(st_size_t cap, st_enc_t enc) { st_size_t size = cap + st__zeronull_size(enc); string* s = (string*)st__malloc(sizeof(string) + size * sizeof(char)); s->length = 0; s->used = 0; s->capacity = size; s->encoding = enc; st__zeronull(s->value, 0, enc); return s; } string* st_new_max(st_len_t len, st_enc_t enc) { switch (enc) { case st_enc_binary: case st_enc_ascii: return st_new(len, enc); case st_enc_utf8: case st_enc_utf32le: case st_enc_utf32be: return st_new(len * 4, enc); } } string* st_newc(const char* src, st_enc_t enc) { st_len_t len; st_size_t used; st_get_meta(src, enc, &len, &used); st_size_t size = used + st__zeronull_size(enc); string* s = (string*)st__malloc(sizeof(string) + (size) * sizeof(char)); s->length = len; s->used = used; s->capacity = size; memcpy(s->value, src, size); // copy null s->encoding = enc; return s; } void st_resize(string** src, st_size_t cap) { // printf("before st_resize %p - %lu\n", *src, cap); st_size_t size = cap + st__zeronull_size((*src)->encoding); // null terminated! *src = (string*)st__realloc(*src, sizeof(string) + size * sizeof(char)); (*src)->capacity = size; // printf("after st_resize %p\n", *src); } void st_grow(string** src, st_size_t cap, st_enc_t enc) { if (*src == 0) { *src = st_new(cap, enc); return; } if (cap + st__zeronull_size(enc) > (*src)->capacity) { (*src)->encoding = enc; st_resize(src, cap); } } string* st_clone(const string* src) { size_t size = sizeof(string) + src->capacity * sizeof(char); string* out = (string*)st__malloc(size); memcpy(out, src, size); // copy everything return out; } // resize & clone string* st_rclone(const string* src, st_size_t cap) { assert(cap >= src->capacity); cap += st__zeronull_size(src->encoding); size_t size = sizeof(string) + cap * sizeof(char); size_t src_size = sizeof(string) + src->capacity * sizeof(char); string* out = (string*)st__malloc(size); memcpy(out, src, src_size); // copy everything out->capacity = cap; return out; } string* st_new_subc(const char* src, st_size_t bytes, st_enc_t enc) { string* out = st_new(bytes, enc); char* oval = out->value; memcpy(oval, src, bytes); st__zeronull(oval, bytes, enc); out->length = st_length(oval, enc); out->used = bytes; return out; } /* deprecate, for reference only string* st_clonec(const char* src, size_t len) { string* out = st_new(len); memcpy(out->value, src, len); out->value[len] = '\0'; out->length = len; return out; } */ void st_copy(string** out, const string* src) { // printf("st_copy %p - %p\n", *out, src); size_t src_used = src->used; string* cache = *out; st_enc_t enc = src->encoding; if (src_used > cache->capacity) { st_resize(out, src_used); cache = *out; } char* cval = cache->value; memcpy(cval, src->value, src_used + st__zeronull_size(enc)); cache->length = src->length; cache->encoding = enc; cache->used = src_used; } void st_copyc(string** out, const char* src, st_enc_t enc) { // printf("st_copy %p - chars* %p\n", *out, src); st_len_t len; st_size_t used; st_get_meta(src, enc, &len, &used); string* cache = *out; // printf("capacity check %zu - %zu\n", cache->capacity, len); if (used > cache->capacity) { st_resize(out, used); cache = *out; } // printf("st_copy %p @ %p\n", cache, cache->value); cache->length = len; cache->used = used; cache->encoding = enc; memcpy(cache->value, src, used + st__zeronull_size(enc)); } void st_delete(string** out) { st__free((void*)*out); *out = __STRING_MEM_FREE_ADDR; // when free set to a know address } void st_clear(string* out) { st__zeronull(out->value, 0, out->encoding); out->length = 0; out->used = 0; } st_size_t st_dump_header_size() { return (sizeof(st_len_t) + sizeof(st_len_t) + sizeof(st_size_t) + sizeof(st_enc_t)); } void st_dump_header(string* s, char* buff) { size_t slen = sizeof(string); char* p = (char*)s; char c[3]; char* pp = buff; do { // printf("len [%lu] char[%c | %2.2x]\n", slen, *p, (*p) & 0xff); sprintf(c, "%2.2x", (*p) & 0xff); pp[0] = '\\'; pp[1] = 'x'; pp[2] = c[0]; pp[3] = c[1]; ++p; pp += 4; } while (--slen); } char* st_dump(string* s) { size_t slen = st_dump_header_size(); size_t len = s->used; char* out = malloc((4 * slen) + len + 1); char* p = s->value; // dump values on by one char* pp = out + slen * 4; st_dump_header(s, out); do { *pp = *p; ++p; ++pp; } while (--len); *pp = '\0'; return out; }
2.484375
2
2024-11-18T23:13:39.420448+00:00
2022-09-21T14:53:07
0c635d7279fe69d8133ec3cbf5d16808b601e8e2
{ "blob_id": "0c635d7279fe69d8133ec3cbf5d16808b601e8e2", "branch_name": "refs/heads/master", "committer_date": "2022-09-22T21:57:08", "content_id": "a1dc3a16fedc5879d503d997feb9218be7d7192f", "detected_licenses": [ "MIT" ], "directory_id": "33c44337d2e413a3e3c31ab11daf4f2118f9babb", "extension": "h", "filename": "lrmalloc.h", "fork_events_count": 6, "gha_created_at": "2018-04-02T17:42:28", "gha_event_created_at": "2022-09-22T21:57:09", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 127790761, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4068, "license": "MIT", "license_type": "permissive", "path": "/lrmalloc.h", "provenance": "stackv2-0126.json.gz:309900", "repo_name": "ricleite/lrmalloc", "revision_date": "2022-09-21T14:53:07", "revision_id": "34c6474861ec7583ac146da5a8f39190de6db991", "snapshot_id": "4018647d0cb637c3195fb2fcbf3cd9f1e13897ff", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/ricleite/lrmalloc/34c6474861ec7583ac146da5a8f39190de6db991/lrmalloc.h", "visit_date": "2022-09-25T22:42:47.667582" }
stackv2
/* * Copyright (C) 2019 Ricardo Leite. All rights reserved. * Licenced under the MIT licence. See COPYING file in the project root for * details. */ #ifndef __LFMALLOC_H #define __LFMALLOC_H #include <stddef.h> // a cache line is 64 bytes #define LG_CACHELINE 6 // a page is 4KB #define LG_PAGE 12 // a huge page is 2MB #define LG_HUGEPAGE 21 // a ptr is sizeof(void*) bytes #define PTR_SZ sizeof(void*) #define CACHELINE ((size_t)(1U << LG_CACHELINE)) #define PAGE ((size_t)(1U << LG_PAGE)) #define HUGEPAGE ((size_t)(1U << LG_HUGEPAGE)) #define PTR_MASK (PTR_SZ - 1) #define CACHELINE_MASK (CACHELINE - 1) #define PAGE_MASK (PAGE - 1) // minimum alignment requirement all allocations must meet // "address returned by malloc will be suitably aligned to store any kind of // variable" #define MIN_ALIGN sizeof(void*) // returns smallest value >= value with alignment align #define ALIGN_VAL(val, align) (__typeof__(val))(((size_t)(val) + (align - 1)) & ((~(align)) + 1)) // returns smallest address >= addr with alignment align #define ALIGN_ADDR(addr, align) ALIGN_VAL(addr, align) // return smallest page size multiple that is >= s #define PAGE_CEILING(s) (((s) + (PAGE - 1)) & ~(PAGE - 1)) // https://stackoverflow.com/questions/109710/how-do-the-likely-and-unlikely-macros-in-the-linux-kernel-work-and-what-is-t #define LIKELY(x) __builtin_expect((x), 1) #define UNLIKELY(x) __builtin_expect((x), 0) #define LFMALLOC_ATTR(s) __attribute__((s)) #define LFMALLOC_ALLOC_SIZE(s) LFMALLOC_ATTR(alloc_size(s)) #define LFMALLOC_ALLOC_SIZE2(s1, s2) LFMALLOC_ATTR(alloc_size(s1, s2)) #define LFMALLOC_EXPORT LFMALLOC_ATTR(visibility("default")) #define LFMALLOC_NOTHROW LFMALLOC_ATTR(nothrow) #if defined(__GNUC__) #define LFMALLOC_INLINE \ LFMALLOC_ATTR(always_inline) \ inline static #elif defined(_MSC_VER) #define LFMALLOC_INLINE __forceinline inline static #else #define LFMALLOC_INLINE #endif // use initial exec tls model, faster than regular tls // with the downside that the malloc lib can no longer be dlopen'd // https://www.ibm.com/support/knowledgecenter/en/SSVUN6_1.1.0/com.ibm.xlcpp11.zlinux.doc/language_ref/attr_tls_model.html #define LFMALLOC_TLS_INIT_EXEC LFMALLOC_ATTR(tls_model("initial-exec")) #define LFMALLOC_CACHE_ALIGNED LFMALLOC_ATTR(aligned(CACHELINE)) #define LFMALLOC_CACHE_ALIGNED_FN LFMALLOC_ATTR(aligned(CACHELINE)) #define STATIC_ASSERT(x, m) static_assert(x, m) #define lf_malloc malloc #define lf_free free #define lf_calloc calloc #define lf_realloc realloc #define lf_malloc_usable_size malloc_usable_size #define lf_posix_memalign posix_memalign #define lf_aligned_alloc aligned_alloc #define lf_valloc valloc #define lf_memalign memalign #define lf_pvalloc pvalloc // exports #ifdef __cplusplus extern "C" { #endif // malloc interface void* lf_malloc(size_t size) LFMALLOC_EXPORT LFMALLOC_NOTHROW LFMALLOC_ALLOC_SIZE(1) LFMALLOC_CACHE_ALIGNED_FN; void lf_free(void* ptr) LFMALLOC_EXPORT LFMALLOC_NOTHROW LFMALLOC_CACHE_ALIGNED_FN; void* lf_calloc(size_t n, size_t size) LFMALLOC_EXPORT LFMALLOC_NOTHROW LFMALLOC_ALLOC_SIZE2(1, 2) LFMALLOC_CACHE_ALIGNED_FN; void* lf_realloc(void* ptr, size_t size) LFMALLOC_EXPORT LFMALLOC_NOTHROW LFMALLOC_ALLOC_SIZE(2) LFMALLOC_CACHE_ALIGNED_FN; // utilities size_t lf_malloc_usable_size(void* ptr); // memory alignment ops int lf_posix_memalign(void** memptr, size_t alignment, size_t size) LFMALLOC_EXPORT LFMALLOC_NOTHROW LFMALLOC_ATTR(nonnull(1)); void* lf_aligned_alloc(size_t alignment, size_t size) LFMALLOC_EXPORT LFMALLOC_NOTHROW LFMALLOC_ALLOC_SIZE(2) LFMALLOC_CACHE_ALIGNED_FN; void* lf_valloc(size_t size) LFMALLOC_EXPORT LFMALLOC_NOTHROW LFMALLOC_ALLOC_SIZE(1) LFMALLOC_CACHE_ALIGNED_FN; // obsolete alignment oos void* lf_memalign(size_t alignment, size_t size) LFMALLOC_EXPORT LFMALLOC_NOTHROW LFMALLOC_ALLOC_SIZE(2) LFMALLOC_CACHE_ALIGNED_FN; void* lf_pvalloc(size_t size) LFMALLOC_EXPORT LFMALLOC_NOTHROW LFMALLOC_ALLOC_SIZE(1) LFMALLOC_CACHE_ALIGNED_FN; #ifdef __cplusplus } #endif #endif // __LFMALLOC_H
2.28125
2
2024-11-18T20:53:26.421706+00:00
2023-04-26T15:57:36
44d9fb844f1d0effd1b96b3feea70a62fcb9dd11
{ "blob_id": "44d9fb844f1d0effd1b96b3feea70a62fcb9dd11", "branch_name": "refs/heads/main", "committer_date": "2023-04-26T16:13:19", "content_id": "33ffabbe75eb5c85fd06f3fe8b648f39210c5513", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3b732e753b1dd8018c0cb350e3e162a6f8300d03", "extension": "h", "filename": "fe25519.h", "fork_events_count": 19, "gha_created_at": "2017-11-17T12:15:47", "gha_event_created_at": "2022-01-29T20:29:16", "gha_language": "Assembly", "gha_license_id": "Apache-2.0", "github_id": 111099996, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2406, "license": "Apache-2.0", "license_type": "permissive", "path": "/lib/ed25519/amd64-64-24k-pic/fe25519.h", "provenance": "stackv2-0127.json.gz:67245", "repo_name": "hyperledger/iroha-ed25519", "revision_date": "2023-04-26T15:57:36", "revision_id": "4c4de7b6df64e6b5e14dfe2ed515c60a8ad2612e", "snapshot_id": "3918132a82a7df1cb263afa0b28cfedf6e0e5787", "src_encoding": "UTF-8", "star_events_count": 27, "url": "https://raw.githubusercontent.com/hyperledger/iroha-ed25519/4c4de7b6df64e6b5e14dfe2ed515c60a8ad2612e/lib/ed25519/amd64-64-24k-pic/fe25519.h", "visit_date": "2023-08-10T08:22:52.587627" }
stackv2
#ifndef FE25519_H #define FE25519_H #define fe25519 crypto_sign_ed25519_amd64_64_fe25519 #define fe25519_freeze crypto_sign_ed25519_amd64_64_fe25519_freeze #define fe25519_unpack crypto_sign_ed25519_amd64_64_fe25519_unpack #define fe25519_pack crypto_sign_ed25519_amd64_64_fe25519_pack #define fe25519_iszero_vartime crypto_sign_ed25519_amd64_64_fe25519_iszero_vartime #define fe25519_iseq_vartime crypto_sign_ed25519_amd64_64_fe25519_iseq_vartime #define fe25519_cmov crypto_sign_ed25519_amd64_64_fe25519_cmov #define fe25519_setint crypto_sign_ed25519_amd64_64_fe25519_setint #define fe25519_neg crypto_sign_ed25519_amd64_64_fe25519_neg #define fe25519_getparity crypto_sign_ed25519_amd64_64_fe25519_getparity #define fe25519_add crypto_sign_ed25519_amd64_64_fe25519_add #define fe25519_sub crypto_sign_ed25519_amd64_64_fe25519_sub #define fe25519_mul crypto_sign_ed25519_amd64_64_fe25519_mul #define fe25519_mul121666 crypto_sign_ed25519_amd64_64_fe25519_mul121666 #define fe25519_square crypto_sign_ed25519_amd64_64_fe25519_square #define fe25519_invert crypto_sign_ed25519_amd64_64_fe25519_invert #define fe25519_pow2523 crypto_sign_ed25519_amd64_64_fe25519_pow2523 typedef struct { unsigned long long v[4]; } fe25519; void fe25519_freeze(fe25519 *r); void fe25519_unpack(fe25519 *r, const unsigned char x[32]); void fe25519_pack(unsigned char r[32], const fe25519 *x); void fe25519_cmov(fe25519 *r, const fe25519 *x, unsigned char b); void fe25519_cswap(fe25519 *r, fe25519 *x, unsigned char b); void fe25519_setint(fe25519 *r, unsigned int v); void fe25519_neg(fe25519 *r, const fe25519 *x); unsigned char fe25519_getparity(const fe25519 *x); int fe25519_iszero_vartime(const fe25519 *x); int fe25519_iseq_vartime(const fe25519 *x, const fe25519 *y); void fe25519_add(fe25519 *r, const fe25519 *x, const fe25519 *y); void fe25519_sub(fe25519 *r, const fe25519 *x, const fe25519 *y); void fe25519_mul(fe25519 *r, const fe25519 *x, const fe25519 *y); void fe25519_mul121666(fe25519 *r, const fe25519 *x); void fe25519_square(fe25519 *r, const fe25519 *x); void fe25519_pow(fe25519 *r, const fe25519 *x, const unsigned char *e); void fe25519_invert(fe25519 *r, const fe25519 *x); void fe25519_pow2523(fe25519 *r, const fe25519 *x); #endif
2
2
2024-11-18T20:53:26.476932+00:00
2020-10-20T13:04:16
c794b744a6d0bc430ed0fc1c5d6d316ce3761843
{ "blob_id": "c794b744a6d0bc430ed0fc1c5d6d316ce3761843", "branch_name": "refs/heads/master", "committer_date": "2020-10-20T13:04:16", "content_id": "da3463c5eed9c5d23f9955aaffc3acfa96fdcc39", "detected_licenses": [ "MIT" ], "directory_id": "84d678dc1ed4c03e0f87b8b787a1bdd8743df2a4", "extension": "c", "filename": "statistics.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 281649137, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2548, "license": "MIT", "license_type": "permissive", "path": "/ans/2/c/statistics.c", "provenance": "stackv2-0127.json.gz:67375", "repo_name": "silenc3502/ESPython001", "revision_date": "2020-10-20T13:04:16", "revision_id": "8efa5c4bb7be8a283cd74d8378dcb6ad9b0f4774", "snapshot_id": "0bc52ec2966234150e1b0716eff69845280ef3f2", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/silenc3502/ESPython001/8efa5c4bb7be8a283cd74d8378dcb6ad9b0f4774/ans/2/c/statistics.c", "visit_date": "2022-12-29T01:03:24.762372" }
stackv2
#include <time.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define AMOUNT_BIAS 100 #define AMOUNT_RANGE 101 #define NUM_RANGE 100 int partition(int *, int, int); void quicksort(int *, int, int); int init_rand_arr(int **arr) { int i; int rand_len; srand(time(NULL)); rand_len = rand() % AMOUNT_RANGE + AMOUNT_BIAS; *arr = (int *)malloc(sizeof(int) * rand_len); for(i = 0; i < rand_len; i++) { (*arr)[i] = rand() % NUM_RANGE; } return rand_len; } float calc_mean(int *arr, int rand_len) { int i; float sum = 0; for(i = 0; i < rand_len; i++) { sum += arr[i]; } return sum / rand_len; } float calc_median(int *arr, int rand_len) { int i; if(!(rand_len % 2)) { return (arr[rand_len / 2] + arr[rand_len / 2 - 1]) / 2.0f; } else { return arr[rand_len / 2]; } } void print_arr(int *arr, int len) { int i; int cnt = 0; for(i = 0; i < len; i++) { if(++cnt % 10) { printf("%3d, ", arr[i]); } else { printf("%3d\n", arr[i]); } } printf("\n"); } void swap(int *arr, int a, int b) { int tmp = arr[a]; arr[a] = arr[b]; arr[b] = tmp; } void quick_sort(int *arr, int left, int right) { if(left <= right) { int pivot = partition(arr, left, right); quick_sort(arr, left, pivot - 1); quick_sort(arr, pivot + 1, right); } } int partition(int *arr, int left, int right) { int pivot = arr[left]; int low = left + 1; int high = right; while(low <= high) { while(low <= right && pivot >= arr[low]) { low++; } while(high >= (left + 1) && pivot <= arr[high]) { high--; } if(low <= high) { swap(arr, low, high); } } swap(arr, left, high); return high; } float calc_var(int *arr, float mean, int len) { int i; float sum = 0; for(i = 0; i < len; i++) { sum += pow(arr[i] - mean, 2); } return sum / len; } float calc_std_dev(float var) { return sqrt(var); } int main(void) { float mean; float median; float variation; float std_dev; int *arr; int rand_len; rand_len = init_rand_arr(&arr); printf("Before Sort Data: \n"); print_arr(arr, rand_len); printf("After Sort Data: \n"); quick_sort(arr, 0, rand_len); print_arr(arr, rand_len); mean = calc_mean(arr, rand_len); printf("mean = %f\n", mean); median = calc_median(arr, rand_len); printf("median = %f\n", median); variation = calc_var(arr, mean, rand_len); printf("variation = %f\n", variation); std_dev = calc_std_dev(variation); printf("standard deviation = %f\n", std_dev); free(arr); return 0; }
3.484375
3
2024-11-18T20:53:26.618341+00:00
2016-02-02T09:31:15
ba6db03509c498b279e078eca32f10f26bd36d39
{ "blob_id": "ba6db03509c498b279e078eca32f10f26bd36d39", "branch_name": "refs/heads/master", "committer_date": "2016-02-02T09:31:15", "content_id": "aa47c7ba0769b07a54b4d2a9bbf9fa062be1691d", "detected_licenses": [ "MIT" ], "directory_id": "999acd67925cc22df7765cbbd6f5c1736533d3b1", "extension": "c", "filename": "test_sha2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 50908348, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6198, "license": "MIT", "license_type": "permissive", "path": "/testing/test_sha2.c", "provenance": "stackv2-0127.json.gz:67637", "repo_name": "nicolas314/mefs", "revision_date": "2016-02-02T09:31:15", "revision_id": "7ead41bac0f15c62ef6f8372da2e4458f8e094e5", "snapshot_id": "679e9e5e4a3f60632505dab20c8804921b8136e2", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/nicolas314/mefs/7ead41bac0f15c62ef6f8372da2e4458f8e094e5/testing/test_sha2.c", "visit_date": "2021-01-10T06:28:20.936871" }
stackv2
/* * FIPS 180-2 SHA-224/256/384/512 implementation * Last update: 02/02/2007 * Issue date: 04/30/2005 * * Copyright (C) 2005, 2007 Olivier Gay <olivier.gay@a3.epfl.ch> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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. */ /* * For inclusion in cachette, test vectors have been moved to a separate * file */ /* FIPS 180-2 Validation tests */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "sha2.h" void test(const char *vector, uint8_t *digest, unsigned int digest_size) { char output[2 * SHA512_DIGEST_SIZE + 1]; int i; output[2 * digest_size] = '\0'; for (i = 0; i < (int) digest_size ; i++) { sprintf(output + 2 * i, "%02x", digest[i]); } printf("H: %s\n", output); if (strcmp(vector, output)) { fprintf(stderr, "Test failed.\n"); exit(EXIT_FAILURE); } } int main(void) { static const char *vectors[4][3] = { /* SHA-224 */ { "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525", "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67", }, /* SHA-256 */ { "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0", }, /* SHA-384 */ { "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed" "8086072ba1e7cc2358baeca134c825a7", "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712" "fcc7c71a557e2db966c3e9fa91746039", "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b" "07b8b3dc38ecc4ebae97ddd87f3d8985", }, /* SHA-512 */ { "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018" "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909", "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb" "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b" } }; static const char message1[] = "abc"; static const char message2a[] = "abcdbcdecdefdefgefghfghighijhi" "jkijkljklmklmnlmnomnopnopq"; static const char message2b[] = "abcdefghbcdefghicdefghijdefghijkefghij" "klfghijklmghijklmnhijklmnoijklmnopjklm" "nopqklmnopqrlmnopqrsmnopqrstnopqrstu"; uint8_t *message3; unsigned int message3_len = 1000000; uint8_t digest[SHA512_DIGEST_SIZE]; message3 = malloc(message3_len); if (message3 == NULL) { fprintf(stderr, "Can't allocate memory\n"); return -1; } memset(message3, 'a', message3_len); printf("SHA-2 FIPS 180-2 Validation tests\n\n"); printf("SHA-224 Test vectors\n"); sha224((const uint8_t *) message1, strlen(message1), digest); test(vectors[0][0], digest, SHA224_DIGEST_SIZE); sha224((const uint8_t *) message2a, strlen(message2a), digest); test(vectors[0][1], digest, SHA224_DIGEST_SIZE); sha224(message3, message3_len, digest); test(vectors[0][2], digest, SHA224_DIGEST_SIZE); printf("\n"); printf("SHA-256 Test vectors\n"); sha256((const uint8_t *) message1, strlen(message1), digest); test(vectors[1][0], digest, SHA256_DIGEST_SIZE); sha256((const uint8_t *) message2a, strlen(message2a), digest); test(vectors[1][1], digest, SHA256_DIGEST_SIZE); sha256(message3, message3_len, digest); test(vectors[1][2], digest, SHA256_DIGEST_SIZE); printf("\n"); printf("SHA-384 Test vectors\n"); sha384((const uint8_t *) message1, strlen(message1), digest); test(vectors[2][0], digest, SHA384_DIGEST_SIZE); sha384((const uint8_t *)message2b, strlen(message2b), digest); test(vectors[2][1], digest, SHA384_DIGEST_SIZE); sha384(message3, message3_len, digest); test(vectors[2][2], digest, SHA384_DIGEST_SIZE); printf("\n"); printf("SHA-512 Test vectors\n"); sha512((const uint8_t *) message1, strlen(message1), digest); test(vectors[3][0], digest, SHA512_DIGEST_SIZE); sha512((const uint8_t *) message2b, strlen(message2b), digest); test(vectors[3][1], digest, SHA512_DIGEST_SIZE); sha512(message3, message3_len, digest); test(vectors[3][2], digest, SHA512_DIGEST_SIZE); printf("\n"); printf("All tests passed.\n"); return 0; }
2.328125
2
2024-11-18T20:53:26.712861+00:00
2021-02-16T22:21:03
21b216b5142c103368e28170ed1695cabc7efdb9
{ "blob_id": "21b216b5142c103368e28170ed1695cabc7efdb9", "branch_name": "refs/heads/main", "committer_date": "2021-02-16T22:21:03", "content_id": "7448148c4f7ca12eab8fa1d79217c98b93b66186", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "cfe9e1725e8995a090b9c8f2742373b1c79aa370", "extension": "c", "filename": "htable.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 321164588, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1601, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/htable.c", "provenance": "stackv2-0127.json.gz:67766", "repo_name": "project-kona/KTracker", "revision_date": "2021-02-16T22:21:03", "revision_id": "c8d57d6e573bcc41dad98765e7bacfb8b3f29788", "snapshot_id": "a2ec799206ea1cc9fe2f4ca1eb3c2c7d0c8e15d7", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/project-kona/KTracker/c8d57d6e573bcc41dad98765e7bacfb8b3f29788/src/htable.c", "visit_date": "2023-03-10T10:08:43.500153" }
stackv2
// Copyright © 2018-2021 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: BSD-2-Clause #include <unistd.h> #include <sys/user.h> #include "htable.h" void htable_init(htable_t *htable) { /* add space for iter and count */ htable->tble = malloc((TABLE_SIZE + 1) * 2*sizeof(uint64_t)); /* iter */ htable->tble[HTABLE_IDX_ITER] = 0; /* count */ htable->tble[HTABLE_IDX_COUNT] = 0; } void htable_add_iter(htable_t *htable, uint64_t iter) { htable->tble[HTABLE_IDX_ITER] = iter; htable->tble[HTABLE_IDX_COUNT] = 0; } void htable_add(htable_t *htable, uintptr_t vaddr, uintptr_t paddr) { uintptr_t page_vaddr = (vaddr & PAGE_MASK); uintptr_t cl_vaddr = (vaddr & CL_MASK); uint64_t tail = htable->tble[HTABLE_IDX_COUNT] + 1; int N = (vaddr - page_vaddr) / CL_SIZE; if ((tail > 1) && (htable->tble[2*tail - 2] == page_vaddr)) { /* same page */ htable->tble[2*tail-1] |= (1ULL << N); } else { /* add new page */ if (tail >= (TABLE_SIZE + 1)) { printf("Too many entriesi %lu!\n", tail); return; } htable->tble[2*tail] = page_vaddr; htable->tble[2*tail + 1] = (1ULL << N); htable->tble[HTABLE_IDX_COUNT]++; } } void htable_print(htable_t *htable, int fd, uint64_t iter) { #ifdef PB_WRITE_DCL uint64_t count = htable->tble[HTABLE_IDX_COUNT]; size_t size = 2*sizeof(uint64_t)*(count+1); if (count > 0) { ssize_t num_bytes = write(fd, (htable->tble), 2 * sizeof(uint64_t) * (count + 1)); if (num_bytes <= 0) { perror("Writing to dcl file failed"); } ASSERT(num_bytes == size); } #endif }
2.84375
3
2024-11-18T20:53:26.955091+00:00
2020-12-31T19:22:05
c4945388f50a05d9b504079e241f758bdae5c47c
{ "blob_id": "c4945388f50a05d9b504079e241f758bdae5c47c", "branch_name": "refs/heads/master", "committer_date": "2020-12-31T19:33:08", "content_id": "9e2d71d133c8343f864712489d3f025241dc4233", "detected_licenses": [ "MIT" ], "directory_id": "72a36ff85a550582400977bb795e271a9ecf1c59", "extension": "c", "filename": "mymath.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": 472, "license": "MIT", "license_type": "permissive", "path": "/1st semester/intro to programming/lab-5/Week5-samples/mymath.c", "provenance": "stackv2-0127.json.gz:68156", "repo_name": "ravinamani15/Assignments", "revision_date": "2020-12-31T19:22:05", "revision_id": "39370eb5befe7f34c12e8f0032be0985ee0434c3", "snapshot_id": "b9704991ebadd0acc2a4d3fafdaca18679da61b9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ravinamani15/Assignments/39370eb5befe7f34c12e8f0032be0985ee0434c3/1st semester/intro to programming/lab-5/Week5-samples/mymath.c", "visit_date": "2023-02-06T06:36:23.660446" }
stackv2
#include"mymath.h" #define PI 3.1416 // powermod(a,b,n) finds a^b modulo n. long powermod(long a,unsigned long b, long n) { unsigned long i=1; long result=1; while (i<=b) { result=(result*a)%n; i=i+1; } return result; } double circleArea(double radius) { double area; area=PI*radius*radius; return area; } // Finds a root of x^2-a double squareRoot(double a) { double x; int i=0; x=a/2; while (i<=100) { x=x-(x*x-a)/(2*x); i=i+1; } return x; }
3.0625
3
2024-11-18T20:53:27.396292+00:00
2020-11-22T17:48:14
4a6dfa67b86089754bf6d05b1723605afd3eda86
{ "blob_id": "4a6dfa67b86089754bf6d05b1723605afd3eda86", "branch_name": "refs/heads/main", "committer_date": "2020-11-22T17:48:14", "content_id": "fa99c1b6b41805948eca2d492175268cf7bc2867", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cdb31d5e4ee6fde90a22981d071265aa12bfb35d", "extension": "h", "filename": "Read.Write.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": 1376, "license": "Apache-2.0", "license_type": "permissive", "path": "/Headers/Read.Write.h", "provenance": "stackv2-0127.json.gz:68544", "repo_name": "mathpopo/Engine-Unreal", "revision_date": "2020-11-22T17:48:14", "revision_id": "1b5de98976561e05b4923d8099d9cf6a7dc2f60e", "snapshot_id": "386de0812230b94810b66cd509b6f21d804e3bb2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mathpopo/Engine-Unreal/1b5de98976561e05b4923d8099d9cf6a7dc2f60e/Headers/Read.Write.h", "visit_date": "2023-03-17T00:06:26.618876" }
stackv2
#ifndef _READ.WRITE_H_ #define _READ.WRITE_H_ #include <stdio.h> #define FILE_NAME "Project1.cm" char *Stlname[512]; int STLC1 = 0; void LoadSaves() { char path[128] = FILE_NAME; FILE *file = fopen("C://Screenshots//Project1.cm", "r"); fscanf(file, "%f\n", &PlanS); fscanf(file, "%d\n", &PC); fscanf(file, "%d\n", &CC); fscanf(file, "%d\n", &SC); fscanf(file, "%d\n", &COC); fscanf(file, "%d\n", &TC); fscanf(file, "%d\n", &MC); fscanf(file, "%d\n", &CYC); fscanf(file, "%d\n", &STLC1); /* // fscanf(file, "%s\n", &STL_name); for(int i = 0; i <= STLC1; i++) { // printf("%s\n", BlenderPath[0]); // printf("%s\n", BlenderPath[1]); fscanf(file, "%s\n", &Stlname[i]); printf("%s\n", &Stlname[i]); blender_file_data[i] = load_bin(Stlname[i], &blender_file_size[i]); // render_blender(0); } */ fclose(file); } void WriteSaves() { char path[128] = FILE_NAME; FILE* fp = fopen("C://Screenshots//Project1.cm", "w"); fprintf(fp, "%f\n", PlanS); fprintf(fp, "%d\n", PC); fprintf(fp, "%d\n", CC); fprintf(fp, "%d\n", SC); fprintf(fp, "%d\n", COC); fprintf(fp, "%d\n", TC); fprintf(fp, "%d\n", MC); fprintf(fp, "%d\n", CYC); fprintf(fp, "%d\n", STLC); /* for(int i = 1; i <= blender_file_count; i++) { fprintf(fp, "%s\n", BlenderPath[i]); } */ fclose(fp); } #endif
2.078125
2
2024-11-18T20:53:27.686929+00:00
2020-01-24T08:29:03
ec60d7fae91d7611efa67da5466cd3e2a99cdc81
{ "blob_id": "ec60d7fae91d7611efa67da5466cd3e2a99cdc81", "branch_name": "refs/heads/master", "committer_date": "2020-01-24T08:29:03", "content_id": "ed2f5f3408837869ae091bd68cea116370c61053", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ae1b8a5fec08e85f56aa4904c7d40cbeb205ba29", "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": 231419487, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 616, "license": "Apache-2.0", "license_type": "permissive", "path": "/01-Compiler Project/main.c", "provenance": "stackv2-0127.json.gz:68935", "repo_name": "MahmoudFawzy01/C-Projects", "revision_date": "2020-01-24T08:29:03", "revision_id": "3d364cc486db611abcfb0d8e6ddd84b2676ee8a6", "snapshot_id": "7be96b9058a25358bcef14e0249dcaf754719cd6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MahmoudFawzy01/C-Projects/3d364cc486db611abcfb0d8e6ddd84b2676ee8a6/01-Compiler Project/main.c", "visit_date": "2020-12-03T17:57:18.320864" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "file_manger.h" #include "Brac_Checking.h" #include "./LexicalAndParser/Compiler_LexicalAndParserPhases.h" int main() { char Buffer[255]; int lineCounts,index; initLexicalAndParserPhases(); char * p = CreateFile(); Compiler_CheckBract(p); lineCounts = countLinesExists(); // to remove the start of the file GetLine (Buffer,255); for (index = 1; index < lineCounts ; index++) { memset(Buffer,0,strlen(Buffer)); GetLine (Buffer,255); checkWords(Buffer,index); } CloseFile(p); }
2.03125
2
2024-11-18T20:53:29.400938+00:00
2012-06-09T23:22:05
8f75d8aab2141cfe70600b9ae8e267132cf9001d
{ "blob_id": "8f75d8aab2141cfe70600b9ae8e267132cf9001d", "branch_name": "refs/heads/master", "committer_date": "2012-06-09T23:22:05", "content_id": "89471b6087c6bc5e4eddac212fb301eb608a8518", "detected_licenses": [ "MIT" ], "directory_id": "17cc4ad73c2e00070772f3ace0e4d8b0fde3e409", "extension": "c", "filename": "metadata.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": 10425, "license": "MIT", "license_type": "permissive", "path": "/src/libmew/metadata.c", "provenance": "stackv2-0127.json.gz:69451", "repo_name": "libsync/libsync-legacy", "revision_date": "2012-06-09T23:22:05", "revision_id": "0e78906fe8f33fda01cb848aeb7061a2b1ba74b6", "snapshot_id": "00a036fcc8d4164435b9a24ea94f23a124cbf161", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/libsync/libsync-legacy/0e78906fe8f33fda01cb848aeb7061a2b1ba74b6/src/libmew/metadata.c", "visit_date": "2016-09-05T16:05:57.482807" }
stackv2
#include <stdlib.h> #include <stdio.h> #include <openssl/evp.h> #include "metadata.h" #include "connector.h" #include "crypto.h" struct _metadata_t { metadata_entry_t **table; size_t table_size, table_len; time_t last_date; }; void metadata_init (metadata_t * data) { /* Initialize the data structure */ *data = (metadata_t) malloc (sizeof (struct _metadata_t)); (*data)->table_size = 16; (*data)->table = (metadata_entry_t **) malloc ( (*data)->table_size * sizeof (metadata_entry_t *)); (*data)->table_len = 0; (*data)->last_date = 0; } enum metadata_update metadata_update_put (metadata_t data, connector_t conn, crypto_sym_t crypto) { char *tmp_data, *tmp_str; time_t new_date; int ret; size_t tmp_size, tmp_len, tmp_pos, array_size; size_t i, len, amount, struct_size; ssize_t table_pos; unsigned long version, time; /* Initialize the data segment */ tmp_len = 0; tmp_size = 2 * sizeof (unsigned long); tmp_data = (char *) malloc (tmp_size * sizeof (char)); /* Setup Version Information */ *((unsigned long *) tmp_data) = htonl(1); tmp_len = sizeof (unsigned long); /* Determine table size */ array_size = 0; for (i = 0; i < data->table_len; i++) if (data->table[i]->filename != NULL) array_size++; *((unsigned long *) (tmp_data + tmp_len)) = htonl(array_size); tmp_len += sizeof (unsigned long); /* Encode each of the metadata entries */ for (i = 0; i < data->table_len; i++) { if (data->table[i]->filename == NULL) continue; /* Calculate struct size */ len = strlen (data->table[i]->filename) * sizeof (char); tmp_pos = len + sizeof (unsigned long) * 3 + sizeof (char) * 1; tmp_pos += 64 * sizeof (char); /* Make sure the tmp data is large enough */ if (tmp_len + tmp_pos > tmp_size) { while (tmp_len + tmp_pos > tmp_size) tmp_size <<= 1; tmp_data = (char *) realloc (tmp_data, tmp_size); } /* Move the string into tmpdata */ *((unsigned long *) (tmp_data + tmp_len)) = htonl (len); tmp_len += sizeof (unsigned long); memcpy(tmp_data + tmp_len, data->table[i]->filename, len); tmp_len += len; /* Move the rest of the struct */ *((unsigned long *) (tmp_data + tmp_len)) = htonl (data->table[i]->timestamp); tmp_len += sizeof (unsigned long); *((unsigned long *) (tmp_data + tmp_len)) = htonl (data->table[i]->mark); tmp_len += sizeof (unsigned long); tmp_data[tmp_len++] = data->table[i]->deleted; /* Move the object name into tmpdata */ memcpy (tmp_data + tmp_len, data->table[i]->objname, 64*sizeof (char)); tmp_len += 64*sizeof (char); } /* Send the Data to the server */ ret = connector_put (conn, "metadata", (void*)tmp_data, tmp_len, crypto); free (tmp_data); if (ret != CONNECTOR_SUCCESS) return METADATA_PUSH_FAILED; return METADATA_SUCCESS; } enum metadata_update metadata_update_get (metadata_t data, connector_t conn, crypto_sym_t crypto) { char *tmp_data, *tmp_str; time_t new_date; int ret; size_t tmp_size, tmp_len, tmp_pos, array_size; size_t i, len, amount, struct_size; ssize_t table_pos; unsigned long version, time; /* Get the Update Time */ ret = connector_get_timestamp (conn, "metadata", &new_date); if (ret != CONNECTOR_DOESNT_EXIST && ret != CONNECTOR_SUCCESS) return METADATA_DOWNLOAD_FAILED; /* Retrieve Updated Metadata */ tmp_data = NULL; tmp_size = 0; tmp_len = 0; if (ret == CONNECTOR_SUCCESS && new_date != data->last_date) { ret = connector_get (conn, "metadata", (void **)&tmp_data, &tmp_size, &tmp_len, crypto); if (ret != CONNECTOR_DOESNT_EXIST && ret != CONNECTOR_SUCCESS) return METADATA_DOWNLOAD_FAILED; } /* Clear Updated Flags */ for (i = 0; i < data->table_len; i++) data->table[i]->updated = 0; /* Parse Updated Binary */ if (ret == CONNECTOR_SUCCESS && new_date != data->last_date) { /* Update the Structure Date */ data->last_date = new_date; /* Check Version */ if (tmp_len < sizeof (unsigned long)) { free (tmp_data); return METADATA_INVALID; } version = ntohl (*((unsigned long *) tmp_data)); if (version > 1 || version == 0) { free (tmp_data); return METADATA_INVALID_VERSION; } tmp_pos = sizeof (unsigned long); /* Version 1 Check */ if (version == 1) { /* Get the amount of entries */ if (tmp_len < tmp_pos || tmp_len - tmp_pos < sizeof (unsigned long)) { free (tmp_data); return METADATA_INVALID; } amount = ntohl(*((unsigned long *) (tmp_data + tmp_pos))); tmp_pos += sizeof (unsigned long); /* Iterate over all data */ for (i = 0; i < amount; i++) { /* Get the length of the string */ if (tmp_len < tmp_pos || tmp_len - tmp_pos < sizeof (unsigned long)) { free (tmp_data); return METADATA_INVALID; } len = ntohl(*((unsigned long *) (tmp_data + tmp_pos))); tmp_pos += sizeof (unsigned long); /* Determine if we have enough stored data */ struct_size = len * sizeof (char); struct_size += 2 * sizeof (unsigned long); struct_size += 1 * sizeof (char); struct_size += 64 * sizeof (char); if (tmp_len < tmp_pos || tmp_len - tmp_pos < struct_size) { free (tmp_data); return METADATA_INVALID; } /* Retrieve the string */ tmp_str = (char *) malloc ((len+1) * sizeof (char)); memcpy (tmp_str, tmp_data + tmp_pos, len); tmp_str[len] = 0; tmp_pos += len * sizeof (char); /* See if the entry already exists */ table_pos = metadata_get_index (data, tmp_str); /* Add a new entry */ if (table_pos == -1) { /* Make sure we have enough table data */ if (data->table_len >= data->table_size) { data->table_size <<= 1; data->table = (metadata_entry_t **) realloc (data->table, data->table_size * sizeof (metadata_entry_t *)); } table_pos = data->table_len++; data->table[table_pos] = (metadata_entry_t *) malloc (sizeof (metadata_entry_t)); data->table[table_pos]->timestamp = 0; data->table[table_pos]->filename = tmp_str; } else free (tmp_str); /* Update the entry if the timestamp is correct */ time = ntohl (*((unsigned long *)(tmp_data + tmp_pos))); tmp_pos += sizeof (unsigned long); if (data->table[table_pos]->timestamp < time) { data->table[table_pos]->timestamp = time; /* Set the mark */ data->table[table_pos]->mark = ntohl (*((unsigned long *)(tmp_data + tmp_pos))); /* Set boolean chars */ data->table[table_pos]->deleted = tmp_data[tmp_pos+sizeof(unsigned long)]; data->table[table_pos]->updated = 1; /* Copy Object Name */ memcpy (data->table[table_pos]->objname, tmp_data+tmp_pos+sizeof (unsigned long)+sizeof (char), 64 * sizeof (char)); data->table[table_pos]->objname[64] = 0; } else if (data->table[table_pos]->timestamp > time) data->table[table_pos]->updated = 2; tmp_pos += sizeof(unsigned long) + sizeof (char) + 64 * sizeof (char); data->table[table_pos]->updated |= 4; } } } /* Check to see if we have new files */ for (i = 0; i < data->table_len; i++) if (data->table[i]->updated == 0) data->table[i]->updated = 2; /* Free Temporary Data */ if (tmp_data != NULL) free (tmp_data); return METADATA_SUCCESS; } enum metadata_update metadata_wait_update (metadata_t data, connector_t conn, crypto_sym_t crypto) { return metadata_update_get (data, conn, crypto); } ssize_t metadata_get_index (metadata_t data, const char * filename) { size_t i; /* Compare each index to see if it matches */ for (i = 0; i < data->table_len; i++) if (filename != NULL && strcmp (data->table[i]->filename, filename) == 0) return i; return -1; } metadata_entry_t * metadata_get_entry (metadata_t data, size_t index) { return data->table[index]; } metadata_entry_t * metadata_insert (metadata_t data) { metadata_entry_t *entry; /* Make sure we have enough room for the new entry */ if (data->table_len >= data->table_size) { data->table_size <<= 1; data->table = (metadata_entry_t **) realloc (data->table, data->table_size * sizeof (metadata_entry_t *)); } /* Initialize New Entry */ entry = (metadata_entry_t *) malloc (sizeof (metadata_entry_t)); entry->filename = NULL; entry->mark = 0; entry->updated = 0; entry->deleted = 0; entry->timestamp = 0; /* Add Entry to the Table */ data->table[data->table_len++] = entry; return entry; } size_t metadata_len (metadata_t data) { return data->table_len; } void metadata_destroy (metadata_t data) { size_t i; /* Iterate over the array freeing each entry */ for (i = 0; i < data->table_len; i++) { if (data->table[i]->filename != NULL) free (data->table[i]->filename); free (data->table[i]); } /* Free the initial data structure */ free (data->table); free (data); } void metadata_print (metadata_t data) { size_t i; metadata_entry_t* entry; /* Iterate over the array printing each entry */ for (i = 0; i < data->table_len; i++) { entry = data->table[i]; if (entry->filename != NULL) { printf ("Filename: %s\n", entry->filename); printf ("Timestamp: %ul\n", entry->timestamp); printf ("Mark: %ul\n", entry->mark); printf ("Updated: %d\n", entry->updated); printf ("Deleted: %d\n", entry->deleted); printf ("--------------------------------------------------\n"); } } } int metadata_object_name (metadata_entry_t * entry, char * filename) { unsigned char hash[32], buffer[2048], *ret; EVP_MD_CTX md; FILE *file; int size; /* Attempt to open the directory */ file = fopen (filename, "rb"); if (file == NULL) return -1; /* Initialize Hash Context */ EVP_MD_CTX_init (&md); EVP_DigestInit_ex (&md, EVP_sha256(), NULL); /* Read and Hash the File */ while((size = fread (buffer, sizeof (char), 2048, file)) > 0) EVP_DigestUpdate (&md, buffer, size); /* Generate and report hash */ EVP_DigestFinal_ex (&md, hash, &size); EVP_MD_CTX_cleanup (&md); ret = crypto_bytes_to_hex (hash, size); memcpy (entry->objname, ret, strlen(ret) + 1); free (ret); return 0; }
2.515625
3
2024-11-18T20:53:29.561101+00:00
2021-08-08T03:18:44
530e8cb62bcf3433eb796d614a47247ab9705703
{ "blob_id": "530e8cb62bcf3433eb796d614a47247ab9705703", "branch_name": "refs/heads/main", "committer_date": "2021-08-08T03:18:44", "content_id": "5fde5fb356120d58d78b1421d7ff11859f17c3fe", "detected_licenses": [ "MIT" ], "directory_id": "a58896b7abdaf4cf60007986778b13ad2591051c", "extension": "c", "filename": "BITM.C", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 393842216, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1946, "license": "MIT", "license_type": "permissive", "path": "/WATCOM_32bit/GUG/BITM/BITM.C", "provenance": "stackv2-0127.json.gz:69581", "repo_name": "nebosite/groundup", "revision_date": "2021-08-08T03:18:44", "revision_id": "667cbb1250ceb6a518969adbdcdd8e1455241529", "snapshot_id": "5e6f6ff8cefd7ca58733ad9fe1c2baae01a355a5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nebosite/groundup/667cbb1250ceb6a518969adbdcdd8e1455241529/WATCOM_32bit/GUG/BITM/BITM.C", "visit_date": "2023-07-03T18:26:23.797493" }
stackv2
#include "stdio.h" #include "malloc.h" #include "..\lib1\gug.h" #include "..\lib1\keydefs.h" #include "..\lib1\colors.h" void main() { char *spr[5]; char *bgd[5]; char *gug[5]; char *nspr; int xs,ys; int x,y; int flag = 0; char *mes; float rt; mes = malloc(120); GUGLoadSprite("sship.spr",bgd); GUGLoadSprite("32x32.spr",spr); GUGLoadSprite("gug.spr",gug); GUGInitialize(); if (!GUGJoystickCalibrate()) { GUGEnd(); printf("Error - No joysticks were detected!\n"); return; } GUGStartKeyboard(); GUGInitTimer(); xs = GUGSpriteWidth(spr[0]); ys = GUGSpriteHeight(spr[0]); x = 10; y = 10; do { delay(1); if (flag == 0) { x = GUGScaleX1Axis(); if (x < 1) x = 1; if (x > 100) x = 100; } else { y = GUGScaleY1Axis(); if (y < 1) y = 1; if (y > 100) y = 100; } GUGFastClear(VGA_START); // GUGPutFGSprite(0, 0,spr[0]); GUGStartTimer(); GUGResizeSpriteToRectangle(spr[0],0,0,x,y); rt = GUGStopTimer(); rt = rt / 1193.0; nspr = GUGResizeSpriteToSprite(spr[0],x,y); // GUGPutFGSprite(160, 0,spr[0]); if (nspr != NULL) GUGPutFGSprite(160,0,nspr); free(nspr); sprintf(mes,"Move the joystick: X:%3d Y:%3d",x,y); GUGPutText(0,180,215,mes); sprintf(mes,"RT:%5.2fmS",rt); GUGPutText(50,190,215,mes); // GUGPutFGSprite(0,100,bgd[0]); GUGStartTimer(); GUGResizeSpriteToRectangle(bgd[0],0,100,x,y+100); rt = GUGStopTimer(); rt = rt / 1193.0; nspr = GUGResizeSpriteToSprite(bgd[0],x,y); // GUGPutFGSprite(160,100,bgd[0]); if (nspr != NULL) GUGPutFGSprite(160,100,nspr); free(nspr); sprintf(mes,"RT:%5.2fmS",rt); GUGPutText(230,190,215,mes); // GUGFastCopy(VGA_START); GUGCopyToDisplay(); ++flag; flag &= 1; if (GUG_key_table[ESC] == KEY_IS_DOWN) flag = -1; } while (flag >= 0); GUGStopKeyboard(); GUGEnd(); }
2.375
2
2024-11-18T20:53:29.684613+00:00
2023-03-22T03:05:00
3a8c56fd35eca21281d75154b9d9c2ff8d015fe3
{ "blob_id": "3a8c56fd35eca21281d75154b9d9c2ff8d015fe3", "branch_name": "refs/heads/master", "committer_date": "2023-03-22T03:05:00", "content_id": "aa14f64a4676909e832f4a65226f88651131e8eb", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c434f0466868b5d7b38ae344dca0abf620045faf", "extension": "c", "filename": "main.c", "fork_events_count": 11, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 122421022, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 29733, "license": "Apache-2.0", "license_type": "permissive", "path": "/SampleCode/RegBased/CAN_Test_MaskFilter/main.c", "provenance": "stackv2-0127.json.gz:69710", "repo_name": "OpenNuvoton/M451BSP", "revision_date": "2023-03-22T03:05:00", "revision_id": "835ded99dec3776db16015b7c0ae155d7877e2fd", "snapshot_id": "bf950163a1c4ba87e64b7d6d4a50c1e5c7956471", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/OpenNuvoton/M451BSP/835ded99dec3776db16015b7c0ae155d7877e2fd/SampleCode/RegBased/CAN_Test_MaskFilter/main.c", "visit_date": "2023-04-15T22:25:26.377643" }
stackv2
/**************************************************************************** * @file main.c * @version V3.0 * $Revision: 7 $ * $Date: 15/09/02 10:03a $ * @brief * Use message object No.1 to send message objects (ID=0x700~0x70F). * This sample code needs to work with CAN_Set_MaskFilter. * @note * Copyright (C) 2014~2015 Nuvoton Technology Corp. All rights reserved. * ******************************************************************************/ #include <stdio.h> #include "M451Series.h" #define PLLCTL_SETTING CLK_PLLCTL_72MHz_HXT #define PLL_CLOCK 72000000 /*---------------------------------------------------------------------------*/ /* Function Declare */ /*---------------------------------------------------------------------------*/ extern char GetChar(void); void CANShowMsg(STR_CANMSG_T* Msg); /*---------------------------------------------------------------------------*/ /* Callback function */ /*---------------------------------------------------------------------------*/ /* Declare a CAN message structure */ STR_CANMSG_T rrMsg; /*---------------------------------------------------------------------------------------------------------*/ /* Clear interrupt pending bit */ /*---------------------------------------------------------------------------------------------------------*/ void ClrIntPendingGBit(CAN_T *tCAN, uint8_t u32MsgNum) { uint32_t u32MsgIfNum = 0; uint32_t u32IFBusyCount = 0; while(u32IFBusyCount < 0x10000000) { if((tCAN->IF[0].CREQ & CAN_IF_CREQ_BUSY_Msk) == 0) { u32MsgIfNum = 0; break; } else if((tCAN->IF[1].CREQ & CAN_IF_CREQ_BUSY_Msk) == 0) { u32MsgIfNum = 1; break; } u32IFBusyCount++; } tCAN->IF[u32MsgIfNum].CMASK = CAN_IF_CMASK_CLRINTPND_Msk | CAN_IF_CMASK_TXRQSTNEWDAT_Msk; tCAN->IF[u32MsgIfNum].CREQ = 1 + u32MsgNum; } /*---------------------------------------------------------------------------------------------------------*/ /* Gets the message */ /*---------------------------------------------------------------------------------------------------------*/ int32_t ReadMsgObj(CAN_T *tCAN, uint8_t u8MsgObj, STR_CANMSG_T* pCanMsg) { uint32_t u32TimeOutCnt; if(!CAN_GET_NEW_DATA_IN_BIT(tCAN, u8MsgObj)) { return FALSE; } tCAN->STATUS &= (~CAN_STATUS_RXOK_Msk); /* read the message contents */ tCAN->IF[1].CMASK = CAN_IF_CMASK_MASK_Msk | CAN_IF_CMASK_ARB_Msk | CAN_IF_CMASK_CONTROL_Msk | CAN_IF_CMASK_CLRINTPND_Msk | CAN_IF_CMASK_TXRQSTNEWDAT_Msk | CAN_IF_CMASK_DATAA_Msk | CAN_IF_CMASK_DATAB_Msk; tCAN->IF[1].CREQ = 1 + u8MsgObj; /* Wait */ u32TimeOutCnt = CAN_TIMEOUT; while(tCAN->IF[1].CREQ & CAN_IF_CREQ_BUSY_Msk) { if(--u32TimeOutCnt == 0) { printf("Wait for CAN_IF1_CREQ register busy flag is cleared time-out!\n"); return FALSE; } } if((tCAN->IF[1].ARB2 & CAN_IF_ARB2_XTD_Msk) == 0) { /* standard ID */ pCanMsg->IdType = CAN_STD_ID; pCanMsg->Id = (tCAN->IF[1].ARB2 & CAN_IF_ARB2_ID_Msk) >> 2; } else { /* extended ID */ pCanMsg->IdType = CAN_EXT_ID; pCanMsg->Id = (((tCAN->IF[1].ARB2) & 0x1FFF) << 16) | tCAN->IF[1].ARB1; } pCanMsg->DLC = tCAN->IF[1].MCON & CAN_IF_MCON_DLC_Msk; pCanMsg->Data[0] = tCAN->IF[1].DAT_A1 & CAN_IF_DAT_A1_DATA0_Msk; pCanMsg->Data[1] = (tCAN->IF[1].DAT_A1 & CAN_IF_DAT_A1_DATA1_Msk) >> CAN_IF_DAT_A1_DATA1_Pos; pCanMsg->Data[2] = tCAN->IF[1].DAT_A2 & CAN_IF_DAT_A2_DATA2_Msk; pCanMsg->Data[3] = (tCAN->IF[1].DAT_A2 & CAN_IF_DAT_A2_DATA3_Msk) >> CAN_IF_DAT_A2_DATA3_Pos; pCanMsg->Data[4] = tCAN->IF[1].DAT_B1 & CAN_IF_DAT_B1_DATA4_Msk; pCanMsg->Data[5] = (tCAN->IF[1].DAT_B1 & CAN_IF_DAT_B1_DATA5_Msk) >> CAN_IF_DAT_B1_DATA5_Pos; pCanMsg->Data[6] = tCAN->IF[1].DAT_B2 & CAN_IF_DAT_B2_DATA6_Msk; pCanMsg->Data[7] = (tCAN->IF[1].DAT_B2 & CAN_IF_DAT_B2_DATA7_Msk) >> CAN_IF_DAT_B2_DATA7_Pos; return TRUE; } /*---------------------------------------------------------------------------------------------------------*/ /* ISR to handle CAN interrupt event */ /*---------------------------------------------------------------------------------------------------------*/ void MsgInterrupt(CAN_T *tCAN, uint32_t u32IIDR) { if(u32IIDR == 1) { printf("Msg-0 INT and Callback\n"); ReadMsgObj(tCAN, 0, &rrMsg); CANShowMsg(&rrMsg); } if(u32IIDR == 5 + 1) { printf("Msg-5 INT and Callback \n"); ReadMsgObj(tCAN, 5, &rrMsg); CANShowMsg(&rrMsg); } if(u32IIDR == 31 + 1) { printf("Msg-31 INT and Callback \n"); ReadMsgObj(tCAN, 31, &rrMsg); CANShowMsg(&rrMsg); } } /*---------------------------------------------------------------------------------------------------------*/ /* CAN0 interrupt handler */ /*---------------------------------------------------------------------------------------------------------*/ void CAN0_IRQHandler(void) { uint32_t u8IIDRstatus; u8IIDRstatus = CAN0->IIDR; if(u8IIDRstatus == 0x00008000) /* Check Status Interrupt Flag (Error status Int and Status change Int) */ { /**************************/ /* Status Change interrupt*/ /**************************/ if(CAN0->STATUS & CAN_STATUS_RXOK_Msk) { CAN0->STATUS &= ~CAN_STATUS_RXOK_Msk; /* Clear RxOK status*/ } if(CAN0->STATUS & CAN_STATUS_TXOK_Msk) { CAN0->STATUS &= ~CAN_STATUS_TXOK_Msk; /* Clear TxOK status*/ } /**************************/ /* Error Status interrupt */ /**************************/ if(CAN0->STATUS & CAN_STATUS_BOFF_Msk) { printf("BOFF INT\n") ; } else if(CAN0->STATUS & CAN_STATUS_EWARN_Msk) { printf("EWARN INT\n") ; } else if((CAN0->ERR & CAN_ERR_TEC_Msk) != 0) { printf("Transmit error!\n") ; } else if((CAN0->ERR & CAN_ERR_REC_Msk) != 0) { printf("Receive error!\n") ; } } else if(u8IIDRstatus != 0) { MsgInterrupt(CAN0, u8IIDRstatus); ClrIntPendingGBit(CAN0, (u8IIDRstatus - 1)); /* Clear Interrupt Pending */ } else if(CAN0->WU_STATUS == 1) { printf("Wake up\n"); CAN0->WU_STATUS = 0; /* Write '0' to clear */ } } /*---------------------------------------------------------------------------------------------------------*/ /* Reset message interface parameters */ /*---------------------------------------------------------------------------------------------------------*/ void ResetIF(CAN_T *tCAN, uint8_t u8IF_Num) { if(u8IF_Num > 1) return; tCAN->IF[u8IF_Num].CREQ = 0x0; // set bit15 for sending tCAN->IF[u8IF_Num].CMASK = 0x0; tCAN->IF[u8IF_Num].MASK1 = 0x0; // useless in basic mode tCAN->IF[u8IF_Num].MASK2 = 0x0; // useless in basic mode tCAN->IF[u8IF_Num].ARB1 = 0x0; // ID15~0 tCAN->IF[u8IF_Num].ARB2 = 0x0; // MsgVal, eXt, xmt, ID28~16 tCAN->IF[u8IF_Num].MCON = 0x0; // DLC tCAN->IF[u8IF_Num].DAT_A1 = 0x0; // data0,1 tCAN->IF[u8IF_Num].DAT_A2 = 0x0; // data2,3 tCAN->IF[u8IF_Num].DAT_B1 = 0x0; // data4,5 tCAN->IF[u8IF_Num].DAT_B2 = 0x0; // data6,7 } /*---------------------------------------------------------------------------*/ /* Show Message Function */ /*---------------------------------------------------------------------------*/ void CANShowMsg(STR_CANMSG_T* Msg) { uint8_t i; /* Show the message information */ printf("Read ID=0x%X, Type=%s, DLC=%d, Data=", Msg->Id, Msg->IdType ? "EXT" : "STD", Msg->DLC); for(i = 0; i < Msg->DLC; i++) printf("%X,", Msg->Data[i]); printf("\n\n"); } void SYS_Init(void) { /*---------------------------------------------------------------------------------------------------------*/ /* Init System Clock */ /*---------------------------------------------------------------------------------------------------------*/ /* Enable HIRC clock (Internal RC 22.1184MHz) */ CLK->PWRCTL |= CLK_PWRCTL_HIRCEN_Msk; /* Waiting for HIRC clock ready */ while(!(CLK->STATUS & CLK_STATUS_HIRCSTB_Msk)); /* Select HCLK clock source as HIRC and HCLK clock divider as 1 */ CLK->CLKSEL0 &= ~CLK_CLKSEL0_HCLKSEL_Msk; CLK->CLKSEL0 |= CLK_CLKSEL0_HCLKSEL_HIRC; CLK->CLKDIV0 &= ~CLK_CLKDIV0_HCLKDIV_Msk; CLK->CLKDIV0 |= CLK_CLKDIV0_HCLK(1); /* Set PLL to Power-down mode and PLLSTB bit in CLK_STATUS register will be cleared by hardware.*/ CLK->PLLCTL |= CLK_PLLCTL_PD_Msk; /* Enable HXT clock (external XTAL 12MHz) */ CLK->PWRCTL |= CLK_PWRCTL_HXTEN_Msk; /* Waiting for HXT clock ready */ while(!(CLK->STATUS & CLK_STATUS_HXTSTB_Msk)); /* Set core clock as PLL_CLOCK from PLL */ CLK->PLLCTL = PLLCTL_SETTING; while(!(CLK->STATUS & CLK_STATUS_PLLSTB_Msk)); CLK->CLKSEL0 &= (~CLK_CLKSEL0_HCLKSEL_Msk); CLK->CLKSEL0 |= CLK_CLKSEL0_HCLKSEL_PLL; /* Update System Core Clock */ PllClock = PLL_CLOCK; // PLL SystemCoreClock = PLL_CLOCK / 1; // HCLK CyclesPerUs = PLL_CLOCK / 1000000; // For CLK_SysTickDelay() /* Enable UART module clock */ CLK->APBCLK0 |= CLK_APBCLK0_UART0CKEN_Msk; /* Select UART module clock source as HXT and UART module clock divider as 1 */ CLK->CLKSEL1 &= ~CLK_CLKSEL1_UARTSEL_Msk; CLK->CLKSEL1 |= CLK_CLKSEL1_UARTSEL_HXT; CLK->CLKDIV0 &= ~CLK_CLKDIV0_UARTDIV_Msk; CLK->CLKDIV0 |= CLK_CLKDIV0_UART(1); /* Enable CAN0 module clock */ CLK->APBCLK0 |= CLK_APBCLK0_CAN0CKEN_Msk; /*---------------------------------------------------------------------------------------------------------*/ /* Init I/O Multi-function */ /*---------------------------------------------------------------------------------------------------------*/ /* Set PD multi-function pins for UART0 RXD and TXD */ SYS->GPD_MFPL &= ~(SYS_GPD_MFPL_PD0MFP_Msk | SYS_GPD_MFPL_PD1MFP_Msk); SYS->GPD_MFPL |= (SYS_GPD_MFPL_PD0MFP_UART0_RXD | SYS_GPD_MFPL_PD1MFP_UART0_TXD); /* Set PA multi-function pins for CANTX0 and CANRX0 */ SYS->GPA_MFPL &= ~(SYS_GPA_MFPL_PA0MFP_Msk | SYS_GPA_MFPL_PA1MFP_Msk); SYS->GPA_MFPL |= SYS_GPA_MFPL_PA1MFP_CAN0_TXD | SYS_GPA_MFPL_PA0MFP_CAN0_RXD; } /*---------------------------------------------------------------------------------------------------------*/ /* Init UART */ /*---------------------------------------------------------------------------------------------------------*/ void UART0_Init() { /* Reset UART IP */ SYS->IPRST1 |= SYS_IPRST1_UART0RST_Msk; SYS->IPRST1 &= ~SYS_IPRST1_UART0RST_Msk; /* Configure UART0 and set UART0 baud rate */ UART0->BAUD = UART_BAUD_MODE2 | UART_BAUD_MODE2_DIVIDER(__HXT, 115200); UART0->LINE = UART_WORD_LEN_8 | UART_PARITY_NONE | UART_STOP_BIT_1; } /*----------------------------------------------------------------------------*/ /* Some description about how to create test environment */ /*----------------------------------------------------------------------------*/ void NoteConfigure() { printf("\n\n"); printf("+--------------------------------------------------------------------------+\n"); printf("| About CAN sample code configure |\n"); printf("+--------------------------------------------------------------------------+\n"); printf("| The sample code provide a simple sample code for you study CAN |\n"); printf("| Before execute it, please check description as below |\n"); printf("| |\n"); printf("| 1.CAN_TX and CAN_RX should be connected to your CAN transceiver |\n"); printf("| 2.Using two module board and connect to the same CAN BUS |\n"); printf("| 3.Check the terminal resistor of bus is connected |\n"); printf("| 4.Using UART0 as print message port |\n"); printf("| |\n"); printf("| |--------| |-----------| CANBUS |-----------| |--------| |\n"); printf("| | |------>| |<--------->| |<------| | |\n"); printf("| | |CAN_TX | CAN | CAN_H | CAN |CAN_TX | | |\n"); printf("| | M451 | |Transceiver| |Transceiver| | M451 | |\n"); printf("| | |<------| |<--------->| |------>| | |\n"); printf("| | |CAN_RX | | CAN_L | |CAN_RX | | |\n"); printf("| |--------| |-----------| |-----------| |--------| |\n"); printf("| | | |\n"); printf("| | | |\n"); printf("| V V |\n"); printf("| UART0 UART0 |\n"); printf("|(print message) (print message) |\n"); printf("+--------------------------------------------------------------------------+\n"); } /*----------------------------------------------------------------------------*/ /* Test Menu */ /*----------------------------------------------------------------------------*/ void TestItem(void) { printf("\n"); printf("+------------------------------------------------------------------ +\n"); printf("| Nuvoton CAN BUS DRIVER DEMO |\n"); printf("+-------------------------------------------------------------------+\n"); printf("| |\n"); printf("| Test Mask Filter |\n"); printf("| (At first, another module board should be set to |\n"); printf("| [CAN_Set_MaskFilter] waiting for receiving data) |\n"); printf("| |\n"); printf("+-------------------------------------------------------------------+\n"); } /*----------------------------------------------------------------------------*/ /* Get current bit rate */ /*----------------------------------------------------------------------------*/ uint32_t GetCANBitRate(CAN_T *tCAN) { uint8_t u8Tseg1, u8Tseg2; uint32_t u32Bpr; u8Tseg1 = (tCAN->BTIME & CAN_BTIME_TSEG1_Msk) >> CAN_BTIME_TSEG1_Pos; u8Tseg2 = (tCAN->BTIME & CAN_BTIME_TSEG2_Msk) >> CAN_BTIME_TSEG2_Pos; u32Bpr = (tCAN->BTIME & CAN_BTIME_BRP_Msk) | (tCAN->BRPE << 6); return (SystemCoreClock / (u32Bpr + 1) / (u8Tseg1 + u8Tseg2 + 3)); } /*----------------------------------------------------------------------------*/ /* Set target baud-rate and Basic mode */ /*----------------------------------------------------------------------------*/ uint32_t CANInit(CAN_T *tCAN, uint32_t u32BaudRate) { uint8_t u8Tseg1, u8Tseg2; uint32_t u32Brp; uint32_t u32Value; uint32_t u32TimeOutCnt; /* Set the CAN to enter initialization mode and enable access bit timing register */ tCAN->CON |= CAN_CON_INIT_Msk; tCAN->CON |= CAN_CON_CCE_Msk; SystemCoreClockUpdate(); u8Tseg1 = 2; u8Tseg2 = 1; u32Value = SystemCoreClock / u32BaudRate; while(1) { if(((u32Value % (u8Tseg1 + u8Tseg2 + 3)) == 0)) break; if(u8Tseg1 < 7) u8Tseg2++; if((u32Value % (u8Tseg1 + u8Tseg2 + 3)) == 0) break; if(u8Tseg1 < 15) u8Tseg1++; else { u8Tseg1 = 2; u8Tseg2 = 1; break; } } u32Brp = SystemCoreClock / (u32BaudRate) / (u8Tseg1 + u8Tseg2 + 3) - 1; u32Value = ((uint32_t)u8Tseg2 << CAN_BTIME_TSEG2_Pos) | ((uint32_t)u8Tseg1 << CAN_BTIME_TSEG1_Pos) | (u32Brp & CAN_BTIME_BRP_Msk) | (tCAN->BTIME & CAN_BTIME_SJW_Msk); tCAN->BTIME = u32Value; tCAN->BRPE = (u32Brp >> 6) & 0x0F; /* Set the CAN to leave initialization mode */ tCAN->CON &= (~(CAN_CON_INIT_Msk | CAN_CON_CCE_Msk)); /* Check INIT bit is released */ u32TimeOutCnt = CAN_TIMEOUT; while(tCAN->CON & CAN_CON_INIT_Msk) { if(--u32TimeOutCnt == 0) { printf("Wait for CAN to leave initialization mode time-out!\n"); return 0; } } return (GetCANBitRate(tCAN)); } /*----------------------------------------------------------------------------*/ /* Check the real baud-rate */ /*----------------------------------------------------------------------------*/ void BaudRateCheck(uint32_t u32BaudRate, uint32_t u32RealBaudRate) { /* Get Core Clock Frequency */ SystemCoreClockUpdate(); if(u32BaudRate != u32RealBaudRate) { printf("\nSet CAN baud-rate is fail\n"); printf("Real baud-rate value(bps): %d\n", u32RealBaudRate); printf("CAN baud-rate calculation equation as below:\n"); printf("CAN baud-rate(bps) = Fin/(BPR+1)*(Tseg1+Tseg2+3)\n"); printf("where: Fin: System clock freq.(Hz)\n"); printf(" BRP: The baud rate prescale. It is composed of BRP (CAN_BTIME[5:0]) and BRPE (CAN_BRPE[3:0]).\n"); printf(" Tseg1: Time Segment before the sample point. You can set tseg1 (CAN_BTIME[11:8]).\n"); printf(" Tseg2: Time Segment after the sample point. You can set tseg2 (CAN_BTIME[14:12]).\n"); if(SystemCoreClock % u32BaudRate != 0) printf("\nThe BPR does not calculate, the Fin must be a multiple of the CAN baud-rate.\n"); else printf("\nThe BPR does not calculate, the (Fin/(CAN baud-rate)) must be a multiple of the (Tseg1+Tseg1+3).\n"); } else printf("\nReal baud-rate value(bps): %d\n", u32RealBaudRate); } /*----------------------------------------------------------------------------*/ /* Set the CAN speed */ /*----------------------------------------------------------------------------*/ void SelectCANSpeed(CAN_T *tCAN) { uint32_t unItem, BaudRate = 0, RealBaudRate = 0; printf("Please select CAN speed you desired\n"); printf("[0] 1000Kbps\n"); printf("[1] 800Kbps\n"); printf("[2] 500Kbps\n"); printf("[3] 250Kbps\n"); printf("[4] 125Kbps\n"); printf("[5] 100Kbps\n"); printf("[6] 50Kbps\n"); unItem = GetChar(); printf("%c\n", unItem); switch(unItem) { case '0': BaudRate = 1000000; RealBaudRate = CANInit(tCAN, BaudRate);//Set target baud-rate and operation mode. break; case '1': BaudRate = 800000; RealBaudRate = CANInit(tCAN, BaudRate); break; case '2': BaudRate = 500000; RealBaudRate = CANInit(tCAN, BaudRate); break; case '3': BaudRate = 250000; RealBaudRate = CANInit(tCAN, BaudRate); break; case '4': BaudRate = 125000; RealBaudRate = CANInit(tCAN, BaudRate); break; case '5': BaudRate = 100000; RealBaudRate = CANInit(tCAN, BaudRate); break; case '6': BaudRate = 50000; RealBaudRate = CANInit(tCAN, BaudRate); break; } /* Check the real baud-rate is OK */ BaudRateCheck(BaudRate, RealBaudRate); } /*---------------------------------------------------------------------------------------------------------*/ /* Disable CAN */ /*---------------------------------------------------------------------------------------------------------*/ void StopCAN(void) { /* Disable CAN0 Clock and Reset it */ SYS->IPRST2 |= SYS_IPRST1_CAN0RST_Msk; /* CAN0 controller reset */ SYS->IPRST2 &= ~SYS_IPRST1_CAN0RST_Msk; /* CAN0 controller normal operation */ CLK->APBCLK0 &= ~CLK_APBCLK0_CAN0CKEN_Msk; /* CAN0 clock disabled */ } /*---------------------------------------------------------------------------------------------------------*/ /* Check if SmartCard slot is presented */ /*---------------------------------------------------------------------------------------------------------*/ static uint32_t GetFreeIF(CAN_T *tCAN) { /* Check Read/write action has finished */ if((tCAN->IF[0].CREQ & CAN_IF_CREQ_BUSY_Msk) == 0) return 0; else if((tCAN->IF[1].CREQ & CAN_IF_CREQ_BUSY_Msk) == 0) return 1; else return 2; } /*----------------------------------------------------------------------------*/ /* The function is used to configure a transmit object */ /*----------------------------------------------------------------------------*/ int32_t SetTxMsgObj(CAN_T *tCAN, uint8_t u8MsgObj, STR_CANMSG_T* pCanMsg) { /* Set the Message Buffer Register */ uint8_t u8MsgIfNum = 0; /* Check Free Interface for configure */ if((u8MsgIfNum = GetFreeIF(tCAN)) == 2) { return FALSE; } /* Update the contents needed for transmission*/ tCAN->IF[u8MsgIfNum].CMASK = CAN_IF_CMASK_WRRD_Msk /* Transfer data from the selected Message Buffer Registers to the Message Object addressed */ | CAN_IF_CMASK_MASK_Msk /* Transfer Identifier Mask + MDir + MXtd to Message Object. */ | CAN_IF_CMASK_ARB_Msk /* Transfer Identifier + Dir + Xtd + MsgVal to Message Object */ | CAN_IF_CMASK_CONTROL_Msk /* Transfer Control Bits to Message Object */ | CAN_IF_CMASK_DATAA_Msk /* Transfer Data Bytes [3:0] to Message Object */ | CAN_IF_CMASK_DATAB_Msk; /* Transfer Data Bytes [7:4] to Message Object */ if(pCanMsg->IdType == CAN_STD_ID) { /* Set the Standard ID(11-bit), Message Direction and Message Valid for IFn Arbitration Register */ tCAN->IF[u8MsgIfNum].ARB1 = 0; tCAN->IF[u8MsgIfNum].ARB2 = (((pCanMsg->Id) & 0x7FF) << 2) | CAN_IF_ARB2_DIR_Msk | CAN_IF_ARB2_MSGVAL_Msk; } else { /* Set the Extended ID(29-bit), Message Direction, Extended Identifier and Message Valid for IFn Arbitration Register */ tCAN->IF[u8MsgIfNum].ARB1 = (pCanMsg->Id) & 0xFFFF; tCAN->IF[u8MsgIfNum].ARB2 = ((pCanMsg->Id) & 0x1FFF0000) >> 16 | CAN_IF_ARB2_DIR_Msk | CAN_IF_ARB2_XTD_Msk | CAN_IF_ARB2_MSGVAL_Msk; } if(pCanMsg->FrameType) tCAN->IF[u8MsgIfNum].ARB2 |= CAN_IF_ARB2_DIR_Msk; /* The Message Object is transmitted as a Data Frame */ else tCAN->IF[u8MsgIfNum].ARB2 &= (~CAN_IF_ARB2_DIR_Msk); /* The Remote Frame with the identifier of this Message Object is transmitted */ /* Set the data for IFn Data Register */ tCAN->IF[u8MsgIfNum].DAT_A1 = ((uint16_t)pCanMsg->Data[1] << 8) | pCanMsg->Data[0]; tCAN->IF[u8MsgIfNum].DAT_A2 = ((uint16_t)pCanMsg->Data[3] << 8) | pCanMsg->Data[2]; tCAN->IF[u8MsgIfNum].DAT_B1 = ((uint16_t)pCanMsg->Data[5] << 8) | pCanMsg->Data[4]; tCAN->IF[u8MsgIfNum].DAT_B2 = ((uint16_t)pCanMsg->Data[7] << 8) | pCanMsg->Data[6]; /* Update the contents needed for transmission*/ tCAN->IF[u8MsgIfNum].MCON = CAN_IF_MCON_NEWDAT_Msk | pCanMsg->DLC | CAN_IF_MCON_TXIE_Msk | CAN_IF_MCON_EOB_Msk; /* Set the Message Object in the Message RAM is selected for data transfer */ tCAN->IF[u8MsgIfNum].CREQ = 1 + u8MsgObj; return TRUE; } /*----------------------------------------------------------------------------*/ /* Set transmit request bit */ /*----------------------------------------------------------------------------*/ uint32_t SetTxRqst(CAN_T *tCAN, uint8_t u8MsgObj) { /* CAN message structure*/ STR_CANMSG_T rMsg; /* Gets the message */ ReadMsgObj(tCAN, u8MsgObj, &rMsg); /* Access Transmission Request Bit */ tCAN->IF[0].CMASK = CAN_IF_CMASK_WRRD_Msk | CAN_IF_CMASK_TXRQSTNEWDAT_Msk ; /* Set the Message Object in the Message RAM is selected for data transfer */ tCAN->IF[0].CREQ = 1 + u8MsgObj; return TRUE; } /*----------------------------------------------------------------------------*/ /* Test Mask Filter Function */ /*----------------------------------------------------------------------------*/ void TestMaskFilter(CAN_T *tCAN) { int32_t i32id = 0; /* Declare a CAN message structure */ STR_CANMSG_T tMsg; printf("Use Message Object No.1 to send ID=0x700 ~0x70F\n"); printf("Enter any key to send\n "); GetChar(); /* Enable CAN interrupt */ tCAN->CON |= (CAN_CON_IE_Msk | CAN_CON_SIE_Msk); /* Install CAN call back functions */ NVIC_SetPriority(CAN0_IRQn, (1 << __NVIC_PRIO_BITS) - 2); /* Enable corresponding NVIC of CAN */ NVIC_EnableIRQ(CAN0_IRQn); while(1) { /* Send a 11-bit Standard Identifier message */ tMsg.FrameType = CAN_DATA_FRAME; /* Set the Frame Type */ tMsg.IdType = CAN_STD_ID; /* Set the Identifier Type */ tMsg.Id = 0x700 + i32id; /* Set the Message Identifier */ tMsg.DLC = 0; /* Set the Data Length Code */ /* Call CAN_SetTxMsgObj() only Configure Msg RAM */ if(SetTxMsgObj(tCAN, MSG(1), &tMsg) < 0) { printf("Set Tx Msg Object failed\n"); return; } /* Set transmit request bit */ SetTxRqst(tCAN, MSG(1)); // /* Check the message has been successfully transmitted */ // while((tCAN->STATUS & CAN_STATUS_TXOK_Msk) == 0); // /* Clear TXOK flag */ // tCAN->STATUS &= ~CAN_STATUS_TXOK_Msk; /* Generate the Delay Time by Systick */ CLK_SysTickDelay(100000); i32id++; if(i32id >= 0x10) break; } printf("\nCheck the receive host received data\n"); } /*---------------------------------------------------------------------------------------------------------*/ /* MAIN function */ /*---------------------------------------------------------------------------------------------------------*/ int main(void) { CAN_T *tCAN; tCAN = (CAN_T *) CAN0; //tCAN = (CAN_T *) CAN1; /* Unlock protected registers */ SYS_UnlockReg(); /* Init System, IP clock and multi-function I/O */ SYS_Init(); /* Lock protected registers */ SYS_LockReg(); /* Init UART0 for printf */ UART0_Init(); /*---------------------------------------------------------------------------------------------------------*/ /* SAMPLE CODE */ /*---------------------------------------------------------------------------------------------------------*/ // /* Set GPB12 to control CAN transceiver for Nuvoton board */ // PB12 = 0; /* Some description about how to create test environment */ NoteConfigure(); /* Configuring the Bit Timing */ SelectCANSpeed(tCAN); /* Test Menu */ TestItem(); printf("Test Mask Filter\n\n"); printf("Please confirm [CAN_Set_MaskFilter] of receiver is selected.\n"); printf("Press any key to continue ...\n\n"); GetChar(); /* Use Message Object No.1 to send ID=0x700~0x70F */ TestMaskFilter(tCAN); /* Disable CAN */ StopCAN(); while(1); }
2.296875
2
2024-11-18T20:53:29.778889+00:00
2018-06-25T06:06:02
d66708d6d6ff665ebb9c3563eaae830d5d8b2b46
{ "blob_id": "d66708d6d6ff665ebb9c3563eaae830d5d8b2b46", "branch_name": "refs/heads/master", "committer_date": "2018-06-25T06:06:02", "content_id": "6e143855a4e030de30b018e7f7f7d96867a6295c", "detected_licenses": [ "MIT" ], "directory_id": "c2c9f467b6b2eecd05a11092a54ea95d47468a0b", "extension": "c", "filename": "acpi.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 135921577, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1628, "license": "MIT", "license_type": "permissive", "path": "/hardware/acpi.c", "provenance": "stackv2-0127.json.gz:69839", "repo_name": "liva/syspro2018-baremetal", "revision_date": "2018-06-25T06:06:02", "revision_id": "98f2e74bfe5b24f8e14a6c6bf19e52437d74c3c7", "snapshot_id": "b92be94db042bd97429cb49b51812fb8ad97c065", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/liva/syspro2018-baremetal/98f2e74bfe5b24f8e14a6c6bf19e52437d74c3c7/hardware/acpi.c", "visit_date": "2020-03-19T05:20:16.965187" }
stackv2
/* * acpi.h * written by Shinichi Awamoto, 2017 * * ACPI関連の関数の定義 */ #include "acpi.h" #include "common.h" struct rsdt { struct acpi_sdt_header h; uint32_t ptr_to_other_sdt[0]; } __attribute__((packed)); static struct rsdt *rsdt = NULL; extern void panic(); void acpi_init(struct rsdp_descriptor *rsdp) { if (rsdp == NULL) { panic(); } if (__builtin_strncmp(rsdp->signature, "RSD PTR ", 8) == 0) { rsdt = (struct rsdt *)(uint64_t)rsdp->rsdt_address; } } // ACPI 2.0 HPET Description Tableを取得するための関数 // 戻り値:見つからなかった場合はNULLを返す struct hpet_descriptor *acpi_get_hpet_desc() { if (rsdt == NULL) { return NULL; } int entries = (rsdt->h.length - sizeof(rsdt->h)) / 4; for (int i = 0; i < entries; i++) { struct acpi_sdt_header *h = (struct acpi_sdt_header *)(uint64_t)rsdt->ptr_to_other_sdt[i]; if (__builtin_strncmp(h->signature, "HPET", 4) == 0) { struct hpet_descriptor *hpet = (struct hpet_descriptor *)h; return hpet; } } return NULL; } // MADT取得関数 // 戻り値:見つからなかった場合はNULLを返す struct apic_descriptor *acpi_get_apic_desc() { if (rsdt == NULL) { return NULL; } int entries = (rsdt->h.length - sizeof(rsdt->h)) / 4; for (int i = 0; i < entries; i++) { struct acpi_sdt_header *h = (struct acpi_sdt_header *)(uint64_t)rsdt->ptr_to_other_sdt[i]; if (__builtin_strncmp(h->signature, "APIC", 4) == 0) { struct apic_descriptor *madt = (struct apic_descriptor *)h; return madt; } } return NULL; }
2.484375
2
2024-11-18T20:53:30.091452+00:00
2023-07-24T08:08:17
175f0f93e4bdfaf685314d80cd6406af2c9ebec4
{ "blob_id": "175f0f93e4bdfaf685314d80cd6406af2c9ebec4", "branch_name": "refs/heads/master", "committer_date": "2023-07-24T08:08:17", "content_id": "d273d0728255b483398edcc0c2fbc8ef8e7e1ddb", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1ed1ece5a776aad35da152133a14a4cee60e34d2", "extension": "c", "filename": "main.c", "fork_events_count": 21, "gha_created_at": "2019-12-16T07:30:56", "gha_event_created_at": "2023-09-12T06:47:09", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 228328445, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4634, "license": "Apache-2.0", "license_type": "permissive", "path": "/examples/hid_keyboard/src/main.c", "provenance": "stackv2-0127.json.gz:70225", "repo_name": "ingchips/ING918XX_SDK_SOURCE", "revision_date": "2023-07-24T08:08:17", "revision_id": "69c2fa62b457a7dbbb0bc581e923ee6039d9cf41", "snapshot_id": "71596b93eee5658e1a512adf910a168235ea59c0", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/ingchips/ING918XX_SDK_SOURCE/69c2fa62b457a7dbbb0bc581e923ee6039d9cf41/examples/hid_keyboard/src/main.c", "visit_date": "2023-08-31T23:48:31.413047" }
stackv2
#include "profile.h" #include "ingsoc.h" #include "platform_api.h" #include "kv_storage.h" #include "btstack_util.h" #include "eflash.h" #include <string.h> #include <stdio.h> #include "trace.h" #include "board.h" #define PRINT_UART APB_UART0 uint32_t cb_hard_fault(hard_fault_info_t *info, void *_) { platform_printf("HARDFAULT:\n" "PC : 0x%08X\n" "LR : 0x%08X\n" "PSR: 0x%08X\n" "R0 : 0x%08X\n" "R1 : 0x%08X\n" "R2 : 0x%08X\n" "P3 : 0x%08X\n" "R12: 0x%08X\n", info->pc, info->lr, info->psr, info->r0, info->r1, info->r2, info->r3, info->r12); for (;;); } uint32_t cb_putc(char *c, void *dummy) { while (apUART_Check_TXFIFO_FULL(PRINT_UART) == 1); UART_SendData(PRINT_UART, (uint8_t)*c); return 0; } int fputc(int ch, FILE *f) { cb_putc((char *)&ch, NULL); return ch; } void config_uart(uint32_t freq, uint32_t baud) { UART_sStateStruct UART_0; UART_0.word_length = UART_WLEN_8_BITS; UART_0.parity = UART_PARITY_NOT_CHECK; UART_0.fifo_enable = 1; UART_0.two_stop_bits = 0; //used 2 stop bit , 0 UART_0.receive_en = 1; UART_0.transmit_en = 1; UART_0.UART_en = 1; UART_0.cts_en = 0; UART_0.rts_en = 0; UART_0.rxfifo_waterlevel = 1; //UART_FIFO_ONE_SECOND; UART_0.txfifo_waterlevel = 1; //UART_FIFO_ONE_SECOND; UART_0.ClockFrequency = freq; UART_0.BaudRate = baud; apUART_Initialize(PRINT_UART, &UART_0, 1 << bsUART_RECEIVE_INTENAB); } #define KB_KEY_1 GIO_GPIO_1 #define KB_KEY_2 GIO_GPIO_5 #define KB_KEY_3 GIO_GPIO_7 #define KEY_MASK ((1 << KB_KEY_1) | (1 << KB_KEY_2) | (1 << KB_KEY_3)) void setup_peripherals(void) { config_uart(OSC_CLK_FREQ, 115200); SYSCTRL_ClearClkGateMulti( (1 << SYSCTRL_ClkGate_APB_GPIO0) | (1 << SYSCTRL_ClkGate_APB_GPIO1) | (1 << SYSCTRL_ClkGate_APB_PinCtrl)); // setup GPIOs for keys setup_keys(); } extern void kb_state_changed(uint16_t key_state); extern void kb_input_char(char c); uint32_t gpio_isr(void *user_data) { uint32_t current = ~GIO_ReadAll(); uint16_t v = 0; // report which keys are pressed if (current & (1 << KB_KEY_1)) v |= 1; if (current & (1 << KB_KEY_2)) v |= 2; if (current & (1 << KB_KEY_3)) v |= 4; kb_state_changed(v); GIO_ClearAllIntStatus(); return 0; } #if (INGCHIPS_FAMILY == INGCHIPS_FAMILY_918) #define DB_FLASH_ADDRESS 0x42000 #elif (INGCHIPS_FAMILY == INGCHIPS_FAMILY_916) #define DB_FLASH_ADDRESS 0x2042000 #else #error unknown or unsupported chip family #endif int db_write_to_flash(const void *db, const int size) { platform_printf("write to flash, size = %d\n", size); printf_hexdump(db, size); program_flash(DB_FLASH_ADDRESS, (const uint8_t *)db, size); return KV_OK; } int read_from_flash(void *db, const int max_size) { memcpy(db, (void *)DB_FLASH_ADDRESS, max_size); return KV_OK; } uint32_t uart_isr(void *user_data) { uint32_t status; while(1) { status = apUART_Get_all_raw_int_stat(PRINT_UART); if (status == 0) break; PRINT_UART->IntClear = status; // rx int if (status & (1 << bsUART_RECEIVE_INTENAB)) { while (apUART_Check_RXFIFO_EMPTY(PRINT_UART) != 1) { char c = PRINT_UART->DataRead; kb_input_char(c); } } } return 0; } trace_rtt_t trace_ctx = {0}; int app_main() { // If there are *three* crystals on board, *uncomment* below line. // Otherwise, below line should be kept commented out. // platform_set_rf_clk_source(0); platform_set_irq_callback(PLATFORM_CB_IRQ_GPIO, gpio_isr, NULL); setup_peripherals(); // platform_config(PLATFORM_CFG_LOG_HCI, PLATFORM_CFG_ENABLE); platform_set_evt_callback(PLATFORM_CB_EVT_PUTC, (f_platform_evt_cb)cb_putc, NULL); platform_set_evt_callback(PLATFORM_CB_EVT_HARD_FAULT, (f_platform_evt_cb)cb_hard_fault, NULL); platform_set_evt_callback(PLATFORM_CB_EVT_PROFILE_INIT, setup_profile, NULL); platform_set_irq_callback(PLATFORM_CB_IRQ_UART0, uart_isr, NULL); kv_init(db_write_to_flash, read_from_flash); trace_rtt_init(&trace_ctx); platform_set_evt_callback(PLATFORM_CB_EVT_TRACE, (f_platform_evt_cb)cb_trace_rtt, &trace_ctx); platform_config(PLATFORM_CFG_TRACE_MASK, 0x1ff); return 0; }
2.140625
2
2024-11-18T20:53:30.411513+00:00
2021-01-19T17:00:25
80ace8f379caffd8c36041c8bb4116ba7e4e9b14
{ "blob_id": "80ace8f379caffd8c36041c8bb4116ba7e4e9b14", "branch_name": "refs/heads/master", "committer_date": "2021-01-19T17:00:25", "content_id": "13ab9dae99a39b61c6398095e3f6e135b981972d", "detected_licenses": [ "MIT" ], "directory_id": "b4f4ba50b3200091dc155ca322e4350b124be39f", "extension": "c", "filename": "LEAPYEAR.C", "fork_events_count": 0, "gha_created_at": "2020-08-24T11:09:34", "gha_event_created_at": "2020-08-24T11:09:35", "gha_language": null, "gha_license_id": "MIT", "github_id": 289905370, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1112, "license": "MIT", "license_type": "permissive", "path": "/C Programs/Control Statements/LEAPYEAR.C", "provenance": "stackv2-0127.json.gz:70742", "repo_name": "sagar-barapatre/OpenEDU", "revision_date": "2021-01-19T17:00:25", "revision_id": "90e65b411df6bbda1057f3abda7dc4fd732c8364", "snapshot_id": "b7fd53555d5d5046f2374c2df102aac36149b083", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/sagar-barapatre/OpenEDU/90e65b411df6bbda1057f3abda7dc4fd732c8364/C Programs/Control Statements/LEAPYEAR.C", "visit_date": "2023-02-20T01:30:13.598350" }
stackv2
/* Leap year - Program to check whether a given year is a leap year. Centennial years are leap years only when they are divisible by 400 */ /* The program can give one of the following four outputs: 1-- not a leap year 2-- leap year 3-- centennial but not a leap year 4-- centennial and a leap year */ #include <stdio.h> #include <conio.h> void main() { int y ; clrscr() ; printf("Enter any year: ") ; scanf("%d" , &y) ; if(y%4 == 0) { if(y%100 != 0) /* checks whether y is not centennial */ printf("%d is a leap year \n" , y); else if( y%400 == 0) /* checks whether centennial year is divisible by 400 */ printf("%d is a centennial leap year \n" , y); else printf("%d is a centennial but not a leap year \n" , y); } else printf("%d is not a leap year \n" , y); getch(); } /* 4 Outputs: Enter any year: 2012 2012 is a leap year Enter any year: 2013 2013 is not a leap year Enter any year: 2000 2000 is a centennial leap year Enter any year: 1900 1900 is a centennial but not a leap year */
3.890625
4
2024-11-18T20:53:30.625635+00:00
2022-06-16T13:42:25
fed14a7a07f61735832315d1d7a78178537bac6d
{ "blob_id": "fed14a7a07f61735832315d1d7a78178537bac6d", "branch_name": "refs/heads/master", "committer_date": "2022-06-16T13:42:25", "content_id": "fb69d912923341285598822c0fcc12ab533d2e30", "detected_licenses": [ "MIT" ], "directory_id": "a6c41a3afec655e173d520edbb8cd2fed827e052", "extension": "c", "filename": "pointers-cast-2.c", "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": 3503, "license": "MIT", "license_type": "permissive", "path": "/004.9pointers-cast-2/pointers-cast-2.c", "provenance": "stackv2-0127.json.gz:70999", "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/004.9pointers-cast-2/pointers-cast-2.c", "visit_date": "2022-06-18T05:25:08.913279" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> // https://stackoverflow.com/a/3974138/974287 // assumes little endian void print_bits(size_t const size, void const * const ptr) { unsigned char *b = (unsigned char*) ptr; unsigned char byte; int i, j; for (i=size-1;i>=0;i--) { for (j=7;j>=0;j--) { byte = (b[i] >> j) & 1; printf("%u", byte); } } } void print_char_bits(unsigned char bb) { print_bits(sizeof(unsigned char), &bb); printf("\n"); } void print_short_int_bits(unsigned short int bb) { print_bits(sizeof(unsigned short int), &bb); printf("\n"); } int main(int argc, char * argv[]) { unsigned char b; int i; unsigned int * iptr; unsigned char * cptr; /////// esempio 1 // puntatore a int, operatore indirizzo (&), operatore indirezione (*) unsigned int prova = 0xADD1CAFE; /* Little endian Big endian +----+----+----+----+ +----+----+----+----+ |0xFE|0xCA|0xD1|0xAD| |0xAD|0xD1|0xCA|0xFE| +----+----+----+----+ +----+----+----+----+ byte: 0 1 2 3 0 1 2 3 */ printf("esempio 1\n"); iptr = &prova; printf("1: prova = %08x\n", prova); printf("2: *iptr = %08x\n", *iptr); // accedo alla zona di memoria il cui indirizzo si trova in iptr printf("\n\n"); /////// esempio 2 // cast da puntatore a uint a puntatore a char, incremento puntatore a char printf("esempio 2:\n"); cptr = (unsigned char *) &prova; printf("1: %x\n", *cptr); cptr++; // incrementa di 1 printf("2: %x\n", *cptr); cptr++; printf("3: %x\n", *cptr); cptr++; printf("4: %x\n", *cptr); printf("\n\n"); /////// esempio 3 (esercizio) // printf("esempio 3\n"); unsigned char add1_cafe[] = {0xA, 0xD, 0xD, 0x1, 0xC, 0xA, 0xF, 0xE}; unsigned int add1_cafe_final = 0; // 0xADD1CAFE; /* ESERCIZIO: * * a partire da add1_cafe, vogliamo arrivare a add1_cafe_final con questo valore: Little endian +----+----+----+----+ |0xFE|0xCA|0xD1|0xAD| +----+----+----+----+ 0 1 2 3 */ unsigned char bytes[4]; // << è l'operatore "shift left" printf("var = 0x%08x , binary: ", 0xF); print_short_int_bits(0xF); printf("var << 4 = 0x%08x , binary: ", 0xF << 4); print_short_int_bits(0xF << 4); printf("var << 8 = 0x%08x , binary: ", 0xF << 8); print_short_int_bits(0xF << 8); printf("var << 12 = 0x%08x , binary: ", 0xF << 12); print_short_int_bits(0xF << 12); printf("\n"); // ... // ... // | è l'operatore aritmetico OR printf("0xA = 0x%08x , binary: ", 0xA); print_short_int_bits(0xA); printf("0xB = 0x%08x , binary: ", 0xB); print_short_int_bits(0xB); printf("0xA << 4 = 0x%08x , binary: ", 0xA << 4); print_short_int_bits(0xA << 4); printf("0xA0 | 0xB= 0x%08x , binary: ", 0xA << 4 | 0xB); print_short_int_bits(0xA << 4 | 0xB); printf("\n"); // {0xA, 0xD, 0xD, 0x1, 0xC, 0xA, 0xF, 0xE}; // 0 1 2 3 4 5 6 7 // 0x AD D1 CA FE // F << 4 | E = FE // ESERCIZIO: COMPLETARE gli indici bytes[0] = add1_cafe[6] << 4 | add1_cafe[7]; // FE bytes[1] = add1_cafe[4] << 4 | add1_cafe[5]; // CA bytes[2] = add1_cafe[2] << 4 | add1_cafe[3]; // D1 bytes[3] = add1_cafe[0] << 4 | add1_cafe[1]; // AD add1_cafe_final = *((unsigned *)bytes); // come output vogliamo: add1cafe printf("add1_cafe_final = 0x%08x\n", add1_cafe_final); printf("\n\n"); return 0; }
3.5625
4
2024-11-18T20:53:30.965668+00:00
2021-09-24T21:20:06
262479e487d3e9442bc0f1f0c5245896f213bf42
{ "blob_id": "262479e487d3e9442bc0f1f0c5245896f213bf42", "branch_name": "refs/heads/master", "committer_date": "2021-09-24T21:20:06", "content_id": "ce035351f917ca1d43ea7fec2428f48d3d28c5e1", "detected_licenses": [ "MIT" ], "directory_id": "859c7702acb643557f7cb6de1e8d4adf20ea358c", "extension": "c", "filename": "runnable_tapenade.c", "fork_events_count": 1, "gha_created_at": "2019-03-12T17:26:57", "gha_event_created_at": "2021-09-24T21:29:18", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 175263974, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3603, "license": "MIT", "license_type": "permissive", "path": "/tests/utils/static_code/runnable_tapenade.c", "provenance": "stackv2-0127.json.gz:71389", "repo_name": "geometryprocessing/acorns-benchmark", "revision_date": "2021-09-24T21:20:06", "revision_id": "df5f43af90a32f4c1578cdea1f4f412237e18c75", "snapshot_id": "a0ebc6f74c223ca71ed8a3f2df1e7b3c8a341a8e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/geometryprocessing/acorns-benchmark/df5f43af90a32f4c1578cdea1f4f412237e18c75/tests/utils/static_code/runnable_tapenade.c", "visit_date": "2023-08-11T11:32:49.141348" }
stackv2
#ifdef _WIN32 #include <windows.h> #endif #include <math.h> #include <stdlib.h> #include <inttypes.h> #include <time.h> #include <stdio.h> #include <stdint.h> void read_file_to_array(char *filename, double *args, int num_params, int num_vars) { FILE *file = fopen(filename, "r"); if (file != NULL) { char line[200]; int i = 0; for (int i = 0; i < num_params * num_vars; i++) { fscanf(file, "%lf", &args[i]); } fclose(file); } else { perror(filename); /* why didn't the file open? */ } } void function_0_b(double a, double *ab, double b, double *bb, double c, double *cb, double d, double *db, double function_0b) { double p = 0; double pb = 0.0; double temp; double temp0; double tempb; double tempb0; double function_0; pb = function_0b; temp = a * d - b * c; temp0 = 1.0 / temp; tempb = (temp0 + 1) * pb; tempb0 = -(temp0 * (a * a + b * b + c * c + d * d) * pb / temp); *ab = *ab + d * tempb0 + 2 * a * tempb; *db = *db + a * tempb0 + 2 * d * tempb; *bb = *bb + 2 * b * tempb - c * tempb0; *cb = *cb + 2 * c * tempb - b * tempb0; } /* Expects command line arguments: num_params num_vars params_filename output_filename */ int main(int argc, char *argv[]) { printf("I am running..."); // read command line arguments char *ptr; int num_params = (int)strtol(argv[1], &ptr, 10); int num_vars = (int)strtol(argv[2], &ptr, 10); char *params_filename = argv[3]; char *output_filename = argv[4]; double *values = malloc(num_params * num_vars * sizeof(double)); double *ders = malloc(num_params * num_vars * sizeof(double)); read_file_to_array(params_filename, values, num_params, num_vars); #ifdef _WIN32 LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds; LARGE_INTEGER Frequency; QueryPerformanceFrequency(&Frequency); QueryPerformanceCounter(&StartingTime); // Activity to be timed // compute(values, num_params, ders); QueryPerformanceCounter(&EndingTime); ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart; // ElapsedMicroseconds.QuadPart *= 1000000; // ElapsedMicroseconds.QuadPart /= Frequency.QuadPart; double delta = (ElapsedMicroseconds.QuadPart) / (double)Frequency.QuadPart; // seconds #else struct timespec tstart = {0, 0}, tend = {0, 0}; clock_gettime(CLOCK_MONOTONIC, &tstart); for (int i = 0; i < num_params; i++) { double a = values[i* 4 + 0]; double ab = 0; double b = values[i* 4 + 1]; double bb = 0; double c = values[i* 4 + 2]; double cb = 0; double d = values[i* 4 + 3]; double db = 0; double function_0b = 1; function_0_b(a, &ab, b, &bb, c, &cb, d, &db, function_0b); ders[i * 4 + 0] = ab; ders[i * 4 + 1] = bb; ders[i * 4 + 2] = cb; ders[i * 4 + 3] = db; } clock_gettime(CLOCK_MONOTONIC, &tend); double delta = ((double)tend.tv_sec + 1.0e-9 * tend.tv_nsec) - ((double)tstart.tv_sec + 1.0e-9 * tstart.tv_nsec); // seconds #endif FILE *fp; fp = fopen(output_filename, "w+"); // printf("%f ", delta); fprintf(fp, "%f ", delta); for (int i = 0; i < num_params * num_vars; i++) { fprintf(fp, "%f ", ders[i]); // printf("%f", ders[i]); } fclose(fp); return 0; }
2.46875
2
2024-11-18T20:53:31.592882+00:00
2021-08-26T01:13:28
d9c56eedf2a4ea59fa10d02010d470634334b8b3
{ "blob_id": "d9c56eedf2a4ea59fa10d02010d470634334b8b3", "branch_name": "refs/heads/master", "committer_date": "2021-08-26T01:13:28", "content_id": "7b2fb7c664effa920195fe5515dffb7d7f4aefe1", "detected_licenses": [ "BSD-3-Clause", "NCSA", "MIT" ], "directory_id": "cd899a08a4e3d14f84b73f4f774443e3401fb0a1", "extension": "c", "filename": "cmd_mmc.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": 3066, "license": "BSD-3-Clause,NCSA,MIT", "license_type": "permissive", "path": "/HiSTBLinuxV100R005C00SPC041B020/source/boot/miniboot/drivers/flash/mmc/cmd_mmc.c", "provenance": "stackv2-0127.json.gz:71777", "repo_name": "xd5520026/hi3798mv100", "revision_date": "2021-08-26T01:13:28", "revision_id": "12aa0504880d518a9fa15800d4f7a305a1f94dc6", "snapshot_id": "d12ebd6cf8e086083740a8b381989256082f0839", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/xd5520026/hi3798mv100/12aa0504880d518a9fa15800d4f7a305a1f94dc6/HiSTBLinuxV100R005C00SPC041B020/source/boot/miniboot/drivers/flash/mmc/cmd_mmc.c", "visit_date": "2023-07-22T15:51:43.969863" }
stackv2
/****************************************************************************** * Copyright (C) 2014 Hisilicon STB Development Dept * All rights reserved. * *** * Create by Lai Yingjun * * 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 <errno.h> #include <stdio.h> #include <stddef.h> #include <malloc.h> #include <cmd-words.h> #include <memory.h> #include <mmc_if.h> #include "mmc_drv.h" extern struct flash_info_t *get_mmcdev_info(void); extern struct mmc_dev_t *get_mmcdev(int devnum); static int do_mmc_read(struct cmd_t *cmd) { int index = param_first(cmd); uint32 devnum = param_int32(cmd, index++); uint32 addr = param_int32(cmd, index++); uint64 offset = param_int64(cmd, index++); uint32 size = param_int32(cmd, index++); uint32 cnt = size; uint64 ret = 0; uint32 blk = offset; uint32 blocksize = get_mmcdev_info()->blocksize; struct mmc_dev_t *mmc_dev = get_mmcdev(devnum); if (!mmc_dev) { printf("No mmc device %d\n", devnum); return 1; } printf("\nMMC read: dev # %d, block # %d, count %d ... ", devnum, blk, cnt); ret = mmcdev_read(blk * blocksize, (void *)addr, cnt * blocksize); printf("%llu blocks read: %s\n", ret / blocksize, (ret / blocksize == cnt) ? "OK" : "ERROR"); return (ret / blocksize == cnt) ? 0 : 1; } CMD({&cw_mmc, NULL}, {&cw_read, NULL}, {&cw_devnum, NULL}, {&cw_addr, _T("memory address to save the data"), NULL}, {&cw_offset, _T("mmc offset"), NULL}, {&cw_size, _T("mmc read data length"), do_mmc_read}); static int do_mmc_write(struct cmd_t *cmd) { int index = param_first(cmd); uint32 devnum = param_int32(cmd, index++); uint32 addr = param_int32(cmd, index++); uint64 offset = param_int64(cmd, index++); uint32 size = param_int32(cmd, index++); uint32 cnt = size; uint64 ret = 0; uint32 blk = offset; struct mmc_dev_t *mmc_dev = get_mmcdev(devnum); uint32 blocksize = get_mmcdev_info()->blocksize; if (!mmc_dev) { printf("No mmc device %d\n", devnum); return 1; } printf("\nMMC write: dev # %d, block # %d, count %d ... ", devnum, blk, cnt); ret = mmcdev_write(blk * blocksize, (void *)addr, cnt * blocksize); printf("%llu blocks written: %s\n", ret / blocksize, (ret / blocksize == cnt) ? "OK" : "ERROR"); return (ret / blocksize == cnt) ? 0 : 1; } CMD({&cw_mmc, NULL}, {&cw_write, NULL}, {&cw_devnum, NULL}, {&cw_addr, _T("memory address that the data got from"), NULL}, {&cw_offset, _T("device offset"), NULL}, {&cw_size, _T("data length"), do_mmc_write});
2.46875
2