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-18T20:15:12.449872+00:00
2011-04-25T10:26:44
4f83b24a56e13c760ec4674c28d89c0a23d115e8
{ "blob_id": "4f83b24a56e13c760ec4674c28d89c0a23d115e8", "branch_name": "refs/heads/master", "committer_date": "2011-04-25T10:26:44", "content_id": "3c27535634e91ae7650fe1c691899b268068b089", "detected_licenses": [ "MIT" ], "directory_id": "675bb42d880e48e7a7a6a438ad655e1e789c0a21", "extension": "c", "filename": "parse.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": 1843, "license": "MIT", "license_type": "permissive", "path": "/nom1/parse.c", "provenance": "stackv2-0033.json.gz:158490", "repo_name": "nekopanic/atomic_burrito", "revision_date": "2011-04-25T10:26:44", "revision_id": "39286c30eb1e7930782d5936ecc8a8fb4baf07cc", "snapshot_id": "3863997025163a17fdfbe55a0a242deccb8082c2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nekopanic/atomic_burrito/39286c30eb1e7930782d5936ecc8a8fb4baf07cc/nom1/parse.c", "visit_date": "2021-05-26T17:22:33.517432" }
stackv2
#include "nom1.h" #define DELIMITER "\t" int parse_event(char *line_buffer, struct event *event) { event->id = strtok(line_buffer, DELIMITER); if (!event->session) { fprintf(stderr, "No id provided in line %ld\n", stats.lines); return 1; } event->session = strtok(NULL, DELIMITER); if (!event->session) { fprintf(stderr, "No session provided in line %ld\n", stats.lines); return 1; } event->user_id = strtok(NULL, DELIMITER); if (!event->user_id) { fprintf(stderr, "No user_id provided in line %ld\n", stats.lines); return 1; } event->occurred_at = strtok(NULL, DELIMITER); if (!event->occurred_at) { fprintf(stderr, "No occurred_at provided in line %ld\n", stats.lines); return 1; } event->event_type = strtok(NULL, DELIMITER); if (!event->event_type) { fprintf(stderr, "No event_type provided in line %ld\n", stats.lines); return 1; } // Continue parsing based on eventType if (strcmp("appearance", event->event_type) == 0 || strcmp("click", event->event_type) == 0) { // Both these types have a URL and ranking event->url = strtok(NULL, DELIMITER); if (!event->url) { fprintf(stderr, "No url provided in line %ld\n", stats.lines); return 1; } event->ranking = strtok(NULL, DELIMITER); if (!event->ranking) { fprintf(stderr, "No ranking provided in line %ld\n", stats.lines); return 1; } } else if (strcmp("search", event->event_type) == 0) { // Search contains a set of search terms. event->query = strtok(NULL, DELIMITER); if (!event->query) { fprintf(stderr, "No query provided in line %ld\n", stats.lines); return 1; } } else { fprintf(stderr, "Invalid event_type provided in line %ld: '%s'\n", stats.lines, event->event_type); return 1; } return 0; }
2.28125
2
2024-11-18T20:15:12.827293+00:00
2018-01-03T08:07:03
a3eeb89e233800fbdb660d11fa759268c04a2b00
{ "blob_id": "a3eeb89e233800fbdb660d11fa759268c04a2b00", "branch_name": "refs/heads/master", "committer_date": "2018-01-03T08:07:03", "content_id": "3831211c267275f89fbbf77a7f3f2d0d3b0a2ed1", "detected_licenses": [ "MIT" ], "directory_id": "0e30b8ade5ad9a60e44a59e23ba312bee4cd23ae", "extension": "h", "filename": "SPFIARGame.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 115198309, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5737, "license": "MIT", "license_type": "permissive", "path": "/SPFIARGame.h", "provenance": "stackv2-0033.json.gz:158878", "repo_name": "LeonAgmonNacht/FourInARowUniveristyProject", "revision_date": "2018-01-03T08:07:03", "revision_id": "5918a3f2e718877824f9fd82844c63da823dc86c", "snapshot_id": "a8500a6dda83f0027329f6672526e52eb73328a9", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/LeonAgmonNacht/FourInARowUniveristyProject/5918a3f2e718877824f9fd82844c63da823dc86c/SPFIARGame.h", "visit_date": "2021-09-02T14:39:08.869924" }
stackv2
#ifndef SPFIARGAME_H_ #define SPFIARGAME_H_ #include <stdbool.h> #include "SPArrayList.h" /** * SPFIARGame Summary: * * A container that represents a classic connect-4 game, a two players 6 by 7 * board game (rows X columns). The container supports the following functions. * * spFiarGameCreate - Creates a new game board * spFiarGameCopy - Copies a game board * spFiarGameDestroy - Frees all memory resources associated with a game * spFiarGameSetMove - Sets a move on a game board * spFiarGameIsValidMove - Checks if a move is valid * spFiarGameUndoPrevMove - Undoes previous move made by the last player * spFiarGamePrintBoard - Prints the current board * spFiarGameGetCurrentPlayer - Returns the current player * */ //Definitions #define SP_FIAR_GAME_SPAN 4 #define SP_FIAR_GAME_N_ROWS 6 #define SP_FIAR_GAME_N_COLUMNS 7 #define SP_FIAR_GAME_PLAYER_1_SYMBOL 'X' #define SP_FIAR_GAME_PLAYER_2_SYMBOL 'O' #define SP_FIAR_GAME_TIE_SYMBOL '-' #define SP_FIAR_GAME_EMPTY_ENTRY ' ' /** * the direction of span */ typedef enum { DIAGONAL_UP,DIAGONAL_DOWN,VERTICAL,HORIZONTAL } SPAN_DIRECTION; typedef struct sp_fiar_game_t { char gameBoard[SP_FIAR_GAME_N_ROWS][SP_FIAR_GAME_N_COLUMNS]; int tops[SP_FIAR_GAME_N_COLUMNS]; char currentPlayer; int historySize; SPArrayList* historyList; } SPFiarGame; /** * this will represent a cell in our game */ typedef struct sp_fiar_board_cell_t{ int x; int y; } SPFiarBoardCell; /** * Type used for returning error codes from game functions */ typedef enum sp_fiar_game_message_t { SP_FIAR_GAME_INVALID_MOVE, SP_FIAR_GAME_INVALID_ARGUMENT, SP_FIAR_GAME_NO_HISTORY, SP_FIAR_GAME_SUCCESS, //You may add any message you like } SP_FIAR_GAME_MESSAGE; /** * Creates a new game with a specified history size. The history size is a * parameter which specifies the number of previous moves to store. If the number * of moves played so far exceeds this parameter, then first moves stored will * be discarded in order for new moves to be stored. * * @historySize - The total number of moves to undo, * a player can undo at most historySizeMoves turns. * @return * NULL if either a memory allocation failure occurs or historySize <= 0. * Otherwise, a new game instant is returned. */ SPFiarGame* spFiarGameCreate(int historySize); /** * Creates a copy of a given game. * The new copy has the same status as the src game. * * @param src - the source game which will be copied * @return * NULL if either src is NULL or a memory allocation failure occurred. * Otherwise, an new copy of the source game is returned. * */ SPFiarGame* spFiarGameCopy(SPFiarGame* src); /** * Frees all memory allocation associated with a given game. If src==NULL * the function does nothing. * * @param src - the source game */ void spFiarGameDestroy(SPFiarGame* src); /** * Sets the next move in a given game by specifying column index. The * columns are 0-based and in the range [0,SP_FIAR_GAME_N_COLUMNS -1]. * * @param src - The target game * @param col - The target column, the columns are 0-based * @return * SP_FIAR_GAME_INVALID_ARGUMENT - if src is NULL or col is out-of-range * SP_FIAR_GAME_INVALID_MOVE - if the given column is full. * SP_FIAR_GAME_SUCCESS - otherwise */ SP_FIAR_GAME_MESSAGE spFiarGameSetMove(SPFiarGame* src, int col); /** * Checks if a disk can be put in the specified column. * * @param src - The source game * @param col - The specified column * @return * true - if the a disc can be put in the target column * false - otherwise. */ bool spFiarGameIsValidMove(SPFiarGame* src, int col); /** * Removes a disc that was put in the previous move and changes the current * player's turn. If the user invoked this command more than historySize times * in a row then an error occurs. * * @param src - The source game * @return * SP_FIAR_GAME_INVALID_ARGUMENT - if src == NULL * SP_FIAR_GAME_NO_HISTORY - if the user invoked this function more then * historySize in a row. * SP_FIAR_GAME_SUCCESS - on success. The last disc that was put on the * board is removed and the current player is changed */ SP_FIAR_GAME_MESSAGE spFiarGameUndoPrevMove(SPFiarGame* src); /** * On success, the function prints the board game. If an error occurs, then the * function does nothing. The characters 'X' and 'O' are used to represent * the discs of player 1 and player 2, respectively. * * @param src - the target game * @return * SP_FIAR_GAME_INVALID_ARGUMENT - if src==NULL * SP_FIAR_GAME_SUCCESS - otherwise * */ SP_FIAR_GAME_MESSAGE spFiarGamePrintBoard(SPFiarGame* src); /** * Returns the current player of the specified game. * @param src - the source game * @return * SP_FIAR_GAME_PLAYER_1_SYMBOL - if it's player one's turn * SP_FIAR_GAME_PLAYER_2_SYMBOL - if it's player two's turn * SP_FIAR_GAME_EMPTY_ENTRY - otherwise */ char spFiarGameGetCurrentPlayer(SPFiarGame* src); /** * Checks if there's a winner in the specified game status. The function returns either * SP_FIAR_GAME_PLAYER_1_SYMBOL or SP_FIAR_GAME_PLAYER_2_SYMBOL in case there's a winner, where * the value returned is the symbol of the winner. If the game is over and there's a tie * then the value SP_FIAR_GAME_TIE_SYMBOL is returned. in any other case the null characters * is returned. * @param src - the source game * @return * SP_FIAR_GAME_PLAYER_1_SYMBOL - if player 1 won * SP_FIAR_GAME_PLAYER_2_SYMBOL - if player 2 won * SP_FIAR_GAME_TIE_SYMBOL - If the game is over and there's a tie * null character - otherwise */ char spFiarCheckWinner(SPFiarGame* src); #endif
2.84375
3
2024-11-18T20:15:13.209301+00:00
2020-04-15T18:26:46
ed9a5f64642fec18297e12213058379ebf6d1e8a
{ "blob_id": "ed9a5f64642fec18297e12213058379ebf6d1e8a", "branch_name": "refs/heads/master", "committer_date": "2020-04-15T18:26:46", "content_id": "01f3533aac6699006cf5674b206d8a6adca11846", "detected_licenses": [ "MIT" ], "directory_id": "bedb7a61285ee3c222576bf9f8de17be44a40b57", "extension": "c", "filename": "example.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": 612, "license": "MIT", "license_type": "permissive", "path": "/C_Code/C_integrate/example.c", "provenance": "stackv2-0033.json.gz:159134", "repo_name": "jtiosue/QuadratureCandJulia", "revision_date": "2020-04-15T18:26:46", "revision_id": "198f7db626641ba551de0316c529c9b367068eb5", "snapshot_id": "a7cb4ee87ea50e6f6c67efeb55ceef632510d4bd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jtiosue/QuadratureCandJulia/198f7db626641ba551de0316c529c9b367068eb5/C_Code/C_integrate/example.c", "visit_date": "2022-04-14T11:49:23.698317" }
stackv2
#include <stdio.h> #include "integrate.h" double f(double x) { return x + 2 * x * x - 3 * x * x * x; } double df(double x) { // derivative of f return 1 + 4 * x - 9 * x * x; } int main() { double xa = -5; double xb = 10; int nfev = 100; printf("True integral: %.10f\n", f(xb) - f(xa)); printf("Approximate with %d function evaluations\n", nfev); printf("\tRectangle rule: %.10f\n", Rectangular(df, xa, xb, nfev)); printf("\tTrapezoid rule: %.10f\n", Trapezoidal(df, xa, xb, nfev)); printf("\tSimpsons rule: %.10f\n\n", Simpson(df, xa, xb, nfev)); return 0; }
2.890625
3
2024-11-18T20:15:16.647587+00:00
2020-10-24T18:54:53
0c931d6c361c9eb8d2cd587855bbd570d1a5ab39
{ "blob_id": "0c931d6c361c9eb8d2cd587855bbd570d1a5ab39", "branch_name": "refs/heads/master", "committer_date": "2020-10-24T18:54:53", "content_id": "0a2b7e29a6f7014c79d1d5f4ff73f88b6cbf7ac1", "detected_licenses": [ "ISC" ], "directory_id": "9759fdf23e96d2aaa3d65378adb39fd7dc974224", "extension": "h", "filename": "hmap.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 159861255, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2046, "license": "ISC", "license_type": "permissive", "path": "/lib/libbodhi/hmap.h", "provenance": "stackv2-0033.json.gz:159519", "repo_name": "markzz/libbodhi", "revision_date": "2020-10-24T18:54:53", "revision_id": "f2921cd3a6f17476d3927661168be8951e0dbf18", "snapshot_id": "634cb832ecb2cfbfbc7f9694f0ee65b69692fc3b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/markzz/libbodhi/f2921cd3a6f17476d3927661168be8951e0dbf18/lib/libbodhi/hmap.h", "visit_date": "2021-06-28T06:08:39.275505" }
stackv2
/* * hmap.h * * Copyright (c) 2018, Mark Weiman <mark.weiman@markzz.com> * * Permission to use, copy, modify, and/or 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. */ #ifndef BODHI_HMAP_H #define BODHI_HMAP_H #include <stdlib.h> #include <libbodhi/list.h> typedef struct _bodhi_hmap_t bodhi_hmap_t; typedef size_t (*bodhi_hash_fn)(void *); typedef int (*bodhi_hmap_cmp_fn)(const void *, const void *); typedef void (*bodhi_hmap_free_fn)(void *); typedef struct _bodhi_hmap_keyval_t { void *key; void *val; } bodhi_hmap_keyval_t; bodhi_hmap_t *bodhi_hmap_new_size(bodhi_hash_fn hash_fn, bodhi_hmap_cmp_fn cmp_fn, bodhi_hmap_free_fn key_free_fn, bodhi_hmap_free_fn val_free_fn, size_t size); bodhi_hmap_t *bodhi_hmap_new(bodhi_hash_fn hash_fn, bodhi_hmap_cmp_fn cmp_fn, bodhi_hmap_free_fn key_free_fn, bodhi_hmap_free_fn val_free_fn); void bodhi_hmap_free(bodhi_hmap_t *hmap); int bodhi_hmap_insert_no_cpy(bodhi_hmap_t *hmap, void *key, void *val); int bodhi_hmap_insert(bodhi_hmap_t *hmap, void *key, size_t key_size, void *val, size_t val_size); int bodhi_hmap_delete(bodhi_hmap_t *hmap, void *key); int bodhi_hmap_key_exists(bodhi_hmap_t *hmap, void *key); void *bodhi_hmap_value(bodhi_hmap_t *hmap, void *key); size_t bodhi_hmap_size(bodhi_hmap_t *hmap); bodhi_list_t *bodhi_hmap_get_keys(bodhi_hmap_t *hmap); bodhi_list_t *bodhi_hmap_get_keyvals(bodhi_hmap_t *hmap); #endif
2.03125
2
2024-11-18T20:15:16.760113+00:00
2023-08-02T07:26:01
35c9a89a012a810232cee475660264163cae70dd
{ "blob_id": "35c9a89a012a810232cee475660264163cae70dd", "branch_name": "refs/heads/master", "committer_date": "2023-08-02T07:26:01", "content_id": "b271277e0d27f9cb00401e9e92394affe9339675", "detected_licenses": [ "MIT" ], "directory_id": "ea401c3e792a50364fe11f7cea0f35f99e8f4bde", "extension": "c", "filename": "runVAA3D_APP2.c", "fork_events_count": 86, "gha_created_at": "2016-01-27T18:19:17", "gha_event_created_at": "2023-05-22T23:43:48", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 50527925, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 963, "license": "MIT", "license_type": "permissive", "path": "/bigneuron_ported/bench_testing/ornl/script_non_MPI/runVAA3D_APP2.c", "provenance": "stackv2-0033.json.gz:159647", "repo_name": "Vaa3D/vaa3d_tools", "revision_date": "2023-08-02T07:26:01", "revision_id": "e6974d5223ae70474efaa85e1253f5df1814fae8", "snapshot_id": "edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9", "src_encoding": "UTF-8", "star_events_count": 107, "url": "https://raw.githubusercontent.com/Vaa3D/vaa3d_tools/e6974d5223ae70474efaa85e1253f5df1814fae8/bigneuron_ported/bench_testing/ornl/script_non_MPI/runVAA3D_APP2.c", "visit_date": "2023-08-03T06:12:01.013752" }
stackv2
#include <stdio.h> #include <unistd.h> #include "mpi.h" int main(int argc, char **argv) { int *buf, i, rank, nints; char hostname[256]; char command_string[1024]; char txt_string[256]; MPI_Init(&argc,&argv); int my_id, num_procs; MPI_Comm_rank(MPI_COMM_WORLD, &my_id); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); sprintf(txt_string, "/lustre/atlas/proj-shared/nro101/BigNeuron/APP2_jobs/%d.txt",my_id); FILE* file = fopen(txt_string, "r"); size_t len = 0; int read; char * line = NULL;// (char *) malloc (1024); int index = 0; MPI_Barrier(MPI_COMM_WORLD); while ((read = getline(&line, &len, file)) != -1) { sprintf(command_string, "cd /lustre/atlas/proj-shared/nro101/BigNeuron/Vaa3D_BigNeuron_version1/;export DISPLAY=:%d;Xvfb :%d -auth /dev/null & %s\n",10+my_id,10+my_id,line); // printf(command_string); system(command_string); } fclose(file); MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); printf("All Done\n"); return 0; }
2.140625
2
2024-11-18T20:15:16.943677+00:00
2017-07-21T03:43:56
d810d9626e8fa0516e66487cda4b2a6b4510da1a
{ "blob_id": "d810d9626e8fa0516e66487cda4b2a6b4510da1a", "branch_name": "refs/heads/master", "committer_date": "2017-07-21T03:43:56", "content_id": "c4a96979b0ce5d39f220e893cee6dd88dcb4fa15", "detected_licenses": [ "MIT" ], "directory_id": "5139122ab3fa426848319e8104434614bdc6ee98", "extension": "h", "filename": "xbt.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": 6411, "license": "MIT", "license_type": "permissive", "path": "/nobio/code/xbt.h", "provenance": "stackv2-0033.json.gz:159903", "repo_name": "ashiklom/Kai_temp_UVic2.9", "revision_date": "2017-07-21T03:43:56", "revision_id": "5d6515a1fdc0d854f29d2f7d8dc5ab7f22ca43c6", "snapshot_id": "2b4e50f76892cb61e6af9fb0c79db2044a5bf416", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ashiklom/Kai_temp_UVic2.9/5d6515a1fdc0d854f29d2f7d8dc5ab7f22ca43c6/nobio/code/xbt.h", "visit_date": "2020-06-01T11:33:08.532265" }
stackv2
! source file: /usr/local/models/UVic_ESCM/2.9/source/mom/xbt.h !====================== include file "xbt.h" =========================== ! Each XBT station is located at latitude "xbtlat" and longitude ! "xbtlon". Data is collected at each grid point from the first ! level down through the nearest model level corresponding to a ! depth of "xbtdpt" cm. Actually, all coordinates are converted to ! the nearest model temperature grid point. ! All basic quantities as well as all terms in the momentum, ! temperature, and salinity equations are averaged over the time ! period specified by "xbtint". ! The maximum number of XBTs may be increased by changing parameter ! "maxxbt" below. ! inputs: ! maxxbt = maximum number of XBTs allowed. ! kmxbt = maximum number of levels from surface downward (<=km) ! set kmxbt < km to save space ! xbtlat = real latitude of XBTs in degrees ! xbtlon = real longitude of XBTs in degrees ! xbtdpt = real depths of XBTs in cm ! items = number of items in the XBT ! xname = character*12 names of XBT quantities ! outputs: ! numxbt = actual number of XBTs used ! nxbtts = current number of time steps in accumulated XTB data ! ixbt = longitude index of nearest model temperature grid point ! corresponding to "xbtlon" ! jxbt = latitude index of nearest model temperature grid point ! corresponding to "xbtlat" ! kxbt = depth index of nearest model temperature grid point ! corresponding to "xbtdpt" ! nsxbt = starting number for the XBTs on each latitude ! nexbt = ending number for the XBTs on each latitude ! txbt = accumulator array for time rate of change of ! tracers. the total time rate of change ! is broken down into components as follows: ! the form is d( )/dt = terms (2) ... (10) where each ! term has the units of "tracer units/sec" using ! schematic terms for illustration. ! (1) = total time rate of change for the tracer ! (2) = change due to zonal nonlinear term (UT)x ! (3) = change due to meridional nonlinear term (VT)y ! (4) = change due to vertical nonlinear term (WT)z ! (5) = change due to zonal diffusion: Ah*Txx ! (6) = change due to meridional diffusion: Ah*Tyy ! (7) = change due to vertical diffusion: kappa_h*Tzz ! (8) = change due to source term ! (9) = change due to explicit convection ! (10) = change due to filtering ! the nonlinear terms can be broken into two parts: advection and a ! continuity part: The physically meaningful part is advection. ! eg: Zonal advection of tracer "A" is -U(A)x = A(Ux) - (UA)x ! (11) = zonal advection U(Ax) ! (12) = meridional advection V(Ay) ! (13) = vertical advection W(Az) ! (14) = change of tracer variance ! (15) = average tracer within volume (tracer units) ! uxbt = accumulator array for time rate of change of ! momentum. the total time rate of change ! is broken down into components as follows: ! the form is d( )/dt = terms (2) ... (13) where each ! term has the units of "cm/sec**2" and "Q" is the ! momentum component {zonal or meridional} using ! schematic terms for illustration. ! (1) = total time rate of change for the momentum ! (2) = change due to the pressure gradient: grad_p ! without the surface pressure gradients ! (i.e., for computing the internal modes) ! (3) = change due to zonal nonlinear term: (UQ)x ! (4) = change due to meridional nonlinear term: (VQ)y ! (5) = change due to vertical nonlinear term: (wQ)z ! (6) = change due to zonal viscosity: Am*Qxx ! (7) = change due to meridional viscosity: Am*Qyy ! (8) = change due to vertical viscosity: kappa_m*Qzz ! (9) = change due to metric terms ! (10) = change due to coriolis terms: fQ ! (11) = change due to source terms ! (12) = change due to surface pressure gradient ! this is obtained after solving the external mode ! in the stream function technique. It is solved ! directly from the elliptic equation for the ! prognostic surface pressure technique ! (13) = change due to metric advection ! the nonlinear terms can be broken into two parts: advection and a ! continuity part: The physically meaningful part is advection. ! eg: Zonal advection of vel component "Q" is -U(Q)x = Q(U)x - (UQ)x ! (14) = zonal advection U(Qx) ! (15) = meridional advection V(Qy) ! (16) = vertical advection W(Qz) ! (17) = average velocity component ! xbtw = accumulator array for vertical velocity. (cm/sec) ! this is the average of adv_vbu at top and bottom of cell ! txbtsf = accumulator array for tracer surface flux terms. ! tracer (#1,#2) units = (cal/cm**2/sec, gm/cm**2/sec) ! uxbtsf = accumulator array for wind stress terms. (dynes/cm**2) ! ntxbt = number of terms for tracers ! nuxbt = number of terms for velocity integer maxxbt, kmxbt, ntxbt, nuxbt parameter (maxxbt=3, kmxbt=4) parameter (ntxbt=15, nuxbt=17) integer nxbtts, numxbt, nsxbt, nexbt, ixbt, jxbt, kxbt common /cxbt_i/ nxbtts, numxbt, nsxbt(jmt), nexbt(jmt) common /cxbt_i/ ixbt(maxxbt), jxbt(maxxbt), kxbt(maxxbt) character(12) :: xnamet, xnameu, xnamex common /cxbt_c/ xnamet(ntxbt), xnameu(nuxbt,2), xnamex(4) real xbtlat, xbtlon, xbtdpt, txbt, txbtsf, uxbt, uxbtsf, xbtw common /cxbt_r/ xbtlat(maxxbt), xbtlon(maxxbt), xbtdpt(maxxbt) common /cxbt_r/ txbt(kmxbt,ntxbt,nt,maxxbt), txbtsf(nt,maxxbt) common /cxbt_r/ uxbt(kmxbt,nuxbt,2,maxxbt), uxbtsf(2,maxxbt) common /cxbt_r/ xbtw(kmxbt,maxxbt)
2.09375
2
2024-11-18T20:15:17.178210+00:00
2016-06-11T16:55:29
594238fcb5ada7eeb5bddf4d0cbc5171fb2c63c6
{ "blob_id": "594238fcb5ada7eeb5bddf4d0cbc5171fb2c63c6", "branch_name": "refs/heads/master", "committer_date": "2016-06-11T16:55:29", "content_id": "b9815f8bf13582672e7c54644690b00826573786", "detected_licenses": [ "MIT" ], "directory_id": "966cb4190b5e5725491b5207a945e3bdfe99b8f2", "extension": "c", "filename": "__construct.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 60603424, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 837, "license": "MIT", "license_type": "permissive", "path": "/lib/srcs/class/car/__construct.c", "provenance": "stackv2-0033.json.gz:160160", "repo_name": "eliastre100/n4s-api", "revision_date": "2016-06-11T16:55:29", "revision_id": "53d7a040f06f4c9a133ca73d32a49f9e66d35734", "snapshot_id": "ee7f834e87e6936ac5016c644239834867483432", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/eliastre100/n4s-api/53d7a040f06f4c9a133ca73d32a49f9e66d35734/lib/srcs/class/car/__construct.c", "visit_date": "2020-12-23T22:14:56.723900" }
stackv2
#include <malloc.h> #include <types.h> #include <unistd.h> #include "class/car.h" #include "class/command.h" static void net_car_methods(car_t *self) { self->listen = car_listen; self->destruct = net_car_destruct; } car_t *new_net_car(int sock) { car_t *self; if ((self = malloc(sizeof(car_t))) == NULL) return (NULL); net_car_methods(self); if ((self->command = new_net_command()) == NULL) { self->destruct(self); return (NULL); } if (read(sock, self->name, NAME_LENGTH) == -1) { fprintf(stderr, "New car: Unable to get name from remote\n"); self->destruct(self); return (NULL); } self->wheels = 0; self->speed = 0; self->io.in = -1; self->io.out = sock; self->io.same = true; self->pos.x = 0; self->pos.y = 0; self->enable = true; self->running = false; return (self); }
2.421875
2
2024-11-18T20:15:18.125898+00:00
2017-08-17T04:07:42
b9724a3f5f8ecb71e23914ab499a3ff5029125e2
{ "blob_id": "b9724a3f5f8ecb71e23914ab499a3ff5029125e2", "branch_name": "refs/heads/master", "committer_date": "2017-08-17T04:07:42", "content_id": "c3ed55e2c7195d4ce46ddf0eec0f2be5d52248ec", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "b3d10845f20c7756b7c4ffc8cc946c3882f1297f", "extension": "c", "filename": "socket.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 37297718, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11775, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/socket/socket.c", "provenance": "stackv2-0033.json.gz:161059", "repo_name": "Justasic/psychic-ninja", "revision_date": "2017-08-17T04:07:42", "revision_id": "87bff62b5e2e49960822fce5aac7e22194a746eb", "snapshot_id": "9f8e434a732e6dde396f2b5a8e6a76be46355284", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Justasic/psychic-ninja/87bff62b5e2e49960822fce5aac7e22194a746eb/src/socket/socket.c", "visit_date": "2020-05-17T07:45:04.755441" }
stackv2
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/socket.h> #include <sys/types.h> #include <netdb.h> #include <assert.h> #include <errno.h> #include <arpa/inet.h> #include "vector/vec.h" // Include our socket types and function declarations. #include "socket/socket.h" // A global vector to store our socket structures. vec_t(socket_t*) sockets; static const char *GetIPAddress(struct addrinfo *adr) { // Buffer big enough to read a human-readable IPv6 address (more than enough room for IPv4) static char txt[INET6_ADDRSTRLEN]; // Clear the buffer to make sure it is completely empty from any previous IP address resolutions. memset(txt, 0, sizeof(txt)); // call inet_ntop to convert the binary form of the address to the human-readable form. if (!inet_ntop(adr->ai_family, adr->ai_addr, txt, sizeof(txt))) { // We had an issue, tell the user about it for debug-reasons. fprintf(stderr, "Failed to convert ip address from binary to text: %s (%d)\n", strerror(errno), errno); return NULL; } // We now have our text address return txt; } /******************************************************************* * Function: InitializeSockets * * * * Arguments: (None) * * * * Returns: (int) a true or false value where true = 1, false = 0 * * * * Description: This initializes any internal data structures * * used to manage and organize the sockets and their structures. * * * *******************************************************************/ int InitializeSockets(void) { // Initialize our global sockets variable so we can start // adding data (eg, socket_t structures) to it. vec_init(&sockets); // Return that we succeeded the above operation. return 1; } /******************************************************************* * Function: DestroySockets * * * * Arguments: (None) * * * * Returns: (int) a true or false value where true = 1, false = 0 * * * * Description: This closes any sockets and deallocates their data * * structures and any associated metadata as well as deallocates * * any other data structures associated with the management of the * * sockets themselves (eg, our global `sockets' variable. * * * *******************************************************************/ int DestroySockets(void) { // Iterate over all our sockets and make sure they're closed // so we don't leak file descriptors or memory. socket_t *socket; // Socket variable used for iteration of our type int i; // 'i' for 'iterator' used to determine how many items we've iterated. vec_foreach(&sockets, socket, i) { DestroySocket(socket); } // Deallocate our global vector vec_deinit(&sockets); return 1; } /******************************************************************* * Function: CreateSocket * * * * Arguments: sockaddr_t union * * * * Returns: (socket_t) A pointer to the socket_t structure with a * * newly created socket ready to start a connection or NULL if * * there was an error creating the socket. * * * * Description: Creates a socket with the operating system, ready * * for a connection to be established over it. No data can be sent * * over this socket quite yet and must be called by ConnectSocket * * before data may be sent or received. * * * *******************************************************************/ socket_t *CreateSocket(const char *host, const char *port) { // Allocate the socket structure. socket_t *sock = malloc(sizeof(socket_t)); // Tell it what kind of socket(s) we want. struct addrinfo hints; struct addrinfo *servinfo; servinfo = malloc(sizeof(struct addrinfo)); hints.ai_family = AF_INET; // IPv4 socket hints.ai_socktype = SOCK_STREAM; // Streaming socket. // Resolve the addresses int rv = 1; rv = getaddrinfo(host, port, &hints, &servinfo); // Check if there was an error and return a failure state. if (rv != 0) return NULL; // Include the address information struct into our socket struct. sock->adr = servinfo; sock->sa->sa = *servinfo->ai_addr; // call the UNIX socket() syscall to acquire a file descriptor. // here, we create a IPv4 socket (AF_INET), tell it that we want // a streaming socket with dynamic-length packets, and tell it // that we're using TCP/IP sock->fd = socket(sock->adr->ai_family, sock->adr->ai_socktype, sock->adr->ai_protocol); // Check if the socket failed to be created. if (sock->fd == -1) return NULL; // Add the socket to the vector. vec_push(&sockets, sock); return sock; } /******************************************************************* * Function: ConnectSocket * * * * Arguments: socket_t* * * * * Returns: (boolean) Attempts to connect to the resolved host for * * the addresses provided and returns a boolean on whether it was * * successful or not. * * * * Description: Creates a connection to a socket so data can be * * transmitted over a connection. Once this function is successfully * called then the read and write functions can be used. * * * *******************************************************************/ int ConnectSocket(socket_t *sock) { // Make sure someone didn't biff. assert(sock); // Check to make sure we connected to something. int ConnectionSuccessful = 0; // Since some hostnames can resolve to multiple addresses (eg, Round-Robin DNS) // this for-loop is required to iterate to one which works. for (struct addrinfo *adr = sock->adr; adr; adr = adr->ai_next) { // Here we check if connect failed, if it did, print an error and continue // otherwise we set the ConnectionSuccessful variable to indicate we can leave the loop. if (connect(sock->fd, adr->ai_addr, adr->ai_addrlen) == -1) { // Print to stderr instead of stdout for shell-routing reasons. fprintf(stderr, "Connection to %s:%hd was unsuccessful: %s (%d)\n", GetIPAddress(adr), sock->port, strerror(errno), errno); } else { // Our connection was a success, set the variable and break from the loop. ConnectionSuccessful = 1; break; } } // Did we find a successful address to connect to? if (!ConnectionSuccessful) { fprintf(stderr, "Failed to find an address to connect to successfully from host %s:%hd\n", sock->host, sock->port); return 0; } return 1; } /******************************************************************* * Function: DestroySocket * * * * Arguments: socket_t* * * * * Returns: (void) No return. * * * * Description: Destroys the socket structure safely and * * deallocates any resources used by the structure. * * * *******************************************************************/ void DestroySocket(socket_t *sock) { assert(sock); // Close the socket so we don't have an untracked file descriptors close(sock->fd); // Deallocate anything we allocated. if (sock->adr) freeaddrinfo(sock->adr); if (sock->host) free(sock->host); // Finally, deallocate the socket structure itself. free(sock); // Remove it out of the vector. vec_remove(&sockets, sock); } /******************************************************************* * Function: ReadSocket * * * * Arguments: socket_t*, void*, size_t * * * * Returns: (size_t) Returns the number of bytes read or -1 for an * * error status from errno. * * * * Description: Reads data from a socket and fills the buffer, * * once the buffer is filled, it returns the number of bytes read * * from the socket or it returns -1 upon an error condition. * * * *******************************************************************/ size_t ReadSocket(socket_t *sock, void *buffer, size_t bufferlen) { assert(buffer && sock); // Fill the buffer with bytes from the socket size_t bytes = read(sock->fd, buffer, bufferlen); // Check for errors if (bytes == -1UL) fprintf(stderr, "Failed to read bytes from socket %d: %s (%d)\n", sock->fd, strerror(errno), errno); // Return the number of bytes, if bytes == -1 then we had an error and should // handle accordingly in the functions which call this function. return bytes; } /******************************************************************* * Function: WriteSocket * * * * Arguments: socket_t*, const void*, size_t * * * * Returns: (size_t) Returns the number of bytes written to the * * socket or -1 for an error condition. * * * * Description: The inverse of the `ReadSocket` function in that * * it writes data to the socket. It returns -1 upon failure and * * returns the number of bytes written upon success. * * * *******************************************************************/ size_t WriteSocket(socket_t *sock, const void *buffer, size_t bufferlen) { assert(sock && buffer); // Write the buffer out the socket and return how many bytes we // wrote or any error codes if we had an error. size_t bytes = send(sock->fd, buffer, bufferlen, 0); // error check again if (bytes == -1UL) fprintf(stderr, "Failed to send bytes to socket %d: %s (%d)\n", sock->fd, strerror(errno), errno); return bytes; }
2.71875
3
2024-11-18T20:15:18.253966+00:00
2018-08-07T09:44:42
e023607817270cb22c5e547c41e2f20620946578
{ "blob_id": "e023607817270cb22c5e547c41e2f20620946578", "branch_name": "refs/heads/master", "committer_date": "2018-08-07T09:44:42", "content_id": "1c49ba7742ad91f28b5c2a1ba881e69388e7c03c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3aff2aae14dba9d2277d128934a86915ab4b06fc", "extension": "h", "filename": "ps_YUV422.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": 2064, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/D3DVideoRender/ps_YUV422.h", "provenance": "stackv2-0033.json.gz:161315", "repo_name": "classic130/direct3d-yv12", "revision_date": "2018-08-07T09:44:42", "revision_id": "99c2326995b0c65af9b3235d7ae4b5b43275127c", "snapshot_id": "37e311fde357330e8f9fb1c456d1a751cc5da7b7", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/classic130/direct3d-yv12/99c2326995b0c65af9b3235d7ae4b5b43275127c/src/D3DVideoRender/ps_YUV422.h", "visit_date": "2023-03-14T23:29:39.388614" }
stackv2
/* Author: dengzikun http://hi.csdn.net/dengzikun 注意:在保留作者信息和出处链接的前提下,您可以任意复制、修改、传播本文件。 */ texture Tex0 ; texture Tex1 ; sampler2D YUVTextue = sampler_state { Texture = <Tex0> ; MipFilter = POINT ; MinFilter = POINT ; MagFilter = POINT ; AddressU = CLAMP ; AddressV = CLAMP ; }; sampler2D ParityTextue = sampler_state { Texture = <Tex1> ; MipFilter = POINT ; MinFilter = POINT ; MagFilter = POINT ; AddressU = CLAMP ; AddressV = CLAMP ; }; struct PS_INPUT { float2 uvCoords0 : TEXCOORD0 ; float2 uvCoords1 : TEXCOORD1 ; }; static float4x4 matYUV2RGB = { 1.164383, 0.0, 1.596027, -0.874202, 1.164383, -0.391762, -0.812968, 0.531668, 1.164383, 2.017232, 0.0, -1.085631, 0.0, 0.0, 0.0, 1.0 } ; static float3 interpolation = { 9.0 / 16.0, -1.0 / 16.0, 1.0 / 510.0} ; float YUV_dx[9] ; float4 main( PS_INPUT input ) : COLOR0 { float4 yuvColor ; yuvColor.x = tex2D( YUVTextue, input.uvCoords0 + float2(YUV_dx[0], 0.0)).x ; float parity = tex2D( ParityTextue, input.uvCoords1 ).x ; if ( parity > 0.5 ) // odd { float3x2 c ; c._m00 = tex2D( YUVTextue, input.uvCoords0 + float2(YUV_dx[1], 0.0)).x + tex2D( YUVTextue, input.uvCoords0 + float2(YUV_dx[2], 0.0)).x ; c._m10 = tex2D( YUVTextue, input.uvCoords0 + float2(YUV_dx[3], 0.0)).x + tex2D( YUVTextue, input.uvCoords0 + float2(YUV_dx[4], 0.0)).x ; c._m20 = 1.0 ; c._m01 = tex2D( YUVTextue, input.uvCoords0 + float2(YUV_dx[5], 0.0)).x + tex2D( YUVTextue, input.uvCoords0 + float2(YUV_dx[6], 0.0)).x ; c._m11 = tex2D( YUVTextue, input.uvCoords0 + float2(YUV_dx[7], 0.0)).x + tex2D( YUVTextue, input.uvCoords0 + float2(YUV_dx[8], 0.0)).x ; c._m21 = 1.0 ; yuvColor.yz = mul ( interpolation, c ) ; } else { yuvColor.y = tex2D( YUVTextue, input.uvCoords0 + float2(YUV_dx[5], 0.0)).x ; yuvColor.z = tex2D( YUVTextue, input.uvCoords0 + float2(YUV_dx[2], 0.0)).x ; } yuvColor.w = 1.0 ; return mul( matYUV2RGB, yuvColor ) ; }
2.765625
3
2024-11-18T20:15:18.343344+00:00
2021-10-25T00:03:25
7d86f8757a105a7f1ad4b3df67e31054fbbb48e4
{ "blob_id": "7d86f8757a105a7f1ad4b3df67e31054fbbb48e4", "branch_name": "refs/heads/master", "committer_date": "2021-10-25T00:03:25", "content_id": "5d608464e92ea323ffb44ff3f5734227b1d403b1", "detected_licenses": [ "MIT" ], "directory_id": "df5d964b7915c4ce8fa626c9bc21bf694cb0e28a", "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": 2648, "license": "MIT", "license_type": "permissive", "path": "/34. IPC - Comunicacion entre Procesos - Signals/ejemplo4/main.c", "provenance": "stackv2-0033.json.gz:161443", "repo_name": "yisusprogramer31/c-samples", "revision_date": "2021-10-25T00:03:25", "revision_id": "04de0ccd28843959653a06f6e9bc6fadc0c6ec34", "snapshot_id": "697aec874f9fa9c7cf3840f1e444c6a28ab4909c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yisusprogramer31/c-samples/04de0ccd28843959653a06f6e9bc6fadc0c6ec34/34. IPC - Comunicacion entre Procesos - Signals/ejemplo4/main.c", "visit_date": "2023-08-16T06:31:32.521602" }
stackv2
/** * \file main.c * \brief 34. IPC - Comunicacion entre Procesos - Signals - Ejemplo 4 - Señales entre padre e hijo * \author Javier Balloffet * \date Oct 28, 2018 * \details Usar makefile para compilar, linkear y ejecutar */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <sys/wait.h> int loopFlag = 1; void signals_handler(int signalNumber); int main() { /* 1. Declaro un entero para almacenar el PID (Process ID) */ int pid, status; /* 2. Genero un nuevo proceso utilizando la función "fork" */ pid = fork(); /* 3. Separo la ejecución del padre y del hijo */ if (pid < 0) { perror("Error al generar el proceso hijo\n"); exit(1); } else if (pid == 0) { /* 4. Proceso hijo */ printf("Hijo: Hola! Mi PID es: %d\n", getpid()); /* 5. Define el handler para SIGUSR1 y se queda esperando una señal del padre (SIGUSR1) */ signal(SIGUSR1, signals_handler); printf("Hijo: Estoy esperando una señal de mi padre...\n"); while (loopFlag); /* 6. Llegó la señal! El hijo ahora envía una señal al padre (SIGUSR2) */ kill(getppid(), SIGUSR2); printf("Hijo: Señal enviada a mi padre!\n"); printf("Hijo: Chau!\n"); } else if (pid > 0) { /* 7. Proceso padre */ printf("Padre: Hola! Mi PID es: %d\n", getpid()); /* 8. Define el handler para SIGUSR2 */ signal(SIGUSR2, signals_handler); /* 9. Espera 3 segundos */ printf("Padre: Esperando 3 segundos...\n"); sleep(3); /* 10. Envía señal al hijo (SIGUSR1) */ kill(pid, SIGUSR1); printf("Padre: Señal enviada a mi hijo!\n"); /* 11. Hago que el padre espere a que su hijo muera antes de morir él */ printf("Padre: Esperando a que mi hijo muera...\n"); wait(&status); printf("Padre: Mi hijo termino con status: %d\n", status); printf("Padre: Chau!\n"); } return 0; } void signals_handler(int signalNumber) { /* 12. Separo según señal recibida */ if (signalNumber == SIGUSR1) { printf("Hijo: Recibi esta señal de mi padre: %d\n", signalNumber); } else if (signalNumber == SIGUSR2) { printf("Padre: Recibi esta señal de mi hijo: %d\n", signalNumber); } /* 13. Limpio flag para cortar ejecución del bucle */ loopFlag = 0; /* 14. Vuelvo a setear el handler para la señal recibida (sino se asigna automáticamente al handler default) */ signal(signalNumber, signals_handler); }
3.671875
4
2024-11-18T20:15:18.812464+00:00
2019-04-03T12:30:08
9afba5209d445fb5ddf49d217370de0fa3a5fb04
{ "blob_id": "9afba5209d445fb5ddf49d217370de0fa3a5fb04", "branch_name": "refs/heads/master", "committer_date": "2019-04-03T12:30:08", "content_id": "79f6e48a97ceceb4f42442168bc7b1eb07947371", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c89049d19572824a941f8e68d002c27d38c90115", "extension": "h", "filename": "instruction.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 179282518, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2861, "license": "Apache-2.0", "license_type": "permissive", "path": "/HAL/x86/instruction.h", "provenance": "stackv2-0033.json.gz:162084", "repo_name": "changkaiyan/CKOS", "revision_date": "2019-04-03T12:30:08", "revision_id": "410e9a80167c2e5920cd2e061a8472da790e0a6d", "snapshot_id": "f6440266c2d0a054c92d53d7e0a5a7d724cf28ee", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/changkaiyan/CKOS/410e9a80167c2e5920cd2e061a8472da790e0a6d/HAL/x86/instruction.h", "visit_date": "2020-05-04T16:36:29.885574" }
stackv2
//本文件是x86指令集中的指令在c语言中的接口 #pragma once #include"types.h" static inline CHAR X86 InByte( WORD port ) { CHAR data; asm volatile("in %1,%0" : "=a" (data) : "d" (port)); return data; } static inline VOID X86 InStringLong( int port, VOID *address, int count) { asm volatile("cld; rep insl" : "=D" (address), "=c" (count) : "d" (port), "0" (address), "1" (count) : "memory", "cc"); } static inline VOID X86 OutByte( WORD port, CHAR data ) { asm volatile("out %0,%1" : : "a" (data), "d" (port)); } static inline VOID X86 OutWord( WORD port, WORD data ) { asm volatile("out %0,%1" : : "a" (data), "d" (port)); } static inline VOID X86 OutStringLong( DWORD port, const VOID *address, DWORD count ) { asm volatile("cld; rep outsl" : "=S" (address), "=c" (count) : "d" (port), "0" (address), "1" (count) : "cc"); } static inline VOID X86 StringToStringByte( VOID *address, int data, int count ) { asm volatile("cld; rep stosb" : "=D" (address), "=c" (count) : "0" (address), "1" (count), "a" (data) : "memory", "cc"); } static inline VOID X86 StringToStringLong( VOID *address, int data, int count ) { asm volatile("cld; rep stosl" : "=D" (address), "=c" (count) : "0" (address), "1" (count), "a" (data) : "memory", "cc"); } struct SegmentDescriptor; static inline VOID X86 LoadGlobalDescriptorTable( struct SegmentDescriptor *p, DWORD size ) { volatile WORD pd[3]; pd[0] = size-1; pd[1] = (DWORD)p; pd[2] = (DWORD)p >> 16; asm volatile("lgdt (%0)" : : "r" (pd)); } struct gatedesc; static inline void lidt(struct gatedesc *p, int size) { volatile WORD pd[3]; pd[0] = size-1; pd[1] = (DWORD)p; pd[2] = (DWORD)p >> 16; asm volatile("lidt (%0)" : : "r" (pd)); } static inline void ltr(WORD sel) { asm volatile("ltr %0" : : "r" (sel)); } static inline DWORD readeflags(void) { DWORD eflags; asm volatile("pushfl; popl %0" : "=r" (eflags)); return eflags; } static inline void loadgs(WORD v) { asm volatile("movw %0, %%gs" : : "r" (v)); } static inline void cli(void) { asm volatile("cli"); } static inline void sti(void) { asm volatile("sti"); } static inline DWORD xchg(volatile DWORD *addr, DWORD newval) { DWORD result; asm volatile("lock; xchgl %0, %1" : "+m" (*addr), "=a" (result) : "1" (newval) : "cc"); return result; } static inline DWORD rcr2(void) { DWORD val; asm volatile("movl %%cr2,%0" : "=r" (val)); return val; } static inline void lcr3(DWORD val) { asm volatile("movl %0,%%cr3" : : "r" (val)); }
2.390625
2
2024-11-18T20:15:18.872697+00:00
2013-11-22T05:00:23
c6ef92d668ac71e6a0f283b384c4dfbbd327e359
{ "blob_id": "c6ef92d668ac71e6a0f283b384c4dfbbd327e359", "branch_name": "refs/heads/master", "committer_date": "2013-11-22T05:00:23", "content_id": "1a5b7d0df50b0033c9af53fade71c37ff1f30e6b", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "482581050bb98cce85d61cdccd4ba36498f4e7f9", "extension": "c", "filename": "sd.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": 9682, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/sd.c", "provenance": "stackv2-0033.json.gz:162213", "repo_name": "futr/sensor-board", "revision_date": "2013-11-22T05:00:23", "revision_id": "4f11332ffa3c3d847be31e0a3a1426df99fcbc9b", "snapshot_id": "c4a793520c0414db8a3ae6b62f00b99d97b35764", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/futr/sensor-board/4f11332ffa3c3d847be31e0a3a1426df99fcbc9b/sd.c", "visit_date": "2020-05-31T01:32:29.793394" }
stackv2
#include "sd.h" /* 内部状態保持用 */ static SDUnit unit; char sd_init( SPISpeed max_speed, uint16_t block_size, SPIPin pullup ) { /* カード初期化 */ int i; SDResp resp; uint32_t ret; uint8_t csd[16]; uint8_t data_token; uint32_t c_size; uint8_t read_block_len; uint8_t c_size_mult; /* 設定保存 */ unit.block_size = block_size; /* 初期化のためにSPIを停止させる */ spi_release(); /* 自分の都合がいいように設定する */ spi_init( SPIMaster, SPIMode0, SPIOscDiv128, SPIMSB, pullup, 0 ); /* CS=H,DI=Hで74クロック以上送る */ spi_release_slave(); for ( i = 0; i < 10; i++ ) { spi_write( 0xFF ); while ( !spi_complete() ); } /* アサート */ spi_select_slave(); /* CMD0送信 */ sd_command( 0, 0 ); /* レスポンスまち */ while ( ( resp = sd_response() ) == SDRespWorking ); /* アイドルステートでなければ失敗 */ if ( resp != SDRespIdleState ) { return 0; } /* CMD8送信 */ sd_command( 8, 0x1AA ); /* レスポンスまち */ while ( ( resp = sd_response() ) == SDRespWorking ); /* 何かしらリジェクトされれば失敗なのでV1として処理 */ if ( resp & SDRespIlligalCommand ) { /* V1 */ unit.version = SDV1; unit.address = SDByte; /* 初期化開始 */ while ( 1 ) { sd_command( 1, 0 ); while ( ( resp = sd_response() ) == SDRespWorking ); /* 終了してたら脱出 */ if ( ( resp & SDRespIdleState ) == 0 ) { break; } } } else if ( resp == SDRespIdleState ) { /* V2*/ unit.version = SDV2; /* 戻り値取得 */ ret = sd_get_returned(); if ( ( ret & 0xFFF ) != 0x1AA ) { /* 対応できないカードだった */ return 0; } /* 初期化開始 */ while ( 1 ) { /* ACMD41発行 */ sd_command( 55, 0 ); while ( ( resp = sd_response() ) == SDRespWorking ); sd_command( 41, 0x40000000UL ); while ( ( resp = sd_response() ) == SDRespWorking ); /* 終了してたら脱出 */ if ( ( resp & SDRespIdleState ) == 0 ) { break; } } } else { /* 何かしら失敗 */ return 0; } /* OCR確認 */ sd_command( 58, 0 ); while ( ( resp = sd_response() ) == SDRespWorking ); /* 戻り値確認 */ ret = sd_get_returned(); if ( ret & 0x40000000UL ) { /* ブロックアドレスだった */ unit.address = SDBlock; } else { unit.address = SDByte; } /* 速度を最高速度に再設定 */ spi_set_speed( max_speed ); /* ブロック長さ再設定 */ sd_command( 16, block_size ); while ( ( resp = sd_response() ) == SDRespWorking ); /* エラーなら失敗 */ if ( resp != SDRespSuccess ) { return 0; } /* カードサイズ取得 ( CSD取得 ) */ sd_command( 9, 0 ); while ( ( resp = sd_response() ) == SDRespWorking ); /* データトークンを待つ */ do { spi_write( 0xFF ); while ( !spi_complete() ); data_token = spi_read(); } while ( data_token == 0xFF ); /* エラートークンなら失敗 */ if ( ( data_token & 0x80 ) == 0 ) { spi_release_slave(); return 0; } /* 16バイト受信 */ for ( i = 0; i < 16; i++ ) { spi_write( 0xFF ); while ( !spi_complete() ); csd[i] = spi_read(); } /* CRC */ spi_write( 0xFF ); while ( !spi_complete() ); spi_write( 0xFF ); while ( !spi_complete() ); /* CSDバージョン判定 */ if ( csd[0] & 0x40 ) { /* バージョン2でカードサイズ作成 */ unit.card_size = ( 1 + csd[9] + (uint64_t)csd[8] * 256 + ( (uint64_t)csd[7] & 0x3F ) * 256 * 256 ) * 512 * 1024; } else { /* バージョン1でカードサイズ作成 */ c_size_mult = ( csd[9] >> 3 ) & 0x07; read_block_len = ( csd[5] & 0x0F ); c_size = ( ( (uint32_t)csd[6] & 0x03 ) << 10 ) | ( (uint32_t)csd[7] << 2 ) | ( csd[8] >> 6 ); unit.card_size = ( 1 << read_block_len ) * ( 1 << ( c_size_mult + 2 ) ) * ( c_size + 1 ); } // unit.card_size = ( 1 + csd[9] + (uint32_t)csd[8] * 256 + ( (uint32_t)csd[7] & 0x3F ) * 256 * 256 ); /* チップセレクト解除 */ spi_release_slave(); /* 初期化完了 */ return 1; } void sd_command( uint8_t cmd, uint32_t arg ) { /* SPIにコマンド送信 */ int i; uint8_t cmd_buf[6]; uint8_t *parg; /* 準備 */ unit.cmd = cmd; parg = (uint8_t *)&arg; /* コマンド作成 */ cmd_buf[0] = 0x40 | cmd; cmd_buf[1] = parg[3]; cmd_buf[2] = parg[2]; cmd_buf[3] = parg[1]; cmd_buf[4] = parg[0]; /* CRCが必要なら固定値を */ if ( cmd == 8 ) { cmd_buf[5] = 0x87; } else if ( cmd == 0 ) { cmd_buf[5] = 0x95; } else { cmd_buf[5] = 0x01; } /* 一個無駄に送る ( 秋月の8MBSDはこれがないと動かない ) */ spi_write( 0xFF ); while ( !spi_complete() ); spi_write( 0xFF ); while ( !spi_complete() ); /* SPIコマンド送信 */ for ( i = 0; i < 6; i++ ) { spi_write( cmd_buf[i] ); while ( !spi_complete() ); } } SDResp sd_response( void ) { /* レスポンスを待って結果を返す */ uint8_t recv; uint8_t *pret; SDResp resp; int i; pret = (uint8_t *)&unit.ret; /* NCR解除を100回まつ */ for ( i = 0; i < 100; i++ ) { spi_write( 0xFF ); while ( !spi_complete() ); recv = spi_read(); /* 解除されたか */ if ( recv != 0xFF ) { break; } } /* タイムアウトしていれば失敗 */ if ( i == 100 ) { return SDRespFailed; } /* 必要な場合は戻り値受信 */ if ( unit.cmd == 58 || unit.cmd == 8 ) { for ( i = 0; i < 4; i++ ) { spi_write( 0xFF ); while ( !spi_complete() ); pret[3-i] = spi_read(); } } /* レスポンスを作る */ if ( recv != 0 ) { resp = recv; } else { resp = SDRespSuccess; } return resp; } uint32_t sd_get_returned( void ) { /* コマンドのリターンデーターを取得 */ return unit.ret; } char sd_block_write( uint32_t address, uint8_t *data, size_t offset, size_t size ) { /* シングルブロックライト */ uint16_t i; /* 初期化 */ if ( !sd_start_step_block_write( address ) ) { return 0; } /* 読み込み */ for ( i = 0; i < unit.block_size; i++ ) { /* 指定範囲外のデーターは0が書き込まれる */ if ( i >= offset && ( i - offset ) < size ) { sd_step_block_write( data[i - offset] ); } else { sd_step_block_write( 0x00 ); } } /* 終了 */ if ( !sd_stop_step_block_write() ) { return 0; } return 1; } SDAddress sd_get_address_mode( void ) { /* アドレスモードを返す */ return unit.address; } char sd_block_read( uint32_t address, uint8_t *data, size_t offset, size_t size ) { /* シングルブロックリード */ uint16_t i; /* 初期化 */ if ( !sd_start_step_block_read( address ) ) { return 0; } /* 読み込み */ for ( i = 0; i < unit.block_size; i++ ) { if ( i >= offset && ( i - offset ) < size ) { data[i - offset] = sd_step_block_read(); } else { sd_step_block_read(); } } /* 終了 */ if ( !sd_stop_step_block_read() ) { return 0; } return 1; } SDVersion sd_get_version() { /* バージョンを返す */ return unit.version; } char sd_start_step_block_write( uint32_t address ) { /* ステップ動作でブロックライト開始 */ SDResp resp; /* アサート */ spi_select_slave(); /* CMD24 */ sd_command( 24, address ); /* レスポンスまち */ while ( ( resp = sd_response() ) == SDRespWorking ); /* 変なレスポンスなら失敗 */ if ( resp != SDRespSuccess ) { spi_release_slave(); return 0; } /* 1バイト開ける */ spi_write( 0xFF ); while ( !spi_complete() ); /* データトークン */ spi_write( 0xFE ); while ( !spi_complete() ); return 1; } void sd_step_block_write( uint8_t data ) { /* 1バイトだけ書き込み */ spi_write( data ); while ( !spi_complete() ); } char sd_stop_step_block_write() { /* ステップ動作ブロックライト完了 */ uint8_t data_resp; uint8_t busy; /* CRC */ spi_write( 0x00 ); while ( !spi_complete() ); spi_write( 0x00 ); while ( !spi_complete() ); /* データレスポンス */ spi_write( 0xFF ); while ( !spi_complete() ); data_resp = spi_read(); /* ビジー解除まち */ do { spi_write( 0xFF ); while ( !spi_complete() ); busy = spi_read(); } while ( busy == 0x00 ); /* 成功か */ if ( ( data_resp & 0x05 ) == 0x05 ) { spi_release_slave(); return 1; } else { spi_release_slave(); return 0; } } char sd_start_step_block_read( uint32_t address ) { /* ステップ動作のシングルブロックリード */ SDResp resp; uint8_t data_token; /* アサート */ spi_select_slave(); /* CMD17 */ sd_command( 17, address ); /* レスポンスまち */ while ( ( resp = sd_response() ) == SDRespWorking ); /* 変なレスポンスなら失敗 */ if ( resp != SDRespSuccess ) { spi_release_slave(); return 0; } /* データトークンを待つ */ do { spi_write( 0xFF ); while ( !spi_complete() ); data_token = spi_read(); } while ( data_token == 0xFF ); /* エラートークンなら失敗 */ if ( ( data_token & 0x80 ) == 0 ) { spi_release_slave(); return 0; } return 1; } uint8_t sd_step_block_read( void ) { /* ステップ動作のシングルブロックリードで1バイト受信 */ spi_write( 0xFF ); while ( !spi_complete() ); return spi_read(); } char sd_stop_step_block_read() { /* ステップ動作のシングルブロックリード完了 */ /* CRC */ spi_write( 0xFF ); while ( !spi_complete() ); spi_write( 0xFF ); while ( !spi_complete() ); /* ( 一応 )ビジー解除を待つ */ do { spi_write( 0xFF ); while ( !spi_complete() ); } while ( spi_read() != 0xFF ); spi_release_slave(); return 1; } uint64_t sd_get_size( void ) { /* カードサイズを返す */ return unit.card_size; }
2.5
2
2024-11-18T20:15:19.930282+00:00
2020-04-17T23:52:23
55e163c626ee62e158b27747902e4778b1531ac1
{ "blob_id": "55e163c626ee62e158b27747902e4778b1531ac1", "branch_name": "refs/heads/master", "committer_date": "2020-04-17T23:52:23", "content_id": "9fdbce32e44cc0ae5df9d46c61e1ed7baad6c813", "detected_licenses": [ "MIT" ], "directory_id": "74eb97f75042587e2282d80179c522c7fa29d183", "extension": "c", "filename": "testificate.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 204818939, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1267, "license": "MIT", "license_type": "permissive", "path": "/.old/experiments/testificate/testificate.c", "provenance": "stackv2-0033.json.gz:162727", "repo_name": "willfindlay/honors-thesis", "revision_date": "2020-04-17T23:52:23", "revision_id": "a2ca3990797342fbf3b51564bc6c0eea686e856f", "snapshot_id": "4bef5f7bdc561f0993c4ae22618afe709aa73f4c", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/willfindlay/honors-thesis/a2ca3990797342fbf3b51564bc6c0eea686e856f/.old/experiments/testificate/testificate.c", "visit_date": "2022-06-04T16:09:37.874545" }
stackv2
#include <linux/sched.h> static inline u32 bpf_strlen(char *s) { u32 i; for (i = 0; s[i] != '\0' && i < (1 << (32 - 1)); i++); return i; } static inline int bpf_strncmp(char *s1, char *s2, u32 n) { int mismatch = 0; for (int i = 0; i < n && i < sizeof(s1) && i < sizeof(s2); i++) { if (s1[i] != s2[i]) return s1[i] - s2[i]; if (s1[i] == s2[i] == '\0') return 0; } return 0; } static inline int bpf_strcmp(char *s1, char *s2) { u32 s1_size = sizeof(s1); u32 s2_size = sizeof(s2); return bpf_strncmp(s1, s2, s1_size < s2_size ? s1_size : s2_size); } /* Keep userland pid and ignore tid */ static u32 bpf_get_pid() { return (u32)(bpf_get_current_pid_tgid() >> 32); } static int filter() { char comm[TASK_COMM_LEN]; bpf_get_current_comm(&comm, sizeof(comm)); return (bpf_strncmp(comm, "3000shell", TASK_COMM_LEN)); } TRACEPOINT_PROBE(raw_syscalls, sys_enter) { if (filter()) return 0; int syscall = args->id; bpf_trace_printk("sys enter %d\n", syscall); return 0; } TRACEPOINT_PROBE(raw_syscalls, sys_exit) { if (filter()) return 0; int syscall = args->id; bpf_trace_printk("sys exit %d\n", syscall); return 0; }
2.421875
2
2024-11-18T20:15:20.346565+00:00
2023-08-11T18:10:35
9b4e7a8463624561e27bf62d23c92b0af202edd4
{ "blob_id": "9b4e7a8463624561e27bf62d23c92b0af202edd4", "branch_name": "refs/heads/master", "committer_date": "2023-08-11T18:10:35", "content_id": "eb75976d3c46b294c84e10c841f196504e2f5419", "detected_licenses": [ "MIT" ], "directory_id": "31f5cddb9885fc03b5c05fba5f9727b2f775cf47", "extension": "c", "filename": "Json.c", "fork_events_count": 102, "gha_created_at": "2018-03-10T04:07:35", "gha_event_created_at": "2021-06-11T14:29:03", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 124620874, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3404, "license": "MIT", "license_type": "permissive", "path": "/engine/modules/live2d/CubismNativeComponents-3.0/Json.c", "provenance": "stackv2-0033.json.gz:163111", "repo_name": "timi-liuliang/echo", "revision_date": "2023-08-11T18:10:35", "revision_id": "d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24", "snapshot_id": "2935a34b80b598eeb2c2039d686a15d42907d6f7", "src_encoding": "UTF-8", "star_events_count": 822, "url": "https://raw.githubusercontent.com/timi-liuliang/echo/d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24/engine/modules/live2d/CubismNativeComponents-3.0/Json.c", "visit_date": "2023-08-17T05:35:08.104918" }
stackv2
/* * Copyright(c) Live2D Inc. All rights reserved. * * Use of this source code is governed by the Live2D Open Software license * that can be found at http://live2d.com/eula/live2d-open-software-license-agreement_en.html. */ #include "Live2DCubismFrameworkINTERNAL.h" // ------- // // HELPERS // // ------- // /// JSON 'true' token as string. static const char TrueStr[] = "true"; /// JSON 'false' token as string. static const char FalseStr[] = "false"; /// JSON 'null' token as string. static const char NullStr[] = "null"; /// Value identifying invalid token. static const csmJsonTokenType InvalidToken = csmJsonTokenTypeCount; // -------------- // // IMPLEMENTATION // // -------------- // void csmLexJson(const char* jsonString, csmJsonTokenHandler onToken, void* userData) { int tokenBegin, tokenEnd, lex; csmJsonTokenType tokenType; const char* string, * base; // Initialize locals for lexing. tokenType = InvalidToken; string = jsonString; base = jsonString; // Lex. for (lex = 1; *string != '\0' && lex; ++string) { switch (*string) { case '{': { tokenType = csmJsonObjectBegin; tokenBegin = (int)(string - base); tokenEnd = tokenBegin + 1; break; } case '}': { tokenType = csmJsonObjectEnd; tokenBegin = (int)(string - base); tokenEnd = tokenBegin + 1; break; } case '[': { tokenType = csmJsonArrayBegin; tokenBegin = (int)(string - base); tokenEnd = tokenBegin + 1; break; } case ']': { tokenType = csmJsonArrayEnd; tokenBegin = (int)(string - base); tokenEnd = tokenBegin + 1; break; } case '"': { tokenBegin = (int)(string - base) + 1; for (++string; *string != '"'; ++string) { ; } tokenEnd = (int)(string - base); tokenType = (*(string + 1) == ':') ? csmJsonName : csmJsonString; break; } case 't': { tokenType = csmJsonTrue; tokenBegin = (int)(string - base); tokenEnd = tokenBegin + (int)sizeof(TrueStr); string += (tokenEnd - tokenBegin); break; } case 'f': { tokenType = csmJsonFalse; tokenBegin = (int)(string - base); tokenEnd = tokenBegin + (int)sizeof(FalseStr); string += (tokenEnd - tokenBegin); break; } case 'n': { tokenType = csmJsonNull; tokenBegin = (int)(string - base); tokenEnd = tokenBegin + (int)sizeof(NullStr); string += (tokenEnd - tokenBegin); break; } default: { if ((*string >= '0' && *string <= '9') || *string == '-') { tokenType = csmJsonNumber; tokenBegin = (int)(string - base); for (; (*string >= '0' && *string <= '9') || *string == '-' || *string == '.'; ++string) { ; } tokenEnd = (int)(string - base); } break; } } // Do callback if token type is valid. if (tokenType != InvalidToken) { lex = onToken(jsonString, tokenType, tokenBegin, tokenEnd, userData); } // Reset condition for callback. tokenType = InvalidToken; } }
2.28125
2
2024-11-18T20:15:20.490198+00:00
2018-07-21T19:25:14
62f6d2ce144b3180336e921548e96cdfb3a2900f
{ "blob_id": "62f6d2ce144b3180336e921548e96cdfb3a2900f", "branch_name": "refs/heads/master", "committer_date": "2018-07-21T19:25:14", "content_id": "2c42be83d6744822dd9332bb10e12f596cc6ffec", "detected_licenses": [ "MIT" ], "directory_id": "aa593434b039f15f3927aff624862a802152eedc", "extension": "h", "filename": "PPCLibrary.h", "fork_events_count": 0, "gha_created_at": "2022-08-26T00:36:38", "gha_event_created_at": "2022-08-26T00:36:38", "gha_language": null, "gha_license_id": null, "github_id": 529062513, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7265, "license": "MIT", "license_type": "permissive", "path": "/Code/Includes/NED Toolkit/PPCLibrary.h", "provenance": "stackv2-0033.json.gz:163367", "repo_name": "vmlemon/Software", "revision_date": "2018-07-21T19:25:14", "revision_id": "a237bf2a6698bf7bc6c8282227fc22b627e512cc", "snapshot_id": "5915e25e7ec1ee4983532d92997256c89c4370b7", "src_encoding": "IBM852", "star_events_count": 1, "url": "https://raw.githubusercontent.com/vmlemon/Software/a237bf2a6698bf7bc6c8282227fc22b627e512cc/Code/Includes/NED Toolkit/PPCLibrary.h", "visit_date": "2023-03-17T20:57:40.124235" }
stackv2
/* PPCLibrary.h History: The OS 9 implementation of Synclavier PowerPC used the Mac's Program-to-Program Toolbox (a.k.a. "program linking", a.k.a. "Program to Progam Communication"). The PPC Toolbox was used to exchange both traditional 'syncnet' messages between applications and new 'termulator-syncnet' messages. PPC Toolbox allowed communication to applications on other computers. */ #ifndef PPCLibrary_h #define PPCLibrary_h // Global Defines #define PPC_SUGGESTED_BLOCKS_FOR_SYNCNET 200 // suggested packet buffers for syncnet connection #define PPC_SUGGESTED_BLOCKS_FOR_TERMULATOR 20 // suggested character buffers for termulator connection #define PPC_SUGGESTED_BLOCKS_FOR_INTERCHANGE 10 // suggested scsi buffers for scsi connection #define PPC_SUGGESTED_SIZE_FOR_SYNCNET (sizeof(PACKET)) // suggested packet buffer size for syncnet connection #define PPC_SUGGESTED_SIZE_FOR_TERMULATOR 1024 // suggested character buffer size for termulator connection #define PPC_SUGGESTED_SIZE_FOR_INTERCHANGE 0 // suggested scsi buffer size for scsi connection #define PPC_SUGGESTED_DATA_AREA_SIZE 20480 // size in bytes of packet data area in session struct #define PPC_MAX_MAX_BLOCKS 200 // max blocks that can be in a session #ifdef __cplusplus extern "C" { #endif // Enums typedef enum PPC_Status { GOOD_PPC_STATUS = 0, BAD_PPC_STATUS } PPC_Status; typedef enum PPC_SessionStateCodes { PPC_SESSION_NO_STATE = 0, PPC_SESSION_INFORM_POSTED, PPC_SESSION_ACCEPT_POSTED, PPC_SESSION_NEW_SESSION, PPC_SESSION_ACTIVE_SESSION, PPC_SESSION_CLOSING_SESSION } PPC_SessionStateCodes; typedef enum PPC_SessionTypes // indicates starting session type: e.g. syncnet or serial { PPC_SESSION_SYNCNET, // session is a syncnet client (e.g. editview, autoconform) PPC_SESSION_TERMULATOR, // session is a termulator serial port emulator PPC_SESSION_RTP // session is a syncnet and/or termulator host } PPC_SessionTypes; typedef enum PPC_SessionLocales // indicates starting session type: e.g. syncnet or serial { PPC_SESSION_LOCAL, // session is on this computer PPC_SESSION_REMOTE // session is on a remote computer } PPC_SessionLocales; // Sessions are managed by an invisible struct typedef struct PPC_Session* PPC_SessionPtr; // Events published - probably should be moved to shared memory extern long PPC_Library_needs_task_service; // set nonzero when PPC library needs task level service extern long PPC_Library_read_was_completed; // set nonzero when a read completes (e.g. we got a message) extern long PPC_Library_write_has_been_filled; // set nonzero when a write is filled // Routines eligible for calling from a kernel context void PPC_SetCoreStruct (struct SynclavierSharedStruct* it); // Set pointer to shared memory (for interpreter core routines only) long PPC_CountIncomingPacketsAvailable (PPC_SessionPtr session); // Count number of received but not processed packets void* PPC_FindNextIncomingPacket(PPC_SessionPtr session, long* len); // Get pointer to next incoming packet (and its length) to process void PPC_AckIncomingPacket (PPC_SessionPtr session); // Ack long PPC_CountOutgoingPacketsWaiting(PPC_SessionPtr session); // Return how many packets have been filled but not sent yet... void* PPC_FindNextOutgoingPacketToFill(PPC_SessionPtr session); // Find next write buffer, if any long PPC_GetBasicPacketSize (PPC_SessionPtr session); // Get size available for filling packet void PPC_StampNextOutgoingPacket (PPC_SessionPtr sess, long pktlen); // Seal & stamp last filled packet void PPC_SetSessionRefcon (PPC_SessionPtr sess, long refcon); // Set a user-available reference constant for a session long PPC_GetSessionRefcon (PPC_SessionPtr sess); // Get a user-available reference constant for a session long PPC_GetHisSessionIndex (PPC_SessionPtr sess); // Get remotes session index long PPC_GetIndexedRefcon (long index); // Get the refcon for a session via its index long PPC_GetHisSessionType (PPC_SessionPtr sess); // Get type of remote session long PPC_GetHisSessionLocale (PPC_SessionPtr sess); // Get local VS remote for this session // Completion callback hooks extern void (*PPC_Library_read_hook )(PPC_SessionPtr); // read callback hook extern void (*PPC_Library_write_hook)(PPC_SessionPtr); // write callback hook // External routines: PPC_Status PPC_InitializePPCSubsystem(int num_sessions); // Basic initialization; pass no. of simult sessions supported void PPC_SetSharedStruct (struct SynclavierSharedStruct* it); // Set pointer to shared memory (for user space main loop level only) PPC_Status PPC_PublishInform (char *app_name, char *type_name, // Call to publish our port availability using PPCInform char *nbp_name, void (*syncio)(), int visible, int should_inform); void PPC_SetSyncIO(void (*syncio)()); // Set the SynchronizeIO routine that the PPC library should use PPC_Status PPC_CloseOffTheWorld (void); // Call to clean up before program terminates PPC_SessionPtr PPC_BrowseForSynclav (long our_type, long his_type); // Browse for a SynclavierĘ void PPC_GetBrowsedLocation(char *here); // Get location name that was selected void PPC_GetSessionLocation(PPC_SessionPtr session, char *here); // Get location name of session int PPC_RecentConnectionAvailability(void); // See if reconnect available PPC_SessionPtr PPC_Reconnect (long our_type, long his_type); // Reconnect to prior session void PPC_AbortSession (PPC_SessionPtr session); // Abort an open session PPC_SessionPtr PPC_LinkToLocalApplication(char *which, long our_type, // Link to app on local machine if available long his_type); PPC_SessionPtr PPC_FindSessionToClose (void); // Find a dead session to close void PPC_CloseSession (PPC_SessionPtr session); // Close a session PPC_SessionPtr PPC_FindNewSession (void); // Find a new session, if any PPC_SessionPtr PPC_AckNewSession (PPC_SessionPtr session, // Ack the new session event long numBlocks, long blockSize); PPC_SessionPtr PPC_FindSessionToPrime (void); // Find a session whose read que needs to be reprimed void PPC_PrimeSession (PPC_SessionPtr session); // Prime the read que to recover from a full que void* PPC_RetrievePriorOutgoingPacket(PPC_SessionPtr session, // Retrieve prior write buffer, if available long* in_use); void PPC_ReStampRetrievedPacket(PPC_SessionPtr session, long pktlen);// Re-stamp a retrieved packet void PPC_PostFilledPacketsFromTask (PPC_SessionPtr session); // Post a write // Routines that process all active sessions void PPC_PostAllFilledPackets (void); // Post filled packets for all active sessions PPC_SessionPtr PPC_FindSessionWithMail (void); // Find active session with mail #ifdef __cplusplus } #endif #endif
2.0625
2
2024-11-18T20:15:22.120065+00:00
2022-10-10T04:43:06
e9e19c9d7d0457f3ba4f4c01c891335fa369e967
{ "blob_id": "e9e19c9d7d0457f3ba4f4c01c891335fa369e967", "branch_name": "refs/heads/master", "committer_date": "2022-10-10T04:43:06", "content_id": "1112ba5af972ea69b6b5d13a95aeddb080c23c15", "detected_licenses": [ "MIT" ], "directory_id": "64743803f351e8fefab1cadfbadfd686fd819387", "extension": "h", "filename": "devices.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 142841940, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3647, "license": "MIT", "license_type": "permissive", "path": "/src/devices.h", "provenance": "stackv2-0033.json.gz:163880", "repo_name": "TAAPArthur/MPXManager", "revision_date": "2022-10-10T04:43:06", "revision_id": "b064ba1d3c31cfd0d7cf3f8aa100ef2bb96341bf", "snapshot_id": "c11d449a85831758e8c9b39ccee78d73b848ab05", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/TAAPArthur/MPXManager/b064ba1d3c31cfd0d7cf3f8aa100ef2bb96341bf/src/devices.h", "visit_date": "2023-06-07T17:25:11.513318" }
stackv2
/** * @file devices.h * @brief Provides XI2 helper methods for pointer/keyboard related methods like grabs and device query * These methods generally don't modify our internal representation, but just make X calls. * The correct events should be listened for to update state */ #ifndef MPX_DEVICES_H_ #define MPX_DEVICES_H_ #include "masters.h" #include "monitors.h" #include "mywm-structs.h" #include "util/arraylist.h" #include "xutil/xsession.h" /** * Creates a master device with the specified name * @param name the user set prefix of the master device pair */ void createMasterDevice(const char* name); /** * Attaches the specified slave to the specified master * @param slaveID valid slaveID * @param masterID valid MasterID */ void attachSlaveToMasterDevice(SlaveID slaveID, MasterID masterID); /** * Attaches slave to master * If master is NULL, slave becomes floating * * @param slave * @param master */ void attachSlaveToMaster(Slave* slave, Master* master); /** * Disassociates a slave from its master * * @param slaveID */ void floatSlave(SlaveID slaveID) ; /** * Sends a XIChangeHierarchy request to remove the specified master. * The internal state will not be updated until we receive a Hierarchy change event * @param id * @param returnPointer * @param returnKeyboard */ void destroyMasterDevice2(MasterID id, int returnPointer, int returnKeyboard); static inline void destroyMasterDevice(MasterID id) {destroyMasterDevice2(id, DEFAULT_POINTER, DEFAULT_KEYBOARD);} void destroyAllNonEmptyMasters(void); /** * Calls destroyMasterDevice for all non default masters */ void destroyAllNonDefaultMasters(void); /** * Add all existing masters to the list of master devices */ void initCurrentMasters(void); /** * Sets the active master to be the device associated with deviceID * @param deviceID either master keyboard or slave keyboard (or master pointer)id */ bool setActiveMasterByDeviceID(MasterID deviceID); /** * @param id a MasterID or a SlaveID * * @return the active master to be the device associated with deviceID */ Master* getMasterByDeviceID(MasterID id) ; /** * Gets the pointer position relative to a given window * @param id the id of the pointer * @param relativeWindow window to report position relative to * @param result where the x,y location will be stored * @return 1 if result now contains position */ bool getMousePosition(MasterID id, int relativeWindow, int16_t result[2]); /** * Wrapper for getMousePosition * * @param result where the x,y location will be stored * * @return 1 if result now contains position */ static inline bool getActiveMousePosition(int16_t result[2]) { return getMousePosition(getActiveMasterPointerID(), root, result); } /** * Sets the client pointer for the given window to the active master * @param window * @param id */ void setClientPointerForWindow(WindowID window, MasterID id); /** * * * @param win * * @return the MasterID (pointer) associated with win */ MasterID getClientPointerForWindow(WindowID win) ; /** * Returns the client keyboard for the given window * @param win * @return */ Master* getClientMaster(WindowID win) ; /** * Queries the X Server and returns the focused window. * Note this method is different than getFocusedWindow() in that we are not looking our view of focus but the Xserver's * @param id a keyboard master device * @return the current window focused by the given keyboard device */ WindowID getActiveFocusOfMaster(MasterID id); static inline WindowID getActiveFocus(void) {return getActiveFocusOfMaster(getActiveMasterKeyboardID());}; #endif /* DEVICES_H_ */
2.21875
2
2024-11-18T20:15:22.312222+00:00
2018-05-23T06:55:18
c8ba3e7f93e1a1d0e5340c0916763ad546160795
{ "blob_id": "c8ba3e7f93e1a1d0e5340c0916763ad546160795", "branch_name": "refs/heads/master", "committer_date": "2018-05-23T06:55:18", "content_id": "e62cef143c9f16d563672bfabd419e79595e749b", "detected_licenses": [ "MIT" ], "directory_id": "2bc3398063fd7251c46a2d93d2e301cd063befcd", "extension": "c", "filename": "heishi-dan.c", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 134525191, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1847, "license": "MIT", "license_type": "permissive", "path": "/nitan/clone/drug/heishi-dan.c", "provenance": "stackv2-0033.json.gz:164138", "repo_name": "HKMUD/NT6", "revision_date": "2018-05-23T06:55:18", "revision_id": "bb518e2831edc6a83d25eccd99271da06eba8176", "snapshot_id": "ae6a3c173ea07c156e8dc387b3ec21f3280ee0be", "src_encoding": "GB18030", "star_events_count": 9, "url": "https://raw.githubusercontent.com/HKMUD/NT6/bb518e2831edc6a83d25eccd99271da06eba8176/nitan/clone/drug/heishi-dan.c", "visit_date": "2020-03-18T08:44:12.400598" }
stackv2
// Code of ShenZhou //heishi-dan.c //kane 1998.5 #include <ansi.h> inherit PILL; void setup() {} int cure_ob(string); void create() { set_name(BLU"玉洞黑石丹"NOR, ({"yudong dan", "heishi dan", "dan"})); set_weight(50); if (clonep()) set_default_object(__FILE__); else { set("unit", "颗"); set("long", "黑黑的一颗药丸,毫不起眼,却是崆峒派的疗伤圣药。\n"); set("value", 20000); set("no_sell", 1); set("medicine", 1); } setup(); } int cure_ob(object me) { if (me->query_condition("hot_drug") > 0) { if( query("neili", me)>500 ) { addn("neili", -500, me); } else { addn("neili", -(query("neili", me)), me); } message_vision(BLU"$N服下一颗黑石玉洞丹,觉得体内真气翻涌,内力大损。原来服食太急太多,药效适得其反!\n" NOR, me); destruct(this_object()); return 1; } message_vision(BLU"$N服下一颗黑石玉洞丹,只觉三焦通畅,五气调和,内外伤都大有好转。\n"NOR, me); set("eff_qi",query("max_qi", me), me); set("qi",query("max_qi", me), me); me->apply_condition("hot_drug", 20); if ((((int)me->query_condition("qs_damage")) > 0) && (((int)me->query_condition("qs_damage")) < 30)) me->apply_condition("qs_damage",0); else me->apply_condition("qs_damage",(int)me->query_condition("qs_damage")-30); destruct(this_object()); return 1; }
2.015625
2
2024-11-18T20:15:22.827981+00:00
2023-06-02T13:46:19
24e1db339b48a73b6aaafcfca9047c7855896faf
{ "blob_id": "24e1db339b48a73b6aaafcfca9047c7855896faf", "branch_name": "refs/heads/3.16.0-stm32mp", "committer_date": "2023-07-28T12:39:20", "content_id": "439ab9a673e58c0ceb40edf9115a3f223f7f108a", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "a8378f8953015617c24004b33177cdfe45422174", "extension": "c", "filename": "rpc_io_i2c.c", "fork_events_count": 18, "gha_created_at": "2019-01-30T08:45:15", "gha_event_created_at": "2023-05-16T06:47:45", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 168309214, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1660, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/core/arch/arm/kernel/rpc_io_i2c.c", "provenance": "stackv2-0033.json.gz:164523", "repo_name": "STMicroelectronics/optee_os", "revision_date": "2023-06-02T13:46:19", "revision_id": "b8750c4600166f0019a8c1cf35362b1889840ec3", "snapshot_id": "5cbc12679f51b64a018f8a848903803c8c17e8e0", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/STMicroelectronics/optee_os/b8750c4600166f0019a8c1cf35362b1889840ec3/core/arch/arm/kernel/rpc_io_i2c.c", "visit_date": "2023-08-14T23:55:38.933221" }
stackv2
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright 2020 Foundries Ltd <jorge@foundries.io> */ #include <kernel/rpc_io_i2c.h> #include <kernel/thread.h> #include <mm/mobj.h> #include <string.h> /* * @brief: I2C master transfer request to an I2C slave device. * It is the responsibility of the caller to validate the number of bytes * processed by the REE. * * @param req: the secure world I2C master request * @param len: the number of bytes processed by REE * @returns: TEE_SUCCESS on success, TEE_ERROR_XXX on error. */ TEE_Result rpc_io_i2c_transfer(struct rpc_i2c_request *req, size_t *len) { struct thread_param p[4] = { }; TEE_Result res = TEE_SUCCESS; struct mobj *mobj = NULL; uint8_t *va = NULL; assert(req); if (!len) return TEE_ERROR_BAD_PARAMETERS; va = thread_rpc_shm_cache_alloc(THREAD_SHM_CACHE_USER_I2C, THREAD_SHM_TYPE_KERNEL_PRIVATE, req->buffer_len, &mobj); if (!va) return TEE_ERROR_OUT_OF_MEMORY; if (req->mode == RPC_I2C_MODE_WRITE) memcpy(va, req->buffer, req->buffer_len); p[0] = THREAD_PARAM_VALUE(IN, req->mode, req->bus, req->chip); p[1] = THREAD_PARAM_VALUE(IN, req->flags, 0, 0); p[2] = THREAD_PARAM_MEMREF(INOUT, mobj, 0, req->buffer_len); p[3] = THREAD_PARAM_VALUE(OUT, 0, 0, 0); res = thread_rpc_cmd(OPTEE_RPC_CMD_I2C_TRANSFER, ARRAY_SIZE(p), p); if (res != TEE_SUCCESS) return res; /* * Reporting more bytes than supplied or requested from the I2C chip is * an REE error */ if (p[3].u.value.a > req->buffer_len) return TEE_ERROR_EXCESS_DATA; *len = p[3].u.value.a; if (req->mode == RPC_I2C_MODE_READ) memcpy(req->buffer, va, *len); return TEE_SUCCESS; }
2.484375
2
2024-11-18T20:15:23.467334+00:00
2016-04-01T07:15:05
1ae1569b127615d4f36971ba0d16ee1e0a5272e9
{ "blob_id": "1ae1569b127615d4f36971ba0d16ee1e0a5272e9", "branch_name": "refs/heads/master", "committer_date": "2016-04-01T07:15:05", "content_id": "c5a377bccf1b1950fa992d7b42c8a2c8b6dc94d7", "detected_licenses": [ "ISC" ], "directory_id": "e1ef2b3b35fc6488bf64e6ac31f4b22b47f7432f", "extension": "c", "filename": "solution005.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": 1836, "license": "ISC", "license_type": "permissive", "path": "/euler/solution005.c", "provenance": "stackv2-0033.json.gz:164780", "repo_name": "jzgriffin/euler-c", "revision_date": "2016-04-01T07:15:05", "revision_id": "2e8b846793bdcd1c2b206b12d3f96046a5ae3023", "snapshot_id": "db29a0699675c09b5c3977174e95fee14caa9cdd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jzgriffin/euler-c/2e8b846793bdcd1c2b206b12d3f96046a5ae3023/euler/solution005.c", "visit_date": "2022-09-18T02:44:28.606718" }
stackv2
/* * Project Euler in C * Copyright (c) Jeremiah Griffin 2016 * * Permission to use, copy, modify, and/or 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. */ /* * Problem 005: Smallest multiple * 2520 is the smallest number that can be divided by each of the numbers from * 1 to 10 without any remainder. * * What is the smallest positive number that is evenly divisible by all of the * numbers from 1 to 20? */ #include "solution.h" #define MINIMUM 2520 static eu_result_t solve() { const eu_result_t lcm = MINIMUM; eu_result_t number = 0; for (eu_result_t i = lcm; i < EU_RESULT_MAX; i += lcm) { /* This reduced set is the smallest set of factors that span [1,20] * 20: 20, 10, 5, 4, 2 * 19: 19 * 18: 18, 9, 6, 3, 2 * 17: 17 * 16: 16, 8, 4, 2 * 14: 14, 7, 2 * 13: 13 * 11: 11 */ if (i % 20 == 0 && i % 19 == 0 && i % 18 == 0 && i % 17 == 0 && i % 16 == 0 && i % 14 == 0 && i % 13 == 0 && i % 11 == 0) { number = i; break; } } return number; } const eu_solution_t eu_solution005 = {5, solve};
2.59375
3
2024-11-18T20:15:23.886113+00:00
2018-08-08T20:50:48
bb43661ae013c43a2e2013c8ba4dd81626f7b199
{ "blob_id": "bb43661ae013c43a2e2013c8ba4dd81626f7b199", "branch_name": "refs/heads/master", "committer_date": "2018-08-08T20:50:48", "content_id": "85fa48bb5982824f4fe85adc7110552fdade607e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "4c4a073dfd5fee5164ea6575a262919acb964fc2", "extension": "c", "filename": "i1620_cd.c", "fork_events_count": 0, "gha_created_at": "2018-08-10T04:46:26", "gha_event_created_at": "2018-08-10T04:46:26", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 144238005, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16703, "license": "Apache-2.0", "license_type": "permissive", "path": "/tools/sim/simh/I1620/i1620_cd.c", "provenance": "stackv2-0033.json.gz:165166", "repo_name": "jessexm/micronix", "revision_date": "2018-08-08T20:50:48", "revision_id": "24e663a48d9d8673a0ac9c2c048a8a3ef2267e7f", "snapshot_id": "53a8380c17bf9c842c34632286a1fb28b627629d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jessexm/micronix/24e663a48d9d8673a0ac9c2c048a8a3ef2267e7f/tools/sim/simh/I1620/i1620_cd.c", "visit_date": "2020-03-25T22:43:04.084088" }
stackv2
/* i1620_cd.c: IBM 1622 card reader/punch Copyright (c) 2002-2012, Robert M. Supnik 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 ROBERT M SUPNIK 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. Except as contained in this notice, the name of Robert M Supnik shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Robert M Supnik. cdr 1622 card reader cdp 1622 card punch 19-Mar-12 RMS Fixed declarations of saved_pc, io_stop (Mark Pizzolato) 19-Jan-07 RMS Set UNIT_TEXT flag 13-Jul-06 RMS Fixed card reader fgets call (Tom McBride) Fixed card reader boot sequence (Tom McBride) 21-Sep-05 RMS Revised translation tables for 7094/1401 compatibility 25-Apr-03 RMS Revised for extended file support Cards are represented as ASCII text streams terminated by newlines. This allows cards to be created and edited as normal files. */ #include "i1620_defs.h" #define CD_LEN 80 extern uint8 M[MAXMEMSIZE]; extern uint8 ind[NUM_IND]; extern UNIT cpu_unit; extern uint32 io_stop; char cdr_buf[CD_LEN + 2]; char cdp_buf[CD_LEN + 2]; t_stat cdr_reset (DEVICE *dptr); t_stat cdr_attach (UNIT *uptr, char *cptr); t_stat cdr_boot (int32 unitno, DEVICE *dptr); t_stat cdr_read (void); t_stat cdp_reset (DEVICE *dptr); t_stat cdp_write (uint32 len); t_stat cdp_num (uint32 pa, uint32 ndig, t_bool dump); /* Card reader data structures cdr_dev CDR descriptor cdr_unit CDR unit descriptor cdr_reg CDR register list */ UNIT cdr_unit = { UDATA (NULL, UNIT_SEQ+UNIT_ATTABLE+UNIT_ROABLE+UNIT_TEXT, 0) }; REG cdr_reg[] = { { FLDATA (LAST, ind[IN_LAST], 0) }, { DRDATA (POS, cdr_unit.pos, T_ADDR_W), PV_LEFT }, { NULL } }; DEVICE cdr_dev = { "CDR", &cdr_unit, cdr_reg, NULL, 1, 10, 31, 1, 8, 7, NULL, NULL, &cdr_reset, &cdr_boot, &cdr_attach, NULL }; /* CDP data structures cdp_dev CDP device descriptor cdp_unit CDP unit descriptor cdp_reg CDP register list */ UNIT cdp_unit = { UDATA (NULL, UNIT_SEQ+UNIT_ATTABLE+UNIT_TEXT, 0) }; REG cdp_reg[] = { { DRDATA (POS, cdp_unit.pos, T_ADDR_W), PV_LEFT }, { NULL } }; DEVICE cdp_dev = { "CDP", &cdp_unit, cdp_reg, NULL, 1, 10, 31, 1, 8, 7, NULL, NULL, &cdp_reset, NULL, NULL, NULL }; /* Data tables. The card reader presents unusual problems. - Unique codes needed for 11-2-8 (uses !) and 12-7-8 (uses ") . - Can punch both 11 (-) and 11-0 (uses ]). On input, the nul and nl generated by C are converted to spaces; tabs and line feeds are also converted to spaces. /* Card reader (ASCII) to numeric (one digit) */ const char cdr_to_num[128] = { 0x00, -1, -1, -1, -1, -1, -1, -1, /* 00 */ -1, 0x00, 0x00, -1, -1, 0x00, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10 */ -1, -1, -1, -1, -1, -1, -1, -1, 0x00, 0x1A, 0x0F, 0x0B, 0x1B, 0x0C, 0x00, 0x0C, /* !"#$%&' */ 0x0C, 0x0C, 0x1C, 0x00, 0x0B, 0x10, 0x1B, 0x01, /* ()*+,-./ */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 01234567 */ 0x08, 0x09, 0x00, 0x1E, 0x1E, 0x0B, 0x0E, 0x1A, /* 89:;<=>? */ 0x0C, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* @ABCDEFG */ 0x08, 0x09, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, /* HIJKLMNO */ 0x17, 0x18, 0x19, 0x02, 0x03, 0x04, 0x05, 0x06, /* PQRSTUVW */ 0x07, 0x08, 0x09, 0x00, 0x0E, 0x10, 0x0A, 0x1F, /* XYZ[\]^_ */ -1, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* `abcdefg */ 0x08, 0x09, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, /* hijklmno */ 0x17, 0x18, 0x19, 0x02, 0x03, 0x04, 0x05, 0x06, /* pqrstuvw */ 0x07, 0x08, 0x09, 0x0F, 0x0A, 0x1F, 0x00, -1 /* xyz{|}~ */ }; /* Numeric (flag + digit) to card punch (ASCII) */ const char num_to_cdp[32] = { '0', '1', '2', '3', '4', '5', '6', '7', /* 0 */ '8', '9', '|', ',', ' ', '"', ' ', '"', ']', 'J', 'K', 'L', 'M', 'N', 'O', 'P', /* F + 0 */ 'Q', 'R', '!', '$', -1, -1, -1, '"' }; /* Card reader (ASCII) to alphameric (two digits) 11-2-8 (!) reads as 5A 11-7-8 (_) reads as 5F 12-2-8 (?) reads inconsistently (here 02) 12-6-8 (<) reads inconsistently (here 5E) 12-7-8 (}) reads as 5F */ const char cdr_to_alp[128] = { 0x00, -1, -1, -1, -1, -1, -1, -1, /* 00 */ -1, 0x00, 0x00, -1, -1, 0x00, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10 */ -1, -1, -1, -1, -1, -1, -1, -1, 0x00, 0x5A, 0x0F, 0x33, 0x13, 0x24, 0x10, 0x34, /* !"#$%&' */ 0x24, 0x04, 0x14, 0x10, 0x23, 0x20, 0x03, 0x21, /* ()*+,-./ */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 01234567 */ 0x78, 0x79, 0x70, 0x5E, 0x5E, 0x33, 0x0E, 0x02, /* 89:;<=>? */ 0x34, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* @ABCDEFG */ 0x48, 0x49, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, /* HIJKLMNO */ 0x57, 0x58, 0x59, 0x62, 0x63, 0x64, 0x65, 0x66, /* PQRSTUVW */ 0x67, 0x68, 0x69, 0x40, 0x0E, 0x50, 0x0A, 0x5F, /* XYZ[\]^_ */ 0x50, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* `abcdefg */ 0x48, 0x49, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, /* hijklmno */ 0x57, 0x58, 0x59, 0x62, 0x63, 0x64, 0x65, 0x66, /* pqrstuvw */ 0x67, 0x68, 0x69, 0x0F, 0x0A, 0x5F, 0x60, -1 /* xyz{|}~ */ }; /* Alphameric (two digits) to card punch (ASCII). Oddities: 02 -> 12-2-8 (?), symmetric 07 -> 12-7-8 (}), reads as 5F 12 -> 11-2-8 (!), reads as 5A 15 -> 11,0 (`), reads as 50 22 -> 0-2-8 (|), reads as 0A 32 -> 2-8 (^), reads as 0A 5B -> 11-3-8 (=), reads as 13 6A -> 0-2-8 (|), reads as 0A 6B -> 0-3-8 (,), reads as 23 AA -> 0-2-8 (|), reads as 0A There is no way to punch 0-5-8 (~), 0-6-8 (\), 11-5-8 (]), 11-6-8 (;), 11-7-8 (_), 12-5-8 ([), or 12-6-8 (<) */ const char alp_to_cdp[256] = { ' ', -1, '?', '.', ')', -1, -1, '}', /* 00 */ -1, -1, '\'', -1, -1, -1, -1, '"', '+', -1, '!', '$', '*', ']', -1, -1, /* 10 */ -1, -1, -1, -1, -1, -1, -1, -1, '-', '/', '|', ',', '(', -1, -1, -1, /* 20 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, '^', '=', '@', ':', ' ', -1, /* 30 */ -1, -1, '|', -1, -1, -1, -1, '"', -1, 'A', 'B', 'C', 'D', 'E', 'F', 'G', /* 40 */ 'H', 'I', -1, -1, -1, -1, -1, -1, '_', 'J', 'K', 'L', 'M', 'N', 'O', 'P', /* 50 */ 'Q', 'R', '?', '=', -1, -1, -1, '}', -1, '/', 'S', 'T', 'U', 'V', 'W', 'X', /* 60 */ 'Y', 'Z', '|', ',', -1, -1, -1, -1, '0', '1', '2', '3', '4', '5', '6', '7', /* 70 */ '8', '9', -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 90 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A0 */ -1, -1, '|', -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* B0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* C0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* D0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* E0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* F0 */ -1, -1, -1, -1, -1, -1, -1, -1 }; /* Card reader IO routine - Hard errors stop the operation and halt the system. - Invalid characters place a blank in memory and set RDCHK. If IO stop is set, the system halts at the end of the operation. */ t_stat cdr (uint32 op, uint32 pa, uint32 f0, uint32 f1) { int32 i; int8 cdc; t_stat r, sta; sta = SCPE_OK; /* assume ok */ switch (op) { /* case on op */ case OP_RN: /* read numeric */ r = cdr_read (); /* fill reader buf */ if (r != SCPE_OK) /* error? */ return r; for (i = 0; i < CD_LEN; i++) { /* transfer to mem */ cdc = cdr_to_num[cdr_buf[i]]; /* translate */ if (cdc < 0) { /* invalid? */ ind[IN_RDCHK] = 1; /* set read check */ if (io_stop) /* set return status */ sta = STOP_INVCHR; cdc = 0; } M[pa] = cdc; /* store digit */ PP (pa); /* incr mem addr */ } break; case OP_RA: /* read alphameric */ r = cdr_read (); /* fill reader buf */ if (r != SCPE_OK) /* error? */ return r; for (i = 0; i < CD_LEN; i++) { /* transfer to mem */ cdc = cdr_to_alp[cdr_buf[i]]; /* translate */ if (cdc < 0) { /* invalid? */ ind[IN_RDCHK] = 1; /* set read check */ if (io_stop) /* set return status */ sta = STOP_INVCHR; cdc = 0; }; M[pa] = (M[pa] & FLAG) | (cdc & DIGIT); /* store 2 digits */ M[pa - 1] = (M[pa - 1] & FLAG) | ((cdc >> 4) & DIGIT); pa = ADDR_A (pa, 2); /* incr mem addr */ } break; default: /* invalid function */ return STOP_INVFNC; } return sta; } /* Fill card reader buffer - all errors are hard errors */ t_stat cdr_read (void) { int32 i; ind[IN_LAST] = 0; /* clear last card */ if ((cdr_unit.flags & UNIT_ATT) == 0) { /* attached? */ ind[IN_RDCHK] = 1; /* no, error */ return SCPE_UNATT; } for (i = 0; i < CD_LEN + 2; i++) /* clear buffer */ cdr_buf[i] = ' '; fgets (cdr_buf, CD_LEN + 2, cdr_unit.fileref); /* read card */ if (feof (cdr_unit.fileref)) /* eof? */ return STOP_NOCD; if (ferror (cdr_unit.fileref)) { /* error? */ ind[IN_RDCHK] = 1; /* set read check */ perror ("CDR I/O error"); clearerr (cdr_unit.fileref); return SCPE_IOERR; } cdr_unit.pos = ftell (cdr_unit.fileref); /* update position */ getc (cdr_unit.fileref); /* see if more */ if (feof (cdr_unit.fileref)) /* eof? set last */ ind[IN_LAST] = 1; fseek (cdr_unit.fileref, cdr_unit.pos, SEEK_SET); /* "backspace" */ return SCPE_OK; } /* Card reader attach */ t_stat cdr_attach (UNIT *uptr, char *cptr) { ind[IN_LAST] = 0; /* clear last card */ return attach_unit (uptr, cptr); } /* Card reader reset */ t_stat cdr_reset (DEVICE *dptr) { ind[IN_LAST] = 0; /* clear last card */ return SCPE_OK; } /* Bootstrap routine */ #define BOOT_START 0 t_stat cdr_boot (int32 unitno, DEVICE *dptr) { t_stat r; uint32 old_io_stop; extern uint32 saved_PC; old_io_stop = io_stop; io_stop = 1; r = cdr (OP_RN, 0, 0, 0); /* read card @ 0 */ io_stop = old_io_stop; if (r != SCPE_OK) /* error? */ return r; saved_PC = BOOT_START; return SCPE_OK; } /* Card punch IO routine - Hard errors stop the operation and halt the system. - Invalid characters stop the operation and set WRCHK. If IO stop is set, the system halts. */ t_stat cdp (uint32 op, uint32 pa, uint32 f0, uint32 f1) { int32 i; int8 cdc; uint8 z, d; switch (op) { /* decode op */ case OP_DN: return cdp_num (pa, 20000 - (pa % 20000), TRUE); /* dump numeric */ case OP_WN: return cdp_num (pa, CD_LEN, FALSE); /* write numeric */ case OP_WA: for (i = 0; i < CD_LEN; i++) { /* one card */ d = M[pa] & DIGIT; /* get digit pair */ z = M[pa - 1] & DIGIT; cdc = alp_to_cdp[(z << 4) | d]; /* translate */ if (cdc < 0) { /* bad char? */ ind[IN_WRCHK] = 1; /* set write check */ CRETIOE (io_stop, STOP_INVCHR); } cdp_buf[i] = cdc; /* store in buf */ pa = ADDR_A (pa, 2); /* incr mem addr */ } return cdp_write (CD_LEN); /* punch buffer */ default: /* invalid function */ break; } return STOP_INVFNC; } /* Punch card numeric */ t_stat cdp_num (uint32 pa, uint32 ndig, t_bool dump) { int32 i, ncd, len; uint8 d; int8 cdc; t_stat r; ncd = ndig / CD_LEN; /* number of cards */ while (ncd-- >= 0) { /* until done */ len = (ncd >= 0)? CD_LEN: (ndig % CD_LEN); /* card length */ if (len == 0) break; for (i = 0; i < len; i++) { /* one card */ d = M[pa] & (FLAG | DIGIT); /* get char */ if (dump && (d == FLAG)) cdc = '-'; /* dump? F+0 is diff */ else cdc = num_to_cdp[d]; /* translate */ if (cdc < 0) { /* bad char? */ ind[IN_WRCHK] = 1; /* set write check */ CRETIOE (io_stop, STOP_INVCHR); /* stop */ } cdp_buf[i] = cdc; /* store in buf */ PP (pa); /* incr mem addr */ } r = cdp_write (len); /* punch card */ if (r != SCPE_OK) /* error? */ return r; } return SCPE_OK; } /* Write punch card buffer - all errors are hard errors */ t_stat cdp_write (uint32 len) { if ((cdp_unit.flags & UNIT_ATT) == 0) { /* attached? */ ind[IN_WRCHK] = 1; /* no, error */ return SCPE_UNATT; } while ((len > 0) && (cdp_buf[len - 1] == ' ')) /* trim spaces */ --len; cdp_buf[len] = '\n'; /* newline, null */ cdp_buf[len + 1] = 0; fputs (cdp_buf, cdp_unit.fileref); /* write card */ cdp_unit.pos = ftell (cdp_unit.fileref); /* count char */ if (ferror (cdp_unit.fileref)) { /* error? */ ind[IN_WRCHK] = 1; perror ("CDP I/O error"); clearerr (cdp_unit.fileref); return SCPE_IOERR; } return SCPE_OK; } /* Reset card punch */ t_stat cdp_reset (DEVICE *dptr) { return SCPE_OK; }
2.109375
2
2024-11-18T20:15:24.100876+00:00
2020-08-09T19:28:03
99da6cc03e55b795d332f9c0533c276775497fee
{ "blob_id": "99da6cc03e55b795d332f9c0533c276775497fee", "branch_name": "refs/heads/dev", "committer_date": "2020-08-09T19:28:03", "content_id": "e324cb2c756dce384fce453226fa49a47dd52917", "detected_licenses": [ "MIT" ], "directory_id": "63b300470e775a73bc0cb9785771cb5d4c2b2ee1", "extension": "h", "filename": "zone.h", "fork_events_count": 12, "gha_created_at": "2019-11-21T02:40:44", "gha_event_created_at": "2020-07-27T21:08:07", "gha_language": "C", "gha_license_id": "MIT", "github_id": 223072567, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 720, "license": "MIT", "license_type": "permissive", "path": "/src/engine/zone.h", "provenance": "stackv2-0033.json.gz:165426", "repo_name": "MotoLegacy/OpenFNaF", "revision_date": "2020-08-09T19:28:03", "revision_id": "5a97b170b7c602046ab570e235e41b7634cfdc45", "snapshot_id": "41ab6e110f4f81c1ada1ff6b5d9f2856ca5b253a", "src_encoding": "UTF-8", "star_events_count": 46, "url": "https://raw.githubusercontent.com/MotoLegacy/OpenFNaF/5a97b170b7c602046ab570e235e41b7634cfdc45/src/engine/zone.h", "visit_date": "2023-06-16T11:36:55.950536" }
stackv2
// (c) 2020 MotoLegacy // This code is licensed under MIT license (see LICENSE for details) typedef struct block_s block_t; struct block_s { int size; // Size of the block int tag; // Block tags int id; // The block's ID block_t* previous; // Previous block in list block_t* next; // Next block in list }; // Tags for block_t enum { MT_STATIC = 1, // Static for the whole time MT_CACHED, // Freed after use MT_FREE, // Can be allocated MT_PURGABLE, // Not immediately important, so can be freed. // MT_TAGS }; extern void Zone_Init();
2.09375
2
2024-11-18T20:15:24.498930+00:00
2021-09-03T13:58:25
b379457d4c74122662ffe94a08ad85ac0e47b162
{ "blob_id": "b379457d4c74122662ffe94a08ad85ac0e47b162", "branch_name": "refs/heads/main", "committer_date": "2021-09-03T13:58:25", "content_id": "1af7cc037001533b13d249424c8a17d7f94ebd7b", "detected_licenses": [ "MIT" ], "directory_id": "56e210d874e156b03ff0b49b2ee3322af2bd7fd2", "extension": "c", "filename": "BigOrLittleEndian.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 402782836, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 257, "license": "MIT", "license_type": "permissive", "path": "/About_Machine/BigOrLittleEndian.c", "provenance": "stackv2-0033.json.gz:165554", "repo_name": "whitejoce/Pwn", "revision_date": "2021-09-03T13:58:25", "revision_id": "445122bbc85bb7cafdbd9623e7926ed8456babdd", "snapshot_id": "d4a69719268edaaba39cf009fde202a3898c4f40", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/whitejoce/Pwn/445122bbc85bb7cafdbd9623e7926ed8456babdd/About_Machine/BigOrLittleEndian.c", "visit_date": "2023-07-25T06:55:35.790410" }
stackv2
#include <stdio.h> //From nginx int main(){ int i = 0x11223344; char *p; p = (char *) &i; if (*p == 0x44) { printf("Little Endian\n"); } else { printf("Big Endian\n"); } return 0; }
2.453125
2
2024-11-18T20:15:25.182896+00:00
2020-06-26T01:19:35
b0dc9aa02a0318b74cec66fa2b9cc77f9a0c3f5e
{ "blob_id": "b0dc9aa02a0318b74cec66fa2b9cc77f9a0c3f5e", "branch_name": "refs/heads/master", "committer_date": "2020-06-26T01:19:35", "content_id": "a61dcc5aa952a4283077e5a09eef95fddd04314a", "detected_licenses": [ "MIT" ], "directory_id": "d7f9674d448a2c801a4c603dfb7798f9795d775c", "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": 271564611, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9579, "license": "MIT", "license_type": "permissive", "path": "/lab07-knapsack/main.c", "provenance": "stackv2-0033.json.gz:166581", "repo_name": "shirosweets/lab07", "revision_date": "2020-06-26T01:19:35", "revision_id": "69536fc2aebfa50267df66759fb54befbdd129a2", "snapshot_id": "912ce01c8844587ecd41995f35c79a67b4f4b827", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/shirosweets/lab07/69536fc2aebfa50267df66759fb54befbdd129a2/lab07-knapsack/main.c", "visit_date": "2022-11-14T14:42:34.798803" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <unistd.h> #include <limits.h> #include "helpers.h" #include "knapsack.h" #define MAX_FILES 100 void show_usage() { printf("Usage:\n"); printf("knapsack <option>\n"); printf("-f <files> Run algorithms on the all the files listed." "Stdin is used by default\n"); printf("-b Enable backtracking algorithm\n"); printf("-d Enable dynamic algorithm\n"); printf("-s Show selected items (only in dynamic algorithm)\n"); printf("-t Enable testing (checks VALUE field on the first line" " of each input file)\n"); printf("-w <arg> Force knapsack capacity to [arg]. "); printf("Reads KNAPSACK field on first line of each input file" " by default\n\r"); printf("Example: knapsack -bds -f input/example*.in\n"); } //open a file with the given name, or select stdin if null. FILE* open_file(const char* filename) { FILE* file = NULL; if (filename == NULL) { file = stdin; } else { file = fopen(filename, "r"); if (file == NULL) { fprintf(stderr, "Error opening file %s.\n", filename); exit(1); } } return (file); } //close file if not stdin void close_file(FILE* file) { if (file != stdin) { fclose(file); } } //parse an unsigned int from a string unsigned int uint_from_string(const char* str) { char* data = NULL; unsigned long int conv = strtoul(str, &data, 10); unsigned int res = 0; if ((data != NULL && *data != 0) || (conv > UINT_MAX)) { fprintf(stderr, "INVALID UNSIGNED INT (INPUT \"%s\")\n", str); exit(1); } else { res = (unsigned int) conv; } return (res); } //parse first line of a file. Looks for a line starting with '#' //then the KNAPSACK field with the desired capacity, and VALUE with the //expected value. void parse_first_line(FILE* file, weight_t* weight, value_t* expected, bool* test) { char* line = readline(file); if (line != NULL) { char* token = strtok(line, " :\t\n"); if (token != NULL && strcmp(token, "#") == 0) { char* wtoken = strtok(NULL, " :\t\n"); if (wtoken != NULL && (strcmp(wtoken, "KNAPSACK") == 0)) { char* w_str = strtok(NULL, " :\t\n"); if (w_str != NULL && strlen(w_str) > 0) { *weight = uint_from_string(w_str); } } wtoken = strtok(NULL, " :\t\n"); if (wtoken != NULL && (strcmp(wtoken, "VALUE") == 0)) { char* w_str = strtok(NULL, " :\t\n"); if (w_str != NULL && strlen(w_str) > 0) { *expected = uint_from_string(w_str); } } else { if (*test) { printf("-t option expects VALUE field" " in the first line\n"); *test = false; } } } else { //no # line, file should point at the beginning. rewind(file); } free(line); } } //execute algorithms on the given file. int run_file(const char* filename, bool do_backtracking, bool do_dynamic, bool show_items, bool test, weight_t weight) { FILE* file = NULL; int fails = 0; value_t expected = 0; unsigned int array_length = 0u; file = open_file(filename); if (file != stdin) { //if not stdin, parse first line, starting with # weight_t aux = 0; parse_first_line(file, &aux, &expected, &test); if (weight == 0) //not -w option, or -w 0. { printf("Reading KNAPSACK capacity from file...\n"); weight = aux; } } printf("Reading ITEMS from %s...\n", file == stdin ? "stdin" : "file"); item_t* items = item_read_from_file(file, &array_length); close_file(file); printf("Knapsack capacity: %u\n", weight); printf("Items: %u\n", array_length); value_t backtracking_value = 0; if (do_backtracking) { //if backtracking is enabled, run it. printf("Backtracking solution...\n"); value_t value = knapsack_backtracking(items, array_length, weight); printf("Value: %u\n", value); if (test) { printf("Test - Value matches expected: %s\n", value == expected ? "OK" : "FAIL"); fails = fails + (value == expected ? 0 : 1); } backtracking_value = value; } if (do_dynamic) { //if dynamic is enabled, run it. printf("Dynamic solution...\n"); value_t value = 0; if (show_items) { //if items are requested, run knapsack_dynamic_selection bool* selected = calloc(array_length, sizeof(bool)); if (selected == NULL) { fprintf(stderr, "No more memory available!\n"); exit(1); } value = knapsack_dynamic_selection(items, selected, array_length, weight); printf("Selected items:\n"); value_t total = 0; weight_t sum = 0; for (unsigned int i = 0u; i < array_length; i++) { if (selected[i]) { //if selected, print it. item_t item = items[i]; total = total + item_value(item); sum = sum + item_weight(item); printf("%s:%u:%u\n", string_ref(item_id(item)), item_value(item), item_weight(item)); } } if (test) { printf("Test - Selected items value: %s\n", total == value ? "OK" : "FAIL"); printf("Test - Selected items weight: %s\n", sum <= weight ? "OK" : "FAIL"); fails = fails + (sum <= weight ? 0 : 1); fails = fails + (total == value ? 0 : 1); } free(selected); selected = NULL; } else { //items are not requested, use knapsack_dynamic algorithm value = knapsack_dynamic(items, array_length, weight); } printf("Value: %d\n", value); if (test) { printf("Test - Value matches expected: %s\n", value == expected ? "OK" : "FAIL"); fails = fails + (value == expected ? 0 : 1); if (do_backtracking) { printf("Test - Matches backtracking value: %s\n", value == backtracking_value ? "OK" : "FAIL"); fails = fails + (value == backtracking_value ? 0 : 1); } } } //destroy items for (unsigned int i = 0; i < array_length; i++) { items[i] = item_destroy(items[i]); } free(items); return (fails); } bool is_option(const char* str) { return (*str == '-' && strlen(str) == 2); } int main(int argc, char** argv) { printf(" ********* Inicio programa *********\n\n"); char* filenames[MAX_FILES]; int option = 0; bool do_backtracking = false; bool do_dynamic = false; bool show_items = false; bool test = false; unsigned int weight = 0u; unsigned int files_count = 0u; if (argc == 1) { show_usage(); exit(EXIT_FAILURE); } while ((option = getopt(argc, argv, "f:w:sbdt")) != -1) { switch (option) { case 'b': do_backtracking = true; break; case 'd': do_dynamic = true; break; case 's': show_items = true; break; case 'f': optind--; while (optind < argc && !is_option(argv[optind]) && files_count < MAX_FILES) { files_count++; filenames[files_count - 1] = argv[optind]; optind++; } break; case 'w': weight = uint_from_string(optarg); break; case 't': test = true; break; case '?': show_usage(); exit(EXIT_FAILURE); break; default: break; } } if (files_count == 0u) { filenames[0] = NULL; files_count = 1; test = false; } int fails = 0; for (unsigned int i = 0u; i < files_count; ++i) { printf("READING %s\n", filenames[i] == NULL ? "stdin" : filenames[i]); fails = run_file(filenames[i], do_backtracking, do_dynamic, show_items, test, weight); printf("DONE %s.\n\n", filenames[i] == NULL ? "stdin" : filenames[i]); } if (fails > 0 && test) { printf("\n\n FAILS: %d \n\n", fails); } else if (test) { printf("\n\n ALL TESTS OK \n\n"); } printf("\n ********* Fin programa *********\n"); return EXIT_SUCCESS; }
2.890625
3
2024-11-18T20:15:25.287116+00:00
2015-06-09T22:46:17
4639805dfd895c0c97f0696320f38f4423066f52
{ "blob_id": "4639805dfd895c0c97f0696320f38f4423066f52", "branch_name": "refs/heads/master", "committer_date": "2015-06-09T22:46:17", "content_id": "ccf168afc3a18c5591967e0d57ef2f649a13bcf9", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "b80b5edd64583497df96e3b07e9b3e12b9577b99", "extension": "c", "filename": "sys.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 36564353, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1285, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Kernel/sys.c", "provenance": "stackv2-0033.json.gz:166709", "repo_name": "LucasCasa/Kerner", "revision_date": "2015-06-09T22:46:17", "revision_id": "8a5c230d228923b3b0815df6a8f0191ecafad6c5", "snapshot_id": "2a14be48924fa8bd7d40ca9f87225a4ebc560161", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LucasCasa/Kerner/8a5c230d228923b3b0815df6a8f0191ecafad6c5/Kernel/sys.c", "visit_date": "2021-03-19T14:15:57.947952" }
stackv2
#include <stdint.h> #include "sys.h" //syscall 1 ---> escribo en pantalla //syscall 2 ---> borro caracter //syscall 3 ---> devuelvo el ultimo caracter //syscall 4 ---> modifica el modificador del video //syscall 5 ---> clear screen // syscall 6 ---> palabra que se escribio. char sys_manager(int order,uint64_t arg1, uint64_t arg2){ char c; switch(order){ case WRITE: sys_write((char) arg1,(char) arg2); break; case ERASE_SCR: erase_screen(); reset_current_video(); break; case GET_STR: return read((char *)arg1,(uint8_t) arg2); break; case GET_CHAR: c = read_char(); return c; break; case RTC_READ: return RTCparameters((char)arg1); break; case RTC_WRITE: set_date((char)arg1,(uint32_t)arg2); // 1st arg type to change (Year, Month, Hour, etc.) 2nd arg the amount break; case COLORS: set_default_modifiers((uint8_t) arg1, (uint8_t) arg2); break; case SCR_TIME: return validateScreenTime(arg1); break; } return 0; } char read_char(){ if(C_is_empty()) return 0; char c = clean_get_char(); return c; } char read(char* buff, uint8_t size){ int i; if(C_is_empty()) return 0; if(size == 0) size = 255; char c; for( i= 0; i<size && (c = clean_get_char()) != '\n';i++){ buff[i] = c; } return i; }
2.484375
2
2024-11-18T20:15:25.358664+00:00
2023-07-28T18:04:02
16f243dbccb853aed79374e8f2be20eb77c6cc40
{ "blob_id": "16f243dbccb853aed79374e8f2be20eb77c6cc40", "branch_name": "refs/heads/master", "committer_date": "2023-07-28T18:32:24", "content_id": "6faa2d1c9d41c256f2916b2ead536c04cc331b16", "detected_licenses": [ "MIT" ], "directory_id": "5a18bd4798e3cdb6fcf1655cbf014083977e8be7", "extension": "c", "filename": "b_sem.c", "fork_events_count": 115, "gha_created_at": "2019-11-21T05:40:42", "gha_event_created_at": "2022-04-21T07:41:23", "gha_language": "C", "gha_license_id": "MIT", "github_id": 223096955, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3703, "license": "MIT", "license_type": "permissive", "path": "/bos/core/b_sem.c", "provenance": "stackv2-0033.json.gz:166839", "repo_name": "notrynohigh/BabyOS", "revision_date": "2023-07-28T18:04:02", "revision_id": "a5f34ebba543b0248d81c0d92023d3f7a792725d", "snapshot_id": "74c9532d9391f9d501ce0c7abe454c9845599b8a", "src_encoding": "UTF-8", "star_events_count": 343, "url": "https://raw.githubusercontent.com/notrynohigh/BabyOS/a5f34ebba543b0248d81c0d92023d3f7a792725d/bos/core/b_sem.c", "visit_date": "2023-08-18T07:19:28.112867" }
stackv2
/** *! * \file b_sem.c * \version v0.0.1 * \date 2019/06/05 * \author Bean(notrynohigh@outlook.com) ******************************************************************************* * @attention * * Copyright (c) 2019 Bean * * 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. ******************************************************************************* */ /*Includes ----------------------------------------------*/ #include "core/inc/b_sem.h" #include "b_section.h" #include "hal/inc/b_hal.h" /** * \addtogroup BABYOS * \{ */ /** * \addtogroup CORE * \{ */ /** * \addtogroup SEM * \{ */ /** * \defgroup SEM_Private_TypesDefinitions * \{ */ /** * \} */ /** * \defgroup SEM_Private_Defines * \{ */ /** * \} */ /** * \defgroup SEM_Private_Macros * \{ */ /** * \} */ /** * \defgroup SEM_Private_Variables * \{ */ static LIST_HEAD(bSemListHead); /** * \} */ /** * \defgroup SEM_Private_FunctionPrototypes * \{ */ /** * \} */ /** * \defgroup SEM_Private_Functions * \{ */ static bSemAttr_t *_bSemFind(bSemId_t id) { struct list_head *pos = NULL; bSemAttr_t *pattr = NULL; list_for_each(pos, &bSemListHead) { pattr = list_entry(pos, bSemAttr_t, list); if (pattr == ((bSemAttr_t *)id)) { break; } pattr = NULL; } return pattr; } /** * \} */ /** * \addtogroup SEM_Exported_Functions * \{ */ bSemId_t bSemCreate(uint32_t max_count, uint32_t initial_count, bSemAttr_t *attr) { if (attr == NULL) { return NULL; } if (_bSemFind(attr) != NULL) { return attr; } attr->value = initial_count; attr->value_max = max_count; list_add(&attr->list, &bSemListHead); return attr; } int bSemAcquireNonblock(bSemId_t id) { bSemAttr_t *attr = NULL; if (id == NULL) { return -1; } attr = _bSemFind(id); if (attr == NULL || attr->value == 0) { return -1; } attr->value -= 1; return 0; } int bSemRelease(bSemId_t id) { bSemAttr_t *attr = NULL; if (id == NULL) { return -1; } attr = _bSemFind(id); if (attr == NULL) { return -1; } if (attr->value < attr->value_max) { attr->value += 1; } return 0; } uint32_t bSemGetCount(bSemId_t id) { bSemAttr_t *attr = NULL; if (id == NULL) { return 0; } attr = _bSemFind(id); if (attr == NULL) { return 0; } return attr->value; } /** * \} */ /** * \} */ /** * \} */ /************************ Copyright (c) 2019 Bean *****END OF FILE****/
2.140625
2
2024-11-18T20:15:25.746313+00:00
2021-01-14T04:01:17
4019046455dc18b1f60cd2976a57671cc28a30c4
{ "blob_id": "4019046455dc18b1f60cd2976a57671cc28a30c4", "branch_name": "refs/heads/main", "committer_date": "2021-01-14T04:01:17", "content_id": "72b28db5612315821321b86b479804355a889808", "detected_licenses": [ "MIT" ], "directory_id": "8729ca1540b71557091902abd0a7785509acc543", "extension": "c", "filename": "mydev.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 304386986, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1097, "license": "MIT", "license_type": "permissive", "path": "/workspace/lab4/mydev.c", "provenance": "stackv2-0033.json.gz:167354", "repo_name": "biomotion/eos-2020", "revision_date": "2021-01-14T04:01:17", "revision_id": "0f457f72cbefe487808183994c7381f59c4e3235", "snapshot_id": "2b5301d4633f40ef9cffb83e924e176983def919", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/biomotion/eos-2020/0f457f72cbefe487808183994c7381f59c4e3235/workspace/lab4/mydev.c", "visit_date": "2023-04-27T11:20:32.854577" }
stackv2
#include<linux/module.h> #include<linux/init.h> #include<linux/kernel.h> #include<linux/fs.h> #include<linux/uaccess.h> #define MAJOR_NUM 244 #define DEV_NAME "mydev" MODULE_LICENSE("GPL"); #define BUF_LEN 80 static char msg_buf[BUF_LEN]; // File operations static ssize_t seg_open(struct inode *inode, struct file *fp){ printk("seg opened\n"); return 0; } static ssize_t seg_read(struct file* fp, char* buf, size_t count, loff_t* fpos){ // printk("call read\n"); return copy_to_user(buf, msg_buf, count); } static ssize_t seg_write(struct file* fp, const char* buf, size_t count, loff_t* fpos){ // printk("call write\n"); return copy_from_user(msg_buf, buf, count); } static struct file_operations fops = { read: seg_read, write: seg_write, open: seg_open }; static int seg_init(void){ if(register_chrdev(MAJOR_NUM, DEV_NAME, &fops) < 0){ printk("Register failed"); return -1; } printk("driver init major number %d\n", MAJOR_NUM); return 0; } static void seg_exit(void){ printk("driver exit"); } module_init(seg_init); module_exit(seg_exit);
2.46875
2
2024-11-18T20:15:25.863268+00:00
2021-10-05T07:50:47
9dfc257774ae4431f624ad54efedd038d9e57c83
{ "blob_id": "9dfc257774ae4431f624ad54efedd038d9e57c83", "branch_name": "refs/heads/main", "committer_date": "2021-10-05T07:50:47", "content_id": "d988b6bfb74da8ea31afb0978074a38cdd7e463c", "detected_licenses": [ "MIT" ], "directory_id": "449e00535d96b1fe055d6195acf5381c510f3524", "extension": "c", "filename": "Bridges_in_a_graph.c", "fork_events_count": 0, "gha_created_at": "2021-10-05T07:49:56", "gha_event_created_at": "2021-10-05T07:49:56", "gha_language": null, "gha_license_id": "MIT", "github_id": 413722698, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3618, "license": "MIT", "license_type": "permissive", "path": "/Bridges_in_a_graph/Bridges_in_a_graph.c", "provenance": "stackv2-0033.json.gz:167483", "repo_name": "gouravkmar/codeWith-hacktoberfest", "revision_date": "2021-10-05T07:50:47", "revision_id": "04739363eb573431c6b291db3b2fcb1c04ce45b5", "snapshot_id": "11f1df371aa7d58bb90fe20c593f363b21904dba", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gouravkmar/codeWith-hacktoberfest/04739363eb573431c6b291db3b2fcb1c04ce45b5/Bridges_in_a_graph/Bridges_in_a_graph.c", "visit_date": "2023-08-27T19:54:39.745098" }
stackv2
// A C++ program to find bridges in a given undirected graph #include<iostream> #include <list> #define NIL -1 using namespace std; // A class that represents an undirected graph class Graph { int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency lists void bridgeUtil(int v, bool visited[], int disc[], int low[], int parent[]); public: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph void bridge(); // prints all bridges }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); adj[w].push_back(v); // Note: the graph is undirected } // A recursive function that finds and prints bridges using // DFS traversal // u --> The vertex to be visited next // visited[] --> keeps track of visited vertices // disc[] --> Stores discovery times of visited vertices // parent[] --> Stores parent vertices in DFS tree void Graph::bridgeUtil(int u, bool visited[], int disc[], int low[], int parent[]) { // A static variable is used for simplicity, we can // avoid use of static variable by passing a pointer. static int time = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; // v is current adjacent of u // If v is not visited yet, then recur for it if (!visited[v]) { parent[v] = u; bridgeUtil(v, visited, disc, low, parent); // Check if the subtree rooted with v has a // connection to one of the ancestors of u low[u] = min(low[u], low[v]); // If the lowest vertex reachable from subtree // under v is below u in DFS tree, then u-v // is a bridge if (low[v] > disc[u]) cout << u <<" " << v << endl; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = min(low[u], disc[v]); } } // DFS based function to find all bridges. It uses recursive // function bridgeUtil() void Graph::bridge() { // Mark all the vertices as not visited bool *visited = new bool[V]; int *disc = new int[V]; int *low = new int[V]; int *parent = new int[V]; // Initialize parent and visited arrays for (int i = 0; i < V; i++) { parent[i] = NIL; visited[i] = false; } // Call the recursive helper function to find Bridges // in DFS tree rooted with vertex 'i' for (int i = 0; i < V; i++) if (visited[i] == false) bridgeUtil(i, visited, disc, low, parent); } // Driver program to test above function int main() { // Create graphs given in above diagrams cout << "\nBridges in first graph \n"; Graph g1(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); g1.bridge(); cout << "\nBridges in second graph \n"; Graph g2(4); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 3); g2.bridge(); cout << "\nBridges in third graph \n"; Graph g3(7); g3.addEdge(0, 1); g3.addEdge(1, 2); g3.addEdge(2, 0); g3.addEdge(1, 3); g3.addEdge(1, 4); g3.addEdge(1, 6); g3.addEdge(3, 5); g3.addEdge(4, 5); g3.bridge(); return 0; }
3.484375
3
2024-11-18T20:15:30.530847+00:00
2014-11-11T10:32:59
581244d824b7e09fdb3794a48a10b592fc9f9fcb
{ "blob_id": "581244d824b7e09fdb3794a48a10b592fc9f9fcb", "branch_name": "refs/heads/master", "committer_date": "2014-11-11T10:32:59", "content_id": "0d97f801fb2cf6a60dacd0798be304dcbde3d9ce", "detected_licenses": [ "Apache-2.0" ], "directory_id": "15f816069610745ca7fdc8ad1011ba19a7986eb9", "extension": "c", "filename": "alias_del.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": 886, "license": "Apache-2.0", "license_type": "permissive", "path": "/Shell Interpreter/src/alias/alias_del.c", "provenance": "stackv2-0033.json.gz:168126", "repo_name": "kpjlabbe/Epitech", "revision_date": "2014-11-11T10:32:59", "revision_id": "d5caabb635dd228fad9fded2866c43994e75c261", "snapshot_id": "e85e06009c1896193e745a4ce4ec871ae42b8ac3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kpjlabbe/Epitech/d5caabb635dd228fad9fded2866c43994e75c261/Shell Interpreter/src/alias/alias_del.c", "visit_date": "2020-03-29T00:50:42.170757" }
stackv2
/* ** alias_del.c for 42sh in /media/data/all/projects/42sh-v1/src ** ** Made by kevin labbe OB** Login <labbe_k@epitech.net> ** ** Started on Tue May 7 20:11:10 2013 kevin labbe ** Last update Fri May 10 13:56:09 2013 pierre-antoine urvoy */ #include "proto.h" int alias_del_name(t_list *list, char *name) { t_list *tmp; t_alias *elt; if (!list) return (0); tmp = list->next; while (tmp != list) { elt = tmp->data; if (!strcmp(elt->name, name)) return (list_del_elt(tmp, &alias_del_elt)); tmp = tmp->next; } return (0); } void alias_del_elt(t_list *elt) { if (((t_alias *)elt->data)->free) { free(((t_alias *)elt->data)->name); free(((t_alias *)elt->data)->val); } free(((t_alias *)elt->data)->args); free(elt->data); } void alias_free(t_list *list) { list_del(list, &alias_del_elt); free(list); }
2.453125
2
2024-11-18T20:15:30.595636+00:00
2023-04-21T21:47:23
252c1de3156a1c6b7ae7d4dae089c179a79dd0de
{ "blob_id": "252c1de3156a1c6b7ae7d4dae089c179a79dd0de", "branch_name": "refs/heads/release", "committer_date": "2023-04-21T21:47:23", "content_id": "2dd5d72d8a4240bb3e85640a56054a69a0fa82b0", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "22f5ec4d85105dc2cb9b2ae38ad806fa5a138f3a", "extension": "c", "filename": "test_retain_release.c", "fork_events_count": 8, "gha_created_at": "2016-11-10T10:29:50", "gha_event_created_at": "2022-01-12T13:56:19", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 73371608, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6410, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/test-startup/methods/inheritance/test_retain_release.c", "provenance": "stackv2-0033.json.gz:168255", "repo_name": "mulle-objc/mulle-objc-runtime", "revision_date": "2023-04-21T21:47:23", "revision_id": "558d9cb71a331315fff0dfbfb1ea20b90d20652f", "snapshot_id": "0fd0fd4c0a4221f693bf7aa33bc43cf5e091dd12", "src_encoding": "UTF-8", "star_events_count": 133, "url": "https://raw.githubusercontent.com/mulle-objc/mulle-objc-runtime/558d9cb71a331315fff0dfbfb1ea20b90d20652f/test-startup/methods/inheritance/test_retain_release.c", "visit_date": "2023-05-01T08:44:16.846552" }
stackv2
// // test_retain_release.c // mulle-objc-runtime // // Created by Nat! on 14.03.15. // Copyright (c) 2015 Mulle kybernetiK. All rights reserved. // #include <mulle-objc-runtime/mulle-objc-runtime.h> #include <mulle-testallocator/mulle-testallocator.h> #include "test_runtime_ids.h" static intptr_t get_retaincount( void *obj) { struct _mulle_objc_objectheader *header; header = _mulle_objc_object_get_objectheader( obj); return( _mulle_objc_objectheader_get_retaincount_1( header)); } static unsigned int instances; static void *my_calloc( size_t n, size_t size, struct mulle_allocator *allocator) { ++instances; return( mulle_allocator_calloc( &mulle_testallocator, n, size)); } static void my_free( void *p, struct mulle_allocator *allocator) { --instances; mulle_allocator_free( &mulle_testallocator, p); } static void my_nop_free( void *p) { --instances; } struct mulle_allocator my_allocator = { my_calloc, NULL, my_free, }; static void *A_alloc( struct _mulle_objc_infraclass *self, mulle_objc_methodid_t _cmd) { return( _mulle_objc_infraclass_allocator_alloc_instance_extra( self, 0, &my_allocator)); } struct _gnu_mulle_objc_methodlist { unsigned int n_methods; // must be #0 and same as struct _mulle_objc_ivarlist void *owner; struct _mulle_objc_method methods[]; }; struct _gnu_mulle_objc_methodlist A_infra_methodlist = { 2, NULL, { { { MULLE_OBJC_RELEASE_METHODID, "v@:", "release", 0 }, (void *) mulle_objc_object_release }, { { MULLE_OBJC_RETAIN_METHODID, "@@:", "retain", 0 }, (void *) mulle_objc_object_retain }, } }; struct _gnu_mulle_objc_methodlist A_meta_methodlist = { 1, NULL, { { { MULLE_OBJC_ALLOC_METHODID, "v@:", "alloc", 0 }, (void *) A_alloc } } }; static void test_simple_retain_release( struct _mulle_objc_infraclass *A_infra) { struct _mulle_objc_object *a; struct _mulle_objc_object *b; assert( instances == 0); a = _mulle_objc_infraclass_allocator_alloc_instance_extra( A_infra, 0, &my_allocator); assert( instances == 1); assert( mulle_objc_object_get_retaincount( a) == 1); b = mulle_objc_object_retain( a); assert( a == b); assert( mulle_objc_object_get_retaincount( a) == 2); mulle_objc_object_release( a); assert( mulle_objc_object_get_retaincount( a) == 1); __mulle_objc_instance_free( a, &my_allocator); assert( instances == 0); } static void test_permanent_retain_release( struct _mulle_objc_infraclass *A_infra) { struct _mulle_objc_object *a; long retain_count; a = _mulle_objc_infraclass_allocator_alloc_instance_extra( A_infra, 0, &my_allocator); _mulle_objc_object_constantify_noatomic( a); retain_count = mulle_objc_object_get_retaincount( a); mulle_objc_object_retain( a); assert( mulle_objc_object_get_retaincount( a) == retain_count); mulle_objc_object_release( a); assert( mulle_objc_object_get_retaincount( a) == retain_count); mulle_objc_object_release( a); assert( mulle_objc_object_get_retaincount( a) == retain_count); assert( instances == 1); __mulle_objc_instance_free( a, &my_allocator); assert( instances == 0); } # pragma mark - dealloc static unsigned int dealloced; static unsigned int finalized; static void A_finalize( void *self, mulle_objc_classid_t sel) { assert( get_retaincount( self) < -1); ++finalized; } static void A_dealloc( void *self, mulle_objc_classid_t sel) { assert( get_retaincount( self) == -1); ++dealloced; __mulle_objc_instance_free( self, &my_allocator); } static struct _gnu_mulle_objc_methodlist finalize_dealloc_methodlist = { 2, NULL, { { { MULLE_OBJC_DEALLOC_METHODID, "@:", "dealloc", 0 }, (void *) A_dealloc }, { { MULLE_OBJC_FINALIZE_METHODID, "@:", "finalize", 0 }, (void *) A_finalize } } }; static void test_dealloc_finalize( struct _mulle_objc_infraclass *A_infra) { struct _mulle_objc_object *a; assert( dealloced == 0); mulle_objc_infraclass_add_methodlist_nofail( A_infra, (void *) &finalize_dealloc_methodlist); a = _mulle_objc_infraclass_allocator_alloc_instance_extra( A_infra, 0, &my_allocator); mulle_objc_object_release( a); assert( finalized == 1); assert( dealloced == 1); dealloced = 0; finalized = 0; } static void test_perform_finalize( struct _mulle_objc_infraclass *A_infra) { struct _mulle_objc_object *a; assert( dealloced == 0); a = _mulle_objc_infraclass_allocator_alloc_instance_extra( A_infra, 0, &my_allocator); assert( get_retaincount( a) == 0); mulle_objc_object_perform_finalize( a); assert( get_retaincount( a) < -1); assert( finalized == 1); assert( dealloced == 0); mulle_objc_object_release( a); assert( dealloced == 1); assert( finalized == 1); dealloced = 0; finalized = 0; } void test_retain_release( void) { struct _mulle_objc_classpair *pair; struct _mulle_objc_infraclass *A_infra; struct _mulle_objc_metaclass *A_meta; struct _mulle_objc_universe *universe; universe = mulle_objc_global_register_universe( MULLE_OBJC_DEFAULTUNIVERSEID, NULL); pair = mulle_objc_universe_new_classpair( universe, A_classid, "A", 0, 0, NULL); assert( pair); A_infra = _mulle_objc_classpair_get_infraclass( pair); A_meta = _mulle_objc_classpair_get_metaclass( pair); mulle_objc_infraclass_add_methodlist_nofail( A_infra, (void *) &A_infra_methodlist); mulle_objc_metaclass_add_methodlist_nofail( A_meta, (void *) &A_meta_methodlist); mulle_objc_infraclass_add_ivarlist_nofail( A_infra, NULL); mulle_objc_infraclass_add_propertylist_nofail( A_infra, NULL); mulle_objc_universe_add_infraclass_nofail( universe, A_infra); test_simple_retain_release( A_infra); test_permanent_retain_release( A_infra); test_dealloc_finalize( A_infra); test_perform_finalize( A_infra); }
2.015625
2
2024-11-18T20:15:30.743394+00:00
2013-03-26T11:02:45
82d839d73e0d44deab6a8988e77d8a6b3d04ad81
{ "blob_id": "82d839d73e0d44deab6a8988e77d8a6b3d04ad81", "branch_name": "refs/heads/master", "committer_date": "2013-03-26T11:02:45", "content_id": "a4b4cca4f6d5e443d8ea9e8b21aaa64d1095314f", "detected_licenses": [ "NCSA" ], "directory_id": "b15e349f68725f536849280a3ab8e3ffb1231cfc", "extension": "c", "filename": "single_do_loop_ll_max_iterations.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 9538093, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 277, "license": "NCSA", "license_type": "permissive", "path": "/tools/polly/test/CodeGen/single_do_loop_ll_max_iterations.c", "provenance": "stackv2-0033.json.gz:168512", "repo_name": "crystax/android-toolchain-llvm-3-1", "revision_date": "2013-03-26T11:02:45", "revision_id": "c4c12e4902b9c0eff170935764b2f85fe6e620ac", "snapshot_id": "100e8a3fc1f5fc2ac08f90a14c1d9c10a0852e5f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/crystax/android-toolchain-llvm-3-1/c4c12e4902b9c0eff170935764b2f85fe6e620ac/tools/polly/test/CodeGen/single_do_loop_ll_max_iterations.c", "visit_date": "2016-09-06T04:55:00.784946" }
stackv2
#define N 20 #include "limits.h" long long A[N]; int main () { long long i; A[0] = 0; __sync_synchronize(); i = 0; do { A[0] = i; ++i; } while (i < LLONG_MAX); __sync_synchronize(); if (A[0] == LLONG_MAX - 1) return 0; else return 1; }
2.21875
2
2024-11-18T20:15:30.836187+00:00
2021-07-29T02:04:42
aad0a840e02888b5d4f9322894c9d607dd6b3d43
{ "blob_id": "aad0a840e02888b5d4f9322894c9d607dd6b3d43", "branch_name": "refs/heads/main", "committer_date": "2021-07-29T02:04:42", "content_id": "963e80df60972f80b23a6cae92a32db517f6c14f", "detected_licenses": [ "MIT" ], "directory_id": "be324d5e1703f31039dbaa9380a93a9605cebb41", "extension": "h", "filename": "byteiter.h", "fork_events_count": 0, "gha_created_at": "2021-08-10T03:08:29", "gha_event_created_at": "2021-08-10T03:08:29", "gha_language": null, "gha_license_id": null, "github_id": 394509459, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2707, "license": "MIT", "license_type": "permissive", "path": "/include/byteiter.h", "provenance": "stackv2-0033.json.gz:168640", "repo_name": "Muyv/adif", "revision_date": "2021-07-29T02:04:42", "revision_id": "37361995c1d7f7a18510cfa2d1292b383d9267e0", "snapshot_id": "212139fdffe235bdf47740fd581833994c0500d9", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Muyv/adif/37361995c1d7f7a18510cfa2d1292b383d9267e0/include/byteiter.h", "visit_date": "2023-07-04T15:13:06.568844" }
stackv2
/* * Copyright (c) 2003-2021 Ke Hengzhong <kehengzhong@hotmail.com> * All rights reserved. See MIT LICENSE for redistribution. */ #ifndef _BYTE_ITER_H_ #define _BYTE_ITER_H_ typedef struct byte_iter_ { uint8 * text; int textlen; int cur; } ByteIter; #define iter_cur(iter) ((iter)->text + (iter)->cur) #define iter_end(iter) ((iter)->text + (iter)->textlen) #define iter_bgn(iter) ((iter)->text) #define iter_len(iter) ((iter)->textlen) #define iter_rest(iter) (((iter)->textlen>(iter)->cur) ? (iter)->textlen-(iter)->cur : 0) #define iter_offset(iter) ((iter)->cur) #define iter_istail(iter) ((iter)->cur >= (iter)->textlen) #define iter_forward(iter, n) (((n)<iter_rest(iter))?((iter)->cur+=(n)):((iter)->cur=(iter)->textlen)) #define iter_back(iter, n) (((n)<iter_offset(iter))?((iter)->cur-=(n)):((iter)->cur=0)) #define iter_seekto(iter, n) (((n)<(iter)->textlen)?((iter)->cur=(n)):((iter)->cur=(iter)->textlen)) #ifdef __cplusplus extern "C" { #endif /* initialize the ByteIter instance */ int iter_init (ByteIter * iter); /* allocate an ByteIter instance */ ByteIter * iter_alloc (); /* release the memory of an ByteIter instance */ int iter_free (ByteIter * iter); /* set the ASF document text for the ByteIter */ int iter_set_buffer (ByteIter * iter, uint8 * text, int len); int iter_get_uint64BE (ByteIter * iter, uint64 * pval); int iter_get_uint64LE (ByteIter * iter, uint64 * pval); int iter_get_uint32BE (ByteIter * iter, uint32 * pval); int iter_get_uint32LE (ByteIter * iter, uint32 * pval); int iter_get_uint16BE (ByteIter * iter, uint16 * pval); int iter_get_uint16LE (ByteIter * iter, uint16 * pval); int iter_get_uint8 (ByteIter * iter, uint8 * pval); int iter_get_bytes (ByteIter * iter, uint8 * pbuf, int buflen); int iter_set_bytes (ByteIter * iter, uint8 * pbuf, int len); int iter_fmtstr (ByteIter * iter, const char * fmt, ...); int iter_set_uint8 (ByteIter * iter, uint8 byte); int iter_set_uint16BE (ByteIter * iter, uint16 val); int iter_set_uint16LE (ByteIter * iter, uint16 val); int iter_set_uint32BE (ByteIter * iter, uint32 val); int iter_set_uint32LE (ByteIter * iter, uint32 val); int iter_set_uint64BE (ByteIter * iter, uint64 val); int iter_set_uint64LE (ByteIter * iter, uint64 val); /* skip to next, once any char of the given char array is encountered, stop skipping*/ int iter_skipTo (ByteIter * iter, uint8 * chs, int charnum); /* skip to next, once any char of the given char array is not encountered, stop skipping*/ int iter_skipOver (ByteIter * iter, uint8 * chs, int charnum); int iter_skipTo_bytes (ByteIter * iter, char * pat, int patlen); #ifdef __cplusplus } #endif #endif
2.5
2
2024-11-18T20:15:30.972321+00:00
2013-01-19T11:18:59
1bff9223ede1121d2ef860004a6d1f98c2ce8b2e
{ "blob_id": "1bff9223ede1121d2ef860004a6d1f98c2ce8b2e", "branch_name": "refs/heads/master", "committer_date": "2013-01-19T11:18:59", "content_id": "7c935e35c5eb30a2828ac500862c5e25df36da5b", "detected_licenses": [ "MIT" ], "directory_id": "a8e7cb4cc0dbbaf6f3cb51b7d9c3776135232495", "extension": "c", "filename": "MQOModelReadScene.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 6850223, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1766, "license": "MIT", "license_type": "permissive", "path": "/CC3MQO/CC3MQO/MQOModelReadScene.c", "provenance": "stackv2-0033.json.gz:168896", "repo_name": "aship/CC3MQO", "revision_date": "2013-01-19T11:18:59", "revision_id": "7636a7bb2851170c7c17685678c70f766894a87f", "snapshot_id": "de363c45a3204a48689dded47975cd73145ae961", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/aship/CC3MQO/7636a7bb2851170c7c17685678c70f766894a87f/CC3MQO/CC3MQO/MQOModelReadScene.c", "visit_date": "2021-01-15T13:44:26.207617" }
stackv2
// // MQOModelReadScene.m // CC3DemoMashUp // // Created by Yasuo Ashina on 12/07/17. // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #include "MQOModel.h" #if 1 void mqoReadScene(FILE *fp, MQOModel *model, double scale) { char buf[SIZE_STR]; glPOINT3f pos; while (!feof(fp)) { fgets(buf, SIZE_STR, fp); // 行読み込み // pos if (strstr(buf,"pos ")) { sscanf(buf," pos %f %f %f", &pos.x, &pos.y, &pos.z); // model->camera_pos.x = scale * pos.x; // model->camera_pos.y = scale * pos.y; // model->camera_pos.z = scale * pos.z; } // lookat else if (strstr(buf,"lookat ")) { sscanf(buf," lookat %f %f %f", &pos.x, &pos.y, &pos.z); // model->camera_lookat.x = scale * pos.x; // model->camera_lookat.y = scale * pos.y; // model->camera_lookat.z = scale * pos.z; } // head else if (strstr(buf,"head ")) { // sscanf(buf," head %f", &model->camera_head); } // pich else if (strstr(buf,"pich ")) { // sscanf(buf," pich %f", &model->camera_pich); } // head else if (strstr(buf,"head ")) { // sscanf(buf," head %f", &model->camera_head); } // ortho else if (strstr(buf,"ortho ")) { // sscanf(buf," ortho %d", &model->ortho); } // zoom2 else if (strstr(buf,"zoom2 ")) { // sscanf(buf," zoom2 %f", &model->camera_zoom2); } // amb else if (strstr(buf,"amb ")) { // sscanf(buf," amb %f %f %f", &model->amb[0], &model->amb[1], &model->amb[2]); } else if (strstr(buf,"}")) { break; } } } #endif
2.015625
2
2024-11-18T20:15:31.197517+00:00
2017-04-25T01:06:21
4eab0ee407afb481d2d14b99500f18536d94e4fa
{ "blob_id": "4eab0ee407afb481d2d14b99500f18536d94e4fa", "branch_name": "refs/heads/master", "committer_date": "2017-04-25T01:06:21", "content_id": "31d832d837c5b877df37519899cb679032a0498e", "detected_licenses": [ "MIT" ], "directory_id": "cdbd912188194a25a4568bbe3d141871ca9038b5", "extension": "c", "filename": "fun_w_strings.c", "fork_events_count": 0, "gha_created_at": "2017-01-22T21:32:59", "gha_event_created_at": "2017-01-22T21:32:59", "gha_language": null, "gha_license_id": null, "github_id": 79747229, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 772, "license": "MIT", "license_type": "permissive", "path": "/Exam/fun_w_strings.c", "provenance": "stackv2-0033.json.gz:169155", "repo_name": "thuctran289/ExercisesInC", "revision_date": "2017-04-25T01:06:21", "revision_id": "b06fd73da8d965888adc6beb8e25b78aa76768e2", "snapshot_id": "1952376786653c47f89e2dec12a74b71189916ee", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/thuctran289/ExercisesInC/b06fd73da8d965888adc6beb8e25b78aa76768e2/Exam/fun_w_strings.c", "visit_date": "2021-01-11T17:19:44.987950" }
stackv2
//For the following code, print the output, and approximate locations in memory for each //variable that begins with an s! //Most of this should be doable using HFC2. #include <stdio.h> #include <string.h> #include <stdlib.h> char * s1 = "hello world1"; char s2[] = "hello world2"; char * foo(char str[]){ char * data = malloc(sizeof(str)); memcpy(data, str, sizeof(str)); return data; } char * bar(){ char * data = "hello"; return data; } int main(int argc, char ** argv) { char * s3 = "Oh hello world3"; char s4[] = "Oh hello world4"; printf("%s\n",s2); printf("%d\n", sizeof(s3)); printf("%d\n", sizeof(s4)); char * s5 = foo(s3); char * s6 = foo(s4); printf("%s\n", s5); printf("%s\n", s6); char * s7 = bar(); printf("%s\n", s7); return 0; }
3.3125
3
2024-11-18T20:15:31.310832+00:00
2023-08-18T19:48:33
33a257a68446f488e10bcaed2abac7aa0550536b
{ "blob_id": "33a257a68446f488e10bcaed2abac7aa0550536b", "branch_name": "refs/heads/main", "committer_date": "2023-08-18T19:48:33", "content_id": "3b5924b09836b47d30a9ba73cdbdb93b43c8557d", "detected_licenses": [ "MIT" ], "directory_id": "604371b2d89212dae30c0213b734817f7e84746e", "extension": "c", "filename": "pickle_ast_node_id.c", "fork_events_count": 39, "gha_created_at": "2022-10-13T13:28:45", "gha_event_created_at": "2023-09-14T06:57:18", "gha_language": "C", "gha_license_id": "MIT", "github_id": 550879823, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1821, "license": "MIT", "license_type": "permissive", "path": "/c/src/pickle_ast_node_id.c", "provenance": "stackv2-0033.json.gz:169283", "repo_name": "cucumber/gherkin", "revision_date": "2023-08-18T19:48:33", "revision_id": "08b209ba49c0faac37e2401d34abb6cd0306b237", "snapshot_id": "d0b72e278db77601acab80ab73667c3c4d590ee1", "src_encoding": "UTF-8", "star_events_count": 81, "url": "https://raw.githubusercontent.com/cucumber/gherkin/08b209ba49c0faac37e2401d34abb6cd0306b237/c/src/pickle_ast_node_id.c", "visit_date": "2023-08-21T16:36:58.689615" }
stackv2
#include "pickle_ast_node_id.h" #include "string_utilities.h" #include <stdlib.h> const PickleAstNodeId* PickleAstNodeId_new(const wchar_t* id) { PickleAstNodeId* ast_node_id = (PickleAstNodeId*)malloc(sizeof(PickleAstNodeId)); ast_node_id->id = 0; if (id) { ast_node_id->id = StringUtilities_copy_string(id); } return ast_node_id; } const PickleAstNodeIds* PickleAstNodeIds_new_single(const wchar_t* id) { const PickleAstNodeId* ast_node_id = PickleAstNodeId_new(id); PickleAstNodeIds* ast_node_ids = (PickleAstNodeIds*)malloc(sizeof(PickleAstNodeIds)); ast_node_ids->ast_node_id_count = 1; ast_node_ids->ast_node_ids = ast_node_id; return ast_node_ids; } const PickleAstNodeIds* PickleAstNodeIds_new_double(const wchar_t* id_1, const wchar_t* id_2) { PickleAstNodeId* ast_node_id_array = (PickleAstNodeId*)malloc(2 * sizeof(PickleAstNodeId)); ast_node_id_array[0].id = 0; ast_node_id_array[1].id = 0; if (id_1) { ast_node_id_array[0].id = StringUtilities_copy_string(id_1); } if (id_2) { ast_node_id_array[1].id = StringUtilities_copy_string(id_2); } PickleAstNodeIds* ast_node_ids = (PickleAstNodeIds*)malloc(sizeof(PickleAstNodeIds)); ast_node_ids->ast_node_id_count = 2; ast_node_ids->ast_node_ids = ast_node_id_array; return ast_node_ids; } void PickleAstNodeId_delete(const PickleAstNodeId* ast_node_id) { if (!ast_node_id) { return; } if (ast_node_id->id) { free((void*) ast_node_id->id); } free((void*) ast_node_id); } void PickleAstNodeIds_delete(const PickleAstNodeIds* ast_node_ids) { if (!ast_node_ids) { return; } if (ast_node_ids->ast_node_ids) { free((void*) ast_node_ids->ast_node_ids); } free((void*) ast_node_ids); }
2.5
2
2024-11-18T20:15:31.471781+00:00
2023-03-27T00:00:00
1b2dd275221210a78bdf4a3bf17cc8a01fa908ab
{ "blob_id": "1b2dd275221210a78bdf4a3bf17cc8a01fa908ab", "branch_name": "refs/heads/master", "committer_date": "2023-03-27T00:00:00", "content_id": "90b1c1a6cfe9e1f61c15b13e2e11b96f3aaa52ff", "detected_licenses": [ "TCL" ], "directory_id": "1577e1cf4e89584a125cffb855ca50a9654c6d55", "extension": "c", "filename": "tclPipe.c", "fork_events_count": 24, "gha_created_at": "2019-04-10T14:06:23", "gha_event_created_at": "2022-12-27T14:54:09", "gha_language": null, "gha_license_id": null, "github_id": 180595052, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 31383, "license": "TCL", "license_type": "permissive", "path": "/tcl/tcl/tcl/generic/tclPipe.c", "provenance": "stackv2-0033.json.gz:169540", "repo_name": "apple-open-source/macos", "revision_date": "2023-03-27T00:00:00", "revision_id": "2d2b15f13487673de33297e49f00ef94af743a9a", "snapshot_id": "a4188b5c2ef113d90281d03cd1b14e5ee52ebffb", "src_encoding": "UTF-8", "star_events_count": 124, "url": "https://raw.githubusercontent.com/apple-open-source/macos/2d2b15f13487673de33297e49f00ef94af743a9a/tcl/tcl/tcl/generic/tclPipe.c", "visit_date": "2023-08-01T11:03:26.870408" }
stackv2
/* * tclPipe.c -- * * This file contains the generic portion of the command channel driver * as well as various utility routines used in managing subprocesses. * * Copyright (c) 1997 by Sun Microsystems, Inc. * * See the file "license.terms" for information on usage and redistribution of * this file, and for a DISCLAIMER OF ALL WARRANTIES. * * RCS: @(#) $Id: tclPipe.c,v 1.19.4.1 2009/07/24 16:51:28 andreas_kupries Exp $ */ #include "tclInt.h" /* * A linked list of the following structures is used to keep track of child * processes that have been detached but haven't exited yet, so we can make * sure that they're properly "reaped" (officially waited for) and don't lie * around as zombies cluttering the system. */ typedef struct Detached { Tcl_Pid pid; /* Id of process that's been detached but * isn't known to have exited. */ struct Detached *nextPtr; /* Next in list of all detached processes. */ } Detached; static Detached *detList = NULL;/* List of all detached proceses. */ TCL_DECLARE_MUTEX(pipeMutex) /* Guard access to detList. */ /* * Declarations for local functions defined in this file: */ static TclFile FileForRedirect(Tcl_Interp *interp, CONST char *spec, int atOk, CONST char *arg, CONST char *nextArg, int flags, int *skipPtr, int *closePtr, int *releasePtr); /* *---------------------------------------------------------------------- * * FileForRedirect -- * * This function does much of the work of parsing redirection operators. * It handles "@" if specified and allowed, and a file name, and opens * the file if necessary. * * Results: * The return value is the descriptor number for the file. If an error * occurs then NULL is returned and an error message is left in the * interp's result. Several arguments are side-effected; see the argument * list below for details. * * Side effects: * None. * *---------------------------------------------------------------------- */ static TclFile FileForRedirect( Tcl_Interp *interp, /* Intepreter to use for error reporting. */ CONST char *spec, /* Points to character just after redirection * character. */ int atOK, /* Non-zero means that '@' notation can be * used to specify a channel, zero means that * it isn't. */ CONST char *arg, /* Pointer to entire argument containing spec: * used for error reporting. */ CONST char *nextArg, /* Next argument in argc/argv array, if needed * for file name or channel name. May be * NULL. */ int flags, /* Flags to use for opening file or to specify * mode for channel. */ int *skipPtr, /* Filled with 1 if redirection target was in * spec, 2 if it was in nextArg. */ int *closePtr, /* Filled with one if the caller should close * the file when done with it, zero * otherwise. */ int *releasePtr) { int writing = (flags & O_WRONLY); Tcl_Channel chan; TclFile file; *skipPtr = 1; if ((atOK != 0) && (*spec == '@')) { spec++; if (*spec == '\0') { spec = nextArg; if (spec == NULL) { goto badLastArg; } *skipPtr = 2; } chan = Tcl_GetChannel(interp, spec, NULL); if (chan == (Tcl_Channel) NULL) { return NULL; } file = TclpMakeFile(chan, writing ? TCL_WRITABLE : TCL_READABLE); if (file == NULL) { Tcl_Obj* msg; Tcl_GetChannelError(chan, &msg); if (msg) { Tcl_SetObjResult (interp, msg); } else { Tcl_AppendResult(interp, "channel \"", Tcl_GetChannelName(chan), "\" wasn't opened for ", ((writing) ? "writing" : "reading"), NULL); } return NULL; } *releasePtr = 1; if (writing) { /* * Be sure to flush output to the file, so that anything written * by the child appears after stuff we've already written. */ Tcl_Flush(chan); } } else { CONST char *name; Tcl_DString nameString; if (*spec == '\0') { spec = nextArg; if (spec == NULL) { goto badLastArg; } *skipPtr = 2; } name = Tcl_TranslateFileName(interp, spec, &nameString); if (name == NULL) { return NULL; } file = TclpOpenFile(name, flags); Tcl_DStringFree(&nameString); if (file == NULL) { Tcl_AppendResult(interp, "couldn't ", ((writing) ? "write" : "read"), " file \"", spec, "\": ", Tcl_PosixError(interp), NULL); return NULL; } *closePtr = 1; } return file; badLastArg: Tcl_AppendResult(interp, "can't specify \"", arg, "\" as last word in command", NULL); return NULL; } /* *---------------------------------------------------------------------- * * Tcl_DetachPids -- * * This function is called to indicate that one or more child processes * have been placed in background and will never be waited for; they * should eventually be reaped by Tcl_ReapDetachedProcs. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ void Tcl_DetachPids( int numPids, /* Number of pids to detach: gives size of * array pointed to by pidPtr. */ Tcl_Pid *pidPtr) /* Array of pids to detach. */ { register Detached *detPtr; int i; Tcl_MutexLock(&pipeMutex); for (i = 0; i < numPids; i++) { detPtr = (Detached *) ckalloc(sizeof(Detached)); detPtr->pid = pidPtr[i]; detPtr->nextPtr = detList; detList = detPtr; } Tcl_MutexUnlock(&pipeMutex); } /* *---------------------------------------------------------------------- * * Tcl_ReapDetachedProcs -- * * This function checks to see if any detached processes have exited and, * if so, it "reaps" them by officially waiting on them. It should be * called "occasionally" to make sure that all detached processes are * eventually reaped. * * Results: * None. * * Side effects: * Processes are waited on, so that they can be reaped by the system. * *---------------------------------------------------------------------- */ void Tcl_ReapDetachedProcs(void) { register Detached *detPtr; Detached *nextPtr, *prevPtr; int status; Tcl_Pid pid; Tcl_MutexLock(&pipeMutex); for (detPtr = detList, prevPtr = NULL; detPtr != NULL; ) { pid = Tcl_WaitPid(detPtr->pid, &status, WNOHANG); if ((pid == 0) || ((pid == (Tcl_Pid) -1) && (errno != ECHILD))) { prevPtr = detPtr; detPtr = detPtr->nextPtr; continue; } nextPtr = detPtr->nextPtr; if (prevPtr == NULL) { detList = detPtr->nextPtr; } else { prevPtr->nextPtr = detPtr->nextPtr; } ckfree((char *) detPtr); detPtr = nextPtr; } Tcl_MutexUnlock(&pipeMutex); } /* *---------------------------------------------------------------------- * * TclCleanupChildren -- * * This is a utility function used to wait for child processes to exit, * record information about abnormal exits, and then collect any stderr * output generated by them. * * Results: * The return value is a standard Tcl result. If anything at weird * happened with the child processes, TCL_ERROR is returned and a message * is left in the interp's result. * * Side effects: * If the last character of the interp's result is a newline, then it is * removed unless keepNewline is non-zero. File errorId gets closed, and * pidPtr is freed back to the storage allocator. * *---------------------------------------------------------------------- */ int TclCleanupChildren( Tcl_Interp *interp, /* Used for error messages. */ int numPids, /* Number of entries in pidPtr array. */ Tcl_Pid *pidPtr, /* Array of process ids of children. */ Tcl_Channel errorChan) /* Channel for file containing stderr output * from pipeline. NULL means there isn't any * stderr output. */ { int result = TCL_OK; int i, abnormalExit, anyErrorInfo; Tcl_Pid pid; WAIT_STATUS_TYPE waitStatus; CONST char *msg; unsigned long resolvedPid; abnormalExit = 0; for (i = 0; i < numPids; i++) { /* * We need to get the resolved pid before we wait on it as the windows * implimentation of Tcl_WaitPid deletes the information such that any * following calls to TclpGetPid fail. */ resolvedPid = TclpGetPid(pidPtr[i]); pid = Tcl_WaitPid(pidPtr[i], (int *) &waitStatus, 0); if (pid == (Tcl_Pid) -1) { result = TCL_ERROR; if (interp != NULL) { msg = Tcl_PosixError(interp); if (errno == ECHILD) { /* * This changeup in message suggested by Mark Diekhans to * remind people that ECHILD errors can occur on some * systems if SIGCHLD isn't in its default state. */ msg = "child process lost (is SIGCHLD ignored or trapped?)"; } Tcl_AppendResult(interp, "error waiting for process to exit: ", msg, NULL); } continue; } /* * Create error messages for unusual process exits. An extra newline * gets appended to each error message, but it gets removed below (in * the same fashion that an extra newline in the command's output is * removed). */ if (!WIFEXITED(waitStatus) || (WEXITSTATUS(waitStatus) != 0)) { char msg1[TCL_INTEGER_SPACE], msg2[TCL_INTEGER_SPACE]; result = TCL_ERROR; sprintf(msg1, "%lu", resolvedPid); if (WIFEXITED(waitStatus)) { if (interp != (Tcl_Interp *) NULL) { sprintf(msg2, "%lu", (unsigned long) WEXITSTATUS(waitStatus)); Tcl_SetErrorCode(interp, "CHILDSTATUS", msg1, msg2, NULL); } abnormalExit = 1; } else if (interp != NULL) { CONST char *p; if (WIFSIGNALED(waitStatus)) { p = Tcl_SignalMsg((int) (WTERMSIG(waitStatus))); Tcl_SetErrorCode(interp, "CHILDKILLED", msg1, Tcl_SignalId((int) (WTERMSIG(waitStatus))), p, NULL); Tcl_AppendResult(interp, "child killed: ", p, "\n", NULL); } else if (WIFSTOPPED(waitStatus)) { p = Tcl_SignalMsg((int) (WSTOPSIG(waitStatus))); Tcl_SetErrorCode(interp, "CHILDSUSP", msg1, Tcl_SignalId((int) (WSTOPSIG(waitStatus))), p, NULL); Tcl_AppendResult(interp, "child suspended: ", p, "\n", NULL); } else { Tcl_AppendResult(interp, "child wait status didn't make sense\n", NULL); } } } } /* * Read the standard error file. If there's anything there, then return an * error and add the file's contents to the result string. */ anyErrorInfo = 0; if (errorChan != NULL) { /* * Make sure we start at the beginning of the file. */ if (interp != NULL) { int count; Tcl_Obj *objPtr; Tcl_Seek(errorChan, (Tcl_WideInt)0, SEEK_SET); objPtr = Tcl_NewObj(); count = Tcl_ReadChars(errorChan, objPtr, -1, 0); if (count < 0) { result = TCL_ERROR; Tcl_DecrRefCount(objPtr); Tcl_ResetResult(interp); Tcl_AppendResult(interp, "error reading stderr output file: ", Tcl_PosixError(interp), NULL); } else if (count > 0) { anyErrorInfo = 1; Tcl_SetObjResult(interp, objPtr); result = TCL_ERROR; } else { Tcl_DecrRefCount(objPtr); } } Tcl_Close(NULL, errorChan); } /* * If a child exited abnormally but didn't output any error information at * all, generate an error message here. */ if ((abnormalExit != 0) && (anyErrorInfo == 0) && (interp != NULL)) { Tcl_AppendResult(interp, "child process exited abnormally", NULL); } return result; } /* *---------------------------------------------------------------------- * * TclCreatePipeline -- * * Given an argc/argv array, instantiate a pipeline of processes as * described by the argv. * * This function is unofficially exported for use by BLT. * * Results: * The return value is a count of the number of new processes created, or * -1 if an error occurred while creating the pipeline. *pidArrayPtr is * filled in with the address of a dynamically allocated array giving the * ids of all of the processes. It is up to the caller to free this array * when it isn't needed anymore. If inPipePtr is non-NULL, *inPipePtr is * filled in with the file id for the input pipe for the pipeline (if * any): the caller must eventually close this file. If outPipePtr isn't * NULL, then *outPipePtr is filled in with the file id for the output * pipe from the pipeline: the caller must close this file. If errFilePtr * isn't NULL, then *errFilePtr is filled with a file id that may be used * to read error output after the pipeline completes. * * Side effects: * Processes and pipes are created. * *---------------------------------------------------------------------- */ int TclCreatePipeline( Tcl_Interp *interp, /* Interpreter to use for error reporting. */ int argc, /* Number of entries in argv. */ CONST char **argv, /* Array of strings describing commands in * pipeline plus I/O redirection with <, <<, * >, etc. Argv[argc] must be NULL. */ Tcl_Pid **pidArrayPtr, /* Word at *pidArrayPtr gets filled in with * address of array of pids for processes in * pipeline (first pid is first process in * pipeline). */ TclFile *inPipePtr, /* If non-NULL, input to the pipeline comes * from a pipe (unless overridden by * redirection in the command). The file id * with which to write to this pipe is stored * at *inPipePtr. NULL means command specified * its own input source. */ TclFile *outPipePtr, /* If non-NULL, output to the pipeline goes to * a pipe, unless overriden by redirection in * the command. The file id with which to read * frome this pipe is stored at *outPipePtr. * NULL means command specified its own output * sink. */ TclFile *errFilePtr) /* If non-NULL, all stderr output from the * pipeline will go to a temporary file * created here, and a descriptor to read the * file will be left at *errFilePtr. The file * will be removed already, so closing this * descriptor will be the end of the file. If * this is NULL, then all stderr output goes * to our stderr. If the pipeline specifies * redirection then the file will still be * created but it will never get any data. */ { Tcl_Pid *pidPtr = NULL; /* Points to malloc-ed array holding all the * pids of child processes. */ int numPids; /* Actual number of processes that exist at * *pidPtr right now. */ int cmdCount; /* Count of number of distinct commands found * in argc/argv. */ CONST char *inputLiteral = NULL; /* If non-null, then this points to a string * containing input data (specified via <<) to * be piped to the first process in the * pipeline. */ TclFile inputFile = NULL; /* If != NULL, gives file to use as input for * first process in pipeline (specified via < * or <@). */ int inputClose = 0; /* If non-zero, then inputFile should be * closed when cleaning up. */ int inputRelease = 0; TclFile outputFile = NULL; /* Writable file for output from last command * in pipeline (could be file or pipe). NULL * means use stdout. */ int outputClose = 0; /* If non-zero, then outputFile should be * closed when cleaning up. */ int outputRelease = 0; TclFile errorFile = NULL; /* Writable file for error output from all * commands in pipeline. NULL means use * stderr. */ int errorClose = 0; /* If non-zero, then errorFile should be * closed when cleaning up. */ int errorRelease = 0; CONST char *p; CONST char *nextArg; int skip, lastBar, lastArg, i, j, atOK, flags, needCmd, errorToOutput = 0; Tcl_DString execBuffer; TclFile pipeIn; TclFile curInFile, curOutFile, curErrFile; Tcl_Channel channel; if (inPipePtr != NULL) { *inPipePtr = NULL; } if (outPipePtr != NULL) { *outPipePtr = NULL; } if (errFilePtr != NULL) { *errFilePtr = NULL; } Tcl_DStringInit(&execBuffer); pipeIn = NULL; curInFile = NULL; curOutFile = NULL; numPids = 0; /* * First, scan through all the arguments to figure out the structure of * the pipeline. Process all of the input and output redirection arguments * and remove them from the argument list in the pipeline. Count the * number of distinct processes (it's the number of "|" arguments plus * one) but don't remove the "|" arguments because they'll be used in the * second pass to seperate the individual child processes. Cannot start * the child processes in this pass because the redirection symbols may * appear anywhere in the command line - e.g., the '<' that specifies the * input to the entire pipe may appear at the very end of the argument * list. */ lastBar = -1; cmdCount = 1; needCmd = 1; for (i = 0; i < argc; i++) { errorToOutput = 0; skip = 0; p = argv[i]; switch (*p++) { case '|': if (*p == '&') { p++; } if (*p == '\0') { if ((i == (lastBar + 1)) || (i == (argc - 1))) { Tcl_SetResult(interp, "illegal use of | or |& in command", TCL_STATIC); goto error; } } lastBar = i; cmdCount++; needCmd = 1; break; case '<': if (inputClose != 0) { inputClose = 0; TclpCloseFile(inputFile); } if (inputRelease != 0) { inputRelease = 0; TclpReleaseFile(inputFile); } if (*p == '<') { inputFile = NULL; inputLiteral = p + 1; skip = 1; if (*inputLiteral == '\0') { inputLiteral = ((i + 1) == argc) ? NULL : argv[i + 1]; if (inputLiteral == NULL) { Tcl_AppendResult(interp, "can't specify \"", argv[i], "\" as last word in command", NULL); goto error; } skip = 2; } } else { nextArg = ((i + 1) == argc) ? NULL : argv[i + 1]; inputLiteral = NULL; inputFile = FileForRedirect(interp, p, 1, argv[i], nextArg, O_RDONLY, &skip, &inputClose, &inputRelease); if (inputFile == NULL) { goto error; } } break; case '>': atOK = 1; flags = O_WRONLY | O_CREAT | O_TRUNC; if (*p == '>') { p++; atOK = 0; /* * Note that the O_APPEND flag only has an effect on POSIX * platforms. On Windows, we just have to carry on regardless. */ flags = O_WRONLY | O_CREAT | O_APPEND; } if (*p == '&') { if (errorClose != 0) { errorClose = 0; TclpCloseFile(errorFile); } errorToOutput = 1; p++; } /* * Close the old output file, but only if the error file is not * also using it. */ if (outputClose != 0) { outputClose = 0; if (errorFile == outputFile) { errorClose = 1; } else { TclpCloseFile(outputFile); } } if (outputRelease != 0) { outputRelease = 0; if (errorFile == outputFile) { errorRelease = 1; } else { TclpReleaseFile(outputFile); } } nextArg = ((i + 1) == argc) ? NULL : argv[i + 1]; outputFile = FileForRedirect(interp, p, atOK, argv[i], nextArg, flags, &skip, &outputClose, &outputRelease); if (outputFile == NULL) { goto error; } if (errorToOutput) { if (errorClose != 0) { errorClose = 0; TclpCloseFile(errorFile); } if (errorRelease != 0) { errorRelease = 0; TclpReleaseFile(errorFile); } errorFile = outputFile; } break; case '2': if (*p != '>') { break; } p++; atOK = 1; flags = O_WRONLY | O_CREAT | O_TRUNC; if (*p == '>') { p++; atOK = 0; flags = O_WRONLY | O_CREAT; } if (errorClose != 0) { errorClose = 0; TclpCloseFile(errorFile); } if (errorRelease != 0) { errorRelease = 0; TclpReleaseFile(errorFile); } if (atOK && p[0] == '@' && p[1] == '1' && p[2] == '\0') { /* * Special case handling of 2>@1 to redirect stderr to the * exec/open output pipe as well. This is meant for the end of * the command string, otherwise use |& between commands. */ if (i != argc-1) { Tcl_AppendResult(interp, "must specify \"", argv[i], "\" as last word in command", NULL); goto error; } errorFile = outputFile; errorToOutput = 2; skip = 1; } else { nextArg = ((i + 1) == argc) ? NULL : argv[i + 1]; errorFile = FileForRedirect(interp, p, atOK, argv[i], nextArg, flags, &skip, &errorClose, &errorRelease); if (errorFile == NULL) { goto error; } } break; default: /* Got a command word, not a redirection */ needCmd = 0; break; } if (skip != 0) { for (j = i + skip; j < argc; j++) { argv[j - skip] = argv[j]; } argc -= skip; i -= 1; } } if (needCmd) { /* We had a bar followed only by redirections. */ Tcl_SetResult(interp, "illegal use of | or |& in command", TCL_STATIC); goto error; } if (inputFile == NULL) { if (inputLiteral != NULL) { /* * The input for the first process is immediate data coming from * Tcl. Create a temporary file for it and put the data into the * file. */ inputFile = TclpCreateTempFile(inputLiteral); if (inputFile == NULL) { Tcl_AppendResult(interp, "couldn't create input file for command: ", Tcl_PosixError(interp), NULL); goto error; } inputClose = 1; } else if (inPipePtr != NULL) { /* * The input for the first process in the pipeline is to come from * a pipe that can be written from by the caller. */ if (TclpCreatePipe(&inputFile, inPipePtr) == 0) { Tcl_AppendResult(interp, "couldn't create input pipe for command: ", Tcl_PosixError(interp), NULL); goto error; } inputClose = 1; } else { /* * The input for the first process comes from stdin. */ channel = Tcl_GetStdChannel(TCL_STDIN); if (channel != NULL) { inputFile = TclpMakeFile(channel, TCL_READABLE); if (inputFile != NULL) { inputRelease = 1; } } } } if (outputFile == NULL) { if (outPipePtr != NULL) { /* * Output from the last process in the pipeline is to go to a pipe * that can be read by the caller. */ if (TclpCreatePipe(outPipePtr, &outputFile) == 0) { Tcl_AppendResult(interp, "couldn't create output pipe for command: ", Tcl_PosixError(interp), NULL); goto error; } outputClose = 1; } else { /* * The output for the last process goes to stdout. */ channel = Tcl_GetStdChannel(TCL_STDOUT); if (channel) { outputFile = TclpMakeFile(channel, TCL_WRITABLE); if (outputFile != NULL) { outputRelease = 1; } } } } if (errorFile == NULL) { if (errorToOutput == 2) { /* * Handle 2>@1 special case at end of cmd line. */ errorFile = outputFile; } else if (errFilePtr != NULL) { /* * Set up the standard error output sink for the pipeline, if * requested. Use a temporary file which is opened, then deleted. * Could potentially just use pipe, but if it filled up it could * cause the pipeline to deadlock: we'd be waiting for processes * to complete before reading stderr, and processes couldn't * complete because stderr was backed up. */ errorFile = TclpCreateTempFile(NULL); if (errorFile == NULL) { Tcl_AppendResult(interp, "couldn't create error file for command: ", Tcl_PosixError(interp), NULL); goto error; } *errFilePtr = errorFile; } else { /* * Errors from the pipeline go to stderr. */ channel = Tcl_GetStdChannel(TCL_STDERR); if (channel) { errorFile = TclpMakeFile(channel, TCL_WRITABLE); if (errorFile != NULL) { errorRelease = 1; } } } } /* * Scan through the argc array, creating a process for each group of * arguments between the "|" characters. */ Tcl_ReapDetachedProcs(); pidPtr = (Tcl_Pid *) ckalloc((unsigned) (cmdCount * sizeof(Tcl_Pid))); curInFile = inputFile; for (i = 0; i < argc; i = lastArg + 1) { int result, joinThisError; Tcl_Pid pid; CONST char *oldName; /* * Convert the program name into native form. */ if (Tcl_TranslateFileName(interp, argv[i], &execBuffer) == NULL) { goto error; } /* * Find the end of the current segment of the pipeline. */ joinThisError = 0; for (lastArg = i; lastArg < argc; lastArg++) { if (argv[lastArg][0] != '|') { continue; } if (argv[lastArg][1] == '\0') { break; } if ((argv[lastArg][1] == '&') && (argv[lastArg][2] == '\0')) { joinThisError = 1; break; } } /* * If this is the last segment, use the specified outputFile. * Otherwise create an intermediate pipe. pipeIn will become the * curInFile for the next segment of the pipe. */ if (lastArg == argc) { curOutFile = outputFile; } else { argv[lastArg] = NULL; if (TclpCreatePipe(&pipeIn, &curOutFile) == 0) { Tcl_AppendResult(interp, "couldn't create pipe: ", Tcl_PosixError(interp), NULL); goto error; } } if (joinThisError != 0) { curErrFile = curOutFile; } else { curErrFile = errorFile; } /* * Restore argv[i], since a caller wouldn't expect the contents of * argv to be modified. */ oldName = argv[i]; argv[i] = Tcl_DStringValue(&execBuffer); result = TclpCreateProcess(interp, lastArg - i, argv + i, curInFile, curOutFile, curErrFile, &pid); argv[i] = oldName; if (result != TCL_OK) { goto error; } Tcl_DStringFree(&execBuffer); pidPtr[numPids] = pid; numPids++; /* * Close off our copies of file descriptors that were set up for this * child, then set up the input for the next child. */ if ((curInFile != NULL) && (curInFile != inputFile)) { TclpCloseFile(curInFile); } curInFile = pipeIn; pipeIn = NULL; if ((curOutFile != NULL) && (curOutFile != outputFile)) { TclpCloseFile(curOutFile); } curOutFile = NULL; } *pidArrayPtr = pidPtr; /* * All done. Cleanup open files lying around and then return. */ cleanup: Tcl_DStringFree(&execBuffer); if (inputClose) { TclpCloseFile(inputFile); } else if (inputRelease) { TclpReleaseFile(inputFile); } if (outputClose) { TclpCloseFile(outputFile); } else if (outputRelease) { TclpReleaseFile(outputFile); } if (errorClose) { TclpCloseFile(errorFile); } else if (errorRelease) { TclpReleaseFile(errorFile); } return numPids; /* * An error occurred. There could have been extra files open, such as * pipes between children. Clean them all up. Detach any child processes * that have been created. */ error: if (pipeIn != NULL) { TclpCloseFile(pipeIn); } if ((curOutFile != NULL) && (curOutFile != outputFile)) { TclpCloseFile(curOutFile); } if ((curInFile != NULL) && (curInFile != inputFile)) { TclpCloseFile(curInFile); } if ((inPipePtr != NULL) && (*inPipePtr != NULL)) { TclpCloseFile(*inPipePtr); *inPipePtr = NULL; } if ((outPipePtr != NULL) && (*outPipePtr != NULL)) { TclpCloseFile(*outPipePtr); *outPipePtr = NULL; } if ((errFilePtr != NULL) && (*errFilePtr != NULL)) { TclpCloseFile(*errFilePtr); *errFilePtr = NULL; } if (pidPtr != NULL) { for (i = 0; i < numPids; i++) { if (pidPtr[i] != (Tcl_Pid) -1) { Tcl_DetachPids(1, &pidPtr[i]); } } ckfree((char *) pidPtr); } numPids = -1; goto cleanup; } /* *---------------------------------------------------------------------- * * Tcl_OpenCommandChannel -- * * Opens an I/O channel to one or more subprocesses specified by argc and * argv. The flags argument determines the disposition of the stdio * handles. If the TCL_STDIN flag is set then the standard input for the * first subprocess will be tied to the channel: writing to the channel * will provide input to the subprocess. If TCL_STDIN is not set, then * standard input for the first subprocess will be the same as this * application's standard input. If TCL_STDOUT is set then standard * output from the last subprocess can be read from the channel; * otherwise it goes to this application's standard output. If TCL_STDERR * is set, standard error output for all subprocesses is returned to the * channel and results in an error when the channel is closed; otherwise * it goes to this application's standard error. If TCL_ENFORCE_MODE is * not set, then argc and argv can redirect the stdio handles to override * TCL_STDIN, TCL_STDOUT, and TCL_STDERR; if it is set, then it is an * error for argc and argv to override stdio channels for which * TCL_STDIN, TCL_STDOUT, and TCL_STDERR have been set. * * Results: * A new command channel, or NULL on failure with an error message left * in interp. * * Side effects: * Creates processes, opens pipes. * *---------------------------------------------------------------------- */ Tcl_Channel Tcl_OpenCommandChannel( Tcl_Interp *interp, /* Interpreter for error reporting. Can NOT be * NULL. */ int argc, /* How many arguments. */ CONST char **argv, /* Array of arguments for command pipe. */ int flags) /* Or'ed combination of TCL_STDIN, TCL_STDOUT, * TCL_STDERR, and TCL_ENFORCE_MODE. */ { TclFile *inPipePtr, *outPipePtr, *errFilePtr; TclFile inPipe, outPipe, errFile; int numPids; Tcl_Pid *pidPtr; Tcl_Channel channel; inPipe = outPipe = errFile = NULL; inPipePtr = (flags & TCL_STDIN) ? &inPipe : NULL; outPipePtr = (flags & TCL_STDOUT) ? &outPipe : NULL; errFilePtr = (flags & TCL_STDERR) ? &errFile : NULL; numPids = TclCreatePipeline(interp, argc, argv, &pidPtr, inPipePtr, outPipePtr, errFilePtr); if (numPids < 0) { goto error; } /* * Verify that the pipes that were created satisfy the readable/writable * constraints. */ if (flags & TCL_ENFORCE_MODE) { if ((flags & TCL_STDOUT) && (outPipe == NULL)) { Tcl_AppendResult(interp, "can't read output from command:" " standard output was redirected", NULL); goto error; } if ((flags & TCL_STDIN) && (inPipe == NULL)) { Tcl_AppendResult(interp, "can't write input to command:" " standard input was redirected", NULL); goto error; } } channel = TclpCreateCommandChannel(outPipe, inPipe, errFile, numPids, pidPtr); if (channel == (Tcl_Channel) NULL) { Tcl_AppendResult(interp, "pipe for command could not be created", NULL); goto error; } return channel; error: if (numPids > 0) { Tcl_DetachPids(numPids, pidPtr); ckfree((char *) pidPtr); } if (inPipe != NULL) { TclpCloseFile(inPipe); } if (outPipe != NULL) { TclpCloseFile(outPipe); } if (errFile != NULL) { TclpCloseFile(errFile); } return NULL; } /* * Local Variables: * mode: c * c-basic-offset: 4 * fill-column: 78 * End: */
2.15625
2
2024-11-18T20:15:31.545499+00:00
2021-08-18T02:38:08
f32509fe68357fa29c0837d468c377902c820a32
{ "blob_id": "f32509fe68357fa29c0837d468c377902c820a32", "branch_name": "refs/heads/master", "committer_date": "2021-08-18T02:38:08", "content_id": "7a3485ad18a1a97decfc5f27623dbc3c258b3428", "detected_licenses": [ "Apache-2.0", "curl" ], "directory_id": "11ddbb17eebddb29a4dbd2e89cf1e403a4e5942d", "extension": "c", "filename": "test_v1beta1_stateful_set_list.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": 2076, "license": "Apache-2.0,curl", "license_type": "permissive", "path": "/kubernetes/unit-test/test_v1beta1_stateful_set_list.c", "provenance": "stackv2-0033.json.gz:169669", "repo_name": "duokuiwang/c", "revision_date": "2021-08-18T02:38:08", "revision_id": "3cb0df06851a369e9b7062cb533ecf6b766e4130", "snapshot_id": "86494f7ace5992f9402e4374e22eb5f6f67de984", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/duokuiwang/c/3cb0df06851a369e9b7062cb533ecf6b766e4130/kubernetes/unit-test/test_v1beta1_stateful_set_list.c", "visit_date": "2023-07-09T10:23:06.946203" }
stackv2
#ifndef v1beta1_stateful_set_list_TEST #define v1beta1_stateful_set_list_TEST // the following is to include only the main from the first c file #ifndef TEST_MAIN #define TEST_MAIN #define v1beta1_stateful_set_list_MAIN #endif // TEST_MAIN #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include "../external/cJSON.h" #include "../model/v1beta1_stateful_set_list.h" v1beta1_stateful_set_list_t* instantiate_v1beta1_stateful_set_list(int include_optional); #include "test_v1_list_meta.c" v1beta1_stateful_set_list_t* instantiate_v1beta1_stateful_set_list(int include_optional) { v1beta1_stateful_set_list_t* v1beta1_stateful_set_list = NULL; if (include_optional) { v1beta1_stateful_set_list = v1beta1_stateful_set_list_create( "0", list_create(), "0", // false, not to have infinite recursion instantiate_v1_list_meta(0) ); } else { v1beta1_stateful_set_list = v1beta1_stateful_set_list_create( "0", list_create(), "0", NULL ); } return v1beta1_stateful_set_list; } #ifdef v1beta1_stateful_set_list_MAIN void test_v1beta1_stateful_set_list(int include_optional) { v1beta1_stateful_set_list_t* v1beta1_stateful_set_list_1 = instantiate_v1beta1_stateful_set_list(include_optional); cJSON* jsonv1beta1_stateful_set_list_1 = v1beta1_stateful_set_list_convertToJSON(v1beta1_stateful_set_list_1); printf("v1beta1_stateful_set_list :\n%s\n", cJSON_Print(jsonv1beta1_stateful_set_list_1)); v1beta1_stateful_set_list_t* v1beta1_stateful_set_list_2 = v1beta1_stateful_set_list_parseFromJSON(jsonv1beta1_stateful_set_list_1); cJSON* jsonv1beta1_stateful_set_list_2 = v1beta1_stateful_set_list_convertToJSON(v1beta1_stateful_set_list_2); printf("repeating v1beta1_stateful_set_list:\n%s\n", cJSON_Print(jsonv1beta1_stateful_set_list_2)); } int main() { test_v1beta1_stateful_set_list(1); test_v1beta1_stateful_set_list(0); printf("Hello world \n"); return 0; } #endif // v1beta1_stateful_set_list_MAIN #endif // v1beta1_stateful_set_list_TEST
2.53125
3
2024-11-18T20:15:32.157968+00:00
2014-03-31T20:09:03
e0dd2a6ae89690b4a68e7efe4a7cdd0dc38b2048
{ "blob_id": "e0dd2a6ae89690b4a68e7efe4a7cdd0dc38b2048", "branch_name": "refs/heads/master", "committer_date": "2014-03-31T20:09:03", "content_id": "984af6d72c259dc1e2101a43ba06cb103ae310a3", "detected_licenses": [ "MIT" ], "directory_id": "307dd62b45c880219edbcb8581b110606c72f478", "extension": "c", "filename": "rgb.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": 1145, "license": "MIT", "license_type": "permissive", "path": "/project2/rgb.c", "provenance": "stackv2-0033.json.gz:170439", "repo_name": "vcwseas/CMSC15200", "revision_date": "2014-03-31T20:09:03", "revision_id": "acbef917a09c086fd8d9a61e2f145e8b83c930fd", "snapshot_id": "d3bae0838fb8916536abe29cbb5444701f0514db", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vcwseas/CMSC15200/acbef917a09c086fd8d9a61e2f145e8b83c930fd/project2/rgb.c", "visit_date": "2021-01-15T14:36:09.999242" }
stackv2
#include "raytracer.h" double rgb_clamp(double x) { return (x<0)?0:((x>1)?1:x); } rgb rgb_expr(double r, double g, double b) { r = rgb_clamp(r); g = rgb_clamp(g); b = rgb_clamp(b); rgb c = {r,g,b}; return c; } double rgb_clamp_above(double x) { return (x>1)?1:x; } rgb rgb_modulate(rgb x, rgb y) { rgb res = {x.r*y.r, x.g*y.g, x.b*y.b}; return res; } rgb rgb_scale(double s, rgb c) { rgb res = {rgb_clamp(s*c.r), rgb_clamp(s*c.g), rgb_clamp(s*c.b)}; return res; } rgb rgb_add(rgb x, rgb y) { rgb res = {rgb_clamp_above(x.r+y.r), rgb_clamp_above(x.g+y.g), rgb_clamp_above(x.b+y.b)}; return res; } void rgb_print(rgb x) { printf("(%lg, %lg, %lg)\n", x.r, x.g, x.b); } char *rgb_tos(rgb x) { char buf[1024] = {0}; sprintf(buf,"RGB(%lf,%lf,%lf)",x.r,x.g,x.b); return strdup(buf); } byte bytify(double x) { return (byte)(x*255); } void rgb_print_bytes(rgb c) { printf("%d %d %d\n",bytify(c.r),bytify(c.g),bytify(c.b)); } /* print bytes to FILE pointed to by FILE* f */ void rgb_fprint_bytes(FILE *f, rgb c) { fprintf(f, "%d %d %d\n",bytify(c.r),bytify(c.g),bytify(c.b)); }
2.78125
3
2024-11-18T20:15:32.319669+00:00
2018-05-29T14:19:31
3671c086eb7ff30f34a643bebb0c989a8e06b873
{ "blob_id": "3671c086eb7ff30f34a643bebb0c989a8e06b873", "branch_name": "refs/heads/master", "committer_date": "2018-05-29T14:19:31", "content_id": "ff77ad8b3fcbb51ca4f62ace218d8bdafd00573b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "fda1cd54799f89a84dc10d0aa2b9aee482c75575", "extension": "c", "filename": "rxtx.c", "fork_events_count": 1, "gha_created_at": "2015-08-26T23:09:32", "gha_event_created_at": "2015-08-26T23:09:32", "gha_language": null, "gha_license_id": null, "github_id": 41454370, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2271, "license": "Apache-2.0", "license_type": "permissive", "path": "/com.ibm.streamsx.network/impl/src/source/dpdk/streams_source/rxtx.c", "provenance": "stackv2-0033.json.gz:170696", "repo_name": "engebret/streamsx.network", "revision_date": "2018-05-29T14:19:31", "revision_id": "3c4a2ef3c4d17c7eafc767c12f0f4d2f79ec598d", "snapshot_id": "a9715f8dcb07a1a76c3a717869d8dac4938fcae9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/engebret/streamsx.network/3c4a2ef3c4d17c7eafc767c12f0f4d2f79ec598d/com.ibm.streamsx.network/impl/src/source/dpdk/streams_source/rxtx.c", "visit_date": "2020-12-24T17:35:28.015231" }
stackv2
/********************************************************************* * Copyright (C) 2015, International Business Machines Corporation * All Rights Reserved *********************************************************************/ #include <rte_cycles.h> #include <rte_ethdev.h> #include <rte_lcore.h> #include <rte_log.h> #include <rte_mbuf.h> #include "rxtx.h" #include "config.h" #define PREFETCH_OFFSET 1 void receive_loop(struct lcore_conf *conf) { struct rte_mbuf *pkts_burst[MAX_PKT_BURST]; unsigned i, portid; int j, num_rx, count; RTE_LOG(INFO, STREAMS_SOURCE, "Starting receive loop on lcore %u\n", rte_lcore_id()); RTE_LOG(INFO, STREAMS_SOURCE, "conf = 0x%lx, num_rx_queue = %d\n", conf, conf->num_rx_queue); for (i = 0; i < conf->num_rx_queue; i++) { RTE_LOG(INFO, STREAMS_SOURCE, "port_id = %d, queue_id = %d\n", conf->rx_queue_list[i].port_id, conf->rx_queue_list[i].queue_id); } while(1) { // Read rx packets from the queue. for (i = 0; i < conf->num_rx_queue; i++) { portid = conf->rx_queue_list[i].port_id; streams_packet_cb_t packetCallback = conf->rx_queue_list[i].packetCallbackFunction; num_rx = rte_eth_rx_burst((uint32_t) portid, conf->rx_queue_list[i].queue_id, pkts_burst, MAX_PKT_BURST); if (num_rx) { for (j = 0; j < PREFETCH_OFFSET && j < num_rx; j++) { rte_prefetch0(rte_pktmbuf_mtod(pkts_burst[j], void *)); } for (j = 0; j < (num_rx - PREFETCH_OFFSET); j++) { rte_prefetch0(rte_pktmbuf_mtod(pkts_burst[j + PREFETCH_OFFSET], void *)); if(packetCallback) { packetCallback(conf->rx_queue_list[i].userData, rte_pktmbuf_mtod(pkts_burst[j], char *), pkts_burst[j]->data_len, rte_rdtsc()); } rte_pktmbuf_free(pkts_burst[j]); count++; } for (; j < num_rx; j++) { if(packetCallback) { packetCallback(conf->rx_queue_list[i].userData, rte_pktmbuf_mtod(pkts_burst[j], char *), pkts_burst[j]->data_len, rte_rdtsc()); } rte_pktmbuf_free(pkts_burst[j]); count++; } } } } }
2.171875
2
2024-11-18T20:15:33.420289+00:00
2008-05-02T22:33:26
3ed3f4fe6fa147c01189da0d12896ce70164328a
{ "blob_id": "3ed3f4fe6fa147c01189da0d12896ce70164328a", "branch_name": "refs/heads/master", "committer_date": "2008-05-02T22:33:26", "content_id": "1139decae0e85fb27fc2ba1c47b300fa82cf1c93", "detected_licenses": [ "Artistic-2.0" ], "directory_id": "5d3c1be292f6153480f3a372befea4172c683180", "extension": "h", "filename": "TeleoInterface.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 40820013, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3630, "license": "Artistic-2.0", "license_type": "permissive", "path": "/trunk/ProxyLauncher/Hardware Proxies/Teleo/teleo/include/TeleoInterface.h", "provenance": "stackv2-0033.json.gz:171850", "repo_name": "BackupTheBerlios/istuff-svn", "revision_date": "2008-05-02T22:33:26", "revision_id": "d0bb9963b899259695553ccd2b01b35be5fb83db", "snapshot_id": "5f47aa73dd74ecf5c55f83765a5c50daa28fa508", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BackupTheBerlios/istuff-svn/d0bb9963b899259695553ccd2b01b35be5fb83db/trunk/ProxyLauncher/Hardware Proxies/Teleo/teleo/include/TeleoInterface.h", "visit_date": "2016-09-06T04:54:24.129060" }
stackv2
/* Copyright 2003 MakingThings LLC. */ /** \file TeleoInterface.h Generic Low Level IO interface. Provides the implementation for opening, reading, writing, and closing interfaces of different types Designed to be linked with the version of TeleoInterfaceXXX.c that is appropriate for the target OS. */ #ifndef TELEOINTERFACE_H_ #define TELEOINTERFACE_H_ #ifdef __cplusplus /* Note: two leading underscores */ extern "C" { #endif #include "TeleoError.h" #include "TeleoTypes.h" /** Teleo Interface. The public structure used for communication with the Interface Internally it is cast into the actual structure used by the Interface - implementation. */ typedef struct { uint8 tag; } TeleoInterface; typedef enum { TI_USB, TI_USB0, TI_USB1, TI_USB2, TI_USB3, TI_SERIAL, TI_SERIAL0, TI_SERIAL1, TI_SERIAL2, TI_SERIAL3, TI_NETWORK } TI_InterfaceType; /** Creates and initializes the interface structure. Does not open the device, since there maybe be configuration to be done first. The name may be omitted. If this happens, the default name for the supplied interface type will be used. \param name the device pathname or URI (optional) \param interfaceType the type of interface \param ti place to return the new interface \return TELEO_OK (0) or appropriate error */ TeleoError TI_Create( cchar* name, TI_InterfaceType interfaceType, TeleoInterface** ti ); /** Destroys the interface \param teleoInterface the interface structure */ TeleoError TI_destroy( TeleoInterface* teleoInterface ); /** Allows the user to retrieve the interface name \param teleoInterface the interface structure \param name pointer to the name pointer \return TELEO_OK (0) or appropriate error */ TeleoError TI_nameGet( TeleoInterface* teleoInterface, cchar** name ); /** Allows the user to get the short name - i.e. "ser", "usb", "net", etc. \param teleoInterface the interface structure \param type the type text pointer \return TELEO_OK (0) or appropriate error */ TeleoError TI_typeGet( TeleoInterface* teleoInterface, cchar** type ); /** Control whether the interface does blocking IO or not \param teleoInterface the interface structure \param blocking yes or no \return TELEO_OK (0) or appropriate error */ TeleoError TI_blockingSet( TeleoInterface* teleoInterface, bool blocking ); /** Open the port \param teleoInterface the interface structure \return TELEO_OK (0) or appropriate error */ TeleoError TI_open( TeleoInterface* teleoInterface ); /** Close the port \param teleoInterface the interface structure \return TELEO_OK (0) or appropriate error */ TeleoError TI_close( TeleoInterface* teleoInterface ); /** Get characters. Currently only permits a single character at a time. \param teleoInterface the interface structure \param cp pointer to the character \param count number of characters to get \return TELEO_OK (0) or appropriate error */ TeleoError TI_get( TeleoInterface* teleoInterface, uint8* cp, int count ); /** Put characters \param teleoInterface the interface structure \param cp pointer to the character \param count number of characters to put \return TELEO_OK (0) or appropriate error */ TeleoError TI_put( TeleoInterface* teleoInterface, uint8* cp, int count ); /** Sleep for the specified ms \param ms number of milliseconds */ TeleoError TI_SleepMs( long ms ); #ifdef __cplusplus } #endif #endif // TELEOCONTROLLERINTERFACE_H_
2.25
2
2024-11-18T20:15:33.479462+00:00
2017-10-04T23:16:52
7e8061d863025578fcdf51b65753cade958e3220
{ "blob_id": "7e8061d863025578fcdf51b65753cade958e3220", "branch_name": "refs/heads/master", "committer_date": "2017-10-04T23:31:56", "content_id": "309492e1ed259d58af807710e1ce61d1869eb0ea", "detected_licenses": [ "Unlicense" ], "directory_id": "46e8663bfe8d0b8067a05b062a2bb970227b3008", "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": 1109, "license": "Unlicense", "license_type": "permissive", "path": "/kernel/resolve/source/main.c", "provenance": "stackv2-0033.json.gz:171978", "repo_name": "inopenspace/ps4sdk-examples", "revision_date": "2017-10-04T23:16:52", "revision_id": "161c63566a5c572766d40ac51f51cfd0d8f4bb30", "snapshot_id": "945811e5082ec1a4476fb33baaae0cd6962e20af", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/inopenspace/ps4sdk-examples/161c63566a5c572766d40ac51f51cfd0d8f4bb30/kernel/resolve/source/main.c", "visit_date": "2020-05-19T06:50:24.315956" }
stackv2
#define __BSD_VISIBLE 1 #define _KERNEL #include <stdint.h> #include <inttypes.h> #include <sys/param.h> #include <sys/systm.h> #include <ps4/kernel.h> #define SERVER_PORT 5088 #define NAME_SIZE 128 int main(int argc, char **argv) { Ps4KernelThread *td; Ps4KernelSocket *client; char symbolName[NAME_SIZE]; void *symbol; int match; ps4KernelThreadGetCurrent(&td); ps4KernelSocketTCPServerCreateAcceptThenDestroy(td, &client, SERVER_PORT); ps4KernelSocketPrint(td, client, "Input: <symbol name>\n"); ps4KernelSocketPrint(td, client, "Output: <symbol name> <symbol address>\n"); ps4KernelSocketPrint(td, client, "To exit input: \"exit!\"\n"); while(1) { symbolName[0] = '\0'; symbol = NULL; ps4KernelSocketScan(td, client, &match, "%s", symbolName); if(match < 1) break; if(strncmp(symbolName, "exit!", 4) == 0) break; symbol = ps4KernelDlSym(symbolName); if(ps4KernelSocketPrint(td, client, "%s %"PRIxPTR"\n", symbolName, (uintptr_t)symbol) != PS4_OK) break; } ps4KernelSocketPrint(td, client, "Done\n"); ps4KernelSocketDestroy(client); return PS4_OK; }
2.40625
2
2024-11-18T20:15:33.644385+00:00
2023-06-11T16:09:06
ac26efa1f97a62b0ba7b9810bd5213bbd5af0483
{ "blob_id": "ac26efa1f97a62b0ba7b9810bd5213bbd5af0483", "branch_name": "refs/heads/master", "committer_date": "2023-06-11T16:09:06", "content_id": "dd65cb703ca44b5d0a6d6e3d9621a9c3604e5d94", "detected_licenses": [ "MIT" ], "directory_id": "5c2e9220307a9d2fa053792043e1252726773cc3", "extension": "c", "filename": "hlsparse.c", "fork_events_count": 2, "gha_created_at": "2017-12-02T17:22:09", "gha_event_created_at": "2023-06-11T16:09:08", "gha_language": "C", "gha_license_id": "MIT", "github_id": 112861731, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5010, "license": "MIT", "license_type": "permissive", "path": "/src/hlsparse.c", "provenance": "stackv2-0033.json.gz:172234", "repo_name": "frejoel/hlsparse", "revision_date": "2023-06-11T16:09:06", "revision_id": "0694c9bf2d7d873960e9f8f1766f4549e211fd61", "snapshot_id": "718ec94fc826bdfe8990cf7d529a9606c0500591", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/frejoel/hlsparse/0694c9bf2d7d873960e9f8f1766f4549e211fd61/src/hlsparse.c", "visit_date": "2023-06-22T15:29:56.682389" }
stackv2
#include "parse.h" #include <memory.h> #include <stdio.h> hlsparse_malloc_callback hls_malloc = (hlsparse_malloc_callback) malloc; hlsparse_free_callback hls_free = (hlsparse_free_callback) free; HLSCode hlsparse_global_init(void) { hls_malloc = (hlsparse_malloc_callback) malloc; hls_free = (hlsparse_free_callback) free; return HLS_OK; } HLSCode hlsparse_init_mem(hlsparse_malloc_callback m, hlsparse_free_callback f) { if(!m || !f) { return HLS_ERROR; } hls_malloc = m; hls_free = f; return HLS_OK; } HLSCode hlsparse_master_init(master_t *dest) { if(!dest) { return HLS_ERROR; } memset(dest, 0, sizeof(master_t)); return HLS_OK; } HLSCode hlsparse_media_playlist_init(media_playlist_t *dest) { if(!dest) { return HLS_ERROR; } memset(dest, 0, sizeof(media_playlist_t)); return HLS_OK; } HLSCode hlsparse_master_term(master_t *dest) { if(!dest) { return HLS_ERROR; } char **params[] = { &dest->uri }; parse_param_term(params, 1); hlsparse_string_list_term(&dest->custom_tags); hlsparse_session_data_list_term(&dest->session_data); hlsparse_media_list_term(&dest->media); hlsparse_stream_inf_list_term(&dest->stream_infs); hlsparse_iframe_stream_inf_list_term(&dest->iframe_stream_infs); return HLS_OK; } HLSCode hlsparse_media_playlist_term(media_playlist_t *dest) { if(!dest) { return HLS_ERROR; } char **params[] = { &dest->uri }; parse_param_term(params, 1); hlsparse_string_list_term(&dest->custom_tags); hlsparse_segment_list_term(&dest->segments); parse_map_list_term(&dest->maps); hlsparse_daterange_list_term(&dest->dateranges); return HLS_OK; } int hlsparse_master(const char *src, size_t size, master_t *dest) { int res = 0; // make sure we have some data if (src && *src != '\0' && src < &src[size]) { // go through each line parsing the tags const char *end = &src[size]; const char *pt = src; // loop until we find a null terminator or hit the end of the data while (*pt != '\0' && pt < end) { if (*pt == '#') { ++pt; pt += parse_master_tag(pt, size - (pt - src), dest); } else { ++pt; } } res = pt - src; } return res; } int hlsparse_media_playlist(const char *src, size_t size, media_playlist_t *dest) { int res = 0; if(dest) { // reset the duration dest->duration = 0; // reset the segment byte range dest->next_segment_byterange.n = dest->next_segment_byterange.o = 0; } // make sure we have some data if(src && (src[0] != '\0') && size > 0) { // go through each line parsing the tags const char* pt = &src[0]; while(*pt != '\0' && pt < &src[size]) { if(*pt == '#') { ++pt; pt += parse_media_playlist_tag(pt, size - (pt - src), dest); } else if(*pt == '\n' && pt[1] != '#') { ++pt; if(dest->last_segment) { pt += parse_segment_uri(pt, size - (pt - src), dest); } }else{ ++pt; } } res = pt - src; } // custom tags can exist after the last segment for things like pre-roll ad insertion // create a zero length segment and attach these custom tags to that segment string_list_t *tag_media = &(dest->custom_tags); if(tag_media && tag_media->data) { // create a new segment segment_t *segment = hls_malloc(sizeof(segment_t)); hlsparse_segment_init(segment); // add the new segment to the playlist segment_list_t *next = &dest->segments; while(next) { if(!next->data) { next->data = segment; break; } else if(!next->next) { next->next = hls_malloc(sizeof(segment_list_t)); hlsparse_segment_list_init(next->next); next->next->data = segment; break; } next = next->next; }; dest->last_segment = segment; ++(dest->nb_segments); segment->key_index = dest->nb_keys - 1; segment->map_index = dest->nb_maps - 1; segment->daterange_index = dest->nb_dateranges - 1; segment->pdt = segment->pdt_end = dest->next_segment_pdt; segment->sequence_num = dest->next_segment_media_sequence; segment->custom_tags.data = dest->custom_tags.data; segment->custom_tags.next = dest->custom_tags.next; dest->custom_tags.data = NULL; dest->custom_tags.next = NULL; segment->discontinuity = dest->next_segment_discontinuity; // reset the discontinuity flag dest->next_segment_discontinuity = HLS_FALSE; } return res; }
2.15625
2
2024-11-18T20:15:34.019970+00:00
2015-06-03T16:07:00
fa77bc6f6548e156c5dc57a4043fb54ea15466d6
{ "blob_id": "fa77bc6f6548e156c5dc57a4043fb54ea15466d6", "branch_name": "refs/heads/master", "committer_date": "2015-06-03T16:07:00", "content_id": "b735d017ad8dd0aae436680c75049bcdde9d169d", "detected_licenses": [ "MIT" ], "directory_id": "57ccde964254f2f253a344e9fab4940c2f71e419", "extension": "h", "filename": "min.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 31310532, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1143, "license": "MIT", "license_type": "permissive", "path": "/min.h", "provenance": "stackv2-0033.json.gz:172619", "repo_name": "interactive-matter/MinProtocol", "revision_date": "2015-06-03T16:07:00", "revision_id": "e152b3dc2cf3f0c569c7535378c999e6d347c1ae", "snapshot_id": "bf28c046f3148427bf7fbeaeacd8547e2b163e6f", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/interactive-matter/MinProtocol/e152b3dc2cf3f0c569c7535378c999e6d347c1ae/min.h", "visit_date": "2020-12-24T15:31:33.349189" }
stackv2
/* * Microcontroller Interconnect Network (MIN) Version 1.0 * * Layer 1 C API. * * Author: Ken Tindell * Copyright (c) 2014-2015 JK Energy Ltd. * Licensed under MIT License. */ #ifndef MIN_H_ #define MIN_H_ #include <stdint.h> /* Maximum size of a MIN frame: * * 3 (header) + 1 (id) + 1 (control) + 15 (payload) + 2 (checksum) + 1 (EOF) + stuff bytes */ #define MAX_FRAME_PAYLOAD_SIZE (256U) /* Initialize Layer 1 */ void min_init_layer1(); /* Called by Layer 2 to transmit a MIN Layer 1 frame */ void min_tx_frame(uint8_t id, uint8_t payload[], uint8_t length); /* Called by Layer 2 when a byte is received from its UART handler */ void min_rx_byte(uint8_t byte); /* Callback; ask Layer 2 to queue a byte into its UART handler */ void min_tx_byte(uint8_t byte); /* Callback; indicate to Layer 2 that a valid frame has been received */ void min_frame_received(uint8_t buf[], uint8_t control, uint8_t id); /* Callback; ask Layer 2 to handle an error frame - can be left at NULL*/ typedef void (*min_frame_dropped_function) (); extern min_frame_dropped_function min_frame_dropped_callback; #endif /* MIN_H_ */
2.28125
2
2024-11-18T20:15:34.850902+00:00
2023-05-11T20:15:26
bb2f78b8b42a4308b01b15399c61d0e3dd0d1c39
{ "blob_id": "bb2f78b8b42a4308b01b15399c61d0e3dd0d1c39", "branch_name": "refs/heads/master", "committer_date": "2023-05-11T20:15:26", "content_id": "8055bcc8d85b1e9397817fd49823aac75058b8eb", "detected_licenses": [ "MIT" ], "directory_id": "ac245e448cdf791f24ee71d2b89e5f13d5fb1fbb", "extension": "c", "filename": "cbie3module.c", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 67619148, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19756, "license": "MIT", "license_type": "permissive", "path": "/Betsy/Betsy/cbie3module.c", "provenance": "stackv2-0033.json.gz:172747", "repo_name": "jefftc/changlab", "revision_date": "2023-05-11T20:15:26", "revision_id": "d9688709cd1ce5185996637c57f001a543b5bb1d", "snapshot_id": "86420c8ce0f3e11a9b1b00d49f17c6af87439f32", "src_encoding": "UTF-8", "star_events_count": 11, "url": "https://raw.githubusercontent.com/jefftc/changlab/d9688709cd1ce5185996637c57f001a543b5bb1d/Betsy/Betsy/cbie3module.c", "visit_date": "2023-05-24T18:59:25.875112" }
stackv2
/* cbie3module.c * 150826 created */ #include "Python.h" #include <math.h> /* Functions in this module. */ struct int_list_struct { int len; int *values; }; struct int_list_struct *new_int_list(int length) { int *values; struct int_list_struct *list; if(!(list = (struct int_list_struct *)malloc( sizeof(struct int_list_struct)))) return NULL; if(!(values = (int *)malloc(length*sizeof(int)))) { free(list); return NULL; } list->len = length; list->values = values; return list; } void free_int_list(struct int_list_struct *list) { if(list == NULL) return; if(list->values) free(list->values); free(list); } void free_list_of_int_list(struct int_list_struct **list_of_lists, int length) { int i; if(!list_of_lists) return; for(i=0; i<length; i++) { if(list_of_lists[i]) free_int_list(list_of_lists[i]); } free(list_of_lists); } struct int_list_struct **PyTupleList_to_C(PyObject *py_tup_list) { // Return a pointer to an array of int_list_structs. It has the // same number of int_list_structs as py_tup_list. int i, j; int len_tup_list; struct int_list_struct **c_tup_list; // Pointer to pointers to c_tup_list; PyObject *py_tuple; PyObject *py_number, *py_int; int len_tup; struct int_list_struct *c_tup; len_tup_list = 0; c_tup_list = NULL; py_tuple = NULL; py_number = NULL; py_int = NULL; c_tup = NULL; if(!PySequence_Check(py_tup_list)) { PyErr_SetString(PyExc_AssertionError, "tup_list1 must be a sequence"); goto py_tuplelist_to_c_cleanup; } if((len_tup_list = PySequence_Size(py_tup_list)) == -1) { PyErr_SetString(PyExc_AssertionError, "unable to get sequence size"); goto py_tuplelist_to_c_cleanup; } i = len_tup_list * sizeof(struct int_list_struct *); if(!(c_tup_list = (struct int_list_struct **)malloc(i))) { PyErr_SetString(PyExc_AssertionError, "malloc"); goto py_tuplelist_to_c_cleanup; } for(i=0; i<len_tup_list; i++) c_tup_list[i] = NULL; // Copy py_tuple_list to c_tup_list. for(i=0; i<len_tup_list; i++) { /* New reference. */ if(!(py_tuple = PySequence_GetItem(py_tup_list, i))) goto py_tuplelist_to_c_cleanup; if(!PyTuple_Check(py_tuple)) { PyErr_SetString(PyExc_AssertionError, "not tuple"); goto py_tuplelist_to_c_cleanup; } len_tup = PyTuple_Size(py_tuple); if(!(c_tup = new_int_list(len_tup))) { PyErr_SetString(PyExc_AssertionError, "memory"); goto py_tuplelist_to_c_cleanup; } for(j=0; j<len_tup; j++) { // Borrowed reference. if(!(py_number = PyTuple_GetItem(py_tuple, j))) { goto py_tuplelist_to_c_cleanup; } if(!PyNumber_Check(py_number)) { //PyObject_Print(py_number, stdout, Py_PRINT_RAW); PyErr_SetString(PyExc_AssertionError, "not number"); py_number = NULL; goto py_tuplelist_to_c_cleanup; } if(!(py_int = PyNumber_Int(py_number))) { py_number = NULL; goto py_tuplelist_to_c_cleanup; } c_tup->values[j] = (int)PyInt_AS_LONG(py_int); py_number = NULL; Py_DECREF(py_int); py_int = NULL; } c_tup_list[i] = c_tup; c_tup = NULL; Py_DECREF(py_tuple); py_tuple = NULL; } py_tuplelist_to_c_cleanup: if(py_tuple) { Py_DECREF(py_tuple); } if(py_number) { Py_DECREF(py_number); } if(py_int) { Py_DECREF(py_int); } if(c_tup) { free_int_list(c_tup); } if(PyErr_Occurred()) { if(c_tup_list) { free_list_of_int_list(c_tup_list, len_tup_list); } return NULL; } return c_tup_list; } int compare_int(const void *a, const void *b) { int *a_int = (int *)a; int *b_int = (int *)b; return *a_int - *b_int; } static void uniq_int_list(int *values, int *num_values) { // Change values in place. int i, j; // 90% of the calls from bie3._merge_paths have only 2 values. // Special code these cases. The rest only have 3. if(*num_values <= 1) { } else if(*num_values == 2) { if(values[0] == values[1]) *num_values = 1; } else if(*num_values == 3) { // Values X1, X2, X3. // Compare X2 and X3. if(values[1] == values[2]) *num_values -= 1; // Now list is either (X1, X2, X3) or (X1, X2). // Compare X1 and X2. if(values[0] == values[1]) { values[1] = values[2]; // May not be necessary, but doesn't hurt. *num_values -= 1; } // Now (X1, X2, X3), (X1, X3), (X1, X2), (X1). // Compare X1 and X3. if((*num_values == 3) && (values[0] == values[2])) *num_values -= 1; else if((*num_values == 2) && (values[0] == values[1])) *num_values -= 1; } else { qsort(values, *num_values, sizeof(int), compare_int); i = 0; while(i < *num_values-1) { if(values[i] == values[i+1]) { for(j=i+1; j<*num_values-1; j++) values[j] = values[j+1]; (*num_values)--; } else { i++; } } } } /* Module definition stuff */ static char cbie3__product_and_chain_h__doc__[] = "XXX\n"; #define MAX_VALUES 1024 * 8 static PyObject *cbie3__product_and_chain_h(PyObject *self, PyObject *args) { int i, j, k, l, m; PyObject *py_tup_list1, *py_tup_list2; int len_tup_list1, len_tup_list2; int max_length; struct int_list_struct **c_tup_list1, **c_tup_list2; //struct int_list_struct *DEBUG; PyObject *py_results; PyObject *py_tuple; PyObject *py_item; int len; int len1, len2; int *values; int v; //int v1, v2; c_tup_list1 = NULL; c_tup_list2 = NULL; py_results = NULL; py_tuple = NULL; py_item = NULL; values = NULL; if(!PyArg_ParseTuple(args, "OOi", &py_tup_list1, &py_tup_list2, &max_length)) return NULL; if(!PySequence_Check(py_tup_list1)) { PyErr_SetString(PyExc_AssertionError, "tup_list1 must be a sequence"); goto _product_and_chain_h_cleanup; } if(!PySequence_Check(py_tup_list2)) { PyErr_SetString(PyExc_AssertionError, "tup_list2 must be a sequence"); goto _product_and_chain_h_cleanup; } if((len_tup_list1 = PySequence_Size(py_tup_list1)) == -1) { PyErr_SetString(PyExc_AssertionError, "unable to get sequence size"); goto _product_and_chain_h_cleanup; } if((len_tup_list2 = PySequence_Size(py_tup_list2)) == -1) { PyErr_SetString(PyExc_AssertionError, "unable to get sequence size"); goto _product_and_chain_h_cleanup; } if(!(c_tup_list1 = PyTupleList_to_C(py_tup_list1))) goto _product_and_chain_h_cleanup; if(!(c_tup_list2 = PyTupleList_to_C(py_tup_list2))) goto _product_and_chain_h_cleanup; if(!(py_results = PyDict_New())) goto _product_and_chain_h_cleanup; if(!(values = (int *)malloc(MAX_VALUES*sizeof(int)))) { PyErr_SetString(PyExc_AssertionError, "out of memory"); goto _product_and_chain_h_cleanup; } for(i=0; i<len_tup_list1; i++) { for(j=0; j<len_tup_list2; j++) { // Merge the two lists. len1 = c_tup_list1[i]->len; len2 = c_tup_list2[j]->len; if(len1+len2 > MAX_VALUES) { PyErr_SetString(PyExc_AssertionError, "too many values"); goto _product_and_chain_h_cleanup; } //// DEBUG //for(k=0; k<len1-1; k++) { // v1 = c_tup_list1[i]->values[k]; // v2 = c_tup_list1[i]->values[k+1]; // if(v1 >= v2) { // PyErr_SetString(PyExc_AssertionError, "out of order 1"); // goto _product_and_chain_h_cleanup; // } // } //// DEBUG //for(k=0; k<len2-1; k++) { // v1 = c_tup_list2[j]->values[k]; // v2 = c_tup_list2[j]->values[k+1]; // if(v1 >= v2) { // PyErr_SetString(PyExc_AssertionError, "out of order 2"); // goto _product_and_chain_h_cleanup; // } // } // The vast majority of the time, len1 and len2 are at the // limit. // Add the members from list1. for(k=0; k<len1; k++) values[k] = c_tup_list1[i]->values[k]; len = len1; // Add each member from list2 if it's not already in // list1. Assume that list1 and list2 are already sorted. // Maintain a sorted order in values. l = 0; for(k=0; k<len2; k++) { // Find the right place to add the new value. v = c_tup_list2[j]->values[k]; for(; l<len; l++) { if(v <= values[l]) break; } // No duplicates. if((l < len) && (v == values[l])) continue; // Move the other values out of the way. for(m=len; m>l; m--) values[m] = values[m-1]; // Add this one. values[l] = v; len++; if(len > max_length) break; //values[len1+k] = c_tup_list2[j]->values[k]; } //// DEBUG //for(k=0; k<len-1; k++) { // if(values[k] >= values[k+1]) { // PyErr_SetString(PyExc_AssertionError, "out of order 3"); // goto _product_and_chain_h_cleanup; // } // } //// Sort the values. //// Optimize: don't sort if there is <= 2 values? //qsort(values, len, sizeof(int), compare_int); // //// No duplicate values. Optimize this. //k = 0; //while(k < len-1) { // if(values[k] == values[k+1]) { // for(l=k+1; l<len-1; l++) // values[l] = values[l+1]; // len -= 1; // } else { // k += 1; // } // } if(len > max_length) continue; /* Make a tuple of the values. */ if(!(py_tuple = PyTuple_New(len))) /* New Reference */ goto _product_and_chain_h_cleanup; for(k=0; k<len; k++) { if(!(py_item = PyInt_FromLong(values[k]))) goto _product_and_chain_h_cleanup; // Returns 0 on success. if(PyTuple_SetItem(py_tuple, k, py_item) != 0) goto _product_and_chain_h_cleanup; py_item = NULL; /* Reference stolen by SetItem */ } /* Add these values to py_results. */ /* Does not steal reference to Py_None. Will increment itself. */ if(PyDict_SetItem(py_results, py_tuple, Py_None) != 0) goto _product_and_chain_h_cleanup; Py_DECREF(py_tuple); py_tuple = NULL; } } _product_and_chain_h_cleanup: if(c_tup_list1) { free_list_of_int_list(c_tup_list1, len_tup_list1); } if(c_tup_list2) { free_list_of_int_list(c_tup_list2, len_tup_list2); } if(values) { free(values); } if(py_tuple) { Py_DECREF(py_tuple); } if(py_item) { Py_DECREF(py_item); } if(PyErr_Occurred()) { if(py_results) { Py_DECREF(py_results); } return NULL; } return py_results; } static char cbie3__uniq_intlist__doc__[] = "XXX\n"; static PyObject *cbie3__uniq_intlist(PyObject *self, PyObject *args) { int i; PyObject *py_seq, *py_number, *py_int; int len_py_seq; int *values; int num_values; PyObject *py_results; PyObject *py_item; values = NULL; py_number = NULL; py_int = NULL; py_results = NULL; py_item = NULL; if(!PyArg_ParseTuple(args, "O", &py_seq)) return NULL; if(!PyList_Check(py_seq)) { PyErr_SetString(PyExc_AssertionError, "seq must be a list"); goto _uniq_intlist_cleanup; } if((len_py_seq = PyList_Size(py_seq)) == -1) { PyErr_SetString(PyExc_AssertionError, "unable to get list size"); goto _uniq_intlist_cleanup; } if(!(values = (int *)malloc(len_py_seq*sizeof(int)))) { PyErr_SetString(PyExc_AssertionError, "out of memory"); goto _uniq_intlist_cleanup; } // Extract the list into values. num_values = len_py_seq; for(i=0; i<len_py_seq; i++) { // Borrowed reference. if(!(py_number = PyList_GetItem(py_seq, i))) { goto _uniq_intlist_cleanup; } if(!PyNumber_Check(py_number)) { //PyObject_Print(py_number, stdout, Py_PRINT_RAW); PyErr_SetString(PyExc_AssertionError, "not number"); py_number = NULL; goto _uniq_intlist_cleanup; } // New reference. if(!(py_int = PyNumber_Int(py_number))) { py_number = NULL; goto _uniq_intlist_cleanup; } values[i] = (int)PyInt_AS_LONG(py_int); py_number = NULL; Py_DECREF(py_int); py_int = NULL; } // Get rid of duplicate values. if(num_values >= 2) { uniq_int_list(values, &num_values); } // Save the results. if(!(py_results = PyList_New(num_values))) goto _uniq_intlist_cleanup; for(i=0; i<num_values; i++) { // New reference. if(!(py_item = PyInt_FromLong(values[i]))) goto _uniq_intlist_cleanup; // Returns 0 on success. Steals reference. // SET_ITEM leads to segfault. Maybe trying to decref NULL? if(PyList_SetItem(py_results, i, py_item) != 0) goto _uniq_intlist_cleanup; py_item = NULL; } _uniq_intlist_cleanup: if(values) { free(values); } if(py_number) { Py_DECREF(py_number); } if(py_int) { Py_DECREF(py_int); } if(py_item) { Py_DECREF(py_item); } if(PyErr_Occurred()) { if(py_results) { Py_DECREF(py_results); } return NULL; } return py_results; } static char cbie3__uniq_flatten1_intlist__doc__[] = "XXX\n"; static PyObject *cbie3__uniq_flatten1_intlist(PyObject *self, PyObject *args) { int i, j; PyObject *py_seq, *py_list, *py_number, *py_int; int len_py_seq, len_py_list; int *values; int num_values; PyObject *py_results; PyObject *py_item; values = NULL; py_number = NULL; py_list = NULL; py_int = NULL; py_results = NULL; py_item = NULL; if(!PyArg_ParseTuple(args, "O", &py_seq)) return NULL; if(!PyList_Check(py_seq)) { PyErr_SetString(PyExc_AssertionError, "seq must be a list"); goto _uniq_flatten1_intlist_cleanup; } if((len_py_seq = PyList_Size(py_seq)) == -1) { PyErr_SetString(PyExc_AssertionError, "unable to get list size"); goto _uniq_flatten1_intlist_cleanup; } if(!(values = (int *)malloc(MAX_VALUES*sizeof(int)))) { PyErr_SetString(PyExc_AssertionError, "out of memory"); goto _uniq_flatten1_intlist_cleanup; } num_values = 0; // Extract the list into values. for(i=0; i<len_py_seq; i++) { // Borrowed reference. if(!(py_list = PyList_GetItem(py_seq, i))) { goto _uniq_flatten1_intlist_cleanup; } if(!PyList_Check(py_list)) { PyErr_SetString(PyExc_AssertionError, "each item must be a list"); py_list = NULL; goto _uniq_flatten1_intlist_cleanup; } if((len_py_list = PyList_Size(py_list)) == -1) { PyErr_SetString(PyExc_AssertionError, "unable to get list size"); py_list = NULL; goto _uniq_flatten1_intlist_cleanup; } for(j=0; j<len_py_list; j++) { // Borrowed reference. if(!(py_number = PyList_GetItem(py_list, j))) { py_list = NULL; goto _uniq_flatten1_intlist_cleanup; } if(!PyNumber_Check(py_number)) { PyErr_SetString(PyExc_AssertionError, "not number"); py_list = NULL; py_number = NULL; goto _uniq_flatten1_intlist_cleanup; } // New reference. if(!(py_int = PyNumber_Int(py_number))) { py_list = NULL; py_number = NULL; goto _uniq_flatten1_intlist_cleanup; } values[num_values++] = (int)PyInt_AS_LONG(py_int); py_number = NULL; Py_DECREF(py_int); py_int = NULL; } py_list = NULL; } // Get rid of duplicate values. if(num_values >= 2) { uniq_int_list(values, &num_values); } // Save the results. if(!(py_results = PyList_New(num_values))) goto _uniq_flatten1_intlist_cleanup; for(i=0; i<num_values; i++) { // New reference. if(!(py_item = PyInt_FromLong(values[i]))) goto _uniq_flatten1_intlist_cleanup; // Returns 0 on success. Steals reference. // SET_ITEM leads to segfault. Maybe trying to decref NULL? if(PyList_SetItem(py_results, i, py_item) != 0) goto _uniq_flatten1_intlist_cleanup; py_item = NULL; } _uniq_flatten1_intlist_cleanup: if(values) { free(values); } if(py_list) { Py_DECREF(py_list); } if(py_number) { Py_DECREF(py_number); } if(py_int) { Py_DECREF(py_int); } if(py_item) { Py_DECREF(py_item); } if(PyErr_Occurred()) { if(py_results) { Py_DECREF(py_results); } return NULL; } return py_results; } //static char cbie3__get_attribute_type__doc__[] = // "XXX\n"; // //#define TYPE_ATOM 100 //#define TYPE_ENUM 101 //static PyObject *cbie3__get_attribute_type(PyObject *self, PyObject *args) //{ // PyObject *py_name; // // if(!PyArg_ParseTuple(args, "O", &py_name)) // return NULL; // if(PyString_Check(py_name)) { // return PyInt_FromLong(TYPE_ATOM); // } // if(PyList_Check(py_name) || PyTuple_Check(py_name)) { // return PyInt_FromLong(TYPE_ENUM); // } // PyErr_SetString(PyExc_AssertionError, "Unknown attribute type"); // return NULL; //} static PyMethodDef cbie3Methods[] = { {"_product_and_chain_h", cbie3__product_and_chain_h, METH_VARARGS, cbie3__product_and_chain_h__doc__}, {"_uniq_intlist", cbie3__uniq_intlist, METH_VARARGS, cbie3__uniq_intlist__doc__}, {"_uniq_flatten1_intlist", cbie3__uniq_flatten1_intlist, METH_VARARGS, cbie3__uniq_flatten1_intlist__doc__}, // Does not result in much speed-up. //{"_get_attribute_type", cbie3__get_attribute_type, METH_VARARGS, // cbie3__get_attribute_type__doc__}, {NULL, NULL, 0, NULL} }; static char cbie3__doc__[] = "This module provides optimized replacement functions.\n\ "; PyMODINIT_FUNC initcbie3(void) { (void) Py_InitModule3("cbie3", cbie3Methods, cbie3__doc__); }
2.71875
3
2024-11-18T20:15:34.978860+00:00
2019-08-28T07:21:12
1638824f4706f3c24809ab346e8cca16bea210bc
{ "blob_id": "1638824f4706f3c24809ab346e8cca16bea210bc", "branch_name": "refs/heads/master", "committer_date": "2019-08-28T07:21:12", "content_id": "1b67e50024a4c0a01c64108aa9f3cce2a32b978e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9edf89d002e75de70f1813c891407616fd8ad38f", "extension": "c", "filename": "driver_framebuffer_orientation.c", "fork_events_count": 0, "gha_created_at": "2019-08-27T20:53:15", "gha_event_created_at": "2019-08-27T21:53:15", "gha_language": null, "gha_license_id": null, "github_id": 204788669, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5637, "license": "Apache-2.0", "license_type": "permissive", "path": "/firmware/components/driver_framebuffer/driver_framebuffer_orientation.c", "provenance": "stackv2-0033.json.gz:172875", "repo_name": "thinkl33t/ESP32-platform-firmware", "revision_date": "2019-08-28T07:21:12", "revision_id": "013bb073792918bbaecb0faeb24ff4a4a1b3b2df", "snapshot_id": "df259efa69a4466a4bd602dfc2c1483b0c1638db", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/thinkl33t/ESP32-platform-firmware/013bb073792918bbaecb0faeb24ff4a4a1b3b2df/firmware/components/driver_framebuffer/driver_framebuffer_orientation.c", "visit_date": "2020-07-12T10:09:34.663076" }
stackv2
/* * The functions in this file translate coordinates between * the point-of-view of the user and the point-of-view of the * buffer in memory when changing the orientation of the framebuffer * or the orientation of a compositor window. * * Additionally the functions in this file allow for setting and * querying the orientation for both the global framebuffer and * for each of the compositor windows. */ #include "include/driver_framebuffer_internal.h" #ifdef CONFIG_DRIVER_FRAMEBUFFER_ENABLE #define TAG "fb-orientation" /* Variables */ enum Orientation globalOrientation; /* Private functions */ inline enum Orientation* _getOrientationContext(Window* window) { if (window == NULL) { //No window provided, use global context return &globalOrientation; } else { //Window provided, use window context return &window->orientation; } } inline void _getSizeContext(Window* window, int16_t* width, int16_t* height) { if (window == NULL) { //No window provided, use global context *width = FB_WIDTH; *height = FB_HEIGHT; } else { //Window provided, use window context *width = window->width; *height = window->height; } } /* Public functions */ enum Orientation driver_framebuffer_get_orientation(Window* window) { enum Orientation *orientation = _getOrientationContext(window); return *orientation; } void driver_framebuffer_set_orientation(Window* window, enum Orientation newOrientation) { enum Orientation *orientation = _getOrientationContext(window); *orientation = newOrientation; } uint16_t driver_framebuffer_get_orientation_angle(Window* window) { enum Orientation *orientation = _getOrientationContext(window); switch (*orientation) { #ifdef CONFIG_DRIVER_FRAMEBUFFER_FLIP case portrait: return 270; case reverse_landscape: return 0; case reverse_portrait: return 90; default: case landscape: return 180; #else case portrait: return 90; case reverse_landscape: return 180; case reverse_portrait: return 270; default: case landscape: return 0; #endif } } void driver_framebuffer_set_orientation_angle(Window* window, uint16_t angle) { enum Orientation *orientation = _getOrientationContext(window); #ifdef CONFIG_DRIVER_FRAMEBUFFER_FLIP switch (angle % 360) { case 270: *orientation = portrait; break; case 0: *orientation = reverse_landscape; break; case 90: *orientation = reverse_portrait; break; default: *orientation = landscape; break; } #else switch (angle % 360) { case 90: *orientation = portrait; break; case 180: *orientation = reverse_landscape; break; case 270: *orientation = reverse_portrait; break; default: *orientation = landscape; break; } #endif } bool driver_framebuffer_orientation_apply(Window* window, int16_t* x, int16_t* y) { enum Orientation *orientation = _getOrientationContext(window); int16_t width, height; _getSizeContext(window, &width, &height); int16_t oldx = *x; int16_t oldy = *y; if (*orientation == portrait || *orientation == reverse_portrait) { //90 degrees int16_t t = *y; *y = *x; *x = (width-1)-t; } if (*orientation == reverse_landscape || *orientation == portrait) { //180 degrees *y = (height-1)-*y; *x = (width-1)-*x; } char* orientationString = "unknown"; if (*orientation == portrait) orientationString = "portrait"; if (*orientation == reverse_portrait) orientationString = "reverse_portrait"; if (*orientation == landscape) orientationString = "landscape"; if (*orientation == reverse_landscape) orientationString = "reverse_landscape"; if (window) printf("Orientation: %s = %s %d=>%d %d=>%d\n", window ? window->name : "global", orientationString, oldx, *x, oldy, *y); return (*x >= 0) && (*x < width) && (*y >= 0) && (*y < height); } void driver_framebuffer_orientation_revert(Window* window, int16_t* x, int16_t* y) { enum Orientation *orientation = _getOrientationContext(window); int16_t width, height; _getSizeContext(window, &width, &height); printf("Orientation revert %u, %u\n", *x, *y); if (*orientation == reverse_landscape || *orientation == portrait) { //90 degrees int16_t t = *x; *x = *y; *y = (width-1)-t; } if (*orientation == portrait || *orientation == reverse_portrait) { //180 degrees *y = (height-1)-*y; *x = (width-1)-*x; } } void driver_framebuffer_orientation_revert_square(Window* window, int16_t* x0, int16_t* y0, int16_t* x1, int16_t* y1) { enum Orientation *orientation = _getOrientationContext(window); int16_t width, height; _getSizeContext(window, &width, &height); if (*orientation == reverse_landscape || *orientation == portrait) { //90 degrees int16_t tx0 = *x0; int16_t ty0 = *y0; *x0 = width-*x1-1; //printf("x0 = %d - %d - 1\n", width, *x1); *y0 = height-*y1-1; //printf("y0 = %d - %d - 1\n", height, *y1); *x1 = width-tx0-1; //printf("x1 = %d - %d - 1\n", width, tx0); *y1 = height-ty0-1; //printf("y1 = %d - %d - 1\n", height, ty0); } if (*orientation == portrait || *orientation == reverse_portrait) { //180 degrees int16_t tx0 = *x0; int16_t tx1 = *x1; int16_t ty1 = *y1; *x0 = *y0; *y0 = width-tx1-1; *x1 = ty1; *y1 = width-tx0-1; } } void driver_framebuffer_get_orientation_size(Window* window, int16_t* width, int16_t* height) { enum Orientation *orientation = _getOrientationContext(window); if ((*orientation == portrait) || (*orientation == reverse_portrait)) { _getSizeContext(window, height, width); //Swapped } else { _getSizeContext(window, width, height); //Normal } } #endif /* CONFIG_DRIVER_FRAMEBUFFER_ENABLE */
2.65625
3
2024-11-18T20:15:35.658865+00:00
2021-04-21T14:05:07
37910a8d5c5b837bda45c865db0f1d3019dcbbf8
{ "blob_id": "37910a8d5c5b837bda45c865db0f1d3019dcbbf8", "branch_name": "refs/heads/master", "committer_date": "2021-04-21T14:05:07", "content_id": "57fba85c5c13dad2a46cbd99ccd33f2a0e9281a1", "detected_licenses": [ "MIT" ], "directory_id": "ee0596879c1e0577139d320e1c6fdbbde40eb22d", "extension": "c", "filename": "Functions.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 121520804, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 22290, "license": "MIT", "license_type": "permissive", "path": "/Functions.c", "provenance": "stackv2-0033.json.gz:173388", "repo_name": "rummeyer/amiga-RO", "revision_date": "2021-04-21T14:05:07", "revision_id": "730803ed31fc70750cfc72f193a879af7759e7b9", "snapshot_id": "8a6c8b6b1d356ef7d26f2778b6b96886f031285f", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/rummeyer/amiga-RO/730803ed31fc70750cfc72f193a879af7759e7b9/Functions.c", "visit_date": "2021-04-30T03:45:52.384963" }
stackv2
#include "Includes.h" #include "Functions.h" /* ** ** ListSwap() ** */ void ListSwap ( void ) { char Path_String[512]; if ( global_DirLoaded[Left_Side] && global_DirLoaded[Right_Side] ) { strcpy( Path_String, GetPath( Left_Side ) ); LoadDirectory( GetPath( Right_Side ), Left_Side ); LoadDirectory( Path_String, Right_Side ); } } /* ** ** ListCopy() ** */ void ListCopy ( int side ) { if ( global_DirLoaded[side] ) LoadDirectory( GetPath( side ), OtherSide( side )); } /* ** ** ListFold() ** */ void ListFold ( void ) { global_Unfolded = !global_Unfolded; DoMethod( FoldGroup, MUIM_Group_InitChange ); set( bl_Balance, MUIA_ShowMe, global_Unfolded ); set( pg_Page[Right_Side], MUIA_ShowMe, global_Unfolded ); ActivateList(Left_Side); ActivateList(Left_Side); DoMethod( FoldGroup, MUIM_Group_ExitChange ); } /* ** ** CreateDirectory() ** */ int CreateDirectory ( int side, BOOL LoadIt ) { BPTR lock; BOOL Skip, Cancel; char Path_String[512], Icon_String[512], * String; int ErrorNum = 0; if ( global_DirLoaded[side] ) { String = StringRequester( GetCatStr( 94, "Enter directory name" ), "", ":/", 31, 0, &Skip, &Cancel ); if ( !Cancel && strlen( String ) > 0 ) { strcpy( Path_String, GetPath( side ) ); AddPart( Path_String, String, sizeof( Path_String ) ); lock = CreateDir( Path_String ); if ( lock ) { UnLock( lock ); if ( cfg_CreateIcons && ( ( strlen( FilePart( Path_String ) ) + 5 ) < 31 ) ) { sprintf( Icon_String, "%s.info", Path_String ); ErrorNum = CopyFile( "ENV:sys/def_drawer.info", Icon_String, FALSE ); } if ( LoadIt ) LoadDirectory( Path_String, side ); else Reload( side ); } else ErrorNum = IoErr(); } } return( ErrorNum ); } /* ** ** RelabelDevice() ** */ int RelabelDevice ( int side ) { BOOL Skip, Cancel; BOOL success; BPTR lock; char * NewName_String, * cptr; char Title_String[61], OldName_String[32], String[512]; int ErrorNum = 0; if ( global_DirLoaded[side] ) { lock = Lock ( GetPath( side ), ACCESS_READ ); if ( lock ) { success = NameFromLock( lock, String, sizeof( String ) ); if ( !success ) ErrorNum = IoErr(); else if ( stricmp( String, ":" ) == 0 ) ErrorNum = -11; if ( ErrorNum == 0 ) { cptr = strrchr( String, ':' ); * cptr = '\0'; strcpy( OldName_String, String ); sprintf( Title_String, GetCatStr( 95, "Relabel '%s' as" ), OldName_String ); NewName_String = StringRequester( Title_String, OldName_String, ":/", 31, 0, &Skip, &Cancel ); strcat( OldName_String, ":" ); if ( !Cancel ) { if ( stricmp ( NewName_String, "" ) != 0 ) { success = Relabel( OldName_String, NewName_String ); if ( !success ) ErrorNum = IoErr(); else { if ( cfg_PathExpand ) { success = NameFromLock( lock, String, sizeof( String ) ); if ( !success ) ErrorNum = IoErr(); else LoadDirectory( String, side ); } } } } } UnLock( lock ); } else ErrorNum = IoErr(); } return( ErrorNum ); } /* ** ** MakeAssign() ** */ int MakeAssign ( int side ) { BOOL Skip, Cancel; BOOL success; BPTR lock; char * Name_String, * cptr; char Device_String[32]; int ErrorNum = 0; if ( global_DirLoaded[side] ) { Name_String = StringRequester( GetCatStr( 96, "Enter assign name for directory" ), "", "", 31, 0, &Skip, &Cancel ); if ( !Cancel && strlen( Name_String ) > 0 ) { strcpy( Device_String, Name_String ); cptr = strrchr( Device_String, ':' ); if ( cptr != NULL ) *cptr = '\0'; if ( strlen( Device_String ) > 0 ) { lock = Lock( GetPath( side ), ACCESS_READ ); if ( lock ) { success = AssignLock( Device_String, lock ); if ( !success ) ErrorNum = IoErr(); } else ErrorNum = IoErr(); } } } return( ErrorNum ); } /* ** ** Select() ** */ void Select ( int side ) { ULONG i, Entries_ULONG; char * Pattern_String, * Pattern_Token; __aligned struct FileInfoBlock * fib; BOOL Skip, Cancel; if ( global_DirLoaded[side] ) { Pattern_String = StringRequester( GetCatStr( 97, "Enter select pattern" ), global_Pattern_String, ":/", 81, 0, &Skip, &Cancel ); if ( !Cancel && strlen( Pattern_String ) > 0 ) { strcpy( global_Pattern_String, Pattern_String ); Pattern_Token = malloc( 256 ); if ( Pattern_Token ) { ParsePatternNoCase( Pattern_String, Pattern_Token, 256 ); get( lv_Directory[side], MUIA_List_Entries, &Entries_ULONG ); for ( i = 0; i < Entries_ULONG; i++ ) { DoMethod( lv_Directory[side], MUIM_List_GetEntry, i, &fib ); if ( MatchPatternNoCase( Pattern_Token, fib -> fib_FileName ) ) DoMethod( lv_Directory[side], MUIM_List_Select, i, MUIV_List_Select_On, NULL ); } free( Pattern_Token ); } } } } /* ** ** Update() ** */ void Update ( int side ) { ULONG i,j, Entries_ULONG, EntriesSrc_ULONG; __aligned struct FileInfoBlock * srcfib; __aligned struct FileInfoBlock * fib; if ( global_DirLoaded[side] ) { get( lv_Directory[side], MUIA_List_Entries, &EntriesSrc_ULONG ); for ( j = 0; j < EntriesSrc_ULONG; j++ ) { DoMethod( lv_Directory[side], MUIM_List_GetEntry, j, &srcfib ); { get( lv_Directory[OtherSide(side)], MUIA_List_Entries, &Entries_ULONG ); for ( i = 0; i < Entries_ULONG; i++ ) { DoMethod( lv_Directory[OtherSide(side)], MUIM_List_GetEntry, i, &fib ); if ( stricmp( srcfib -> fib_FileName , fib -> fib_FileName ) == 0 ) DoMethod( lv_Directory[side], MUIM_List_Select, j, MUIV_List_Select_On, NULL ); } } } } } /* ** ** Icon() ** */ void Icon ( int side ) { ULONG i,j, Entries_ULONG, Selection_State; char Info_String[41]; __aligned struct FileInfoBlock * fib[2]; if ( global_DirLoaded[side] ) { get( lv_Directory[side], MUIA_List_Entries, &Entries_ULONG ); for ( i = 0; i < Entries_ULONG; i++ ) { DoMethod( lv_Directory[side], MUIM_List_Select, i, MUIV_List_Select_Ask, &Selection_State ); if ( Selection_State == MUIV_List_Select_On ) { DoMethod( lv_Directory[side], MUIM_List_GetEntry, i, &fib[0] ); sprintf( Info_String, "%s.info", fib[0] -> fib_FileName ); for ( j = 0; j < Entries_ULONG; j++ ) { DoMethod( lv_Directory[side], MUIM_List_GetEntry, j, &fib[1] ); if ( stricmp( Info_String, fib[1] -> fib_FileName ) == 0 ) DoMethod( lv_Directory[side], MUIM_List_Select, j, MUIV_List_Select_On, NULL ); } } } } } /* ** ** Change() ** */ void Change ( int side ) { BOOL Running = TRUE, NoChange = FALSE; APTR wi_Change, bt_Okay, bt_Cancel, cy_Sort, cy_First, cy_HighLow; ULONG signal, num; const char *cya_Sort[] = { "X", "X", "X", NULL }; const char *cya_First[] = { "X", "X", "X", NULL }; const char *cya_HighLow[] = { "X", "X", NULL }; cya_Sort[0] = GetCatStr( 98, "Name" ); cya_Sort[1] = GetCatStr( 99, "Date" ); cya_Sort[2] = GetCatStr( 100, "Size" ); cya_First[0] = GetCatStr( 101, "Dirs" ); cya_First[1] = GetCatStr( 102, "Files" ); cya_First[2] = GetCatStr( 103, "Mixed" ); cya_HighLow[0] = GetCatStr( 128, "High" ); cya_HighLow[1] = GetCatStr( 129, "Low" ); wi_Change = WindowObject, MUIA_Window_ID, 4, MUIA_Window_Title, GetCatStr( 104, "Change" ), MUIA_Window_Menu, MUIV_Window_Menu_NoMenu, MUIA_Window_SizeGadget, FALSE, WindowContents, VGroup, Child, HGroup, MUIA_Group_SameSize, TRUE, Child, cy_Sort = Radio( GetCatStr( 105, "Sort" ), cya_Sort ), Child, cy_First = Radio( GetCatStr( 106, "First" ), cya_First ), Child, cy_HighLow = Radio( GetCatStr( 130, "Order" ), cya_HighLow ), End, Child, HGroup, MUIA_Group_SameSize, TRUE, Child, bt_Okay = SimpleButton(GetCatStr( 72, "_Okay" ) ), Child, HSpace(0), Child, bt_Cancel = SimpleButton(GetCatStr( 73, "_Cancel" ) ), End, End, End; if ( !wi_Change ) Fail(); DoMethod( wi_Change, MUIM_Notify, MUIA_Window_CloseRequest, TRUE, app_RumorOpus, 2, MUIM_Application_ReturnID, 2); DoMethod( bt_Okay, MUIM_Notify, MUIA_Pressed, FALSE, app_RumorOpus, 2, MUIM_Application_ReturnID, 1); DoMethod( bt_Cancel, MUIM_Notify, MUIA_Pressed, FALSE, app_RumorOpus, 2, MUIM_Application_ReturnID, 2); DoMethod( app_RumorOpus, OM_ADDMEMBER, wi_Change ); set(cy_Sort, MUIA_Radio_Active, cfg_SortType[side] ); set(cy_First, MUIA_Radio_Active, cfg_FirstType[side] ); if ( !cfg_SortHighLow[side] ) set(cy_HighLow, MUIA_Radio_Active, 0 ); else set(cy_HighLow, MUIA_Radio_Active, 1 ); set( wi_Change, MUIA_Window_Open, TRUE ); while ( Running ) { switch ( DoMethod( app_RumorOpus, MUIM_Application_Input, &signal ) ) { case MUIV_Application_ReturnID_Quit: global_QuitProgram = QuitRequester(); if ( global_QuitProgram ) Running = FALSE; break; case 1: Running = FALSE; break; case 2: NoChange = TRUE; Running = FALSE; break; } if (signal) Wait(signal); } set(wi_Change, MUIA_Window_Open, FALSE); if ( !NoChange ) { get( cy_Sort, MUIA_Radio_Active, &cfg_SortType[side] ); get( cy_First, MUIA_Radio_Active, &cfg_FirstType[side] ); get( cy_HighLow, MUIA_Radio_Active, &num ); if ( num == 0 ) cfg_SortHighLow[side] = FALSE; else cfg_SortHighLow[side] = TRUE; set( lv_Directory[side], MUIA_Dirlist_SortType, cfg_SortType[side] ); set( lv_Directory[side], MUIA_Dirlist_SortDirs, cfg_FirstType[side] ); set( lv_Directory[side], MUIA_Dirlist_SortHighLow, cfg_SortHighLow[side] ); } DoMethod(app_RumorOpus, OM_REMMEMBER, wi_Change ); MUI_DisposeObject( wi_Change ); } /* ** ** DiskInfo() ** */ void DiskInfo ( int side ) { BOOL Running=TRUE; char * cptr; char Device_String[32], String[1024], Status_String[21], Bytes_String[8][21]; ULONG BytesTotal_ULONG, BytesUsed_ULONG, Density_ULONG, signal; BPTR lock; APTR wi_Disk, tx_TextLeft, tx_TextRight, bt_Okay, bt_Cancel; struct InfoData *pid; if ( global_DirLoaded[side] ) { lock = Lock( GetPath(side), ACCESS_READ ); if ( lock ) { pid = malloc( sizeof( struct InfoData ) ); if ( pid ) { Info( lock, pid ); strcpy( String, GetPath( side ) ); cptr = strrchr( String, ':' ); cptr++; * cptr = '\0'; strcpy( Device_String, String ); BytesTotal_ULONG = ( pid -> id_NumBlocks ) * ( pid -> id_BytesPerBlock ); BytesUsed_ULONG = ( pid -> id_NumBlocksUsed ) * ( pid -> id_BytesPerBlock ); Density_ULONG = ( pid -> id_BytesPerBlock ); switch ( pid -> id_DiskState ) { case ID_WRITE_PROTECTED: strcpy( Status_String, GetCatStr( 107, "Read Only" ) ); break; case ID_VALIDATING: strcpy( Status_String, GetCatStr( 108, "Validating" ) ); break; case ID_VALIDATED: strcpy( Status_String, GetCatStr( 109, "Read/Write" ) ); break; } strcpy( Bytes_String[0], NumberToString( ( BytesTotal_ULONG / 1024 ) ) ); strcpy( Bytes_String[1], NumberToString( BytesTotal_ULONG / Density_ULONG ) ); strcpy( Bytes_String[2], NumberToString( BytesTotal_ULONG ) ); strcpy( Bytes_String[3], NumberToString( BytesUsed_ULONG / Density_ULONG ) ); strcpy( Bytes_String[4], NumberToString( BytesUsed_ULONG ) ); strcpy( Bytes_String[5], NumberToString( ( BytesTotal_ULONG - BytesUsed_ULONG ) / Density_ULONG ) ); strcpy( Bytes_String[6], NumberToString( ( BytesTotal_ULONG - BytesUsed_ULONG ) ) ); strcpy( Bytes_String[7], NumberToString( Density_ULONG ) ); sprintf( String, GetCatStr( 110, "%s\n%sK\n%s blocks or %s bytes\n%s blocks or %s bytes\n%s blocks or %s bytes\n%ld%%\n%s bytes/block\n%s" ), Device_String, Bytes_String[0] , Bytes_String[1], Bytes_String[2], Bytes_String[3], Bytes_String[4], Bytes_String[5], Bytes_String[6], ( BytesUsed_ULONG / ( BytesTotal_ULONG / 100 ) ), Bytes_String[7], Status_String ); wi_Disk = WindowObject, MUIA_Window_ID, 5, MUIA_Window_Title, GetCatStr( 111, "Device Information" ), MUIA_Window_Menu, MUIV_Window_Menu_NoMenu, WindowContents, VGroup, Child, HGroup, MUIA_Group_SameSize, FALSE, TextFrame, MUIA_Background, MUII_TextBack, Child, tx_TextLeft = TextObject, TextFrame, MUIA_FramePhantomHoriz, TRUE, MUIA_Background, MUII_TextBack, MUIA_Text_Contents, GetCatStr( 112, "Name:\nSize:\nTotal:\nUsed:\nFree:\nFull:\nDensity:\nStatus:" ), MUIA_Text_SetMax, TRUE, End, Child, tx_TextRight = TextObject, TextFrame, MUIA_FramePhantomHoriz, TRUE, MUIA_Background, MUII_TextBack, MUIA_Text_Contents, String, End, End, Child, HGroup, MUIA_Group_SameSize, TRUE, Child, bt_Okay = SimpleButton(GetCatStr( 72, "_Okay" ) ), Child, HSpace(0), Child, HSpace(0), Child, bt_Cancel = SimpleButton(GetCatStr( 73, "_Cancel" ) ), End, End, End; if( !wi_Disk ) Fail(); DoMethod( wi_Disk, MUIM_Notify, MUIA_Window_CloseRequest, TRUE, app_RumorOpus, 2, MUIM_Application_ReturnID, 1 ); DoMethod( bt_Okay, MUIM_Notify, MUIA_Pressed, FALSE, app_RumorOpus, 2, MUIM_Application_ReturnID, 1 ); DoMethod( bt_Cancel, MUIM_Notify, MUIA_Pressed, FALSE, app_RumorOpus, 2, MUIM_Application_ReturnID, 1 ); DoMethod( app_RumorOpus, OM_ADDMEMBER, wi_Disk ); set( wi_Disk, MUIA_Window_Open, TRUE ); set( wi_Disk, MUIA_Window_ActiveObject, bt_Okay ); while ( Running ) { switch ( DoMethod( app_RumorOpus, MUIM_Application_Input, &signal ) ) { case MUIV_Application_ReturnID_Quit: global_QuitProgram = QuitRequester(); if( global_QuitProgram ) Running = FALSE; break; case 1: Running = FALSE; break; } if (signal) Wait(signal); } set( wi_Disk, MUIA_Window_Open, FALSE ); DoMethod( app_RumorOpus, OM_REMMEMBER, wi_Disk ); MUI_DisposeObject( wi_Disk ); free( pid ); } UnLock(lock); } } } /* ** ** Bytes() ** */ char * Bytes ( int side ) { ULONG i, k = 0, Entries_ULONG, Active_LONG, Selection_State, Iconified; char FileName_String[512], String[512], Return_String[256], Size_String[3][21]; BOOL Action_BOOL = FALSE; __aligned struct FileInfoBlock * fib; ULONG Total_ULONG, Files_ULONG = 0, Dirs_ULONG = 0, Size_ULONG = 0; int ErrorNum = 0; if ( global_DirLoaded[side] ) { get( lv_Directory[side], MUIA_List_Active, &Active_LONG ); get( lv_Directory[side], MUIA_List_Entries, &Entries_ULONG ); for ( i = 0; i < Entries_ULONG; i++ ) { DoMethod( lv_Directory[side], MUIM_List_Select, i, MUIV_List_Select_Ask, &Selection_State ); if ( Selection_State == MUIV_List_Select_On ) k++; } if ( k == 0 && Active_LONG != MUIV_List_Active_Off) { k = 1; DoMethod( lv_Directory[side], MUIM_List_Select, Active_LONG, MUIV_List_Select_On, NULL ); } set( ga_Gauge, MUIA_Gauge_Current, 0 ); set( ga_Gauge, MUIA_Gauge_Max, k ); if ( k > 0 ) set( wi_Progress, MUIA_Window_Open, TRUE ); k = 0; for ( i = 0; i < Entries_ULONG; i++ ) { DoMethod( lv_Directory[side], MUIM_List_Select, i, MUIV_List_Select_Ask, &Selection_State ); if ( Selection_State == MUIV_List_Select_On ) { DoMethod( lv_Directory[side], MUIM_List_GetEntry, i, &fib ); sprintf( FileName_String, "%s%s", GetPath( side ), fib -> fib_FileName ); sprintf( String, GetCatStr( 113, "Sizing '%s'..." ), FileName_String ); set( bt_StatusBar, MUIA_Text_Contents, String ); Total_ULONG = 0; if ( fib -> fib_DirEntryType < 0 ) { Total_ULONG = Total_ULONG + fib -> fib_Size; Files_ULONG++; } if (fib->fib_DirEntryType > 0) { ErrorNum = BytesDirectory( FileName_String, &Total_ULONG, &Files_ULONG, &Dirs_ULONG ); Dirs_ULONG++; } Size_ULONG = Size_ULONG + Total_ULONG; k++; set( ga_Gauge, MUIA_Gauge_Current, k ); Action_BOOL = TRUE; } if ( ErrorNum != 0 ) break; } set( wi_Progress, MUIA_Window_Open, FALSE ); if ( Action_BOOL ) { if ( ErrorNum == 0 ) { strcpy( Size_String[0], NumberToString( Size_ULONG ) ); strcpy( Size_String[1], NumberToString( Files_ULONG ) ); strcpy( Size_String[2], NumberToString( Dirs_ULONG ) ); sprintf( Return_String, GetCatStr( 114, "%s Bytes in %s Files and %s Directories" ), Size_String[0], Size_String[1], Size_String[2] ); get( app_RumorOpus, MUIA_Application_Iconified, &Iconified ); if ( Iconified ) { switch ( cfg_Completed ) { case 1: DisplayBeep( 0 ); break; case 2: set( app_RumorOpus, MUIA_Application_Iconified, 0 ); break; } } } else strcpy( Return_String, Error( ErrorNum ) ); return( Return_String ); } } return( NULL ); } /* ** ** Fit() ** */ char * Fit ( int side, BOOL window ) { ULONG i, k = 0, Entries_ULONG, Active_LONG, Selection_State, Iconified; char FileName_String[512], String[512], Return_String[256], Size_String[3][21]; BOOL Action_BOOL = FALSE; __aligned struct FileInfoBlock * fib; struct InfoData * pid; ULONG Total_ULONG, Files_ULONG = 0, Dirs_ULONG = 0, Size_ULONG = 0, BlockSize_ULONG; ULONG BytesTotal_ULONG, BytesUsed_ULONG, FreeBytes_ULONG; BPTR lock; int ErrorNum = 0; if ( global_DirLoaded[Left_Side] && global_DirLoaded[Right_Side] ) { lock = Lock( GetPath( OtherSide( Active_Side ) ), ACCESS_READ ); if ( lock ) { pid = malloc( sizeof( struct InfoData ) ); if ( pid ) { Info( lock, pid ); BlockSize_ULONG = pid -> id_BytesPerBlock; get( lv_Directory[side], MUIA_List_Active, &Active_LONG ); get( lv_Directory[side], MUIA_List_Entries, &Entries_ULONG ); if ( window ) { for ( i = 0; i < Entries_ULONG; i++ ) { DoMethod( lv_Directory[side], MUIM_List_Select, i, MUIV_List_Select_Ask, &Selection_State ); if ( Selection_State == MUIV_List_Select_On ) k++; } if ( k == 0 && Active_LONG != MUIV_List_Active_Off) { k = 1; DoMethod( lv_Directory[side], MUIM_List_Select, Active_LONG, MUIV_List_Select_On, NULL ); } set( ga_Gauge, MUIA_Gauge_Current, 0 ); set( ga_Gauge, MUIA_Gauge_Max, k ); if ( k > 0 ) set( wi_Progress, MUIA_Window_Open, TRUE ); k = 0; } for ( i = 0; i < Entries_ULONG; i++ ) { DoMethod( lv_Directory[side], MUIM_List_Select, i, MUIV_List_Select_Ask, &Selection_State ); if ( Selection_State == MUIV_List_Select_On ) { DoMethod( lv_Directory[side], MUIM_List_GetEntry, i, &fib ); sprintf( FileName_String, "%s%s", GetPath( side ), fib -> fib_FileName ); sprintf( String, GetCatStr( 113, "Sizing '%s'..." ), FileName_String ); set( bt_StatusBar, MUIA_Text_Contents, String ); Total_ULONG = 0; if ( fib -> fib_DirEntryType < 0 ) { if ( ( fib -> fib_Size % BlockSize_ULONG ) > 0 ) Total_ULONG = Total_ULONG + ( ( fib -> fib_Size / BlockSize_ULONG ) + 1 ); else Total_ULONG = Total_ULONG + ( fib -> fib_Size / BlockSize_ULONG ); Files_ULONG++; } if (fib->fib_DirEntryType > 0) { ErrorNum = FitDirectory( FileName_String, &Total_ULONG, &Files_ULONG, &Dirs_ULONG, BlockSize_ULONG ); Dirs_ULONG++; } Size_ULONG = Size_ULONG + Total_ULONG; if ( window ) { k++; set( ga_Gauge, MUIA_Gauge_Current, k ); } Action_BOOL = TRUE; } if ( ErrorNum != 0 ) break; } if ( window ) set( wi_Progress, MUIA_Window_Open, FALSE ); if ( Action_BOOL ) { if ( ErrorNum == 0 ) { BytesTotal_ULONG = ( pid -> id_NumBlocks ) * ( pid -> id_BytesPerBlock ); BytesUsed_ULONG = ( pid -> id_NumBlocksUsed ) * ( pid -> id_BytesPerBlock ); FreeBytes_ULONG = BytesTotal_ULONG - BytesUsed_ULONG; Size_ULONG = ( Size_ULONG + Files_ULONG + Dirs_ULONG ) * BlockSize_ULONG; strcpy( Size_String[0], NumberToString( Size_ULONG ) ); strcpy( Size_String[1], NumberToString( FreeBytes_ULONG ) ); if ( Size_ULONG > FreeBytes_ULONG ) { strcpy( Size_String[2], NumberToString( Size_ULONG - FreeBytes_ULONG ) ); sprintf( Return_String, GetCatStr( 115, "NO! Bytes: %s required, %s available, %s short" ), Size_String[0], Size_String[1], Size_String[2] ); } else { strcpy( Size_String[2], NumberToString( FreeBytes_ULONG - Size_ULONG ) ); sprintf( Return_String, GetCatStr( 116, "YES! Bytes: %s required, %s available, %s to spare" ), Size_String[0], Size_String[1], Size_String[2] ); } } else strcpy( Return_String, Error( ErrorNum ) ); } if ( window ) { get( app_RumorOpus, MUIA_Application_Iconified, &Iconified ); if ( Iconified ) switch ( cfg_Completed ) { case 1: DisplayBeep( 0 ); break; case 2: set( app_RumorOpus, MUIA_Application_Iconified, 0 ); break; } } free( pid ); } UnLock( lock ); } if( Action_BOOL ) return( Return_String ); } return( NULL ); } /* ** ** Expand() ** */ void Expand ( int side ) { char Path_String[512], Expanded_String[512]; char * cptr; if ( global_DirLoaded[side] ) { strcpy( Path_String, GetPath( side ) ); cptr = strrchr( Path_String, ':' ); *cptr = '/'; sprintf( Expanded_String, "ARC:%s", Path_String ); LoadDirectory( Expanded_String, side ); } } /* ** ** Shrink() ** */ void Shrink ( int side ) { char Path_String[512], Shrinked_String[512], Device_String[512], Archives_String[32]; char * cptr; BPTR lock; if ( global_DirLoaded[side] ) { lock = Lock( "ARC:", ACCESS_READ ); if ( lock ) { if ( cfg_PathExpand ) NameFromLock ( lock, Archives_String, sizeof( Archives_String ) ); else strcpy( Archives_String, "ARC:" ); strcpy( Path_String, GetPath( side ) ); if ( strstr( Path_String, Archives_String ) != NULL ) { strcpy( Device_String, Path_String ); cptr = strrchr( Device_String, ':' ); cptr++; *cptr = '\0'; strmid( Path_String, Shrinked_String, ( strlen( Device_String ) + 1 ), ( strlen( Path_String ) ) - ( strlen( Device_String ) ) ); cptr = strchr( Shrinked_String, '/' ); *cptr = ':'; LoadDirectory( Shrinked_String, side ); } UnLock( lock ); } } }
2.125
2
2024-11-18T20:15:35.860944+00:00
2021-10-12T11:49:22
1b9aa71a09030e165d496db370237fdab150289b
{ "blob_id": "1b9aa71a09030e165d496db370237fdab150289b", "branch_name": "refs/heads/main", "committer_date": "2021-10-12T11:49:22", "content_id": "d90317585e30b439ae48bb553c9e1cc7129f97f1", "detected_licenses": [ "MIT" ], "directory_id": "b8ce236cb4734330bc089147e658dc0d7af286ad", "extension": "c", "filename": "A_star.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 401074580, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6829, "license": "MIT", "license_type": "permissive", "path": "/N-Puzzle/A_star.c", "provenance": "stackv2-0033.json.gz:173645", "repo_name": "taiprogramer/ClassicAI", "revision_date": "2021-10-12T11:49:22", "revision_id": "26a85df26631d7f3c3f3745c2c0be5df3c0fa1e2", "snapshot_id": "5a72bd66e15af231c1f79b259cf1655bead0eaf0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/taiprogramer/ClassicAI/26a85df26631d7f3c3f3745c2c0be5df3c0fa1e2/N-Puzzle/A_star.c", "visit_date": "2023-08-21T05:57:27.952300" }
stackv2
// Implement solution for N-Puzzle with A_star algorithm (class: // Best First Search) // A_star means: // - f = (g + h) (min is better) // h: heuristic value (approximation cost from current state to goal) // g: cost from current state to start state // if f equal -> compare g // if g equal -> first-come first-served // This code is written in NeoVim by taiprogramer #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #define MATRIX_SIZE 3 // 3 x 3 matrix (8-puzzle) #define EMPTY_TILE 0 // empty tile notation struct State { int matrix[MATRIX_SIZE][MATRIX_SIZE]; int row, col; // position of empty tile, count from zero }; void set_state(struct State *state, int matrix[][MATRIX_SIZE], int row, int col); bool same_state(struct State s1, struct State s2); void print_state(struct State state); // available actions bool empty_left(struct State state, struct State *new_state); // op_code = 1 bool empty_right(struct State state, struct State *new_state); // op_code = 2 bool empty_up(struct State state, struct State *new_state); // op_code = 3 bool empty_down(struct State state, struct State *new_state); // op_code = 4 // Lookup Table (LUT) bool (*actions[5])(struct State state, struct State *new_state) = { NULL, empty_left, empty_right, empty_up, empty_down}; bool execute_action(struct State state, struct State *new_state, int op_code); struct Node { struct Node *parent; struct State state; int g, h, f; }; struct Node *A_star(struct State start_state, struct State goal_state); int h1(struct State s1, struct State s2); void print_result(struct Node *goal_node); static void *allocations[10000]; static int num_alloc = 0; void cleanup(); int main() { int start_state_matrix[][MATRIX_SIZE] = { {1, 4, 2}, {3, 7, 5}, {6, 8, 0}, }; int goal_state_matrix[][MATRIX_SIZE] = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, }; struct State start_state, goal_state; set_state(&start_state, start_state_matrix, 2, 2); set_state(&goal_state, goal_state_matrix, 0, 0); struct Node *result = A_star(start_state, goal_state); if (result == NULL) puts("I\'m limited by the technology of my time."); print_result(result); cleanup(); return 0; } void set_state(struct State *state, int matrix[][MATRIX_SIZE], int row, int col) { for (int i = 0; i < MATRIX_SIZE; ++i) { for (int j = 0; j < MATRIX_SIZE; ++j) { state->matrix[i][j] = matrix[i][j]; if (matrix[i][j] == 0) { state->row = row; state->col = col; } } } } bool same_state(struct State s1, struct State s2) { for (int i = 0; i < MATRIX_SIZE; ++i) { for (int j = 0; j < MATRIX_SIZE; ++j) { if (s1.matrix[i][j] != s2.matrix[i][j]) return false; } } return true; } void print_state(struct State state) { puts(""); for (int i = 0; i < MATRIX_SIZE; ++i) { for (int j = 0; j < MATRIX_SIZE; ++j) { printf("%d ", state.matrix[i][j]); } puts(""); } puts(""); } bool empty_left(struct State state, struct State *new_state) { // deep copy old state *new_state = state; int row = state.row; int col = state.col; // empty box already on the left if (col == 0) return false; // perform swap new_state->matrix[row][col] = state.matrix[row][col - 1]; new_state->matrix[row][col - 1] = EMPTY_TILE; new_state->col--; return true; } bool empty_right(struct State state, struct State *new_state) { *new_state = state; int row = state.row; int col = state.col; // empty box already on the right if (col == 2) return false; new_state->matrix[row][col] = state.matrix[row][col + 1]; new_state->matrix[row][col + 1] = EMPTY_TILE; new_state->col++; return true; } bool empty_up(struct State state, struct State *new_state) { *new_state = state; int row = state.row; int col = state.col; // empty box already on the top if (row == 0) return false; new_state->matrix[row][col] = state.matrix[row - 1][col]; new_state->matrix[row - 1][col] = EMPTY_TILE; new_state->row--; return true; } bool empty_down(struct State state, struct State *new_state) { *new_state = state; int row = state.row; int col = state.col; // empty box already on the bottom if (row == 2) return false; new_state->matrix[row][col] = state.matrix[row + 1][col]; new_state->matrix[row + 1][col] = EMPTY_TILE; new_state->row++; return true; } bool execute_action(struct State state, struct State *new_state, int op_code) { if (op_code < 1 || op_code > 4) return false; return actions[op_code](state, new_state); } void print_result(struct Node *goal_node) { if (goal_node == NULL) return; print_result(goal_node->parent); print_state(goal_node->state); } int h1(struct State s1, struct State s2) { int count = 0; for (int i = 0; i < MATRIX_SIZE; ++i) { for (int j = 0; j < MATRIX_SIZE; ++j) { if (s1.matrix[i][j] != 0) { if (s1.matrix[i][j] != s2.matrix[i][j]) count++; } } } return count; } bool find_node(struct State state, struct Node *arr[100], int len) { while (len > 0) { struct Node *node = arr[--len]; if (node == NULL) continue; if (same_state(node->state, state)) return true; } return false; } int cmp(const void *a, const void *b) { struct Node *node1 = *((struct Node **)a); struct Node *node2 = *((struct Node **)b); if (node1->f > node2->f) return -1; if (node1->f < node2->f) return 1; return 0; } struct Node *A_star(struct State start_state, struct State goal_state) { struct Node *open[100]; int num_open = 0; struct Node *closed[100]; int num_closed = 0; struct Node *root = malloc(sizeof(struct Node)); allocations[num_alloc++] = root; root->state = start_state; root->parent = NULL; root->g = 0; root->h = h1(start_state, goal_state); root->f = root->g + root->h; open[num_open++] = root; while (num_open > 0) { struct Node *node = open[--num_open]; if (num_closed == 100) return NULL; closed[num_closed++] = node; if (same_state(node->state, goal_state)) return node; // perform actions // left-right-up-down for (int i = 1; i <= 4; ++i) { struct State new_state; if (!execute_action(node->state, &new_state, i)) continue; if (find_node(new_state, closed, num_closed) || find_node(new_state, open, num_open)) continue; struct Node *new_node = malloc(sizeof(struct Node)); allocations[num_alloc++] = new_node; new_node->state = new_state; new_node->parent = node; new_node->g = node->g + 1; new_node->h = h1(new_node->state, goal_state); new_node->f = new_node->g + new_node->h; if (num_open == 100) return NULL; open[num_open++] = new_node; } // perform quick sort desc order qsort(open, num_open, sizeof(struct Node *), cmp); } return NULL; } void cleanup() { while (num_alloc > 0) { free(allocations[--num_alloc]); } }
3.078125
3
2024-11-18T20:15:36.157730+00:00
2018-09-12T13:11:07
1f31f7303912feb27cd853390ece3049ad2e4e86
{ "blob_id": "1f31f7303912feb27cd853390ece3049ad2e4e86", "branch_name": "refs/heads/master", "committer_date": "2018-09-12T13:11:07", "content_id": "d6bd050b51ea25717fa51deeeb36bfdc5d500b8f", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "e5289e0780eee7014a2aa699f9f211590fbb770e", "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": 147675353, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1284, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/h8sx/board/test5.fiber/main.c", "provenance": "stackv2-0033.json.gz:174031", "repo_name": "uchiyama-yasushi/w", "revision_date": "2018-09-12T13:11:07", "revision_id": "0323a5aa450bea7cebfedc72c7977086c4796f3b", "snapshot_id": "2abf502d8a84d896a5546dd04d081b2ad4ec7627", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/uchiyama-yasushi/w/0323a5aa450bea7cebfedc72c7977086c4796f3b/h8sx/board/test5.fiber/main.c", "visit_date": "2020-03-28T03:50:42.574025" }
stackv2
#include <sys/system.h> #include <sys/console.h> #include <sys/shell.h> #include <sys/fiber.h> #include <sys/board.h> #include <1655/timer.h> #include <setjmp.h> #include <string.h> SHELL_COMMAND_DECL (setjmp_test); void board_main (uint32_t arg __attribute__((unused))) { void fiber_test_setup (void); fiber_test_setup (); SHELL_COMMAND_REGISTER (setjmp_test); printf ("sizeof long int: %d\n", sizeof (long int)); printf ("sizeof long long: %d\n", sizeof (long long)); printf ("sizeof long: %d\n", sizeof (long)); printf ("sizeof int: %d\n", sizeof (int)); printf ("sizeof short: %d\n", sizeof (short)); shell_prompt (stdin, stdout); } void board_device_init (uint32_t arg __attribute__((unused))) { timer_init (); } uint32_t board_boot_config () { return CONSOLE_ENABLE | RAM_CHECK | DELAY_CALIBRATE; } void stack_check (const char *); uint32_t setjmp_test (int32_t argc __attribute__((unused)), const char *argv[] __attribute__((unused))) { jmp_buf env; int i; memset (env, 0, sizeof env); stack_check (0); if (!(i = setjmp (env))) { printf ("setjmp %x\n", env[3]); } else { printf ("longjmp (12345)%d\n", i); return 0; } longjmp (env, 12345); printf ("XXX longjmp failed.\n"); return 0; }
2.390625
2
2024-11-18T20:15:36.464043+00:00
2021-08-07T04:36:27
069827ee183fafab0a2ba68e0703e69addd09677
{ "blob_id": "069827ee183fafab0a2ba68e0703e69addd09677", "branch_name": "refs/heads/master", "committer_date": "2021-08-07T04:36:27", "content_id": "c02684f134c28d32b2b7127a805d9c2efe216a90", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "2ca55cfd1b5eeab9c0d530bda247c23ec3800214", "extension": "c", "filename": "freertos.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": 4970, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Src/freertos.c", "provenance": "stackv2-0033.json.gz:174547", "repo_name": "wyfOnePiece/HAL_FreeRTOS_Modbus", "revision_date": "2021-08-07T04:36:27", "revision_id": "2055d05368ee87c6cd8947e1616c364869fbb3fd", "snapshot_id": "ca073a5dd09b4dece40b2fc12eaf9937655a764c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wyfOnePiece/HAL_FreeRTOS_Modbus/2055d05368ee87c6cd8947e1616c364869fbb3fd/Src/freertos.c", "visit_date": "2023-06-30T10:37:28.596651" }
stackv2
/* USER CODE BEGIN Header */ /** ****************************************************************************** * File Name : freertos.c * Description : Code for freertos applications ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "FreeRTOS.h" #include "task.h" #include "main.h" #include "cmsis_os.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "user_mb_app.h" #include "tim.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ extern SPI_HandleTypeDef hspi1; /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN Variables */ osThreadId_t MasterTaskHandle; const osThreadAttr_t MasterTask_attributes = { .name = "MasterTask", .priority = (osPriority_t)osPriorityNormal, .stack_size = 128 * 4}; osThreadId_t SlaveTaskHandle; const osThreadAttr_t SlaveTask_attributes = { .name = "SlaveTask", .priority = (osPriority_t)osPriorityNormal, .stack_size = 128 * 4}; /* USER CODE END Variables */ /* Definitions for SYSTask */ osThreadId_t SYSTaskHandle; const osThreadAttr_t SYSTask_attributes = { .name = "SYSTask", .priority = (osPriority_t)osPriorityNormal-10, .stack_size = 128 * 4}; /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN FunctionPrototypes */ void MasterTask(void *argument); void SlaveTask(void *argument); /* USER CODE END FunctionPrototypes */ void StartSYSTask(void *argument); void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */ /** * @brief FreeRTOS initialization * @param None * @retval None */ void MX_FREERTOS_Init(void) { /* USER CODE BEGIN Init */ HAL_TIM_Base_Start(&htim7); //开启帧率测试 eMBMasterInit(MB_RTU, 3, 115200, MB_PAR_NONE); eMBMasterEnable(); eMBInit(MB_RTU, 0x01, 2, 115200, MB_PAR_NONE); eMBEnable(); /* USER CODE END Init */ /* USER CODE BEGIN RTOS_MUTEX */ /* add mutexes, ... */ /* USER CODE END RTOS_MUTEX */ /* USER CODE BEGIN RTOS_SEMAPHORES */ /* add semaphores, ... */ /* USER CODE END RTOS_SEMAPHORES */ /* USER CODE BEGIN RTOS_TIMERS */ /* start timers, add new ones, ... */ /* USER CODE END RTOS_TIMERS */ /* USER CODE BEGIN RTOS_QUEUES */ /* add queues, ... */ /* USER CODE END RTOS_QUEUES */ /* Create the thread(s) */ /* creation of SYSTask */ SYSTaskHandle = osThreadNew(StartSYSTask, NULL, &SYSTask_attributes); /* USER CODE BEGIN RTOS_THREADS */ /* add threads, ... */ MasterTaskHandle = osThreadNew(MasterTask, NULL, &MasterTask_attributes); SlaveTaskHandle = osThreadNew(SlaveTask, NULL, &SlaveTask_attributes); /* USER CODE END RTOS_THREADS */ /* USER CODE BEGIN RTOS_EVENTS */ /* add events, ... */ /* USER CODE END RTOS_EVENTS */ } /* USER CODE BEGIN Header_StartSYSTask */ /** * @brief Function implementing the SYSTask thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_StartSYSTask */ void StartSYSTask(void *argument) { /* USER CODE BEGIN StartSYSTask */ uint16_t data[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; /* Infinite loop */ for (;;) { //eMBMasterReqReadHoldingRegister(1, 0, 10, 100); eMBMasterReqWriteMultipleHoldingRegister(1, 0, 10, data, 100); HAL_GPIO_TogglePin(LED_2_GPIO_Port, LED_2_Pin); for(uint8_t i=0;i<sizeof(data)/sizeof(uint16_t);i++) data[i]++; osDelay(100); } /* USER CODE END StartSYSTask */ } /* Private application code --------------------------------------------------*/ /* USER CODE BEGIN Application */ void MasterTask(void *argument) { for (;;) { eMBMasterPoll(); } } void SlaveTask(void *argument) { /* USER CODE BEGIN StartDefaultTask */ /* Infinite loop */ for (;;) { eMBPoll(); } /* USER CODE END StartDefaultTask */ } /* USER CODE END Application */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
2.03125
2
2024-11-18T20:15:36.613604+00:00
2020-02-02T22:43:45
cd4b6e817cfc255c9878aa9d06684db33dfcbb27
{ "blob_id": "cd4b6e817cfc255c9878aa9d06684db33dfcbb27", "branch_name": "refs/heads/master", "committer_date": "2020-02-02T22:43:45", "content_id": "4b58c1148ce9077844ddc0651bac2064b91f686b", "detected_licenses": [ "MIT" ], "directory_id": "5ac97c7547ea09b62ef6647daae658d97478caf1", "extension": "h", "filename": "grid_utils.h", "fork_events_count": 8, "gha_created_at": "2017-10-14T19:13:40", "gha_event_created_at": "2019-12-21T18:13:25", "gha_language": "C", "gha_license_id": "MIT", "github_id": 106955573, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3322, "license": "MIT", "license_type": "permissive", "path": "/grid_utils.h", "provenance": "stackv2-0033.json.gz:174677", "repo_name": "Wyatt915/fireplace", "revision_date": "2020-02-02T22:43:45", "revision_id": "aa2070b73be9fb177007fc967b066d88a37e3408", "snapshot_id": "e9030975951070fac43ffabf83ef27784f8ecb45", "src_encoding": "UTF-8", "star_events_count": 67, "url": "https://raw.githubusercontent.com/Wyatt915/fireplace/aa2070b73be9fb177007fc967b066d88a37e3408/grid_utils.h", "visit_date": "2022-04-01T11:44:47.663201" }
stackv2
#ifndef GRIDUTILS_H #define GRIDUTILS_H #ifndef CELL_TYPE #error CELL_TYPE must be defined as a data type before the inclusion of grid_utils.h #endif #include <stdlib.h> #define MIN(X, Y) ((X) < (Y) ? (X) : (Y)) #define MAX(X, Y) ((X) > (Y) ? (X) : (Y)) //Clamp the variable X between the bounds A and B. #define CLAMP(X, A, B) (MAX((A),MIN((X),(B)))) //Gives the ability to treat a 1d array as a 2d array #define IDX(GRID, R, C) ((GRID->data)[(R) * (GRID->cols) + (C)]) /** * Grid structure for celluluar automata */ typedef struct ca_grid{ CELL_TYPE* data; int rows, cols; } ca_grid; /** * Initializes a new grid of cells to be printed in the terminal * @param rows the number of rows in the terminal * @param cols the number of columns in the terminal */ ca_grid* new_grid(size_t rows, size_t cols) { ca_grid* out = malloc(sizeof(ca_grid)); out->data = calloc(rows * cols, sizeof(CELL_TYPE)); out->rows = rows; out->cols = cols; return out; } /** * Frees a grid previously created by the function new_grid * @param rows number of rows in the grid */ void free_grid(ca_grid* grid) { free(grid->data); free(grid); } /** * Copies grid data from src to dest * @param dest the grid into which the data will be copied * @param src the grid from which the data will be copied * @param rows the number of rows to be copied * @param cols the number of columns to be copied */ void copy_grid(ca_grid* dest, ca_grid* src, const size_t rows, const size_t cols){ for(size_t i = 0; i < rows; i++){ for (size_t j = 0; j < cols; j++){ IDX(dest, i, j) = IDX(src, i, j); } } } /** * Resize a grid with a custom copy function. Useful for when the terminal is resized and/or when * a SIGWINCH is caught. A user may wish not to begin copying from the top left of the screen moving * left-to-right. For this reason we allow the user to define their own copy routine and pass it to * this function as a function pointer. * @param grid the grid to be resized * @param old_r the current (old) number of rows * @param old_c the current (old) number of columns * @param new_r the number of rows in the resized grid * @param new_c the number of columns in the resized grid * @param copyfunc a function pointer to a user-defined function to perform the array copying */ void resize_grid_cust(ca_grid** grid, size_t old_r, size_t old_c, size_t new_r, size_t new_c, void (*copyfunc)(ca_grid*, ca_grid*, const size_t, const size_t) ) { ca_grid* resized = new_grid(new_r, new_c); size_t row_copylimit = MIN(old_r, new_r); size_t col_copylimit = MIN(old_c, new_c); copyfunc(resized, *grid, row_copylimit, col_copylimit); free_grid(*grid); *grid = resized; } /** * Resize a grid. Useful for when the terminal is resized and/or when a SIGWINCH is caught * @param grid the grid to be resized * @param old_r the current (old) number of rows * @param old_c the current (old) number of columns * @param new_r the number of rows in the resized grid * @param new_c the number of columns in the resized grid */ void resize_grid(ca_grid** grid, size_t old_r, size_t old_c, size_t new_r, size_t new_c){ resize_grid_cust(grid, old_r, old_c, new_r, new_c, &copy_grid); } #endif /* GRIDUTILS_H */
2.96875
3
2024-11-18T20:15:37.037624+00:00
2017-04-27T09:47:58
fd2024708eb5854d6d0568eff13d7bc8de123823
{ "blob_id": "fd2024708eb5854d6d0568eff13d7bc8de123823", "branch_name": "refs/heads/master", "committer_date": "2017-04-27T09:47:58", "content_id": "e5dab6992147920077150c9d9ce06bf477986a72", "detected_licenses": [ "MIT" ], "directory_id": "5306fb95423ea2cb804cb55cf891900494a326f2", "extension": "c", "filename": "hash.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 81427104, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8185, "license": "MIT", "license_type": "permissive", "path": "/lab7/hash.c", "provenance": "stackv2-0033.json.gz:174934", "repo_name": "Panda-Lewandowski/Types-and-Data-Structures", "revision_date": "2017-04-27T09:47:58", "revision_id": "99bd864b1c7055a7aa956b2080b8daf539242f08", "snapshot_id": "7a93d351b5ff39b5f6e51359c1d98532ead7d731", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Panda-Lewandowski/Types-and-Data-Structures/99bd864b1c7055a7aa956b2080b8daf539242f08/lab7/hash.c", "visit_date": "2021-01-13T05:25:19.817218" }
stackv2
#include "methods.h" //инициализация хеш-таблицы Hash_row **init_hash(int n) { Hash_row **hashtable = (Hash_row**)malloc(n*sizeof(Hash_row*)); for(int i = 0; i < n; i++) hashtable[i] = NULL; return hashtable; } //хеш-функция(суммирует коды всех символов и делит на размер таблицы int hash(char *keyword, int n) { int hashidx = 0, i = 0; while(keyword[i] != '\0') { hashidx += keyword[i]; i++; } hashidx %= n; return hashidx; } //добавление значение в хэш-таблицу методом цепочек void add_open_hash(Hash_row **hashtable, node *temp, int n) { Hash_row *buff = (Hash_row*)malloc(sizeof(Hash_row)); strcpy(buff->keyword, temp->keyword); strcpy(buff->HELP, temp->HELP); int hashidx = hash(temp->keyword, n);//нахождение ключа if(hashtable[hashidx] == NULL)//если нужная ячейка пуста { buff->next = NULL; hashtable[hashidx] = buff; //присоединяем значение } else //иначе { buff->next = hashtable[hashidx]; //присоединяем в начало списка значений hashtable[hashidx] = buff; } } //добавление значения в хэш-таблицу методом открытой адресации int add_closed_hash(Hash_row **hashtable, node *temp, int n) { Hash_row *buff = (Hash_row*)malloc(sizeof(Hash_row)); strcpy(buff->keyword, temp->keyword); strcpy(buff->HELP, temp->HELP); buff->next = NULL; int hashidx = hash(temp->keyword, n), l_idx, r_idx, check = 0; if(hashtable[hashidx] == NULL)//если ячейка пуста { hashtable[hashidx] = buff;//присоединяем значение check = 1; } else { l_idx = r_idx = hashidx; l_idx--; r_idx++; while((l_idx >= 0 && l_idx < n) || (r_idx >= 0 && r_idx < n))//ищем значение ближайшего пустого места { if(l_idx >= 0 && l_idx < n) if(hashtable[l_idx] == NULL)//если слева есть место ближайшее, то все ок { hashtable[l_idx] = buff; check = 1; break; } if(r_idx >= 0 && r_idx < n)//--||-- справа if(hashtable[r_idx] == NULL) { hashtable[r_idx] = buff; check = 1; break; } l_idx--; r_idx++; } } if(!check)//если не нашли, все плохо return ERR_INPUT; else return OK; } //печать хеш-таблицы void print_hashtable(Hash_row **hashtable, int n) { Hash_row *buff = (Hash_row*)malloc(sizeof(Hash_row)); for(int i = 0; i < n; i++) { printf("%d ", i); buff = hashtable[i]; while(buff != NULL) { printf("%s ", buff->keyword); buff = buff->next; } printf("%s", "\n"); } free(buff); } //удаление значения из хеш-таблицы метода цепочек void delete_open_hash(Hash_row **hashtable, char *keyword, int n) { int hashidx = hash(keyword, n), count = 0; Hash_row *buff = (Hash_row*)malloc(sizeof(Hash_row)); buff = hashtable[hashidx]; if(buff->next == NULL)//если одно значение, то ок { if(!strcmp(buff->keyword, keyword)) hashtable[hashidx] = NULL; } while(buff != NULL)//если нет { if(count == 0 && !strcmp(buff->keyword, keyword))//если первое в списке { hashtable[hashidx] = buff->next; break; } else if(!strcmp(buff->keyword, keyword))//если в середине или последнее { buff = hashtable[hashidx]; for(int i = 0; i < count - 1; i++) buff = buff->next; if(buff->next->next == NULL) buff->next = NULL; else buff->next = buff->next->next; } else { count++; buff = buff->next; } } } //удаление значение из хеш-таблицы с методом открытой адресации void delete_closed_hash(Hash_row **hashtable, char *keyword, int n) { int count = 0; int idx = closed_hash_search(hashtable, keyword, n, &count, 1);//ищем значение if(idx >= 0) hashtable[idx] = NULL; } //поиск в таблице методом цепочек void open_hash_search(Hash_row *hashtable, char *keyword, int n, int *count, int mode) { int check = 0, question; Hash_row *buff; buff = hashtable; while(buff != NULL) { *count = *count + 1; if(!strcmp(buff->keyword, keyword)) { check = 1; if(!mode) { printf("Number of comparisons in the open hash-table: %d\n", *count); printf("%s", "The keyword has been found.\n"); printf("HELP: %s\n", buff->HELP); printf("%s", "Rewrite HELP description?\n"); printf("%s", "1 - Yes\n"); printf("%s", "2 - No\n"); scanf("%d", &question); if(question == 1) { printf("%s", "Input HELP description:\n"); fflush(stdin); gets(buff->HELP); } } break; } else buff = buff->next; } if(!mode && !check) { printf("Number of comparisons in the open hash-table: %d\n", *count); printf("%s", "The keyword has not been found.\n"); } } //поиск в хеш-таблице с открытой адресацией int closed_hash_search(Hash_row **hashtable, char *keyword, int n, int *count, int mode) { int hashidx = hash(keyword, n), idx, l_idx, r_idx, check = 0, question = 0; *count = *count + 1; if(!strcmp(hashtable[hashidx]->keyword, keyword)) { idx = hashidx; check = 1; } else { idx = l_idx = r_idx = hashidx; l_idx--; r_idx++; while((l_idx >= 0 && l_idx < n) || (r_idx >= 0 && r_idx < n)) { *count = *count + 1; if(l_idx >= 0 && l_idx < n) if(!strcmp(hashtable[l_idx]->keyword, keyword)) { idx = l_idx; check = 1; break; } *count = *count + 1; if(r_idx >= 0 && r_idx < n) if(!strcmp(hashtable[r_idx]->keyword, keyword)) { idx = r_idx; check = 1; break; } l_idx--; r_idx++; } } if(!mode && !check) { printf("Number of comparisons in the open hash-table: %d\n", *count); printf("%s", "The keyword has not been found.\n"); idx = -1; } else if(!mode) { printf("Number of comparisons in the open hash-table: %d\n", *count); printf("%s", "The keyword has been found.\n"); printf("HELP: %s\n", hashtable[idx]->HELP); printf("%s", "Rewrite HELP description?\n"); printf("%s", "1 - Yes\n"); printf("%s", "2 - No\n"); scanf("%d", &question); if(question == 1) { printf("%s", "Input HELP description:\n"); fflush(stdin); gets(hashtable[idx]->HELP); } } return idx; }
2.9375
3
2024-11-18T20:15:37.131912+00:00
2019-12-16T12:44:05
05ae5ed008d41ad759d18865ec574287a6a4f715
{ "blob_id": "05ae5ed008d41ad759d18865ec574287a6a4f715", "branch_name": "refs/heads/master", "committer_date": "2019-12-16T12:44:05", "content_id": "63f249806276cb83e969469bad5e26169ef58a22", "detected_licenses": [ "MIT" ], "directory_id": "533825a9a4d5e10dc4d96a3978431348c61e35b8", "extension": "c", "filename": "end.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 97133849, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1554, "license": "MIT", "license_type": "permissive", "path": "/firmware/src/end.c", "provenance": "stackv2-0033.json.gz:175062", "repo_name": "256dpi/ThroughMomentum", "revision_date": "2019-12-16T12:44:05", "revision_id": "7027e4fccf589fdd164df1df2d6fa597216289b9", "snapshot_id": "2d044eac838b4a294242b2d153be0cb3f22a8342", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/256dpi/ThroughMomentum/7027e4fccf589fdd164df1df2d6fa597216289b9/firmware/src/end.c", "visit_date": "2023-09-04T14:27:44.917718" }
stackv2
#include <driver/gpio.h> #include <freertos/FreeRTOS.h> #include <freertos/event_groups.h> #include <naos.h> #include "end.h" #define END_DELAY 50 #define END_BIT (1 << 0) static EventGroupHandle_t end_group; static end_callback_t end_callback; static void end_handler(void *args) { // send event xEventGroupSetBitsFromISR(end_group, END_BIT, NULL); } static void end_task(void *p) { // loop forever for (;;) { // wait for bit EventBits_t bits = xEventGroupWaitBits(end_group, END_BIT, pdFALSE, pdFALSE, portMAX_DELAY); if ((bits & END_BIT) != END_BIT) { continue; } // call callback naos_acquire(); end_callback(); naos_release(); // delay next reading naos_delay(END_DELAY); // clear bit xEventGroupClearBits(end_group, END_BIT); } } void end_init(end_callback_t cb) { // save callback end_callback = cb; // create mutex end_group = xEventGroupCreate(); // prepare in a+b config gpio_config_t end = {.pin_bit_mask = GPIO_SEL_13, .mode = GPIO_MODE_INPUT, .pull_up_en = GPIO_PULLUP_DISABLE, .pull_down_en = GPIO_PULLDOWN_DISABLE, .intr_type = GPIO_INTR_POSEDGE}; // configure in a+b pins ESP_ERROR_CHECK(gpio_config(&end)); // register interrupt handler gpio_isr_handler_add(GPIO_NUM_13, &end_handler, NULL); // run async task xTaskCreatePinnedToCore(&end_task, "end", 8192, NULL, 2, NULL, 1); } bool end_read() { return gpio_get_level(GPIO_NUM_13) == 1; }
2.453125
2
2024-11-18T20:15:37.304397+00:00
2018-06-03T12:05:22
827110efd96e31591f2f3c43c31b220e7c2fcb93
{ "blob_id": "827110efd96e31591f2f3c43c31b220e7c2fcb93", "branch_name": "refs/heads/master", "committer_date": "2018-06-03T12:05:22", "content_id": "96bfc334a4565ea6b7ebc78332243040a5893232", "detected_licenses": [ "Zlib" ], "directory_id": "110978b6025d556f32c154ab979c5f0fa8c76af4", "extension": "h", "filename": "frame.h", "fork_events_count": 1, "gha_created_at": "2019-05-01T19:46:42", "gha_event_created_at": "2019-05-01T19:46:42", "gha_language": null, "gha_license_id": "Zlib", "github_id": 184472152, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1093, "license": "Zlib", "license_type": "permissive", "path": "/src/frame.h", "provenance": "stackv2-0033.json.gz:175191", "repo_name": "Mikenno/ModelGen", "revision_date": "2018-06-03T12:05:22", "revision_id": "1e036f2eb9f08219ddd77de0518b68fc9fe2453b", "snapshot_id": "8bfafb85f932efd74eca75d2e4b4aecc6a521728", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Mikenno/ModelGen/1e036f2eb9f08219ddd77de0518b68fc9fe2453b/src/frame.h", "visit_date": "2020-05-18T14:27:20.220213" }
stackv2
#ifndef MODELGEN_STACK_FRAME_H #define MODELGEN_STACK_FRAME_H #include "value.h" #include "types/composite.h" #define _MG_STACK_FRAME_STATES \ _MG_SFS(ACTIVE, "Active") \ _MG_SFS(RETURN, "Return") \ _MG_SFS(BREAK, "Break") \ _MG_SFS(CONTINUE, "Continue") #define _MG_LONGEST_STACK_FRAME_STATE_NAME_LENGTH 9 static char *_MG_STACK_FRAME_STATE_NAMES[] = { #define _MG_SFS(state, name) name, _MG_STACK_FRAME_STATES #undef _MG_SFS }; typedef enum MGStackFrameState { #define _MG_SFS(state, name) MG_STACK_FRAME_STATE_##state, _MG_STACK_FRAME_STATES #undef _MG_SFS } MGStackFrameState; typedef struct MGStackFrame MGStackFrame; typedef struct MGStackFrame { MGStackFrameState state; MGStackFrame *last; MGStackFrame *next; MGValue *module; const MGNode *caller; const char *callerName; MGValue *value; MGValue *locals; } MGStackFrame; #define mgCreateStackFrame(frame, module) mgCreateStackFrameEx(frame, module, mgCreateValueMap(1 << 4)) void mgCreateStackFrameEx(MGStackFrame *frame, MGValue *module, MGValue *locals); void mgDestroyStackFrame(MGStackFrame *frame); #endif
2.046875
2
2024-11-18T20:15:37.573647+00:00
2020-01-20T11:14:30
e951e39d70fac4cd59a1f5f239896008090df043
{ "blob_id": "e951e39d70fac4cd59a1f5f239896008090df043", "branch_name": "refs/heads/master", "committer_date": "2020-01-20T11:14:30", "content_id": "dcd649e4253d61becef993a8339c9bb831c46c12", "detected_licenses": [], "directory_id": "a03e2ad742f8a424bc66745a2a17e7e1e0fd917b", "extension": "h", "filename": "vfs.h", "fork_events_count": 0, "gha_created_at": "2018-03-05T11:19:36", "gha_event_created_at": "2018-03-05T11:19:36", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 123909022, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3600, "license": "", "license_type": "permissive", "path": "/include/sys/vfs.h", "provenance": "stackv2-0033.json.gz:175576", "repo_name": "JakubSzczerbinski/mimiker", "revision_date": "2020-01-20T11:14:30", "revision_id": "60d9312ac7d56f7b5ab404939e3d149ac1ce038b", "snapshot_id": "61b567ff435d5f0a8234cd4020f9cfc69281a618", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JakubSzczerbinski/mimiker/60d9312ac7d56f7b5ab404939e3d149ac1ce038b/include/sys/vfs.h", "visit_date": "2021-06-05T00:50:45.428362" }
stackv2
#ifndef _SYS_VFS_H_ #define _SYS_VFS_H_ #ifdef _KERNEL typedef struct uio uio_t; typedef struct proc proc_t; typedef struct thread thread_t; typedef struct vnode vnode_t; typedef struct stat stat_t; typedef struct statfs statfs_t; typedef struct timeval timeval_t; typedef struct file file_t; /* * vnr (vfs name resolver) is used to convert pathnames to file system vnodes * and is loosely based on NetBSD's namei interface. You can find details in * NAMEI(9). */ typedef enum { VNR_LOOKUP = 0, VNR_CREATE = 1, VNR_DELETE = 2, VNR_RENAME = 3, } vnrop_t; /* Path name component flags */ #define VNR_ISLASTPC 0x00000001 /* this is last component of pathname */ /* * Encapsulation of lookup parameters. */ typedef struct componentname { uint32_t cn_flags; const char *cn_nameptr; /* not NULL-terminated */ size_t cn_namelen; } componentname_t; #define COMPONENTNAME(str) \ (componentname_t) { \ .cn_flags = 0, .cn_nameptr = str, .cn_namelen = strlen(str) \ } bool componentname_equal(const componentname_t *cn, const char *name); /* Kernel interface */ int do_open(proc_t *p, char *pathname, int flags, mode_t mode, int *fd); int do_close(proc_t *p, int fd); int do_read(proc_t *p, int fd, uio_t *uio); int do_write(proc_t *p, int fd, uio_t *uio); int do_lseek(proc_t *p, int fd, off_t offset, int whence, off_t *newoffp); int do_fstat(proc_t *p, int fd, stat_t *sb); int do_dup(proc_t *p, int oldfd, int *newfdp); int do_dup2(proc_t *p, int oldfd, int newfd); int do_fcntl(proc_t *p, int fd, int cmd, int arg, int *resp); int do_unlink(proc_t *p, char *path); int do_mkdir(proc_t *p, char *path, mode_t mode); int do_rmdir(proc_t *p, char *path); int do_ftruncate(proc_t *p, int fd, off_t length); int do_access(proc_t *p, char *path, int amode); int do_chmod(proc_t *p, char *path, mode_t mode); int do_chown(proc_t *p, char *path, int uid, int gid); int do_utimes(proc_t *p, char *path, timeval_t *tptr); int do_stat(proc_t *p, char *path, stat_t *sb); int do_symlink(proc_t *p, char *path, char *link); ssize_t do_readlink(proc_t *p, char *path, char *buf, size_t count); int do_rename(proc_t *p, char *from, char *to); int do_chdir(proc_t *p, char *path); int do_getcwd(proc_t *p, char *buf, size_t *lastp); int do_umask(proc_t *p, int newmask, int *oldmaskp); int do_ioctl(proc_t *p, int fd, u_long cmd, void *data); /* Mount a new instance of the filesystem named fs at the requested path. */ int do_mount(const char *fs, const char *path); int do_statfs(proc_t *p, char *path, statfs_t *buf); int do_getdirentries(proc_t *p, int fd, uio_t *uio, off_t *basep); /* Finds the vnode corresponding to the given path. * Increases use count on returned vnode. */ int vfs_namelookup(const char *path, vnode_t **vp); /* Yield the vnode for an existing entry; or, if there is none, yield NULL. * Parent vnode is locked and held; vnode, if exists, is only held.*/ int vfs_namecreate(const char *path, vnode_t **dvp, vnode_t **vp, componentname_t *cn); /* Both vnode and its parent is held and locked. */ int vfs_namedelete(const char *path, vnode_t **dvp, vnode_t **vp, componentname_t *cn); /* Looks up the vnode corresponding to the pathname and opens it into f. */ int vfs_open(file_t *f, char *pathname, int flags, int mode); /* Finds name of v-node in given directory. */ int vfs_name_in_dir(vnode_t *dv, vnode_t *v, char *buf, size_t *lastp); #endif /* !_KERNEL */ #endif /* !_SYS_VFS_H_ */
2.25
2
2024-11-18T20:15:37.690713+00:00
2023-08-17T21:51:22
b25e570ebabd77b2bb84f1f69a5f6e2cc1a7a348
{ "blob_id": "b25e570ebabd77b2bb84f1f69a5f6e2cc1a7a348", "branch_name": "refs/heads/master", "committer_date": "2023-08-17T21:51:22", "content_id": "bdb01ae8e7a5d1ff7b6a1495f9107dc2a6ffa3d2", "detected_licenses": [ "MIT" ], "directory_id": "80f3b23dce2738ff296d938a16b9f5bc8a7773f2", "extension": "c", "filename": "caxeiro_viajante.c", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 41948152, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3876, "license": "MIT", "license_type": "permissive", "path": "/2019/np-completude/caxeiro_viajante.c", "provenance": "stackv2-0033.json.gz:175706", "repo_name": "ed1rac/AulasEstruturasDados", "revision_date": "2023-08-17T21:51:22", "revision_id": "8e656f846f2de4783aa59dbed8ff57b9b4b48c09", "snapshot_id": "32431334fcbf072a5a5a34124ca54f59d69f8eda", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/ed1rac/AulasEstruturasDados/8e656f846f2de4783aa59dbed8ff57b9b4b48c09/2019/np-completude/caxeiro_viajante.c", "visit_date": "2023-08-31T22:08:25.222803" }
stackv2
/* * Problema do Caixeiro Viajante em C * Utilizando uma matriz de distância para representar um grafo não direcionado. * Objetivo: Encontrar o menor caminho que passe por todos os vértices sem repetir nenhum, e chegar novamente ao vértice de início * * 6 * (4)-----(0) * | \ / \ * | \ 3/ \2 * | \/ \ * 3| /\ (1) * | / 3\ 4/ | * | / \ / | * (3)-----(2) | * | 7 | * | | 3 * -------------- * * * Matriz de Distância * 0 1 2 3 4 * 0 0 2 - 3 6 * 1 2 0 4 3 - * 2 - 4 0 7 3 * 3 3 3 7 0 3 * 4 6 - 3 3 0 * * */ #include <stdio.h> #define VERTICES 5 #define INFINITO 429496729 int tempSolucao[VERTICES]; int melhorSolucao[VERTICES]; int visitados[VERTICES]; int valorMelhorSolucao = INFINITO; int valorSolucaoAtual = 0; int matriz[VERTICES][VERTICES] = {{ 0, 2, INFINITO, 3, 6 }, { 2, 0, 4, 3, INFINITO }, { INFINITO, 4, 0, 7, 3 }, { 3, 3, 7, 0, 3 }, { 6, INFINITO, 3, 3, 0 }}; void caixeiroViajanteAux(int x){ // Se o valor da solução atual já estiver maior que o valor da melhor solução já para, pois já não pode mais ser a melhor solução if( valorSolucaoAtual > valorMelhorSolucao ) return; if( x == VERTICES ){ // Se x == VERTICES significa que o vetor da solução temporária está completo int distancia = matriz[tempSolucao[x-1]][tempSolucao[0]]; // Se encontrou uma solução melhor/menor if( distancia < INFINITO && valorSolucaoAtual + distancia < valorMelhorSolucao ){ valorMelhorSolucao = valorSolucaoAtual + distancia; // Substitui a melhor solução pela melhor encontrada agora // Copia todo o vetor de solução temporária para o vetor de melhor solução encontrada for (int i = 0; i < VERTICES; ++i){ melhorSolucao[i] = tempSolucao[i]; } } return; } int ultimo = tempSolucao[x-1]; // Ultimo recebe o número do último vértice que se encontra na solução temporária // For que percorre todas as colunas da matriz na linha do último vértice do vetor solução temporária for (int i = 0; i < VERTICES; i++){ // Se a posição i do vetor ainda não foi visitada, e se o valor da matriz na posição é menor que INFINITO if( visitados[i] == 0 && matriz[ultimo][i] < INFINITO ){ visitados[i] = 1; // Marca como visitado tempSolucao[x] = i; // Carrega o vértice que está passando no vetor de solução temporária valorSolucaoAtual += matriz[ultimo][i]; // Incrementa o valor da matriz na variável que guarda o total do caminho percorrido caixeiroViajanteAux(x+1); // Chama recursivamente para o próximo vértice valorSolucaoAtual -= matriz[ultimo][i]; // Se ainda não terminou, diminuí o valor da váriavel que guarda o total da solução atual visitados[i] = 0; // Seta como false a posição para poder ser utilizado por outro vértice } } } void caixeiroViajante(int inicial){ visitados[inicial] = 1; // Marca o primeiro vértice como visitado (0) tempSolucao[0] = inicial; // Coloca o vértice 0 na primeira posição do vetor de solução temporária caixeiroViajanteAux(1); // Chama o método auxiliar do caixeiro viajante } void iniciaVetores(){ for (int i = 0; i < VERTICES; i++){ visitados[i] = 0; tempSolucao[i] = -1; melhorSolucao[i] = -1; } } int main(){ iniciaVetores(); caixeiroViajante(0); printf("Caminho mínimo: %d\n", valorMelhorSolucao); for (int i = 0; i < VERTICES; i++){ printf("%d, ", melhorSolucao[i]); } printf("\n\n"); }
3.3125
3
2024-11-18T20:15:37.895525+00:00
2016-01-21T21:54:43
bb2cff3c5e5d5b7e68418a89e8756fdbba68a6f5
{ "blob_id": "bb2cff3c5e5d5b7e68418a89e8756fdbba68a6f5", "branch_name": "refs/heads/master", "committer_date": "2016-01-21T21:54:43", "content_id": "819ca50f7af4429d8c512fabce00de8599dd0067", "detected_licenses": [ "MIT" ], "directory_id": "f05bc64d2d359d7d78c1d34ad6d52bebf549ca81", "extension": "c", "filename": "softbeeb.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 39401166, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 95167, "license": "MIT", "license_type": "permissive", "path": "/turboc/softbeeb.c", "provenance": "stackv2-0033.json.gz:176091", "repo_name": "donald-w/softbeeb", "revision_date": "2016-01-21T21:54:43", "revision_id": "ff9efbd38bca11784e91b2a4b9a939ae024e46fe", "snapshot_id": "5d0b10d6c0859551c3a3923c3ed59fafa1ef7982", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/donald-w/softbeeb/ff9efbd38bca11784e91b2a4b9a939ae024e46fe/turboc/softbeeb.c", "visit_date": "2021-01-10T19:19:40.610249" }
stackv2
#include <stdio.h> #include "header.h" #include "io.h" #include "reg_name.h" #define CLKFREQ 850 // compile time instructions between interrupt counter /* Softbeeb- A BBC Model B Microcomputer for the PC Code begun on 16th December 1995 Designed for Compilation on Turbo C++ For DOS V3.0 Written for CSYS Computing Studies Copyright Donald Walker */ ubyte RAM[0x8000]; // the BBC's ram uint pc=0xD9CD; // where the processor starts execution ubyte acc =0; // ubyte x_reg =0; // initialise registers. ubyte y_reg =0; // ubyte sp =0xFF; // initialise the stack pointer. ubyte dyn_p =0; // the dynamic processor status // update_dyn_p() must be executed // before use of this variable /* update_dyn_p uses these flags to construct the full processor status byte when required i.e. during BRKs, IRQs or PHP's */ ubyte result_f=0; // dual purpose flag holding neg and zero. ubyte ovr_f=0; // sign overflow flag ubyte brk_f=1; // set to zero when an IRQ occurs ubyte dec_f=0; // flag indicating decimal mode operation // (current unsupported) ubyte intd_f=0; // set when interrupts are disabled ubyte carry_f=0; // arithmetic carry flag ubyte except=0; // set for a negative zero condition int main() { uint clock; // local clock counter ubyte ir=0; // holds current instruction system_init(); // initialise everything. for (clock=CLKFREQ;;clock--) // interrupt generation timer { ir=getbyte(pc++); // fetch instruction decode[ir](); // decode and execute the instructon if (!clock) // if an interrupt is due { if (!intd_f) // and if interrupts are enabled, { gen_irq(); // call the interrupt handler clock=CLKFREQ; // and reset interrupt generation timer } else(clock++); // if interrupts are disabled, // increment the clock timer so that // an interrupt occurs when enabled } } } =========================================== ------------------------------------------- ------------------------------------------- =========================================== #include <stdio.h> #include <stdlib.h> #include "header.h" #include "screen.h" unsigned char lang_ROM[0x4000]; // reserve 16K for the language ROM data unsigned char OS_ROM[0x4000]; // reserve 16K for the OS_ROM data void (*screen_byte_P)(ubyte,uint); /* This function is _always_ used to access an address unless it is in the zero page or the stack, then it may be directly accessed in the RAM[] */ unsigned char getbyte(unsigned int address) { if (address<0x8000) return RAM[address]; // If address is below the 32K mark access the RAM if (address<0xC000) return (romsel==0xC?lang_ROM[address-0x8000]:0xFF); // If address is below the 48K mark access the language ROM if ((address>0xFEFF)||(address<0xFC00)) return OS_ROM[address-0xC000]; // If address is outside the 3 pages of memmapped io, // access the OS_ROM return ((address&0xFF00)==0xFE00)?rsheila[(char)(address)]():0xff; } // the address must be in the 3 pages of memmapped io. /* This functions is always used to write to an address unless it is known for certain to exist with the zeropage/stack range. (when it may be accessed directly through the RAM[]). */ void putbyte (unsigned char byte, unsigned int address) { if (address<0x8000) { if (address>=ram_screen_start) // if screen RAM screen_byte_P(byte,address); // output screen data RAM[address]=byte; // update RAM } else if ((address&0xFF00)==0xFE00) wsheila[(char)(address)](byte); else if ((address<0xFC00)||(address>0xFEFF)) { // Since this is an impossible situation, a crash probably has occured // therefore display error and exit printf("\nROM write attempt at %X",address); exit(1); } } void init_mem(void) // initialise the 6502 memory space { FILE *fp1; // misc files pointers FILE *fp2; unsigned int c; // misc loop counter for (c=0;c<0x8000;c++) { RAM[c]=0; // intiialise the 6502 emulator RAM } printf("Opening ROM Image files..."); // display pretty startup status if ((fp1=fopen("data\\os.bin","rb"))==NULL) { printf("\nError: Could not open OS_ROM image."); exit(1); // exit abnormally } if ((fp2=fopen("data\\basic.bin","rb"))==NULL) { printf("\nError: Could not open lang_ROM image."); exit(1); // exit abnormally } printf("Done\n"); // display pretty status status printf("Reading ROM Image data..."); // display pretty startup status for (c=0;c<0x4000;c++) // initialise the ROM blocks { OS_ROM[c]=getc(fp1); // read data from the image files lang_ROM[c]=getc(fp2); // if ((ferror(fp2))||(ferror(fp1))) { printf("\nFatal Error:- Rom image file error"); exit(1); // exit abnormally if there is a file error } } printf("Done\n"); // display pretty startup status printf("Closing ROM Image files..."); fclose(fp1); fclose(fp2); // close the image files printf("Done\n"); } =========================================== ------------------------------------------- ------------------------------------------- =========================================== #include <stdio.h> #include <conio.h> #include <stdlib.h> #include "header.h" #define popbyte() (RAM[0x100+(++sp)]) #define pushbyte(A) (RAM[0x100+sp--]=(A)) #define CLE except=0 void non_opcode(void); // prototype for function occuring when // an illegal opcode is executed void update_flags(void); void update_dyn_p(void); // builds a valid status byte for // stack pushing ubyte temp1 =0; // ubyte temp2 =0; // Misc scratchpad variables for use in ubyte temp3 =0; // decode functions uint tempint=0; void (*decode[256])(void); // array of pointers to decode functions /* The decode logic for individual instructions follows they are not necessarily individually commented since they are generally self explanatory. However some details are common. they take no arguments and return no values operating on global data. However they make extensive use of subfunctions. The name of each function is constructed of the BBC Basic mnemonic and the opcode in hex Due to the possibility of the 'BIT' instruction creating a negative zero condition, and both the negative and zero flags being contained in one variable, in which this condition is unrepresentable, a pseudo flag called except exists. Any instruction which alters the negative and zero flags must clear the except flag using the CLE #define. All instructions which test the negative or zero flags must also check except (where a non zero value indicates a negative zero condition */ void brk_00(void) { brk_f=1; pc++; pushbyte(pc/0x100); pushbyte(pc%0x100); update_dyn_p(); pushbyte(dyn_p); intd_f=1; pc=getbyte(0xFFFE)+(0x100*getbyte(0xFFFF)); } void ora_01(void) { CLE; temp1=(getbyte(pc)+x_reg); acc|=getbyte(RAM[temp1]+0x100*RAM[(char)temp1+1]); result_f=acc; pc++; } void ora_05(void) { CLE; acc|=RAM[getbyte(pc)]; result_f=acc; pc++; } void asl_06(void) { CLE; result_f=RAM[temp2=getbyte(pc)]; carry_f=result_f&0x80; result_f<<=1; RAM[temp2]=result_f; pc++; } void php_08(void) { update_dyn_p(); pushbyte(dyn_p); } void ora_09(void) { CLE; acc|=getbyte(pc); result_f=acc; pc++; } void asl_0A(void) { CLE; carry_f=acc&0x80; acc<<=1; result_f=acc; } void ora_0D(void) { CLE; result_f=acc|=getbyte(getbyte(pc)+0x100*getbyte(pc+1)); pc+=2; } void asl_0E(void) { CLE; tempint=getbyte(pc)+0x100*getbyte(pc+1); result_f=getbyte(tempint); carry_f=result_f&0x80; result_f<<=1; putbyte(result_f,tempint); pc+=2; } void bpl_10(void) { pc++; if (except) return; if (!(result_f&0x80)) pc+=(signed char)(getbyte(pc-1)); } void ora_11(void) { CLE; temp1=getbyte(pc); acc|=getbyte((RAM[temp1]+0x100*RAM[temp1+1])+(ubyte)y_reg); result_f=acc; pc++; } void ora_15(void) { CLE; acc|=RAM[(ubyte)(getbyte(pc)+(ubyte)x_reg)]; result_f=acc; pc++; } void asl_16(void) { CLE; temp2=(getbyte(pc)+(ubyte)x_reg); result_f=RAM[temp2]; carry_f=result_f&0x80; result_f<<=1; RAM[temp2]=result_f; pc++; } void clc_18(void) { carry_f=0; } void ora_19(void) { CLE; acc|=getbyte(getbyte(pc)+(0x100*getbyte(pc+1))+y_reg); result_f=acc; pc+=2; } void ora_1D(void) { CLE; acc|=getbyte(getbyte(pc)+(0x100*getbyte(pc+1))+x_reg); result_f=acc; pc+=2; } void asl_1E(void) { CLE; tempint=getbyte(pc)+0x100*getbyte(pc+1)+x_reg; result_f=getbyte(tempint); carry_f=result_f&0x80; result_f<<=1; putbyte(result_f,tempint); pc+=2; } void jsr_20(void) { pc++; pushbyte(pc/0x100); pushbyte((ubyte)(pc)); pc=(getbyte(pc-1))+(0x100*(getbyte(pc))); } void and_21(void) { CLE; temp1=(getbyte(pc)+x_reg); acc&=getbyte(getbyte(temp1)+0x100*getbyte(temp1+1)); result_f=acc; pc++; } void bit_24(void) { temp1=RAM[getbyte(pc)]; result_f=(acc&temp1); result_f|=(temp1&0x80); ovr_f=temp1&0x40; if ((!(acc&temp1))&&(temp1&0x80)) except=1; pc++; } void and_25(void) { CLE; acc&=RAM[getbyte(pc)]; result_f=acc; pc++; } void rol_26(void) { ubyte oldcar; oldcar=carry_f; CLE; result_f=RAM[temp2=getbyte(pc)]; carry_f=result_f&0x80; result_f<<=1; if (oldcar) result_f++; RAM[temp2]=result_f; pc++; } void plp_28(void) { dyn_p=popbyte(); update_flags(); } void and_29(void) { CLE; acc&=getbyte(pc); result_f=acc; pc++; } void rol_2A(void) { ubyte oldcar; CLE; oldcar=carry_f; carry_f=acc&0x80; acc<<=1; if (oldcar) acc++; result_f=acc; } void bit_2C(void) { temp1=getbyte(getbyte(pc)+(0x100*getbyte(pc+1))); result_f=(acc&temp1); result_f|=(temp1&0x80); ovr_f=temp1&0x40; if ((!(acc&temp1))&&(temp1&0x80)) except=1; pc+=2; } void and_2D(void) { CLE; acc&=getbyte((getbyte(pc))+(0x100*getbyte(pc+1))); result_f=acc; pc+=2; } void rol_2E(void) { ubyte oldcar; CLE; oldcar=carry_f; tempint=getbyte(pc)+0x100*getbyte(pc+1); result_f=getbyte(tempint); carry_f=result_f&0x80; result_f<<=1; if (oldcar) result_f++; putbyte(result_f,tempint); pc+=2; } void bmi_30(void) { pc++; if (except) {pc+=(signed char)(getbyte(pc-1)); return; } if (result_f&0x80) pc+=(signed char)(getbyte(pc-1)); } void and_31(void) { CLE; temp1=getbyte(pc); acc&=getbyte((RAM[temp1]+0x100*RAM[temp1+1])+(ubyte)y_reg); result_f=acc; pc++; } void and_35(void) { CLE; acc&=RAM[(ubyte)(getbyte(pc)+(ubyte)x_reg)]; result_f=acc; pc++; } void rol_36(void) { ubyte oldcar; CLE; oldcar=carry_f; result_f=RAM[temp2=getbyte(pc)+x_reg]; carry_f=result_f&0x80; result_f<<=1; if (oldcar) result_f++; RAM[temp2]=result_f; pc++; } void sec_38(void) { carry_f=1; } void and_39(void) { CLE; acc&=getbyte(getbyte(pc)+(0x100*getbyte(pc+1))+y_reg); result_f=acc; pc+=2; } void and_3D(void) { CLE; acc&=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+y_reg); result_f=acc; pc+=2; } void rol_3E(void) { ubyte oldcar; CLE; oldcar=carry_f; result_f=getbyte(tempint=(getbyte(pc))+(0x100*getbyte(pc+1))+x_reg); carry_f=result_f&0x80; result_f<<=1; if (oldcar) result_f++; putbyte(result_f,tempint); pc+=2; } void rti_40(void) { dyn_p=popbyte(); update_flags(); brk_f=1; pc=popbyte(); pc+=popbyte()*0x100; } void eor_41(void) { CLE; temp1=getbyte(pc)+x_reg; acc^=getbyte(RAM[temp1]+0x100*RAM[temp1+1]); result_f=acc; pc++; } void eor_45(void) { CLE; acc^=RAM[getbyte(pc)]; result_f=acc; pc++; } void lsr_46(void) { CLE; result_f=RAM[temp1=getbyte(pc)]; carry_f=result_f&1; result_f>>=1; RAM[temp1]=result_f; pc++; } void pha_48(void) { pushbyte(acc); } void eor_49(void) { CLE; acc^=getbyte(pc); result_f=acc; pc++; } void lsr_4A(void) { CLE; carry_f=(acc&1); acc>>=1; result_f=acc; } void jmp_4C(void) { pc=getbyte(pc)+0x100*getbyte(pc+1); } void eor_4D(void) { CLE; acc^=getbyte(getbyte(pc)+0x100*getbyte(pc+1)); result_f=acc; pc+=2; } void lsr_4E(void) { CLE; result_f=getbyte(tempint=getbyte(pc)+0x100*getbyte(pc+1)); carry_f=result_f&1; result_f>>=1; putbyte(result_f,tempint); pc+=2; } void bvc_50(void) { pc++; if (ovr_f==0) pc+=(signed char)(getbyte(pc-1)); } void eor_51(void) { CLE; temp1=getbyte(pc); acc^=getbyte((RAM[temp1]+0x100*RAM[temp1+1])+(ubyte)y_reg); result_f=acc; pc++; } void eor_55(void) { CLE; acc^=RAM[(ubyte)(getbyte(pc)+(ubyte)x_reg)]; result_f=acc; pc++; } void lsr_56(void) { CLE; result_f=RAM[temp2=getbyte(pc)+x_reg]; carry_f=result_f&1; result_f>>=1; RAM[temp2]=result_f; pc++; } void cli_58(void) { intd_f=0; } void eor_59(void) { CLE; acc^=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+y_reg); result_f=acc; pc+=2; } void eor_5D(void) { CLE; acc^=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+x_reg); result_f=acc; pc+=2; } void lsr_5E(void) { CLE; result_f=getbyte(tempint=getbyte(pc)+0x100*getbyte(pc+1)+x_reg); carry_f=result_f&1; result_f>>=1; putbyte(result_f,tempint); pc+=2; } void rts_60(void) { pc=popbyte(); pc+=0x100*popbyte(); pc++; } void adc_61(void) { uint flags; uint answer; CLE; temp2=getbyte(pc)+x_reg; temp1=getbyte(RAM[temp2]+0x100*RAM[temp2+1]); asm push ax asm CLC if (carry_f) asm STC; _AL=acc; _AH=temp1; asm adc AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=flags&0x01; pc++; } void adc_65(void) { uint flags; uint answer; CLE; temp1=RAM[getbyte(pc)]; asm push ax asm CLC if (carry_f) asm STC; _AL=acc; _AH=temp1; asm adc AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=flags&0x01; pc++; } void ror_66(void) { ubyte oldcar; CLE; oldcar=carry_f; result_f=RAM[temp2=getbyte(pc)]; carry_f=result_f&1; result_f>>=1; if (oldcar) result_f|=0x80; RAM[temp2]=result_f; pc++; } void pla_68(void) { result_f=acc=popbyte(); } void adc_69(void) { uint flags; uint answer; CLE; temp1=getbyte(pc); asm push ax asm CLC if (carry_f) asm STC; _AL=acc; _AH=temp1; asm adc AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=flags&0x01; pc++; } void ror_6A(void) { ubyte oldcar; CLE; oldcar=carry_f; carry_f=acc&1; acc>>=1; if (oldcar) acc|=0x80; result_f=acc; } void jmp_6C(void) { tempint=getbyte(pc)+0x100*getbyte(pc+1); pc=getbyte(tempint)+0x100*getbyte(tempint+1); } void adc_6D(void) { uint flags; uint answer; CLE; temp1=getbyte(getbyte(pc)+0x100*getbyte(pc+1)); asm push ax asm CLC if (carry_f) asm STC; _AL=acc; _AH=temp1; asm adc AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=(acc=answer); (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=flags&0x01; pc+=2; } void ror_6E(void) { ubyte oldcar; CLE; oldcar=carry_f; result_f=getbyte(tempint=getbyte(pc)+0x100*getbyte(pc+1)); carry_f=result_f&1; result_f>>=1; if (oldcar) result_f|=0x80; putbyte(result_f,tempint); pc+=2; } void bvs_70(void) { pc++; if (ovr_f) pc+=(signed char)(getbyte(pc-1)); } void adc_71(void) { uint flags; uint answer; CLE; temp2=getbyte(pc); temp1=getbyte(RAM[temp2]+0x100*RAM[temp2+1]+y_reg); asm push ax asm CLC if (carry_f) asm STC; _AL=acc; _AH=temp1; asm adc AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=(acc=answer); (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=flags&0x01; pc++; } void adc_75(void) { uint flags; uint answer; CLE; temp1=RAM[(ubyte)(getbyte(pc)+x_reg)]; asm push ax asm CLC if (carry_f) asm STC; _AL=acc; _AH=temp1; asm adc AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=(acc=answer); (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=flags&0x01; pc++; } void ror_76(void) { ubyte oldcar; CLE; oldcar=carry_f; result_f=RAM[temp2=getbyte(pc)+x_reg]; carry_f=result_f&1; result_f>>=1; if (oldcar) result_f|=0x80; RAM[temp2]=result_f; pc++; } void sei_78(void) { intd_f=1; } void adc_79(void) { uint flags; uint answer; CLE; temp1=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+y_reg); asm push ax asm CLC if (carry_f) asm STC; _AL=acc; _AH=temp1; asm adc AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=(acc=answer); (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=flags&1; pc+=2; } void adc_7D(void) { uint flags; uint answer; CLE; temp1=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+x_reg); asm push ax asm CLC if (carry_f) asm STC; _AL=acc; _AH=temp1; asm adc AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=flags&0x01; pc+=2; } void ror_7E(void) { ubyte oldcar; CLE; oldcar=carry_f; result_f=getbyte(tempint=getbyte(pc)+0x100*getbyte(pc+1)+x_reg); carry_f=result_f&1; result_f>>=1; if (oldcar) result_f|=0x80; putbyte(result_f,tempint); pc+=2; } void sta_81(void) { temp1=getbyte(pc)+x_reg; putbyte(acc,RAM[temp1]+0x100*RAM[(ubyte)(temp1+1)]); pc++; } void sty_84(void) { RAM[getbyte(pc)]=y_reg; pc++; } void sta_85(void) { RAM[getbyte(pc)]=acc; pc++; } void stx_86(void) { RAM[getbyte(pc)]=x_reg; pc++; } void dey_88(void) { CLE; --y_reg; result_f=y_reg; } void txa_8A(void) { CLE; result_f=(acc=x_reg); } void sty_8C(void) { putbyte(y_reg,getbyte(pc)+0x100*getbyte(pc+1)); pc+=2; } void sta_8D(void) { putbyte(acc,getbyte(pc)+0x100*getbyte(pc+1)); pc+=2; } void stx_8E(void) { putbyte(x_reg,getbyte(pc)+0x100*getbyte(pc+1)); pc+=2; } void bcc_90(void) { pc++; if (!carry_f) pc+=(signed char)(getbyte(pc-1)); } void sta_91(void) { temp1=getbyte(pc); putbyte(acc,RAM[temp1]+0x100*RAM[(ubyte)(temp1+1)]+y_reg); pc++; } void sty_94(void) { RAM[(ubyte)(getbyte(pc)+x_reg)]=y_reg; pc++; } void sta_95(void) { RAM[(ubyte)(getbyte(pc)+x_reg)]=acc; pc++; } void stx_96(void) { RAM[(unsigned char)(getbyte(pc)+y_reg)]=x_reg; pc++; } void tya_98(void) { CLE; result_f=(acc=y_reg); } void sta_99(void) { putbyte(acc,getbyte(pc)+0x100*getbyte(pc+1)+y_reg); pc+=2; } void txs_9A(void) { sp=x_reg; } void sta_9D(void) { putbyte(acc,getbyte(pc)+0x100*getbyte(pc+1)+x_reg); pc+=2; } void ldy_A0(void) { CLE; result_f=(y_reg=getbyte(pc)); pc++; } void lda_A1(void) { CLE; temp1=getbyte(pc)+x_reg; result_f=(acc=getbyte(RAM[temp1]+0x100*RAM[temp1+1])); pc++; } void ldx_A2(void) { CLE; result_f=(x_reg=getbyte(pc)); pc++; } void ldy_A4(void) { CLE; result_f=(y_reg=RAM[getbyte(pc)]); pc++; } void lda_A5(void) { CLE; result_f=(acc=RAM[getbyte(pc)]); pc++; } void ldx_A6(void) { CLE; result_f=(x_reg=RAM[getbyte(pc)]); pc++; } void tay_A8(void) { CLE; result_f=(y_reg=acc); } void lda_A9(void) { CLE; result_f=(acc=getbyte(pc)); pc++; } void tax_AA(void) { CLE; result_f=(x_reg=acc); } void ldy_AC(void) { CLE; result_f=(y_reg=getbyte(getbyte(pc)+0x100*getbyte(pc+1))); pc+=2; } void lda_AD(void) { CLE; result_f=(acc=getbyte(getbyte(pc)+0x100*getbyte(pc+1))); pc+=2; } void ldx_AE(void) { CLE; result_f=(x_reg=getbyte(getbyte(pc)+0x100*getbyte(pc+1))); pc+=2; } void bcs_B0(void) { pc++; if (carry_f) pc+=(signed char)(getbyte(pc-1)); } void lda_B1(void) { CLE; temp1=getbyte(pc); result_f=(acc=getbyte(RAM[temp1]+0x100*RAM[temp1+1]+y_reg)); pc++; } void ldy_B4(void) { CLE; result_f=(y_reg=RAM[(ubyte)(getbyte(pc)+x_reg)]); pc++; } void lda_B5(void) { CLE; result_f=(acc=RAM[(ubyte)(getbyte(pc)+x_reg)]); pc++; } void ldx_B6(void) { CLE; result_f=(x_reg=RAM[(ubyte)(getbyte(pc)+y_reg)]); pc++; } void clv_B8(void) { ovr_f=0; } void lda_B9(void) { CLE; result_f=(acc=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+y_reg)); pc+=2; } void tsx_BA(void) { CLE; result_f=(x_reg=sp); } void ldy_BC(void) { CLE; result_f=(y_reg=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+x_reg)); pc+=2; } void lda_BD(void) { CLE; result_f=(acc=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+x_reg)); pc+=2; } void ldx_BE(void) { CLE; result_f=(x_reg=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+y_reg)); pc+=2; } void cpy_C0(void) { uint flags; CLE; temp1=getbyte(pc); asm push ax asm CLC if (!carry_f) asm STC; _AL=y_reg; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc++; } void cmp_C1(void) { uint flags; CLE; temp2=getbyte(pc)+x_reg; temp1=getbyte(RAM[temp2]+0x100*RAM[(ubyte)(temp2+1)]); asm push ax asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc++; } void cpy_C4(void) { uint flags; ubyte neartemp; CLE; neartemp=RAM[getbyte(pc)]; asm push ax asm CLC if (!carry_f) asm STC; _AL=y_reg; _AH=neartemp; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc++; } void cmp_C5(void) { uint flags; CLE; temp1=RAM[getbyte(pc)]; asm push ax asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc++; update_dyn_p(); } void dec_C6(void) { CLE; RAM[temp1=getbyte(pc)]--; result_f=RAM[temp1]; pc++; } void iny_C8(void) { CLE; result_f=++y_reg; } void cmp_C9(void) { uint flags; CLE; temp1=getbyte(pc); asm push ax asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc++; } void dex_CA(void) { CLE; x_reg--; result_f=x_reg; } void cpy_CC(void) { uint flags; CLE; temp1=getbyte(getbyte(pc)+0x100*getbyte(pc+1)); asm push ax asm CLC if (!carry_f) asm STC; _AL=y_reg; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc+=2; } void cmp_CD(void) { uint flags; CLE; temp1=getbyte(getbyte(pc)+0x100*getbyte(pc+1)); asm push ax asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc+=2; } void dec_CE(void) { CLE; result_f=getbyte(tempint=getbyte(pc)+0x100*getbyte(pc+1)); result_f--; putbyte(result_f,tempint); pc+=2; } void bne_D0(void) { pc++; if (except) return; if (result_f) pc+=(signed char)(getbyte(pc-1)); } void cmp_D1(void) { uint flags; CLE; temp2=getbyte(pc); temp1=getbyte(RAM[temp2]+0x100*RAM[temp2+1]+y_reg); asm push ax asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc++; } void cmp_D5(void) { uint flags; CLE; temp1=RAM[(ubyte)(getbyte(pc)+x_reg)]; asm push ax asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc++; } void dec_D6(void) { CLE; result_f=RAM[temp1=getbyte(pc)+x_reg]; result_f--; RAM[temp1]=result_f; pc++; } void cld_D8(void) { dec_f=0; } void cmp_D9(void) { uint flags; CLE; temp1=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+y_reg); asm push ax asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc+=2; } void cmp_DD(void) { uint flags; CLE; temp1=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+x_reg); asm push ax asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc+=2; } void dec_DE(void) { CLE; result_f=getbyte(tempint=getbyte(pc)+0x100*getbyte(pc+1)+x_reg); result_f--; putbyte(result_f,tempint); pc+=2; } void cpx_E0(void) { uint flags; CLE; temp1=getbyte(pc); asm push ax asm CLC if (!carry_f) asm STC; _AL=x_reg; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc++; } void sbc_E1(void) { uint flags; uint answer; CLE; temp2=getbyte(pc)+x_reg; temp1=getbyte(RAM[temp2]+0x100*RAM[(ubyte)(temp2+1)]); asm push ax asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm sbb AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=(flags&1)^1; pc++; } void cpx_E4(void) { uint flags; CLE; temp1=RAM[getbyte(pc)]; asm push ax asm CLC if (!carry_f) asm STC; _AL=x_reg; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc++; } void sbc_E5(void) { uint flags; uint answer; CLE; temp1=RAM[getbyte(pc)]; asm push ax asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm sbb AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=(flags&1)^1; pc++; } void inc_E6(void) { CLE; temp1=getbyte(pc); RAM[temp1]++; result_f=RAM[temp1]; pc++; } void inx_E8(void) { CLE; x_reg++; result_f=x_reg; } void sbc_E9(void) { uint flags; uint answer; CLE; temp1=getbyte(pc); asm push ax asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm sbb AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=(flags&1)^1; pc++; } void nop_EA(void) { } void cpx_EC(void) { uint flags; CLE; temp1=getbyte(getbyte(pc)+0x100*getbyte(pc+1)); asm push ax asm CLC if (!carry_f) asm STC; _AL=x_reg; _AH=temp1; asm cmp AL,AH asm pushf asm pop flags asm pop AX carry_f=(flags&1)^1; result_f=flags&0xC0; result_f^=0x40; pc+=2; } void sbc_ED(void) { uint flags; uint answer; asm push ax CLE; temp1=getbyte(getbyte(pc)+0x100*getbyte(pc+1)); asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm sbb AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=(flags&1)^1; pc+=2; } void inc_EE(void) { CLE; result_f=getbyte(tempint=getbyte(pc)+0x100*getbyte(pc+1)); result_f++; putbyte(result_f,tempint); pc+=2; } void beq_F0(void) { pc++; if (except) {pc+=(signed char)(getbyte(pc-1));return;} if (!result_f) pc+=(signed char)(getbyte(pc-1)); } void sbc_F1(void) { uint flags; uint answer; CLE; asm push ax temp2=getbyte(pc); temp1=getbyte(RAM[temp2]+0x100*RAM[(ubyte)(temp2+1)]+y_reg); asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm sbb AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=(flags&0x01)^1; pc++; } void sbc_F5(void) { uint flags; uint answer; CLE; asm push ax temp1=RAM[(ubyte)(getbyte(pc)+x_reg)]; asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm sbb AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=(flags&1)^1; pc++; } void inc_F6(void) { CLE; RAM[temp1=getbyte(pc)+x_reg]++; result_f=RAM[temp1]; pc++; } void sed_F8(void) { dec_f=1; puts("Decimal Mode Not Supported!"); exit(1); } void sbc_F9(void) { uint flags; uint answer; CLE; asm push ax temp1=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+y_reg); asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm sbb AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=(flags&1)^1; pc+=2; } void sbc_FD(void) { uint flags; uint answer; CLE; asm push ax temp1=getbyte(getbyte(pc)+0x100*getbyte(pc+1)+x_reg); asm CLC if (!carry_f) asm STC; _AL=acc; _AH=temp1; asm sbb AL,AH asm pushf asm pop flags asm push AX asm pop answer asm pop AX result_f=acc=answer; (flags&0x800)?(ovr_f=1):(ovr_f=0); carry_f=(flags&1)^1; pc+=2; } void inc_FE(void) { CLE; result_f=getbyte(tempint=getbyte(pc)+0x100*getbyte(pc+1)+x_reg); result_f++; putbyte(result_f,tempint); pc+=2; } /* Not a 6502 instruction, but is used in place of opcode 0xFF, which is undefined. Thus when this is excuted it ends execution. This is useful for writing small test programs, and means that the exact number of instructions to be executed doens't have to be calculated. */ void exitprog_FF(void) { puts("\n_____________________________________\n"); puts("\nExecution Terminated with opcode 0xFF"); exit(0); } void init_decode(void) // Initialises the array of decode functions { int c=0; // misc counter printf("Init Decode Array..."); // display pretty startup status. for (;c<256;c++) // { // Initialise all pointers to a decode[c]=non_opcode; // function dealing with illegal } // opcodes // initialise specific locations in the array with a pointer // to the relevant function. decode[0x00]=brk_00; decode[0x01]=ora_01; decode[0x05]=ora_05; decode[0x06]=asl_06; decode[0x08]=php_08; decode[0x09]=ora_09; decode[0x0A]=asl_0A; decode[0x0D]=ora_0D; decode[0x0E]=asl_0E; decode[0x10]=bpl_10; decode[0x11]=ora_11; decode[0x15]=ora_15; decode[0x16]=asl_16; decode[0x18]=clc_18; decode[0x19]=ora_19; decode[0x1D]=ora_1D; decode[0x1E]=asl_1E; decode[0x20]=jsr_20; decode[0x21]=and_21; decode[0x24]=bit_24; decode[0x25]=and_25; decode[0x26]=rol_26; decode[0x28]=plp_28; decode[0x29]=and_29; decode[0x2A]=rol_2A; decode[0x2C]=bit_2C; decode[0x2D]=and_2D; decode[0x2E]=rol_2E; decode[0x30]=bmi_30; decode[0x31]=and_31; decode[0x35]=and_35; decode[0x36]=rol_36; decode[0x38]=sec_38; decode[0x39]=and_39; decode[0x3D]=and_3D; decode[0x3E]=rol_3E; decode[0x40]=rti_40; decode[0x41]=eor_41; decode[0x45]=eor_45; decode[0x46]=lsr_46; decode[0x48]=pha_48; decode[0x49]=eor_49; decode[0x4A]=lsr_4A; decode[0x4C]=jmp_4C; decode[0x4D]=eor_4D; decode[0x4E]=lsr_4E; decode[0x50]=bvc_50; decode[0x51]=eor_51; decode[0x55]=eor_55; decode[0x56]=lsr_56; decode[0x59]=eor_59; decode[0x5D]=eor_5D; decode[0x5E]=lsr_5E; decode[0x58]=cli_58; decode[0x60]=rts_60; decode[0x61]=adc_61; decode[0x65]=adc_65; decode[0x66]=ror_66; decode[0x68]=pla_68; decode[0x69]=adc_69; decode[0x6A]=ror_6A; decode[0x6C]=jmp_6C; decode[0x6D]=adc_6D; decode[0x6E]=ror_6E; decode[0x70]=bvs_70; decode[0x71]=adc_71; decode[0x75]=adc_75; decode[0x76]=ror_76; decode[0x78]=sei_78; decode[0x79]=adc_79; decode[0x7D]=adc_7D; decode[0x7E]=ror_7E; decode[0x81]=sta_81; decode[0x84]=sty_84; decode[0x85]=sta_85; decode[0x86]=stx_86; decode[0x88]=dey_88; decode[0x8A]=txa_8A; decode[0x8C]=sty_8C; decode[0x8D]=sta_8D; decode[0x8E]=stx_8E; decode[0x90]=bcc_90; decode[0x91]=sta_91; decode[0x94]=sty_94; decode[0x95]=sta_95; decode[0x96]=stx_96; decode[0x98]=tya_98; decode[0x99]=sta_99; decode[0x9A]=txs_9A; decode[0x9D]=sta_9D; decode[0xA0]=ldy_A0; decode[0xA1]=lda_A1; decode[0xA2]=ldx_A2; decode[0xA4]=ldy_A4; decode[0xA5]=lda_A5; decode[0xA6]=ldx_A6; decode[0xA8]=tay_A8; decode[0xA9]=lda_A9; decode[0xAA]=tax_AA; decode[0xAC]=ldy_AC; decode[0xAD]=lda_AD; decode[0xAE]=ldx_AE; decode[0xB0]=bcs_B0; decode[0xB1]=lda_B1; decode[0xB4]=ldy_B4; decode[0xB5]=lda_B5; decode[0xB6]=ldx_B6; decode[0xB8]=clv_B8; decode[0xB9]=lda_B9; decode[0xBA]=tsx_BA; decode[0xBC]=ldy_BC; decode[0xBD]=lda_BD; decode[0xBE]=ldx_BE; decode[0xC0]=cpy_C0; decode[0xC1]=cmp_C1; decode[0xC4]=cpy_C4; decode[0xC5]=cmp_C5; decode[0xC6]=dec_C6; decode[0xC8]=iny_C8; decode[0xC9]=cmp_C9; decode[0xCA]=dex_CA; decode[0xCC]=cpy_CC; decode[0xCD]=cmp_CD; decode[0xCE]=dec_CE; decode[0xD0]=bne_D0; decode[0xD1]=cmp_D1; decode[0xD5]=cmp_D5; decode[0xD6]=dec_D6; decode[0xD8]=cld_D8; decode[0xD9]=cmp_D9; decode[0xDD]=cmp_DD; decode[0xDE]=dec_DE; decode[0xE0]=cpx_E0; decode[0xE1]=sbc_E1; decode[0xE4]=cpx_E4; decode[0xE5]=sbc_E5; decode[0xE6]=inc_E6; decode[0xE8]=inx_E8; decode[0xEA]=nop_EA; decode[0xEC]=cpx_EC; decode[0xED]=sbc_ED; decode[0xEE]=inc_EE; decode[0xE9]=sbc_E9; decode[0xF0]=beq_F0; decode[0xF1]=sbc_F1; decode[0xF5]=sbc_F5; decode[0xF6]=inc_F6; decode[0xF8]=sed_F8; decode[0xF9]=sbc_F9; decode[0xFD]=sbc_FD; decode[0xFE]=inc_FE; decode[0xFF]=exitprog_FF; printf("Done\n"); // display pretty startup status } void non_opcode(void) // functions to deal with illegal opcode { printf("\nInvalid Opcode Error.\nProgram Execution terminated."); printf("\nOpcode=%2X Address=%4X",getbyte(pc-1),pc-1); exit(1); } void update_dyn_p(void) // build valid processor status byte // for pushing { dyn_p=0x20; // bit 5 is always set in the status byte dyn_p|=(result_f&0x80); // if (ovr_f) dyn_p|=0x40; // if (brk_f) dyn_p|=0x10; // if (dec_f) dyn_p|=0x08; // set the relevant bit in the status byte if (intd_f) dyn_p|=0x04; // for each flag if (!result_f) dyn_p|=0x02; // if (carry_f) dyn_p|=0x01; // if (except) dyn_p|=0x82; } void update_flags(void) // update the flags depending on dyn_p { result_f=(dyn_p&0x82)^2; carry_f=dyn_p&0x01; intd_f=dyn_p&0x04; dec_f=dyn_p&0x08; brk_f=dyn_p&0x10; ovr_f=dyn_p&0x40; if ((dyn_p&0x82)==0x82) except=1; } void irq(void) { brk_f=0; update_dyn_p(); pushbyte(pc/0x100); pushbyte((ubyte)(pc)); pushbyte(dyn_p); intd_f=1; pc=getbyte(0xFFFE)+0x100*getbyte(0xFFFF); }=========================================== ------------------------------------------- ------------------------------------------- =========================================== #include<stdio.h> #include "header.h" #include "reg_name.h" #include "io.h" ubyte (*rsheila[256])(void); // array of pointers to i/o handling funcs ubyte current_latch; // last value sent to latch ubyte s_via_opa=0; // system via output port a ubyte s_via_ipa=0; // system via input port a ubyte s_via_opb=0; // system via output port b ubyte s_via_ipb=0; // system via input port b /* The following functions { of the form s??loc() } return the value ??. These are used in memory mapped locations which always return a constant value (to the best of my knowledge). */ ubyte s00loc() { return 0x00; } ubyte s02loc() { return 0x02; } ubyte s10loc() { return 0x10; } ubyte s20loc() { return 0x20; } ubyte s28loc() { return 0x28; } ubyte s9Dloc() { return 0x9D; } ubyte sABloc() { return 0xAB; } ubyte sB7loc() { return 0xB7; } ubyte sFEloc() { return 0xFE; } ubyte sFFloc() { return 0xFF; } // Return the values of crt_regs 14,15,16,17 decimal else return 0 ubyte crt_reg(void) { if ((crt_sel>17)||(crt_sel<14)) return 0; return crt_regs[crt_sel]; } /****************************************************** ******************************************************/ /* Functions of the form ubyte sr_via_?(void) are used when reading from the system via. with ? representing the register in hexadecimal. */ ubyte sr_via_0(void) { return 0xF0|current_latch; // return the last value sent to latch } ubyte sr_via_1(void) { if ((current_key)&&(s_via_opa==current_key)) return (current_key|0x80); if ((s_via_opa==0)&&(current_shift)) return 0x80; if ((s_via_opa==1)&&(current_control)) return 0x81; return s_via_opa; } ubyte sr_via_2(void) { return s_via[DDRB]; } ubyte sr_via_3(void) { return s_via[DDRA]; } ubyte sr_via_4(void) { return 0; } ubyte sr_via_5(void) { return 0; } ubyte sr_via_6(void) { return 0; } ubyte sr_via_7(void) { return 0; } ubyte sr_via_8(void) { return 0; } ubyte sr_via_9(void) { return 0; } ubyte sr_via_A(void) { return 0; } ubyte sr_via_B(void) { return 0; } ubyte sr_via_C(void) { return 0; } ubyte sr_via_D(void) { return (s_via[IFR]); } ubyte sr_via_E(void) { return (s_via[IER]|0x80); } ubyte sr_via_F(void) { return sr_via_1(); } /* This function initialises all the pointers to functions for the io read function. First it fills all locations with a warning that no return function is defined. Then fills the locations with suitable i/o handling functions relevant to the specific address. */ void rinit_io(void) { unsigned int c; printf("Init read IO system..."); // display pretty startup status for (c=0;c<=0xFF;c++) { rsheila[c]=s00loc; } for (c=0x00;c<=0x07;c+=2) { rsheila[c]=s00loc; rsheila[c+1]=crt_reg; } for (c=0x08;c<=0xF;c+=2) { rsheila[c]=s02loc; rsheila[c+1]=sFFloc; } for (c=0x10;c<=0x17;c++) { rsheila[c]=s00loc; } for (c=0x18;c<=0x1F;c++) { rsheila[c]=sB7loc; } for (c=0x20;c<=0x3F;c++) { rsheila[c]=sFEloc; } rsheila[0x50]=rsheila[0x40]=sr_via_0; rsheila[0x51]=rsheila[0x41]=sr_via_1; rsheila[0x52]=rsheila[0x42]=sr_via_2; rsheila[0x53]=rsheila[0x43]=sr_via_3; rsheila[0x54]=rsheila[0x44]=sr_via_4; rsheila[0x55]=rsheila[0x45]=sr_via_5; rsheila[0x56]=rsheila[0x46]=sr_via_6; rsheila[0x57]=rsheila[0x47]=sr_via_7; rsheila[0x58]=rsheila[0x48]=sr_via_8; rsheila[0x59]=rsheila[0x49]=sr_via_9; rsheila[0x5A]=rsheila[0x4A]=sr_via_A; rsheila[0x5B]=rsheila[0x4B]=sr_via_B; rsheila[0x5C]=rsheila[0x4C]=sr_via_C; rsheila[0x5D]=rsheila[0x4D]=sr_via_D; rsheila[0x5E]=rsheila[0x4E]=sr_via_E; rsheila[0x5F]=rsheila[0x4F]=sr_via_F; for (c=0x60;c<=0x7F;c++) { rsheila[c]=s00loc; } for (c=0x80;c<=0x9F;c+=8) { rsheila[c+0]=s00loc; rsheila[c+1]=sFFloc; rsheila[c+2]=s9Dloc; rsheila[c+3]=sFFloc; rsheila[c+4]=sABloc; rsheila[c+5]=sABloc; rsheila[c+6]=sABloc; rsheila[c+7]=sABloc; } for (c=0xA0;c<=0xBF;c+=4) { rsheila[c+0]=s10loc; rsheila[c+1]=s20loc; rsheila[c+2]=s28loc; rsheila[c+3]=s28loc; } for (c=0xC0;c<=0xDF;c++) { rsheila[c]=s00loc; } for (c=0xE0;c<=0xFF;c++) { rsheila[c]=sFEloc; } printf("Done\n"); // display pretty startup status } =========================================== ------------------------------------------- ------------------------------------------- =========================================== #include <stdio.h> #include <stdlib.h> #include <graphics.h> #include "header.h" #include "screen.h" #include "reg_name.h" #include "io.h" void (*wsheila[256])(ubyte); // array of pointers to functions for io-write // decoding void flash(void); // prototype for flash function ubyte adc_control=0; // analogue digital control register ubyte vid_con_reg=0; // video ULA control register ubyte crt_sel=0; // crt register select register ubyte crt_regs[18]; // array of crt register ubyte romsel=0; // paged rom select register ubyte s_via[16]; // array of system via registers ubyte s_via_latch[8]; // the system via latch ubyte vidpal[16]; // the video palette /******************************************************** --------------------------------------------------------- ********************************************************/ void donald(void) { puts("Donald"); } void nullwrite() { } void write_crt(ubyte iobyte) // crt controller write decode function { if (crt_sel<=15) // if a valid register for writing to { crt_regs[crt_sel]=iobyte; // write to the register } switch (crt_sel) // take relevant action depending on // register action { case 1: set_colour_bits(); case 12: break; case 13: if (teletext) { screen_start=crt_regs[12]*0x100+crt_regs[13]; screen_start=0x7400+(screen_start^0x2000); update_screen(); } else { screen_start=crt_regs[12]*0x100+crt_regs[13]; screen_start<<=3; update_screen(); } break; case 14: break; case 15: update_cursor();break; // if the cursor address has changed, } // update the cursor. } void crt_select(ubyte iobyte) // crt register select function { crt_sel=iobyte; } void vid_ULA(ubyte iobyte) // Video ULA control register { ubyte tempbits; ubyte flashstate; flashstate=vid_con_reg&1; // initial flash state vid_con_reg=iobyte; // update control register if (!(iobyte&2)&&teletext) // if 1-0 transition on the teletext select { // initialise graphics teletext=0; pixel_vid_init(); } if ((iobyte&2)&&(!teletext)) // if 0-1 transition on the teletext select { // initialise teletext teletext=1; teletext_init(); } tempbits=disp_chars; // initial number of display characters switch (vid_con_reg&0xC) { case 0x00: disp_chars=10 ; break; case 0x04: disp_chars=20 ; break; case 0x08: disp_chars=40 ; break; case 0x0C: disp_chars=80 ; break; } // if displayed characters change, set_colour_bits() if (tempbits!=disp_chars) set_colour_bits(); // if flash state has changed, flash() if ((flashstate!=(vid_con_reg&1))&&(!teletext)) flash(); } void vidpalset(ubyte iobyte) // video palette update functions { ubyte logical_colour; ubyte actual_colour; ubyte pc_colour; logical_colour=iobyte/0x10; // calculate logical colour actual_colour=iobyte&0xF; // calculate actual programmed colour vidpal[logical_colour]=actual_colour; // update vidpal copy of palette switch(actual_colour^0x7) // convert actual colour to { // pc colour case 0: pc_colour=EGA_BLACK ;break; case 1: pc_colour=EGA_RED ;break; case 2: pc_colour=EGA_GREEN ;break; case 3: pc_colour=EGA_YELLOW ;break; case 4: pc_colour=EGA_BLUE ;break; case 5: pc_colour=EGA_MAGENTA ;break; case 6: pc_colour=EGA_CYAN ;break; case 7: pc_colour=EGA_WHITE ;break; case 8: pc_colour=EGA_BLACK ;break; case 9: pc_colour=EGA_RED ;break; case 10: pc_colour=EGA_GREEN ;break; case 11: pc_colour=EGA_YELLOW ;break; case 12: pc_colour=EGA_BLUE ;break; case 13: pc_colour=EGA_MAGENTA;break; case 14: pc_colour=EGA_CYAN ;break; case 15: pc_colour=EGA_WHITE ;break; } setpalette(logical_colour,pc_colour); // update pc palette } void promsel(ubyte iobyte) // paged rom select write function { romsel=iobyte; } /****************************************************** ******************************************************/ /* Functions of the form "void sw_via_?(ubyte)" are the system via register decodes functions */ void sw_via_0(ubyte iobyte) { s_via[ORB]=iobyte; current_latch=s_via_opb=iobyte&s_via[DDRB]; if (iobyte==0) iobyte=0; s_via_latch[s_via_opb&7]=s_via_opb&8; iobyte&=7; if ((iobyte==4)||(iobyte==5)) if (!teletext) set_screen_start(); if (iobyte==0) sound_byte(s_via_opa); } void sw_via_1(ubyte iobyte) { s_via[ORA]=iobyte; s_via_opa=iobyte&s_via[DDRA]; if (s_via_latch[3]==0) if (current_key) if ((current_key&0xF)==(s_via_opa&0xF)) s_via[IFR]|=1; } void sw_via_2(ubyte iobyte) { s_via[DDRB]=iobyte; s_via_opb=iobyte&s_via[ORB]; } void sw_via_3(ubyte iobyte) { s_via[DDRA]=iobyte; s_via_opa=iobyte&s_via[ORA]; } void sw_via_4(ubyte iobyte) { s_via[T1C_L]=iobyte; } void sw_via_5(ubyte iobyte) { s_via[T1C_H]=iobyte; } void sw_via_6(ubyte iobyte) { s_via[T1L_L]=iobyte; } void sw_via_7(ubyte iobyte) { s_via[T1L_H]=iobyte; } void sw_via_8(ubyte iobyte) { s_via[T2C_L]=iobyte; } void sw_via_9(ubyte iobyte) { s_via[T2C_H]=iobyte; } void sw_via_A(ubyte iobyte) { s_via[SR]=iobyte; } void sw_via_B(ubyte iobyte) { s_via[ACR]=iobyte; } void sw_via_C(ubyte iobyte) { s_via[PCR]=iobyte; } void sw_via_D(ubyte iobyte) { s_via[IFR]=((s_via[IFR]|iobyte)^iobyte); } void sw_via_E(ubyte iobyte) { (iobyte&0x80)?(s_via[IER]|=iobyte):(s_via[IER]=((s_via[IER]|iobyte)^iobyte)); s_via[IER]|=0x80; } void sw_via_F(ubyte iobyte) { sw_via_1(iobyte); } /****************************************************** ******************************************************/ void adc_con_reg(ubyte iobyte) // adc_control is never used { // but a copy is kept for debugging adc_control=iobyte; // purposes } void winit_io(void) // Called to do any io_write initialising { unsigned int c; // misc loop counter printf("Init write IO system..."); // Display pretty startup info for (c=0;c<=17;c++) crt_regs[c]=0; // initialise the arrays to 0 for (c=0;c<=15;c++) s_via[c]=0; for (c=0;c<=7;c++) s_via_latch[c]=0; for (c=0x00;c<=0xFF;c++) // initialise wsheila to point to a { // dummy function wsheila[c]=nullwrite; } for (c=0x00;c<=0x07;c+=2) { wsheila[c]=crt_select; wsheila[c+1]=write_crt; } for (c=0x20;c<=0x2F;c+=0x02) { wsheila[c]=vid_ULA; wsheila[c+1]=vidpalset; } for (c=0x30;c<=0x3F;c++) { wsheila[c]=promsel; } wsheila[0x50]=wsheila[0x40]=sw_via_0; wsheila[0x51]=wsheila[0x41]=sw_via_1; wsheila[0x52]=wsheila[0x42]=sw_via_2; wsheila[0x53]=wsheila[0x43]=sw_via_3; wsheila[0x54]=wsheila[0x44]=sw_via_4; wsheila[0x55]=wsheila[0x45]=sw_via_5; wsheila[0x56]=wsheila[0x46]=sw_via_6; wsheila[0x57]=wsheila[0x47]=sw_via_7; wsheila[0x58]=wsheila[0x48]=sw_via_8; wsheila[0x59]=wsheila[0x49]=sw_via_9; wsheila[0x5A]=wsheila[0x4A]=sw_via_A; wsheila[0x5B]=wsheila[0x4B]=sw_via_B; wsheila[0x5C]=wsheila[0x4C]=sw_via_C; wsheila[0x5D]=wsheila[0x4D]=sw_via_D; wsheila[0x5E]=wsheila[0x4E]=sw_via_E; wsheila[0x5F]=wsheila[0x4F]=sw_via_F; for (c=0xC0;c<=0xDF;c+=0x04) { wsheila[c]=adc_con_reg; } printf("Done\n"); // display pretty startup status } void flash(void) { // flash function, alternates the flash colours ubyte c; // depending on the video ULA control register ubyte d; for (c=0;c<16;c++) // loop through each logical colour if (vidpal[c]&8) { if (vid_con_reg&1) { switch ((vidpal[c]&7)^7) { case 0: d=EGA_WHITE ;break; case 1: d=EGA_CYAN ;break; case 2: d=EGA_MAGENTA ;break; case 3: d=EGA_BLUE ;break; case 4: d=EGA_YELLOW ;break; case 5: d=EGA_GREEN ;break; case 6: d=EGA_RED ;break; case 7: d=EGA_BLACK ;break; } setpalette(c,d); // update pc palette } else { switch ((vidpal[c]&7)^7) { case 0: d=EGA_BLACK ;break; case 1: d=EGA_RED ;break; case 2: d=EGA_GREEN ;break; case 3: d=EGA_YELLOW ;break; case 4: d=EGA_BLUE ;break; case 5: d=EGA_MAGENTA ;break; case 6: d=EGA_CYAN ;break; case 7: d=EGA_WHITE ;break; } setpalette(c,d); // update pc palette } } }=========================================== ------------------------------------------- ------------------------------------------- =========================================== #include <stdio.h> #include <conio.h> #include <bios.h> #include <dos.h> #include "header.h" #include "io.h" #include "reg_name.h" #define SHIFT current_shift=1 #define CLEAR current_shift=0 ubyte current_key=0; ubyte current_shift=0; ubyte current_control=0; void vert_sync(void); void getkey(void); void gen_irq(void) { // Main interrupt generation and handler routine static type_counter=0; getkey(); // Check for key input and convert pc // keypress to BBC internal keynumber if (!intd_f) // if interrupts are enabled { type_counter++; // step through different interrupt types switch(type_counter) { case 1: case 2: if (s_via[IER]&0x40) {s_via[IFR]|=0xC0; irq();} else s_via[IFR]|=0x40; break; // 100 Hz interrupt case 3: if (s_via[IER]&0x02) {s_via[IFR]|=0x82; irq();} else s_via[IFR]|=0x02; type_counter=0; // 50 Hz vertical blank interrupt break; } } } void getkey(void) { uint pc_scan_code; static uint old_scan_code; static ubyte pressed=0; // If no key is pressed, if (!pressed) { // get the shift status current_shift=(_bios_keybrd(_KEYBRD_SHIFTSTATUS)&3); } if (_bios_keybrd(_KEYBRD_READY)) { // if a keystroke is waiting if (!pressed) { // and if not key is being processed // Synchronise BBC and PC capslock switch((peekb(0,0x417)&0x40)|s_via_latch[6]) { case 0x48: case 0x00: current_key=0x40; goto caps_lock_pressed; } // get pc keystroke pc_scan_code=_bios_keybrd(_KEYBRD_READ); pressed=7; // hold the key for 7 interrupts switch (pc_scan_code&0xff) { /********************************************** Keyboard Translation statements **********************************************/ case 0x8: current_key=0x59;CLEAR;break; case 0x9: current_key=0x60;CLEAR;break; case 0xD: current_key=0x49;CLEAR;break; case 0x1B: current_key=0x70;CLEAR;break; case ' ': current_key=0x62;CLEAR;break; case '!': current_key=0x30;SHIFT;break; case '"': current_key=0x31;SHIFT;break; case '#': current_key=0x11;SHIFT;break; case '$': current_key=0x12;SHIFT;break; case '%': current_key=0x13;SHIFT;break; case '&': current_key=0x34;SHIFT;break; case '\'': current_key=0x24;SHIFT;break; case '(': current_key=0x15;SHIFT;break; case ')': current_key=0x26;SHIFT;break; case '*': current_key=0x48;SHIFT;break; case '+': current_key=0x57;SHIFT;break; case ',': current_key=0x66;CLEAR;break; case '-': current_key=0x17;CLEAR;break; case '.': current_key=0x67;CLEAR;break; case '/': current_key=0x68;CLEAR;break; case '0': current_key=0x27;CLEAR;break; case '1': current_key=0x30;CLEAR;break; case '2': current_key=0x31;CLEAR;break; case '3': current_key=0x11;CLEAR;break; case '4': current_key=0x12;CLEAR;break; case '5': current_key=0x13;CLEAR;break; case '6': current_key=0x34;CLEAR;break; case '7': current_key=0x24;CLEAR;break; case '8': current_key=0x15;CLEAR;break; case '9': current_key=0x26;CLEAR;break; case ':': current_key=0x48;CLEAR;break; case ';': current_key=0x57;CLEAR;break; case '<': current_key=0x66;SHIFT;break; case '=': current_key=0x17;SHIFT;break; case '>': current_key=0x67;SHIFT;break; case '?': current_key=0x68;SHIFT;break; case '@': current_key=0x47;CLEAR;break; case 'A': current_key=0x41;SHIFT;break; case 'B': current_key=0x64;SHIFT;break; case 'C': current_key=0x52;SHIFT;break; case 'D': current_key=0x32;SHIFT;break; case 'E': current_key=0x22;SHIFT;break; case 'F': current_key=0x43;SHIFT;break; case 'G': current_key=0x53;SHIFT;break; case 'H': current_key=0x54;SHIFT;break; case 'I': current_key=0x25;SHIFT;break; case 'J': current_key=0x45;SHIFT;break; case 'K': current_key=0x46;SHIFT;break; case 'L': current_key=0x56;SHIFT;break; case 'M': current_key=0x65;SHIFT;break; case 'N': current_key=0x55;SHIFT;break; case 'O': current_key=0x36;SHIFT;break; case 'P': current_key=0x37;SHIFT;break; case 'Q': current_key=0x10;SHIFT;break; case 'R': current_key=0x33;SHIFT;break; case 'S': current_key=0x51;SHIFT;break; case 'T': current_key=0x23;SHIFT;break; case 'U': current_key=0x35;SHIFT;break; case 'V': current_key=0x63;SHIFT;break; case 'W': current_key=0x21;SHIFT;break; case 'X': current_key=0x42;SHIFT;break; case 'Y': current_key=0x44;SHIFT;break; case 'Z': current_key=0x61;SHIFT;break; case '[': current_key=0x38;CLEAR;break; case '\\': current_key=0x78;CLEAR;break; case ']': current_key=0x58;CLEAR;break; case '^': current_key=0x18;CLEAR;break; case '_': current_key=0x28;CLEAR;break; case '`': current_control=1;break; case 'a': current_key=0x41;CLEAR;break; case 'b': current_key=0x64;CLEAR;break; case 'c': current_key=0x52;CLEAR;break; case 'd': current_key=0x32;CLEAR;break; case 'e': current_key=0x22;CLEAR;break; case 'f': current_key=0x43;CLEAR;break; case 'g': current_key=0x53;CLEAR;break; case 'h': current_key=0x54;CLEAR;break; case 'i': current_key=0x25;CLEAR;break; case 'j': current_key=0x45;CLEAR;break; case 'k': current_key=0x46;CLEAR;break; case 'l': current_key=0x56;CLEAR;break; case 'm': current_key=0x65;CLEAR;break; case 'n': current_key=0x55;CLEAR;break; case 'o': current_key=0x36;CLEAR;break; case 'p': current_key=0x37;CLEAR;break; case 'q': current_key=0x10;CLEAR;break; case 'r': current_key=0x33;CLEAR;break; case 's': current_key=0x51;CLEAR;break; case 't': current_key=0x23;CLEAR;break; case 'u': current_key=0x35;CLEAR;break; case 'v': current_key=0x63;CLEAR;break; case 'w': current_key=0x21;CLEAR;break; case 'x': current_key=0x42;CLEAR;break; case 'y': current_key=0x44;CLEAR;break; case 'z': current_key=0x61;CLEAR;break; case '{': current_key=0x38;SHIFT;break; case '|': current_key=0x78;SHIFT;break; case '}': current_key=0x58;SHIFT;break; case '~': current_key=0x18;SHIFT;break; case '�': current_key=0x28;SHIFT;break; case 0: switch(pc_scan_code/0x100) { case 0x3B: current_key=0x71;break; case 0x3C: current_key=0x72;break; case 0x3D: current_key=0x73;break; case 0x3E: current_key=0x14;break; case 0x3F: current_key=0x74;break; case 0x40: current_key=0x75;break; case 0x41: current_key=0x16;break; case 0x42: current_key=0x76;break; case 0x43: current_key=0x77;break; case 0x44: current_key=0x20;break; case 0x47: monitor_call();return; // The home key case 0x48: current_key=0x39;break; case 0x4B: current_key=0x19;break; case 0x4D: current_key=0x79;break; case 0x4F: current_key=0x69;break; case 0x50: current_key=0x29;break; } } /********************************************** **********************************************/ caps_lock_pressed: if (s_via[IER]&0x01) { // if relevant interrupts are enabled s_via[IFR]|=0x81; // generate the interrupt irq(); } else s_via[IFR]|=0x01; old_scan_code=pc_scan_code; // store a copy of the current key } // discard key repeats of the same key else if (_bios_keybrd(_KEYBRD_READY)==old_scan_code) getch(); } if (!pressed) { asm IN AL,0x60 asm push AX asm pop pc_scan_code; if (pc_scan_code&0x80) { // detect if no keys are physically current_key=0; // pressed current_shift=0; current_control=0; } } if (pressed) pressed--; // decrease the current key counter } =========================================== ------------------------------------------- ------------------------------------------- =========================================== #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <graphics.h> #include <dos.h> #include "header.h" #include "screen.h" #include "io.h" void update_full_text_screen(void); void (*update_screen)(void)=update_full_text_screen; // initialise update // screen function uint screen_start=0x7C00; // init screen variables for teletext uint ram_screen_start=0x7C00; // ubyte teletext=1; // // Declare graphics variables.. ubyte disp_chars; // displayed characters per row ubyte colour_bits; // bits per pixel /* Teletext screen write function. */ void text_screen_byte(ubyte iobyte,uint address) { ubyte column=1; // init column (first column=1) ubyte row=1; // init row (first row=1) if (address<screen_start) address+=0x400;// deal with hardware wrap-around address-=screen_start; // column+=address%40; // calculate column row+=address/40; // calculate row if (column==40&&row==25) // if bottom right, return since, any putchar return; // in this position will scroll the screen gotoxy(column,row); // move pc cursor to correct position switch(iobyte) { // convert pc characters to teletext // characters case '_': iobyte='#' ;break; case '[': iobyte='\x1B';break; // some of these conversion are not case '\\': iobyte='�'; break; // stricly correct, since no corresponding case ']': iobyte='\x1A';break; // character in the pc set exists case '^': iobyte='\x18';break; // case '`': iobyte='�' ;break; // notably the } characters is not case '#': iobyte='�' ;break; // converted to the proper 3/4 symbol case '{': iobyte='�' ;break; case '|': iobyte='�' ;break; case '}': iobyte='}' ;break; case '~': iobyte='�' ;break; case 0x7F: iobyte='�' ;break; // This conversion takes place because // 0x7F is used for the cursor when // copying } putch(iobyte); // Ouput the character update_cursor(); // update to the correct position // as specified in the BBC hardware } /* This function is used for graphics modes with 1 bit per pixel */ void screen_byte_1(ubyte iobyte,uint address) { uint x_cord=0; // init real x cordinate variable uint y_cord=0; // init real y cordinate variable uint virt_y_cord=0; // init actual pc output y coordinate uint bitsperline; // variable holding bits per line // deal with hardware wrap-around if (address<screen_start) address+=(0x8000-ram_screen_start); address-=screen_start; bitsperline=crt_regs[1]<<3; // calculate bits per line y_cord=address/(bitsperline); // calculate character row of address y_cord*=8; // convert to pixel row y_cord+=(address%8); // add fraction of character to pixel row virt_y_cord+=y_cord+y_cord/4; // scale output to pc screen x_cord=address%(bitsperline); // calculate x coordinate x_cord&=0xFFF8; // mask off lower 3 bits if (bitsperline==640) // if an 80 character mode { putpixel(x_cord+0,virt_y_cord,(iobyte&0x80)?8:0); putpixel(x_cord+1,virt_y_cord,(iobyte&0x40)?8:0); putpixel(x_cord+2,virt_y_cord,(iobyte&0x20)?8:0); putpixel(x_cord+3,virt_y_cord,(iobyte&0x10)?8:0); putpixel(x_cord+4,virt_y_cord,(iobyte&0x08)?8:0); putpixel(x_cord+5,virt_y_cord,(iobyte&0x04)?8:0); putpixel(x_cord+6,virt_y_cord,(iobyte&0x02)?8:0); putpixel(x_cord+7,virt_y_cord,(iobyte&0x01)?8:0); } else // if not an 80 character mode { x_cord<<=1; // scale output to fit pc screen putpixel(x_cord+0,virt_y_cord,(iobyte&0x80)?8:0); putpixel(x_cord+1,virt_y_cord,(iobyte&0x80)?8:0); putpixel(x_cord+2,virt_y_cord,(iobyte&0x40)?8:0); putpixel(x_cord+3,virt_y_cord,(iobyte&0x40)?8:0); putpixel(x_cord+4,virt_y_cord,(iobyte&0x20)?8:0); putpixel(x_cord+5,virt_y_cord,(iobyte&0x20)?8:0); putpixel(x_cord+6,virt_y_cord,(iobyte&0x10)?8:0); putpixel(x_cord+7,virt_y_cord,(iobyte&0x10)?8:0); putpixel(x_cord+8,virt_y_cord,(iobyte&0x08)?8:0); putpixel(x_cord+9,virt_y_cord,(iobyte&0x08)?8:0); putpixel(x_cord+10,virt_y_cord,(iobyte&0x04)?8:0); putpixel(x_cord+11,virt_y_cord,(iobyte&0x04)?8:0); putpixel(x_cord+12,virt_y_cord,(iobyte&0x02)?8:0); putpixel(x_cord+13,virt_y_cord,(iobyte&0x02)?8:0); putpixel(x_cord+14,virt_y_cord,(iobyte&0x01)?8:0); putpixel(x_cord+15,virt_y_cord,(iobyte&0x01)?8:0); } if (!(y_cord&3)) // if the vertical coordinate has been scaled { virt_y_cord--; // file in the extra pixels if (bitsperline==640) // if an 80 character mode { putpixel(x_cord+0,virt_y_cord,(iobyte&0x80)?8:0); putpixel(x_cord+1,virt_y_cord,(iobyte&0x40)?8:0); putpixel(x_cord+2,virt_y_cord,(iobyte&0x20)?8:0); putpixel(x_cord+3,virt_y_cord,(iobyte&0x10)?8:0); putpixel(x_cord+4,virt_y_cord,(iobyte&0x08)?8:0); putpixel(x_cord+5,virt_y_cord,(iobyte&0x04)?8:0); putpixel(x_cord+6,virt_y_cord,(iobyte&0x02)?8:0); putpixel(x_cord+7,virt_y_cord,(iobyte&0x01)?8:0); } else // if not an 80 character mode { putpixel(x_cord+0,virt_y_cord,(iobyte&0x80)?8:0); putpixel(x_cord+1,virt_y_cord,(iobyte&0x80)?8:0); putpixel(x_cord+2,virt_y_cord,(iobyte&0x40)?8:0); putpixel(x_cord+3,virt_y_cord,(iobyte&0x40)?8:0); putpixel(x_cord+4,virt_y_cord,(iobyte&0x20)?8:0); putpixel(x_cord+5,virt_y_cord,(iobyte&0x20)?8:0); putpixel(x_cord+6,virt_y_cord,(iobyte&0x10)?8:0); putpixel(x_cord+7,virt_y_cord,(iobyte&0x10)?8:0); putpixel(x_cord+8,virt_y_cord,(iobyte&0x08)?8:0); putpixel(x_cord+9,virt_y_cord,(iobyte&0x08)?8:0); putpixel(x_cord+10,virt_y_cord,(iobyte&0x04)?8:0); putpixel(x_cord+11,virt_y_cord,(iobyte&0x04)?8:0); putpixel(x_cord+12,virt_y_cord,(iobyte&0x02)?8:0); putpixel(x_cord+13,virt_y_cord,(iobyte&0x02)?8:0); putpixel(x_cord+14,virt_y_cord,(iobyte&0x01)?8:0); putpixel(x_cord+15,virt_y_cord,(iobyte&0x01)?8:0); } } } /* Screen output function for 2 bits per pixels (4 colour) modes. */ void screen_byte_2(ubyte iobyte,uint address) { uint x_cord=0; // general x coordinate variable uint y_cord=0; // general y coordinate variable uint virt_y_cord=0; // vertically scaled pc y coordinate uint bitsperline; // bits per line variable ubyte colpix1; // colour of pixel 1 ubyte colpix2; // colour of pixel 2 ubyte colpix3; // colour of pixel 3 ubyte colpix4; // colour of pixel 4 // deal with hardware wraparound if (address<screen_start) address+=(0x8000-ram_screen_start); address-=screen_start; bitsperline=8*crt_regs[1]; // calculate bits per scanline y_cord=address/bitsperline; // calculate character row y_cord*=8; // convert to pixel row y_cord+=(address%8); // add fraction of character offset virt_y_cord+=y_cord+y_cord/4; // scale output to fit pc screen x_cord=address%bitsperline; // calculate x character column x_cord&=0xFFF8; // mask off lower 3 bits switch(iobyte&0x88) // calculate colour of pixel 1 { case 0x00: colpix1=0x00;break; case 0x08: colpix1=0x02;break; case 0x80: colpix1=0x08;break; case 0x88: colpix1=0x0A;break; } switch(iobyte&0x44) // calculate colour of pixel 2 { case 0x00: colpix2=0x00;break; case 0x04: colpix2=0x02;break; case 0x40: colpix2=0x08;break; case 0x44: colpix2=0x0A;break; } switch(iobyte&0x22) // calculate colour of pixel 3 { case 0x00: colpix3=0x00;break; case 0x02: colpix3=0x02;break; case 0x20: colpix3=0x08;break; case 0x22: colpix3=0x0A;break; } switch(iobyte&0x11) // calcalate colour of pixel 4 { case 0x00: colpix4=0x00;break; case 0x01: colpix4=0x02;break; case 0x10: colpix4=0x08;break; case 0x11: colpix4=0x0A;break; } if (bitsperline==640) // if this is a 40 character mode { putpixel(x_cord+0,virt_y_cord,colpix1); putpixel(x_cord+1,virt_y_cord,colpix1); putpixel(x_cord+2,virt_y_cord,colpix2); putpixel(x_cord+3,virt_y_cord,colpix2); putpixel(x_cord+4,virt_y_cord,colpix3); putpixel(x_cord+5,virt_y_cord,colpix3); putpixel(x_cord+6,virt_y_cord,colpix4); putpixel(x_cord+7,virt_y_cord,colpix4); } else // if this is not a 40 character mode { x_cord<<=1; // scale the x coorinate to fit the scren putpixel(x_cord+0,virt_y_cord,colpix1); putpixel(x_cord+1,virt_y_cord,colpix1); putpixel(x_cord+2,virt_y_cord,colpix1); putpixel(x_cord+3,virt_y_cord,colpix1); putpixel(x_cord+4,virt_y_cord,colpix2); putpixel(x_cord+5,virt_y_cord,colpix2); putpixel(x_cord+6,virt_y_cord,colpix2); putpixel(x_cord+7,virt_y_cord,colpix2); putpixel(x_cord+8,virt_y_cord,colpix3); putpixel(x_cord+9,virt_y_cord,colpix3); putpixel(x_cord+10,virt_y_cord,colpix3); putpixel(x_cord+11,virt_y_cord,colpix3); putpixel(x_cord+12,virt_y_cord,colpix4); putpixel(x_cord+13,virt_y_cord,colpix4); putpixel(x_cord+14,virt_y_cord,colpix4); putpixel(x_cord+15,virt_y_cord,colpix4); } if (!(y_cord&3)) // if the y coordinate was scaled, { virt_y_cord--; // put the pixels on the original line if (bitsperline==640) // if this is a 40 character mode { putpixel(x_cord+0,virt_y_cord,colpix1); putpixel(x_cord+1,virt_y_cord,colpix1); putpixel(x_cord+2,virt_y_cord,colpix2); putpixel(x_cord+3,virt_y_cord,colpix2); putpixel(x_cord+4,virt_y_cord,colpix3); putpixel(x_cord+5,virt_y_cord,colpix3); putpixel(x_cord+6,virt_y_cord,colpix4); putpixel(x_cord+7,virt_y_cord,colpix4); } else // if this is not a 40 character mode { putpixel(x_cord+0,virt_y_cord,colpix1); putpixel(x_cord+1,virt_y_cord,colpix1); putpixel(x_cord+2,virt_y_cord,colpix1); putpixel(x_cord+3,virt_y_cord,colpix1); putpixel(x_cord+4,virt_y_cord,colpix2); putpixel(x_cord+5,virt_y_cord,colpix2); putpixel(x_cord+6,virt_y_cord,colpix2); putpixel(x_cord+7,virt_y_cord,colpix2); putpixel(x_cord+8,virt_y_cord,colpix3); putpixel(x_cord+9,virt_y_cord,colpix3); putpixel(x_cord+10,virt_y_cord,colpix3); putpixel(x_cord+11,virt_y_cord,colpix3); putpixel(x_cord+12,virt_y_cord,colpix4); putpixel(x_cord+13,virt_y_cord,colpix4); putpixel(x_cord+14,virt_y_cord,colpix4); putpixel(x_cord+15,virt_y_cord,colpix4); } } } /* Screen output function for 16 colour modes */ void screen_byte_4(ubyte iobyte,uint address) { uint x_cord=0; // general x coordinate uint y_cord=0; // general y coordinate uint virt_y_cord=0; // scaled pc y coordinate uint bitsperline; // bits per scaline ubyte colpix1; // holds the colour of pixel 1 ubyte colpix2; // holds the colour of pixel 2 bitsperline=8*crt_regs[1]; // calculate bits per line // deal with hardware wraparound if (address<screen_start) address+=(0x8000-ram_screen_start); address-=screen_start; y_cord=address/bitsperline; // calculate the character row y_cord*=8; // convert to the pixel row y_cord+=(address%8); // add fraction of character offset virt_y_cord+=y_cord+y_cord/4; // scale output to fit screen x_cord=address%bitsperline; // calcalate the character column x_cord&=0xFFF8; // mask off the lower 3 bits switch(iobyte&0xAA) // calculate the colour of pixel 1 { case 0x00: colpix1=0x0; break; case 0x02: colpix1=0x1; break; case 0x08: colpix1=0x2; break; case 0x0A: colpix1=0x3; break; case 0x20: colpix1=0x4; break; case 0x22: colpix1=0x5; break; case 0x28: colpix1=0x6; break; case 0x2A: colpix1=0x7; break; case 0x80: colpix1=0x8; break; case 0x82: colpix1=0x9; break; case 0x88: colpix1=0xA; break; case 0x8A: colpix1=0xB; break; case 0xA0: colpix1=0xC; break; case 0xA2: colpix1=0xD; break; case 0xA8: colpix1=0xE; break; case 0xAA: colpix1=0xF; break; } switch(iobyte&0x55) // calculate the colour of pixel 2 { case 0x00: colpix2=0x0; break; case 0x01: colpix2=0x1; break; case 0x04: colpix2=0x2; break; case 0x05: colpix2=0x3; break; case 0x10: colpix2=0x4; break; case 0x11: colpix2=0x5; break; case 0x14: colpix2=0x6; break; case 0x15: colpix2=0x7; break; case 0x40: colpix2=0x8; break; case 0x41: colpix2=0x9; break; case 0x44: colpix2=0xA; break; case 0x45: colpix2=0xB; break; case 0x50: colpix2=0xC; break; case 0x51: colpix2=0xD; break; case 0x54: colpix2=0xE; break; case 0x55: colpix2=0xF; break; } // only a twenty column mode is // officially supported, // so no need to scale output putpixel(x_cord+0,virt_y_cord,colpix1); putpixel(x_cord+1,virt_y_cord,colpix1); putpixel(x_cord+2,virt_y_cord,colpix1); putpixel(x_cord+3,virt_y_cord,colpix1); putpixel(x_cord+4,virt_y_cord,colpix2); putpixel(x_cord+5,virt_y_cord,colpix2); putpixel(x_cord+6,virt_y_cord,colpix2); putpixel(x_cord+7,virt_y_cord,colpix2); if (!(y_cord&3)) // if the y_cord was scaled, // fill in the pixels for the { // original line virt_y_cord--; putpixel(x_cord+0,virt_y_cord,colpix1); putpixel(x_cord+1,virt_y_cord,colpix1); putpixel(x_cord+2,virt_y_cord,colpix1); putpixel(x_cord+3,virt_y_cord,colpix1); putpixel(x_cord+4,virt_y_cord,colpix2); putpixel(x_cord+5,virt_y_cord,colpix2); putpixel(x_cord+6,virt_y_cord,colpix2); putpixel(x_cord+7,virt_y_cord,colpix2); } } void update_cursor(void) { uint cursor_add; // cursor address uint cursor_wid; // cursor width in bytes static uint old_cursor_add; // static variable to hold the static uint old_cursor_wid; // previous cursor data, // so that it may be erased if (teletext) { // if in teletext mode cursor_add=crt_regs[14]*0x100+crt_regs[15]; cursor_add^=0x2000; cursor_add+=0x7400; // calculate actual address // move the cursor to the relevant place if (cursor_add<screen_start) cursor_add+=0x400;// deal with hardware wraparound cursor_add-=screen_start; gotoxy(cursor_add%40+1,cursor_add/40+1); } else { // if in a graphics mode cursor_add=0x100*crt_regs[14]+crt_regs[15]; cursor_add<<=3; // calculte the actual address // deal with hardware wrap around if (cursor_add>=0x8000) cursor_add-=0x8000-ram_screen_start; switch (vid_con_reg&0x60) { // get the cursor width in bytes case 0x60: cursor_wid=4;break; case 0x40: cursor_wid=2;break; case 0x20: puts("Invalid Cursor");exit(1);break; case 0x00: cursor_wid=1;break; } switch (old_cursor_wid) { // remove the old cursor case 4: screen_byte_P(RAM[old_cursor_add+0x1F],old_cursor_add+0x1F); screen_byte_P(RAM[old_cursor_add+0x17],old_cursor_add+0x17); case 2: screen_byte_P(RAM[old_cursor_add+0x0F],old_cursor_add+0x0F); case 1: screen_byte_P(RAM[old_cursor_add+0x07],old_cursor_add+0x07); } switch (cursor_wid) { // position the new cursor case 4: screen_byte_P(0xFF,cursor_add+0x1F); screen_byte_P(0xFF,cursor_add+0x17); case 2: screen_byte_P(0xFF,cursor_add+0x0F); case 1: screen_byte_P(0xFF,cursor_add+0x07); } old_cursor_wid=cursor_wid; // store a copy of the current cursor old_cursor_add=cursor_add; // } } // The name says it all really, used to update // the teletext screen after a hardware scroll void update_full_text_screen(void) { uint c; uint d; _setcursortype(_NOCURSOR); // turn off the cursor to stop flickering c=screen_start; for(d=0;d<999;d++,c++) { // work through every byte if (c==0x8000) c=0x7C00; // deal with hardware wraparound text_screen_byte(RAM[c],c); // output the current byte } _setcursortype(_NORMALCURSOR); // turn the cursor back on again } /* This function does not really do anywork, it calls the relevant function */ void update_graphics_screen(void) { switch(colour_bits) { case 1: mono_update();break; case 2: four_update();break; case 4: sixt_update();break; default: puts("Error, unknown number of colours");exit(1); } } /* Called upon a negative transition of the teletext select bit in the video ULA Sheila Address 0xFE20 */ void pixel_vid_init(void) { setgraphmode(VGAMED); // Change mode from text to graphics set_colour_bits(); // initialise for the relevant colour mode set_screen_start(); // initialise the screen start update_screen=update_graphics_screen; // point the screen update function return; } /* Called upon a positive transition of the teletext select bit in the video ULA */ void teletext_init(void) { restorecrtmode(); // Change to a text mode ram_screen_start=0x7C00; // Set screen start screen_byte_P=text_screen_byte; // Point screen access function update_screen=update_full_text_screen; // point screen update function textcolor(WHITE); // set text to white colour return; } /* Called only once, during system initialisation */ void graphics_init(void) { signed int errorcode; printf("Init graphics system..."); // display pretty startup info errorcode=registerfarbgidriver(EGAVGA_driver_far); // initialise the graphics if (errorcode<0) // system. check for error { printf("\nUnable to Initialise Graphics\n"); // if unable to init, printf("This software requires VGA/EGA"); // print error exit(1); // and exit } screen_byte_P=text_screen_byte; // point screen access function for text printf("Done\n"); // display pretty startup info } void set_colour_bits(void) // initialise colour functions { if (!teletext) // only if in graphics mode switch(colour_bits=crt_regs[1]/disp_chars) // calc bits per pixel { case 1: screen_byte_P=screen_byte_1; break; // point screen access func. case 2: screen_byte_P=screen_byte_2; break; case 4: screen_byte_P=screen_byte_4; break; } } /* Update ram screen start, used in putbyte() (to decide if output is directed at the screen) and elsewhere */ void set_screen_start(void) { ubyte screen_latch=0; screen_latch=s_via_latch[4]+(2*s_via_latch[5]); // read from the system // via latch // There is a possibly bug here: the system via latch does not // correspond to values given in the Advanced User Guide or the // Advanced Master Series Guide. // However, inaccuracies would probably have gone unnoticed, since // these bits are only ever altered by the OS and cannot be read by the // user switch (screen_latch) { case 0x000: ram_screen_start=0x4000; break; case 0x008: ram_screen_start=0x6000; break; case 0x018: ram_screen_start=0x5800; break; case 0x010: ram_screen_start=0x3000; break; default: puts("Fatal error in detecting screen boundary"); exit(1); } } =========================================== ------------------------------------------- ------------------------------------------- =========================================== #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <graphics.h> #include <dos.h> #include "header.h" #include "screen.h" #include "io.h" // Used to scroll a mono screen up 1 line void mono_update(void) { getimage(0,10,639,96,pic_temp_ram); putimage(0,0,pic_temp_ram,0); getimage(0,97,639,184,pic_temp_ram); putimage(0,87,pic_temp_ram,0); getimage(0,185,639,271,pic_temp_ram); putimage(0,175,pic_temp_ram,0); getimage(0,272,639,350,pic_temp_ram); putimage(0,262,pic_temp_ram,0); } // Used to scroll a four colour screen up 1 line void four_update(void) { getimage(0,10,639,96,pic_temp_ram); putimage(0,0,pic_temp_ram,0); getimage(0,97,639,184,pic_temp_ram); putimage(0,87,pic_temp_ram,0); getimage(0,185,639,271,pic_temp_ram); putimage(0,175,pic_temp_ram,0); getimage(0,272,639,350,pic_temp_ram); putimage(0,262,pic_temp_ram,0); } // Used to scroll a sixteen colour screen up 1 line void sixt_update(void) { getimage(0,10,639,96,pic_temp_ram); putimage(0,0,pic_temp_ram,0); getimage(0,97,639,184,pic_temp_ram); putimage(0,87,pic_temp_ram,0); getimage(0,185,639,271,pic_temp_ram); putimage(0,175,pic_temp_ram,0); getimage(0,272,639,350,pic_temp_ram); putimage(0,262,pic_temp_ram,0); }=========================================== ------------------------------------------- ------------------------------------------- =========================================== #include <stdio.h> #include <dos.h> #include "header.h" #include "io.h" void get_vol(ubyte iobyte); // prototypes for sound functions void get_freq(ubyte iobyte); uint freqbits[4]; // arrays holding frequencys ubyte vol[4]; // and volumes for each channel ubyte soundyesno=1; void sound_byte(ubyte iobyte) { // if a noise program byte, return if ((iobyte&0xE0)==0xE0) return; if ((iobyte&0x90)==0x90) get_vol(iobyte); // if a volume byte if ((iobyte&0x90)==0x80) get_freq(iobyte); // if a frequency byte if (!(iobyte&0x80)) get_freq(iobyte); // if a frequency byte if (soundyesno) update_sound(); // update sound } void get_vol(ubyte iobyte) { // used to extract volume data from a byte ubyte channel; switch (iobyte&0x60) { // select channel case 0x00: channel=3;break; case 0x20: channel=2;break; case 0x40: channel=1;break; } vol[channel]=15-(iobyte&(0xF)); // update channel } void get_freq(ubyte iobyte) { // used to extract frequency data from // a byte static ubyte channel=0xFF; if (iobyte&0x80) { // select channel switch (iobyte&0x60) { case 0x00: channel=3; break; case 0x20: channel=2;break; case 0x40: channel=1;break; } freqbits[channel]&=0; // update high order bits of channel freqbits[channel]|=(iobyte&0xF); } if (!(iobyte&0x80)) { // if a `low order' frequency byte freqbits[channel]&=0x000F; freqbits[channel]|=(((uint)(iobyte&0x3F))<<4); // update low order bits } } /* This function has the fairly difficult task of selecting a suitable single frequency, which best describes the combined sound of three variable frequency, variable volume frequencies. */ void update_sound(void) { uint c,totvol=0; double totfreq=0; for (c=1;c<4;c++) { // step through each channel totvol+=vol[c]; // keep a running volume count if (freqbits[c]==0) continue; // check to avoid divide by zero totfreq+=vol[c]*(4000000./(32.*freqbits[c])); } if (totvol==0) { // if no channels are turned on, switch off nosound(); // all sound return; } totfreq/=totvol; // normalise sound sound(totfreq); // and generate it } =========================================== ------------------------------------------- ------------------------------------------- =========================================== #include <stdio.h> #include <stdlib.h> #include <dos.h> #include <conio.h> #include <graphics.h> #include <alloc.h> #include "header.h" #include "screen.h" #include "mnemonic.h" ubyte debuginfo=0; ubyte pic_temp_ram[0x8000]; char far *graph_ptr; void titlepic(void); FILE *output; void system_init(void) { int gdriver=VGA,gmode=VGAMED; output=fopen("C:\\tc\\source\\softbeeb\\output.dat","wb"); // unsigned int c; // unsigned char test[]={END}; textmode(C80); // intialise the screen mode clrscr(); // clear the screen textbackground(BLUE);//display pretty startup screen textcolor(YELLOW); cprintf(" Softbeeb Initialisation \n\n\r"); textbackground(BLACK); textbackground(WHITE); init_decode(); // initialise the 6502 processor emulator init_mem(); // initialise the memory rinit_io(); // initialize the read io system winit_io(); // initialise the write io system graphics_init(); // initialise the graphics system textmode(C40); initgraph(&gdriver,&gmode,""); titlepic(); restorecrtmode(); textcolor(WHITE); printf("_________________________\n\n"); // display end of startup line clrscr(); /* // instructions for testing purposes pc=0x4000; for (c=0;(c<sizeof(test)+1);c++) putbyte(test[c2],pc+c2); // *********** SETUP FOR TESTS GOES HERE ********* // ************************************************ */ } void show_regs(void) // debugging procedure to display misc status // and registers. { fprintf(output,"\nPC=%4X A =%02X ",pc,acc); fprintf(output,"X=%02X Y=%02X S=%02X:%02X ",x_reg,y_reg,sp,RAM[sp+0x101]); fprintf(output,"n%dv%db%dd%d",((except)||(result_f&0x80))?1:0,ovr_f==0?0:1,brk_f==0?0:1,dec_f==0?0:1); fprintf(output,"id%dz%dc%d",intd_f==0?0:1,(except||result_f)?0:1,carry_f==0?0:1); fprintf(output," %18s D=%2X%02X",mnemonic[getbyte(pc)],getbyte(pc+2),getbyte(pc+1)); fprintf(output," %02X",getbyte(pc)); } void show_screen(void) // only used in the waitkey function { unsigned int c; for (c=0x7C00;c<0x8000;c++) { if (!((c+16)%40)) printf("\n"); putchar(RAM[c]); } } /* Waits for a keypress, then discards it. Useful as a pause procedure. */ void waitkey(void) { int c; if (debuginfo) // Check if debugging is enabled { c=getchar(); switch (c) { case 'i': irq(); break; // if "I" is pressed, generated an IRQ case 'r': debuginfo=0;break; // turn off debugging and run freely case 's': show_screen(); break; // if "s", display a mode 7 screen case 'x': decode[0xFF](); break; // if "x", exit! } } } void titlepic(void) { // the title picture display // display function int horz,vert; int vvert=0; uint c,d=0; uint red=63,green=0,blue=0; FILE *title; if ((title=fopen("data\\title.bmp","rb"))==NULL) { printf("Titlepic fileopen Error"); getch(); // open the picture file exit(1); }; pokeb(0x0040,0x0017,peekb(0x0040,0x0017)|0x40); // turn on capslock for (c=0x8000;c;c--) { // load the picture pic_temp_ram[c-1]=getc(title); } for (c=0;c<16;c++) { // initialise the palette setrgbpalette(c,c<<2,c<<2,c<<2); // for greyscale setpalette(c,c); } setrgbpalette(15,63,0,0); // set the red colour setpalette(15,15); for (vert=0,c=650;vert<200;vert++) { // loop through each vvert++; // pixel row if (vert&0x3) vvert++; // scale output to fit // screen for (horz=640;horz;horz-=4,c++) { putpixel(horz+0,vvert,pic_temp_ram[c]>>4); putpixel(horz+1,vvert,pic_temp_ram[c]>>4); putpixel(horz+2,vvert,pic_temp_ram[c]&0xF); putpixel(horz+3,vvert,pic_temp_ram[c]&0xF); if (vert&0x3) { // if y cord has been scaled, draw on original line vvert--; putpixel(horz+0,vvert,pic_temp_ram[c]>>4); putpixel(horz+1,vvert,pic_temp_ram[c]>>4); putpixel(horz+2,vvert,pic_temp_ram[c]&0xF); putpixel(horz+3,vvert,pic_temp_ram[c]&0xF); vvert++; } if (kbhit()) {getch(); return;} // wait for keypress } } for(;;) // cycle colours until for (c=0;c<=4;c++) for (d=0;d<15;d++) { switch(c) { case 0:green+=4; break; case 1:red-=4; break; case 2:blue+=4; break; case 3:green-=4; break; case 4:blue-=4;red+=4;break; } setrgbpalette(15,red,green,blue); setpalette(15,15); delay(10); // delay deliberately if (kbhit()) {getch(); return;} // until keypressed } }=========================================== ------------------------------------------- ------------------------------------------- =========================================== #include <stdio.h> #include "header.h" /* This file provides names for the instructions, and the data here is only ever used by show_regs(). It may be removed before the `final release' */ char *mnemonic[]={ "BRK", "ORA (indirect , X)", "- ", "-", "-", "ORA-Zero Page", "ASL-Zero Page", "-", "PHP", "ORA-Immediate", "ASL-Accumulator", "-", "-", "ORA-Absolute", "ASL-Absolute", "-", "BPL", "ORA (Indirect) , Y", "-", "-", "-", "ORA-Zero Page , X", "ASL-Zero Page , X", "-", "CLC", "ORA-Absolute ,Y", "-", "-", "-", "ORA-Absolute , X", "ASL Absolute , X", "-", "JSR", "AND-(Indirect , X)", "-", "-", "BIT-Zero Page", "AND-Zero Page", "ROL-Zero Page", "-", "PLP", "AND-Immediate", "ROL-Accumulator", "-", "BIT-Absolute", "AND-Absolute", "ROL-Absolute", "-", "BMI", "AND (Indirect) , Y", "-", "-", "-", "AND-Zero Page , X", "ROL-Zero Page , X", "-", "SEC", "AND-Absolute , Y", "-", "-", "-", "AND-Absolute , X", "ROL-Absolute , X", "-", "RTI", "EOR (Indirect , X)", "-", "-", "-", "EOR-Zero Page", "LSR-Zero Page", "-", "PHA", "EOR-Immediate", "LSR-Accumulator", "-", "JMP-Absolute", "EOR-Absolute", "LSR-Absolute", "-", "BVC", "EOR (Indirect) , Y", "-", "-", "-", "EOR-Zero Page , X", "LSR-Zero Page , X", "-", "CLI", "EOR-Absolute ,Y", "-", "-", "-", "EOR-Absolute , X", "LSR-Absolute , X", "-", "RTS", "ADC (Indirect , X)", "-", "-", "-", "ADC-Zero Page", "ROR-Zero Page", "-", "PLA", "ADC-Immediate", "ROR-Accumulator", "-", "JMP-Indirect", "ADC-Absolute", "ROR-Absolute", "-", "BVS", "ADC (Indirect) , Y", "-", "-", "-", "ADC-Zero Page , X", "ROR-Zero Page , X", "-", "SEI", "ADC-Absolute , Y", "-", "-", "-", "ADC-Absolute , X", "ROR-Absolute , X", "-", "-", "STA (Indirect , X)", "-", "-", "STY-Zero Page", "STA-Zero Page", "STX-Zero Page", "-", "DEY", "-", "TXA", "-", "STY-Absolute", "STA-Absolute", "STX-Absolute", "-", "BCC", "STA-(Indirect) , Y", "-", "-", "STY-Zero Page , X", "STA-Zero Page , X", "STX-Zero Page, Y", "-", "TYA", "STA-Absolute , Y", "TXS", "-", "-", "STA-Absolute , X", "-", "-", "LDY-Immediate", "LDA (Indirect , X)", "LDX-Immediate", "-", "LDY-Zero Page", "LDA-Zero Page", "LDX-Zero PAge", "-", "TAY", "LDA-Immediate", "TAX", "-", "LDY-Absolute", "LDA-Absolute", "LDX-Absolute", "-", "BCS", "LDA (Indirect) , Y", "-", "-", "LDY-Zero Page , X", "LDA-Zero Page , X", "LDX-Zero Page, Y", "-", "CLV", "LDA-Absolute , Y", "TSX", "-", "LDY- Absolute , X", "LDA-Absolute , X", "LDX-Absolute ,Y", "-", "CPY-Immediate", "CMP (Indirect , X)", "-", "-", "CPY-Zero Page", "CMP-Zero Page", "DEC-Zero Page", "-", "INY", "CMP-Immediate", "DEX", "-", "CPY-Absolute", "CMP-Absolute", "DEC-Absolute", "-", "BNE", "CMP (Indirect) , Y", "-", "-", "-", "CMP-Zero Page , X", "DEC-Zero Page , X", "-", "CLD", "CMP-Absolute , Y", "-", "-", "-", "CMP-Absolute , X", "DEC-Absolute , X", "-", "CPX-Immediate", "SBC (Indirect , X)", "-", "-", "CPX-Zero Page", "SBC-Zero Page", "INC-Zero Page", "-", "INX", "SBC-Immediate", "NOP", "-", "CPX-Absolute", "SBC-Absolute", "INC-Absolute", "-", "BEQ", "SBC (Indirect) , Y", "-", "-", "-", "SBC-Zero Page , X", "INC-Zero Page , X", "-", "SED", "SBC-Absolute , Y", "-", "-", "-", "SBC-Absolute , X", "INC-Absolute , X", "-", }; =========================================== ------------------------------------------- ------------------------------------------- =========================================== #include <stdio.h> #include <conio.h> #include <dos.h> #include <stdlib.h> #include <graphics.h> #include <ctype.h> #include "header.h" #include "io.h" #include "screen.h" #define RED 11 #define BLACK 12 #define WHITE 13 #define BLUE 14 #define YELLOW 15 void monitor(void); void monitor_call(void) { // Is called when home is pressed if (teletext) { setgraphmode(VGAMED); monitor(); flash(); restorecrtmode(); update_screen(); } if (!teletext) { setvisualpage(1); setactivepage(1); monitor(); flash(); setvisualpage(0); setactivepage(0); } } void monitor(void) { uint init_colour; uint c=0; // misc counters uint d=0; // misc counters init_colour=getcolor(); setpalette(11,EGA_LIGHTRED); setpalette(12,EGA_BLACK); setpalette(13,EGA_WHITE); setpalette(14,EGA_BLUE); setpalette(15,EGA_YELLOW); setbkcolor(BLACK); cleardevice(); settextstyle(DEFAULT_FONT,HORIZ_DIR,3); setcolor(YELLOW); outtextxy(10,10,"Options"); setcolor(RED); outtextxy(12,12,"Options"); setcolor(BLUE); outtextxy(14,14,"Options"); setcolor(WHITE); settextstyle(DEFAULT_FONT,HORIZ_DIR,1); /* The area 0,300,0,350 is to be left clear for further option prompts */ /***************************************** ****************************************** *****************************************/ outtextxy(0,60,"X : Quit Softbeeb"); outtextxy(0,70,"B : Simulate Break Key (Reset)"); outtextxy(0,80,"R : Redraw Graphics Screen"); outtextxy(0,90,"S : PC Speaker Sound Emulation"); outtextxy(0,110,"Press the key of your choice"); outtextxy(50,200," Press `return' to continue the Emulation"); while(kbhit()) getch(); for(;c!='\r';c=getch()) { switch(tolower(c)) { case 'x': setcolor(YELLOW); outtextxy(0,305,"Are you sure you want to quit? Y/N"); if(tolower(getch())=='y') quit_prog(); else { setcolor(BLACK); outtextxy(0,305,"Are you sure you want to quit? Y/N"); } setcolor(WHITE); break; case 'r': if (!teletext) { setcolor(YELLOW); outtextxy(0,305,"Redrawing Graphics Screen..."); d=screen_start; setactivepage(0); for(c=0;c<(0x8000-ram_screen_start);c++) { if (d==0x8000) d=ram_screen_start; screen_byte_P(RAM[d],d); d++; update_cursor(); } setactivepage(1); } setcolor(BLACK); outtextxy(0,305,"Redrawing Graphics Screen..."); setcolor(WHITE); break; case 'b': setcolor(YELLOW); outtextxy(0,305,"Press Y to confirm reset"); if(tolower(getch())=='y') pc=0xD9CD; setcolor(BLACK); outtextxy(0,305,"Press Y to confirm reset"); setcolor(WHITE); break; case 's': setcolor(YELLOW); outtextxy(0,305,"Do you want sound? Y/N"); if(tolower(getch())=='y') { soundyesno=1; update_sound(); } else { soundyesno=0; nosound(); } setcolor(BLACK); outtextxy(0,305,"Do you want sound? Y/N"); setcolor(WHITE); break; } } setbkcolor(0); setcolor(init_colour); } void quit_prog() { closegraph(); textmode(C80); pokeb(0,0x417,peekb(0,0x417)&0xBF); puts("Thankyou for using `SOFTBEEB'\n"); puts("Have a nice day {;-)\n"); exit(0); }=========================================== ------------------------------------------- ------------------------------------------- =========================================== // Standard type definitions typedef unsigned char ubyte; typedef unsigned int uint; typedef signed char sbyte; // __________________________ // Miscellaneous control functions / data extern FILE *output; extern ubyte debuginfo; extern char *mnemonic[]; extern void show_regs(void); extern void monitor_call(void); extern void show_screen(void); extern void waitkey(void); extern void quit_prog(void); // ____________________ // Startup Initialisation Routines extern void system_init(void); extern void graphics_init(void); extern void init_decode(void); extern void init_mem(void); extern void rinit_io(void); extern void winit_io(void); extern void titlepic(); // __________________________ // Interrupt Handling Functions extern void irq(void); extern void gen_irq(void); // _____________________________ // Video Output Control Functions / Data extern void (*screen_byte_P)(ubyte,uint); extern void text_screen_byte(ubyte,uint); extern void teletext_init(void); extern void pixel_vid_init(void); extern void update_cursor(void); extern void set_colour_bits(void); extern void set_screen_start(void); extern void (*update_screen)(void); extern uint ram_screen_start; extern ubyte teletext; extern ubyte disp_chars; extern uint screen_start; extern ubyte vidpal[16]; // ___________________________________- // Address Decoding Functions / Data extern ubyte getbyte(uint); extern void putbyte (ubyte byte, uint address); extern void (*wsheila[256])(ubyte); extern ubyte (*rsheila[256])(void); extern ubyte romsel; // _______________________________________________ // Processor Control Data extern void (*decode[256])(void); extern ubyte RAM[0x8000]; // extern ubyte OS_ROM[0x4000]; // Memory Arrays extern ubyte lang_ROM[0x4000]; // extern uint pc; // extern ubyte acc; // 6502 Internal Registers extern ubyte x_reg; // extern ubyte y_reg; // extern ubyte sp; // extern ubyte ir; // extern ubyte dyn_p; // extern ubyte result_f; // extern ubyte ovr_f; // 6502 Status Flags extern ubyte brk_f; // extern ubyte dec_f; // extern ubyte intd_f; // extern ubyte carry_f; // extern ubyte except; // _______________________ =========================================== ------------------------------------------- ------------------------------------------- =========================================== extern void non_opcode(void); // prototype for function occuring when // an illegal opcode is executed extern void update_flags(void); extern void update_dyn_p(void); // builds a valid status byte for // stack pushing extern void pushbyte(unsigned char ); // push sub instruction extern unsigned char popbyte(void); // pop sub instruction =========================================== ------------------------------------------- ------------------------------------------- =========================================== /* Graphics Related Declarations. */ extern ubyte crt_regs[18]; extern ubyte crt_sel; extern void update_cursor(void); extern ubyte vid_con_reg; extern ubyte vid_ula; /*********************************/ /* System Via Related Declarations */ extern ubyte s_via[16]; extern ubyte s_via_latch[8]; extern ubyte s_via_opa; extern ubyte s_via_ipa; extern ubyte s_via_opb; extern ubyte s_via_ipb; extern ubyte current_latch; extern ubyte current_key; extern ubyte current_shift; extern ubyte current_control; /**********************************/ /* Sound Related Declarations */ extern void sound_byte(ubyte); extern void update_sound(void); extern uint freqbits[4]; extern ubyte vol[4]; extern ubyte soundyesno; /**********************************/ /* Miscellaneous Declarations */ extern ubyte adc_control; /**********************************/ =========================================== ------------------------------------------- ------------------------------------------- =========================================== // Video Output Control Functions / Data extern void (*screen_byte_P)(ubyte,uint); extern void text_screen_byte(ubyte,uint); extern void teletext_init(void); extern void pixel_vid_init(void); extern void update_cursor(void); extern void set_colour_bits(void); extern void set_screen_start(void); extern void (*update_screen)(void); extern void flash(void); extern uint ram_screen_start; extern ubyte teletext; extern ubyte disp_chars; extern uint screen_start; extern ubyte vidpal[16]; extern void mono_update(void); extern void four_update(void); extern void sixt_update(void); extern ubyte pic_temp_ram[];=========================================== ------------------------------------------- ------------------------------------------- =========================================== #define BRK 0x00 #define PHP 0x08 #define ORA 0x09 #define ASL 0x0A #define BPL 0x10 #define CLC 0x18 #define JSR 0x20 #define PLP 0x28 #define AND 0x29 #define ROL 0x2A #define BIT 0x2C #define BMI 0x30 #define SEC 0x38 #define RTI 0x40 #define PHA 0x48 #define EOR 0x49 #define LSR 0x4A #define JMP 0x4C #define BVC 0x50 #define CLI 0x58 #define RTS 0x60 #define PLA 0x68 #define ADC 0x69 #define ROR 0x6A #define BVS 0x70 #define SEI 0x78 #define DEY 0x88 #define TXA 0x8A #define STY 0x8C #define STA 0x8D #define STX 0x8E #define BCC 0x90 #define TYA 0x98 #define TXS 0x9A #define LDY 0xA0 #define LDX 0xA2 #define TAY 0xA8 #define LDA 0xA9 #define TAX 0xAA #define BCS 0xBO #define CLV 0xB8 #define TSX 0xBA #define CPY 0xC0 #define INY 0xC8 #define CMP 0xC9 #define DEX 0xCA #define DEC 0xCE #define BNE 0xD0 #define CLD 0xD8 #define CPX 0xE0 #define INX 0xE8 #define SBC 0xE9 #define NOP 0xEA #define INC 0xEE #define BEQ 0xF0 #define SED 0xF8 #define END 0xFF =========================================== ------------------------------------------- ------------------------------------------- =========================================== #define ORB 0 #define ORA 1 #define DDRB 2 #define DDRA 3 #define T1C_L 4 #define T1C_H 5 #define T1L_L 6 #define T1L_H 7 #define T2C_L 8 #define T2C_H 9 #define SR 10 #define ACR 11 #define PCR 12 #define IFR 13 #define IER 14 #define ORA_15 15
2.5625
3
2024-11-18T20:15:38.054924+00:00
2019-09-20T17:02:01
974831daf5523408d8ff40c076e3f8693131c7ad
{ "blob_id": "974831daf5523408d8ff40c076e3f8693131c7ad", "branch_name": "refs/heads/master", "committer_date": "2019-09-20T17:02:01", "content_id": "941838d6d3d8089751644ec3d897dc0cab9a1ae3", "detected_licenses": [ "Unlicense" ], "directory_id": "2a790a3a78af815fa5413c558b3a08799714add1", "extension": "h", "filename": "drivers.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 206581077, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1122, "license": "Unlicense", "license_type": "permissive", "path": "/include/drivers.h", "provenance": "stackv2-0033.json.gz:176348", "repo_name": "NicoNex/kowalski-cli", "revision_date": "2019-09-20T17:02:01", "revision_id": "8a3306f91d547ec4d65342fea9af86aae8bde63a", "snapshot_id": "866ce1d26c117d1844926752d90d36df452bb363", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/NicoNex/kowalski-cli/8a3306f91d547ec4d65342fea9af86aae8bde63a/include/drivers.h", "visit_date": "2020-07-20T05:30:10.289373" }
stackv2
/* * Kowalski * Copyright (C) 2019 Nicolò Santamaria */ #ifndef DRIVERS_H_ #define DRIVERS_H_ #include <inttypes.h> #include "list.h" #define DRIVERS_FILE "res/drivers.json" struct driver { int id; int age; int rating; char *name; char *vehicle; int64_t token; }; // Loads the drivers list from a json file and returns the list head. list_t load_drivers(); // Frees the memory occupied by the drivers list. void dispose_drivers(const list_t drivers); // Updates the file that stores the information regarding the drivers. void update_drivers_file(const list_t drivers); // Adds a new driver to the list and returns its head. list_t add_driver(list_t drivers, struct driver *drv); // Deletes the driver that has the specified ID from the list and returns its head. list_t del_driver(list_t drivers, const int id); // Returns the pointer to the driver with the specified id. struct driver *get_driver_by_id(list_t drivers, const int id); // Returns the pointer to the driver with the specified token. struct driver *get_driver_by_token(list_t drivers, const int64_t token); #endif // DRIVERS_H_
2.109375
2
2024-11-18T20:15:38.473353+00:00
2021-04-07T12:19:47
ca6ba3b894f3b5034e091e738bd5ced2fa281bdb
{ "blob_id": "ca6ba3b894f3b5034e091e738bd5ced2fa281bdb", "branch_name": "refs/heads/master", "committer_date": "2021-04-07T12:19:47", "content_id": "58db55308e98b895f00a82f2df5f8721595d1a50", "detected_licenses": [ "MIT" ], "directory_id": "4adcf2abefe1acca30ac328d60090d3a631d62c1", "extension": "h", "filename": "CMultiArrayList.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 255349841, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6642, "license": "MIT", "license_type": "permissive", "path": "/include/CCollections/CMultiArrayList.h", "provenance": "stackv2-0033.json.gz:176476", "repo_name": "dfalcone/CCollections", "revision_date": "2021-04-07T12:19:47", "revision_id": "06b2bb37703a4760d3243a77e024e88f9056ac5f", "snapshot_id": "676015a56d4f7cfbcb18c615453fab1fd688e2e0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dfalcone/CCollections/06b2bb37703a4760d3243a77e024e88f9056ac5f/include/CCollections/CMultiArrayList.h", "visit_date": "2023-04-08T16:14:10.748215" }
stackv2
// MIT License - CCollections // Copyright(c) 2020 Dante Falcone (dantefalcone@gmail.com) #pragma once #include "CArrayList.h" ///////////////// // CMultiArrayList // - list of indirect keys // - multiple lists #ifdef __cplusplus extern "C" { #endif // __cplusplus // internal use only typedef struct CMultiArrayListKey { uint32_t ListIndex; uint32_t SubListIndex; } CMultiArrayListKey; uint32_t cmultiarraylistItemStride(CMultiArrayList* c); uint32_t cmultiarraylistFindListIndexFromItems(uint32_t itemsStride, uint32_t itemsCount); void cmultiarraylistAlloc(CMultiArrayList* c, uint32_t itemsStride, uint32_t keyCapacity); void cmultiarraylistFree(CMultiArrayList* c); CMultiArrayListKey cmultiarraylistAddRange(CMultiArrayList* c, void* items, uint32_t itemsCount, uint32_t itemStride); void cmultiarraylistAddRangeAtKey(CMultiArrayList* c, CMultiArrayListKey* key, void* items, uint32_t itemsCount); void cmultiarraylistRemoveRangeAtKey(CMultiArrayList* c, CMultiArrayListKey* key, uint32_t itemsIndex, uint32_t itemsCount); inline uint32_t cmultiarraylistItemStride(CMultiArrayList* c) { return carraylistItemStride(c->ArrayLists); } //inline uint32_t cmultiarraylistFindListIndexFromItemCount(CMultiArrayList* c, uint32_t itemsCount) //{ // uint32_t itemsSize = itemsCount * cmultiarraylistItemStride(c); // CList* list = c->ArrayLists; // for (uint32_t i = 0; i != 16; ++i, ++list) // { // if (itemsSize <= list->Stride) // return i; // } // return CCOLLECTION_ERROR; //} // //inline uint32_t cmultiarraylistFindListIndexFromItemsSize(CMultiArrayList* c, uint32_t itemsSize) //{ // CArrayList* list = c->ArrayLists; // for (uint32_t i = 0; i != 16; ++i, ++list) // { // if (itemsSize > list->Stride) // continue; // return i; // } // return CCOLLECTION_ERROR; //} inline uint32_t cmultiarraylistFindListIndexFromItems(uint32_t itemsStride, uint32_t itemsCount) { uint32_t itemsSize = itemsStride * itemsCount; for (uint32_t i = 0; i != 16; i = i << 1) { uint32_t capSize = i * itemsStride; if (itemsSize < capSize) return i; } return CCOLLECTION_ERROR; } inline void cmultiarraylistAlloc(CMultiArrayList* c, uint32_t itemsStride, uint32_t keyCapacity) { memset(c, 0, sizeof(CMultiArrayList)); clistAlloc(&c->Keys, (uint32_t)sizeof(CMultiArrayListKey), keyCapacity); CArrayList* itr = c->ArrayLists; CArrayList* end = itr + 16; for (uint32_t i = 16; itr != end; ++itr, i = i << 1) { itr->Stride = (uint32_t)sizeof(CArrayHeader) + (itemsStride * i); itr->Type = CCOLLECTION_TYPE_ARRAYLIST; } } inline void cmultiarraylistFree(CMultiArrayList* c) { clistFree(&c->Keys); CArrayList* itr = c->ArrayLists; CArrayList* end = itr + 16; for (; itr != end; ++itr) { if (itr->Data == NULL) continue; carraylistFree(itr); } } inline CMultiArrayListKey cmultiarraylistAddRange(CMultiArrayList* c, void* items, uint32_t itemsCount, uint32_t itemsStride) { CMultiArrayListKey key; uint32_t itemsSize = itemsStride * itemsCount; key.ListIndex = cmultiarraylistFindListIndexFromItems(itemsStride, itemsCount); CArrayList* list = &c->ArrayLists[key.ListIndex]; key.SubListIndex = list->Count; if (list->Count == list->Capacity) { // grow if (list->Capacity) { // shift to next pow 2 uint32_t newcapacity = list->Capacity << 1u; carraylistRealloc(list, newcapacity); } // first alloc else { uint32_t arrayItemsSize = list->Stride - (uint32_t)sizeof(CArrayHeader); uint32_t arrayCapacity = arrayItemsSize / itemsStride; carraylistAlloc(list, itemsStride, arrayCapacity, 8u); } // init arrays CArrayHeader* itr = (CArrayHeader*)carraylistEnd(list); CArrayHeader* end = (CArrayHeader*)carraylistCapacityEnd(list); CArrayHeader ref = { 0u, 0u, itemsStride, 0u}; for ( ; itr != end; ++itr) { *itr = ref; } } // copy CArrayHeader* header = (CArrayHeader*)carraylistEnd(list); header->Count = itemsCount; header->Capacity = (list->Stride - (uint32_t)sizeof(CArrayHeader)) / itemsStride; header->Stride = itemsStride; header->UserData = 0u; uint8_t* dst = (uint8_t*)header + sizeof(CArrayHeader); memcpy(dst, items, itemsSize); return key; } void cmultiarraylistAddRangeAtKey(CMultiArrayList* c, CMultiArrayListKey* key, void* items, uint32_t itemsCount) { CArrayList* list = &c->ArrayLists[key->ListIndex]; CArrayHeader* header = (CArrayHeader*)carraylistArrayAt(list, key->SubListIndex); uint32_t totalItemsCount = header->Count + itemsCount; if (totalItemsCount > header->Capacity) { uint32_t oldListIndex = key->ListIndex; uint32_t oldArrayIndex = key->SubListIndex; key->ListIndex = cmultiarraylistFindListIndexFromItems(header->Stride, totalItemsCount); CArrayList* movlist = &c->ArrayLists[key->ListIndex]; key->SubListIndex = carraylistAddArray(movlist); // move data to bigger list CArrayHeader* movheader = (CArrayHeader*)carraylistArrayAt(movlist, key->SubListIndex); uint32_t cpysize = header->Stride * header->Count; memcpy(carraylistData(movheader), carraylistData(header), cpysize); // update key with last array index to remove array index uint32_t lastArrayIndex = (uint32_t)((uint8_t*)carraylistLast(list) - (uint8_t*)carraylistBegin(list)); CMultiArrayListKey lastKeyVal = { oldListIndex, lastArrayIndex }; CMultiArrayListKey* lastKeyPtr = (CMultiArrayListKey*)clistItemAt(&c->Keys, clistFindIndex(&c->Keys, &lastKeyVal)); lastKeyPtr->SubListIndex = oldArrayIndex; carraylistRemoveArrayAt(list, oldArrayIndex); list = movlist; header = movheader; } // copy uint8_t* data = (uint8_t*)carraylistData(header); uint32_t dataSize = header->Stride * header->Count; uint8_t* dst = data + dataSize; uint32_t cpysize = header->Stride * itemsCount; memcpy(dst, items, cpysize); header->Count += itemsCount; } inline void cmultiarraylistRemoveRangeAtKey(CMultiArrayList* c, CMultiArrayListKey* key, uint32_t itemsIndex, uint32_t itemsCount) { CArrayList* list = &c->ArrayLists[key->ListIndex]; carraylistRemoveItemRangeAt(list, key->SubListIndex, itemsIndex, itemsCount); } #ifdef __cplusplus } #endif // __cplusplus
2.484375
2
2024-11-18T20:15:38.576946+00:00
2023-07-10T12:47:49
dd88229c604a3fb6be24449bad069844e691af22
{ "blob_id": "dd88229c604a3fb6be24449bad069844e691af22", "branch_name": "refs/heads/master", "committer_date": "2023-07-10T12:47:49", "content_id": "482d127fbe0d7d643a3b4aa768a05fbba4d9bf62", "detected_licenses": [ "MIT" ], "directory_id": "4974a3b5bf52e499c4fd4d98bf7fff3cb02087aa", "extension": "c", "filename": "Temp.c", "fork_events_count": 0, "gha_created_at": "2019-12-25T15:45:01", "gha_event_created_at": "2020-12-04T09:33:35", "gha_language": "C", "gha_license_id": "MIT", "github_id": 230122533, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1264, "license": "MIT", "license_type": "permissive", "path": "/Structure/Tree/Temp.c", "provenance": "stackv2-0033.json.gz:176607", "repo_name": "Kagurazaka-Chiaki/Homework", "revision_date": "2023-07-10T12:47:49", "revision_id": "2cde5dd21686d16aa4dca47dc64698814234ab7a", "snapshot_id": "d47d66a510d88a01e0447221828198fe94549a2d", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/Kagurazaka-Chiaki/Homework/2cde5dd21686d16aa4dca47dc64698814234ab7a/Structure/Tree/Temp.c", "visit_date": "2023-07-20T08:51:04.999320" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #define LEN 20 void b_sort(void *bs, size_t num, size_t size, int (*compar)(const void *, const void *)) { int sorted = 0; char *base = (char *) bs; // void * 算术运算g++会发出警告,为了消除警告,强制转换成char* void *ptmp = malloc(size); for (; !sorted; num--) { sorted = 1; // 每一趟都假设排序好了 for (size_t i = 1; i < num; i++) if (compar(base + i * size, base + (i - 1) * size) < 0) { sorted = 0; memcpy(ptmp, base + i * size, size); memcpy(base + i * size, base + (i - 1) * size, size); memcpy(base + (i - 1) * size, ptmp, size); } } free(ptmp); } int compar(const void *a, const void *b) { return *(int *) a - *(int *) b; } // 主函数 int main() { int max = 100, min = 1; int v[LEN]; srand(time(NULL)); for (int i = 0; i < LEN; i++) { v[i] = rand() % max + min; printf("%d %s", v[i], i == LEN - 1 ? "\n" : ""); } b_sort(v, LEN, sizeof(int), compar); for (int i = 0; i < LEN; i++) printf("%d %s", v[i], i == LEN - 1 ? "\n" : ""); return 0; }
3.140625
3
2024-11-18T20:28:20.537039+00:00
2015-07-28T10:00:17
5fa2614b6268d305cf616172f40ffdfedbdd4fae
{ "blob_id": "5fa2614b6268d305cf616172f40ffdfedbdd4fae", "branch_name": "refs/heads/master", "committer_date": "2015-07-28T10:00:17", "content_id": "bcbef184d1cc23dcfa77f4be0b872dc938891f47", "detected_licenses": [ "MIT" ], "directory_id": "13eebb17e400baec5696aba530d6f251cb69978c", "extension": "h", "filename": "im-thread.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 39498675, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5530, "license": "MIT", "license_type": "permissive", "path": "/src/im-thread.h", "provenance": "stackv2-0033.json.gz:262405", "repo_name": "tuhuayuan/imcore", "revision_date": "2015-07-28T10:00:17", "revision_id": "f9a4ef57041f78416cb7146be46e3c5a1a902a65", "snapshot_id": "7063c53638004feac60447499f8de21c4b98ff9c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tuhuayuan/imcore/f9a4ef57041f78416cb7146be46e3c5a1a902a65/src/im-thread.h", "visit_date": "2021-01-02T08:56:49.018960" }
stackv2
/* * imcore-thread.h * 线程模块 */ #ifndef _IMCORE_THREAD_H #define _IMCORE_THREAD_H #include <stdint.h> #include <stdbool.h> #include "sock.h" #ifdef POSIX #include <pthread.h> #endif #ifdef __cplusplus extern "C" { #endif /** * @brief IM线程指针 */ typedef struct im_thread im_thread_t; /** * @brief 初始化线程库。 * @details 初始化libevent线程库,以及全局的线程本地变量。 */ void im_thread_init(); /** * @brief 释放线程库 * @details 释放线程本地变量 */ void im_thread_destroy(); /** * @brief 创建一个新的线程对象。 * @details 一个IM线程包含自己的消息循环,可以使用post,send等方法 * 把操作交给线程去做。 * @return im_thread_t* 或者 NULL */ im_thread_t *im_thread_new(); /** * @brief 包装当前系统线程 * @details 创建一个新的IM线程,使用当前系统线程。break,stop等线程循环控制 * 函数不能对包装的线程调用,释放必须调用unwrap * * @return im_thread_t* 或者 NULL */ im_thread_t *im_thread_wrap_current(); /** * @brief 释放包装线程 * @details 该方法只能对当前线程是包装线程的情况下调用,为了保证不勿用所以给没有提供输入参数. * 通常在系统线程中按如下方式调用 * wrap -> run (阻塞) -> unwrap */ void im_thread_unwrap_current(); /** * @brief 释放IM线程 * @details 如果线程没有停止, 函数会阻塞等待线程结束后释放 * * @param t 需要释放的线程指针 */ void im_thread_free(im_thread_t *t); /** * @brief 获取当前线程指针 * * @return im_thread_t* 或者 NULL 表示当前线程不是一个IM线程 */ im_thread_t *im_thread_current(); /** * @brief 给定线程是否是当前线程 * * @param t 需要判别的线程指针 * @return true 或者 false t为NULL或者当前线程不是IM或者t不是当前线程 */ bool im_thread_is_current(im_thread_t *t); /** * @brief 强制结束线程 * @details 该方法作用于当前IM线程, 在当前消息处理完以后立即结束循环 * 会导致run(包装的线程 ), join, stop的阻塞立即结束. */ void im_thread_break(); /** * @brief 请求线程结束 * @details 向线程发送结束请求, 并且等待线程安全结束, 所有当前激活的消息都会被执行. * 由于不能在当前线程等待. 对当前线程结束, 因为这将是一个死循环. * * @param t 请求结束的线程指针 */ void im_thread_stop(im_thread_t *t); /** * @brief 启动线程 * @details 启动一个IM线程有并且立即返回,不能对当前线程调用 * * @param t 要启动的线程 * @param userdata 用户自定义数据 * * @return true 表示线程已经启动 */ bool im_thread_start(im_thread_t *t, void *userdata); /** * @brief 启动消息队列, 阻塞直到退出消息循环 * @details 没有给定线程指针,所以只能对当前线程调用. 线程没启动前获取不到当前线程 * 因此这个API设计的目的是用来启动wrap线程的. * * @param userdata 用户自定义数据 * @return 0 表示运行成功 */ int im_thread_run(void *userdata); /** * @brief 阻塞当前线程等待给定线程结束 * @details 不能再当前线程等待自己退出, 会导致死循环. * * @param t 要等待的线程 */ void im_thread_join(im_thread_t *t); /** * @brief 当前线程挂起 * * @param milliseconds 毫秒 * @return true 表示成功休眠 */ bool im_thread_sleep(int milliseconds); /** * @brief 消息处理函数 * * @param b 消息id * @param userdata 自定义数据 * */ typedef void(*im_thread_msg_handler)(int msg_id, void *userdata); /** * @brief POST消息给指定线程 * @details 等同于window的post消息行为, 可以给指定一个延时. * * @param sink 处理线程 * @param msg_id 消息id * @param handler 消息处理函数 * @param milliseconds 延时 * @param userdata 自定义数据 */ void im_thread_post(im_thread_t *sink, int msg_id, im_thread_msg_handler handler, long milliseconds, void *userdata); /** * @brief SEND一个消息给指定线程 * @details 等同于window的send消息, 调用会阻塞到指定线程执行完消息处理函数返回 * * @param sink 处理线程 * @param msg_id 消息id * @param handler 消息处理函数 * @param userdata 自定义数据 */ void im_thread_send(im_thread_t *sink, int msg_id, im_thread_msg_handler handler, void *userdata); /** * @brief 获取线程的even_base * * @param t 线程指针或者NULL * @return event_base* 或者 NULL */ struct event_base *im_thread_get_eventbase(im_thread_t *t); /** * @brief 获取线程的自定义数据 * * @param t 线程指针或者NULL * @return 或者 NULL */ void *im_thread_get_userdata(im_thread_t *t); /** * @brief 相当于window的Mutex */ typedef struct im_thread_mutex im_thread_mutex_t; /** * @brief 创建一个mutex * @return NULL 或者 im_thread_mutex_t* */ im_thread_mutex_t *im_thread_mutex_create(); /** * @brief 销毁一个mutex * @param mutex * @return 0 表示正常 */ int im_thread_mutex_destroy(im_thread_mutex_t *mutex); /** * @brief 获取锁 * @details 获取成功则返回并且独占锁, 或者一个等待 * * @param mutex * @return 0 表示正常 */ int im_thread_mutex_lock(im_thread_mutex_t *mutex); /** * @brief 释放锁 * * @param mutex * @return 0 表示正常 */ int im_thread_mutex_unlock(im_thread_mutex_t *mutex); #ifdef __cplusplus } #endif #endif // _IMCORE_THREAD_H
2.578125
3
2024-11-18T20:28:20.678291+00:00
2020-11-30T14:40:56
84a1659cc92f4f73abec299ccfccb92ff233f94e
{ "blob_id": "84a1659cc92f4f73abec299ccfccb92ff233f94e", "branch_name": "refs/heads/master", "committer_date": "2020-12-01T13:00:27", "content_id": "3d624b91154b9a18b9efc2e4296c641599cfd761", "detected_licenses": [ "MIT" ], "directory_id": "782da04d45e480ec122c22ae837731ce9af7febf", "extension": "c", "filename": "py_lcd.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": 21645, "license": "MIT", "license_type": "permissive", "path": "/src/omv/py/py_lcd.c", "provenance": "stackv2-0033.json.gz:262664", "repo_name": "EmbeddedSystemClass/openmv", "revision_date": "2020-11-30T14:40:56", "revision_id": "f94e5fae6467388072f534aa6fe9b35cd3d441e0", "snapshot_id": "c97c26c9bec59c9047e181e4e8382f9e53cdf49d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/EmbeddedSystemClass/openmv/f94e5fae6467388072f534aa6fe9b35cd3d441e0/src/omv/py/py_lcd.c", "visit_date": "2023-03-31T15:37:53.080408" }
stackv2
/* * This file is part of the OpenMV project. * * Copyright (c) 2013-2019 Ibrahim Abdelkader <iabdalkader@openmv.io> * Copyright (c) 2013-2019 Kwabena W. Agyeman <kwagyeman@openmv.io> * * This work is licensed under the MIT license, see the file LICENSE for details. * * LCD Python module. */ #include <mp.h> #include <objstr.h> #include <spi.h> #include <systick.h> #include "imlib.h" #include "fb_alloc.h" #include "ff_wrapper.h" #include "py_assert.h" #include "py_helper.h" #include "py_image.h" #define RST_PORT GPIOE #define RST_PIN GPIO_PIN_15 #define RST_PIN_WRITE(bit) HAL_GPIO_WritePin(RST_PORT, RST_PIN, bit); #define RS_PORT GPIOE #define RS_PIN GPIO_PIN_13 #define RS_PIN_WRITE(bit) HAL_GPIO_WritePin(RS_PORT, RS_PIN, bit); #define CS_PORT GPIOE #define CS_PIN GPIO_PIN_11 #define CS_PIN_WRITE(bit) HAL_GPIO_WritePin(CS_PORT, CS_PIN, bit); #define LED_PORT GPIOE #define LED_PIN GPIO_PIN_10 #define LED_PIN_WRITE(bit) HAL_GPIO_WritePin(LED_PORT, LED_PIN, bit); extern mp_obj_t pyb_spi_send(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args); extern mp_obj_t pyb_spi_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args); extern mp_obj_t pyb_spi_deinit(mp_obj_t self_in); static mp_obj_t spi_port = NULL; static int width = 0; static int height = 0; static enum { LCD_NONE, LCD_SHIELD_1_8 , LCD_SHIELD_0_96} type = LCD_NONE; static bool backlight_init = false; // Send out 8-bit data using the SPI object. static void lcd_write_command_byte(uint8_t data_byte) { mp_map_t arg_map; arg_map.all_keys_are_qstrs = true; arg_map.is_fixed = true; arg_map.is_ordered = true; arg_map.used = 0; arg_map.alloc = 0; arg_map.table = NULL; CS_PIN_WRITE(false); RS_PIN_WRITE(false); // command pyb_spi_send( 2, (mp_obj_t []) { spi_port, mp_obj_new_int(data_byte) }, &arg_map ); CS_PIN_WRITE(true); } // Send out 8-bit data using the SPI object. static void lcd_write_data_byte(uint8_t data_byte) { mp_map_t arg_map; arg_map.all_keys_are_qstrs = true; arg_map.is_fixed = true; arg_map.is_ordered = true; arg_map.used = 0; arg_map.alloc = 0; arg_map.table = NULL; CS_PIN_WRITE(false); RS_PIN_WRITE(true); // data pyb_spi_send( 2, (mp_obj_t []) { spi_port, mp_obj_new_int(data_byte) }, &arg_map ); CS_PIN_WRITE(true); } // Send out 8-bit data using the SPI object. static void lcd_write_command(uint8_t data_byte, uint32_t len, uint8_t *dat) { lcd_write_command_byte(data_byte); for (uint32_t i=0; i<len; i++) lcd_write_data_byte(dat[i]); } // Send out 8-bit data using the SPI object. static void lcd_write_data(uint32_t len, uint8_t *dat) { mp_obj_str_t arg_str; arg_str.base.type = &mp_type_bytes; arg_str.hash = 0; arg_str.len = len; arg_str.data = dat; mp_map_t arg_map; arg_map.all_keys_are_qstrs = true; arg_map.is_fixed = true; arg_map.is_ordered = true; arg_map.used = 0; arg_map.alloc = 0; arg_map.table = NULL; CS_PIN_WRITE(false); RS_PIN_WRITE(true); // data pyb_spi_send( 2, (mp_obj_t []) { spi_port, &arg_str }, &arg_map ); CS_PIN_WRITE(true); } static mp_obj_t py_lcd_deinit() { switch (type) { case LCD_NONE: return mp_const_none; case LCD_SHIELD_0_96: case LCD_SHIELD_1_8: HAL_GPIO_DeInit(RST_PORT, RST_PIN); HAL_GPIO_DeInit(RS_PORT, RS_PIN); HAL_GPIO_DeInit(CS_PORT, CS_PIN); pyb_spi_deinit(spi_port); spi_port = NULL; width = 0; height = 0; type = LCD_NONE; if (backlight_init) { HAL_GPIO_DeInit(LED_PORT, LED_PIN); backlight_init = false; } return mp_const_none; } return mp_const_none; } static mp_obj_t py_lcd_init(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) { py_lcd_deinit(); switch (py_helper_keyword_int(n_args, args, 0, kw_args, MP_OBJ_NEW_QSTR(MP_QSTR_type), LCD_SHIELD_0_96)) { case LCD_NONE: return mp_const_none; case LCD_SHIELD_1_8: { GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.Pull = GPIO_NOPULL; GPIO_InitStructure.Speed = GPIO_SPEED_LOW; GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_OD; GPIO_InitStructure.Pin = CS_PIN; CS_PIN_WRITE(true); // Set first to prevent glitches. HAL_GPIO_Init(CS_PORT, &GPIO_InitStructure); GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStructure.Pin = RST_PIN; RST_PIN_WRITE(true); // Set first to prevent glitches. HAL_GPIO_Init(RST_PORT, &GPIO_InitStructure); spi_port = pyb_spi_make_new(NULL, 2, // n_args 3, // n_kw (mp_obj_t []) { MP_OBJ_NEW_SMALL_INT(4), // SPI Port MP_OBJ_NEW_SMALL_INT(SPI_MODE_MASTER), MP_OBJ_NEW_QSTR(MP_QSTR_baudrate), MP_OBJ_NEW_SMALL_INT(1000000000/66), // 66 ns clk period MP_OBJ_NEW_QSTR(MP_QSTR_polarity), MP_OBJ_NEW_SMALL_INT(0), MP_OBJ_NEW_QSTR(MP_QSTR_phase), MP_OBJ_NEW_SMALL_INT(0) } ); GPIO_InitStructure.Pin = RS_PIN; RS_PIN_WRITE(true); // Set first to prevent glitches. HAL_GPIO_Init(RS_PORT, &GPIO_InitStructure); width = 128; height = 160; type = LCD_SHIELD_1_8; backlight_init = false; lcd_write_command_byte(0x01); //software reset RST_PIN_WRITE(false); systick_sleep(120); RST_PIN_WRITE(true); lcd_write_command_byte(0x01); //software reset systick_sleep(120); lcd_write_command_byte(0x11); // Sleep Exit systick_sleep(120); lcd_write_command(0xB1, 3, (uint8_t []) {0x01, 0x2C, 0x2D}); lcd_write_command_byte(0xB2); lcd_write_command(0xB3, 6, (uint8_t []) {0x01, 0x2c, 0x2d, 0x01, 0x2c, 0x2d}); lcd_write_command(0xB4, 1, (uint8_t []) {0x07}); lcd_write_command(0xC0, 3, (uint8_t []) {0xA2, 0x02, 0x84}); lcd_write_command(0xC1, 1, (uint8_t []) {0xC5}); lcd_write_command(0xC2, 2, (uint8_t []) {0x0A, 0x00}); lcd_write_command(0xC3, 2, (uint8_t []) {0x8A, 0x2A}); lcd_write_command(0xC4, 1, (uint8_t []) {0x8A, 0xEE}); lcd_write_command(0xC5, 1, (uint8_t []) {0x0E}); // Memory Data Access Control uint8_t madctl = 0xC0; uint8_t bgr = py_helper_keyword_int(n_args, args, 0, kw_args, MP_OBJ_NEW_QSTR(MP_QSTR_bgr), 0); lcd_write_command(0x36, 1, (uint8_t []) {madctl | (bgr<<3)}); // Interface Pixel Format lcd_write_command(0x3A, 1, (uint8_t []) {0x05}); // choose panel lcd_write_command_byte(0x20); // column lcd_write_command(0x2A, 4, (uint8_t []) {0, 0, 0, width-1}); // row lcd_write_command(0x2B, 4, (uint8_t []) {0, 0, 0, height-1}); // GMCTRP lcd_write_command(0xE0, 16, (uint8_t []) {0x02, 0x1c, 0x07, 0x12, 0x37, 0x32, 0x29, 0x2d, 0x29, 0x25, 0x2b, 0x39, 0x00, 0x01, 0x03, 0x10}); // GMCTRN lcd_write_command(0xE1, 16, (uint8_t []) {0x03, 0x1d, 0x07, 0x06, 0x2e, 0x2c, 0x29, 0x2d, 0x2e, 0x2e, 0x37, 0x3f, 0x00, 0x00, 0x02, 0x10}); // Display on lcd_write_command_byte(0x13); systick_sleep(10); // Display on lcd_write_command_byte(0x29); systick_sleep(100); if (!backlight_init) { GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.Pull = GPIO_NOPULL; GPIO_InitStructure.Speed = GPIO_SPEED_LOW; GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_OD; GPIO_InitStructure.Pin = LED_PIN; LED_PIN_WRITE(false); // Set first to prevent glitches. HAL_GPIO_Init(LED_PORT, &GPIO_InitStructure); backlight_init = true; } return mp_const_none; } case LCD_SHIELD_0_96: { GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.Pull = GPIO_NOPULL; GPIO_InitStructure.Speed = GPIO_SPEED_LOW; GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_OD; GPIO_InitStructure.Pin = CS_PIN; CS_PIN_WRITE(true); // Set first to prevent glitches. HAL_GPIO_Init(CS_PORT, &GPIO_InitStructure); GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStructure.Pin = RST_PIN; RST_PIN_WRITE(true); // Set first to prevent glitches. HAL_GPIO_Init(RST_PORT, &GPIO_InitStructure); spi_port = pyb_spi_make_new(NULL, 2, // n_args 3, // n_kw (mp_obj_t []) { MP_OBJ_NEW_SMALL_INT(4), // SPI Port MP_OBJ_NEW_SMALL_INT(SPI_MODE_MASTER), MP_OBJ_NEW_QSTR(MP_QSTR_prescaler), MP_OBJ_NEW_SMALL_INT(8), // 66 ns clk period MP_OBJ_NEW_QSTR(MP_QSTR_polarity), MP_OBJ_NEW_SMALL_INT(0), MP_OBJ_NEW_QSTR(MP_QSTR_phase), MP_OBJ_NEW_SMALL_INT(0) } ); GPIO_InitStructure.Pin = RS_PIN; RS_PIN_WRITE(true); // Set first to prevent glitches. HAL_GPIO_Init(RS_PORT, &GPIO_InitStructure); width = 160; height = 80; type = LCD_SHIELD_0_96; backlight_init = false; lcd_write_command_byte(0x01); //software reset RST_PIN_WRITE(false); systick_sleep(120); RST_PIN_WRITE(true); lcd_write_command_byte(0x01); //software reset systick_sleep(120); lcd_write_command_byte(0x11); // Sleep Exit systick_sleep(120); lcd_write_command(0xB1, 3, (uint8_t []) {0x01, 0x2C, 0x2D}); lcd_write_command_byte(0xB2); lcd_write_command(0xB3, 6, (uint8_t []) {0x01, 0x2c, 0x2d, 0x01, 0x2c, 0x2d}); lcd_write_command(0xB4, 1, (uint8_t []) {0x07}); lcd_write_command(0xC0, 3, (uint8_t []) {0xA2, 0x02, 0x84}); lcd_write_command(0xC1, 1, (uint8_t []) {0xC5}); lcd_write_command(0xC2, 2, (uint8_t []) {0x0A, 0x00}); lcd_write_command(0xC3, 2, (uint8_t []) {0x8A, 0x2A}); lcd_write_command(0xC4, 1, (uint8_t []) {0x8A, 0xEE}); lcd_write_command(0xC5, 1, (uint8_t []) {0x0E}); // choose panel lcd_write_command_byte(0x21); // Memory Data Access Control uint8_t madctl = 0xA0; uint8_t bgr = py_helper_keyword_int(n_args, args, 0, kw_args, MP_OBJ_NEW_QSTR(MP_QSTR_bgr), 1); lcd_write_command(0x36, 1, (uint8_t []) {madctl | (bgr<<3)}); // Interface Pixel Format lcd_write_command(0x3A, 1, (uint8_t []) {0x05}); // set Window uint8_t xPos = 1; uint8_t yPos = 26; // column lcd_write_command(0x2A, 4, (uint8_t []) {0, xPos&0xFF, 0, xPos+width-1}); // row lcd_write_command(0x2B, 4, (uint8_t []) {0, yPos&0xFF, 0, yPos+height-1}); // GMCTRP lcd_write_command(0xE0, 16, (uint8_t []) {0x02, 0x1c, 0x07, 0x12, 0x37, 0x32, 0x29, 0x2d, 0x29, 0x25, 0x2b, 0x39, 0x00, 0x01, 0x03, 0x10}); // GMCTRN lcd_write_command(0xE1, 16, (uint8_t []) {0x03, 0x1d, 0x07, 0x06, 0x2e, 0x2c, 0x29, 0x2d, 0x2e, 0x2e, 0x37, 0x3f, 0x00, 0x00, 0x02, 0x10}); // Display on lcd_write_command_byte(0x13); systick_sleep(10); lcd_write_command_byte(0x29); systick_sleep(100); if (!backlight_init) { GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.Pull = GPIO_NOPULL; GPIO_InitStructure.Speed = GPIO_SPEED_LOW; GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_OD; GPIO_InitStructure.Pin = LED_PIN; LED_PIN_WRITE(false); // Set first to prevent glitches. HAL_GPIO_Init(LED_PORT, &GPIO_InitStructure); backlight_init = true; } return mp_const_none; } } return mp_const_none; } static mp_obj_t py_lcd_width() { if (type == LCD_NONE) return mp_const_none; return mp_obj_new_int(width); } static mp_obj_t py_lcd_height() { if (type == LCD_NONE) return mp_const_none; return mp_obj_new_int(height); } static mp_obj_t py_lcd_type() { if (type == LCD_NONE) return mp_const_none; return mp_obj_new_int(type); } static mp_obj_t py_lcd_set_backlight(mp_obj_t state_obj) { switch (type) { case LCD_NONE: return mp_const_none; case LCD_SHIELD_0_96: case LCD_SHIELD_1_8: { bool bit = !mp_obj_get_int(state_obj); if (!backlight_init) { GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.Pull = GPIO_NOPULL; GPIO_InitStructure.Speed = GPIO_SPEED_LOW; GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_OD; GPIO_InitStructure.Pin = LED_PIN; LED_PIN_WRITE(bit); // Set first to prevent glitches. HAL_GPIO_Init(LED_PORT, &GPIO_InitStructure); backlight_init = true; } LED_PIN_WRITE(bit); return mp_const_none; } } return mp_const_none; } static mp_obj_t py_lcd_get_backlight() { switch (type) { case LCD_NONE: return mp_const_none; case LCD_SHIELD_0_96: case LCD_SHIELD_1_8: if (!backlight_init) { return mp_const_none; } return mp_obj_new_int(!HAL_GPIO_ReadPin(LED_PORT, LED_PIN)); } return mp_const_none; } static mp_obj_t py_lcd_display(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) { image_t *arg_img = py_image_cobj(args[0]); PY_ASSERT_TRUE_MSG(IM_IS_MUTABLE(arg_img), "Image format is not supported."); rectangle_t rect; py_helper_keyword_rectangle_roi(arg_img, n_args, args, 1, kw_args, &rect); // Fit X. int l_pad = 0, r_pad = 0; if (rect.w > width) { int adjust = rect.w - width; rect.w -= adjust; rect.x += adjust / 2; } else if (rect.w < width) { int adjust = width - rect.w; l_pad = adjust / 2; r_pad = (adjust + 1) / 2; } // Fit Y. int t_pad = 0, b_pad = 0; if (rect.h > height) { int adjust = rect.h - height; rect.h -= adjust; rect.y += adjust / 2; } else if (rect.h < height) { int adjust = height - rect.h; t_pad = adjust / 2; b_pad = (adjust + 1) / 2; } switch (type) { case LCD_NONE: return mp_const_none; case LCD_SHIELD_1_8: lcd_write_command_byte(0x2C); fb_alloc_mark(); uint8_t *zero = fb_alloc0(width*2, FB_ALLOC_NO_HINT); uint16_t *line = fb_alloc(width*2, FB_ALLOC_NO_HINT); for (int i=0; i<t_pad; i++) { lcd_write_data(width*2, zero); } for (int i=0; i<rect.h; i++) { if (l_pad) { lcd_write_data(l_pad*2, zero); // l_pad < width } if (IM_IS_GS(arg_img)) { for (int j=0; j<rect.w; j++) { uint8_t pixel = IM_GET_GS_PIXEL(arg_img, (rect.x + j), (rect.y + i)); line[j] = IM_RGB565(IM_R825(pixel),IM_G826(pixel),IM_B825(pixel)); } lcd_write_data(rect.w*2, (uint8_t *) line); } else { lcd_write_data(rect.w*2, (uint8_t *) (((uint16_t *) arg_img->pixels) + ((rect.y + i) * arg_img->w) + rect.x)); } if (r_pad) { lcd_write_data(r_pad*2, zero); // r_pad < width } } for (int i=0; i<b_pad; i++) { lcd_write_data(width*2, zero); } fb_alloc_free_till_mark(); return mp_const_none; case LCD_SHIELD_0_96: // column lcd_write_command(0x2A, 2, (uint8_t []) {0, 1}); // row lcd_write_command(0x2B, 2, (uint8_t []) {0, 26}); lcd_write_command_byte(0x2C); fb_alloc_mark(); uint8_t *zero_096 = fb_alloc0(width*2, FB_ALLOC_NO_HINT); uint16_t *line_096 = fb_alloc(width*2, FB_ALLOC_NO_HINT); for (int i=0; i<t_pad; i++) { lcd_write_data(width*2, zero_096); } for (int i=0; i<rect.h; i++) { if (l_pad) { lcd_write_data(l_pad*2, zero_096); // l_pad < width } if (IM_IS_GS(arg_img)) { for (int j=0; j<rect.w; j++) { uint8_t pixel = IM_GET_GS_PIXEL(arg_img, (rect.x + j), (rect.y + i)); line_096[j] = IM_RGB565(IM_R825(pixel),IM_G826(pixel),IM_B825(pixel)); } lcd_write_data(rect.w*2, (uint8_t *) line_096); } else { lcd_write_data(rect.w*2, (uint8_t *) (((uint16_t *) arg_img->pixels) + ((rect.y + i) * arg_img->w) + rect.x)); } if (r_pad) { lcd_write_data(r_pad*2, zero_096); // r_pad < width } } for (int i=0; i<b_pad; i++) { lcd_write_data(width*2, zero_096); } fb_alloc_free_till_mark(); return mp_const_none; } return mp_const_none; } static mp_obj_t py_lcd_clear() { switch (type) { case LCD_NONE: return mp_const_none; case LCD_SHIELD_0_96: // column lcd_write_command(0x2A, 2, (uint8_t []) {0, 1}); // row lcd_write_command(0x2B, 2, (uint8_t []) {0, 26}); lcd_write_command_byte(0x2C); fb_alloc_mark(); uint8_t *zero_096 = fb_alloc0(width*2, FB_ALLOC_NO_HINT); for (int i=0; i<height; i++) { lcd_write_data(width*2, zero_096); } fb_alloc_free_till_mark(); return mp_const_none; case LCD_SHIELD_1_8: lcd_write_command_byte(0x2C); fb_alloc_mark(); uint8_t *zero = fb_alloc0(width*2, FB_ALLOC_NO_HINT); for (int i=0; i<height; i++) { lcd_write_data(width*2, zero); } fb_alloc_free_till_mark(); return mp_const_none; } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(py_lcd_init_obj, 0, py_lcd_init); STATIC MP_DEFINE_CONST_FUN_OBJ_0(py_lcd_deinit_obj, py_lcd_deinit); STATIC MP_DEFINE_CONST_FUN_OBJ_0(py_lcd_width_obj, py_lcd_width); STATIC MP_DEFINE_CONST_FUN_OBJ_0(py_lcd_height_obj, py_lcd_height); STATIC MP_DEFINE_CONST_FUN_OBJ_0(py_lcd_type_obj, py_lcd_type); STATIC MP_DEFINE_CONST_FUN_OBJ_1(py_lcd_set_backlight_obj, py_lcd_set_backlight); STATIC MP_DEFINE_CONST_FUN_OBJ_0(py_lcd_get_backlight_obj, py_lcd_get_backlight); STATIC MP_DEFINE_CONST_FUN_OBJ_KW(py_lcd_display_obj, 1, py_lcd_display); STATIC MP_DEFINE_CONST_FUN_OBJ_0(py_lcd_clear_obj, py_lcd_clear); static const mp_map_elem_t globals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_lcd) }, { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&py_lcd_init_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&py_lcd_deinit_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_width), (mp_obj_t)&py_lcd_width_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_height), (mp_obj_t)&py_lcd_height_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_type), (mp_obj_t)&py_lcd_type_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_backlight), (mp_obj_t)&py_lcd_set_backlight_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_get_backlight), (mp_obj_t)&py_lcd_get_backlight_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_display), (mp_obj_t)&py_lcd_display_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_clear), (mp_obj_t)&py_lcd_clear_obj }, { NULL, NULL }, }; STATIC MP_DEFINE_CONST_DICT(globals_dict, globals_dict_table); const mp_obj_module_t lcd_module = { .base = { &mp_type_module }, .globals = (mp_obj_t)&globals_dict, }; void py_lcd_init0() { py_lcd_deinit(); }
2.078125
2
2024-11-18T20:28:21.286854+00:00
2019-08-22T14:46:28
a7570bca2311ba3d362ad853a2f36fec33161cc8
{ "blob_id": "a7570bca2311ba3d362ad853a2f36fec33161cc8", "branch_name": "refs/heads/master", "committer_date": "2019-08-22T14:46:28", "content_id": "75e9f2018a116f8b01dcc01d84dfb6eca636882a", "detected_licenses": [ "MIT" ], "directory_id": "31fc9b36fc1022150ef5478c72cf1877450d6b6e", "extension": "c", "filename": "jit_test.c", "fork_events_count": 0, "gha_created_at": "2019-09-19T22:01:04", "gha_event_created_at": "2019-09-19T22:01:04", "gha_language": null, "gha_license_id": "MIT", "github_id": 209655847, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 697, "license": "MIT", "license_type": "permissive", "path": "/jit_test.c", "provenance": "stackv2-0033.json.gz:262794", "repo_name": "namin/nfv-benchmark", "revision_date": "2019-08-22T14:46:28", "revision_id": "618655e6ca2f2cff14f9ff8e6417e17255e621b7", "snapshot_id": "edbe52e10534604a411230301323408dfc855d5a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/namin/nfv-benchmark/618655e6ca2f2cff14f9ff8e6417e17255e621b7/jit_test.c", "visit_date": "2020-07-29T03:41:36.086783" }
stackv2
#include "log.h" #include "packets.h" #include "pipeline.h" #include "benchmark.h" #include <stdio.h> void jit_test(struct packet_pool_t *pool, uint32_t repeat) { log_info("In the jit test module."); packet_index_t batch_size = 0; packet_t *pkts[32] = {0}; struct benchmark_t bench; benchmark_config_init(&bench); struct pipeline_t *pipe = bench.pipeline; uint64_t count = 0; for (uint32_t i = 0; i < repeat; ++i) { while ((batch_size = packets_pool_next_batch(pool, pkts, 32)) != 0) { pipeline_process(pipe, pkts, batch_size); count+= batch_size; } packets_pool_reset(pool); } pipeline_release(pipe); }
2.1875
2
2024-11-18T20:55:22.669345+00:00
2020-10-28T07:16:32
468c28f7f46c524caaa79be4dea42c21b6a71f77
{ "blob_id": "468c28f7f46c524caaa79be4dea42c21b6a71f77", "branch_name": "refs/heads/master", "committer_date": "2020-10-28T07:16:32", "content_id": "e37d3b087a3f975c159bc70969b41a4ff9ba6a83", "detected_licenses": [ "Apache-2.0" ], "directory_id": "287dc1683f7e19a5239c2b8addbc8531809f9177", "extension": "c", "filename": "majority_num.c", "fork_events_count": 0, "gha_created_at": "2019-01-03T22:02:24", "gha_event_created_at": "2023-01-06T00:39:06", "gha_language": "C++", "gha_license_id": "Apache-2.0", "github_id": 164027453, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 470, "license": "Apache-2.0", "license_type": "permissive", "path": "/mooc42-dongfei-algo/class8/majority_num.c", "provenance": "stackv2-0034.json.gz:110050", "repo_name": "yaominzh/CodeLrn2019", "revision_date": "2020-10-28T07:16:32", "revision_id": "adc727d92904c5c5d445a2621813dfa99474206d", "snapshot_id": "ea192cf18981816c6adafe43d85e2462d4bc6e5d", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/yaominzh/CodeLrn2019/adc727d92904c5c5d445a2621813dfa99474206d/mooc42-dongfei-algo/class8/majority_num.c", "visit_date": "2023-01-06T14:11:45.281011" }
stackv2
class Solution { public: int majorityNumber(vector<int> nums) { int candidate, count = 0; for (int i = 0; i < nums.size(); i++) { if (count == 0) { candidate = nums[i]; count ++; } else { if (candidate == nums[i]) { count ++; } else { count --; } } } return candidate; } };
2.34375
2
2024-11-18T20:55:22.935742+00:00
2020-05-07T13:32:51
8d9b9e2a76acaaebbf33036995b20c3e610555ee
{ "blob_id": "8d9b9e2a76acaaebbf33036995b20c3e610555ee", "branch_name": "refs/heads/master", "committer_date": "2020-05-07T13:32:51", "content_id": "a901c9e2f062c56e0670aa60f6093986e5d366d5", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "79ce09c472987d0ae993ac73f9a84929fe5faaac", "extension": "c", "filename": "umka.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": 2400, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/umka.c", "provenance": "stackv2-0034.json.gz:110179", "repo_name": "Laeeth/umka-lang", "revision_date": "2020-05-07T13:32:51", "revision_id": "d50e34a618dcdfcf488fb50f7aa4fc46e5d94a13", "snapshot_id": "0e3ec7763ef5e28b8d758c5d753d22ed5dba5cfe", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Laeeth/umka-lang/d50e34a618dcdfcf488fb50f7aa4fc46e5d94a13/src/umka.c", "visit_date": "2022-06-23T06:38:35.994523" }
stackv2
#define __USE_MINGW_ANSI_STDIO 1 #include <stdio.h> #include <stdlib.h> #include <string.h> #include "umka_api.h" // Umka extension example void meow(UmkaStackSlot *params, UmkaStackSlot *result) { int i = params[0].intVal; printf("Meow! (%d)\n", i); result->intVal = i; } int main(int argc, char **argv) { if (argc < 2) { printf("Umka interpreter (C) Vasiliy Tereshkov, 2020\n"); printf("Usage: umka <file.um> [-storage <storage-size>] [-stack <stack-size>]\n"); return 1; } int storageSize = 1024 * 1024; // Bytes int stackSize = 1024 * 1024; // Slots for (int i = 0; i < 4; i += 2) { if (argc > 2 + i) { if (strcmp(argv[2 + i], "-storage") == 0) { if (argc == 2 + i + 1) { printf("Illegal command line parameter\n"); return 1; } storageSize = strtol(argv[2 + i + 1], NULL, 0); if (storageSize <= 0) { printf("Illegal storage size\n"); return 1; } } else if (strcmp(argv[2 + i], "-stack") == 0) { if (argc == 2 + i + 1) { printf("Illegal command line parameter\n"); return 1; } stackSize = strtol(argv[2 + i + 1], NULL, 0); if (stackSize <= 0) { printf("Illegal stack size\n"); return 1; } } } } int res = umkaInit(argv[1], storageSize, argc, argv); if (res == 0) { umkaAddFunc("meow", &meow); res = umkaCompile(); } if (res == 0) { res = umkaRun(stackSize); if (res != 0) { UmkaError error; umkaGetError(&error); printf("Runtime error %s (%d): %s\n", error.fileName, error.line, error.msg); } } else { UmkaError error; umkaGetError(&error); printf("Error %s (%d, %d): %s\n", error.fileName, error.line, error.pos, error.msg); } if (res == 0) res = umkaFree(); return res; }
2.640625
3
2024-11-18T20:55:23.127958+00:00
2023-01-13T15:32:42
4e001b0d1736462dcd64929226451d63880caa0a
{ "blob_id": "4e001b0d1736462dcd64929226451d63880caa0a", "branch_name": "refs/heads/master", "committer_date": "2023-01-13T15:32:42", "content_id": "67e3d6c444c3808749ab0974972d8fc9b9d7a214", "detected_licenses": [ "MIT" ], "directory_id": "6bdf49c3b8913bcf15746e0b91666b56111804b4", "extension": "h", "filename": "slab.h", "fork_events_count": 54, "gha_created_at": "2019-05-09T09:57:09", "gha_event_created_at": "2022-07-07T17:12:27", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 185773406, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6260, "license": "MIT", "license_type": "permissive", "path": "/mentos/inc/mem/slab.h", "provenance": "stackv2-0034.json.gz:110437", "repo_name": "mentos-team/MentOS", "revision_date": "2023-01-13T15:32:42", "revision_id": "0ecda4d40c3b63cf23abe332ba2d2c236d2a3363", "snapshot_id": "71d3108effbb5c2a1fae476c61f00c70350d2baa", "src_encoding": "UTF-8", "star_events_count": 75, "url": "https://raw.githubusercontent.com/mentos-team/MentOS/0ecda4d40c3b63cf23abe332ba2d2c236d2a3363/mentos/inc/mem/slab.h", "visit_date": "2023-07-25T15:44:06.367100" }
stackv2
/// @file slab.h /// @brief Functions and structures for managing memory slabs. /// @copyright (c) 2014-2022 This file is distributed under the MIT License. /// See LICENSE.md for details. #pragma once #include "klib/list_head.h" #include "stddef.h" #include "mem/gfp.h" /// @brief Type for slab flags. typedef unsigned int slab_flags_t; /// Create a new cache. #define KMEM_CREATE(objtype) kmem_cache_create(#objtype, \ sizeof(objtype), \ alignof(objtype), \ GFP_KERNEL, \ NULL, \ NULL) /// Creates a new cache and allows to specify the constructor. #define KMEM_CREATE_CTOR(objtype, ctor) kmem_cache_create(#objtype, \ sizeof(objtype), \ alignof(objtype), \ GFP_KERNEL, \ ((void (*)(void *))(ctor)), \ NULL) /// @brief Stores the information of a cache. typedef struct kmem_cache_t { /// Handler for placing it inside a lists of caches. list_head cache_list; /// Name of the cache. const char *name; /// Size of the cache. unsigned int size; /// Size of the objects contained in the cache. unsigned int object_size; /// Alignment requirement of the type of objects. unsigned int align; /// The total number of slabs. unsigned int total_num; /// The number of free slabs. unsigned int free_num; /// The Get Free Pages (GFP) flags. slab_flags_t flags; /// The order for getting free pages. unsigned int gfp_order; /// Constructor for the elements. void (*ctor)(void *); /// Destructor for the elements. void (*dtor)(void *); /// Handler for the full slabs list. list_head slabs_full; /// Handler for the partial slabs list. list_head slabs_partial; /// Handler for the free slabs list. list_head slabs_free; } kmem_cache_t; /// Initialize the slab system void kmem_cache_init(); /// @brief Creates a new slab cache. /// @param name Name of the cache. /// @param size Size of the objects contained inside the cache. /// @param align Memory alignment for the objects inside the cache. /// @param flags Flags used to define the properties of the cache. /// @param ctor Constructor for initializing the cache elements. /// @param dtor Destructor for finalizing the cache elements. /// @return Pointer to the object used to manage the cache. kmem_cache_t *kmem_cache_create( const char *name, unsigned int size, unsigned int align, slab_flags_t flags, void (*ctor)(void *), void (*dtor)(void *)); /// @brief Deletes the given cache. /// @param cachep Pointer to the cache. void kmem_cache_destroy(kmem_cache_t *cachep); #ifdef ENABLE_CACHE_TRACE /// @brief Allocs a new object using the provided cache. /// @param file File where the object is allocated. /// @param fun Function where the object is allocated. /// @param line Line inside the file. /// @param cachep The cache used to allocate the object. /// @param flags Flags used to define where we are going to Get Free Pages (GFP). /// @return Pointer to the allocated space. void *pr_kmem_cache_alloc(const char *file, const char *fun, int line, kmem_cache_t *cachep, gfp_t flags); /// @brief Frees an cache allocated object. /// @param file File where the object is deallocated. /// @param fun Function where the object is deallocated. /// @param line Line inside the file. /// @param addr Address of the object. void pr_kmem_cache_free(const char *file, const char *fun, int line, void *addr); /// Wrapper that provides the filename, the function and line where the alloc is happening. #define kmem_cache_alloc(...) pr_kmem_cache_alloc(__FILE__, __func__, __LINE__, __VA_ARGS__) /// Wrapper that provides the filename, the function and line where the free is happening. #define kmem_cache_free(...) pr_kmem_cache_free(__FILE__, __func__, __LINE__, __VA_ARGS__) #else /// @brief Allocs a new object using the provided cache. /// @param cachep The cache used to allocate the object. /// @param flags Flags used to define where we are going to Get Free Pages (GFP). /// @return Pointer to the allocated space. void *kmem_cache_alloc(kmem_cache_t *cachep, gfp_t flags); /// @brief Frees an cache allocated object. /// @param addr Address of the object. void kmem_cache_free(void *addr); #endif #ifdef ENABLE_ALLOC_TRACE /// @brief Provides dynamically allocated memory in kernel space. /// @param file File where the object is allocated. /// @param fun Function where the object is allocated. /// @param line Line inside the file. /// @param size The amount of memory to allocate. /// @return A pointer to the allocated memory. void *pr_kmalloc(const char *file, const char *fun, int line, unsigned int size); /// @brief Frees dynamically allocated memory in kernel space. /// @param file File where the object is deallocated. /// @param fun Function where the object is deallocated. /// @param line Line inside the file. /// @param ptr The pointer to the allocated memory. void pr_kfree(const char *file, const char *fun, int line, void *addr); /// Wrapper that provides the filename, the function and line where the alloc is happening. #define kmalloc(...) pr_kmalloc(__FILE__, __func__, __LINE__, __VA_ARGS__) /// Wrapper that provides the filename, the function and line where the free is happening. #define kfree(...) pr_kfree(__FILE__, __func__, __LINE__, __VA_ARGS__) #else /// @brief Provides dynamically allocated memory in kernel space. /// @param size The amount of memory to allocate. /// @return A pointer to the allocated memory. void *kmalloc(unsigned int size); /// @brief Frees dynamically allocated memory in kernel space. /// @param ptr The pointer to the allocated memory. void kfree(void *ptr); #endif
2.484375
2
2024-11-18T19:19:47.098687+00:00
2021-09-16T05:48:51
97a3768ec09c38342f6d5568aad9b2af161df293
{ "blob_id": "97a3768ec09c38342f6d5568aad9b2af161df293", "branch_name": "refs/heads/master", "committer_date": "2021-09-16T05:48:51", "content_id": "0372cd0d54db9fda07404efd6dd411339a7f1d91", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "3597c7193ff73de81d2867891062627fed1efd66", "extension": "h", "filename": "start08.h", "fork_events_count": 5, "gha_created_at": "2016-09-15T18:19:14", "gha_event_created_at": "2021-08-13T03:44:18", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 68319577, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3329, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/hc08c/include/start08.h", "provenance": "stackv2-0036.json.gz:18", "repo_name": "exsilium/pxbee-trigger", "revision_date": "2021-09-16T05:48:51", "revision_id": "b1b9095bb0e152e2a6fd9291a0ff0388933eea59", "snapshot_id": "3c06a7e4b63701f95a12b7d6be3b9ea2743ce8cc", "src_encoding": "UTF-8", "star_events_count": 27, "url": "https://raw.githubusercontent.com/exsilium/pxbee-trigger/b1b9095bb0e152e2a6fd9291a0ff0388933eea59/hc08c/include/start08.h", "visit_date": "2021-09-24T12:41:27.515840" }
stackv2
/****************************************************************************** FILE : start08.h PURPOSE : datastructures for startup LANGUAGE: ANSI-C */ /********************************************************************************/ #ifndef START08_H #define START08_H #ifdef __cplusplus extern "C" { #endif #include <hidef.h> /* the following data structures contain the data needed to initialize the processor and memory */ typedef struct{ unsigned char *_FAR beg; int size; /* [beg..beg+size] */ } _Range; typedef struct _Copy{ int size; unsigned char *_FAR dest; } _Copy; typedef void (*_PFunc)(void); typedef struct _LibInit{ _PFunc *startup; /* address of startup desc */ } _LibInit; typedef struct _Cpp{ _PFunc initFunc; /* address of init function */ } _Cpp; #define STARTUP_FLAGS_NONE 0 #define STARTUP_FLAGS_ROM_LIB (1<<0) /* if module is a ROM library */ #define STARTUP_FLAGS_NOT_INIT_SP (1<<1) /* if stack pointer has not to be initialized */ #pragma DATA_SEG FAR _STARTUP #ifdef __ELF_OBJECT_FILE_FORMAT__ /* ELF/DWARF object file format */ /* attention: the linker scans the debug information for these structures */ /* to obtain the available fields and their sizes. */ /* So don't change the names in this file. */ extern struct _tagStartup { #ifndef __NO_FLAGS_OFFSET unsigned char flags; /* STARTUP_FLAGS_xxx */ #endif #ifndef __NO_MAIN_OFFSET _PFunc main; /* top level procedure of user program */ #endif unsigned short nofZeroOuts; /* number of zero out ranges */ _Range *_FAR pZeroOut; /* vector of ranges with nofZeroOuts elements */ _Copy *_FAR toCopyDownBeg; /* ROM-address where copy down-data begins */ #if 0 /* switch on to implement ROM libraries */ unsigned short nofLibInits; /* number of library startup descriptors */ _LibInit *_FAR libInits; /* vector of pointers to library startup descriptors */ #endif #if defined(__cplusplus) unsigned short nofInitBodies; /* number of init functions for C++ constructors */ _Cpp *_FAR initBodies; /* vector of function pointers to init functions for C++ constructors */ #endif } _startupData; #else extern struct _tagStartup{ unsigned flags; _PFunc main; /* top procedure of user program */ unsigned dataPage; /* page where data allocation begins */ long stackOffset; int nofZeroOuts; _Range *_FAR pZeroOut; /* pZeroOut is a vector of ranges with nofZeroOuts elements */ long toCopyDownBeg; /* ROM-address where copy down-data begins */ _PFunc *_FAR mInits; /* mInits is a vector of function pointers, terminated by 0 */ _PFunc *_FAR libInits; /* libInits is a vector of function pointers, terminated by 0x0000FFFF */ } _startupData; #endif #pragma DATA_SEG DEFAULT #pragma push #include "non_bank.sgm" /* _Startup is referred by the reset vector -> must be non banked. */ extern void _Startup(void); /* execution begins in this procedure */ /*-------------------------------------------------------------------*/ #pragma pop #ifdef __cplusplus } #endif #endif
2.296875
2
2024-11-18T19:19:48.654677+00:00
2017-07-18T12:59:34
8a6df88630da0efdd97d992a23dcd09e168bfc09
{ "blob_id": "8a6df88630da0efdd97d992a23dcd09e168bfc09", "branch_name": "refs/heads/master", "committer_date": "2017-07-18T12:59:34", "content_id": "e1306193113d14b19b6d18a2152a9526602ce107", "detected_licenses": [ "MIT" ], "directory_id": "fbf1998c4cdd28d89c0e856a59db51aad73a8a7e", "extension": "c", "filename": "pal_file_win.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": 5579, "license": "MIT", "license_type": "permissive", "path": "/src/pal/pal_file_win.c", "provenance": "stackv2-0036.json.gz:403", "repo_name": "Mesh-Systems-Eng/iot-edge-opc-proxy", "revision_date": "2017-07-18T12:59:34", "revision_id": "755dea333b8b320f26a9e1f9683cfa572d01aac9", "snapshot_id": "90be70e943c4d440a6aa8a07ec7535288f40c995", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Mesh-Systems-Eng/iot-edge-opc-proxy/755dea333b8b320f26a9e1f9683cfa572d01aac9/src/pal/pal_file_win.c", "visit_date": "2023-07-20T02:25:08.596616" }
stackv2
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "os.h" #include "util_mem.h" #include "pal_file.h" #include "pal_err.h" #include "util_string.h" #include "util_misc.h" const char* k_sep = "\\"; // // Enumerate all drives // static int32_t pal_read_drives( pal_dir_cb_t cb, void* context ) { int32_t result; DWORD drives; prx_file_info_t palstat; char drive_path[4]; dbg_assert_ptr(cb); drive_path[0] = 'C'; drive_path[1] = ':'; drive_path[2] = '\\'; drive_path[3] = 0; memset(&palstat, 0, sizeof(prx_file_info_t)); palstat.type = prx_file_type_dir; result = er_nomore; drives = GetLogicalDrives(); for (char x = 'A'; drives && x <= 'Z'; x++) { if (drives & 1) { drive_path[0] = x; if (er_ok != cb(context, er_ok, drive_path, &palstat)) { result = er_ok; break; } } drives >>= 1; } return result != er_ok ? cb(context, result, NULL, NULL) : er_ok; } // // Initialize // int32_t pal_file_init( void ) { return er_ok; } // // Test whether file exists // bool pal_file_exists( const char* file_name ) { DWORD attributes = GetFileAttributesA(file_name); return (attributes != INVALID_FILE_ATTRIBUTES && !(attributes & FILE_ATTRIBUTE_DIRECTORY)); } // // Get Full path of a file name // int32_t pal_get_real_path( const char* file_name, const char** path ) { DWORD copied; char *buf = NULL; chk_arg_fault_return(file_name); chk_arg_fault_return(path); buf = (char*)mem_alloc(MAX_PATH); if (!buf) return er_out_of_memory; copied = GetFullPathNameA(file_name, MAX_PATH, buf, NULL); if (!copied || copied > MAX_PATH) { mem_free(buf); return copied ? er_fatal : pal_os_last_error_as_prx_error(); } *path = buf; return er_ok; } // // Traverse a folder and call callback for each file // int32_t pal_read_dir( const char* dir_name, pal_dir_cb_t cb, void* context ) { int32_t result; HANDLE h_find; WIN32_FIND_DATAA data; ULARGE_INTEGER ull; STRING_HANDLE root, file = NULL; prx_file_info_t palstat; chk_arg_fault_return(dir_name); chk_arg_fault_return(cb); // Handle drive letter enumeration if (!*dir_name || *dir_name == '/') return pal_read_drives(cb, context); root = STRING_construct_n(dir_name, string_trim_back_len(dir_name, strlen(dir_name), k_sep)); if (!root) return er_out_of_memory; do { result = er_out_of_memory; if (0 != STRING_concat(root, k_sep)) break; file = STRING_clone(root); if (!file || 0 != STRING_concat(file, "*")) break; h_find = FindFirstFileA(STRING_c_str(file), &data); if (h_find == INVALID_HANDLE_VALUE) { result = cb(context, pal_os_last_error_as_prx_error(), NULL, NULL); if (result == er_nomore) result = er_ok; break; } result = er_not_found; while(true) { if (!data.cFileName[0] || (data.cFileName[0] == '.' && !data.cFileName[1]) || (data.cFileName[0] == '.' && data.cFileName[1] == '.' && !data.cFileName[2])) { // Skipping ".", ".." or empty path... } else { STRING_delete(file); file = STRING_clone(root); if (!file || 0 != STRING_concat(file, data.cFileName)) { result = er_out_of_memory; break; } memset(&palstat, 0, sizeof(prx_file_info_t)); ull.u.HighPart = data.nFileSizeHigh; ull.u.LowPart = data.nFileSizeLow; palstat.total_size = ull.QuadPart; ull.u.LowPart = data.ftLastAccessTime.dwLowDateTime; ull.u.HighPart = data.ftLastAccessTime.dwHighDateTime; palstat.last_atime = ull.QuadPart / 10000000ULL - 11644473600ULL; ull.u.LowPart = data.ftLastWriteTime.dwLowDateTime; ull.u.HighPart = data.ftLastWriteTime.dwHighDateTime; palstat.last_mtime = ull.QuadPart / 10000000ULL - 11644473600ULL; /**/ if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) palstat.type = prx_file_type_dir; else palstat.type = prx_file_type_file; if (er_ok != cb(context, er_ok, STRING_c_str(file), &palstat)) { result = er_ok; break; } } if (!FindNextFileA(h_find, &data)) { result = pal_os_last_error_as_prx_error(); break; } } (void)FindClose(h_find); if (result != er_ok) result = cb(context, result, NULL, NULL); if (result == er_nomore) result = er_ok; break; } while (0); if (file) STRING_delete(file); STRING_delete(root); return result; } // // Free path // void pal_free_path( const char* path ) { if (!path) return; mem_free((char*)path); } // // Deinit // void pal_file_deinit( void ) { // no-op }
2.359375
2
2024-11-18T19:20:49.382431+00:00
2023-01-30T09:21:37
912615a6da3b0705e13b29e48e07c1b31e0cb16a
{ "blob_id": "912615a6da3b0705e13b29e48e07c1b31e0cb16a", "branch_name": "refs/heads/master", "committer_date": "2023-01-30T09:21:37", "content_id": "b6a47640bb756a2ddf758434416502acc0005b62", "detected_licenses": [ "MIT" ], "directory_id": "c000832959af901aed5cb2ae9258631354f2817b", "extension": "c", "filename": "fl2.c", "fork_events_count": 7, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 241288950, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 443, "license": "MIT", "license_type": "permissive", "path": "/Section 18/fl2.c", "provenance": "stackv2-0036.json.gz:916", "repo_name": "PacktPublishing/Programming-in-C-The-Complete-Course", "revision_date": "2023-01-30T09:21:37", "revision_id": "e07c93fbfd583e7cb5f0532970ff574e4dc4137e", "snapshot_id": "b127a0751988f420afd160e19e0e669e01455ced", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/PacktPublishing/Programming-in-C-The-Complete-Course/e07c93fbfd583e7cb5f0532970ff574e4dc4137e/Section 18/fl2.c", "visit_date": "2023-02-04T19:19:04.083450" }
stackv2
// WAP that reads character by character from a file and displays on screen #include <stdio.h> #include <stdlib.h> int main() { FILE *fpnt ; // decl. of pointer to structure FILE char mychar ; fpnt=fopen("c:\\myfiles\\data.txt","r"); if(fpnt==NULL) { printf("Unable to open the file ....."); exit(0); // terminates the program } while (mychar!=EOF) { mychar=fgetc(fpnt); putchar(mychar); } fclose(fpnt); }
3.203125
3
2024-11-18T19:59:50.111778+00:00
2021-10-18T08:51:32
5598e6546390a4f7798b6f1bb492031bbc866554
{ "blob_id": "5598e6546390a4f7798b6f1bb492031bbc866554", "branch_name": "refs/heads/master", "committer_date": "2021-10-18T08:51:32", "content_id": "47ce020cbcbabaeb823ffa821eea7fe8d1dd7a51", "detected_licenses": [ "Unlicense" ], "directory_id": "1833d9fc4c0590f638a6bb18fbc192b1b4e81646", "extension": "h", "filename": "error_macros.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 90477974, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2900, "license": "Unlicense", "license_type": "permissive", "path": "/src/TimeTracker/error_macros.h", "provenance": "stackv2-0037.json.gz:78915", "repo_name": "miere43/jatt", "revision_date": "2021-10-18T08:51:32", "revision_id": "49a2125c5dd1c3c31aa63cfc223e8ae8c58a3585", "snapshot_id": "86dd924f4e1318ea73dc1bbc42d0643726dcaa79", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/miere43/jatt/49a2125c5dd1c3c31aa63cfc223e8ae8c58a3585/src/TimeTracker/error_macros.h", "visit_date": "2021-10-27T23:59:29.457258" }
stackv2
#ifndef ERROR_MACROS_H #define ERROR_MACROS_H #include <QString> typedef void (*ErrorListener)(const char* function, const char* file, int line, const char* message, void* userdata); struct ErrorListenerListItem { ErrorListener func; void* userdata; ErrorListenerListItem(ErrorListener func, void* userdata, ErrorListenerListItem* next); ErrorListenerListItem* next; }; extern ErrorListenerListItem* errorListenerList; void addErrorListener(ErrorListener func, void* userdata); void shutdownErrorListeners(); void callErrorListeners(const char* function, const char* file, int line, const char* message); #if defined(QT_DEBUG) && defined(APP_BREAK_ON_ERROR) #ifdef Q_CC_MSVC #define APP_DEBUGBREAK() __debugbreak() #else #define APP_DEBUGBREAK() #endif #else #define APP_DEBUGBREAK() #endif /** Just like Q_ASSERT, but returns if 'cond' evaluates to false and reports error to registered error handlers. **/ #define ERR_VERIFY(cond) \ do { \ if (!(cond)) { \ callErrorListeners(__FUNCTION__, __FILE__, __LINE__, "Condition \"" #cond "\" is false."); \ APP_DEBUGBREAK(); \ return; \ } \ } while (0) /** Just like Q_ASSERT, but returns specified value if 'cond' evaluates to false and reports error to registered error handlers. **/ #define ERR_VERIFY_V(cond, returnValue) \ do { \ if (!(cond)) { \ callErrorListeners(__FUNCTION__, __FILE__, __LINE__, "Condition \"" #cond "\" is false, returning \"" #returnValue "\"."); \ APP_DEBUGBREAK(); \ return (returnValue); \ } \ } while (0) /** Just like Q_ASSERT, but returns if pointer is null and reports error to registered error handlers. **/ #define ERR_VERIFY_NULL(m_pointer) \ do { \ if (!(m_pointer)) { \ callErrorListeners(__FUNCTION__, __FILE__, __LINE__, "\"" #m_pointer "\" is null."); \ APP_DEBUGBREAK(); \ return; \ } \ } while (0) /** Just like Q_ASSERT, but returns specified value if pointer is null and reports error to registered error handlers. **/ #define ERR_VERIFY_NULL_V(m_pointer, m_returnValue) \ do { \ if (!(m_pointer)) { \ callErrorListeners(__FUNCTION__, __FILE__, __LINE__, "\"" #m_pointer "\" is null, returning \"" #m_returnValue "\""); \ APP_DEBUGBREAK(); \ return m_returnValue; \ } \ } while (0) /** Just like Q_ASSERT, but executes 'continue' statement if 'cond' evaluates to false and reports error to registered error handlers. **/ #define ERR_VERIFY_CONTINUE(cond) \ do { \ if (!(cond)) { \ callErrorListeners(__FUNCTION__, __FILE__, __LINE__, "Condition \"" #cond "\" is false."); \ APP_DEBUGBREAK(); \ continue; \ } \ } while (0) #endif // ERROR_MACROS_H
2.3125
2
2024-11-18T19:59:50.177561+00:00
2018-07-06T05:43:18
b93a3d2dc97debb622746ad6997f4ded9429aaec
{ "blob_id": "b93a3d2dc97debb622746ad6997f4ded9429aaec", "branch_name": "refs/heads/master", "committer_date": "2018-07-06T05:43:18", "content_id": "c19fd244a3cc0d70c938e8d6bb45ac22818881cc", "detected_licenses": [ "MIT" ], "directory_id": "4d8a0765c45e12cceb30a8bde26864196cbecfad", "extension": "h", "filename": "complex_macro_kernel.h", "fork_events_count": 0, "gha_created_at": "2018-07-16T16:29:27", "gha_event_created_at": "2018-07-16T16:29:27", "gha_language": null, "gha_license_id": "MIT", "github_id": 141164790, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5564, "license": "MIT", "license_type": "permissive", "path": "/ext/cumo/include/cumo/types/complex_macro_kernel.h", "provenance": "stackv2-0037.json.gz:79043", "repo_name": "Watson1978/cumo", "revision_date": "2018-07-06T05:43:18", "revision_id": "df1c27a088911477809cee7d7c887e4b20fd4ab8", "snapshot_id": "290e9fc4ae0015b4b697a9c9eba0495d71b136f7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Watson1978/cumo/df1c27a088911477809cee7d7c887e4b20fd4ab8/ext/cumo/include/cumo/types/complex_macro_kernel.h", "visit_date": "2020-03-23T05:45:54.382101" }
stackv2
#ifndef CUMO_COMPLEX_MACRO_KERNEL_H #define CUMO_COMPLEX_MACRO_KERNEL_H #include "float_def_kernel.h" extern double round(double); extern double log2(double); extern double exp2(double); extern double exp10(double); #define r_abs(x) fabs(x) #define r_sqrt(x) sqrt(x) #define r_exp(x) exp(x) #define r_log(x) log(x) #define r_sin(x) sin(x) #define r_cos(x) cos(x) #define r_sinh(x) sinh(x) #define r_cosh(x) cosh(x) #define r_tanh(x) tanh(x) #define r_atan2(y,x) atan2(y,x) #define r_hypot(x,y) hypot(x,y) #include "complex_kernel.h" __host__ __device__ static inline dtype c_from_scomplex(cumo_scomplex x) { dtype z; CUMO_REAL(z) = CUMO_REAL(x); CUMO_IMAG(z) = CUMO_IMAG(x); return z; } __host__ __device__ static inline dtype c_from_dcomplex(cumo_dcomplex x) { dtype z; CUMO_REAL(z) = CUMO_REAL(x); CUMO_IMAG(z) = CUMO_IMAG(x); return z; } /* --------------------------- */ #define m_zero c_zero() #define m_one c_one() //#define m_num_to_data(x) NUM2COMP(x) //#define m_data_to_num(x) COMP2NUM(x) #define m_from_double(x) c_new(x,0) #define m_from_real(x) c_new(x,0) #define m_from_sint(x) c_new(x,0) #define m_from_int32(x) c_new(x,0) #define m_from_int64(x) c_new(x,0) #define m_from_uint32(x) c_new(x,0) #define m_from_uint64(x) c_new(x,0) #define m_from_scomplex(x) c_from_scomplex(x) #define m_from_dcomplex(x) c_from_dcomplex(x) //#define m_extract(x) COMP2NUM(*(dtype*)x) #define m_real(x) CUMO_REAL(x) #define m_imag(x) CUMO_IMAG(x) #define m_set_real(x,y) c_set_real(x,y) #define m_set_imag(x,y) c_set_imag(x,y) #define m_add(x,y) c_add(x,y) #define m_sub(x,y) c_sub(x,y) #define m_mul(x,y) c_mul(x,y) #define m_div(x,y) c_div(x,y) #define m_mod(x,y) c_mod(x,y) #define m_pow(x,y) c_pow(x,y) #define m_pow_int(x,y) c_pow_int(x,y) #define m_abs(x) c_abs(x) #define m_minus(x) c_minus(x) #define m_reciprocal(x) c_reciprocal(x) #define m_square(x) c_square(x) #define m_floor(x) c_new(floor(CUMO_REAL(x)),floor(CUMO_IMAG(x))) #define m_round(x) c_new(round(CUMO_REAL(x)),round(CUMO_IMAG(x))) #define m_ceil(x) c_new(ceil(CUMO_REAL(x)),ceil(CUMO_IMAG(x))) #define m_trunc(x) c_new(trunc(CUMO_REAL(x)),trunc(CUMO_IMAG(x))) #define m_rint(x) c_new(rint(CUMO_REAL(x)),rint(CUMO_IMAG(x))) #define m_sign(x) c_new( \ ((CUMO_REAL(x)==0) ? 0.0:((CUMO_REAL(x)>0) ? 1.0:((CUMO_REAL(x)<0) ? -1.0:CUMO_REAL(x)))), \ ((CUMO_IMAG(x)==0) ? 0.0:((CUMO_IMAG(x)>0) ? 1.0:((CUMO_IMAG(x)<0) ? -1.0:CUMO_IMAG(x))))) #define m_copysign(x,y) c_new(copysign(CUMO_REAL(x),CUMO_REAL(y)),copysign(CUMO_IMAG(x),CUMO_IMAG(y))) #define m_im(x) c_im(x) #define m_conj(x) c_new(CUMO_REAL(x),-CUMO_IMAG(x)) #define m_arg(x) atan2(CUMO_IMAG(x),CUMO_REAL(x)) #define m_eq(x,y) c_eq(x,y) #define m_ne(x,y) c_ne(x,y) #define m_nearly_eq(x,y) c_nearly_eq(x,y) #define m_isnan(x) c_isnan(x) #define m_isinf(x) c_isinf(x) #define m_isposinf(x) c_isposinf(x) #define m_isneginf(x) c_isneginf(x) #define m_isfinite(x) c_isfinite(x) #define m_sprintf(s,x) sprintf(s,"%g%+gi",CUMO_REAL(x),CUMO_IMAG(x)) #define m_sqrt(x) c_sqrt(x) #define m_cbrt(x) c_cbrt(x) #define m_log(x) c_log(x) #define m_log2(x) c_log2(x) #define m_log10(x) c_log10(x) #define m_exp(x) c_exp(x) #define m_exp2(x) c_exp2(x) #define m_exp10(x) c_exp10(x) #define m_sin(x) c_sin(x) #define m_cos(x) c_cos(x) #define m_tan(x) c_tan(x) #define m_asin(x) c_asin(x) #define m_acos(x) c_acos(x) #define m_atan(x) c_atan(x) #define m_sinh(x) c_sinh(x) #define m_cosh(x) c_cosh(x) #define m_tanh(x) c_tanh(x) #define m_asinh(x) c_asinh(x) #define m_acosh(x) c_acosh(x) #define m_atanh(x) c_atanh(x) #define m_hypot(x,y) c_hypot(x,y) #define m_sinc(x) c_div(c_sin(x),x) #define m_sum_init 0 #define m_mulsum_init 0 #define not_nan(x) (CUMO_REAL(x)==CUMO_REAL(x) && CUMO_IMAG(x)==CUMO_IMAG(x)) #define m_mulsum(x,y,z) {z = m_add(m_mul(x,y),z);} #define m_mulsum_nan(x,y,z) { \ if(not_nan(x) && not_nan(y)) { \ z = m_add(m_mul(x,y),z); \ }} #define m_cumsum(x,y) {(x)=m_add(x,y);} #define m_cumsum_nan(x,y) { \ if (!not_nan(x)) { \ (x) = (y); \ } else if (not_nan(y)) { \ (x) = m_add(x,y); \ }} #define m_cumprod(x,y) {(x)=m_mul(x,y);} #define m_cumprod_nan(x,y) { \ if (!not_nan(x)) { \ (x) = (y); \ } else if (not_nan(y)) { \ (x) = m_mul(x,y); \ }} __host__ __device__ static inline dtype f_seq(dtype x, dtype y, double c) { return c_add(x,c_mul_r(y,c)); } /* --------- thrust ----------------- */ #include "cumo/cuda/cumo_thrust_complex.hpp" struct cumo_thrust_plus : public thrust::binary_function<dtype, dtype, dtype> { __host__ __device__ dtype operator()(dtype x, dtype y) { return m_add(x,y); } }; struct cumo_thrust_multiplies : public thrust::binary_function<dtype, dtype, dtype> { __host__ __device__ dtype operator()(dtype x, dtype y) { return m_mul(x,y); } }; struct cumo_thrust_multiplies_mulsum_nan : public thrust::binary_function<dtype, dtype, dtype> { __host__ __device__ dtype operator()(dtype x, dtype y) { if (not_nan(x) && not_nan(y)) { return m_mul(x, y); } else { return m_zero; } } }; struct cumo_thrust_square : public thrust::unary_function<dtype, dtype> { __host__ __device__ rtype operator()(const dtype& x) const { return c_abs_square(x); } }; #endif // CUMO_COMPLEX_MACRO_KERNEL_H
2.296875
2
2024-11-18T19:59:50.324394+00:00
2021-08-16T18:47:38
3cf8dfe4253f193a4be17fca974298951fdf214a
{ "blob_id": "3cf8dfe4253f193a4be17fca974298951fdf214a", "branch_name": "refs/heads/main", "committer_date": "2021-08-16T18:47:38", "content_id": "aca232e8d58aaa538069196affe4c9b40319183f", "detected_licenses": [ "MIT" ], "directory_id": "ee0551fd26acf498ba487ad3677d2f9f34ba85c1", "extension": "h", "filename": "mat_handler.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": 1233, "license": "MIT", "license_type": "permissive", "path": "/slmx4_projects/vcom_xep_matlab_server/source/mat_handler.h", "provenance": "stackv2-0037.json.gz:79299", "repo_name": "Heins2100/modules", "revision_date": "2021-08-16T18:47:38", "revision_id": "067e11a295273101d9a62891a69f957c0d06ca10", "snapshot_id": "223ee50eb5af85fbe64459bfcba82f6b47dd74ab", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Heins2100/modules/067e11a295273101d9a62891a69f957c0d06ca10/slmx4_projects/vcom_xep_matlab_server/source/mat_handler.h", "visit_date": "2023-08-29T06:57:40.212940" }
stackv2
/** @file mat_handler.h Definitions for the Matlab connector data handler @par Environment Environment Independent @par Compiler Compiler Independent @author Justin Hadella @copyright (c) 2021 Sensor Logic */ #ifndef MAT_HANDLER_h #define MAT_HANDLER_h #include <stdint.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif // ----------------------------------------------------------------------------- // Definitions // ----------------------------------------------------------------------------- #define MAT_HANDLER_VERSION "1.0.0" // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Public Functions // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** Function to initialize components needed in order to handle client requests when connected */ void handle_client_init(); /** Function to handle client requests In this version, the client task is a basic TCP server. The server acts like an infinite loop where it will check to see if there are any commands from the user to handle. It also will do things like stream the radar data. */ void handle_client_request(uint8_t *buf, int n); #ifdef __cplusplus } #endif #endif // MAT_HANDLER_h
2
2
2024-11-18T19:59:50.435120+00:00
2023-08-23T16:50:55
51812e5281b72bde34c7a9d5fc3fd70238fe0bdf
{ "blob_id": "51812e5281b72bde34c7a9d5fc3fd70238fe0bdf", "branch_name": "refs/heads/master", "committer_date": "2023-08-23T16:50:55", "content_id": "4e78f4f7ed29d5eb151b3962f570265dbba9e67e", "detected_licenses": [ "MIT" ], "directory_id": "fbdc48c28e54fb33ae4842ef95ff63893902c99a", "extension": "c", "filename": "nm_bus_wrapper.c", "fork_events_count": 1226, "gha_created_at": "2013-11-13T10:23:44", "gha_event_created_at": "2023-09-14T07:18:15", "gha_language": "C", "gha_license_id": "MIT", "github_id": 14360940, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2150, "license": "MIT", "license_type": "permissive", "path": "/src/drivers/winc1500/src/nm_bus_wrapper.c", "provenance": "stackv2-0037.json.gz:79427", "repo_name": "openmv/openmv", "revision_date": "2023-08-23T16:50:55", "revision_id": "8a90e070a88b7fc14c87a00351b9c4a213278419", "snapshot_id": "44d4b79fc8693950a2e330e5e0fd95b5c36e230f", "src_encoding": "UTF-8", "star_events_count": 2150, "url": "https://raw.githubusercontent.com/openmv/openmv/8a90e070a88b7fc14c87a00351b9c4a213278419/src/drivers/winc1500/src/nm_bus_wrapper.c", "visit_date": "2023-08-30T20:59:57.227603" }
stackv2
/* * This file is part of the OpenMV project. * * Copyright (c) 2013->2023 Ibrahim Abdelkader <iabdalkader@openmv.io> * Copyright (c) 2013->2023 Kwabena W. Agyeman <kwagyeman@openmv.io> * * This work is licensed under the MIT license, see the file LICENSE for details. * * WINC1500 bus wrapper. */ #include <stdint.h> #include <string.h> #include "py/mphal.h" #include "omv_boardconfig.h" #include "omv_gpio.h" #include "omv_spi.h" #include "conf_winc.h" #include "bsp/include/nm_bsp.h" #include "common/include/nm_common.h" #include "bus_wrapper/include/nm_bus_wrapper.h" #define NM_BUS_MAX_TRX_SZ (4096) #define NM_BUS_SPI_TIMEOUT (1000) static omv_spi_t spi_bus; tstrNmBusCapabilities egstrNmBusCapabilities = { NM_BUS_MAX_TRX_SZ }; sint8 nm_bus_init(void *pvinit) { sint8 result = M2M_SUCCESS; omv_spi_config_t spi_config; omv_spi_default_config(&spi_config, WINC_SPI_ID); spi_config.baudrate = WINC_SPI_BAUDRATE; spi_config.nss_enable = false; // Soft NSS if (omv_spi_init(&spi_bus, &spi_config) != 0) { result = M2M_ERR_BUS_FAIL; } nm_bsp_reset(); return result; } sint8 nm_bus_deinit(void) { omv_spi_deinit(&spi_bus); return M2M_SUCCESS; } static sint8 nm_bus_rw(uint8 *txbuf, uint8 *rxbuf, uint16 size) { sint8 result = M2M_SUCCESS; omv_spi_transfer_t spi_xfer = { .txbuf = txbuf, .rxbuf = rxbuf, .size = size, .timeout = NM_BUS_SPI_TIMEOUT, .flags = OMV_SPI_XFER_BLOCKING, .callback = NULL, .userdata = NULL, }; if (txbuf == NULL) { memset(rxbuf, 0, size); spi_xfer.txbuf = rxbuf; spi_xfer.rxbuf = rxbuf; } omv_gpio_write(spi_bus.cs, 0); omv_spi_transfer_start(&spi_bus, &spi_xfer); omv_gpio_write(spi_bus.cs, 1); return result; } sint8 nm_bus_ioctl(uint8 cmd, void *arg) { sint8 ret = 0; switch (cmd) { case NM_BUS_IOCTL_RW: { tstrNmSpiRw *spi_rw = (tstrNmSpiRw *) arg; ret = nm_bus_rw(spi_rw->pu8InBuf, spi_rw->pu8OutBuf, spi_rw->u16Sz); } break; default: ret = -1; M2M_ERR("Invalid IOCTL\n"); break; } return ret; }
2.109375
2
2024-11-18T19:59:50.492349+00:00
2018-07-11T10:37:47
b03212c35e0665a1511bdc8e0bc99e315565d91a
{ "blob_id": "b03212c35e0665a1511bdc8e0bc99e315565d91a", "branch_name": "refs/heads/master", "committer_date": "2018-07-11T10:37:47", "content_id": "474b99fa84e15d1dc4269bba00d51fe43f7ead0b", "detected_licenses": [ "Unlicense" ], "directory_id": "95cb8f7d9aec0e5ae14d1d6bb742f63b9e5ff414", "extension": "h", "filename": "FairLogo.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 140557822, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1941, "license": "Unlicense", "license_type": "permissive", "path": "/FairLogo.h", "provenance": "stackv2-0037.json.gz:79555", "repo_name": "dellaquilamaster/FAIRUNPACKER", "revision_date": "2018-07-11T10:37:47", "revision_id": "a2e183861d5117790c95a9897361a4d0cb86f214", "snapshot_id": "b8535354ea3ffe867469b37d166f9acf57c3e28f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dellaquilamaster/FAIRUNPACKER/a2e183861d5117790c95a9897361a4d0cb86f214/FairLogo.h", "visit_date": "2020-03-22T19:53:18.226710" }
stackv2
#ifndef FAIRLOGO_H #define FAIRLOGO_H #include <stdio.h> void FairLogo() { system("clear"); printf("\n"); printf("███████╗ █████╗ ██╗██████╗ ██╗ ██╗███╗ ██╗██████╗ █████╗ ██████╗██╗ ██╗███████╗██████╗ \n"); printf("██╔════╝██╔══██╗██║██╔══██╗██║ ██║████╗ ██║██╔══██╗██╔══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗ \n"); printf("█████╗ ███████║██║██████╔╝██║ ██║██╔██╗ ██║██████╔╝███████║██║ █████╔╝ █████╗ ██████╔╝ \n"); printf("██╔══╝ ██╔══██║██║██╔══██╗██║ ██║██║╚██╗██║██╔═══╝ ██╔══██║██║ ██╔═██╗ ██╔══╝ ██╔══██╗ \n"); printf("██║ ██║ ██║██║██║ ██║╚██████╔╝██║ ╚████║██║ ██║ ██║╚██████╗██║ ██╗███████╗██║ ██║ \n"); printf("╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ v1.0 \n\n"); printf("v1.0 01/02/2016\n"); printf("Created by: Daniele Dell'Aquila (dellaquila@na.infn.it)\n"); printf("Unpacker for the FAIR DAQ\n"); printf("Press any key to start the unpacker...\n"); getchar(); } #endif
2.1875
2
2024-11-18T20:10:16.664599+00:00
2018-04-04T15:13:34
0c98cf4d525bad905991d18238e60147081ee404
{ "blob_id": "0c98cf4d525bad905991d18238e60147081ee404", "branch_name": "refs/heads/master", "committer_date": "2018-04-04T15:21:01", "content_id": "dc1359bec0675905cd767098e10b866b138e4f4a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "4e832bf8d9a99c22e8ba85898e0349d5bd44fd17", "extension": "c", "filename": "spi.c", "fork_events_count": 0, "gha_created_at": "2018-03-25T20:09:21", "gha_event_created_at": "2019-06-19T18:11:59", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 126735696, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8458, "license": "Apache-2.0", "license_type": "permissive", "path": "/tests/drivers/spi/spi_loopback/src/spi.c", "provenance": "stackv2-0038.json.gz:234", "repo_name": "ulfalizer/zephyr", "revision_date": "2018-04-04T15:13:34", "revision_id": "7c0662fe6c9fa3cee2b6df7ea4c0ca1e2725a15c", "snapshot_id": "298f2cc671e6650a5fb82c88c7f9a229fb742033", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ulfalizer/zephyr/7c0662fe6c9fa3cee2b6df7ea4c0ca1e2725a15c/tests/drivers/spi/spi_loopback/src/spi.c", "visit_date": "2021-04-15T09:38:43.270450" }
stackv2
/* * Copyright (c) 2017 Intel Corporation. * * SPDX-License-Identifier: Apache-2.0 */ #define SYS_LOG_LEVEL SYS_LOG_LEVEL_DEBUG #include <logging/sys_log.h> #include <zephyr.h> #include <misc/printk.h> #include <string.h> #include <stdio.h> #include <spi.h> #define SPI_DRV_NAME CONFIG_SPI_LOOPBACK_DRV_NAME #define SPI_SLAVE CONFIG_SPI_LOOPBACK_SLAVE_NUMBER #define SLOW_FREQ CONFIG_SPI_LOOPBACK_SLOW_FREQ #define FAST_FREQ CONFIG_SPI_LOOPBACK_FAST_FREQ #if defined(CONFIG_SPI_LOOPBACK_CS_GPIO) #define CS_CTRL_GPIO_DRV_NAME CONFIG_SPI_LOOPBACK_CS_CTRL_GPIO_DRV_NAME struct spi_cs_control spi_cs = { .gpio_pin = CONFIG_SPI_LOOPBACK_CS_CTRL_GPIO_PIN, .delay = 0, }; #define SPI_CS (&spi_cs) #else #define SPI_CS NULL #define CS_CTRL_GPIO_DRV_NAME "" #endif #define BUF_SIZE 17 u8_t buffer_tx[] = "0123456789abcdef\0"; u8_t buffer_rx[BUF_SIZE] = {}; /* * We need 5x(buffer size) + 1 to print a comma-separated list of each * byte in hex, plus a null. */ u8_t buffer_print_tx[BUF_SIZE * 5 + 1]; u8_t buffer_print_rx[BUF_SIZE * 5 + 1]; static void to_display_format(const u8_t *src, size_t size, char *dst) { size_t i; for (i = 0; i < size; i++) { sprintf(dst + 5 * i, "0x%02x,", src[i]); } } struct spi_config spi_slow = { .frequency = SLOW_FREQ, .operation = SPI_OP_MODE_MASTER | SPI_MODE_CPOL | SPI_MODE_CPHA | SPI_WORD_SET(8) | SPI_LINES_SINGLE, .slave = SPI_SLAVE, .cs = SPI_CS, }; struct spi_config spi_fast = { .frequency = FAST_FREQ, .operation = SPI_OP_MODE_MASTER | SPI_MODE_CPOL | SPI_MODE_CPHA | SPI_WORD_SET(8) | SPI_LINES_SINGLE, .slave = SPI_SLAVE, .cs = SPI_CS, }; static int cs_ctrl_gpio_config(struct spi_cs_control *cs) { if (cs) { cs->gpio_dev = device_get_binding(CS_CTRL_GPIO_DRV_NAME); if (!cs->gpio_dev) { SYS_LOG_ERR("Cannot find %s!\n", CS_CTRL_GPIO_DRV_NAME); return -1; } } return 0; } static int spi_complete_loop(struct spi_config *spi_conf) { const struct spi_buf tx_bufs[] = { { .buf = buffer_tx, .len = BUF_SIZE, }, }; struct spi_buf rx_bufs[] = { { .buf = buffer_rx, .len = BUF_SIZE, }, }; int ret; SYS_LOG_INF("Start"); ret = spi_transceive(spi_conf, tx_bufs, ARRAY_SIZE(tx_bufs), rx_bufs, ARRAY_SIZE(rx_bufs)); if (ret) { SYS_LOG_ERR("Code %d", ret); return ret; } if (memcmp(buffer_tx, buffer_rx, BUF_SIZE)) { to_display_format(buffer_tx, BUF_SIZE, buffer_print_tx); to_display_format(buffer_rx, BUF_SIZE, buffer_print_rx); SYS_LOG_ERR("Buffer contents are different: %s", buffer_print_tx); SYS_LOG_ERR(" vs: %s", buffer_print_rx); return -1; } SYS_LOG_INF("Passed"); return 0; } static int spi_rx_half_start(struct spi_config *spi_conf) { const struct spi_buf tx_bufs[] = { { .buf = buffer_tx, .len = BUF_SIZE, }, }; struct spi_buf rx_bufs[] = { { .buf = buffer_rx, .len = 8, }, }; int ret; SYS_LOG_INF("Start"); memset(buffer_rx, 0, BUF_SIZE); ret = spi_transceive(spi_conf, tx_bufs, ARRAY_SIZE(tx_bufs), rx_bufs, ARRAY_SIZE(rx_bufs)); if (ret) { SYS_LOG_ERR("Code %d", ret); return -1; } if (memcmp(buffer_tx, buffer_rx, 8)) { to_display_format(buffer_tx, 8, buffer_print_tx); to_display_format(buffer_rx, 8, buffer_print_rx); SYS_LOG_ERR("Buffer contents are different: %s", buffer_print_tx); SYS_LOG_ERR(" vs: %s", buffer_print_rx); return -1; } SYS_LOG_INF("Passed"); return 0; } static int spi_rx_half_end(struct spi_config *spi_conf) { const struct spi_buf tx_bufs[] = { { .buf = buffer_tx, .len = BUF_SIZE, }, }; struct spi_buf rx_bufs[] = { { .buf = NULL, .len = 8, }, { .buf = buffer_rx, .len = 8, }, }; int ret; SYS_LOG_INF("Start"); memset(buffer_rx, 0, BUF_SIZE); ret = spi_transceive(spi_conf, tx_bufs, ARRAY_SIZE(tx_bufs), rx_bufs, ARRAY_SIZE(rx_bufs)); if (ret) { SYS_LOG_ERR("Code %d", ret); return -1; } if (memcmp(buffer_tx+8, buffer_rx, 8)) { to_display_format(buffer_tx + 8, 8, buffer_print_tx); to_display_format(buffer_rx, 8, buffer_print_rx); SYS_LOG_ERR("Buffer contents are different: %s", buffer_print_tx); SYS_LOG_ERR(" vs: %s", buffer_print_rx); return -1; } SYS_LOG_INF("Passed"); return 0; } static int spi_rx_every_4(struct spi_config *spi_conf) { const struct spi_buf tx_bufs[] = { { .buf = buffer_tx, .len = BUF_SIZE, }, }; struct spi_buf rx_bufs[] = { { .buf = NULL, .len = 4, }, { .buf = buffer_rx, .len = 4, }, { .buf = NULL, .len = 4, }, { .buf = buffer_rx + 4, .len = 4, }, }; int ret; SYS_LOG_INF("Start"); memset(buffer_rx, 0, BUF_SIZE); ret = spi_transceive(spi_conf, tx_bufs, ARRAY_SIZE(tx_bufs), rx_bufs, ARRAY_SIZE(rx_bufs)); if (ret) { SYS_LOG_ERR("Code %d", ret); return -1; } if (memcmp(buffer_tx + 4, buffer_rx, 4)) { to_display_format(buffer_tx + 4, 4, buffer_print_tx); to_display_format(buffer_rx, 4, buffer_print_rx); SYS_LOG_ERR("Buffer contents are different: %s", buffer_print_tx); SYS_LOG_ERR(" vs: %s", buffer_print_rx); return -1; } else if (memcmp(buffer_tx + 12, buffer_rx + 4, 4)) { to_display_format(buffer_tx + 12, 4, buffer_print_tx); to_display_format(buffer_rx + 4, 4, buffer_print_rx); SYS_LOG_ERR("Buffer contents are different: %s", buffer_print_tx); SYS_LOG_ERR(" vs: %s", buffer_print_rx); return -1; } SYS_LOG_INF("Passed"); return 0; } static struct k_poll_signal async_sig = K_POLL_SIGNAL_INITIALIZER(async_sig); static struct k_poll_event async_evt = K_POLL_EVENT_INITIALIZER(K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &async_sig); static K_SEM_DEFINE(caller, 0, 1); K_THREAD_STACK_DEFINE(spi_async_stack, 256); static int result = 1; static void spi_async_call_cb(struct k_poll_event *async_evt, struct k_sem *caller_sem, void *unused) { SYS_LOG_DBG("Polling..."); while (1) { k_poll(async_evt, 1, K_MSEC(100)); result = async_evt->signal->result; k_sem_give(caller_sem); /* Reinitializing for next call */ async_evt->signal->signaled = 0; async_evt->state = K_POLL_STATE_NOT_READY; } } static int spi_async_call(struct spi_config *spi_conf) { const struct spi_buf tx_bufs[] = { { .buf = buffer_tx, .len = BUF_SIZE, }, }; struct spi_buf rx_bufs[] = { { .buf = buffer_rx, .len = BUF_SIZE, }, }; int ret; SYS_LOG_INF("Start"); ret = spi_transceive_async(spi_conf, tx_bufs, ARRAY_SIZE(tx_bufs), rx_bufs, ARRAY_SIZE(rx_bufs), &async_sig); if (ret == -ENOTSUP) { SYS_LOG_DBG("Not supported"); return 0; } if (ret) { SYS_LOG_ERR("Code %d", ret); return -1; } k_sem_take(&caller, K_FOREVER); if (result) { SYS_LOG_ERR("Call code %d", ret); return -1; } SYS_LOG_INF("Passed"); return 0; } static int spi_resource_lock_test(struct spi_config *spi_conf_lock, struct spi_config *spi_conf_try) { spi_conf_lock->operation |= SPI_LOCK_ON; if (spi_complete_loop(spi_conf_lock)) { return -1; } if (spi_release(spi_conf_lock)) { SYS_LOG_ERR("Deadlock now?"); return -1; } if (spi_complete_loop(spi_conf_try)) { return -1; } return 0; } void main(void) { struct k_thread async_thread; k_tid_t async_thread_id; SYS_LOG_INF("SPI test on buffers TX/RX %p/%p", buffer_tx, buffer_rx); if (cs_ctrl_gpio_config(spi_slow.cs) || cs_ctrl_gpio_config(spi_fast.cs)) { return; } spi_slow.dev = device_get_binding(SPI_DRV_NAME); if (!spi_slow.dev) { SYS_LOG_ERR("Cannot find %s!\n", SPI_DRV_NAME); return; } spi_fast.dev = spi_slow.dev; async_thread_id = k_thread_create(&async_thread, spi_async_stack, 256, (k_thread_entry_t)spi_async_call_cb, &async_evt, &caller, NULL, K_PRIO_COOP(7), 0, 0); if (spi_complete_loop(&spi_slow) || spi_rx_half_start(&spi_slow) || spi_rx_half_end(&spi_slow) || spi_rx_every_4(&spi_slow) || spi_async_call(&spi_slow)) { goto end; } if (spi_complete_loop(&spi_fast) || spi_rx_half_start(&spi_fast) || spi_rx_half_end(&spi_fast) || spi_rx_every_4(&spi_fast) || spi_async_call(&spi_fast)) { goto end; } if (spi_resource_lock_test(&spi_slow, &spi_fast)) { goto end; } SYS_LOG_INF("All tx/rx passed"); end: k_thread_abort(async_thread_id); }
2.59375
3
2024-11-18T20:10:16.758513+00:00
2018-05-14T12:36:40
427ccfe1a033640cc552043ba1c46a18cca4a014
{ "blob_id": "427ccfe1a033640cc552043ba1c46a18cca4a014", "branch_name": "refs/heads/master", "committer_date": "2018-05-14T12:36:40", "content_id": "4a6aeff3ec3ce8747f2feda29fd2d11512aa5a1c", "detected_licenses": [ "MIT" ], "directory_id": "54d4a3db7cf7997cd9c1a0b9d19e0414144be42e", "extension": "h", "filename": "gameframe.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 130363814, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 774, "license": "MIT", "license_type": "permissive", "path": "/gameframe.h", "provenance": "stackv2-0038.json.gz:362", "repo_name": "sinking-point/fortuna-gameframe", "revision_date": "2018-05-14T12:36:40", "revision_id": "e6659de29fcca1484e6c1fb41603e694e3f6c110", "snapshot_id": "d02ce7e55c4735f59ef642daa94f40c372fa56c6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sinking-point/fortuna-gameframe/e6659de29fcca1484e6c1fb41603e694e3f6c110/gameframe.h", "visit_date": "2020-03-12T00:59:29.552968" }
stackv2
#ifndef GAMEFRAME_H #define GAMEFRAME_H #include <stdlib.h> #include "os.h" typedef uint16_t colour; // constants // structs typedef struct game_entity { int x, y, width, height, changed; // colour that should be interpreted as transparent colour transparency_code; /* returns the pixel colour of the sprite of this entity at coords given, origin being top left corner of the sprite */ colour (*pixel_colour)(int x, int y); // defines the behaviour of this entity each cycle of the game loop void (*update)(void); } game_entity; typedef struct game_scene { int num_entities; game_entity *entities; } game_scene; // functions //changes the current scene void set_scene(game_scene*); // runs a frame of gameplay int run_frame(int); #endif
2.03125
2
2024-11-18T20:10:16.950719+00:00
2016-04-13T16:10:19
6c35d03880fc06cec7186fbea956fd332bebc849
{ "blob_id": "6c35d03880fc06cec7186fbea956fd332bebc849", "branch_name": "refs/heads/master", "committer_date": "2016-04-13T16:10:19", "content_id": "5666b8af72100a04f98e272b491b430116e30948", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b523a1ddc114324eb7819bb3a162f33a2816eb83", "extension": "c", "filename": "gen_cases.c", "fork_events_count": 1, "gha_created_at": "2016-04-13T15:27:35", "gha_event_created_at": "2016-04-13T15:27:36", "gha_language": null, "gha_license_id": null, "github_id": 56163793, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3842, "license": "Apache-2.0", "license_type": "permissive", "path": "/tests/float/gen_cases.c", "provenance": "stackv2-0038.json.gz:618", "repo_name": "nickodell/NyuziProcessor", "revision_date": "2016-04-13T16:10:19", "revision_id": "67fa32974d2fd95c0072e22dc9d15ee8032f6cfd", "snapshot_id": "7ea7b08651e6d14371b2e014b5b7847f212300c0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nickodell/NyuziProcessor/67fa32974d2fd95c0072e22dc9d15ee8032f6cfd/tests/float/gen_cases.c", "visit_date": "2021-01-18T09:07:19.432929" }
stackv2
// // Copyright 2016 Jeff Bush // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <stdio.h> #include <stdlib.h> #define NUM_ELEMS(x) (sizeof(x) / sizeof(x[0])) #define RAND_ELEM(x) x[rand() % NUM_ELEMS(x)] unsigned int addFunc(unsigned int param1, unsigned int param2); unsigned int subFunc(unsigned int param1, unsigned int param2); unsigned int mulFunc(unsigned int param1, unsigned int param2); unsigned int ftoiFunc(unsigned int param1, unsigned int param2); unsigned int itofFunc(unsigned int param1, unsigned int param2); unsigned int fgtrFunc(unsigned int param1, unsigned int param2); // // Floating point values are constrained so common edge cases are // more common (for example, equal exponents) // unsigned int EXPONENTS[] = { 0, 1, 100, // -27 125, // -2 126, // -1 127, // 0 128, // 1 129, // 2 154, // 27 254, 255, // Special }; unsigned int SIGNIFICANDS[] = { 0x000000, 0x000001, 0x000002, 0x000010, 0x000100, 0x001000, 0x010000, 0x7ffffd, 0x7ffffe, 0x7fffff }; struct Operation { const char *name; unsigned int (*func)(unsigned int op1, unsigned int op2); int numOperands; } OPS[] = { { "FADD", addFunc, 2 }, { "FSUB", subFunc, 2 }, { "FMUL", mulFunc, 2 }, { "FGTR", fgtrFunc, 2 }, { "ITOF", itofFunc, 1 }, { "FTOI", ftoiFunc, 1 } }; float valueAsFloat(unsigned int value) { union { float f; unsigned int i; } u = { .i = value }; return u.f; } unsigned int valueAsInt(float value) { union { float f; unsigned int i; } u = { .f = value }; return u.i; } unsigned int addFunc(unsigned int param1, unsigned int param2) { return valueAsInt(valueAsFloat(param1) + valueAsFloat(param2)); } unsigned int subFunc(unsigned int param1, unsigned int param2) { return valueAsInt(valueAsFloat(param1) - valueAsFloat(param2)); } unsigned int mulFunc(unsigned int param1, unsigned int param2) { return valueAsInt(valueAsFloat(param1) * valueAsFloat(param2)); } unsigned int ftoiFunc(unsigned int param1, unsigned int param2) { return (unsigned int)(int) valueAsFloat(param1); } unsigned int itofFunc(unsigned int param1, unsigned int param2) { return valueAsInt((float)(int)param1); } unsigned int fgtrFunc(unsigned int param1, unsigned int param2) { return valueAsFloat(param1) > valueAsFloat(param2); } unsigned int generateRandomValue(void) { return (RAND_ELEM(EXPONENTS) << 23) | RAND_ELEM(SIGNIFICANDS) | ((rand() & 1) << 31); } int main() { for (int opidx = 0; opidx < NUM_ELEMS(OPS); opidx++) { struct Operation *op = &OPS[opidx]; for (int i = 0; i < 256; i++) { unsigned int value1 = generateRandomValue(); unsigned int value2 = op->numOperands == 1 ? 0 : generateRandomValue(); unsigned int result = op->func(value1, value2); if (op->func != ftoiFunc) { // Make NaN consistent if (((result >> 23) & 0xff) == 0xff && (result & 0x7fffff) != 0) result = 0x7fffffff; } printf("{ %s, 0x%08x, 0x%08x, 0x%08x },\n", op->name, value1, value2, result); } } }
3.109375
3
2024-11-18T20:11:37.603219+00:00
2018-11-21T12:34:07
11d50d6e962451b83098c1154e067eecb469423c
{ "blob_id": "11d50d6e962451b83098c1154e067eecb469423c", "branch_name": "refs/heads/master", "committer_date": "2018-11-21T12:34:07", "content_id": "393e40cb80f18e82ede0c01ca748a5e0b3184376", "detected_licenses": [ "MIT" ], "directory_id": "74bb4823475985b3b0526bc45e85b66cb59d8656", "extension": "c", "filename": "openmp_demo2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 151335410, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 721, "license": "MIT", "license_type": "permissive", "path": "/2018-Q3/PAP-A/OpenMP/openmp_demo2.c", "provenance": "stackv2-0038.json.gz:24633", "repo_name": "rafael-telles/ufabc-classes", "revision_date": "2018-11-21T12:34:07", "revision_id": "bc09ce984496b4d3c164d007d7c482f692becd33", "snapshot_id": "89a2c8de05b0e8f3fc69f2bb605ca3ad0489fe17", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rafael-telles/ufabc-classes/bc09ce984496b4d3c164d007d7c482f692becd33/2018-Q3/PAP-A/OpenMP/openmp_demo2.c", "visit_date": "2020-03-30T14:46:27.036349" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> int main(int argc, char const *argv[]) { int n = 1000; int *a = NULL; a = (int*) malloc(n * sizeof(int)); int i; for (i=n; i--;) { a[i] = i; } long long sum = 0; long long sum2 = 0; #pragma omp parallel { #pragma omp for reduction(+:sum) reduction(+:sum2) for (i = 0; i < n; i++) { sum += a[i]; sum2 += a[i] * a[i]; } } double mean = sum / (double) n; double var = (sum2 - 2 * mean * sum + n * (mean*mean)) / n; double stdev = sqrt(var); printf("sum: %.2lld\n", sum); printf("sum2: %.2lld\n", sum2); printf("mean: %.2lf\n", mean); printf("var: %.2lf\n", var); printf("stdev: %.2lf\n", stdev); return 0; }
3.109375
3
2024-11-18T20:11:38.627094+00:00
2015-08-01T16:29:13
ff1f0f626dd08dcc0cd76222649e01f82662ab6b
{ "blob_id": "ff1f0f626dd08dcc0cd76222649e01f82662ab6b", "branch_name": "refs/heads/master", "committer_date": "2015-08-01T16:29:13", "content_id": "e89d65a198aa82f05c02a37e76f6e46081e78d5c", "detected_licenses": [ "MIT" ], "directory_id": "9df87cf106bcc88028a007c979c19a8e54f9a14d", "extension": "c", "filename": "farm_gate.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 40052469, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4639, "license": "MIT", "license_type": "permissive", "path": "/Areas/NewbieIsle/HobbitFarm/o/Room/farm_gate.c", "provenance": "stackv2-0038.json.gz:25018", "repo_name": "yodakingdoms/kingdoms", "revision_date": "2015-08-01T16:29:13", "revision_id": "831b74ba4a086de69cce213ad2398f646c3efb39", "snapshot_id": "b00751ec6a838c23d916a311ba101cf8d3e4b19d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yodakingdoms/kingdoms/831b74ba4a086de69cce213ad2398f646c3efb39/Areas/NewbieIsle/HobbitFarm/o/Room/farm_gate.c", "visit_date": "2020-05-20T16:04:32.008700" }
stackv2
#pragma strict_types #include "../def.h" inherit MASTER_ROOM; inherit DOOR_MOD; void create_object(void); void reset(int arg); void create_object(void) { set_short("A gate to a farm (n/w/s)"); set_long("Inside the gate of a small farm in the middle of the rolling " + "landscape of Newbie Island. To the east is a wooden arch over " + "the gate and a finely crafted fence. North of here is a small " + "field and south of there there seems to be a well. To the " + "west are the buildings that make up the farm. You can see a " + "barn, a stable, a big hill that seems to be a normal hobbit " + "house and a smaller shed. A huge oak tree grows on top " + "of the hill. The grass all around you is trampled and flat " + "and you see tracks from many different kinds of creatures.\n"); set_new_light(5); add_item("farm|small farm","It lies tucked away in a small, flatter " + "area in the rolling landscape around you"); add_item("area|flatter area|small area|small, flatter area","The area " + "that makes up the farm is flatter than the landscape around " + "it. It was probably the reason why this area was chosen to " + "build the farm on"); add_item("landscape|rolling landscape","Grassy, green hills as far as " + "the eye can see"); add_item("hill|hills|green hill|green hills|grassy hill|grassy hills|" + "green, grassy hill|green, grassy hills","Grassy hills, most " + "of them crowned with trees"); add_item("trees","They grow on most of the hills but you can't tell " + "more about them from this distance"); add_item("island|newbie island|Island|Newbie Island","It's the island " + "this area is on"); add_item("arch|wooden arch","The arch rises over the gate. There's a " + "wooden sign nailed to it"); add_item("@sign|@wooden sign|sign|wooden sign","You can't see what is " + "says from here, you would have to go outside the gate to " + "read it"); add_item("fence|crafted fence|finely crafted fence","The fence " + "stretches a long distance both to the south and to the north"); add_item("field|small field","A small field where something is growing"); add_item("something","You can't tell what's growing there from here"); add_item("well","There's a well a short distance to the south. You'd " + "have to go there to get a better look"); add_item("building|buildings","The buildings look like your normal farm " + "buildings, but there's something about their scale that's not " + "quite right"); add_item("scale","The buildings all seem a little smaller than they " + "should be"); add_item("barn","The barn is some distance to the west of here"); add_item("stable","The stable is northwest from here"); add_item("hill|big hill|grassy hill|big, grassy hill|house|hobbit house|" + "normal hobbit house","A big, grassy hill with a round door " + "and some windows"); add_item("door|round door","You'd have to go east to get a better " + "look at it"); add_item("window|windows","There are windows facing all directions in " + "the hill"); add_item("shed|smaller shed","It's squeezed in between the barn and " + "the stable"); add_item("top|top of the hill","A huge tree grows on top of the hill, " + "looming over the farm"); add_item("oak|tree|oak tree|huge oak|huge tree|huge oak tree","It " + "grows on top of the hill and looks very impressive"); add_item("ground","The ground is covered with short grass"); add_item("grass|short grass","It's pretty short to begin with and it's " + "also trampled flat all around you"); add_item("track|tracks","Many different kinds of creatures seem to " + "have been walking around here"); add_item("$|$sound|$sounds|$animal|$animals","You hear the sounds of " + "farm animals coming from all around you"); add_item("%|%smell|%animal|%animals","You feel the smell of farm " + "animals. It is rather faint here though"); add_exit(ROOM + "farm_pumpkin_field","north"); add_exit(ROOM + "farm_well","south"); add_exit(ROOM + "farm_center","west"); set_door_control("door_control"); reset(0); } void reset(int arg) { add_monster(MONSTER + "bird",3); ::reset(arg); }
2.546875
3
2024-11-18T20:11:38.726526+00:00
2014-12-03T01:19:47
ff947d50dfa908e45a3dd76e7481aaa88118f6bb
{ "blob_id": "ff947d50dfa908e45a3dd76e7481aaa88118f6bb", "branch_name": "refs/heads/master", "committer_date": "2014-12-03T01:19:47", "content_id": "392190c8a5f3103593120dc61a5164cf5580c91d", "detected_licenses": [ "MIT" ], "directory_id": "25cc0372c0612609b1efc346a2e8c5e5699946cd", "extension": "c", "filename": "File Management.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": 7473, "license": "MIT", "license_type": "permissive", "path": "/Calendar/Calendar/File Management.c", "provenance": "stackv2-0038.json.gz:25146", "repo_name": "bschron/Calendar", "revision_date": "2014-12-03T01:19:47", "revision_id": "95d15526a2d5541f8fd0531e52d95964d475250b", "snapshot_id": "dca41f01c1b79272bcf583a8c937cca7763a7b9e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bschron/Calendar/95d15526a2d5541f8fd0531e52d95964d475250b/Calendar/Calendar/File Management.c", "visit_date": "2020-06-06T11:39:09.813983" }
stackv2
// // File Management.c // Calendar // // Created by Bruno Chroniaris on 11/9/14. // Copyright (c) 2014 Universidade Federal De Alagoas. All rights reserved. // #include "File Management.h" void exportEvents (Calendar *calendar) { if (calendar == NULL) { return; } else if (emptyCalendar(calendar)) { return; } char output[Max]; char output2[Max]; char *home = getenv("HOME");//path to home folder sprintf(output, "%s%s", home, MainDir); int exists = access(output, R_OK); Node *list = NULL; //creates if it does not exist if (exists != 0) { mkdir(output, chmod(output, 2)); } sprintf(output2, "%s/%s%s", output, MainCalendar, CalendarFileExtension); FILE *export = fopen(output2, "w"); Node *pop; //inserts every formated data on the lists Node->name list = listEventsExportingStr(list, peekCalendarFirstEvent(calendar)); //prints every event on the list for (pop = popNode(&list); !emptyNode(pop); pop=popNode(&list)) { fprintf(export, "%s\n", peekNodeName(pop)); } if (list != NULL) { free(list); } fclose(export); } Node* listEventsExportingStr (Node *list, Event *events) { if (events == NULL) { return list; } /* else if (list == NULL) { Node *new = (Node*) malloc(sizeof(Node)); return listEventsExportingStr(new, events); } */ char output[Max*5]; //treat recurrent event differently than regular events if (peekEventRecurrency(events) == 0) { snprintf(output, sizeof(output)/sizeof(char), "*%s-%s-%d/%d/%d", peekEventTitle(events), peekEventDesc(events), peekEventDateDay(events), peekEventDateMonth(events), peekEventDateYear(events)); } else { printRecurrentEventFileExportingToStr(output, sizeof(output)/sizeof(char), events); } list = insertNode(list, output, not_in_use); return listEventsExportingStr(list, peekNextEvent(events)); } Calendar* importCalendarFromFile (Calendar* calendar, FILE *file) { if (file == NULL) { return calendar; } else if (calendar == NULL) { return importCalendarFromFile(createEmptyCalendar(), file); } //gets first character from line char character = fgetc(file); //checks if the end of file was reached if (character == EOF) { return calendar; } else if (character == '*')//start reading event { Event *new = createEmptyEvent(); new = getEventMainInformationsFromStream(file, new); calendar = insertEvent(calendar, new); return importCalendarFromFile(calendar, file); } else if (character == '+') { Event *provisory = createEmptyEvent(); Event *new = NULL; int *provFrequency = (int*) malloc(sizeof(int)); provisory = getEventMainInformationsFromStream(file, provisory); provisory = getRecurrentAdditionalInformationsFromStream(file, provisory); //using createEvent function so recurrences will be created. new = createEvent(peekEventDateDay(provisory), peekEventDateMonth(provisory), peekEventDateYear(provisory), peekEventDesc(provisory), peekEventTitle(provisory), peekEventRecurrency(provisory), peekEventFrequency(provisory)); calendar = insertEvent(calendar, new); //created a new provisory frequency, just to evoid SIGNALRBIT while running setEventFrequency(provisory, provFrequency); freeEvent(&provisory); return importCalendarFromFile(calendar, file); } else//does not match any case, maybe file is corrupted { return calendar; } } Calendar* importCalendarFromMainDirectory (Calendar *calendar) { if (calendar == NULL) { return importCalendarFromMainDirectory(createEmptyCalendar()); } char output[Max]; char *home = getenv("HOME");//path to home folder sprintf(output, "%s%s/%s%s", home, MainDir, MainCalendar, CalendarFileExtension); FILE *file = fopen(output, "r"); //if file does not exist if (file == NULL) { return calendar; } calendar = importCalendarFromFile(calendar, file); return calendar; } void printRecurrentEventFileExportingToStr (char *dest, int destLength, Event *event) { char frequencyStr[Max]; if (peekEventRecurrency(event) != 3) { int frequecyLength = 0; int i; if (peekEventRecurrency(event) == 1) { frequecyLength = 7; } else if (peekEventRecurrency(event) == 2) { frequecyLength = 31; } int *frequency = peekEventFrequency(event); for (i=0; i<frequecyLength; i++) { frequencyStr[i] = frequency[i]+'0'; } } if (peekEventRecurrency(event) == 1 || peekEventRecurrency(event) == 2) { snprintf(dest, destLength, "+%s-%s-%d/%d/%d-%d-%s", peekEventTitle(event), peekEventDesc(event), peekEventDateDay(event), peekEventDateMonth(event), peekEventDateYear(event), peekEventRecurrency(event), frequencyStr); } else if (peekEventRecurrency(event) == 3) { int *frequency = peekEventFrequency(event); snprintf(dest, destLength, "+%s-%s-%d/%d/%d-%d-%d/%d", peekEventTitle(event), peekEventDesc(event), peekEventDateDay(event), peekEventDateMonth(event), peekEventDateYear(event), peekEventRecurrency(event), frequency[0], frequency[1]); } return; } Event* getEventMainInformationsFromStream (FILE *stream, Event *event) { if (stream == NULL) { return event; } else if (event == NULL) { return getEventMainInformationsFromStream(stream, createEmptyEvent()); } int day, month, year; unwantedgets(peekEventTitle(event), Max, '-', stream); unwantedgets(peekEventDesc(event), description, '-', stream); fscanf(stream, "%d", &day); fgetc(stream); fscanf(stream, "%d", &month); fgetc(stream); fscanf(stream, "%d", &year); fgetc(stream); setEventDateDay(event, day); setEventDateMonth(event, month); setEventDateYear(event, year); return event; } Event *getRecurrentAdditionalInformationsFromStream (FILE *stream, Event *event) { if (stream == NULL || event == NULL) { return event; } int frequencyLength = 0; int i; int *frequency = NULL; setEventRecurrency(event, fgetNumber(stream)); if (peekEventRecurrency(event) == 1) { frequencyLength = 7; } else if (peekEventRecurrency(event) == 2) { frequencyLength = 31; } if (peekEventRecurrency(event) == 1 || peekEventRecurrency(event) == 2) { frequency = (int*) malloc(sizeof(int)*frequencyLength); setEventFrequency(event, frequency); for (i = 0; i < frequencyLength; i++) { frequency[i] = fgetc(stream) - '0'; } fgetc(stream);//gets line break } else if (peekEventRecurrency(event) == 3) { frequency = (int*) malloc(sizeof(int)*2); setEventFrequency(event, frequency); frequency[0] = fgetNumber(stream); frequency[1] = fgetNumber(stream);//gets like break } return event; }
2.484375
2
2024-11-18T20:35:12.862770+00:00
2021-04-19T23:14:46
f05d48eb9f962b3b5d7473185b98795686e0c775
{ "blob_id": "f05d48eb9f962b3b5d7473185b98795686e0c775", "branch_name": "refs/heads/master", "committer_date": "2021-04-19T23:14:46", "content_id": "d143ef9b45240c92e116cc8fce992c25bc40eaac", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cfe200ff7aee266ddd7b6fa743c2203c843ddd62", "extension": "h", "filename": "ant_colony.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 278813357, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2214, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/ant_colony.h", "provenance": "stackv2-0039.json.gz:38", "repo_name": "D0656146/heuristic", "revision_date": "2021-04-19T23:14:46", "revision_id": "caea805a361dc79d3ec02186786e3fcac8797e2c", "snapshot_id": "3997d897e7ffa9361b04f299facd834a932dc841", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/D0656146/heuristic/caea805a361dc79d3ec02186786e3fcac8797e2c/src/ant_colony.h", "visit_date": "2023-04-02T03:22:48.718300" }
stackv2
/** * Ant Colony Optimization framework * using best ant system */ #ifndef ANT_COLONY_H_ #define ANT_COLONY_H_ #ifndef __cplusplus #include <stdbool.h> #endif #include <stdio.h> #include "heuristic_utils.h" #include "problem_solution.h" // class of ant typedef struct { int* route_ar; int route_steps; Solution* solution; } Ant; // constructor // route_steps = solution_length + 1 for tsp Ant* NewEmptyAnt_MA(const int size); // destructor void FreeAnt(Ant* ant); // clone function void CloneAnt_RP(const Ant* origin, Ant* copy); // abstract class of problem to be solve with ACO typedef struct { // method to count number of states from dataset int (*CountNumStates)(const void* dataset); // method to count priori value of a edge double (*CountPriori)(const void* dataset, const int current_state, const int next_state); // method to determine if a state is still avalible for an ant to go bool (*IsStateAvalible)(const void* dataset, const Ant* ant, const int state); // method to translate a route to a solution // evaluate here void (*AntToSolution_DA)(const void* dataset, Ant* ant); } AntColonyProblem; // ant colony optimization framework Solution* AntColony_MA( // instance of the problem const AntColonyProblem* problem, // problem dataset const void* dataset, // solution size const int solution_size, // size of ant colony const int num_ants, // influence coefficient of pheromone const double pheromone_influence, // influence coefficient of priori const double priori_influence, // pheromone amount per single ant to update per iteration const double pheromone_amount, // global best pheromone amount to update per iteration const double global_pheromone_amount, // local best pheromone amount to update per iteration const double local_pheromone_amount, // evaporation rate of pheromone per iteration const double evaporation_rate, // constraint of max evaluations const int max_evaluations, // file pointer of logging // must had already opened a file for writing // pass NULL to skip logging FILE* loggings); #endif // ANT_COLONY_H_
2.4375
2
2024-11-18T20:35:13.109706+00:00
2021-05-24T12:04:17
3255c7d168ebb38d3fd065a07a7e2e798785a984
{ "blob_id": "3255c7d168ebb38d3fd065a07a7e2e798785a984", "branch_name": "refs/heads/master", "committer_date": "2021-05-24T12:04:17", "content_id": "67d0723a110bd5fc4b0da2c959d5c64ec8b96124", "detected_licenses": [ "ISC" ], "directory_id": "7aa70c787e82e5f4f0d8bd2dbc51cef9bfbfa313", "extension": "c", "filename": "socket.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 255168563, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1983, "license": "ISC", "license_type": "permissive", "path": "/compat/socket.c", "provenance": "stackv2-0039.json.gz:166", "repo_name": "job/rpki-client-portable", "revision_date": "2021-05-24T12:04:17", "revision_id": "e28a27b256d9ae7d24b182d640a1bc5a698746f0", "snapshot_id": "3405c04708009853d352e83be29717dfa1811730", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/job/rpki-client-portable/e28a27b256d9ae7d24b182d640a1bc5a698746f0/compat/socket.c", "visit_date": "2023-04-26T02:54:35.252916" }
stackv2
/* * Copyright (c) 2020 Claudio Jeker <claudio@openbsd.org> * * 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. */ #define IN_SOCKET_COMPAT #include <sys/socket.h> #ifdef NEED_SOCKET_FLAGS #include <errno.h> #include <fcntl.h> #include <unistd.h> static int setflags(int fd, int type) { int flags; if (type & SOCK_CLOEXEC) { flags = fcntl(fd, F_GETFD); if (flags == -1) return -1; if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) return -1; } if (type & SOCK_NONBLOCK) { flags = fcntl(fd, F_GETFL); if (flags == -1) return -1; if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) return -1; } return 0; } int _socketpair(int domain, int type, int protocol, int sv[2]) { int mask = ~(SOCK_CLOEXEC | SOCK_NONBLOCK); if (socketpair(domain, type & mask, protocol, sv) == -1) return -1; if (setflags(sv[0], type) == -1 || setflags(sv[1], type) == -1) { int save_errno = errno; close(sv[0]); close(sv[1]); errno = save_errno; return -1; } return 0; } int _socket(int domain, int type, int protocol) { int fd, mask = ~(SOCK_CLOEXEC | SOCK_NONBLOCK); if ((fd = socket(domain, type & mask, protocol)) == -1) return -1; if (setflags(fd, type) == -1) { int save_errno = errno; close(fd); errno = save_errno; return -1; } return fd; } #endif
2.125
2
2024-11-18T20:35:13.556237+00:00
2018-07-10T01:19:56
ba36849b39e31ea3a48a96e8be28a719c4b88cc1
{ "blob_id": "ba36849b39e31ea3a48a96e8be28a719c4b88cc1", "branch_name": "refs/heads/master", "committer_date": "2018-07-10T01:19:56", "content_id": "7d065ec54bb6e23c77d4fb9e11315b6cb8173171", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "3c9eab68937147e2464a67a8e171dd7f00b21ebf", "extension": "c", "filename": "dubinscar.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 67562272, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12844, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/examples/dubinscar_new/dubinscar.c", "provenance": "stackv2-0039.json.gz:678", "repo_name": "goroda/c3sc", "revision_date": "2018-07-10T01:19:56", "revision_id": "0236698a5180b56f7ad7516e707d6bb28fd6fae5", "snapshot_id": "d0eb19aa9c157cd666b799df70781c06cb88aaca", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/goroda/c3sc/0236698a5180b56f7ad7516e707d6bb28fd6fae5/examples/dubinscar_new/dubinscar.c", "visit_date": "2020-12-01T09:20:11.921972" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <getopt.h> /* #include "c3.h" */ #include "cdyn/simulate.h" #include "cdyn/integrate.h" #include "nodeutil.h" #include "valuefunc.h" #include "bellman.h" #include "c3sc.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif static char * program_name; void print_code_usage (FILE *, int) __attribute__ ((noreturn)); void print_code_usage (FILE * stream, int exit_code) { fprintf(stream, "Usage: %s options \n", program_name); fprintf(stream, " -h --help Display this usage information.\n" " -d --directory Output directory (defaults to .)\n" " -n --nodes Number of nodes (defaults to 10)\n" " -s --steps Number of iterations (default 100)\n" " -v --verbose Output words (default 0)\n" " 1 - output main file stuff\n" " >1 - also output approximation info\n" ); exit (exit_code); } int f1(double t, const double * x, const double * u, double * out, double * jac, void * args) { (void)(t); (void)(args); out[0] = cos(x[2]); out[1] = sin(x[2]); out[2] = u[0]; if (jac != NULL){ jac[0] = 0.0; jac[1] = 0.0; jac[2] = 1.0; } return 0; } int s1(double t,const double * x,const double * u,double * out, double * grad, void * args) { (void)(t); (void)(x); (void)(u); (void)(args); double val1 = 1e0; double val2 = 1e-2; out[0] = val1; out[3] = 0e0; out[6] = 0.0; out[1] = 0.0; out[4] = val1; out[7] = 0.0; out[2] = 0.0; out[5] = 0e0; out[8] = val2; if (grad != NULL){ for (size_t ii = 0; ii < 3*3; ii++){ grad[ii] = 0.0; } } return 0; } int stagecost(double t, const double * x, const double * u, double * out, double * grad) { (void)(t); (void)(u); (void)(x); *out = 0.0; //*out += pow(x[0],2) + pow(x[1],2); *out = 1.0; if (grad!= NULL){ grad[0] = 0.0; } return 0; } // cost of going into the boundaries int boundcost(double t, const double * x, double * out) { (void)(t); (void)(x); *out = 0.0; *out = 10.0; return 0; } // cost of hitting obstacle int ocost(const double * x,double * out) { /* printf("absorbed\n"); */ /* dprint(3,x); */ (void)(x); *out = 0.0; return 0; } // starting cost int startcost(size_t N, const double * x, double * out, void * args) { (void)(args); (void)(x); //double out = 10.0*x[0]*x[0] + 10.0*x[1]*x[1]; for (size_t ii = 0; ii < N; ii++){ out[ii] = 20.0; } return 0; } // needed for simulation int f1sym(double t, const double * x, const double * u, double * out, double * jac, void * args) { (void)(args); if (fabs(x[0]) < 0.1){ if (fabs(x[1]) < 0.1){ return 0; } } out[0] = cos(x[2]); out[1] = sin(x[2]); out[2] = u[0]; (void)(t); /* printf("t=%G,u=%G\n",t,u[0]); */ /* printf("x = "); dprint(3,x); */ /* printf("out = "); dprint(3,out); */ /* printf("----\n"); */ if (jac != NULL){ jac[0] = 0.0; jac[1] = 0.0; jac[2] = 1.0; } return 0; } void state_transform(size_t ndim, const double * x, double * y) { (void)(ndim); y[0] = x[0]; y[1] = x[1]; y[2] = x[2]; /* int trans = 0; */ if ((x[2] < M_PI ) && (x[2] > -M_PI)){ y[2] = x[2]; } else if (x[2] > M_PI){ /* trans = 1; */ while (y[2] > 2 * M_PI){ y[2] -= 2.0*M_PI; } if (y[2] > M_PI){ y[2] = y[2] - 2.0*M_PI; } } else if (x[2] < -M_PI){ /* trans = 1; */ while (y[2] < - 2.0* M_PI){ y[2] += 2.0 * M_PI; } if (y[2] < -M_PI){ y[2] += 2.0 * M_PI; } } /* if (trans == 1){ */ /* printf("out here x = (%G,%G,%G)\n",x[0],x[1],x[2]); */ /* printf("out here y = (%G,%G,%G)\n",y[0],y[1],y[2]); */ /* } */ } void print_cost(char * filename, struct ValueF * cost, size_t N1, size_t N2, double * lb, double * ub, double angle) { FILE * fp2 = fopen(filename, "w"); if (fp2 == NULL){ fprintf(stderr, "cat: can't open %s\n", filename); exit(0); } fprintf(fp2,"x y f\n"); double * xtest = linspace(lb[0],ub[0],N1); double * ytest = linspace(lb[1],ub[1],N2); double pt3[3]; double v2; for (size_t zz = 0; zz < N1; zz++){ for (size_t jj = 0; jj < N2; jj++){ pt3[0] = xtest[zz]; pt3[1] = ytest[jj]; pt3[2] = angle; v2 = valuef_eval(cost,pt3); fprintf(fp2, "%3.5f %3.5f %3.5f \n", xtest[zz],ytest[jj],v2); } fprintf(fp2,"\n"); } free(xtest); xtest = NULL; free(ytest); ytest = NULL; fclose(fp2); } int main(int argc, char * argv[]) { int next_option; const char * const short_options = "hd:n:s:v:"; const struct option long_options[] = { { "help" , 0, NULL, 'h' }, { "directory", 1, NULL, 'd' }, { "nodes" , 1, NULL, 'n' }, { "steps" , 1, NULL, 's' }, { "verbose" , 1, NULL, 'v' }, { NULL , 0, NULL, 0 } }; program_name = argv[0]; char * dirout = "."; int verbose = 0; size_t N = 30; size_t niter = 100; do { next_option = getopt_long (argc, argv, short_options, long_options, NULL); switch (next_option) { case 'h': print_code_usage(stdout, 0); case 'd': dirout = optarg; break; case 'n': N = strtoul(optarg,NULL,10); break; case 's': niter = strtoul(optarg,NULL,10); break; case 'v': verbose = strtol(optarg,NULL,10); break; case '?': // The user specified an invalid option print_code_usage (stderr, 1); case -1: // Done with options. break; default: // Something unexpected abort(); } } while (next_option != -1); size_t dx = 3; size_t dw = 3; size_t du = 1; double lb[3] = {-4.0, -4.0,-M_PI}; double ub[3] = {4.0, 4.0, M_PI}; size_t Narr[3] = {N, N, N}; double beta = 0.0; struct c3Opt * opt = c3opt_alloc(BRUTEFORCE,du); size_t dopts = 3; double uopts[3] = {-1.0,0.0,1.0}; c3opt_set_brute_force_vals(opt,dopts,uopts); // cross approximation tolerances struct ApproxArgs * aargs = approx_args_init(); approx_args_set_cross_tol(aargs,1e-5); approx_args_set_round_tol(aargs,1e-5); approx_args_set_kickrank(aargs,5); approx_args_set_startrank(aargs,5); size_t maxrank = 35; if (maxrank > N){ maxrank = N; } approx_args_set_maxrank(aargs,maxrank); // setup problem struct C3Control * c3c = c3control_create(dx,du,dw,lb,ub,Narr,beta); c3control_add_drift(c3c,f1,NULL); c3control_add_diff(c3c,s1,NULL); c3control_add_stagecost(c3c,stagecost); c3control_add_boundcost(c3c,boundcost); c3control_add_obscost(c3c,ocost); c3control_set_external_boundary(c3c,2,"periodic"); // possible obstacle double w = 0.5; double center[3] = {0.0,0.0,0.0}; double width[3] = {w,w,2.0*M_PI}; c3control_add_obstacle(c3c,center,width); char filename[256]; sprintf(filename,"%s/%s.c3",dirout,"cost"); double ** xgrid = c3control_get_xgrid(c3c); struct ValueF * cost = valuef_load(filename,Narr,xgrid); if (cost == NULL){ cost = c3control_init_value(c3c,startcost,NULL,aargs,0); } size_t maxiter_vi = niter+1; double abs_conv_vi = 1e-3; size_t maxiter_pi = 10; double abs_conv_pi = 1e-2; struct Diag * diag = NULL; char filename_diag[256]; sprintf(filename_diag,"%s/n%zu_%s",dirout,N,"diagnostic.dat"); printf("\n\n\n\n\n\n\n\n\n\n"); printf("Start Solver Iterations\n"); printf("\n\n\n\n\n\n\n\n\n\n"); for (size_t ii = 0; ii < maxiter_vi; ii++){ /* for (size_t ii = 0; ii < 0; ii++){ */ struct ValueF * next = c3control_pi_solve(c3c,maxiter_pi,abs_conv_pi, cost,aargs,opt,verbose,&diag); valuef_destroy(cost); cost = NULL; cost = c3control_vi_solve(c3c,1,abs_conv_vi,next,aargs,opt,verbose,&diag); valuef_destroy(next); next = NULL; sprintf(filename,"%s/%s.c3",dirout,"cost"); int saved = valuef_save(cost,filename); assert (saved == 0); if (verbose != 0){ printf("ii=%zu ranks=",ii); size_t * ranks = valuef_get_ranks(cost); iprint_sz(4,ranks); } saved = diag_save(diag,filename_diag); assert (saved == 0); } sprintf(filename,"%s/%s_angle=1.6.dat",dirout,"cost"); print_cost(filename,cost,30,30,lb,ub,1.6); sprintf(filename,"%s/%s_angle=-1.6.dat",dirout,"cost"); print_cost(filename,cost,30,30,lb,ub,-1.6); sprintf(filename,"%s/%s_angle=pi_3.dat",dirout,"cost"); print_cost(filename,cost,30,30,lb,ub,M_PI/3.0); c3control_add_policy_sim(c3c,cost,opt,state_transform); printf("created policy\n"); char odename[256] = "rk4"; struct Integrator * ode_sys = NULL; ode_sys = integrator_create_controlled( 3,1,f1sym, NULL,c3control_controller,c3c); integrator_set_type(ode_sys,odename); integrator_set_dt(ode_sys,1e-2); integrator_set_verbose(ode_sys,0); printf("initialized integrator\n"); // Initialize trajectories for filter and for observations double time = 0.0; double state[3] = {-1.0, 0.0, 3*M_PI/4.0}; double con[1] = {0.0}; struct Trajectory * traj = NULL; printf("add trajectory\n"); trajectory_add(&traj,3,1,time,state,con); printf("initialized trajectory\n"); double final_time = 1e1; double dt = 1e-2; int res; while (time < final_time){ /* printf("time = %G\n",time); */ res = trajectory_step(traj,ode_sys,dt); double * ls = trajectory_get_last_state(traj); if ((fabs(ls[0]) < w/2.0) && (fabs(ls[1]) < w/2.0) ){ break; } if (res != 0){ break; } // assert(res == 0); time = time + dt; } if (verbose == 1){ trajectory_print(traj,stdout,4); } sprintf(filename,"%s/%s.dat",dirout,"traj"); FILE * fp = fopen(filename,"w"); assert (fp != NULL); trajectory_print(traj,fp,4); fclose(fp); /* double final_time = 1e1; */ /* double dt = 1e-2; */ /* int res; */ double state2[3] = {3.0, 2.0, -M_PI/2}; /* double state2[3] = {-1.0, -1.0, M_PI/3.0}; */ double con2[1] = {0.0}; time = 0.0; struct Trajectory * traj2 = NULL; trajectory_add(&traj2,3,1,time,state2,con2); // final_time = 1e1; time = 0.0; while (time < final_time){ res = trajectory_step(traj2,ode_sys,dt); double * ls = trajectory_get_last_state(traj2); if ((fabs(ls[0]) < w/2.0) && (fabs(ls[1]) < w/2.0) ){ break; } if (res != 0){ break; } time = time + dt; } if (verbose == 1){ trajectory_print(traj2,stdout,4); } sprintf(filename,"%s/%s.dat",dirout,"traj2"); fp = fopen(filename,"w"); assert (fp != NULL); trajectory_print(traj2,fp,4); fclose(fp); double state3[3] = {-3.0, -1.0, 0.3}; double con3[1] = {0.0}; time = 0.0; struct Trajectory * traj3 = NULL; printf("add trajectory\n"); trajectory_add(&traj3,3,1,time,state3,con3); printf("initialized trajectory\n"); final_time = 1e1; time = 0.0; while (time < final_time){ res = trajectory_step(traj3,ode_sys,dt); double * ls = trajectory_get_last_state(traj3); if ((fabs(ls[0]) < w/2.0) && (fabs(ls[1]) < w/2.0) ){ break; } if (res != 0){ break; } time = time + dt; } sprintf(filename,"%s/%s.dat",dirout,"traj3"); fp = fopen(filename,"w"); assert (fp != NULL); trajectory_print(traj3,fp,4); fclose(fp); integrator_destroy(ode_sys); trajectory_free(traj); trajectory_free(traj2); valuef_destroy(cost); cost = NULL; c3control_destroy(c3c); c3c = NULL; diag_destroy(&diag); diag = NULL; c3opt_free(opt); opt = NULL; approx_args_free(aargs); aargs = NULL; return 0; }
2.40625
2
2024-11-18T20:49:53.509775+00:00
2018-06-06T13:16:49
45004d2cd8892469e53923559a4bd52b7a3e6882
{ "blob_id": "45004d2cd8892469e53923559a4bd52b7a3e6882", "branch_name": "refs/heads/master", "committer_date": "2018-06-06T13:16:49", "content_id": "a2305d9402351c5ccf4471b7afffa5426cd125aa", "detected_licenses": [ "MIT" ], "directory_id": "aea83600ee871e030200c92c725a0aeeb61af494", "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": 126294528, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5849, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0039.json.gz:200916", "repo_name": "PUT-PTM/2018_GuitarTuner", "revision_date": "2018-06-06T13:16:49", "revision_id": "bb984b0033dbc2d3c0a5505c90c9ec6f53402cec", "snapshot_id": "02db69155468e09fa8243dfe0d45bc6f6aab0e00", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PUT-PTM/2018_GuitarTuner/bb984b0033dbc2d3c0a5505c90c9ec6f53402cec/main.c", "visit_date": "2021-04-15T05:21:01.053812" }
stackv2
#include <math.h> #include <stdio.h> #include "arm_math.h" #include "main.h" #include "pdm_filter.h" #include "stm32f4xx.h" uint8_t PDM_Input_Buffer[PDM_Input_Buffer_SIZE]; uint16_t PCM_Output_Buffer[PCM_Output_Buffer_SIZE]; float32_t buffer_input[4096]; float32_t buffer_output[4096]; float32_t buffer_output_mag[4096]; float32_t maxvalue; uint32_t maxvalueindex; float32_t peak = 0; uint8_t mode = 1; arm_rfft_instance_f32 S; arm_cfft_radix4_instance_f32 S_CFFT; PDMFilter_InitStruct Filter; static void GPIO_Configure(void); static void I2S_Configure(void); static void NVIC_Configure(void); static void RCC_Configure(void); void compare(int a, int b) { // Compare the peak with given frequencies if (peak > a && peak < b) { GPIO_WriteBit(GPIOD, GPIO_Pin_12, Bit_SET); GPIO_WriteBit(GPIOD, GPIO_Pin_14, Bit_SET); } else if (peak < a) GPIO_WriteBit(GPIOD, GPIO_Pin_12, Bit_SET); else if (peak > b) GPIO_WriteBit(GPIOD, GPIO_Pin_14, Bit_SET); } int main(void) { extern uint32_t Data_Status; unsigned int i, z; RCC_Configure(); NVIC_Configure(); GPIO_Configure(); I2S_Configure(); // Initialize PDM filter Filter.Fs = OUT_FREQ; Filter.HP_HZ = 70; Filter.LP_HZ = 1000; Filter.In_MicChannels = 1; Filter.Out_MicChannels = 1; PDM_Filter_Init(&Filter); arm_rfft_init_f32(&S, &S_CFFT, 2048, 0, 1); // Initialize FFT z = 0; I2S_Cmd(SPI2, ENABLE); while (1) { if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0)) { while (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0)) ; if (mode == 1) { mode = 2; GPIO_WriteBit(GPIOD, GPIO_Pin_13, Bit_SET); } else if (mode == 2) { mode = 1; GPIO_WriteBit(GPIOD, GPIO_Pin_13, Bit_RESET); } } if (Data_Status) { for (i = 0; i < (OUT_FREQ / 1000); i++) { //Fill FFT buffer with samples buffer_input[i + (OUT_FREQ / 1000) * z] = (float32_t) PCM_Output_Buffer[i]; } ++z; if (z > 2048 / (OUT_FREQ / 1000)) { z = 0; // FFT arm_rfft_f32(&S, buffer_input, buffer_output); // Calculate magnitude arm_cmplx_mag_f32(buffer_output, buffer_output_mag, 2048); // Get maximum value of magnitude arm_max_f32(&(buffer_output_mag[1]), 2048, &maxvalue, &maxvalueindex); } Data_Status = 0; } if (maxvalue < 5000000) { // Threshold peak = 0; GPIO_WriteBit(GPIOD, GPIO_Pin_12, Bit_RESET); GPIO_WriteBit(GPIOD, GPIO_Pin_14, Bit_RESET); } else { peak = (maxvalueindex + 1) * 62.5 / 4 / 4; // Calculate peak frequency GPIO_WriteBit(GPIOD, GPIO_Pin_12, Bit_RESET); GPIO_WriteBit(GPIOD, GPIO_Pin_14, Bit_RESET); if (mode == 2){ peak /= 2; } if (peak >= 280 && peak < 400) { //E compare(328, 330); } else if (peak >= 220 && peak < 280) { //B compare(244, 248); } else if (peak >= 165 && peak < 220) { //G compare(195, 199); } else if (peak >= 130 && peak < 165) { //D compare(144, 148); } else if (peak >= 95 && peak < 130) { //A compare(109, 114); } else if (peak >= 70 && peak < 95) { //E compare(81, 83); } } } I2S_Cmd(SPI2, DISABLE); } static void GPIO_Configure(void) { GPIO_InitTypeDef GPIO_InitStructure; // Configure MP45DT02's CLK / I2S2_CLK (PB10) line GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); // Configure MP45DT02's DOUT / I2S2_DATA (PC3) line GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz; GPIO_Init(GPIOC, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_SPI2); // Connect pin 10 of port B to the SPI2 peripheral GPIO_PinAFConfig(GPIOC, GPIO_PinSource3, GPIO_AF_SPI2); // Connect pin 3 of port C to the SPI2 peripheral RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOD, &GPIO_InitStructure); // Enable LED indicators RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN; GPIO_Init(GPIOA, &GPIO_InitStructure); // Enable LED indicators } static void I2S_Configure(void) { I2S_InitTypeDef I2S_InitStructure; SPI_I2S_DeInit(SPI2); I2S_InitStructure.I2S_AudioFreq = OUT_FREQ * 2; I2S_InitStructure.I2S_Standard = I2S_Standard_LSB; I2S_InitStructure.I2S_DataFormat = I2S_DataFormat_16b; I2S_InitStructure.I2S_CPOL = I2S_CPOL_High; I2S_InitStructure.I2S_Mode = I2S_Mode_MasterRx; I2S_InitStructure.I2S_MCLKOutput = I2S_MCLKOutput_Disable; I2S_Init(SPI2, &I2S_InitStructure); SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_RXNE, ENABLE); } static void NVIC_Configure(void) { NVIC_InitTypeDef NVIC_InitStructure; NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); NVIC_InitStructure.NVIC_IRQChannel = SPI2_IRQn; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; NVIC_Init(&NVIC_InitStructure); } static void RCC_Configure(void) { RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOB | RCC_AHB1Periph_GPIOC | RCC_AHB1Periph_CRC, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE); RCC_PLLI2SCmd(ENABLE); }
2.5
2
2024-11-18T20:49:54.171533+00:00
2021-10-29T19:33:34
9f930b3f7bc9730aa853d34724f3407f4d60e4ca
{ "blob_id": "9f930b3f7bc9730aa853d34724f3407f4d60e4ca", "branch_name": "refs/heads/main", "committer_date": "2021-10-29T19:33:34", "content_id": "bff1c1ea4bd8157449f7437c7a7fe256a3cf8397", "detected_licenses": [ "MIT" ], "directory_id": "d6f4245de8d48703508b9b1430b042867625de68", "extension": "c", "filename": "round.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": 635, "license": "MIT", "license_type": "permissive", "path": "/test/c/mathc/round.c", "provenance": "stackv2-0039.json.gz:201303", "repo_name": "songfu1983/smack", "revision_date": "2021-10-29T19:33:34", "revision_id": "c7d0694f08cefb422ebcc67c23824727b06b370e", "snapshot_id": "7d6193a89aeda544638ef1f6b5cdddf6a7a1f910", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/songfu1983/smack/c7d0694f08cefb422ebcc67c23824727b06b370e/test/c/mathc/round.c", "visit_date": "2023-08-23T03:11:27.907783" }
stackv2
#include "smack.h" #include <assert.h> #include <math.h> // @expect verified // @flag --integer-encoding=bit-vector int main(void) { double NaN = 0.0 / 0.0; double Inf = 1.0 / 0.0; double negInf = -1.0 / 0.0; double val = __VERIFIER_nondet_double(); if (!__isnan(val) && !__isinf(val) && !__iszero(val)) { double rval = round(val); assert(rval == floor(val) || rval == ceil(val)); } assert(round(0.0) == 0.0); assert(round(-0.0) == -0.0); int isNeg = __signbit(round(-0.0)); assert(isNeg); assert(round(Inf) == Inf); assert(round(negInf) == negInf); assert(__isnan(round(NaN))); return 0; }
2.3125
2
2024-11-18T20:49:54.245054+00:00
2018-03-28T06:00:40
d09da94b1e5e18521f07be1d28d302e955fd6ab7
{ "blob_id": "d09da94b1e5e18521f07be1d28d302e955fd6ab7", "branch_name": "refs/heads/master", "committer_date": "2018-03-28T06:00:40", "content_id": "d28f237cd10d86ba4f174518a99bb4bae9b9b6f6", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3372a0e4dbfe751c42c7f0896037939904bd5206", "extension": "c", "filename": "shaders.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": 3345, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/shaders.c", "provenance": "stackv2-0039.json.gz:201432", "repo_name": "nhantt92/Espirgbani", "revision_date": "2018-03-28T06:00:40", "revision_id": "ffbe3bfb7c2bf795675deeb004648acba6a9bbf4", "snapshot_id": "a2e588ea70d208464dee57989245fdba90451474", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nhantt92/Espirgbani/ffbe3bfb7c2bf795675deeb004648acba6a9bbf4/src/main/shaders.c", "visit_date": "2020-03-09T19:49:04.341844" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "esp_log.h" // #include "wifi_startup.h" // #include "web_console.h" #include "rgb_led_panel.h" // #include "sdcard.h" // #include "animations.h" #include "frame_buffer.h" // #include "bmp.h" // #include "font.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "shaders.h" #include "app_main.h" static const char *T = "SHADERS"; // The animated background patterns void drawXorFrame(){ static int frm=0; static uint16_t aniZoom=0x04, boost=7; startDrawing( 0 ); for( int y=0; y<=31; y++ ) for( int x=0; x<=127; x++ ) setPixel( 0, x, y, SRGBA( ((x+y+frm)&aniZoom)*boost, ((x-y-frm)&aniZoom)*boost, ((x^y)&aniZoom)*boost, 0xFF ) ); doneDrawing( 0 ); if( (frm%1024) == 0 ){ aniZoom = rand(); boost = RAND_AB(1,8); ESP_LOGI(T, "aniZoom = %d, boost = %d", aniZoom, boost); } frm++; } void drawPlasmaFrame(){ static int frm=3001, i, j, k, l; int temp1, temp2; if( frm > 3000 ){ frm = 0; i = RAND_AB(1,8); j = RAND_AB(1,8); k = ((i<<5)-1); l = ((j<<5)-1); } startDrawing( 0 ); for( int y=0; y<=31; y++ ){ for( int x=0; x<=127; x++ ){ temp1 = abs((( i*y+(frm*16)/(x+16))%64)-32)*7; temp2 = abs((( j*x+(frm*16)/(y+16))%64)-32)*7; setPixel( 0, x, y, SRGBA( temp1&k, temp2&l, (temp1^temp2)&0x88, 0xFF ) ); } } doneDrawing( 0 ); frm++; } void drawAlienFlameFrame(){ // *p points to last pixel of second last row (lower right) // uint32_t *p = (uint32_t*)g_frameBuff[0][DISPLAY_WIDTH*(DISPLAY_HEIGHT-1)-1]; // uint32_t *tempP; uint32_t colIndex, temp; startDrawing( 0 ); colIndex = RAND_AB(0,127); temp = getPixel( 0, colIndex, 31 ); setPixel( 0, colIndex, 31, 0xFF000000 | (temp+2) ); colIndex = RAND_AB(0,127); temp = getPixel( 0, colIndex, 31 ); temp = scale32( 127, temp ); setPixel( 0, colIndex, 31, temp ); for( int y=30; y>=0; y-- ){ for( int x=0; x<=127; x++ ){ colIndex = RAND_AB(0,2); temp = GC(getPixel(0, x-1, y+1), colIndex); temp += GC(getPixel(0, x, y+1), colIndex); temp += GC(getPixel(0, x+1, y+1), colIndex); setPixelColor( 0, x, y, RAND_AB(0,2), MIN(temp*5/8,255) ); } } doneDrawing( 0 ); } void aniBackgroundTask(void *pvParameters){ ESP_LOGI(T,"aniBackgroundTask started"); uint32_t frameCount = 1; uint8_t aniMode = 3; setAll( 0, 0xFF000000 ); while(1){ switch( aniMode ){ case 1: drawXorFrame(); break; case 2: drawPlasmaFrame(); break; case 3: drawAlienFlameFrame(); default: vTaskDelay( 10 / portTICK_PERIOD_MS ); } updateFrame(); if( (frameCount%10000)==0 ){ aniMode = RAND_AB(0,5); if( aniMode==0 || aniMode>3 ){ int tempColor = 0xFF000000;// | scale32( 128, rand() ); setAll( 0, tempColor ); } } frameCount++; vTaskDelay( 10 / portTICK_PERIOD_MS ); } vTaskDelete( NULL ); }
2.078125
2
2024-11-18T18:43:51.097055+00:00
2021-03-07T03:05:31
ace55dbe74e282e6c95757778155b582be4b5d7f
{ "blob_id": "ace55dbe74e282e6c95757778155b582be4b5d7f", "branch_name": "refs/heads/main", "committer_date": "2021-03-07T03:05:31", "content_id": "3f1fb81ab1e8b457c8839ce95369326fe4e21844", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "62bfd82e9f14d0ab2cb0a9cdaca1185fac343e78", "extension": "c", "filename": "console.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": 23313, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/kernel/chr_drv/console.c", "provenance": "stackv2-0040.json.gz:118564", "repo_name": "spyos/LinuxKernel-src0.12", "revision_date": "2021-03-07T03:05:31", "revision_id": "b473d4244cb139647c621db99118fe0f1118054e", "snapshot_id": "2c3c5c387854f1ae54d0a5dd8b5923687550739f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/spyos/LinuxKernel-src0.12/b473d4244cb139647c621db99118fe0f1118054e/kernel/chr_drv/console.c", "visit_date": "2023-03-17T22:46:52.679610" }
stackv2
/* * linux/kernel/console.c * * (C) 1991 Linus Torvalds */ /* * console.c * * This module implements the console io functions * 'void con_init(void)' * 'void con_write(struct tty_queue * queue)' * Hopefully this will be a rather complete VT102 implementation. * * Beeping thanks to John T Kohl. * * Virtual Consoles, Screen Blanking, Screen Dumping, Color, Graphics * Chars, and VT100 enhancements by Peter MacDonald. */ /* * NOTE!!! We sometimes disable and enable interrupts for a short while * (to put a word in video IO), but this will work even for keyboard * interrupts. We know interrupts aren't enabled when getting a keyboard * interrupt, as we use trap-gates. Hopefully all is well. */ /* * Code to check for different video-cards mostly by Galen Hunt, * <g-hunt@ee.utah.edu> */ #include <linux/sched.h> #include <linux/tty.h> #include <linux/config.h> #include <linux/kernel.h> #include <asm/io.h> #include <asm/system.h> #include <asm/segment.h> #include <string.h> #include <errno.h> #define DEF_TERMIOS \ (struct termios) { \ ICRNL, \ OPOST | ONLCR, \ 0, \ IXON | ISIG | ICANON | ECHO | ECHOCTL | ECHOKE, \ 0, \ INIT_C_CC \ } /* * These are set up by the setup-routine at boot-time: */ #define ORIG_X (*(unsigned char *)0x90000) #define ORIG_Y (*(unsigned char *)0x90001) #define ORIG_VIDEO_PAGE (*(unsigned short *)0x90004) #define ORIG_VIDEO_MODE ((*(unsigned short *)0x90006) & 0xff) #define ORIG_VIDEO_COLS (((*(unsigned short *)0x90006) & 0xff00) >> 8) #define ORIG_VIDEO_LINES ((*(unsigned short *)0x9000e) & 0xff) #define ORIG_VIDEO_EGA_AX (*(unsigned short *)0x90008) #define ORIG_VIDEO_EGA_BX (*(unsigned short *)0x9000a) #define ORIG_VIDEO_EGA_CX (*(unsigned short *)0x9000c) #define VIDEO_TYPE_MDA 0x10 /* Monochrome Text Display */ #define VIDEO_TYPE_CGA 0x11 /* CGA Display */ #define VIDEO_TYPE_EGAM 0x20 /* EGA/VGA in Monochrome Mode */ #define VIDEO_TYPE_EGAC 0x21 /* EGA/VGA in Color Mode */ #define NPAR 16 int NR_CONSOLES = 0; extern void keyboard_interrupt(void); static unsigned char video_type; /* Type of display being used */ static unsigned long video_num_columns; /* Number of text columns */ static unsigned long video_mem_base; /* Base of video memory */ static unsigned long video_mem_term; /* End of video memory */ static unsigned long video_size_row; /* Bytes per row */ static unsigned long video_num_lines; /* Number of test lines */ static unsigned char video_page; /* Initial video page */ static unsigned short video_port_reg; /* Video register select port */ static unsigned short video_port_val; /* Video register value port */ static int can_do_colour = 0; static struct { unsigned short vc_video_erase_char; unsigned char vc_attr; unsigned char vc_def_attr; int vc_bold_attr; unsigned long vc_ques; unsigned long vc_state; unsigned long vc_restate; unsigned long vc_checkin; unsigned long vc_origin; /* Used for EGA/VGA fast scroll */ unsigned long vc_scr_end; /* Used for EGA/VGA fast scroll */ unsigned long vc_pos; unsigned long vc_x,vc_y; unsigned long vc_top,vc_bottom; unsigned long vc_npar,vc_par[NPAR]; unsigned long vc_video_mem_start; /* Start of video RAM */ unsigned long vc_video_mem_end; /* End of video RAM (sort of) */ unsigned int vc_saved_x; unsigned int vc_saved_y; unsigned int vc_iscolor; char * vc_translate; } vc_cons [MAX_CONSOLES]; #define origin (vc_cons[currcons].vc_origin) #define scr_end (vc_cons[currcons].vc_scr_end) #define pos (vc_cons[currcons].vc_pos) #define top (vc_cons[currcons].vc_top) #define bottom (vc_cons[currcons].vc_bottom) #define x (vc_cons[currcons].vc_x) #define y (vc_cons[currcons].vc_y) #define state (vc_cons[currcons].vc_state) #define restate (vc_cons[currcons].vc_restate) #define checkin (vc_cons[currcons].vc_checkin) #define npar (vc_cons[currcons].vc_npar) #define par (vc_cons[currcons].vc_par) #define ques (vc_cons[currcons].vc_ques) #define attr (vc_cons[currcons].vc_attr) #define saved_x (vc_cons[currcons].vc_saved_x) #define saved_y (vc_cons[currcons].vc_saved_y) #define translate (vc_cons[currcons].vc_translate) #define video_mem_start (vc_cons[currcons].vc_video_mem_start) #define video_mem_end (vc_cons[currcons].vc_video_mem_end) #define def_attr (vc_cons[currcons].vc_def_attr) #define video_erase_char (vc_cons[currcons].vc_video_erase_char) #define iscolor (vc_cons[currcons].vc_iscolor) int blankinterval = 0; int blankcount = 0; static void sysbeep(void); /* * this is what the terminal answers to a ESC-Z or csi0c * query (= vt100 response). */ #define RESPONSE "\033[?1;2c" static char * translations[] = { /* normal 7-bit ascii */ " !\"#$%&'()*+,-./0123456789:;<=>?" "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_" "`abcdefghijklmnopqrstuvwxyz{|}~ ", /* vt100 graphics */ " !\"#$%&'()*+,-./0123456789:;<=>?" "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ " "\004\261\007\007\007\007\370\361\007\007\275\267\326\323\327\304" "\304\304\304\304\307\266\320\322\272\363\362\343\\007\234\007 " }; #define NORM_TRANS (translations[0]) #define GRAF_TRANS (translations[1]) /* NOTE! gotoxy thinks x==video_num_columns is ok */ static inline void gotoxy(int currcons, int new_x,unsigned int new_y) { if (new_x > video_num_columns || new_y >= video_num_lines) return; x = new_x; y = new_y; pos = origin + y*video_size_row + (x<<1); } static inline void set_origin(int currcons) { if (video_type != VIDEO_TYPE_EGAC && video_type != VIDEO_TYPE_EGAM) return; if (currcons != fg_console) return; cli(); outb_p(12, video_port_reg); outb_p(0xff&((origin-video_mem_base)>>9), video_port_val); outb_p(13, video_port_reg); outb_p(0xff&((origin-video_mem_base)>>1), video_port_val); sti(); } static void scrup(int currcons) { if (bottom<=top) return; if (video_type == VIDEO_TYPE_EGAC || video_type == VIDEO_TYPE_EGAM) { if (!top && bottom == video_num_lines) { origin += video_size_row; pos += video_size_row; scr_end += video_size_row; if (scr_end > video_mem_end) { __asm__("cld\n\t" "rep\n\t" "movsl\n\t" "movl video_num_columns,%1\n\t" "rep\n\t" "stosw" ::"a" (video_erase_char), "c" ((video_num_lines-1)*video_num_columns>>1), "D" (video_mem_start), "S" (origin) :); scr_end -= origin-video_mem_start; pos -= origin-video_mem_start; origin = video_mem_start; } else { __asm__("cld\n\t" "rep\n\t" "stosw" ::"a" (video_erase_char), "c" (video_num_columns), "D" (scr_end-video_size_row) :); } set_origin(currcons); } else { __asm__("cld\n\t" "rep\n\t" "movsl\n\t" "movl video_num_columns,%%ecx\n\t" "rep\n\t" "stosw" ::"a" (video_erase_char), "c" ((bottom-top-1)*video_num_columns>>1), "D" (origin+video_size_row*top), "S" (origin+video_size_row*(top+1)) :); } } else /* Not EGA/VGA */ { __asm__("cld\n\t" "rep\n\t" "movsl\n\t" "movl video_num_columns,%%ecx\n\t" "rep\n\t" "stosw" ::"a" (video_erase_char), "c" ((bottom-top-1)*video_num_columns>>1), "D" (origin+video_size_row*top), "S" (origin+video_size_row*(top+1)) :); } } static void scrdown(int currcons) { if (bottom <= top) return; if (video_type == VIDEO_TYPE_EGAC || video_type == VIDEO_TYPE_EGAM) { __asm__("std\n\t" "rep\n\t" "movsl\n\t" "addl $2,%%edi\n\t" /* %edi has been decremented by 4 */ "movl video_num_columns,%%ecx\n\t" "rep\n\t" "stosw" ::"a" (video_erase_char), "c" ((bottom-top-1)*video_num_columns>>1), "D" (origin+video_size_row*bottom-4), "S" (origin+video_size_row*(bottom-1)-4) :); } else /* Not EGA/VGA */ { __asm__("std\n\t" "rep\n\t" "movsl\n\t" "addl $2,%%edi\n\t" /* %edi has been decremented by 4 */ "movl video_num_columns,%%ecx\n\t" "rep\n\t" "stosw" ::"a" (video_erase_char), "c" ((bottom-top-1)*video_num_columns>>1), "D" (origin+video_size_row*bottom-4), "S" (origin+video_size_row*(bottom-1)-4) :); } } static void lf(int currcons) { if (y+1<bottom) { y++; pos += video_size_row; return; } scrup(currcons); } static void ri(int currcons) { if (y>top) { y--; pos -= video_size_row; return; } scrdown(currcons); } static void cr(int currcons) { pos -= x<<1; x=0; } static void del(int currcons) { if (x) { pos -= 2; x--; *(unsigned short *)pos = video_erase_char; } } static void csi_J(int currcons, int vpar) { // long count __asm__("cx"); // long start __asm__("di"); long count; long start; switch (vpar) { case 0: /* erase from cursor to end of display */ count = (scr_end-pos)>>1; start = pos; break; case 1: /* erase from start to cursor */ count = (pos-origin)>>1; start = origin; break; case 2: /* erase whole display */ count = video_num_columns * video_num_lines; start = origin; break; default: return; } __asm__("cld\n\t" "rep\n\t" "stosw\n\t" ::"c" (count), "D" (start),"a" (video_erase_char) :); } static void csi_K(int currcons, int vpar) { // long count __asm__("cx"); // long start __asm__("di"); long count; long start; switch (vpar) { case 0: /* erase from cursor to end of line */ if (x>=video_num_columns) return; count = video_num_columns-x; start = pos; break; case 1: /* erase from start of line to cursor */ start = pos - (x<<1); count = (x<video_num_columns)?x:video_num_columns; break; case 2: /* erase whole line */ start = pos - (x<<1); count = video_num_columns; break; default: return; } __asm__("cld\n\t" "rep\n\t" "stosw\n\t" ::"c" (count), "D" (start),"a" (video_erase_char) :); } void csi_m(int currcons ) { int i; for (i=0;i<=npar;i++) switch (par[i]) { case 0: attr=def_attr;break; /* default */ case 1: attr=(iscolor?attr|0x08:attr|0x0f);break; /* bold */ /*case 4: attr=attr|0x01;break;*/ /* underline */ case 4: /* bold */ if (!iscolor) attr |= 0x01; else { /* check if forground == background */ if (vc_cons[currcons].vc_bold_attr != -1) attr = (vc_cons[currcons].vc_bold_attr&0x0f)|(0xf0&(attr)); else { short newattr = (attr&0xf0)|(0xf&(~attr)); attr = ((newattr&0xf)==((attr>>4)&0xf)? (attr&0xf0)|(((attr&0xf)+1)%0xf): newattr); } } break; case 5: attr=attr|0x80;break; /* blinking */ case 7: attr=(attr<<4)|(attr>>4);break; /* negative */ case 22: attr=attr&0xf7;break; /* not bold */ case 24: attr=attr&0xfe;break; /* not underline */ case 25: attr=attr&0x7f;break; /* not blinking */ case 27: attr=def_attr;break; /* positive image */ case 39: attr=(attr & 0xf0)|(def_attr & 0x0f); break; case 49: attr=(attr & 0x0f)|(def_attr & 0xf0); break; default: if (!can_do_colour) break; iscolor = 1; if ((par[i]>=30) && (par[i]<=38)) attr = (attr & 0xf0) | (par[i]-30); else /* Background color */ if ((par[i]>=40) && (par[i]<=48)) attr = (attr & 0x0f) | ((par[i]-40)<<4); else break; } } static inline void set_cursor(int currcons) { blankcount = blankinterval; if (currcons != fg_console) return; cli(); outb_p(14, video_port_reg); outb_p(0xff&((pos-video_mem_base)>>9), video_port_val); outb_p(15, video_port_reg); outb_p(0xff&((pos-video_mem_base)>>1), video_port_val); sti(); } static inline void hide_cursor(int currcons) { outb_p(14, video_port_reg); outb_p(0xff&((scr_end-video_mem_base)>>9), video_port_val); outb_p(15, video_port_reg); outb_p(0xff&((scr_end-video_mem_base)>>1), video_port_val); } static void respond(int currcons, struct tty_struct * tty) { char * p = RESPONSE; cli(); while (*p) { PUTCH(*p,tty->read_q); p++; } sti(); copy_to_cooked(tty); } static void insert_char(int currcons) { int i=x; unsigned short tmp, old = video_erase_char; unsigned short * p = (unsigned short *) pos; while (i++<video_num_columns) { tmp=*p; *p=old; old=tmp; p++; } } static void insert_line(int currcons) { int oldtop,oldbottom; oldtop=top; oldbottom=bottom; top=y; bottom = video_num_lines; scrdown(currcons); top=oldtop; bottom=oldbottom; } static void delete_char(int currcons) { int i; unsigned short * p = (unsigned short *) pos; if (x>=video_num_columns) return; i = x; while (++i < video_num_columns) { *p = *(p+1); p++; } *p = video_erase_char; } static void delete_line(int currcons) { int oldtop,oldbottom; oldtop=top; oldbottom=bottom; top=y; bottom = video_num_lines; scrup(currcons); top=oldtop; bottom=oldbottom; } static void csi_at(int currcons, unsigned int nr) { if (nr > video_num_columns) nr = video_num_columns; else if (!nr) nr = 1; while (nr--) insert_char(currcons); } static void csi_L(int currcons, unsigned int nr) { if (nr > video_num_lines) nr = video_num_lines; else if (!nr) nr = 1; while (nr--) insert_line(currcons); } static void csi_P(int currcons, unsigned int nr) { if (nr > video_num_columns) nr = video_num_columns; else if (!nr) nr = 1; while (nr--) delete_char(currcons); } static void csi_M(int currcons, unsigned int nr) { if (nr > video_num_lines) nr = video_num_lines; else if (!nr) nr=1; while (nr--) delete_line(currcons); } static void save_cur(int currcons) { saved_x=x; saved_y=y; } static void restore_cur(int currcons) { gotoxy(currcons,saved_x, saved_y); } enum { ESnormal, ESesc, ESsquare, ESgetpars, ESgotpars, ESfunckey, ESsetterm, ESsetgraph }; void con_write(struct tty_struct * tty) { int nr; char c; int currcons; currcons = tty - tty_table; if ((currcons>=MAX_CONSOLES) || (currcons<0)) panic("con_write: illegal tty"); nr = CHARS(tty->write_q); while (nr--) { if (tty->stopped) break; GETCH(tty->write_q,c); if (c == 24 || c == 26) state = ESnormal; switch(state) { case ESnormal: if (c>31 && c<127) { if (x>=video_num_columns) { x -= video_num_columns; pos -= video_size_row; lf(currcons); } __asm__("movb %2,%%ah\n\t" "movw %%ax,%1\n\t" ::"a" (translate[c-32]), "m" (*(short *)pos), "m" (attr) :); pos += 2; x++; } else if (c==27) state=ESesc; else if (c==10 || c==11 || c==12) lf(currcons); else if (c==13) cr(currcons); else if (c==ERASE_CHAR(tty)) del(currcons); else if (c==8) { if (x) { x--; pos -= 2; } } else if (c==9) { c=8-(x&7); x += c; pos += c<<1; if (x>video_num_columns) { x -= video_num_columns; pos -= video_size_row; lf(currcons); } c=9; } else if (c==7) sysbeep(); else if (c == 14) translate = GRAF_TRANS; else if (c == 15) translate = NORM_TRANS; break; case ESesc: state = ESnormal; switch (c) { case '[': state=ESsquare; break; case 'E': gotoxy(currcons,0,y+1); break; case 'M': ri(currcons); break; case 'D': lf(currcons); break; case 'Z': respond(currcons,tty); break; case '7': save_cur(currcons); break; case '8': restore_cur(currcons); break; case '(': case ')': state = ESsetgraph; break; case 'P': state = ESsetterm; break; case '#': state = -1; break; case 'c': tty->termios = DEF_TERMIOS; state = restate = ESnormal; checkin = 0; top = 0; bottom = video_num_lines; break; /* case '>': Numeric keypad */ /* case '=': Appl. keypad */ } break; case ESsquare: for(npar=0;npar<NPAR;npar++) par[npar]=0; npar=0; state=ESgetpars; if (c =='[') /* Function key */ { state=ESfunckey; break; } if ( (ques=(c=='?')) ) break; case ESgetpars: if (c==';' && npar<NPAR-1) { npar++; break; } else if (c>='0' && c<='9') { par[npar]=10*par[npar]+c-'0'; break; } else state=ESgotpars; case ESgotpars: state = ESnormal; if (ques) { ques =0; break; } switch(c) { case 'G': case '`': if (par[0]) par[0]--; gotoxy(currcons,par[0],y); break; case 'A': if (!par[0]) par[0]++; gotoxy(currcons,x,y-par[0]); break; case 'B': case 'e': if (!par[0]) par[0]++; gotoxy(currcons,x,y+par[0]); break; case 'C': case 'a': if (!par[0]) par[0]++; gotoxy(currcons,x+par[0],y); break; case 'D': if (!par[0]) par[0]++; gotoxy(currcons,x-par[0],y); break; case 'E': if (!par[0]) par[0]++; gotoxy(currcons,0,y+par[0]); break; case 'F': if (!par[0]) par[0]++; gotoxy(currcons,0,y-par[0]); break; case 'd': if (par[0]) par[0]--; gotoxy(currcons,x,par[0]); break; case 'H': case 'f': if (par[0]) par[0]--; if (par[1]) par[1]--; gotoxy(currcons,par[1],par[0]); break; case 'J': csi_J(currcons,par[0]); break; case 'K': csi_K(currcons,par[0]); break; case 'L': csi_L(currcons,par[0]); break; case 'M': csi_M(currcons,par[0]); break; case 'P': csi_P(currcons,par[0]); break; case '@': csi_at(currcons,par[0]); break; case 'm': csi_m(currcons); break; case 'r': if (par[0]) par[0]--; if (!par[1]) par[1] = video_num_lines; if (par[0] < par[1] && par[1] <= video_num_lines) { top=par[0]; bottom=par[1]; } break; case 's': save_cur(currcons); break; case 'u': restore_cur(currcons); break; case 'l': /* blank interval */ case 'b': /* bold attribute */ if (!((npar >= 2) && ((par[1]-13) == par[0]) && ((par[2]-17) == par[0]))) break; if ((c=='l')&&(par[0]>=0)&&(par[0]<=60)) { blankinterval = HZ*60*par[0]; blankcount = blankinterval; } if (c=='b') vc_cons[currcons].vc_bold_attr = par[0]; } break; case ESfunckey: state = ESnormal; break; case ESsetterm: /* Setterm functions. */ state = ESnormal; if (c == 'S') { def_attr = attr; video_erase_char = (video_erase_char&0x0ff) | (def_attr<<8); } else if (c == 'L') ; /*linewrap on*/ else if (c == 'l') ; /*linewrap off*/ break; case ESsetgraph: state = ESnormal; if (c == '0') translate = GRAF_TRANS; else if (c == 'B') translate = NORM_TRANS; break; default: state = ESnormal; } } set_cursor(currcons); } /* * void con_init(void); * * This routine initalizes console interrupts, and does nothing * else. If you want the screen to clear, call tty_write with * the appropriate escape-sequece. * * Reads the information preserved by setup.s to determine the current display * type and sets everything accordingly. */ void con_init(void) { register unsigned char a; char *display_desc = "????"; char *display_ptr; int currcons = 0; long base, term; long video_memory; video_num_columns = ORIG_VIDEO_COLS; video_size_row = video_num_columns * 2; video_num_lines = ORIG_VIDEO_LINES; video_page = ORIG_VIDEO_PAGE; video_erase_char = 0x0720; blankcount = blankinterval; if (ORIG_VIDEO_MODE == 7) /* Is this a monochrome display? */ { video_mem_base = 0xb0000; video_port_reg = 0x3b4; video_port_val = 0x3b5; if ((ORIG_VIDEO_EGA_BX & 0xff) != 0x10) { video_type = VIDEO_TYPE_EGAM; video_mem_term = 0xb8000; display_desc = "EGAm"; } else { video_type = VIDEO_TYPE_MDA; video_mem_term = 0xb2000; display_desc = "*MDA"; } } else /* If not, it is color. */ { can_do_colour = 1; video_mem_base = 0xb8000; video_port_reg = 0x3d4; video_port_val = 0x3d5; if ((ORIG_VIDEO_EGA_BX & 0xff) != 0x10) { video_type = VIDEO_TYPE_EGAC; video_mem_term = 0xc0000; display_desc = "EGAc"; } else { video_type = VIDEO_TYPE_CGA; video_mem_term = 0xba000; display_desc = "*CGA"; } } video_memory = video_mem_term - video_mem_base; NR_CONSOLES = video_memory / (video_num_lines * video_size_row); if (NR_CONSOLES > MAX_CONSOLES) NR_CONSOLES = MAX_CONSOLES; if (!NR_CONSOLES) NR_CONSOLES = 1; video_memory /= NR_CONSOLES; /* Let the user known what kind of display driver we are using */ display_ptr = ((char *)video_mem_base) + video_size_row - 8; while (*display_desc) { *display_ptr++ = *display_desc++; display_ptr++; } /* Initialize the variables used for scrolling (mostly EGA/VGA) */ base = origin = video_mem_start = video_mem_base; term = video_mem_end = base + video_memory; scr_end = video_mem_start + video_num_lines * video_size_row; top = 0; bottom = video_num_lines; attr = 0x07; def_attr = 0x07; restate = state = ESnormal; checkin = 0; ques = 0; iscolor = 0; translate = NORM_TRANS; vc_cons[0].vc_bold_attr = -1; gotoxy(currcons,ORIG_X,ORIG_Y); NR_CONSOLES = 4;//add by sky for (currcons = 1; currcons<NR_CONSOLES; currcons++) { vc_cons[currcons] = vc_cons[0]; origin = video_mem_start = (base += video_memory); scr_end = origin + video_num_lines * video_size_row; video_mem_end = (term += video_memory); gotoxy(currcons,0,0); } update_screen(); set_trap_gate(0x21,&keyboard_interrupt); outb_p(inb_p(0x21)&0xfd,0x21); a=inb_p(0x61); outb_p(a|0x80,0x61); outb_p(a,0x61); } void update_screen(void) { set_origin(fg_console); set_cursor(fg_console); } /* from bsd-net-2: */ void sysbeepstop(void) { /* disable counter 2 */ outb(inb_p(0x61)&0xFC, 0x61); } int beepcount = 0; static void sysbeep(void) { /* enable counter 2 */ outb_p(inb_p(0x61)|3, 0x61); /* set command for counter 2, 2 byte write */ outb_p(0xB6, 0x43); /* send 0x637 for 750 HZ */ outb_p(0x37, 0x42); outb(0x06, 0x42); /* 1/8 second */ beepcount = HZ/8; } int do_screendump(int arg) { char *sptr, *buf = (char *)arg; int currcons, l; verify_area(buf,video_num_columns*video_num_lines); currcons = get_fs_byte(buf); if ((currcons<1) || (currcons>NR_CONSOLES)) return -EIO; currcons--; sptr = (char *) origin; for (l=video_num_lines*video_num_columns; l>0 ; l--) put_fs_byte(*sptr++,buf++); return(0); } void blank_screen() { if (video_type != VIDEO_TYPE_EGAC && video_type != VIDEO_TYPE_EGAM) return; /* blank here. I can't find out how to do it, though */ } void unblank_screen() { if (video_type != VIDEO_TYPE_EGAC && video_type != VIDEO_TYPE_EGAM) return; /* unblank here */ } void console_print(const char * b) { int currcons = fg_console; char c; while ( (c = *(b++)) ) { if (c == 10) { cr(currcons); lf(currcons); continue; } if (c == 13) { cr(currcons); continue; } if (x>=video_num_columns) { x -= video_num_columns; pos -= video_size_row; lf(currcons); } __asm__("movb %2,%%ah\n\t" "movw %%ax,%1\n\t" ::"a" (c), "m" (*(short *)pos), "m" (attr) :); pos += 2; x++; } set_cursor(currcons); }
2.0625
2
2024-11-18T18:55:54.799646+00:00
2017-11-27T19:58:10
f3198118b1dd4ee2b11d087e3b8b473685bb139b
{ "blob_id": "f3198118b1dd4ee2b11d087e3b8b473685bb139b", "branch_name": "refs/heads/master", "committer_date": "2017-11-27T19:58:10", "content_id": "dd597d4c8691c367d1d98538000c2e900ded70c9", "detected_licenses": [ "Unlicense" ], "directory_id": "3c7056772ad9ca625042cb18b88b05d760c43786", "extension": "h", "filename": "Fifo.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 112238419, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1586, "license": "Unlicense", "license_type": "permissive", "path": "/Fifo.h", "provenance": "stackv2-0040.json.gz:211482", "repo_name": "FredericoBalcao/queue_management", "revision_date": "2017-11-27T19:58:10", "revision_id": "e58e9584a2a980890852b862e5d644b5d495107f", "snapshot_id": "a578f4b203d5aa6b3e88ba693faa08f09e4746ba", "src_encoding": "ISO-8859-1", "star_events_count": 1, "url": "https://raw.githubusercontent.com/FredericoBalcao/queue_management/e58e9584a2a980890852b862e5d644b5d495107f/Fifo.h", "visit_date": "2021-08-20T00:26:46.277972" }
stackv2
//**************************************************************// // Engenharia Informática - Algoritmos e Estruturas de Dados // // Projeto - Gestão de Filas de Espero // // Data- 12/06/2015 // // Docente - Sérgio Correia // // Álvaro Benjamim - 16372 // // Frederico Balcão - 15307 // // Fifo.h // //**************************************************************// #ifndef FIFO_H_INCLUDED #define FIFO_H_INCLUDED #include <stdio.h> #include <time.h> #include "No.h" #include "Print.h" #include "Menus.h" /* Estrutura que representa uma FIFO */ typedef struct { No *primeiro; /* primeiro nó da fifo */ No *ultimo; /* último nó da fifo */ No *maior; /* nó com maior numero de senha nes a fifo */ } FIFO; FIFO *criar_fifo(); /* criar FIFO*/ void lista_fifo(FIFO*); /* lista FIFO*/ int empty_queue(FIFO*); /* verifica se a FIFO esta vazia*/ void ADD_FIFO(FIFO*, char); /* insere No a FIFO (normal)*/ void read_fifo(FIFO*); /* Apaga FIFO*/ void Transferir(FIFO*, FIFO*, char); /* Transfere de uma FIFO para outra FIFO*/ void ADDFIFO1(FIFO *, char ); /* insere No a FIFO (prioritária)*/ FIFO *FIFOA; FIFO *FIFOB; FIFO *FIFOC; FIFO *FIFOD; #endif // FIFO_H_INCLUDED
2.484375
2
2024-11-18T18:55:55.437064+00:00
2019-02-10T07:48:48
28a585a39b10926cdaee0c49a00e03fa78255efd
{ "blob_id": "28a585a39b10926cdaee0c49a00e03fa78255efd", "branch_name": "refs/heads/master", "committer_date": "2019-02-10T07:48:48", "content_id": "964826862efe2e04d8da25dd973b0a44cfdc937f", "detected_licenses": [ "MIT" ], "directory_id": "d09dba3a902a1d578c5225362bdcf5eaf2ba1bb0", "extension": "h", "filename": "fonts.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 169951488, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2834, "license": "MIT", "license_type": "permissive", "path": "/Fonts/fonts.h", "provenance": "stackv2-0040.json.gz:211742", "repo_name": "iharuspex/1.54inch_epaper", "revision_date": "2019-02-10T07:48:48", "revision_id": "46c14c1e33dbdb74f1ba54547bff7b03621cbd42", "snapshot_id": "6239597d865cc62918fe1db63e79b8530a3a97b5", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/iharuspex/1.54inch_epaper/46c14c1e33dbdb74f1ba54547bff7b03621cbd42/Fonts/fonts.h", "visit_date": "2020-04-21T23:36:07.135017" }
stackv2
/** * | File : fonts.h * | Author : Artem Paraev (iharuspex) * | Function : Font definitions * Copyright (c) 2019 Artem Paraev * 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. **/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __FONTS_H #define __FONTS_H /* (32x41) */ #define MAX_HEIGHT_FONT 41 #define MAX_WIDTH_FONT 32 #define OFFSET_BITMAP #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include <stdint.h> //ASCII #define CHAR_WIDTH(c) Font->FontTable[(c) - Font->FirstChar].width // Get char width #define CHAR_START_INDEX(c) Font->FontTable[(c) - Font->FirstChar].start // Get start char's index #define CHAR_DATA(c) &Font->FontBitmaps[CHAR_START_INDEX(c)] // Get char's data #define CHAR_SPACE 2 // Get space between chars typedef struct FontTable { uint16_t width; // Char width uint16_t start; // First char's byte index } FONT_CHAR_INFO; typedef struct { uint8_t Height; // Char height uint8_t FirstChar; // First char's index uint8_t LastChar; // Last char's index //uint8_t FontSpace; // Space between chars const FONT_CHAR_INFO *FontTable; // Fonts descriptor const uint8_t *FontBitmaps; // Fonts array } FONT_INFO; extern FONT_INFO comfortaa_14ptFontInfo1; #ifdef __cplusplus } #endif #endif /* __FONTS_H */
2.015625
2
2024-11-18T18:55:55.631636+00:00
2017-11-08T08:19:45
be9a71ccbc8b197de4a4c0381930e779ee731f6a
{ "blob_id": "be9a71ccbc8b197de4a4c0381930e779ee731f6a", "branch_name": "refs/heads/master", "committer_date": "2017-11-08T08:19:45", "content_id": "89563afbf4af2fd6a440efb4b17eff61ef625f73", "detected_licenses": [ "MIT" ], "directory_id": "85ff6d904816330d520dd55798d20925c0f86e3d", "extension": "c", "filename": "colaestatica.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 90580981, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2185, "license": "MIT", "license_type": "permissive", "path": "/p5/e1/colaestatica.c", "provenance": "stackv2-0040.json.gz:212000", "repo_name": "jhm-ciberman/progra2-unmdp", "revision_date": "2017-11-08T08:19:45", "revision_id": "996024ef8a3689997ecb4f48aa589a3b139a8cc7", "snapshot_id": "651a5147f3936d5c61acf23771cea118a0fe8643", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jhm-ciberman/progra2-unmdp/996024ef8a3689997ecb4f48aa589a3b139a8cc7/p5/e1/colaestatica.c", "visit_date": "2021-08-07T13:53:59.997232" }
stackv2
#include "colaestatica.h" #include <assert.h> /* |------------------------------------------------------ | IMPLEMENTACION |------------------------------------------------------ */ void colae_inicia(Colae* cola) { cola->primero = -1; cola->ultimo = -1; } void colae_pone(Colae* cola, ColaeDato dato){ if (cola->ultimo <= COLAE_MAX) { cola->datos[++(cola->ultimo)] = dato; if (cola->primero == -1) cola->primero = 0; } } void colae_saca(Colae* cola, ColaeDato* dato) { if (cola->primero != -1) { *dato = cola->datos[cola->primero++]; if (cola->primero > cola->ultimo) { cola->primero = -1; cola->ultimo = -1; } } } ColaeDato colae_consulta(Colae cola) { if (cola.primero != -1) return cola.datos[cola.primero]; } int colae_vacia(Colae cola) { return (cola.primero == -1); } /* |------------------------------------------------------ | TESTS |------------------------------------------------------ */ static void _test_vacia_debe_indicar_si_la_pila_esta_vacia() { Colae c; int d; colae_inicia(&c); assert(colae_vacia(c) == 1); colae_pone(&c, 10); assert(colae_vacia(c) == 0); colae_saca(&c, &d); assert(colae_vacia(c) == 1); } static void _test_pone_y_saca_deben_permitir_poner_y_sacar_elementos() { Colae c; int d1, d2, d3; colae_inicia(&c); colae_pone(&c, 10); colae_pone(&c, 11); colae_pone(&c, 12); colae_saca(&c, &d1); colae_saca(&c, &d2); colae_saca(&c, &d3); assert(d1 == 10); assert(d2 == 11); assert(d3 == 12); assert(colae_vacia(c) == 1); } static void _test_consulta_debe_permitir_consultar_un_elemento_sin_sacarlo() { Colae c; int d; colae_inicia(&c); colae_pone(&c, 10); colae_pone(&c, 12); assert(colae_consulta(c) == 10); colae_saca(&c, &d); assert(d == 10); colae_saca(&c, &d); assert(d == 12); } void colae_tests() { _test_vacia_debe_indicar_si_la_pila_esta_vacia(); _test_pone_y_saca_deben_permitir_poner_y_sacar_elementos(); _test_consulta_debe_permitir_consultar_un_elemento_sin_sacarlo(); }
2.828125
3
2024-11-18T21:00:52.168593+00:00
2018-09-18T22:25:19
e7423c589bd86dda59a1a8b187c3ecdf87d990cd
{ "blob_id": "e7423c589bd86dda59a1a8b187c3ecdf87d990cd", "branch_name": "refs/heads/master", "committer_date": "2018-09-18T22:25:19", "content_id": "15f15694f1dacd0c7722350c2c11de4d79fdca66", "detected_licenses": [ "MIT" ], "directory_id": "f7995d57c3b73087cfced628ef26266cab4ac0fe", "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": 149359257, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10335, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0045.json.gz:236780", "repo_name": "shinobisoft/eolcvt", "revision_date": "2018-09-18T22:25:19", "revision_id": "d1c1a2a89b6b9545f0d53d63724e8be91249921a", "snapshot_id": "dbcab244199b9c362145e0c8fbaf1685ffb4e10c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/shinobisoft/eolcvt/d1c1a2a89b6b9545f0d53d63724e8be91249921a/main.c", "visit_date": "2020-03-29T00:51:18.926280" }
stackv2
#include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "main.h" // COMMAND-LINE FLAGS // -b Make backup // -h, --help Help // -i Input file // -o Output file // -t Test -> determine current line ending scheme char* src; char* dst; char* tmpName; int backup = 0; int test = 0; ///////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////// int main( int argc, char** argv ) { if( argc == 1 ) return showUsage(); else if( argc == 2 ) { if( !strcmp( argv[ 1 ], "-h" ) || !strcmp( argv[ 1 ], "--help" ) ) return showUsage(); } long srcSize = 0; int err = 0; int lineType = 0; // 1 == Unix( \n ), 2 == Windows( \r\n ) int linesOut = 0; int lineFeeds = 0; int elms = 0; FILE* fIn, *fOut; char* buf = NULL; struct stat att; parseArgs( argc, argv ); if( src == NULL ) return -1; // Determine the size of the source file if( ( err = stat( src, &att ) ) == 0 ) { srcSize = att.st_size; } else { // most likely, the file doesn't exist printf( "%s\n", strerror( err ) ); return err; } // First make backup copy of src if( backup ) { tmpName = (char*)malloc( strlen( src )+5 ); strcpy( tmpName, src ); tmpName = strcat( tmpName, ".bak" ); printf( "Backing up %s...\nSaving as %s...\n", src, tmpName ); sprintf( buf, "cp %s %s", src, tmpName ); if( !system( buf ) ) puts( "Backup complete!" ); } // Now read the contents of src in to a buffer... buf = (char*)malloc( srcSize+1 ); int nRead = 0; fIn = fopen( src, "r" ); nRead = fread( &buf[ 0 ], 1, srcSize, fIn ); fclose( fIn ); if( nRead != srcSize ) { printf( "[ERROR] Unknown error occurred reading %s.\nAborting.\n", src ); return -1; } buf[ srcSize ] = '\0'; lineFeeds = getLFCount( buf ); lineType = getLEType( buf ); if( test ) { if( lineType ) { if( lineType == 1 ) puts( "UnixEOL" ); else if( lineType == 2 ) puts( "WindowsEOL" ); err = 0; } else { puts( "Unknown error." ); puts( "Unable to determine EOL scheme! \'src\' is either empty" ); puts( "or it simply doesn\'t contain any EOL characters." ); err = -1; } return err; } puts( "Starting conversion process..." ); if( lineType ) { if( lineType == 1 ) puts( "* Unix -> Windows..." ); else if( lineType == 2 ) puts( "* Windows -> Unix..." ); } else { puts( "* ERROR Unable to determine line ending scheme!" ); goto bail; } char* leUnix = "\n"; char* leWin = "\r\n"; char* p = NULL; char** lineBuf = splitLines( buf, &elms ); char* out = NULL; out = (dst != NULL) ? dst : src; if( lineBuf != NULL ) { fOut = fopen( out, "w" ); if( fOut != NULL && lineFeeds ) { while( linesOut < lineFeeds ) { p = lineBuf[ linesOut ]; if( p != NULL && *p != '\0' ) { // Only write if there is actual content to write... fwrite( p, 1, strlen( p ), fOut ); } // If p == NULL, this would indicate an empty line in // the source file... if( lineType == 1 ) { // Unix to Windows fwrite( leWin, 1, 2, fOut ); linesOut++; } else if( lineType == 2 ) { // Windows to Unix fwrite( leUnix, 1, 1, fOut ); linesOut++; } } fclose( fOut ); } } bail: if( linesOut == lineFeeds && err == 0 ) { puts( "Line endings converted successfully." ); } else if( err != 0 ){ puts( "ERROR: An unknown error has occurred." ); printf( "You can restore %s from\nit\'s backup file %s\n", src, tmpName ); } return err; } ///////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////// /** * Function to determine what EOL scheme is being used by a text file. * @param s Buffer containing the contents of a text file * @return Returns 0 on failure, 1 for Unix, 2 for Windows */ int getLEType( const char* s ) { if( s == NULL || *s == '\0') { #ifdef _DEBUG printf( "[DEBUG] %s() ERROR: \'s\' is NULL\n", __FUNCTION__ ); #endif // _DEBUG return -1; } int i = (int)strlen( s )-1; int t = 0; char chLast; for( ; i >= 0; i-- ) { chLast = (int)s[ i ]; if( chLast == 10 ) { // \n if( i > 0 ) { i--; if( (int)s[ i ] == 13 ) // \r t = 2; else t = 1; break; } else { t = 1; break; } } } return t; } ///////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////// /** * Function to get the number of EOL characters within a text file * @param s1 Buffer containing the contents of a text file * @return Returns the number of EOLs detected on success, 0 on failure. */ int getLFCount( const char* s1 ) { int lf = 0; if( s1 != NULL && *s1 != '\0' ) { int len = strlen( s1 ); int p = 0; for( ; p < len; p++ ) { if( s1[ p ] == '\n' ) lf++; } } return lf; } ///////////////////////////////////////////////////////////////////// // Utility function to split a string buffer in to lines. This works // for both line ending styles. The function strips line endings from // the source. ///////////////////////////////////////////////////////////////////// char** splitLines( char* src, int* elements ) { char** buffer = NULL; int lfType = getLEType( src ); int iter = 0; if( lfType ) { int lines = getLFCount( src ); if( lines ) { buffer = (char**)calloc( lines+8, sizeof( char* ) ); char buf[ 4096 ] = { "\0" }; int pos = 0; int l = strlen( src ); char ch; int items = 0; while( iter < l ) { ch = src[ iter ]; if( ch == '\r' || ch == '\n' ) { // Delimiter. NULL terminate buf and add to buffer if( *buf != '\0' ) { buf[ pos ] = '\0'; buffer[ items ] = (char*)realloc( buffer[ items ], strlen( buf )+1 ); strcpy( buffer[ items ], buf ); buf[ 0 ] = 0; pos = 0; items++; } } else { buf[ pos ] = ch; pos++; } if( iter+1 == l && *buf != '\0' ) { buf[ pos ] = '\0'; buffer[ items ] = (char*)realloc( buffer[ items ], strlen( buf )+1 ); strcpy( buffer[ items ], buf ); items++; break; } iter++; } } if( elements != NULL ) *elements = lines; } return buffer; } ///////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////// int showUsage() { puts( "/////////////////////////////////////////////////////////////////////" ); puts( "// eolcvt " ); puts( "// Copyright \u00A9 2018 ShinobiSoft Software" ); puts( "/////////////////////////////////////////////////////////////////////" ); puts( "" ); puts( "eolcvt is a simple EOL conversion utility designed to easily swap" ); puts( "EOL characters between Unix line endings and Windows line endings." ); puts( "eolcvt detects the line endings currently in use by an input file" ); puts( "and will automatically convert to the other format." ); puts( "" ); puts( "USAGE: eolcvt -b -i <somefile.txt> -o <somefile2.txt>" ); puts( " OR: eolcvt -i <somefile.txt>" ); puts( " OR: eolcvt -t <somefile.txt>\n" ); puts( " -b\tMake a backup of the input file before conversion" ); puts( " -h\tShows this screen. ( also --help )" ); puts( " -i\tSpecifies the input file" ); puts( " -o\tSpecifies the output file ( Optional )" ); puts( " -t\tTest the input file. Prints current EOL scheme used." ); puts( " \tThis will print UnixEOL or WindowsEOL. This flag will also" ); puts( " \toverride any other flags on the command-line." ); puts( "" ); puts( "NOTE:" ); puts( "Flags CANNOT be combined in to a single flag ( ie: -bio ). They MUST" ); puts( "be used as specified above." ); puts( "" ); return 0; } ///////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////// /** * Simple function for parsing command-line arguments and setting * initial values for some global variables. */ void parseArgs( int argc, char** argv ) { int iter = 1; char* p; while( iter < argc ) { p = argv[ iter ]; if( p[ 0 ] == '-' ) { switch( p[ 1 ] ) { case 'b': { backup = 1; break; } case 'i': { if( src == NULL ) src = argv[ ++iter ]; break; } case 'o': { dst = argv[ ++iter ]; break; } case 't': { test = 1; src = argv[ ++iter ]; break; } } } iter++; } }
2.5625
3
2024-11-18T21:00:52.931578+00:00
2013-12-23T19:39:25
067eaf9818eda13bfd84ad5b45e02d7773551aa8
{ "blob_id": "067eaf9818eda13bfd84ad5b45e02d7773551aa8", "branch_name": "refs/heads/master", "committer_date": "2013-12-23T19:39:25", "content_id": "8692b43f5fe3ac4b162bbe77d4cd08fa8ba3f7ff", "detected_licenses": [ "MIT" ], "directory_id": "6d129d89600c17f3fe6bfe692b7708c00a796217", "extension": "c", "filename": "server.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": 2340, "license": "MIT", "license_type": "permissive", "path": "/tp5b/archivos/server.c", "provenance": "stackv2-0045.json.gz:236908", "repo_name": "mostror/Projects-ComputacionII", "revision_date": "2013-12-23T19:39:25", "revision_id": "f5cf7a58ba142e120952d05c097cf46de76d65e3", "snapshot_id": "2f48100cec1340f70f35e0cb6d8d93aa238bf42d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mostror/Projects-ComputacionII/f5cf7a58ba142e120952d05c097cf46de76d65e3/tp5b/archivos/server.c", "visit_date": "2016-09-06T13:37:59.098636" }
stackv2
#include "mostronet.h" #define REQUESTS 5 int main(int argc, char ** argv){ signal (SIGCHLD,SIG_IGN); int sd, csd ,leido, opcion, confd=0, reqs = 0, flag4=0, flag6=0; char buffer[1000]; struct sockaddr_in dir = {}; serverData config; while ((opcion = getopt(argc, argv, "hf:46") ) >= 0) { switch(opcion) { case 'h': write(STDOUT_FILENO, "Usage: hist [OPTION...]\n -h, show this help and exit\n -a <ppm-file>, use ppm-file file\n -c <rojo/verde/azul>, show only the result for selected colour\n -o <file-name>, create a file named file-name and stores the results\n", 249); return 0; break; case 'f': if ((confd = open(optarg, O_RDONLY)) == -1) { perror("open"); return -3; } if (setConfig(confd, &config) < 0) return -1; break; case '4': if (flag6 == 1) { printf("Options 4 & 6 called. Please, call only one, or none\n"); return -2; } else { flag4=1; } break; case '6': if (flag4 == 1) { printf("Options 4 & 6 called. Please, call only one, or none\n"); return -2; } else { flag6=1; } break; case '?': write(STDERR_FILENO, "Missing file configuration path, default used\n", 46); break; } } if (confd == 0){ if ((confd = open("tp3.conf", O_RDONLY)) == -1) { perror("open"); return -1; } if (setConfig(confd, &config) < 0 ) return -1; } sd = socket(AF_INET,SOCK_STREAM,0); if (sd < 0){ perror ("socket"); return -1; } dir.sin_family = AF_INET; dir.sin_port = htons(atoi(config.port)); printf("puerto: %d\nruta: %s", atoi(config.port), config.droot); inet_pton(AF_INET, "0.0.0.0", &dir.sin_addr); if (bind(sd , (struct sockaddr *)&dir , sizeof dir) < 0 ){ perror ("bind"); return -1; } listen(sd,10); printf("Server running, waiting for clients\n"); while ((csd = accept(sd,NULL,NULL)) > 0) { switch (fork()){ case 0: printf("New incoming client\n"); while ((leido = read (csd,buffer,sizeof buffer)) > 0){ buffer[leido]=0; printf ("leido %s\n",buffer); write(csd,buffer,leido); if (++reqs == REQUESTS) { write(csd, "Requests depleted\n", 5 ); shutdown(csd, SHUT_RDWR); } } return 0; //del hijo } } close (csd); return 0; }
2.296875
2
2024-11-18T21:00:53.019462+00:00
2023-02-16T11:27:40
13f538526ba891247d7c7d1617ecf1ba1697d4e7
{ "blob_id": "13f538526ba891247d7c7d1617ecf1ba1697d4e7", "branch_name": "refs/heads/main", "committer_date": "2023-02-16T14:59:16", "content_id": "f640e42b799a6ad4da5c7f3a4ffb75857549ce01", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493", "extension": "c", "filename": "disk_access.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": 3978, "license": "Apache-2.0", "license_type": "permissive", "path": "/subsys/disk/disk_access.c", "provenance": "stackv2-0045.json.gz:237038", "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/subsys/disk/disk_access.c", "visit_date": "2023-09-04T00:20:35.217393" }
stackv2
/* * Copyright (c) 2018 Intel Corporation. * * SPDX-License-Identifier: Apache-2.0 */ #include <string.h> #include <zephyr/types.h> #include <zephyr/sys/__assert.h> #include <zephyr/sys/util.h> #include <zephyr/init.h> #include <zephyr/storage/disk_access.h> #include <errno.h> #include <zephyr/device.h> #define LOG_LEVEL CONFIG_DISK_LOG_LEVEL #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(disk); /* list of mounted file systems */ static sys_dlist_t disk_access_list; /* lock to protect storage layer registration */ static struct k_mutex mutex; struct disk_info *disk_access_get_di(const char *name) { struct disk_info *disk = NULL, *itr; size_t name_len = strlen(name); sys_dnode_t *node; k_mutex_lock(&mutex, K_FOREVER); SYS_DLIST_FOR_EACH_NODE(&disk_access_list, node) { itr = CONTAINER_OF(node, struct disk_info, node); /* * Move to next node if mount point length is * shorter than longest_match match or if path * name is shorter than the mount point name. */ if (strlen(itr->name) != name_len) { continue; } /* Check for disk name match */ if (strncmp(name, itr->name, name_len) == 0) { disk = itr; break; } } k_mutex_unlock(&mutex); return disk; } int disk_access_init(const char *pdrv) { struct disk_info *disk = disk_access_get_di(pdrv); int rc = -EINVAL; if ((disk != NULL) && (disk->ops != NULL) && (disk->ops->init != NULL)) { rc = disk->ops->init(disk); } return rc; } int disk_access_status(const char *pdrv) { struct disk_info *disk = disk_access_get_di(pdrv); int rc = -EINVAL; if ((disk != NULL) && (disk->ops != NULL) && (disk->ops->status != NULL)) { rc = disk->ops->status(disk); } return rc; } int disk_access_read(const char *pdrv, uint8_t *data_buf, uint32_t start_sector, uint32_t num_sector) { struct disk_info *disk = disk_access_get_di(pdrv); int rc = -EINVAL; if ((disk != NULL) && (disk->ops != NULL) && (disk->ops->read != NULL)) { rc = disk->ops->read(disk, data_buf, start_sector, num_sector); } return rc; } int disk_access_write(const char *pdrv, const uint8_t *data_buf, uint32_t start_sector, uint32_t num_sector) { struct disk_info *disk = disk_access_get_di(pdrv); int rc = -EINVAL; if ((disk != NULL) && (disk->ops != NULL) && (disk->ops->write != NULL)) { rc = disk->ops->write(disk, data_buf, start_sector, num_sector); } return rc; } int disk_access_ioctl(const char *pdrv, uint8_t cmd, void *buf) { struct disk_info *disk = disk_access_get_di(pdrv); int rc = -EINVAL; if ((disk != NULL) && (disk->ops != NULL) && (disk->ops->ioctl != NULL)) { rc = disk->ops->ioctl(disk, cmd, buf); } return rc; } int disk_access_register(struct disk_info *disk) { int rc = 0; k_mutex_lock(&mutex, K_FOREVER); if ((disk == NULL) || (disk->name == NULL)) { LOG_ERR("invalid disk interface!!"); rc = -EINVAL; goto reg_err; } if (disk_access_get_di(disk->name) != NULL) { LOG_ERR("disk interface already registered!!"); rc = -EINVAL; goto reg_err; } /* append to the disk list */ sys_dlist_append(&disk_access_list, &disk->node); LOG_DBG("disk interface(%s) registered", disk->name); reg_err: k_mutex_unlock(&mutex); return rc; } int disk_access_unregister(struct disk_info *disk) { int rc = 0; k_mutex_lock(&mutex, K_FOREVER); if ((disk == NULL) || (disk->name == NULL)) { LOG_ERR("invalid disk interface!!"); rc = -EINVAL; goto unreg_err; } if (disk_access_get_di(disk->name) == NULL) { LOG_ERR("disk interface not registered!!"); rc = -EINVAL; goto unreg_err; } /* remove disk node from the list */ sys_dlist_remove(&disk->node); LOG_DBG("disk interface(%s) unregistered", disk->name); unreg_err: k_mutex_unlock(&mutex); return rc; } static int disk_init(const struct device *dev) { ARG_UNUSED(dev); k_mutex_init(&mutex); sys_dlist_init(&disk_access_list); return 0; } SYS_INIT(disk_init, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
2.4375
2
2024-11-18T21:00:53.074565+00:00
2015-11-25T18:38:25
5860a1e1d6c9f2b02f41299602257ae8c6d9785a
{ "blob_id": "5860a1e1d6c9f2b02f41299602257ae8c6d9785a", "branch_name": "refs/heads/master", "committer_date": "2015-11-25T18:38:25", "content_id": "277b95f8f8de4015978be5fc7419ca510710b3e3", "detected_licenses": [ "MIT" ], "directory_id": "7d1103e4efd710e1a385f830549c4dfaa202d8c4", "extension": "c", "filename": "slicemap.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 46874150, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5457, "license": "MIT", "license_type": "permissive", "path": "/daq/orbcomm_software/muon/dataAnalysis/slicemap.c", "provenance": "stackv2-0045.json.gz:237167", "repo_name": "abrahamneben/orbcomm_beam_mapping", "revision_date": "2015-11-25T18:38:25", "revision_id": "71b3e7d6e4214db0a6f4e68ebeeb7d7f846f5004", "snapshot_id": "b7e4b83647f615f90d0a3606b21eb689770a4c98", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/abrahamneben/orbcomm_beam_mapping/71b3e7d6e4214db0a6f4e68ebeeb7d7f846f5004/daq/orbcomm_software/muon/dataAnalysis/slicemap.c", "visit_date": "2021-01-10T14:47:43.187719" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include <math.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <signal.h> #include <errno.h> #include <arpa/inet.h> #include "dask.h" #include "conio.h" #include "cpgplot.h" #include <fftw3.h> #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 : sqrarg*sqrarg) struct Acquisition { struct { char wkday[128]; char month[128]; char dateX[128]; char utime[128]; char year[128]; } UT; struct Satellite { int ALH; float az; float el; float range; } Sat[40]; float bin[260]; } acqdata[51000]; struct PassInfo { int sat_id; int start_acq; int stop_acq; int peak_bin; } pass[25]; //prototypes int plot_map(void); int write_map(void); int read_map(void); int read_data(void); int read_pass_file(void); int test_data(void); int plot_voltage_at_elevation(void); //Variable Declarations FILE *fp; FILE *fpass; FILE *fmapx; FILE *ipass; char *scans="includepass"; char powerfile[30]; char passfile[30]; char mapfile[30]="BeamMapGroupD"; char *prefix="pass"; char *p; char powerfilename[30]; int Pindex; int Ptotal; int pg_id,pg_2; char acq[15]; int i,jj,b; char timemark[3]; char voltmark[20]; char satname[10]; int satnum=0; int acqcount=0; int numofacqs=50000; int viewstep=3000; // float f[129600]; float f[3240000]; float mapx[40][3601][901]; int azindex, elindex; int sat_choice=0; float altitude=800; //km float elev=0; float fmin=1, fmax=0; float mapplot[720][180]; //******************************************************** int main(void) { read_map(); pg_id = cpgopen("/XSERVE"); pg_2 = cpgopen("/XSERVE"); sat_choice=0; plot_map(); while ((elev <=90)&(elev>=0)) { printf("\nElevation: "); scanf("%f", &elev); if ((elev <=90)&(elev>=0)) plot_voltage_at_elevation(); } printf("End of Program\n"); return 0; } //******************************************************** int read_map() { int az_i, el_i; if ((fmapx=fopen(mapfile,"r"))==NULL) { printf("Cannot open file. \n"); exit(1); } printf("\nReading map file: %s\n", mapfile); for (azindex=0; azindex<3600; azindex++) { for (elindex=0; elindex<900; elindex++) { fscanf(fmapx,"%i",&az_i); fscanf(fmapx,"%i",&el_i); fscanf(fmapx,"%f\n",&mapx[sat_choice][az_i][el_i]); } } printf("Map file: %s read.\n", mapfile); return 0; } //******************************************************** int plot_map() { int nx=720; int ny=180; int deli, delj; float value; int counter; int i=0, j=0, k=0; float tr[6]= {0.0, 0.5, 0.0, 0.0, 0.0, 0.5}; // float RL[9]={-0.5, 0.004, 0.006, 0.008, 0.02, 0.04, 0.06, 0.08, 0.1}; float RL[9]={-0.5, 0.0, 0.04, 0.08, 0.2, 0.4, 0.6, 0.8, 1.0}; float RR[9]={0.0, 0.0, 0.0, 0.0, 0.6, 1.0, 1.0, 1.0, 1.0}; float RG[9]={0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.6, 1.1, 1.0}; float RB[9]={0.0, 0.3, 0.8, 1.0, 0.3, 0.0, 0.0, 0.0, 1.0}; float bright=0.5; //0.53 float contra=1.0; //1.0 //map larger array into smaller array for (j=1; j<ny; j++) { for (i=1; i<nx; i++) { value=0; counter=0; for (deli=0; deli<=5; deli++) { for (delj=0; delj<=5; delj++) { value=value+mapx[sat_choice][(5*i)+deli][(5*j)+delj]; if (mapx[sat_choice][(5*i)+deli][(5*j)+delj]>0) { counter++; // printf("%i %f\n", counter, value/counter); } } } if (counter==0) mapplot[i][j]=value; else mapplot[i][j]=value/counter; } } for (j=1; j<ny; j++) { for (i=1; i<nx; i++) { k=(j-1)*nx + (i-1); f[k]=mapplot[i][j]; if (f[k] <fmin) fmin = f[k]; if (f[k] >fmax) fmax = f[k]; } } printf("min=%f max=%f\n", fmin, fmax); fmax=0.08; cpgslct(pg_id); cpgeras(); cpgenv(0.0, 360, 0.0, 90, 1.0, -2); cpglab("Azimuth", "Elevation", "Antenna Power Pattern: Sleeved Dipole [Data: May 7-22, 2006]"); cpgctab(RL, RR, RG, RB, 9, contra, bright); cpgimag(f, (float)nx, (float)ny, 1.0, (float)nx, 1.0, (float)ny, fmin, fmax, tr); cpgbox("BCNST1",0.0,0,"BCNST1",0.0,0); return 0; } //******************************************************** int plot_voltage_at_elevation() { int az_i, el_i; char textlineA[12]="Elevation: "; char textlineB[6]=" deg."; char elevC[10]; float ppdb=0; az_i=0; // el_i=(int)elev*10; el_i=(int)elev*2; printf("\nplotting ..."); cpgslct(pg_2); cpgsci(3); cpgeras(); cpgsvp(0.15f, 0.95f, 0.2f, 0.8f); cpgupdt(); cpgsch(2.0); // cpgswin(0, 360, 0.000f, 0.07f); cpgswin(0, 360, -50.0f, 10.0f); cpgbox("BC1NST",0.0,0,"BCNST",0.0,0); // cpglab("Azimuth [Degrees]", "Voltage [volts]", "Antenna Measurement"); cpglab("Azimuth [Degrees]", "Rel Power [dB]", "Antenna Measurement"); // cpgmove((float)az_i/10, mapx[sat_choice][az_i][el_i]); // for (az_i=1; az_i<=3600; az_i++) // { // cpgpt1((float)az_i/10, mapx[sat_choice][az_i][el_i],-1); // } //for (az_i=0; az_i<=3600; az_i++) // { // ppdb=20*log(mapx[sat_choice][az_i][el_i]/0.045); // cpgpt1((float)az_i/10, ppdb, -2); // } for (az_i=0; az_i<=720; az_i++) { ppdb=20*log(mapplot[az_i][el_i]/0.045); cpgpt1((float)az_i/2, ppdb, -2); } sprintf(elevC,"%i",(int)elev); strcat(textlineA,elevC); strcat(textlineA,textlineB); cpgtext (200,0.0, textlineA); return 0; }
2.140625
2
2024-11-18T21:00:53.152283+00:00
2022-10-27T18:04:06
427fdc833ac77ddeb7c9fa12197e6f0ac431ea00
{ "blob_id": "427fdc833ac77ddeb7c9fa12197e6f0ac431ea00", "branch_name": "refs/heads/master", "committer_date": "2022-10-27T18:04:06", "content_id": "a0579c4221c9d9d2cf24b9057bcc99daed48e31a", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e632e9d2b1e37a95cce8983bb27177e188492bd7", "extension": "c", "filename": "bt_specfn_minmax.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 266549697, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 721, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/old/solvers/smurf/fn_minmax/bt_specfn_minmax.c", "provenance": "stackv2-0045.json.gz:237298", "repo_name": "weaversa/sbsat", "revision_date": "2022-10-27T18:04:06", "revision_id": "4fa840237b78a18a2f0ad2a3568ca0c4a5656062", "snapshot_id": "fc46413b7b3c564484a8c41d94fab49100060514", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/weaversa/sbsat/4fa840237b78a18a2f0ad2a3568ca0c4a5656062/old/solvers/smurf/fn_minmax/bt_specfn_minmax.c", "visit_date": "2022-11-09T13:58:08.056684" }
stackv2
#include "sbsat.h" #include "sbsat_solvers.h" #include "solver.h" void SetMINMAXStateVisitedFlag(TypeStateEntry *pTypeState) { MINMAXStateEntry *pMINMAXState = (MINMAXStateEntry *)pTypeState; assert(pMINMAXState->type == FN_MINMAX); if(pMINMAXState->visited==0) { pMINMAXState->visited = 1; } } void UnsetMINMAXStateVisitedFlag(TypeStateEntry *pTypeState) { MINMAXStateEntry *pMINMAXState = (MINMAXStateEntry *)pTypeState; assert(pMINMAXState->type == FN_MINMAX); if(pMINMAXState->visited==1) { pMINMAXState->visited = 0; } } void CleanUpMINMAXState(TypeStateEntry *pTypeState) { MINMAXStateEntry *pMINMAXState = (MINMAXStateEntry *)pTypeState; assert(pMINMAXState->type == FN_MINMAX); }
2.140625
2
2024-11-18T18:45:31.719315+00:00
2020-11-12T01:40:48
03be481ff829fc3066855944cb1b04d7d104d142
{ "blob_id": "03be481ff829fc3066855944cb1b04d7d104d142", "branch_name": "refs/heads/master", "committer_date": "2020-11-12T01:40:48", "content_id": "a58e9cb898ef88c927efa94c02c9b6b8fa5d2a0d", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "57eba9063c7e90877207c3ccff9316ccd4ef2527", "extension": "c", "filename": "sleep.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": 640, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/Snobol/snobol4/snobol4-2.0/modules/time/posix/sleep.c", "provenance": "stackv2-0046.json.gz:34714", "repo_name": "rigidus/uexp", "revision_date": "2020-11-12T01:40:48", "revision_id": "81c8e6f1997c5eddf09abb62a6e10ded11218ae3", "snapshot_id": "7f34136fa3b9e806ae26a8e08492568dca9b77cf", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rigidus/uexp/81c8e6f1997c5eddf09abb62a6e10ded11218ae3/Snobol/snobol4/snobol4-2.0/modules/time/posix/sleep.c", "visit_date": "2023-01-11T02:31:53.470831" }
stackv2
/* * test: * cc -o sleep sleep.c -I../../include -DTEST */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> /* NULL, FILE */ #include <time.h> #include "snotypes.h" #include "h.h" #include "lib.h" int sleepf(real_t t) { struct timespec ts; ts.tv_sec = (int) t; /* 5e-10 + 5e-10 < 1e-9 !! */ ts.tv_nsec = (t - ts.tv_sec + 0.000000000501) * 1000000000; #ifdef TEST printf("%e => %d %d\n", t, ts.tv_sec, ts.tv_nsec); #endif if (!ts.tv_sec && !ts.tv_nsec) return 0; return nanosleep(&ts, NULL); } #ifdef TEST main() { sleepf(0.0000000005); sleepf(0.5); sleepf(10); } #endif
2.65625
3
2024-11-18T18:45:31.877597+00:00
2020-10-01T20:27:52
495e7601f97f0263625654b5b5a4347bc7f17f0c
{ "blob_id": "495e7601f97f0263625654b5b5a4347bc7f17f0c", "branch_name": "refs/heads/master", "committer_date": "2020-10-01T20:27:52", "content_id": "1aab99e067e2cc84b12dfcda6f5567e86525dfae", "detected_licenses": [ "MIT" ], "directory_id": "f4752ed453ae2b0758a4b3dd32bde1f149790c72", "extension": "c", "filename": "40.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 286571280, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 644, "license": "MIT", "license_type": "permissive", "path": "/C - Condicional/Afonso/40.c", "provenance": "stackv2-0046.json.gz:34971", "repo_name": "alisson09/Exercicios-em-linguagem-c", "revision_date": "2020-10-01T20:27:52", "revision_id": "aa152a0650065ea3571c5377eb80e04178565672", "snapshot_id": "30117d21e4ba4648372710fb63b7a1f2eb77b611", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alisson09/Exercicios-em-linguagem-c/aa152a0650065ea3571c5377eb80e04178565672/C - Condicional/Afonso/40.c", "visit_date": "2023-07-09T08:25:55.422316" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argc, char const *argv[]) { float custoFabrica,custoConsumidor; printf("Custo de Fabrica: "); scanf("%f",&custoFabrica); if (custoFabrica<12000) { custoConsumidor = custoFabrica + (custoFabrica*0.05); } else if (custoFabrica>=12000 && custoFabrica<=25000) { custoConsumidor = custoFabrica + (custoFabrica*0.10) + (custoFabrica*0.15); } else { custoConsumidor = custoFabrica + (custoFabrica*0.15) + (custoFabrica*0.20); } printf("Custo do Consumidor: %0.2f",custoConsumidor); return 0; }
3.015625
3
2024-11-18T18:45:31.932574+00:00
2017-11-18T21:09:28
400094a172d1118320c000f4600a36d85c963406
{ "blob_id": "400094a172d1118320c000f4600a36d85c963406", "branch_name": "refs/heads/master", "committer_date": "2017-11-18T21:09:28", "content_id": "ff26579dc02153cf43261df5f682253db7a713dc", "detected_licenses": [ "MIT" ], "directory_id": "e1ae491f91ccad5d709802a367170661563d7dde", "extension": "c", "filename": "example.c", "fork_events_count": 0, "gha_created_at": "2017-01-21T17:40:04", "gha_event_created_at": "2017-11-18T21:09:29", "gha_language": "C", "gha_license_id": null, "github_id": 79661585, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2214, "license": "MIT", "license_type": "permissive", "path": "/example/example.c", "provenance": "stackv2-0046.json.gz:35099", "repo_name": "GeorgeGkas/slog", "revision_date": "2017-11-18T21:09:28", "revision_id": "26980b66f12803b9f9901768732494bc328f93e9", "snapshot_id": "eae60cf2ca375e4cf19f00f908ce1043c3807e28", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/GeorgeGkas/slog/26980b66f12803b9f9901768732494bc328f93e9/example/example.c", "visit_date": "2021-05-01T08:00:38.644808" }
stackv2
/* * example.c * Copyleft (C) 2015 Sun Dro (a.k.a 7th Ghost) * Copyleft (C) 2017 George G. Gkasdrogkas (a.k.a. GeorgeGkas) * * Source example of slog library usage. Use GCC. */ #include <stdio.h> #include <string.h> #include <slog.h> void seperator() { for (int i = 1; i <= 68; ++i) { printf("="); } printf("\n"); } void greet() { /* Get and print slog version. */ seperator(); printf("slog Version: %s\n", slog_version(0)); seperator(); } int main() { /* Used variables. */ char char_arg[32]; int int_arg; /* Init args */ strcpy(char_arg, "test string"); int_arg = 69; /* Greet users. */ greet(); /* * slog_init - Initialize slog. * First argument is log filename. * Second argument is config file. * Third argument is max log level on console. * Fourth is max log level on file. * Fifth is thread safe flag. */ slog_init("example", "slog.cfg", 2, 3, 1); /* Log and print something with level 0. */ slog_live(0, "Test message with level 0"); /* Log and print something with level 1. */ slog_warn(1, "Warn message with level 1"); /* Log and print something with level 2. */ slog_info(2, "Info message with level 2"); /* Log and print something with level 3. */ slog_live(3, "Test message with level 3"); /* Log and print something with char argument */ slog_debug(0, "Debug message with char argument: %s", char_arg); /* Log and print something with int argument. */ slog_error(0, "Error message with int argument: %d", int_arg); /* Log and print something fatal. */ slog_fatal(0, "Fatal message. We fell into dead zone."); /* Log and print something in panic mode. */ slog_panic(0, "Panic here! We don't have tim...."); /* * Test log with higher level than log max value * This will never be printed while log level argument is higher than max log level. */ slog_none(4, "[LIVE] Test log with higher level than log max value"); /* Print something with our own colorized line. */ slog_none(0, "[%s] This is our own colorized string", strclr(CLR_NAGENTA, "TEST")); return 0; }
2.84375
3
2024-11-18T19:35:02.395326+00:00
2017-05-04T11:50:52
2e12255b15db55ab6fed76d6dfeae3b645586e11
{ "blob_id": "2e12255b15db55ab6fed76d6dfeae3b645586e11", "branch_name": "refs/heads/master", "committer_date": "2017-05-04T11:50:52", "content_id": "c59bbba9f64184022a0fc1de2ff22adad70ddcd7", "detected_licenses": [ "MIT" ], "directory_id": "99dc5038615ac0d041baa9f326e516869c50c85a", "extension": "c", "filename": "comm.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": 3723, "license": "MIT", "license_type": "permissive", "path": "/Software/Source/App/comm.c", "provenance": "stackv2-0048.json.gz:114", "repo_name": "trigrass2/navi-panel", "revision_date": "2017-05-04T11:50:52", "revision_id": "93b222595732017cec168aff9dca84e7ce5d9a81", "snapshot_id": "004e598b125706ec451bf88dc1795ad6e750164c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/trigrass2/navi-panel/93b222595732017cec168aff9dca84e7ce5d9a81/Software/Source/App/comm.c", "visit_date": "2021-06-18T12:39:58.093262" }
stackv2
/** ****************************************************************************** * @file comm.c * @author Jalon * @date 2016/02/01 * @brief 通讯协议传输层解包封包等相关函数 * @attention Copyright (C) 2016 Inmotion ****************************************************************************** */ #include "comm.h" #include "comm_usart.h" #include "global_defines.h" #include "queue.h" #include "tim_user.h" #include "gpio_user.h" #define TALK_MAX 1 #define TALK_MSG_BOX_SIZE 10 #define UART_BUFF_SIZE 128 #define NAVI_MAX(a, b) (a>b?a:b) #define NAVI_MAX_BLOCK (u32)(NAVI_MAX(NAVI_MAX( sizeof(NaviPack_CtrlType), sizeof(NaviPack_StatusType)), sizeof(NaviPack_ConfigType))) #define NAVIPACK_COMM_SIZE (NAVI_MAX_BLOCK + sizeof(NaviPack_HeadType) + 1) NavipackComm_Type NavipackComm; NavipackUserType UserReg; static CommUsartType CommUsart; static u8 UartBuffer[UART_BUFF_SIZE]; static QueueType TxQueue; static NaviPack_HeadType TxQueuePool[10]; static u8 CommTxBuffer[NAVIPACK_COMM_SIZE*2+6]; static u8 CommRxBuffer[NAVIPACK_COMM_SIZE]; /** * @brief 通讯传输层初始化 * @param None * @retval 是否成功 */ bool Comm_Init(void) { NavipackComm_Type *comm = &NavipackComm; comm->rxBuffer = CommRxBuffer; comm->txBuffer = CommTxBuffer; comm->rxSize = sizeof(CommRxBuffer); comm->txSize = sizeof(CommTxBuffer); comm->rxDataLen = 0; comm->txDataLen = 0; Queue_Init(&TxQueue, TxQueuePool, sizeof(TxQueuePool), sizeof(TxQueuePool[0])); NaviPack_Init(); if(GetCommMode()) { GlobalParams.commMode = COMM_UART; CommUsart.buffer_size = UART_BUFF_SIZE; CommUsart.dma_rx_buffer = UartBuffer; } else { GlobalParams.commMode = COMM_USB; } return true; } /** * @brief 获得串口句柄 * @retval 串口句柄 */ void* GetCommUartHandle(void) { return &CommUsart; } /** * @brief 数据接收 * @param data : 数据 * @retval None */ void Comm_RecvPackage(u8 data) { NaviPack_RxProcessor(&NavipackComm, data); } /** * @brief 通讯发送处理 Task * @param p_arg: 参数 * @retval None */ void Comm_TxTask(void) { NaviPack_HeadType head; if(Queue_Query(&TxQueue, &head)) { if(NaviPack_TxProcessor(&NavipackComm, &head)) { Queue_Get(&TxQueue, NULL); } } } /** * @brief 通讯接收处理 Task * @param None * @retval None */ void Comm_RxTask(void) { u8 *data; u32 len, i; if(GlobalParams.commMode == COMM_UART) { if(CommUsart_RecvData(&CommUsart, &data, &len)) { for(i=0; i<len; i++) { Comm_RecvPackage(data[i]); } } } else if(CDC_ReceiveData(&data, &len) == USBD_OK) { for(i=0; i<len; i++) { Comm_RecvPackage(data[i]); } CDC_StartReceiveData(); } } /** * @brief 推送一个发送事件 * @param handle : 对象编号 * @param head : 数据头指针 * @retval 是否成功 */ bool Comm_PostTxEvent(NaviPack_HeadType *head) { Queue_Put(&TxQueue, head); return true; }; /** * @brief 通讯定时发送 Task * @param p_arg: 参数 * @retval None */ void Comm_BoostTask(void) { static NaviPack_HeadType head = { NAVIPACK_SLAVE_ID, FUNC_ID_READ_STATUS, 0, sizeof(NaviPack_StatusType), }; if(RunFlag.boost) { RunFlag.boost = 0; Comm_PostTxEvent(&head); } }
2.46875
2
2024-11-18T19:35:02.574405+00:00
2021-09-07T03:52:06
43cbe7772e6c699611e986b3044a68c235c6838f
{ "blob_id": "43cbe7772e6c699611e986b3044a68c235c6838f", "branch_name": "refs/heads/main", "committer_date": "2021-09-07T03:52:06", "content_id": "013ad412381e65126e7353e4aa5516a4ef152db1", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cb475d167529660ffa55c44af568b78ab7172472", "extension": "c", "filename": "18 Area of Rectangle.c", "fork_events_count": 1, "gha_created_at": "2021-09-07T02:59:29", "gha_event_created_at": "2021-09-07T03:15:56", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 403822117, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 415, "license": "Apache-2.0", "license_type": "permissive", "path": "/C/Functions/18 Area of Rectangle.c", "provenance": "stackv2-0048.json.gz:370", "repo_name": "Noob-coder-07/DeepAlgo", "revision_date": "2021-09-07T03:52:06", "revision_id": "b7f5f8eacefff561648b476946d80948b3f69f51", "snapshot_id": "84b0e4890b79b9e4a796f883bce9ddbce13c9872", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Noob-coder-07/DeepAlgo/b7f5f8eacefff561648b476946d80948b3f69f51/C/Functions/18 Area of Rectangle.c", "visit_date": "2023-07-18T11:40:21.104475" }
stackv2
#include<stdio.h> #include<conio.h> float Area_Rectangle(float,float); int main() { float No1,No2; float Res; printf("\nEnter the measures of Circle to find its Area : "); scanf("%f%f",&No1,&No2); Res=Area_Rectangle(No1,No2); printf("\nArea of given Rectangle is %.2f.",Res); getch(); return 0; } float Area_Rectangle(float length,float breadth) { return length*breadth; }
3.125
3
2024-11-18T20:01:54.915087+00:00
2017-05-24T20:16:22
e06ba4a7ec2edb4bf61715f8d49fdc9e37a42063
{ "blob_id": "e06ba4a7ec2edb4bf61715f8d49fdc9e37a42063", "branch_name": "refs/heads/master", "committer_date": "2017-05-24T20:16:22", "content_id": "deaae34ca2135877e4d8bb9f9fc7c8886ba8da33", "detected_licenses": [ "MIT" ], "directory_id": "5fe4ec7c223bc2a47e710dd7b4c2f0d38e169cf1", "extension": "c", "filename": "stdio.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": 2402, "license": "MIT", "license_type": "permissive", "path": "/src/libc/stdio.c", "provenance": "stackv2-0049.json.gz:6566", "repo_name": "wassekaran/willOS", "revision_date": "2017-05-24T20:16:22", "revision_id": "508c8fce29c03070a2d4cd87ae58d841a37e3877", "snapshot_id": "c300a9e0a59aeed2730a3385afa17e01442329f7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wassekaran/willOS/508c8fce29c03070a2d4cd87ae58d841a37e3877/src/libc/stdio.c", "visit_date": "2020-04-11T18:28:46.477147" }
stackv2
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <stddef.h> #include <ctype.h> #include <drivers/screen.h> #include <drivers/serial.h> void putchar(int device, char c); void puts(int device, char *s); void printf(const char* format, ...) { va_list arg; va_start(arg, format); vprintf(DEVICE_SCREEN, format, arg); va_end(arg); } void vprintf(int device, const char* format, va_list arg) { int32_t i_val; uint32_t u_val; uint64_t l_val; char s_val[20]; for (size_t i = 0; i < strlen(format); i++) { char c = format[i]; if (c == '%') { uint8_t leftpad = format[i + 1] - '0'; if (isdigit(leftpad)) { i++; } else { leftpad = 0; } switch (format[i + 1]) { case '%': putchar(device, '%'); break; case 'c': putchar(device, va_arg(arg, int)); break; case 'd': i_val = va_arg(arg, int32_t); itoa(i_val, s_val, 10); while ((leftpad - (uint8_t) strlen(s_val)) > 0) { putchar(device, '0'); leftpad--; } puts(device, s_val); break; case 'u': case 'x': u_val = va_arg(arg, uint32_t); itoa(u_val, s_val, format[i + 1] == 'x' ? 16 : 10); puts(device, s_val); break; case 'L': case 'X': l_val = va_arg(arg, uint64_t); ulltoa(l_val, s_val, format[i + 1] == 'X' ? 16 : 10); puts(device, s_val); break; case 's': puts(device, va_arg(arg, char *)); break; } i++; } else { putchar(device, c); } } } void putchar(int device, char c) { if (device > DEVICE_SCREEN) { serial_write(device, c); } else { screen_write(c); } } void puts(int device, char *s) { if (device > DEVICE_SCREEN) { serial_print(device, s); } else { screen_print(s); } }
3.125
3
2024-11-18T20:01:55.154473+00:00
2019-12-18T06:00:40
b00e997c2aacdb8a891c99ce6fc0d7e69399bb6f
{ "blob_id": "b00e997c2aacdb8a891c99ce6fc0d7e69399bb6f", "branch_name": "refs/heads/master", "committer_date": "2019-12-18T06:00:40", "content_id": "8e5dfd0c804a53e7dd9daaaf232c8efc687d16e0", "detected_licenses": [ "MIT" ], "directory_id": "74edc399f159607525a89c2dfda1905c8c22576e", "extension": "h", "filename": "garbage.h", "fork_events_count": 0, "gha_created_at": "2019-12-19T01:28:44", "gha_event_created_at": "2019-12-19T01:28:45", "gha_language": null, "gha_license_id": null, "github_id": 228950951, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1885, "license": "MIT", "license_type": "permissive", "path": "/minijvm/c/jvm/garbage.h", "provenance": "stackv2-0049.json.gz:6824", "repo_name": "moneytech/miniJVM", "revision_date": "2019-12-18T06:00:40", "revision_id": "e178c487b391a57483f21914e43b0f323cf2e86f", "snapshot_id": "5611c253abf2505d31cd0458ef3f3e6fc542785f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/moneytech/miniJVM/e178c487b391a57483f21914e43b0f323cf2e86f/minijvm/c/jvm/garbage.h", "visit_date": "2020-11-26T03:19:22.888914" }
stackv2
#ifndef _GARBAGE_H #define _GARBAGE_H #include "../utils/hashtable.h" #include "../utils/hashset.h" #include "../utils/linkedlist.h" #include "jvm.h" #include "jvm_util.h" #ifdef __cplusplus extern "C" { #endif typedef struct _GcCollectorType GcCollector; //回收线程 extern s64 GARBAGE_PERIOD_MS;// extern GcCollector *collector; extern s64 MAX_HEAP_SIZE; //每个线程一个回收站,线程多了就是灾难 struct _GcCollectorType { // Hashset *objs_holder; //法外之地,防回收的持有器,放入其中的对象及其引用的其他对象不会被回收 MemoryBlock *header, *tmp_header, *tmp_tailer; s64 obj_count; Runtime *runtime; // // thrd_t _garbage_thread;//垃圾回收线程 ThreadLock garbagelock; spinlock_t lock; // ArrayList *runtime_refer_copy; // s64 _garbage_count; u8 _garbage_thread_status; u8 flag_refer; u8 isgc; s16 exit_flag; s16 exit_code; }; enum { GARBAGE_THREAD_NORMAL, GARBAGE_THREAD_PAUSE, GARBAGE_THREAD_STOP, GARBAGE_THREAD_DEAD, }; s32 _collect_thread_run(void *para); s32 garbage_thread_trylock(); void garbage_thread_lock(void); void garbage_thread_unlock(void); void garbage_thread_stop(void); void garbage_thread_pause(void); void garbage_thread_resume(void); void garbage_thread_wait(void); void garbage_thread_timedwait(s64 ms); void garbage_thread_notify(void); void garbage_thread_notifyall(void); //其他函数 s32 garbage_collector_create(void); void garbage_collector_destory(void); s64 garbage_collect(void); MemoryBlock *gc_is_alive(__refer obj); void gc_refer_hold(__refer ref); void gc_refer_release(__refer ref); void gc_refer_reg(Runtime *runtime, __refer ref); void gc_move_refer_thread_2_gc(Runtime *runtime); void garbage_dump_runtime(); #ifdef __cplusplus } #endif #endif //_GARBAGE_H
2.046875
2