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:48:30.697349+00:00
2016-05-02T06:17:20
c4a1f99d54c479863203f3a69fd3d3a26f38954c
{ "blob_id": "c4a1f99d54c479863203f3a69fd3d3a26f38954c", "branch_name": "refs/heads/master", "committer_date": "2016-05-02T06:17:20", "content_id": "6cb238af53645304bf88597178f2ad22df68cd78", "detected_licenses": [ "MIT" ], "directory_id": "19dcbc38765c64f29f762b56455875a1f4ca6fff", "extension": "c", "filename": "ConsoleFuncs.c", "fork_events_count": 0, "gha_created_at": "2016-04-25T01:49:35", "gha_event_created_at": "2016-04-25T01:49:36", "gha_language": null, "gha_license_id": null, "github_id": 57004066, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10638, "license": "MIT", "license_type": "permissive", "path": "/AsciiEngine/ConsoleFuncs.c", "provenance": "stackv2-0102.json.gz:64269", "repo_name": "luizcg/AsciiEngine", "revision_date": "2016-05-02T06:17:20", "revision_id": "0e0eea92d7c0b0b02443778a41a0e3417c325bed", "snapshot_id": "239c365a0b3a8e105304a447323575b0d3c908f6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/luizcg/AsciiEngine/0e0eea92d7c0b0b02443778a41a0e3417c325bed/AsciiEngine/ConsoleFuncs.c", "visit_date": "2021-01-17T15:33:18.304554" }
stackv2
//////////////////////////////////////////////////// // Copyright (c) 2012 ICRL // See the file LICENSE.txt for copying permission. // // Original Author: Randy Gaul // Date: 7/3/2012 // Contact: r.gaul@digipen.edu //////////////////////////////////////////////////// // This file mostly sets up the windows console, but also has some other // various functionality. // Documentation: http://cecilsunkure.blogspot.com/2011/12/windows-console-game-set-custom-color.html #include "ConsoleFuncs.h" #include "Graphics.h" WCHAR CONSOLE_TITLE[MAX_CONSOLE_TITLE]; BOOL WINDOW_FOCUS = TRUE; /* BOOL for storing window focus */ HANDLE OUTPUT_HANDLE; /* write (output) handle */ HANDLE INPUT_HANDLE; /* read (input handle */ HWND WINDOW_HANDLE; /* Handle to window */ WNDPROC OLD_WNDPROC = { 0 }; /* Handle to the default wndproc */ LRESULT CALLBACK WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); /****************************************************************************** initConsole Initializes various aspects of the console. ******************************************************************************/ void initConsole(unsigned short *title, wchar_t *fontName, int fontx, int fonty ) { // Used to center the window on the user's screen int x = GetSystemMetrics(SM_CXSCREEN) / 2; int y = GetSystemMetrics(SM_CYSCREEN) / 2; /* Setting the color palette to the default colors */ /* Browse MSDN for COLORREF to learn more about these RGB values */ COLORREF palette[16] = { 0x00000000, 0x001AA3ED, 0x002d5c2c, 0x007fb412, 0x00000080, 0x005a4b61, 0x003e5f81, 0x00c0c0c0, 0x00808080, 0x00f3a600, 0x0077c371, 0x00c8cc7a, 0x000000ff, 0x00ff00ff, 0x003CFAFA, 0x00ffffff }; /* Search MSDN for the RGB macro to easily generate COLORREF values */ /* Window size coordinates, be sure to start index at zero! */ SMALL_RECT windowSize = {0, 0, BUFFERWIDTH - 1, BUFFERHEIGHT - 1}; /* A COORD struct for specificying the console's screen buffer dimensions */ COORD bufferSize = {BUFFERWIDTH, BUFFERHEIGHT}; CONSOLE_CURSOR_INFO cursorInfo = {1, 0}; /* initialize handles */ HANDLE wHnd = GetStdHandle(STD_OUTPUT_HANDLE); WINDOW_HANDLE = GetConsoleWindow( ); /* initialize handles */ OUTPUT_HANDLE = GetStdHandle(STD_OUTPUT_HANDLE); INPUT_HANDLE = GetStdHandle(STD_INPUT_HANDLE); /* Set the console's title */ SetConsoleTitle((LPCWSTR)title); /* Set cursor info */ SetConsoleCursorInfo(wHnd, &cursorInfo); /* Set the console font settings and palette */ SetConsolePalette(palette, fontx, fonty, fontName); /* Set the window size */ SetConsoleWindowInfo(OUTPUT_HANDLE, TRUE, &windowSize); /* Set the screen's buffer size */ SetConsoleScreenBufferSize(wHnd, bufferSize); /* Set the window size */ SetConsoleWindowInfo(OUTPUT_HANDLE, TRUE, &windowSize); /* Set the window position */ SetWindowPos(WINDOW_HANDLE, HWND_TOP, (x - ((BUFFERWIDTH / 2) * fontx)) - 5, (y - ((BUFFERHEIGHT / 2) * fonty)) - 5, 0, 0, SWP_NOSIZE); } /****************************************************************************** windowsVersionTest Checks to see if have Vista/7 or earlier by attempting to retrieve function from kernel32.dll that is only available in Vista+ version of Windows. ******************************************************************************/ int windowsVersionTest(void) { /* Retrieving pointers for Windows Vista/7 Functions */ PGetCurrentConsoleFontEx pGetCurrentConsoleFontEx = (PGetCurrentConsoleFontEx) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetCurrentConsoleFontEx"); /* If exists then we have Vita/7 */ if (pGetCurrentConsoleFontEx) { return 1; } else { return 0; } } /****************************************************************************** SetConsolePalette Sets the console palette and font size. ******************************************************************************/ VOID WINAPI SetConsolePalette(COLORREF palette[], int fontX, int fontY, wchar_t *fontName) { int i; HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); /* Retrieving pointers for Windows Vista/7 Functions */ PGetCurrentConsoleFontEx pGetCurrentConsoleFontEx = (PGetCurrentConsoleFontEx) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetCurrentConsoleFontEx"); PSetCurrentConsoleFontEx pSetCurrentConsoleFontEx = (PSetCurrentConsoleFontEx) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "SetCurrentConsoleFontEx"); PGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx = (PGetConsoleScreenBufferInfoEx) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetConsoleScreenBufferInfoEx"); PSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx = (PSetConsoleScreenBufferInfoEx) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "SetConsoleScreenBufferInfoEx"); /* Check for pointers: if they exist, we have Vista/7 and we can use them */ if (pGetCurrentConsoleFontEx && pSetCurrentConsoleFontEx && pGetConsoleScreenBufferInfoEx && pSetConsoleScreenBufferInfoEx) { CONSOLE_SCREEN_BUFFER_INFOEX cbi; CONSOLE_FONT_INFOEX cfi = {sizeof(CONSOLE_FONT_INFOEX)}; /* Tell the font info how big it is, to avoid memory corruption */ cfi.cbSize = sizeof(CONSOLE_FONT_INFOEX); pGetCurrentConsoleFontEx(hOutput, TRUE, &cfi); /* Set the font type to name indicated by wide string literal */ /* Set to 0 to keep current settings */ lstrcpyW(cfi.FaceName, fontName); cfi.dwFontSize.X = fontX; cfi.dwFontSize.Y = fontY; cfi.FontFamily = 0; /* Set to 0x30 for Terminal font */ cfi.FontWeight = 0; /* Set the console font info */ pSetCurrentConsoleFontEx(hOutput, TRUE, &cfi); /* Get the size of the structure before filling the struct */ cbi.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX); pGetConsoleScreenBufferInfoEx(hOutput, &cbi); /* Loop through the given palette, copying the data into the color table */ for (i = 0 ; i < 16 ; ++i) { cbi.ColorTable[i] = palette[i]; } /* Set the console screen buffer info */ pSetConsoleScreenBufferInfoEx(hOutput, &cbi); } else /* We don't have access to the vista functions */ { int i; CONSOLE_INFO ci = { sizeof(ci) }; HWND hwndConsole = GetConsoleWindow(); GetConsoleSizeInfo(&ci, hOutput); /* Set to 0 to keep current settings */ ci.FontSize.X = fontX; ci.FontSize.Y = fontY; ci.FontFamily = 0; /* Set to 0x30 for Terminal font */ ci.FontWeight = 0; lstrcpyW(ci.FaceName, fontName); ci.CursorSize = 100; ci.FullScreen = FALSE; ci.QuickEdit = FALSE; ci.AutoPosition = 0x10000; ci.InsertMode = TRUE; ci.ScreenColors = MAKEWORD(0x7, 0x0); ci.PopupColors = MAKEWORD(0x5, 0xf); ci.HistoryNoDup = TRUE; ci.HistoryBufferSize = 50; ci.NumberOfHistoryBuffers = 4; for(i = 0; i < 16; i++) { ci.ColorTable[i] = palette[i]; } ci.CodePage = 0; ci.Hwnd = hwndConsole; lstrcpyW(ci.ConsoleTitle, L""); SetConsoleInfo(hwndConsole, &ci); } } /****************************************************************************** GetConsoleSizeInfo (XP only) Fills up some info about the console font in the CONSOLE_INFO struct. ******************************************************************************/ static void GetConsoleSizeInfo(CONSOLE_INFO *pci, HANDLE hOutput) { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(hOutput, &csbi); pci->ScreenBufferSize = csbi.dwSize; pci->WindowSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1; pci->WindowSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; pci->WindowPosX = csbi.srWindow.Left; pci->WindowPosY = csbi.srWindow.Top; } /****************************************************************************** SetConsoleInfo (XP only) Ends up sending a message to windows to reset the console info. ******************************************************************************/ BOOL SetConsoleInfo(HWND hwndConsole, CONSOLE_INFO *pci) { DWORD dwConsoleOwnerPid; HANDLE hProcess; HANDLE hSection, hDupSection; PVOID ptrView = 0; HANDLE hThread; /* Open the process which "owns" the console */ GetWindowThreadProcessId(hwndConsole, &dwConsoleOwnerPid); hProcess = OpenProcess(MAXIMUM_ALLOWED, FALSE, dwConsoleOwnerPid); /* Create a SECTION entity backed by page-file, then map a view of */ /* this section into the owner process so we can write the contents */ /* of the CONSOLE_INFO buffer into it */ hSection = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, pci->Length, 0); /* Copy our console structure into the section-entity */ ptrView = MapViewOfFile(hSection, FILE_MAP_WRITE|FILE_MAP_READ, 0, 0, pci->Length); memcpy(ptrView, pci, pci->Length); UnmapViewOfFile(ptrView); /* Map the memory into owner process */ DuplicateHandle(GetCurrentProcess(), hSection, hProcess, &hDupSection, 0, FALSE, DUPLICATE_SAME_ACCESS); /* Send console window the "update" message WM_SETCONSOLEINFO */ SendMessage(hwndConsole, WM_SETCONSOLEINFO, (WPARAM)hDupSection, 0); /*clean up */ hThread = CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)CloseHandle, hDupSection, 0, 0); CloseHandle(hThread); CloseHandle(hSection); CloseHandle(hProcess); return TRUE; } #include "Graphics.h" #include "FrameRateController.h" /* Wrapper function for writing to console */ void RenderScreen( void ) { /* Positions used to write to the screen */ COORD charBufSize = {BUFFERWIDTH, BUFFERHEIGHT}; COORD characterPos = {0,0}; SMALL_RECT writeArea = {0,0,BUFFERWIDTH - 1,BUFFERHEIGHT - 1}; #ifdef DISPLAY_FPS char buffer[100]; float currentTime = GetCurrentGameTime( ); float frameStateTime = GetTimeAtFrameStart( ); sprintf_s( buffer, 100, "FPS: %f", 1.f / (currentTime - frameStateTime) ); WriteStringToScreenNoCam( buffer, BUFFERWIDTH - 20, 0 ); #endif // DISPLAY_FPS // This function renders to the console's screen buffer. This function is slow! Only // call this once per game loop at most. WriteConsoleOutputA( OUTPUT_HANDLE, DOUBLE_BUFFER, charBufSize, characterPos, &writeArea ); }
2.140625
2
2024-11-18T20:48:30.886755+00:00
2019-04-30T14:12:39
31fccaad357de4f6c7db6052911784c12b6095d9
{ "blob_id": "31fccaad357de4f6c7db6052911784c12b6095d9", "branch_name": "refs/heads/master", "committer_date": "2019-04-30T14:12:39", "content_id": "4a42f9764154d1d2819181b69e68cfccc69ffdca", "detected_licenses": [ "MIT" ], "directory_id": "4d9c48d055ad1d8a888d0fca3f440519cb512504", "extension": "h", "filename": "fkfont.h", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 164331492, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3864, "license": "MIT", "license_type": "permissive", "path": "/src/fontkit/fkfont.h", "provenance": "stackv2-0102.json.gz:64531", "repo_name": "rsms/fontkit", "revision_date": "2019-04-30T14:12:39", "revision_id": "c362db1ef8cf0b7f4e598454275465ce82d24820", "snapshot_id": "ed56309a2ea210d8b5348966206d15f85da3d5a6", "src_encoding": "UTF-8", "star_events_count": 60, "url": "https://raw.githubusercontent.com/rsms/fontkit/c362db1ef8cf0b7f4e598454275465ce82d24820/src/fontkit/fkfont.h", "visit_date": "2020-04-15T02:59:14.344051" }
stackv2
#pragma once #include "common.h" #include "fkfont-props.inc" #include "fkbuf.h" #include "fkvar.h" #include <freetype/ftsnames.h> typedef struct _FKFont { FT_Face face; hb_font_t* font; hb_map_t* nameindex; // maps strid to SFNT index FKVar* vm; } FKFont; // FKFontCreate allocates and initialized a new font object from font data. // You must not deallocate the memory at p before calling FKFontFree. // FKFont* FKFontCreate(const FT_Byte* p, unsigned length); // FKFontFree deallocates font previously allocated with FKFontCreate. // void FKFontFree(FKFont*); // FKFontSetCharSize sets the character size which is used as the basis // for layout. Defaults to the font's UPM, causing all other functions // to return metrics in the font's UPM (i.e. 1:1.) // bool FKFontSetCharSize(const FKFont*, long size); // FKFontGetGlyphAdvance returns the nominal glyph advance (horizontal) // for glyph with codepoint. // i32 FKFontGetGlyphAdvance(FKFont*, FKCodepoint); // FKFontGetGlyphKerning returns the kerning (horizontal) for a glyph pair, // defined by codepoints. // i32 FKFontGetGlyphKerning(FKFont*, FKCodepoint left, FKCodepoint right); // FKFontGetGlyphName copies the name of glyph with codepoint into memory // at pch. No more than size bytes will be copied. If there's not enough // space, or if there's no glyph mapped to cp, the function returns false // and FKErr is set. // bool FKFontGetGlyphName(FKFont*, FKGlyphID, char* pch, u32 size); // FKFontGetVarCount returns a variations object if the font is variable, // or null if the font is not variable. // The returned object is managed by the FKFont and is valid as long as the // parent FKFont object is. // FKVar* FKFontGetVar(FKFont*); // FKFontLayout executes text layout // bool FKFontLayout(FKFont*, FKBuf*, hb_feature_t*, u32 nfeats); // Properties of FT_Face exposed via accessor functions. // i.e. // const char* FKFontGet_family_name(const FKFont*) // #define A(TYPE, NAME) \ TYPE FKFontGet_##NAME(const FKFont*); FK_FONT_PROPS(A) #undef A // Return a string describing the format of a given face. // Possible values are "TrueType", "Type 1", "BDF", "PCF", "Type 42", // "CID Type 1", "CFF", "PFR", and "Windows FNT". const char* FKFontGet_format_name(const FKFont*); // FKFontGet_isSFNT returns true when the font format is based on the // SFNT storage scheme. This usually means: TrueType fonts, OpenType fonts, // as well as SFNT-based embedded bitmap fonts. bool FKFontGetIsSFNT(const FKFont*); // true whenever the font contains a scalable/vector font face. // i.e. TrueType, Type 1, Type 42, CID, OpenType/CFF, and PFR font formats. bool FKFontGetIsScalable(const FKFont*); // true whenever the font contains fixed-width glyphs. bool FKFontGetIsMonospace(const FKFont*); // FKFontGetWeightClass returns the weight class. Valid range: [1-1000] // https://docs.microsoft.com/en-us/typography/opentype/spec/os2#usweightclass u16 FKFontGetWeightClass(const FKFont*); // FKFontGetWidthClass returns the width class. Valid range: [1-9] // https://docs.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass u16 FKFontGetWidthClass(const FKFont*); // FKFontGetXHeight returns the (metrics) x-height if known; 0 if unknown. i16 FKFontGetXHeight(const FKFont*); // FKFontGetCapHeight returns the (metrics) cap height if known; 0 if unknown. i16 FKFontGetCapHeight(const FKFont*); // FKFontGetVendorID returns the four-byte vendor ID, or NULL if unknown. // https://docs.microsoft.com/en-us/typography/opentype/spec/os2#achvendid const char* FKFontGetVendorID(const FKFont*); // ------------------------------------------------------- // internal hb_font_t* FKFontGetHB(FKFont*); // FKFontGetName finds a name in the SFNT table, by string id. // Returns true if strid was found. // bool FKFontGetName(FKFont*, u32 strid, /*out*/FT_SfntName*);
2.4375
2
2024-11-18T20:48:31.153912+00:00
2020-03-01T15:00:23
be5b2cf869bc0be2a4b7e24918a75ba6449c2382
{ "blob_id": "be5b2cf869bc0be2a4b7e24918a75ba6449c2382", "branch_name": "refs/heads/master", "committer_date": "2020-03-01T15:00:23", "content_id": "eea8d71c7a77b00206eb9ecdf022a7edee6cf36c", "detected_licenses": [ "MIT" ], "directory_id": "c298163c6819285f00bd6e06f28d157dbd5c1a8b", "extension": "c", "filename": "ADC.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 242531018, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1171, "license": "MIT", "license_type": "permissive", "path": "/AVR source code/Code V1.0 for PCB V1.0/ADC.c", "provenance": "stackv2-0102.json.gz:64660", "repo_name": "kwiecinski/Polymerization-lamp-for-dentistry", "revision_date": "2020-03-01T15:00:23", "revision_id": "a14364a14716e2b78817a836b81cb535062cbbc5", "snapshot_id": "48231d10980b8fc682574424c385a438245c0796", "src_encoding": "WINDOWS-1250", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kwiecinski/Polymerization-lamp-for-dentistry/a14364a14716e2b78817a836b81cb535062cbbc5/AVR source code/Code V1.0 for PCB V1.0/ADC.c", "visit_date": "2021-01-13T23:48:54.984815" }
stackv2
#include <avr/io.h> #include "ADC.h" //----------------------------------------------------------------------------------------------------------------- void ADC_init(void) { //ustawienia ADC ADMUX |= (1<<REFS0); //napięcie odniesienia wewnętrzne 1,1V ADCSRA |= (1<<ADEN)| (1<<ADPS2)| (1<<ADPS0); //włączenie ADC, preskaler 128 } //----------------------------------------------------------------------------------------------------------------- /* * * Returning voltage in format: ex. 15364 ->1,5364V * */ uint16_t ADC_measure(uint8_t channel) { const uint16_t RefVoltage=108; const uint8_t samples=50; uint8_t MSB,LSB,LoopCounter; uint16_t voltage,sum; uint32_t ADC_result; ADMUX |=(ADMUX & 0xF8) | channel; sum=0; for(LoopCounter=0;LoopCounter<samples;LoopCounter++) { ADCSRA |=(1<<ADSC); while(ADCSRA & (1<<ADSC)); //czekam na dokonanie pomiaru LSB=ADCL; //odczyt danych z ADC MSB=ADCH; ADC_result=(uint16_t)MSB<<8 | (uint16_t)LSB; sum=sum+ADC_result; } ADC_result=sum/(uint16_t)samples; ADC_result=ADC_result*100; voltage=(ADC_result/1024)*RefVoltage; return voltage; }
2.890625
3
2024-11-18T20:48:31.695609+00:00
2023-07-25T12:21:55
2e58b589e8ebf03e844b6c0bc176e9c510f0051d
{ "blob_id": "2e58b589e8ebf03e844b6c0bc176e9c510f0051d", "branch_name": "refs/heads/master", "committer_date": "2023-07-25T12:21:55", "content_id": "21bec91e0c5fcd647eaba872f632752abe396e6d", "detected_licenses": [ "MIT" ], "directory_id": "3e159a51aa9360f3dbc845f6597a285dea739f6b", "extension": "c", "filename": "psi_gradients.c", "fork_events_count": 33, "gha_created_at": "2018-06-15T16:11:39", "gha_event_created_at": "2023-08-25T14:43:40", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 137508275, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1550, "license": "MIT", "license_type": "permissive", "path": "/src/psi_gradients.c", "provenance": "stackv2-0102.json.gz:65047", "repo_name": "ludwig-cf/ludwig", "revision_date": "2023-07-25T12:21:55", "revision_id": "c21dba0281a3dad53b179ddce8f9ea75718dd5ee", "snapshot_id": "d8bf20ea2b250322299efc058805b8bd6047a8d1", "src_encoding": "UTF-8", "star_events_count": 49, "url": "https://raw.githubusercontent.com/ludwig-cf/ludwig/c21dba0281a3dad53b179ddce8f9ea75718dd5ee/src/psi_gradients.c", "visit_date": "2023-08-31T20:37:19.573342" }
stackv2
/**************************************************************************** * * psi_gradients.c * * Currently just routines for the electric field, aka, the gradient * of the potential. * * * Edinburgh Soft Matter and Statistical Physics Group and * Edinburgh Parallel Computing Centre * * Oliver Henrich (ohenrich@epcc.ed.ac.uk) * * (c) 2014-2023 The University of Edinburgh * ****************************************************************************/ #include <assert.h> #include "coords.h" #include "psi_gradients.h" /***************************************************************************** * * psi_electric_field * * Return the electric field associated with the current potential. * E_a = - \nabla_a \psi * *****************************************************************************/ int psi_electric_field(psi_t * psi, int index, double e[3]) { int ijk[3] = {0}; cs_t * cs = NULL; stencil_t * s = NULL; assert(psi); cs = psi->cs; s = psi->stencil; assert(cs); assert(s); cs_index_to_ijk(cs, index, ijk); e[X] = 0; e[Y] = 0; e[Z] = 0; for (int p = 1; p < s->npoints; p++) { int8_t cx = s->cv[p][X]; int8_t cy = s->cv[p][Y]; int8_t cz = s->cv[p][Z]; int index1 = cs_index(cs, ijk[X] + cx, ijk[Y] + cy, ijk[Z] + cz); double psi0 = psi->psi->data[addr_rank0(psi->nsites, index1)]; /* E_a = -\nabla_a psi */ e[X] -= s->wgradients[p]*cx*psi0; e[Y] -= s->wgradients[p]*cy*psi0; e[Z] -= s->wgradients[p]*cz*psi0; } return 0; }
2.578125
3
2024-11-18T20:48:32.580643+00:00
2021-09-20T17:28:00
927dfe56e074433a7de8df816d7889ef78e4f79e
{ "blob_id": "927dfe56e074433a7de8df816d7889ef78e4f79e", "branch_name": "refs/heads/main", "committer_date": "2021-09-20T17:28:00", "content_id": "e8c60c776eb7138fc4d382b915ce1ad8a7e9e777", "detected_licenses": [ "MIT" ], "directory_id": "7708a10f488fbe2239fdf2921d82c16a24c86d57", "extension": "c", "filename": "helio.c", "fork_events_count": 0, "gha_created_at": "2021-07-19T10:00:42", "gha_event_created_at": "2021-07-19T10:00:42", "gha_language": null, "gha_license_id": "MIT", "github_id": 387418093, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1365, "license": "MIT", "license_type": "permissive", "path": "/libastro/helio.c", "provenance": "stackv2-0102.json.gz:65560", "repo_name": "obspsr/XEphem", "revision_date": "2021-09-20T17:28:00", "revision_id": "39b13d41597f99d7bc760634c23e377f831c336e", "snapshot_id": "ab434f0b0b042cbb2f489ca417c089eed421d64a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/obspsr/XEphem/39b13d41597f99d7bc760634c23e377f831c336e/libastro/helio.c", "visit_date": "2023-08-03T03:00:22.101152" }
stackv2
#include <stdlib.h> #include <math.h> #include <math.h> #include "astro.h" /* given geocentric time jd and coords of a distant object at ra/dec (J2000), * find the difference in time between light arriving at earth vs the sun. * *hcp must be subtracted from geocentric jd to get heliocentric jd. * From RLM Oct 12, 1995. */ void heliocorr (double jd, double ra, double dec, double *hcp) { double e; /* obliquity of ecliptic */ double n; /* day number */ double g; /* solar mean anomaly */ double L; /* solar ecliptic longitude */ double l; /* mean solar ecliptic longitude */ double R; /* sun distance, AU */ double X, Y; /* equatorial rectangular solar coords */ double cdec, sdec; double cra, sra; /* following algorithm really wants EOD */ precess (J2000, jd - MJD0, &ra, &dec); cdec = cos(dec); sdec = sin(dec); cra = cos(ra); sra = sin(ra); n = jd - 2451545.0; /* use epoch 2000 */ e = degrad(23.439 - 0.0000004*n); g = degrad(357.528) + degrad(0.9856003)*n; L = degrad(280.461) + degrad(0.9856474)*n; l = L + degrad(1.915)*sin(g) + degrad(0.02)*sin(2.0*g); R = 1.00014 - 0.01671*cos(g) - 0.00014*cos(2.0*g); X = R*cos(l); Y = R*cos(e)*sin(l); #if 0 printf ("n=%g g=%g L=%g l=%g R=%g X=%g Y=%g\n", n, raddeg(g), raddeg(L), raddeg(l), R, X, Y); #endif *hcp = 0.0057755 * (cdec*cra*X + (cdec*sra + tan(e)*sdec)*Y); }
2.53125
3
2024-11-18T20:48:32.866811+00:00
2019-05-05T08:13:04
eb0b4b187288bcc7d01d0967239ff9b8699fc122
{ "blob_id": "eb0b4b187288bcc7d01d0967239ff9b8699fc122", "branch_name": "refs/heads/master", "committer_date": "2019-05-05T08:13:04", "content_id": "aaa82743fd83311c335f628fddebce7fc8d5ab8a", "detected_licenses": [ "MIT" ], "directory_id": "d79b2fb40b2f8486bf2082414447a84707a7b961", "extension": "h", "filename": "util.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": 506, "license": "MIT", "license_type": "permissive", "path": "/src/util.h", "provenance": "stackv2-0102.json.gz:65819", "repo_name": "AxelOc5959/asteroid", "revision_date": "2019-05-05T08:13:04", "revision_id": "b3ab6e1dd1a24602051f52334836f68c7c372174", "snapshot_id": "c57a83af37cfd85392fa6b9d315c5d32afa7bf96", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AxelOc5959/asteroid/b3ab6e1dd1a24602051f52334836f68c7c372174/src/util.h", "visit_date": "2023-03-16T03:11:41.542891" }
stackv2
#pragma once #include <allegro.h> #include <math.h> #include <float.h> #define RAD_PER_FIX (128.0 / M_PI) #define FIX_PER_RAD (M_PI / 128.0) // return int in range [0, MAX) int Rnd(int max); // return double in range [0, 1) double randf(); // convert radians (0 == East, O to 2PI) // to Allegro fixed point binary angle (0 == North, 0 to 256) fixed RAD2FIX(double r); double squareDistance(double x1, double y1, double x2, double y2); double relativeAngle(double x1, double y1, double x2, double y2);
2.171875
2
2024-11-18T20:48:33.003292+00:00
2020-04-29T23:23:19
fc2dade27f27d9cc167656e0c9157dfa5b36473b
{ "blob_id": "fc2dade27f27d9cc167656e0c9157dfa5b36473b", "branch_name": "refs/heads/master", "committer_date": "2020-04-29T23:23:19", "content_id": "d683513768b19f1c65a4854ed9b861c116977b63", "detected_licenses": [ "MIT" ], "directory_id": "7caa1206facfdf588dd86d9383d0518bc2561058", "extension": "c", "filename": "my_vect.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 236864961, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3241, "license": "MIT", "license_type": "permissive", "path": "/Final_Proj/Wright_RTOS_Final_Proj/src/Source_Files/my_vect.c", "provenance": "stackv2-0102.json.gz:65949", "repo_name": "derekwright29/RTOS", "revision_date": "2020-04-29T23:23:19", "revision_id": "fa4981fbd50ac1d70ed3ac960562013bd42ee87d", "snapshot_id": "8d24120eb39d6282a76176aad35eb16121329307", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/derekwright29/RTOS/fa4981fbd50ac1d70ed3ac960562013bd42ee87d/Final_Proj/Wright_RTOS_Final_Proj/src/Source_Files/my_vect.c", "visit_date": "2020-12-22T16:56:35.857521" }
stackv2
#include <my_vect.h> #include <math.h> float vect_mag(vect_t vector) { if (vector.x == 0.0 && vector.y == 0.0) { return 0.0; } return sqrt(pow((vector.x),2) + pow(vector.y,2)); } vect_t vect_parallel(vect_t reference_vect, float magnitude) { if (vect_mag(reference_vect) ==0.0) { return (vect_t){0,0}; } return vect_mult(reference_vect, magnitude / vect_mag(reference_vect)); } vect_t vect_orth(vect_t reference_vect, float magnitude, vect_orth_ref_angle_t angle) { vect_t new_vect = {0,0}; if (vect_mag(reference_vect) == 0.0) { return new_vect; } if (angle == RIGHT_NINETY) { new_vect = (vect_t) {reference_vect.y, -1* reference_vect.x}; } else if (angle == LEFT_NINETY) { new_vect = (vect_t) {-1*reference_vect.y, reference_vect.x}; } return vect_mult(new_vect, magnitude / vect_mag(reference_vect)); } vect_t vect_plus(vect_t vect_a, vect_t vect_b) { return (vect_t) {vect_a.x + vect_b.x, vect_a.y + vect_b.y}; } vect_t vect_mult(vect_t vect_a, float scalar) { return (vect_t) {vect_a.x * scalar, vect_a.y * scalar}; } float vect_inner_prod(vect_t vect_a, vect_t vect_b) { return (vect_a.x * vect_b.x) + (vect_a.y * vect_b.y); } vect_t vect_get_unitvector(float rads) { return (vect_t) {cos(rads),sin(rads)}; } float vect_get_heading(vect_t vector) { return atan((float)vector.y / (float)vector.x); } //float vect_get_heading_lcd(vect_t vector) { // return atan(vector.x / (float)-1*vector.y); //} int16_t int_vect_mag(int_vect_t vector){ if (vector.x == 0. && vector.y == 0.) { return 0; } return (int16_t) sqrt(pow((vector.x),2) + pow(vector.y,2)); } int16_t int_vect_inner_prod(int_vect_t vect_a, vect_t vect_b) { return (int16_t) ((vect_a.x * vect_b.x) + (vect_a.y * vect_b.y)); } int_vect_t int_vect_parallel(int_vect_t reference_vect, int16_t magnitude) { if (int_vect_mag(reference_vect) ==0) { return (int_vect_t){0,0}; } return int_vect_mult(reference_vect, magnitude / int_vect_mag(reference_vect)); } int_vect_t int_vect_orth(int_vect_t reference_vect,int16_t magnitude, vect_orth_ref_angle_t angle){ int_vect_t new_vect = {0,0}; if (int_vect_mag(reference_vect) == 0) { return new_vect; } if (angle == RIGHT_NINETY) { new_vect = (int_vect_t) {reference_vect.y, -1* reference_vect.x}; } else if (angle == LEFT_NINETY) { new_vect = (int_vect_t) {-1*reference_vect.y, reference_vect.x}; } return int_vect_mult(new_vect, magnitude / int_vect_mag(reference_vect)); } int_vect_t int_vect_plus(int_vect_t vect_a, int_vect_t vect_b) { return (int_vect_t) {vect_a.x + vect_b.x, vect_a.y + vect_b.y}; } int_vect_t int_vect_mult(int_vect_t vect_a, int16_t scalar) { return (int_vect_t) {vect_a.x * scalar, vect_a.y * scalar}; } // not a useful function for int16_t's i don't think... // //int_vect_t int_vect_get_unitvector(int16_t degrees) { // float rads = (float) M_PI * degrees / 180 ; // return (int_vect_t) {cos(rads),sin(rads)}; // //} // gets arrow where 0 degrees is defined "straight up" when looking at the screen with buttons on the bottom //#define int_vect_LCD_get_unitvector(deg) int_vect_get_unitvector(deg - 90) //
3.03125
3
2024-11-18T20:48:33.218525+00:00
2022-03-25T13:55:33
794a3fa17ba12c63f81f07d2d80d480fc39926a3
{ "blob_id": "794a3fa17ba12c63f81f07d2d80d480fc39926a3", "branch_name": "refs/heads/master", "committer_date": "2022-03-25T13:55:33", "content_id": "2596e805c12ad8495acaa815103930494c865081", "detected_licenses": [ "MIT" ], "directory_id": "19cf5c5a22fad2e5a3ae222134f4a30812ffbbf7", "extension": "h", "filename": "maths.h", "fork_events_count": 68, "gha_created_at": "2020-09-24T01:09:14", "gha_event_created_at": "2022-07-21T22:26:46", "gha_language": "C", "gha_license_id": "MIT", "github_id": 298134035, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9462, "license": "MIT", "license_type": "permissive", "path": "/src/common/maths.h", "provenance": "stackv2-0102.json.gz:66207", "repo_name": "mgerdes/Open-Golf", "revision_date": "2022-03-25T13:55:33", "revision_id": "b9029f1e80c3110ae3d4fc9300854bdaeef96508", "snapshot_id": "6805e5a8b0378167259869e0087913ef0f77e94c", "src_encoding": "UTF-8", "star_events_count": 1319, "url": "https://raw.githubusercontent.com/mgerdes/Open-Golf/b9029f1e80c3110ae3d4fc9300854bdaeef96508/src/common/maths.h", "visit_date": "2023-08-20T13:58:13.657077" }
stackv2
#ifndef _MATHS_H #define _MATHS_H #define _USE_MATH_DEFINES #include <math.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include "common/map.h" #include "common/vec.h" #define MF_PI ((float) M_PI) #define DEGREES_PER_RADIAN 0.01745329251f #define EPSILON 0.00001f int golf_clampi(int v, int min, int max); float golf_clampf(float v, float min, float max); float golf_snapf(float v, float s); float golf_randf(float min, float max); typedef struct vec2 { float x, y; } vec2; typedef vec_t(vec2) vec_vec2_t; typedef map_t(vec2) map_vec2_t; typedef struct vec3 { float x, y, z; } vec3; typedef vec_t(vec3) vec_vec3_t; typedef map_t(vec3) map_vec3_t; typedef struct vec4 { float x, y, z, w; } vec4; typedef vec_t(vec4) vec_vec4_t; typedef map_t(vec4) map_vec4_t; typedef struct line_segment_2d { vec2 p0, p1; } line_segment_2d; /* * 4 x 4 matrices * Stored in row-order form */ typedef struct mat4 { float m[16]; } mat4; typedef struct quat { float x, y, z, w; } quat; typedef vec_t(quat) vec_quat_t; struct ray_2D { vec2 orig; vec2 dir; }; struct ray { vec3 orig; vec3 dir; }; struct bounding_box { vec3 center; vec3 half_lengths; }; struct rect_2D { vec2 top_left; vec2 size; }; struct ray_2D ray_2D_create(vec2 origin, vec2 direction); vec2 ray_2D_at_time(struct ray_2D r, float t); bool ray_2D_intersect(struct ray_2D r1, struct ray_2D r2, float *t1, float *t2); struct ray ray_create(vec3 origin, vec3 direction); struct bounding_box bounding_box_create(vec3 center, vec3 half_lengths); #define V2 vec2_create #define V3 vec3_create #define V4 vec4_create #define QUAT quat_create #define V2_ZERO V2(0.0f, 0.0f) #define V3_ZERO V3(0.0f, 0.0f, 0.0f) #define V4_ZERO V4(0.0f, 0.0f, 0.0f, 0.0f) vec2 vec2_create(float x, float y); vec2 vec2_create_from_array(float *a); vec2 vec2_sub(vec2 v1, vec2 v2); vec2 vec2_normalize(vec2 v); vec2 vec2_scale(vec2 v, float s); vec2 vec2_div(vec2 v, float s); vec2 vec2_interpolate(vec2 p0, vec2 p1, float a); float vec2_determinant(vec2 u, vec2 v); float vec2_length(vec2 v); float vec2_distance_squared(vec2 v1, vec2 v2); float vec2_distance(vec2 u, vec2 v); vec2 vec2_add_scaled(vec2 v1, vec2 v2, float s); vec2 vec2_add(vec2 v1, vec2 v2); float vec2_length_squared(vec2 v); float vec2_dot(vec2 v1, vec2 v2); float vec2_cross(vec2 u, vec2 v); vec2 vec2_reflect(vec2 u, vec2 v); vec2 vec2_parallel_component(vec2 u, vec2 v); vec2 vec2_rotate(vec2 v, float theta); vec2 vec2_perpindicular_component(vec2 u, vec2 v); vec2 vec2_set_length(vec2 v, float l); vec2 vec2_isometric_projection(vec2 v, float scale, float angle); bool vec2_point_left_of_line(vec2 point, vec2 line_p0, vec2 line_p1); bool vec2_point_right_of_line(vec2 point, vec2 line_p0, vec2 line_p1); bool vec2_lines_intersect(vec2 line0_p0, vec2 line0_p1, vec2 line1_p0, vec2 line1_p1); bool vec2_point_on_line(vec2 point, vec2 line_p0, vec2 line_p1); bool vec2_point_in_polygon(vec2 point, int num_poly_points, vec2 *poly_points); vec2 vec2_bezier(vec2 p0, vec2 p1, vec2 p2, vec2 p3, float t); bool vec2_equal(vec2 v1, vec2 v2); void vec2_print(vec2 v); vec3 vec3_create(float x, float y, float z); vec3 vec3_create_from_array(float *a); vec3 vec3_add(vec3 v1, vec3 v2); vec3 vec3_sub(vec3 v1, vec3 v2); vec3 vec3_add_scaled(vec3 v1, vec3 v2, float s); vec3 vec3_subtract(vec3 v1, vec3 v2); vec3 vec3_normalize(vec3 v); float vec3_dot(vec3 v1, vec3 v2); vec3 vec3_cross(vec3 v1, vec3 v2); vec3 vec3_apply_quat(vec3 v, float w, quat q); vec3 vec3_apply_mat4(vec3 v, float w, mat4 m); float vec3_distance(vec3 v1, vec3 v2); float vec3_distance_squared(vec3 v1, vec3 v2); vec3 vec3_set_length(vec3 v, float l); float vec3_length(vec3 v); float vec3_length_squared(vec3 v); vec3 vec3_scale(vec3 v, float s); vec3 vec3_div(vec3 v, float s); bool vec3_equal(vec3 v1, vec3 v2); vec3 vec3_rotate_x(vec3 v, float theta); vec3 vec3_rotate_y(vec3 v, float theta); vec3 vec3_rotate_z(vec3 v, float theta); vec3 vec3_rotate_about_axis(vec3 vec, vec3 axis, float theta); vec3 vec3_reflect(vec3 u, vec3 v); vec3 vec3_reflect_with_restitution(vec3 u, vec3 v, float e); vec3 vec3_parallel_component(vec3 u, vec3 v); vec3 vec3_perpindicular_component(vec3 u, vec3 v); vec3 vec3_interpolate(vec3 v1, vec3 v2, float t); vec3 vec3_from_hex_color(int hex_color); vec3 vec3_multiply(vec3 v1, vec3 v2); vec3 vec3_orthogonal(vec3 u); vec3 vec3_snap(vec3 v, float s); float vec3_distance_squared_point_line_segment(vec3 p, vec3 a, vec3 b); bool vec3_point_on_line_segment(vec3 p, vec3 a, vec3 b, float eps); bool vec3_line_segments_on_same_line(vec3 a_p0, vec3 a_p1, vec3 b_p0, vec3 b_p1, float eps); void vec3_print(vec3 v); vec4 vec4_create(float x, float y, float z, float w); vec4 vec4_add(vec4 a, vec4 b); vec4 vec4_sub(vec4 a, vec4 b); vec4 vec4_apply_mat(vec4 v, mat4 m); vec4 vec4_scale(vec4 v, float s); void vec4_normalize_this(vec4 v); void vec4_print(vec4 v); mat4 mat4_create(float a, float b, float c, float d, float e, float f, float g, float h, float i, float j, float k, float l, float m, float n, float o, float p); bool mat4_equal(mat4 m0, mat4 m1); mat4 mat4_zero(void); mat4 mat4_identity(void); mat4 mat4_translation(vec3 v); mat4 mat4_scale(vec3 v); mat4 mat4_rotation_x(float theta); mat4 mat4_rotation_y(float theta); mat4 mat4_rotation_z(float theta); mat4 mat4_shear(float theta, vec3 a, vec3 b); mat4 mat4_multiply_n(int count, ...); mat4 mat4_multiply(mat4 m1, mat4 m2); mat4 mat4_inverse(mat4 m); mat4 mat4_transpose(mat4 m); mat4 mat4_normal_transform(mat4 m); mat4 mat4_look_at(vec3 position, vec3 target, vec3 up); mat4 mat4_from_axes(vec3 x, vec3 y, vec3 z); void mat4_get_axes(mat4 m, vec3 *x, vec3 *y, vec3 *z); mat4 mat4_perspective_projection(float fov, float aspect, float near, float far); mat4 mat4_orthographic_projection(float left, float right, float bottom, float top, float near, float far); mat4 mat4_from_quat(quat q); mat4 mat4_box_inertia_tensor(vec3 half_lengths, float mass); mat4 mat4_sphere_inertia_tensor(float radius, float mass); mat4 mat4_triangle_transform(vec2 src_p1, vec2 src_p2, vec2 src_p3, vec2 dest_p1, vec2 dest_p2, vec2 dest_p3); mat4 mat4_box_to_line_transform(vec3 p0, vec3 p1, float sz); mat4 mat4_interpolate(mat4 m0, mat4 m1, float t); void mat4_print(mat4 m); quat quat_create(float x, float y, float z, float w); float quat_dot(quat v0, quat v1); quat quat_add(quat v0, quat v1); quat quat_scale(quat v, float s); quat quat_subtract(quat v0, quat v1); quat quat_create_from_axis_angle(vec3 axis, float angle); quat quat_multiply(quat u, quat v); quat quat_interpolate(quat u, quat v, float a); quat quat_slerp(quat u, quat v, float a); quat quat_normalize(quat q); quat quat_between_vectors(vec3 u, vec3 v); void quat_get_axes(quat q, vec3 *x, vec3 *y, vec3 *z); void quat_get_axis_angle(quat q, vec3 *axis, float *angle); void quat_print(quat q); struct rect_2D rect_2D_create(vec2 tl, vec2 sz); bool rect_2D_contains_point(struct rect_2D rect, vec2 pt); bool point_inside_box(vec3 p, vec3 box_center, vec3 box_half_lengths); typedef enum triangle_contact_type { TRIANGLE_CONTACT_A, TRIANGLE_CONTACT_B, TRIANGLE_CONTACT_C, TRIANGLE_CONTACT_AB, TRIANGLE_CONTACT_AC, TRIANGLE_CONTACT_BC, TRIANGLE_CONTACT_FACE, } triangle_contact_type_t; void ray_intersect_triangles_all(vec3 ro, vec3 rd, vec3 *points, int num_points, mat4 transform, float *t); bool ray_intersect_triangles_with_transform(vec3 ro, vec3 rd, vec3 *points, int num_points, mat4 transform, float *t, int *idx); bool ray_intersect_triangles(vec3 ro, vec3 rd, vec3 *points, int num_points, float *t, int *idx); bool ray_intersect_spheres(vec3 ro, vec3 rd, vec3 *center, float *radius, int num_spheres, float *t, int *idx); bool ray_intersect_segments(vec3 ro, vec3 rd, vec3 *p0, vec3 *p1, float *radius, int num_segments, float *t, int *idx); bool ray_intersect_planes(vec3 ro, vec3 rd, vec3 *p, vec3 *n, int num_planes, float *t, int *idx); bool ray_intersect_aabb(vec3 ro, vec3 rd, vec3 aabb_min, vec3 aabb_max, float *t); bool sphere_intersect_aabb(vec3 sp, float sr, vec3 aabb_min, vec3 aabb_max); bool sphere_intersect_triangles_with_transform(vec3 sp, float sr, vec3 *points, int num_points, mat4 transform, triangle_contact_type_t *type, bool *hit); void triangles_inside_box(vec3 *triangle_points, int num_triangles, vec3 box_center, vec3 box_half_lengths, bool *is_inside); void triangles_inside_frustum(vec3 *triangle_points, int num_triangles, vec3 *frustum_corners, bool *is_inside); vec3 closest_point_point_plane(vec3 point, vec3 plane_point, vec3 plane_normal); vec3 closest_point_point_circle(vec3 point, vec3 circle_center, vec3 circle_plane, float circle_radius); vec3 closest_point_point_triangle(vec3 p, vec3 a, vec3 b, vec3 c, enum triangle_contact_type *type); vec3 closest_point_point_obb(vec3 p, vec3 bc, vec3 bx, vec3 by, vec3 bz, float bex, float bey, float bez); float closest_point_ray_segment(vec3 p1, vec3 q1, vec3 p2, vec3 q2, float *s, float *t, vec3 *c1, vec3 *c2); float closest_point_ray_ray(vec3 p1, vec3 q1, vec3 p2, vec3 q2, float *s, float *t, vec3 *c1, vec3 *c2); float closest_point_ray_circle(vec3 ro, vec3 rd, vec3 cc, vec3 cn, float cr, float *s, vec3 *c1, vec3 *c2); bool intersection_moving_sphere_triangle(vec3 sc, float sr, vec3 v, vec3 tp0, vec3 tp1, vec3 tp2, float *t, vec3 *p, vec3 *n); #endif
2.421875
2
2024-11-18T20:48:33.363222+00:00
2023-07-01T07:58:33
61186a8d1b71ed4a0f55a3fd4036d48a6d25155b
{ "blob_id": "61186a8d1b71ed4a0f55a3fd4036d48a6d25155b", "branch_name": "refs/heads/develop", "committer_date": "2023-07-01T07:58:33", "content_id": "d70a4a1330602b1220605b3273f64dfdea71f1d7", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "17227ad12bc0826771ac6ac2b95dddd9517d0117", "extension": "h", "filename": "psp_pthread.h", "fork_events_count": 364, "gha_created_at": "2013-08-27T20:34:36", "gha_event_created_at": "2023-08-01T07:42:35", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 12416862, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7561, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/PVSupport/Sources/retro/libretro-common/rthreads/psp_pthread.h", "provenance": "stackv2-0102.json.gz:66336", "repo_name": "Provenance-Emu/Provenance", "revision_date": "2023-07-01T07:58:33", "revision_id": "c6f49d7921ee27eb8c0c34ca95ec9dc7baf584c1", "snapshot_id": "e38f7c81e784455d4876f8a2ff999baca0135199", "src_encoding": "UTF-8", "star_events_count": 2367, "url": "https://raw.githubusercontent.com/Provenance-Emu/Provenance/c6f49d7921ee27eb8c0c34ca95ec9dc7baf584c1/PVSupport/Sources/retro/libretro-common/rthreads/psp_pthread.h", "visit_date": "2023-08-17T05:04:01.554294" }
stackv2
/* Copyright (C) 2010-2016 The RetroArch team * * --------------------------------------------------------------------------------------- * The following license statement only applies to this file (psp_pthread.h). * --------------------------------------------------------------------------------------- * * 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. */ /* FIXME: unfinished on PSP, mutexes and condition variables basically a stub. */ #ifndef _PSP_PTHREAD_WRAP__ #define _PSP_PTHREAD_WRAP__ #ifdef VITA #include <psp2/kernel/threadmgr.h> #else #include <pspkernel.h> #include <pspthreadman.h> #include <pspthreadman_kernel.h> #endif #include <stdio.h> #include <retro_inline.h> #define STACKSIZE (8 * 1024) typedef SceUID pthread_t; typedef SceUID pthread_mutex_t; typedef void* pthread_mutexattr_t; typedef int pthread_attr_t; typedef struct { SceUID mutex; SceUID sema; int waiting; } pthread_cond_t; typedef SceUID pthread_condattr_t; /* Use pointer values to create unique names for threads/mutexes */ char name_buffer[256]; typedef void* (*sthreadEntry)(void *argp); typedef struct { void* arg; sthreadEntry start_routine; } sthread_args_struct; static int psp_thread_wrap(SceSize args, void *argp) { sthread_args_struct* sthread_args = (sthread_args_struct*)argp; return (int)sthread_args->start_routine(sthread_args->arg); } static INLINE int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg) { sprintf(name_buffer, "0x%08X", (uint32_t) thread); #ifdef VITA *thread = sceKernelCreateThread(name_buffer, psp_thread_wrap, 0x10000100, 0x10000, 0, 0, NULL); #else *thread = sceKernelCreateThread(name_buffer, psp_thread_wrap, 0x20, STACKSIZE, 0, NULL); #endif sthread_args_struct sthread_args; sthread_args.arg = arg; sthread_args.start_routine = start_routine; return sceKernelStartThread(*thread, sizeof(sthread_args), &sthread_args); } static INLINE int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr) { sprintf(name_buffer, "0x%08X", (uint32_t) mutex); #ifdef VITA *mutex = sceKernelCreateMutex(name_buffer, 0, 0, 0); if(*mutex<0) return *mutex; return 0; #else return *mutex = sceKernelCreateSema(name_buffer, 0, 1, 1, NULL); #endif } static INLINE int pthread_mutex_destroy(pthread_mutex_t *mutex) { #ifdef VITA return sceKernelDeleteMutex(*mutex); #else return sceKernelDeleteSema(*mutex); #endif } static INLINE int pthread_mutex_lock(pthread_mutex_t *mutex) { #ifdef VITA int ret = sceKernelLockMutex(*mutex, 1, 0); //sceClibPrintf("pthread_mutex_lock: %x\n",ret); return ret; #else /* FIXME: stub */ return 1; #endif } static INLINE int pthread_mutex_unlock(pthread_mutex_t *mutex) { #ifdef VITA int ret = sceKernelUnlockMutex(*mutex, 1); //sceClibPrintf("pthread_mutex_unlock: %x\n",ret); return ret; #else /* FIXME: stub */ return 1; #endif } static INLINE int pthread_join(pthread_t thread, void **retval) { #ifdef VITA int res = sceKernelWaitThreadEnd(thread, 0, 0); if (res < 0) { return res; } return sceKernelDeleteThread(thread); #else SceUInt timeout = (SceUInt)-1; sceKernelWaitThreadEnd(thread, &timeout); exit_status = sceKernelGetThreadExitStatus(thread); sceKernelDeleteThread(thread); return exit_status; #endif } static INLINE int pthread_mutex_trylock(pthread_mutex_t *mutex) { #ifdef VITA return sceKernelTryLockMutex(*mutex, 1 /* not sure about this last param */); #else /* FIXME: stub */ return 1; #endif } static INLINE int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) { #ifdef VITA int ret = pthread_mutex_lock(&cond->mutex); if (ret < 0) { return ret; } ++cond->waiting; pthread_mutex_unlock(mutex); pthread_mutex_unlock(&cond->mutex); ret = sceKernelWaitSema(cond->sema, 1, 0); if (ret < 0) { sceClibPrintf("Premature wakeup: %08X", ret); } pthread_mutex_lock(mutex); return ret; #else /* FIXME: stub */ sceKernelDelayThread(10000); return 1; #endif } static INLINE int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) { #ifdef VITA int ret = pthread_mutex_lock(&cond->mutex); if (ret < 0) { return ret; } ++cond->waiting; pthread_mutex_unlock(mutex); pthread_mutex_unlock(&cond->mutex); SceUInt timeout = 0; timeout = abstime->tv_sec; timeout += abstime->tv_nsec / 1.0e6; ret = sceKernelWaitSema(cond->sema, 1, &timeout); if (ret < 0) { sceClibPrintf("Premature wakeup: %08X", ret); } pthread_mutex_lock(mutex); return ret; #else /* FIXME: stub */ return 1; #endif } static INLINE int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr) { #ifdef VITA pthread_mutex_init(&cond->mutex,NULL); sceClibPrintf("pthread_cond_init: mutex %x\n",cond->mutex); if(cond->mutex<0){ return cond->mutex; } sprintf(name_buffer, "0x%08X", (uint32_t) cond); //cond->sema = sceKernelCreateCond(name_buffer, 0, cond->mutex, 0); cond->sema = sceKernelCreateSema(name_buffer, 0, 0, 1, 0); sceClibPrintf("pthread_cond_init: sema %x\n",cond->sema); if(cond->sema<0){ pthread_mutex_destroy(&cond->mutex); return cond->sema; } cond->waiting = 0; return 0; #else /* FIXME: stub */ return 1; #endif } static INLINE int pthread_cond_signal(pthread_cond_t *cond) { #ifdef VITA pthread_mutex_lock(&cond->mutex); if (cond->waiting) { --cond->waiting; int ret = sceKernelSignalSema(cond->sema, 1); sceClibPrintf("pthread_cond_signal: %x\n",ret); } pthread_mutex_unlock(&cond->mutex); return 0; #else /* FIXME: stub */ return 1; #endif } static INLINE int pthread_cond_broadcast(pthread_cond_t *cond) { /* FIXME: stub */ return 1; } static INLINE int pthread_cond_destroy(pthread_cond_t *cond) { #ifdef VITA int ret = sceKernelDeleteSema(cond->sema); if(ret < 0) return ret; return sceKernelDeleteMutex(cond->mutex); #else /* FIXME: stub */ return 1; #endif } static INLINE int pthread_detach(pthread_t thread) { return 0; } static INLINE void pthread_exit(void *retval) { #ifdef VITA sceKernelExitDeleteThread(sceKernelGetThreadId()); #endif } static INLINE pthread_t pthread_self(void) { /* zero 20-mar-2016: untested */ return sceKernelGetThreadId(); } static INLINE int pthread_equal(pthread_t t1, pthread_t t2) { return t1 == t2; } #endif //_PSP_PTHREAD_WRAP__
2.046875
2
2024-11-18T20:48:33.534485+00:00
2021-04-05T07:13:29
5eba4715fc9e33a230521b55c2d315db7b421cc9
{ "blob_id": "5eba4715fc9e33a230521b55c2d315db7b421cc9", "branch_name": "refs/heads/master", "committer_date": "2021-04-05T07:13:29", "content_id": "a50aeafae862d3a289e1a72143dc5d60971fc6f9", "detected_licenses": [ "MIT" ], "directory_id": "7f6c77b9989fbb289ff50c73184eca8e27743215", "extension": "h", "filename": "IdGenOptions.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": 1143, "license": "MIT", "license_type": "permissive", "path": "/C/source/idgen/IdGenOptions.h", "provenance": "stackv2-0102.json.gz:66465", "repo_name": "ywscr/IdGenerator", "revision_date": "2021-04-05T07:13:29", "revision_id": "c1ae192931bcf8db9b2a1655c957d4198e6f75aa", "snapshot_id": "912c24d63d85de5110043aad98f9fc1ed0dbac40", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ywscr/IdGenerator/c1ae192931bcf8db9b2a1655c957d4198e6f75aa/C/source/idgen/IdGenOptions.h", "visit_date": "2023-03-27T21:37:23.181307" }
stackv2
/* * 版权属于:yitter(yitter@126.com) * 开源地址:https://gitee.com/yitter/idgenerator */ #pragma once #include <stdint.h> typedef struct IdGenOptions { /// 雪花计算方法,(1-漂移算法|2-传统算法),默认1 uint8_t Method; /// 基础时间(ms单位),不能超过当前系统时间 uint64_t BaseTime; /// 机器码,与 WorkerIdBitLength 有关系 uint32_t WorkerId; /// 机器码位长,范围:1-21(要求:序列数位长+机器码位长不超过22) uint8_t WorkerIdBitLength; /// 序列数位长,范围:2-21(要求:序列数位长+机器码位长不超过22) uint8_t SeqBitLength; /// 最大序列数(含),(由 SeqBitLength 计算的最大值) uint32_t MaxSeqNumber; /// 最小序列数(含),默认5,不小于5,不大于 MaxSeqNumber uint32_t MinSeqNumber; /// 最大漂移次数(含),默认2000,推荐范围 500-20000(与计算能力有关) uint32_t TopOverCostCount; } IdGeneratorOptions; extern IdGeneratorOptions BuildIdGenOptions(uint32_t workerId);
2.3125
2
2024-11-18T20:48:33.769026+00:00
2015-06-06T10:41:39
4c37f3cd61e01cce66a178dd8880612c61293ebc
{ "blob_id": "4c37f3cd61e01cce66a178dd8880612c61293ebc", "branch_name": "refs/heads/master", "committer_date": "2015-06-06T10:41:39", "content_id": "36c19fe2dcbdd753da85c9841574cd686560fc47", "detected_licenses": [ "MIT" ], "directory_id": "90d45d5ed3effdfb76a71961ae70fcd504ea343e", "extension": "c", "filename": "list.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 21331329, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2136, "license": "MIT", "license_type": "permissive", "path": "/src/list.c", "provenance": "stackv2-0102.json.gz:66593", "repo_name": "jon-stewart/replicaters", "revision_date": "2015-06-06T10:41:39", "revision_id": "b2f8eaced126e263cf92288cd1c0c92924e94db0", "snapshot_id": "0981b3d354720a5bd268be1a2b931266ee50c420", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jon-stewart/replicaters/b2f8eaced126e263cf92288cd1c0c92924e94db0/src/list.c", "visit_date": "2016-09-15T20:08:45.534009" }
stackv2
#include <stdlib.h> #include <assert.h> #include <list.h> void list_init(list_t *list) { list->next = list->prev = list; } void list_add(list_t *head, list_t *list) { list_t *prev; assert(head != NULL); assert(list != NULL); prev = head->prev; /* if list is empty */ if (head->prev == head) { head->next = list; } else { prev->next = list; } head->prev = list; list->prev = prev; list->next = head; } list_t * list_rm_front(list_t *head) { list_t *list = NULL; assert(head != NULL); if (!list_empty(head)) { list = head->next; head->next = list->next; head->next->prev = head; } return (list); } list_t * list_rm_back(list_t *head) { list_t *list = NULL; assert(head != NULL); if (!list_empty(head)) { list = head->prev; head->prev = list->prev; head->prev->next = head; } return (list); } void list_rm(list_t *ele) { list_t *prev = ele->prev; list_t *next = ele->next; prev->next = next; next->prev = prev; ele->prev = NULL; ele->next = NULL; } static void list_insert(list_t *prev, list_t *list, list_t *next) { prev->next = list; list->prev = prev; list->next = next; next->prev = list; } void list_add_sorted(list_t *head, list_t *list, sort_fn func) { list_t *ptr = NULL; list_t *prev = NULL; int loc = 0; assert(head != NULL); assert(list != NULL); assert(func != NULL); if (list_empty(head)) { list_add(head, list); return; } prev = head; LIST_FOR_EACH(head, ptr) { loc = func(ptr, list); switch (loc) { case -1: { list_insert(prev, list, ptr); return; } case 0: { list_insert(prev, list, ptr); return; } case 1: { prev = ptr; break; } default: { assert(0); } } } list_insert(prev, list, head); }
2.953125
3
2024-11-18T20:48:34.082052+00:00
2014-05-05T17:33:31
36d21207431a0f01ccffceb9cde60889a9f9369b
{ "blob_id": "36d21207431a0f01ccffceb9cde60889a9f9369b", "branch_name": "refs/heads/master", "committer_date": "2014-05-05T17:33:31", "content_id": "4a4dee51beff8088e245250de6b2efbf60f7658b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ca0b220bc0e3d65b2ea19985dda2817dafa37406", "extension": "c", "filename": "hashtable.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": 9907, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/hashtable.c", "provenance": "stackv2-0102.json.gz:66850", "repo_name": "mnunberg/typelib", "revision_date": "2014-05-05T17:33:31", "revision_id": "e28e284d5d3d040038027a17e196d93b8950b9d9", "snapshot_id": "2794bc89aca83741643fa04f06008c3dc09fa8b2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mnunberg/typelib/e28e284d5d3d040038027a17e196d93b8950b9d9/src/hashtable.c", "visit_date": "2021-01-24T15:05:45.213846" }
stackv2
/* * Copyright (c) 2006 Dustin Sallings <dustin@spy.net> */ #include <math.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include "tl_hashtable.h" /* Table of 32 primes by their distance from the nearest power of two */ static size_t prime_size_table[] = { 3, 7, 13, 23, 47, 97, 193, 383, 769, 1531, 3067, 6143, 12289, 24571, 49157, 98299, 196613, 393209, 786433, 1572869, 3145721, 6291449, 12582917, 25165813, 50331653, 100663291, 201326611, 402653189, 805306357, 1610612741 }; #define TABLE_SIZE ((int)(sizeof(prime_size_table) / sizeof(int))) struct genhash_entry_t { /** The key for this entry */ void *key; /** Size of the key */ size_t nkey; /** The value for this entry */ void *value; /** Size of the value */ size_t nvalue; /** Pointer to the next entry */ struct genhash_entry_t *next; }; struct _genhash { size_t size; struct tl_HASHOPS ops; struct genhash_entry_t *buckets[]; }; static size_t estimate_table_size(size_t est); static void *dup_key(tl_HASHTABLE *h, const void *key, size_t klen) { if (h->ops.dup_key != NULL) { return h->ops.dup_key(key, klen); } else { return (void *)key; } } static void *dup_value(tl_HASHTABLE *h, const void *value, size_t vlen) { if (h->ops.dup_value != NULL) { return h->ops.dup_value(value, vlen); } else { return (void *)value; } } static void free_key(tl_HASHTABLE *h, void *key) { if (h->ops.free_key != NULL) { h->ops.free_key(key); } } static void free_value(tl_HASHTABLE *h, void *value) { if (h->ops.free_value != NULL) { h->ops.free_value(value); } } static size_t estimate_table_size(size_t est) { size_t rv = 0; while (prime_size_table[rv] < est && rv + 1 < TABLE_SIZE) { rv++; } return prime_size_table[rv]; } void tl_ht_free(tl_HASHTABLE *h) { if (h != NULL) { tl_ht_clear(h); free(h); } } int tl_ht_store(tl_HASHTABLE *h, const void *k, size_t klen, const void *v, size_t vlen) { size_t n = 0; struct genhash_entry_t *p; assert(h != NULL); n = h->ops.hashfunc(k, klen) % h->size; assert(n < h->size); p = calloc(1, sizeof(struct genhash_entry_t)); if (!p) { return -1; } p->key = dup_key(h, k, klen); p->nkey = klen; p->value = dup_value(h, v, vlen); p->nvalue = vlen; p->next = h->buckets[n]; h->buckets[n] = p; return 0; } static struct genhash_entry_t *genhash_find_entry(tl_HASHTABLE *h, const void *k, size_t klen) { size_t n = 0; struct genhash_entry_t *p; assert(h != NULL); n = h->ops.hashfunc(k, klen) % h->size; assert(n < h->size); p = h->buckets[n]; for (p = h->buckets[n]; p && !h->ops.hasheq(k, klen, p->key, p->nkey); p = p->next); return p; } void *tl_ht_find(tl_HASHTABLE *h, const void *k, size_t klen) { struct genhash_entry_t *p; void *rv = NULL; p = genhash_find_entry(h, k, klen); if (p) { rv = p->value; } return rv; } enum tl_UPDATETYPE tl_ht_update(tl_HASHTABLE *h, const void *k, size_t klen, const void *v, size_t vlen) { struct genhash_entry_t *p; enum tl_UPDATETYPE rv = 0; p = genhash_find_entry(h, k, klen); if (p) { free_value(h, p->value); p->value = dup_value(h, v, vlen); rv = MODIFICATION; } else { if (-1 == tl_ht_store(h, k, klen, v, vlen)) { rv = ALLOC_FAILURE; } rv = NEW; } return rv; } enum tl_UPDATETYPE tl_ht_funupdate(tl_HASHTABLE *h, const void *k, size_t klen, void * (*upd)(const void *, const void *, size_t *, void *), void (*fr)(void *), void *arg, const void *def, size_t deflen) { struct genhash_entry_t *p; enum tl_UPDATETYPE rv = 0; size_t newSize = 0; p = genhash_find_entry(h, k, klen); if (p) { void *newValue = upd(k, p->value, &newSize, arg); free_value(h, p->value); p->value = dup_value(h, newValue, newSize); fr(newValue); rv = MODIFICATION; } else { void *newValue = upd(k, def, &newSize, arg); tl_ht_store(h, k, klen, newValue, newSize); fr(newValue); rv = NEW; } (void)deflen; return rv; } static void free_item(tl_HASHTABLE *h, struct genhash_entry_t *i) { assert(i); free_key(h, i->key); free_value(h, i->value); free(i); } int tl_ht_del(tl_HASHTABLE *h, const void *k, size_t klen) { struct genhash_entry_t *deleteme = NULL; size_t n = 0; int rv = 0; assert(h != NULL); n = h->ops.hashfunc(k, klen) % h->size; assert(n < h->size); if (h->buckets[n] != NULL) { /* Special case the first one */ if (h->ops.hasheq(h->buckets[n]->key, h->buckets[n]->nkey, k, klen)) { deleteme = h->buckets[n]; h->buckets[n] = deleteme->next; } else { struct genhash_entry_t *p = NULL; for (p = h->buckets[n]; deleteme == NULL && p->next != NULL; p = p->next) { if (h->ops.hasheq(p->next->key, p->next->nkey, k, klen)) { deleteme = p->next; p->next = deleteme->next; } } } } if (deleteme != NULL) { free_item(h, deleteme); rv++; } return rv; } int tl_ht_delall(tl_HASHTABLE *h, const void *k, size_t klen) { int rv = 0; while (tl_ht_del(h, k, klen) == 1) { rv++; } return rv; } void tl_ht_iter(tl_HASHTABLE *h, void (*iterfunc)(const void *key, size_t nkey, const void *val, size_t nval, void *arg), void *arg) { size_t i = 0; struct genhash_entry_t *p = NULL; assert(h != NULL); for (i = 0; i < h->size; i++) { for (p = h->buckets[i]; p != NULL; p = p->next) { iterfunc(p->key, p->nkey, p->value, p->nvalue, arg); } } } int tl_ht_clear(tl_HASHTABLE *h) { size_t i = 0; int rv = 0; assert(h != NULL); for (i = 0; i < h->size; i++) { while (h->buckets[i]) { struct genhash_entry_t *p = NULL; p = h->buckets[i]; h->buckets[i] = p->next; free_item(h, p); } } return rv; } static void count_entries(const void *key, size_t klen, const void *val, size_t vlen, void *arg) { int *count = (int *)arg; (*count)++; (void)key; (void)klen; (void)val; (void)vlen; } int tl_ht_size(tl_HASHTABLE *h) { int rv = 0; assert(h != NULL); tl_ht_iter(h, count_entries, &rv); return rv; } int tl_ht_sizekey(tl_HASHTABLE *h, const void *k, size_t klen) { int rv = 0; assert(h != NULL); tl_ht_iterkey(h, k, klen, count_entries, &rv); return rv; } void tl_ht_iterkey(tl_HASHTABLE *h, const void *key, size_t klen, void (*iterfunc)(const void *key, size_t klen, const void *val, size_t vlen, void *arg), void *arg) { size_t n = 0; struct genhash_entry_t *p = NULL; assert(h != NULL); n = h->ops.hashfunc(key, klen) % h->size; assert(n < h->size); for (p = h->buckets[n]; p != NULL; p = p->next) { if (h->ops.hasheq(key, klen, p->key, p->nkey)) { iterfunc(p->key, p->nkey, p->value, p->nvalue, arg); } } } int tl_ht_strhash(const void *p, size_t nkey) { int rv = 5381; int i = 0; char *str = (char *)p; for (i = 0; i < (int)nkey; i++) { assert(str[i]); rv = ((rv << 5) + rv) ^ str[i]; } return rv; } tl_HASHTABLE* tl_ht_new(size_t est, struct tl_HASHOPS ops) { tl_HASHTABLE *rv = NULL; size_t size = 0; if (est < 1) { return NULL ; } assert(ops.hashfunc != NULL); assert(ops.hasheq != NULL); assert((ops.dup_key != NULL && ops.free_key != NULL) || ops.free_key == NULL); assert((ops.dup_value != NULL && ops.free_value != NULL) || ops.free_value == NULL); size = estimate_table_size(est); rv = calloc(1, sizeof(tl_HASHTABLE) + (size * sizeof(struct genhash_entry_t*))); if (rv == NULL ) { return NULL ; } rv->size = size; rv->ops = ops; return rv; } /** * Convenience functions for creating string-based hashes */ static int hasheq_strp(const void *a, size_t na, const void *b, size_t nb) { if (na != nb) { return 0; } return memcmp(a, b, na) == 0; } static struct tl_HASHOPS hashops_nocopy = { tl_ht_strhash, hasheq_strp, NULL, NULL, NULL, NULL }; static int u32_hash(const void *p, size_t n) { (void)p; return n; } static int u32_eq(const void *a, size_t na, const void *b, size_t nb) { (void)a; (void)b; return na == nb; } static struct tl_HASHOPS hashops_u32 = { u32_hash, u32_eq, NULL, NULL, NULL, NULL }; tl_pHASHTABLE tl_ht_stringnc_new(size_t est) { return tl_ht_new(est, hashops_nocopy); } tl_pHASHTABLE tl_ht_szt_new(size_t est) { return tl_ht_new(est, hashops_u32); }
2.859375
3
2024-11-18T20:48:35.146048+00:00
2022-08-02T21:57:35
8e0fb225dbfacd2df88008e740562a1258ca171d
{ "blob_id": "8e0fb225dbfacd2df88008e740562a1258ca171d", "branch_name": "refs/heads/master", "committer_date": "2022-08-02T21:57:35", "content_id": "23ad253dbfd4183901b6952e965c52f9384fe820", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c607ff8108397f871ff26c8f08ea524043b96ae5", "extension": "c", "filename": "multi_perf.c", "fork_events_count": 22, "gha_created_at": "2014-09-10T21:05:11", "gha_event_created_at": "2023-08-28T23:10:28", "gha_language": "JavaScript", "gha_license_id": "Apache-2.0", "github_id": 23892201, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13848, "license": "Apache-2.0", "license_type": "permissive", "path": "/gooda-analyzer/multi_perf.c", "provenance": "stackv2-0102.json.gz:67880", "repo_name": "David-Levinthal/gooda", "revision_date": "2022-08-02T21:57:35", "revision_id": "84507e8f4a1dbc81d1cfac29b1b0e2777bbceaa8", "snapshot_id": "026cedc581c4a3ee35dc398bdfdaa2532d9f4f0d", "src_encoding": "UTF-8", "star_events_count": 70, "url": "https://raw.githubusercontent.com/David-Levinthal/gooda/84507e8f4a1dbc81d1cfac29b1b0e2777bbceaa8/gooda-analyzer/multi_perf.c", "visit_date": "2023-09-01T11:30:33.561046" }
stackv2
/* Copyright 2012 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <stddef.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <getopt.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> #include "perf_event.h" #include "gooda.h" #include "perf_gooda.h" #include "gooda_util.h" typedef struct properties * properties_ptr; typedef struct properties{ char* arch; char* cpu_desc; char* path; int family; int model; int num_col; int num_cores; int num_sockets; int num_fixed; int num_ordered; int num_branch; int num_sub_branch; } properties_data; typedef struct csv_field_pointer * csv_field_pointer_ptr; typedef struct csv_field_pointer{ csv_field_pointer_ptr next; csv_field_pointer_ptr previous; char * csv_field; }csv_field_pointer_data; char prop_str[] = "platform_properties.txt"; char func_str[] = "function_hotspots.csv"; char proc_str[] = "process.csv"; char spreadsheets[] = "/spreadsheets/"; int prop_len=23,func_len=21, proc_len=11, spread_len=14; int dbg_count = 0; properties_data * input_properties; event_order_struc_ptr *input_order, global_event_order; char* extract_input_string(char* instr, char key, int index, int* next) { int i,j,k,len; char* ret_string; len = strlen(instr); i = 0; while((instr[i] != key) && (i <= len))i++; if(i == len) err(1,"unrecognized input string in read_platform_properties for index = %d, string = %s",index,instr); j=i+1; while((instr[j] != '\n') && (instr[j] != ',') && (j <= len))j++; *next = j+1; len = j - i - 1; ret_string = malloc(len+1); if(ret_string == NULL) err(1,"extract_input_string failled to malloc return string of length %d for processing %s",len,instr); strncpy(ret_string,&instr[i+1],len); ret_string[len]='\0'; // fprintf(stderr," address of instr = %p, i = %d, j = %d, return_string = %s\n",instr,i,j,ret_string); return ret_string; } char* extract_csv_field(char* instr, int index, int* next) { int i,j,k,len; char* ret_string; len = strlen(instr); i = 0; while((instr[i] != ',') && (instr[i] != '\n') && (i <= len)) { if(instr[i] == '"') { i++; while(instr[i] != '"')i++; } i++; } if(i >= len) err(1,"unrecognized input string in read_platform_properties for index = %d, string = %s",index,instr); len = i; *next = i+1; if((i == 0) && (instr[i] == '\n'))len++; if((i == 1) && (instr[i] == '\n'))len++; ret_string = malloc(len+1); if(ret_string == NULL) err(1,"extract_input_string failled to malloc return string of length %d for processing %s",len,instr); strncpy(ret_string,instr,len); ret_string[len]='\0'; if(dbg_count < 100) { fprintf(stderr," address of instr = %p, i = %d, return_string = %s\n",instr,i,ret_string); dbg_count++; } return ret_string; } char* read_file(char* local_path) { FILE *fdesc; int access_status; char* input_str; long file_size, test; access_status = access(local_path, R_OK); if(access_status != 0) err(1,"cannot find the platform_properties.txt file from path %s",local_path); fdesc = fopen(local_path, "r"); if(fdesc == NULL) err(1, "failed to open file %s\n",local_path); fseek(fdesc, 0, SEEK_END); file_size = ftell(fdesc); rewind(fdesc); input_str = (char*)malloc(sizeof(char)*file_size); if(input_str == NULL) err(1," failed to malloc buffer for reading input file %s size = %ld",local_path,file_size); test = fread(input_str,1,file_size,fdesc); if(test != file_size) err(1,"read size, %ld != file_size %ld for file %s",test,file_size,local_path); return input_str; } int read_platform_properties(int index) { int i,j,k,len,ret=0, access_status, test; char * local_prop, *input_str, *ret_str; FILE * pr; long file_size; int begin_line=0, read_start = 0;; len = strlen(input_properties[index].path); // fprintf(stderr," index = %d, len = %d, path = %s\n",index,len,input_properties[index].path); local_prop = malloc(len + spread_len + prop_len + 1); if(local_prop == NULL) err(1,"malloc failed for input properties index = %d",index); strncpy(local_prop, input_properties[index].path, len); local_prop[len] = '\0'; // fprintf(stderr,"local_prop = %s\n",local_prop); strncpy(&local_prop[len], spreadsheets, spread_len); local_prop[len+spread_len] = '\0'; // fprintf(stderr,"local_prop = %s\n",local_prop); strncpy(&local_prop[len+spread_len], prop_str, prop_len); // for(i=0; i < len; i++)local_prop[i] = input_properties[index].path[i]; // for(i=len; i < len + spread_len; i++)local_prop[i] = spreadsheets[i-len]; // for(i=len + spread_len; i < len + spread_len + prop_len; i++)local_prop[i] = prop_str[i-len-spread_len]; local_prop[len + spread_len + prop_len] = '\0'; fprintf(stderr,"local_prop = %s\n",local_prop); input_str = read_file(local_prop); if(input_str == NULL) err(1,"read_file returned a NULL pointer for index %d path = %s",index,local_prop); len = strlen(input_str); fprintf(stderr," length of input_str = %d\n",len); // fprintf(stderr,"input_str = \n"); // fprintf(stderr,"%s\n",input_str); input_properties[index].arch = extract_input_string(input_str, ':', index, &begin_line); read_start+=begin_line; input_properties[index].family = atoi(extract_input_string(&input_str[read_start], ':', index, &begin_line)); read_start+=begin_line; input_properties[index].model = atoi(extract_input_string(&input_str[read_start], ':', index, &begin_line)); read_start+=begin_line; input_properties[index].num_sockets = atoi(extract_input_string(&input_str[read_start], ':', index, &begin_line)); read_start+=begin_line; input_properties[index].num_cores = atoi(extract_input_string(&input_str[read_start], ':', index, &begin_line)); read_start+=begin_line; input_properties[index].num_col = atoi(extract_input_string(&input_str[read_start], ':', index, &begin_line)); read_start+=begin_line; input_properties[index].cpu_desc = extract_input_string(&input_str[read_start], ':', index, &begin_line); read_start+=begin_line; input_properties[index].num_fixed = atoi(extract_input_string(&input_str[read_start], ':', index, &begin_line)); read_start+=begin_line; input_properties[index].num_ordered = atoi(extract_input_string(&input_str[read_start], ':', index, &begin_line)); read_start+=begin_line; input_properties[index].num_branch = atoi(extract_input_string(&input_str[read_start], ':', index, &begin_line)); read_start+=begin_line; input_properties[index].num_sub_branch = atoi(extract_input_string(&input_str[read_start], ':', index, &begin_line)); fprintf(stderr,"arch = %s\n",input_properties[index].arch); fprintf(stderr,"cpu_desc = %s\n",input_properties[index].cpu_desc); fprintf(stderr,"family = %d, model = %d\n",input_properties[index].family,input_properties[index].model); fprintf(stderr,"num_sockets = %d, num_cores = %d\n",input_properties[index].num_sockets,input_properties[index].num_cores); fprintf(stderr,"num_col = %d\n",input_properties[index].num_col); fprintf(stderr,"num_fixed = %d, num_ordered = %d\n",input_properties[index].num_fixed,input_properties[index].num_ordered); fprintf(stderr,"num_branch = %d, num_sub_branch = %d\n",input_properties[index].num_branch,input_properties[index].num_sub_branch); return 0; } int read_func_table(int index) { int i,j,k,len,ret=0, field_len, fields_per_line=0, lines=0;; char * local_func, *input_str, *ret_str; FILE *func_tab; long file_size; int begin_line=0, read_start=0; len = strlen(input_properties[index].path); // fprintf(stderr," index = %d, len = %d, path = %s\n",index,len,input_properties[index].path); local_func = malloc(len + spread_len + func_len + 1); if(local_func == NULL) err(1,"malloc failed for input properties index = %d",index); strncpy(local_func, input_properties[index].path, len); local_func[len] = '\0'; // fprintf(stderr,"local_func = %s\n",local_func); strncpy(&local_func[len], spreadsheets, spread_len); local_func[len+spread_len] = '\0'; // fprintf(stderr,"local_func = %s\n",local_func); strncpy(&local_func[len+spread_len], func_str, func_len); local_func[len + spread_len + func_len] = '\0'; fprintf(stderr,"local_func = %s\n",local_func); input_str = read_file(local_func); if(input_str == NULL) err(1,"read_file returned a NULL pointer for index %d path = %s",index,local_func); len = strlen(input_str); fprintf(stderr," length of input_str = %d\n",len); while(read_start < len) { ret_str = extract_csv_field(&input_str[read_start],index,&begin_line); fields_per_line++; // field_len = strlen(ret_str); field_len = begin_line-1; if(ret_str[field_len] == '\n') { lines++; fprintf(stderr,"line number %d, fields_per_line = %d\n",lines,fields_per_line); fields_per_line = 0; } read_start+=begin_line; } return 0; } int read_proc_table(int index) { int i,j,k,len,ret=0; char * local_func, *local_proc; return 0; } void usage() { fprintf(stderr,"multi_perf creates a new ./spreadsheets tree by summing the table contents\n"); fprintf(stderr,"from the spreadsheet directories in a list of input report directory paths or\n"); fprintf(stderr,"by taking the difference of the tables in the spreadsheet directories of 2 report paths\n"); fprintf(stderr,"The first argument must be -n followed by the number of report directories to come (with or without a space)\n"); fprintf(stderr," each report directory path (absolute or relative) is input with the -d flag, one directory for each -d\n"); fprintf(stderr," -a (with no argument value) indicates the tables should be summed\n"); fprintf(stderr," -s (with no argument value) indicates a subtraction of the table data and the value for -n MUST be 2\n"); fprintf(stderr," -h produces this output\n"); } int main( int argc, char** argv) { int i,j,k,dir=0,len,len1,ret; int num_dir=0, add = 0, sub = 0; int c; char* path_buf; fprintf(stderr,"argc = %d\n",argc); for(i=0;i<argc; i++)fprintf(stderr,"argv[%d] = %s\n",i,argv[i]); while ((c= getopt(argc, argv, "h:n:d:a:s")) != -1) { switch(c) { case 'h': usage(); exit(0); case 'n': num_dir = atoi(optarg); fprintf(stderr," num_dir = %d, sizeof(properties_data) = %ld\n",num_dir, sizeof(properties_data)); // malloc array of structures for the platform properites data input_properties = (properties_data*)calloc(1,(num_dir+1)*sizeof(properties_data)); fprintf(stderr,"finished calloc for properties_data at %p\n",input_properties); if(input_properties == NULL) err(1," failed to malloc buffer for input_properties array"); break; case 'd': fprintf(stderr,"argument = -d\n"); if(num_dir == 0){ usage(); err(1,"the number of directories argument -n must appear before any of the directory arguments, -d"); } fprintf(stderr,"address of optarg = %p\n",optarg); fprintf(stderr," -d arg = %s\n",optarg); len = strlen(optarg); if(dir < num_dir){ dir++; // fprintf(stderr,"address of *path = %p\n",&input_properties[dir].path); // for(i=0;i<=num_dir;i++)fprintf(stderr," loop index %d, address of *path = %p\n",i,&input_properties[i].path); // path_buf = (char*)malloc(len+1); // if(path_buf == NULL) // err(1,"cannot malloc buffer for path %d, len = %d",dir,len); // for(i=0; i<len; i++)path_buf[i] = optarg[i]; // path_buf[len] = '\0'; // fprintf(stderr,"address of path_buf = %p, path_buf = %s\n",path_buf,path_buf); input_properties[dir].path = (char*)malloc(len+1); if(input_properties[dir].path == NULL) err(1,"cannot malloc buffer for path %d, len = %d",dir,len); for(i=0; i<len; i++)input_properties[dir].path[i] = optarg[i]; input_properties[dir].path[len] = '\0'; // input_properties[dir].path = path_buf; len1 = strlen(input_properties[dir].path); // fprintf(stderr," dir = %d, len = %d, len1 = %d, path = %s\n",dir,len,len1,input_properties[dir].path); // fprintf(stderr,"address of path = %p, = %p\n",&input_properties[dir].path,&input_properties[dir].path[0]); // for(i=1;i<=dir;i++){ // len1 = strlen(input_properties[i].path); // fprintf(stderr," dir = %d, len1 = %d, path = %s, address = %p\n",i,len1,input_properties[i].path,input_properties[i].path); // } break; } else{ err(1," more directories listed with -d flag than were declared with -n"); } case 'a': fprintf(stderr," -a arg, num_dir = %d, sub = %d\n",num_dir,sub); if((sub != 0) || (num_dir < 2)) err(1," cannot set both -a and -s or value of -n argument less than 2"); add = 1; break; case 's': if((add != 0) || (num_dir < 2)) err(1," cannot set both -a and -s or value of -n argument less than 2"); sub = 1; break; default: errx(1, "invalid argument key"); } } fprintf(stderr,"exited input arg case statement\n"); // create_dir(); for(i=1; i<=num_dir; i++) { len1 = strlen(input_properties[i].path); fprintf(stderr," i = %d, len1 = %d, path = %s\n",i,len1,input_properties[i].path); ret = read_platform_properties(i); if(ret != 0) err(1,"could not read platform properties for path %d = %s",i,input_properties[i].path); ret = read_func_table(i); if(ret != 0) err(1,"could not read function table for path %d = %s",i,input_properties[i].path); } }
2.21875
2
2024-11-18T20:48:35.391391+00:00
2019-10-18T10:55:28
35fcde62a0774416f2de543fd0f9a82bfa6db188
{ "blob_id": "35fcde62a0774416f2de543fd0f9a82bfa6db188", "branch_name": "refs/heads/master", "committer_date": "2019-10-18T10:55:28", "content_id": "9a1db93a9a36a1a2c3c4084cbe74bb0f645852b0", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f3a6b045ebf824603cfc27bd010215e2c62410f9", "extension": "c", "filename": "io.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 211590383, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2787, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/driver/io.c", "provenance": "stackv2-0102.json.gz:68136", "repo_name": "wookong-dot/solo", "revision_date": "2019-10-18T10:55:28", "revision_id": "ed55d0c7e30c6e6cd9c0f0fb6b6711d31a1c468a", "snapshot_id": "eacf362c6710a9fb2cfd57ff65b15f3b6c2b5453", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wookong-dot/solo/ed55d0c7e30c6e6cd9c0f0fb6b6711d31a1c468a/src/driver/io.c", "visit_date": "2020-08-03T01:58:59.074218" }
stackv2
#include "def.h" #include "uart.h" #include "crc.h" #include "io.h" SOLO_INTERNAL UINT32 gen_cmd(UINT8 cmd_index, UINT8* data, UINT16 data_len, UINT8* cmd, UINT16* len) { UINT8 header[SOLO_HEADER_LEN] = {SOLO_SYNC_1, SOLO_SYNC_2, 0, 0, 0, 0, 0, 0}; UINT8 crc[SOLO_CRC_LEN] = { 0 }; UINT32 rv = 0 ; //para check if(data_len > 0x1000) return SOLO_ERROR_PARA; if(cmd==0) return SOLO_ERROR_PARA; //gen header header[SOLO_CMD_OFFSET] = cmd_index; if(data_len>0) { header[SOLO_LEN_OFFSET] = (UINT8)((data_len>>8)&0x00ff); header[SOLO_LEN_OFFSET+1] = (UINT8)(data_len&0x00ff); } memcpy(cmd,header,SOLO_HEADER_LEN); //gen data if have if(data_len>0&&data!=0) { memcpy(cmd+SOLO_HEADER_LEN,data, data_len); } //gen crc rv = calc_crc(cmd,SOLO_HEADER_LEN+data_len,crc); if (rv) return SOLO_ERROR_CRC; memcpy(cmd+SOLO_HEADER_LEN+data_len,crc,SOLO_CRC_LEN); *len = SOLO_HEADER_LEN + data_len + SOLO_CRC_LEN; return SOLO_OK; } SOLO_INTERNAL UINT32 handle_cmd(UINT8* cmd, UINT16 cmd_len,UINT32 delays, UINT8* response, UINT16* len) { UINT32 rv = 0; UINT16 l = 0; rv = SOLO_uart_write(cmd, cmd_len); if (rv) return SOLO_ERROR_COMM; usleep(delays); rv = SOLO_uart_read(response, SOLO_SIMPLE_CMD_LEN); if (rv) return SOLO_ERROR_COMM; //sync if (response[SOLO_COMM_OFFSET] != SOLO_OK) return response[SOLO_COMM_OFFSET]; if (response[SOLO_OP_OFFSET] != SOLO_OK) return response[SOLO_OP_OFFSET]; l = response[SOLO_LEN_OFFSET]*256 + response[SOLO_LEN_OFFSET+1]; if(l>0) { rv = SOLO_uart_read(response+SOLO_SIMPLE_CMD_LEN, l); if (rv) return SOLO_ERROR_COMM; } // rv = check_crc(response, SOLO_HEADER_LEN+l, response + SOLO_HEADER_LEN+l); // if (rv) // return SOLO_ERROR_CRC; *len = l; return SOLO_OK; } SOLO_INTERNAL UINT32 get_response(UINT8* response, UINT16* len) { UINT16 l = 0; UINT32 rv = 0; usleep(SOLO_DELAY_COMMON); rv = SOLO_uart_read(response, SOLO_SIMPLE_CMD_LEN); if (rv) return SOLO_ERROR_COMM; if (response[SOLO_COMM_OFFSET] != SOLO_OK) return response[SOLO_COMM_OFFSET]; if (response[SOLO_OP_OFFSET] != SOLO_OK) return response[SOLO_OP_OFFSET]; l = response[SOLO_LEN_OFFSET]*256 + response[SOLO_LEN_OFFSET+1]; if(l>0) { rv = SOLO_uart_read(response+SOLO_SIMPLE_CMD_LEN, l); if (rv) return SOLO_ERROR_COMM; } rv = check_crc(response, SOLO_HEADER_LEN+l, response + SOLO_HEADER_LEN+l); if (rv) return SOLO_ERROR_CRC; if(l>0&&len!=0) *len = l; return SOLO_OK; }
2.46875
2
2024-11-18T20:48:35.487180+00:00
2020-05-11T23:49:53
e6bac2571e419b08f73ded9a286449707ba3571c
{ "blob_id": "e6bac2571e419b08f73ded9a286449707ba3571c", "branch_name": "refs/heads/master", "committer_date": "2020-05-11T23:49:53", "content_id": "bb14b055488a787ad08b0f6c99ffe014b5703c9e", "detected_licenses": [ "MIT" ], "directory_id": "95a44a0ed483cc608132321310dd6ba2387d7b9e", "extension": "c", "filename": "05.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 249592266, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 404, "license": "MIT", "license_type": "permissive", "path": "/src/03/05.c", "provenance": "stackv2-0102.json.gz:68264", "repo_name": "kgoettler/c-primer-plus", "revision_date": "2020-05-11T23:49:53", "revision_id": "0ed507465629942c5fb8766c4d42b5dbb7b45757", "snapshot_id": "0579ea81b797ad86f264e65d31d6d04a4ef90bdf", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/kgoettler/c-primer-plus/0ed507465629942c5fb8766c4d42b5dbb7b45757/src/03/05.c", "visit_date": "2021-04-19T07:46:43.864269" }
stackv2
/* * There are approximately 3.156E7 seconds in a year. Write a program that * requests your age in years and then displays the equivalent number of * seconds */ #include <stdio.h> #define YEAR_TO_SEC 3.156E7 int main (void) { double age_yrs; printf("Enter your age: "); scanf("%lf", &age_yrs); printf("You have been alive for %f seconds\n", age_yrs * YEAR_TO_SEC); return 0; }
3.640625
4
2024-11-18T20:48:35.609918+00:00
2021-08-02T14:29:25
e1b7fd6d924419dd61981c090e90992c8bffef16
{ "blob_id": "e1b7fd6d924419dd61981c090e90992c8bffef16", "branch_name": "refs/heads/master", "committer_date": "2021-08-02T14:29:25", "content_id": "9ba6bea87c83e5bcf072c019c28a36c834fe150b", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "d99620e968467ba75902fc88acbd85e3bbea7b8f", "extension": "c", "filename": "hpglparse.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 388387636, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5271, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/hpglparse.c", "provenance": "stackv2-0102.json.gz:68392", "repo_name": "Annwan/hpgl", "revision_date": "2021-08-02T14:29:25", "revision_id": "fb3f992e391ea9e9fc971326a163e1b8eec569e5", "snapshot_id": "5d082da7ac694622cf7325049c1a79b8181332a6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Annwan/hpgl/fb3f992e391ea9e9fc971326a163e1b8eec569e5/src/hpglparse.c", "visit_date": "2023-06-28T16:30:49.915940" }
stackv2
#include "hpglparse.h" typedef struct ParserContext { char* input; HPGLOpcode op; int instc; int maxinstc; HPGLInstruction* prog; char delim; } ParserContext; static HPGLInstruction *allocProgram(int instc, HPGLInstruction* current){ return realloc(current, instc * sizeof(HPGLInstruction)); } static int parse_t(ParserContext *ctx){ HPGLInstruction current; current.cmd = ctx->op; current.argc = 0; while(*(ctx->input) != ctx->delim){ if (current.argc < 256) { HPGLArgument a = {.c = *(ctx->input++)}; current.args[current.argc++] = a; } } ctx->input++; // consume the delimiter ctx->prog[ctx->instc++] = current; return 0; } static int parse_0(ParserContext *ctx){ HPGLInstruction current = { .cmd = ctx->op, .argc = 0 }; ctx->prog[ctx->instc++] = current; return 0; } static int parse_4(ParserContext *ctx){ HPGLInstruction current; current.cmd = ctx->op; HPGLArgument a,b,c,d; int argc = sscanf(ctx->input, "%f,%f,%f,%f", &(a.n), &(b.n), &(c.n), &(d.n)); current.argc = argc; current.args[0] = a; current.args[1] = b; current.args[2] = c; current.args[3] = d; ctx->prog[ctx->instc++] = current; return 0; } static int parse_n(ParserContext *ctx){ HPGLInstruction current; current.cmd = ctx->op; HPGLArgument a; while (sscanf(ctx->input, "%f", &(a.n)) > 0 && current.argc < 256){ current.args[current.argc++] = a; while(*(ctx->input++) != ','); } ctx->prog[ctx->instc++] = current; return 0; } static int parse_c(ParserContext *ctx){ HPGLInstruction current; current.cmd = ctx->op; current.argc = 1; HPGLArgument a = {.c = *(ctx->input)}; current.args[0] = a; ctx->input++; ctx->delim = a.c; ctx->prog[ctx->instc++] = current; return 0; } static const struct { char cmd[2]; HPGLOpcode op; int (*parser)(ParserContext*); } jumpTable[50] = { {.cmd="AA",.op=hpgl_AA,.parser=parse_4}, {.cmd="AF",.op=hpgl_AF,.parser=parse_0}, {.cmd="AR",.op=hpgl_AR,.parser=parse_4}, {.cmd="BL",.op=hpgl_BL,.parser=parse_t}, {.cmd="CA",.op=hpgl_CA,.parser=parse_4}, {.cmd="CI",.op=hpgl_CI,.parser=parse_4}, {.cmd="CP",.op=hpgl_CP,.parser=parse_4}, {.cmd="CS",.op=hpgl_CS,.parser=parse_4}, {.cmd="CT",.op=hpgl_CT,.parser=parse_4}, {.cmd="DF",.op=hpgl_DF,.parser=parse_0}, {.cmd="DI",.op=hpgl_DI,.parser=parse_4}, {.cmd="DR",.op=hpgl_DR,.parser=parse_4}, {.cmd="DT",.op=hpgl_DT,.parser=parse_c}, {.cmd="DU",.op=hpgl_DU,.parser=parse_4}, {.cmd="DV",.op=hpgl_DV,.parser=parse_4}, {.cmd="EA",.op=hpgl_EA,.parser=parse_4}, {.cmd="EP",.op=hpgl_EP,.parser=parse_0}, {.cmd="ER",.op=hpgl_ER,.parser=parse_4}, {.cmd="ES",.op=hpgl_ES,.parser=parse_4}, {.cmd="EW",.op=hpgl_EW,.parser=parse_4}, {.cmd="FP",.op=hpgl_FP,.parser=parse_0}, {.cmd="FT",.op=hpgl_FT,.parser=parse_4}, {.cmd="IN",.op=hpgl_IN,.parser=parse_0}, {.cmd="IP",.op=hpgl_IP,.parser=parse_4}, {.cmd="IW",.op=hpgl_IW,.parser=parse_4}, {.cmd="LB",.op=hpgl_LB,.parser=parse_t}, {.cmd="LO",.op=hpgl_LO,.parser=parse_4}, {.cmd="LT",.op=hpgl_LT,.parser=parse_4}, {.cmd="NR",.op=hpgl_NR,.parser=parse_0}, {.cmd="PA",.op=hpgl_PA,.parser=parse_n}, {.cmd="PB",.op=hpgl_PB,.parser=parse_0}, {.cmd="PD",.op=hpgl_PD,.parser=parse_n}, {.cmd="PG",.op=hpgl_PG,.parser=parse_0}, {.cmd="PM",.op=hpgl_PM,.parser=parse_4}, {.cmd="PR",.op=hpgl_PR,.parser=parse_n}, {.cmd="PS",.op=hpgl_PS,.parser=parse_4}, {.cmd="PT",.op=hpgl_PT,.parser=parse_4}, {.cmd="PU",.op=hpgl_PU,.parser=parse_n}, {.cmd="RA",.op=hpgl_RA,.parser=parse_4}, {.cmd="RR",.op=hpgl_RR,.parser=parse_4}, {.cmd="RO",.op=hpgl_RO,.parser=parse_4}, {.cmd="SA",.op=hpgl_SA,.parser=parse_0}, {.cmd="SC",.op=hpgl_SC,.parser=parse_4}, {.cmd="SI",.op=hpgl_SI,.parser=parse_4}, {.cmd="SL",.op=hpgl_SL,.parser=parse_4}, {.cmd="SP",.op=hpgl_SP,.parser=parse_4}, {.cmd="SS",.op=hpgl_SS,.parser=parse_0}, {.cmd="SR",.op=hpgl_SR,.parser=parse_4}, {.cmd="SU",.op=hpgl_SU,.parser=parse_4}, {.cmd="WG",.op=hpgl_WG,.parser=parse_4} }; int HPGLParse(char *input, HPGLInstruction **prog) { // Initialize the context ParserContext ctx = { .input = NULL, .instc=0, .maxinstc=32, .prog = NULL, .delim = '\3' }; // Allocate some memory for the program ctx.prog = allocProgram(ctx.maxinstc, NULL); char curcmd[1024] = ""; // Main loop while(*input){ // Read the command char cmd[2] = {*input, *(input+1)}; input+=2; int min = 0; int max = 50; int curind; do { if (min == max) { log_error("hpgl:HPGLParse: unknown command, aborting"); abort(); } curind = (min + max) / 2; if (cmd[0] < jumpTable[curind].cmd[0]) { max = curind; } else if (cmd[0] > jumpTable[curind].cmd[0]) { min = curind; } else { if (cmd[1] < jumpTable[curind].cmd[1]) { max = curind; } else { min = curind; } } } while(jumpTable[curind].cmd[0] != cmd[0] || jumpTable[curind].cmd[1] != cmd[1]); int index = curind; int len = 0; while (*input != ';'){ if (len < 1023){ curcmd[len++]=*(input++); } } curcmd[len] = '\0'; input++; //skip the `;' ctx.input = curcmd; ctx.op = jumpTable[index].op; (jumpTable[index].parser)(&ctx); if (ctx.instc == ctx.maxinstc) { ctx.maxinstc *= 2; ctx.prog = allocProgram(ctx.maxinstc, ctx.prog); } } *prog = ctx.prog; return ctx.instc; }
2.65625
3
2024-11-18T20:48:35.671900+00:00
2015-03-14T12:16:51
dd375bae050407f08cc65f44c4acdabed538cd5b
{ "blob_id": "dd375bae050407f08cc65f44c4acdabed538cd5b", "branch_name": "refs/heads/master", "committer_date": "2015-03-14T12:16:51", "content_id": "3af942041725530c9adf3c40db298eff713afec4", "detected_licenses": [ "MIT" ], "directory_id": "7879d5e61fe15da41059f208209fd8af0684fcee", "extension": "c", "filename": "alloctest.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 23588618, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4620, "license": "MIT", "license_type": "permissive", "path": "/ch07/7-2/alloctest.c", "provenance": "stackv2-0102.json.gz:68520", "repo_name": "enil/tlpi-exercises", "revision_date": "2015-03-14T12:16:51", "revision_id": "a98f3d1f25d2aac8a1b50ecaa4d97f736a6fc62e", "snapshot_id": "57a83bcabaf8f51d486b030c4384b4b01db4b96d", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/enil/tlpi-exercises/a98f3d1f25d2aac8a1b50ecaa4d97f736a6fc62e/ch07/7-2/alloctest.c", "visit_date": "2021-01-22T05:27:52.342162" }
stackv2
#include "newalloc.h" // for printf, fprintf, scanf, stderr #include <stdio.h> // for strtol, free, NULL, EXIT_SUCCESS #include <stdlib.h> // for intptr_t #include <stdint.h> // for sbrk #include <unistd.h> // for strcasecmp #include <strings.h> // for LONG_MIN, LONG_MAX #include <limits.h> // for bool, true, false #include <stdbool.h> /** * A command entered by the user. */ typedef enum { INVALID_COMMAND, QUIT_COMMAND, ALLOC_COMMAND, FREE_COMMAND, LIST_COMMAND, DETAILED_LIST_COMMAND, BRK_COMMAND, HELP_COMMAND } command; /** * A function for a command. */ typedef bool (* command_func)(void); /** * Description of a command. */ typedef struct { command type; command_func func; char * name; char * short_name; char * description; } command_description; static bool alloc_command(void); static bool free_command(void); static bool list_command(void); static bool detailed_list_command(void); static bool brk_command(void); static bool help_command(void); /** * Descriptions for the commands. */ static command_description command_descriptions[] = { {QUIT_COMMAND, NULL, "quit", "q", "Quits the program."}, {ALLOC_COMMAND, alloc_command, "alloc [size]", "a", "Allocates memory of the specified size."}, {FREE_COMMAND, free_command, "free [address]", "f", "Frees the specified memory."}, {LIST_COMMAND, list_command, "list", "l", "Displays a list of the allocations."}, {DETAILED_LIST_COMMAND, detailed_list_command, "dlist", "d", "Displays a detailed list of the allocations."}, {BRK_COMMAND, brk_command, "brk", "b", "Displays the program break."}, {HELP_COMMAND, help_command, "help", "h", "Shows usage of all commands."}, {INVALID_COMMAND, NULL, NULL, NULL, NULL} }; #define EACH_COMMAND(command) for (command_description * command = command_descriptions; command->name; ++command) /** * Prompts the user to enter a command. */ static command prompt_command(void) { char * buffer; command command; do { // prompt printf("> "); // WARNING: not protected against overflow scanf("%ms", &buffer); // find a matching command command = INVALID_COMMAND; EACH_COMMAND(description) { // check against name and short name if (strcasecmp(buffer, description->name) == 0 || (description->short_name && strcasecmp(buffer, description->short_name) == 0)) { command = description->type; break; } } if (command == INVALID_COMMAND) { fprintf(stderr, "Invalid command, enter \"help\" to display all commands\n"); } free(buffer); } while (command == INVALID_COMMAND); return command; } /** * Gets the command function for a command. */ static command_func get_command_func(command command) { EACH_COMMAND(description) { if (description->type == command) { return description->func; } } // not found return NULL; } /** * Reads a long value. */ static bool read_long(long * value, int base) { bool result = false; char * buffer; char * end; long converted; scanf("%ms", &buffer); if (buffer == NULL) { goto fail; } converted = strtol(buffer, &end, base); if (converted == LONG_MIN || converted == LONG_MAX || *end != '\0') { goto fail; } *value = converted; result = true; fail: if (buffer != NULL) { free(buffer); } return result; } bool alloc_command(void) { long size; if (!read_long(&size, 0)) { fprintf(stderr, "Invalid size\n"); return false; } void * mem = na_malloc((size_t)size); printf("Allocated memory at 0x%08lx\n", (intptr_t)mem); } bool free_command(void) { uintptr_t address; if (!read_long(&address, 16)) { fprintf(stderr, "Invalid address\n"); return false; } na_free((void *)address); printf("Free memory at 0x%08lx\n", address); } bool list_command(void) { na_list_nodes(); return true; } bool detailed_list_command(void) { na_print_nodes(); return true; } bool brk_command(void) { printf("brk: 0x%08lx\n", (uintptr_t)sbrk(0)); return true; } bool help_command(void) { printf("Available commands\n"); EACH_COMMAND(description) { printf("%-16s %1s %s\n", description->name, (description->short_name ? description->short_name : ""), description->description); } return true; } int main(int argc, char * argv[]) { command command; printf("Type \"help\" to list available commands\n"); while ((command = prompt_command()) != QUIT_COMMAND) { command_func func = get_command_func(command); if (func == NULL) { fprintf(stderr, "Unknown command, try again\n"); } else { // execute the command function func(); } } printf("bye!\n"); return EXIT_SUCCESS; }
2.953125
3
2024-11-18T20:48:35.992438+00:00
2015-03-16T15:02:11
e9650775b2a3f68c8db587ec1cdb6874f542a2b4
{ "blob_id": "e9650775b2a3f68c8db587ec1cdb6874f542a2b4", "branch_name": "refs/heads/master", "committer_date": "2015-03-16T15:04:58", "content_id": "12c9dfac9c6340ccde915207c91cca65f1bfa201", "detected_licenses": [ "MIT" ], "directory_id": "06df1e57108d34d899dc204ac5f1423d6e2507fe", "extension": "c", "filename": "Toast.c", "fork_events_count": 6, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 32332498, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5124, "license": "MIT", "license_type": "permissive", "path": "/GSM/Toast.c", "provenance": "stackv2-0102.json.gz:68909", "repo_name": "goodspeed24e/2011Corel", "revision_date": "2015-03-16T15:02:11", "revision_id": "4efb585a589ea5587a877f4184493b758fa6f9b2", "snapshot_id": "dcf51f34b153f96a3f3904a9249cfcd56d5ff4aa", "src_encoding": "WINDOWS-1252", "star_events_count": 2, "url": "https://raw.githubusercontent.com/goodspeed24e/2011Corel/4efb585a589ea5587a877f4184493b758fa6f9b2/GSM/Toast.c", "visit_date": "2021-01-01T17:28:23.541299" }
stackv2
#include "toast.h" char * progname; int f_decode = 1; /* decode rather than encode (-d) */ int f_cat = 0; /* write to stdout; implies -p (-c) */ int f_force = 0; /* don't ask about replacements (-f) */ int f_precious = 0; /* avoid deletion of original (-p) */ int f_fast = 0; /* use faster fpt algorithm (-F) */ int f_verbose = 0; /* debugging (-V) */ int f_ltp_cut = 0; /* LTP cut-off margin (-C) */ FILE *in, *out; char inname[30], outname[30]; /* * The function (*output)() writes a frame of 160 samples given as * 160 signed 16 bit values (gsm_signals) to <out>. * The function (*input)() reads one such frame from <in>. * The function (*init_output)() begins output (e.g. writes a header)., * The function (*init_input)() begins input (e.g. skips a header). * * There are different versions of input, output, init_input and init_output * for different formats understood by toast; which ones are used * depends on the command line arguments and, in their absence, the * filename; the fallback is #defined in toast.h * * The specific implementations of input, output, init_input and init_output * for a format `foo' live in toast_foo.c. */ int (*output ) P((gsm_signal *)), (*input ) P((gsm_signal *)); int (*init_input) P((void)), (*init_output) P((void)); static int generic_init P0() { return 0; } /* NOP */ struct fmtdesc { char * name, * longname, * suffix; int (* init_input ) P((void)), (* init_output) P((void)); int (* input ) P((gsm_signal * )), (* output) P((gsm_signal * )); } f_linear = { "linear", "16 bit (13 significant) signed 8 kHz signal", ".l", generic_init, generic_init, linear_input, linear_output }; struct fmtdesc * alldescs[] = { &f_linear, (struct fmtdesc *)NULL }; #define DEFAULT_FORMAT f_linear /* default audio format, others */ /* are: f_alaw,f_audio,f_linear */ struct fmtdesc * f_format = 0; static void prepare_io P1(( desc), struct fmtdesc * desc) { output = desc->output; input = desc->input; init_input = desc->init_input; init_output = desc->init_output; } static int process_encode P0() { gsm r; gsm_signal s[ 160 ]; gsm_frame d; int cc; if (!(r = gsm_create())) { perror(progname); return -1; } (void)gsm_option(r, GSM_OPT_FAST, &f_fast); (void)gsm_option(r, GSM_OPT_VERBOSE, &f_verbose); (void)gsm_option(r, GSM_OPT_LTP_CUT, &f_ltp_cut); //while ((cc = (*input)(s)) > 0) { while ((cc = fread(s,2,160,in)) > 0) { if (cc < sizeof(s) / sizeof(*s)) memset((char *)(s+cc), 0, sizeof(s)-(cc * sizeof(*s))); gsm_encode(r, s, d); if (fwrite((char *)d, sizeof(d), 1, out) != 1) { perror(outname ? outname : "stdout"); fprintf(stderr, "%s: error writing to %s\n", progname, outname ? outname : "stdout"); gsm_destroy(r); return -1; } } if (cc < 0) { perror(inname ? inname : "stdin"); fprintf(stderr, "%s: error reading from %s\n", progname, inname ? inname : "stdin"); gsm_destroy(r); return -1; } gsm_destroy(r); return 0; } static int process_decode P0() { gsm r; gsm_frame s; gsm_signal d[ 160 ]; int cc; if (!(r = gsm_create())) { /* malloc failed */ perror(progname); return -1; } (void)gsm_option(r, GSM_OPT_FAST, &f_fast); (void)gsm_option(r, GSM_OPT_VERBOSE, &f_verbose); while ((cc = fread(s, 1, sizeof(s), in)) > 0) { //erroreffect(s); if (cc != sizeof(s)) { if (cc >= 0) fprintf(stderr, "%s: incomplete frame (%d byte%s missing) from %s\n", progname, sizeof(s) - cc, "s" + (sizeof(s) - cc == 1), inname ? inname : "stdin" ); gsm_destroy(r); errno = 0; return -1; } if (gsm_decode(r, s, d)) { fprintf(stderr, "%s: bad frame in %s\n", progname, inname ? inname : "stdin"); gsm_destroy(r); errno = 0; return -1; } //if ((*output)(d) < 0) { if (fwrite(d,2,160,out) < 0) { perror(outname); fprintf(stderr, "%s: error writing to %s\n", progname, outname); gsm_destroy(r); return -1; } } if (cc < 0) { perror(inname ? inname : "stdin" ); fprintf(stderr, "%s: error reading from %s\n", progname, inname ? inname : "stdin"); gsm_destroy(r); return -1; } gsm_destroy(r); return 0; } int main () { int flag=0; int control_flag; printf("\n input control flag=<int put=0 encode&decode outsame?>\n<int put=1 encode outsame?>\n<int put=2 decode outsame?>\n"); scanf("%d",&control_flag); printf("control_flag=%d\n",control_flag); if(control_flag!=2) { printf("\n input insame?\n"); scanf("%s",inname); printf("\n input outsame?\n"); scanf("%s",outname); in = fopen (inname , "rb" ); out = fopen ( outname, "wb" ); prepare_io ( f_linear ); process_encode (); fclose ( in ); fclose ( out ); } if(control_flag!=1) { printf("\n input insame?\n"); scanf("%s",inname); printf("\n input outsame?\n"); scanf("%s",outname); in = fopen (inname, "rb" ); //ÂëÁ÷Îļþ264·´¸´ out = fopen ( outname, "wb" ); prepare_io ( f_linear ); process_decode (); fclose ( in ); fclose ( out ); } }
2.265625
2
2024-11-18T20:48:36.056336+00:00
2021-01-09T15:33:44
321a4b363979ed843a17bf786fecbd9597987742
{ "blob_id": "321a4b363979ed843a17bf786fecbd9597987742", "branch_name": "refs/heads/master", "committer_date": "2021-01-09T15:33:44", "content_id": "f308cff6713ba6d780dc1ecc56c6a4e93ed4b389", "detected_licenses": [ "MIT" ], "directory_id": "8030fab0df69629fe8b0cb4ad49d8627d670b769", "extension": "h", "filename": "speed_calculator.h", "fork_events_count": 0, "gha_created_at": "2020-03-18T08:08:00", "gha_event_created_at": "2020-03-18T08:08:01", "gha_language": null, "gha_license_id": null, "github_id": 248172566, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1433, "license": "MIT", "license_type": "permissive", "path": "/apps/distributed-tracking/speed_calculator.h", "provenance": "stackv2-0102.json.gz:69037", "repo_name": "germandevelop/node-apps", "revision_date": "2021-01-09T15:33:44", "revision_id": "40f9fb05c6a98f07fc72e81c7466350afd81ea18", "snapshot_id": "d76f73e4c4bfc9ba8bdc7249fb87eebfe221330f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/germandevelop/node-apps/40f9fb05c6a98f07fc72e81c7466350afd81ea18/apps/distributed-tracking/speed_calculator.h", "visit_date": "2022-05-10T08:54:29.843032" }
stackv2
#ifndef SPEED_CALCULATOR_H_ #define SPEED_CALCULATOR_H_ // CONFIGURABLE VALUES /************************************************************************************************/ #define SPEED_DETECTION_WINDOW 10U /************************************************************************************************/ #include <stdint.h> #include <stdbool.h> typedef struct motion_data motion_data_t; typedef struct speed_calculator { double pass_detection_threshold; double energy[4]; // [2 - 4] uint8_t energy_size; double speed[SPEED_DETECTION_WINDOW]; uint8_t speed_size; void(*append_measurements)(struct speed_calculator * const speed_calculator, motion_data_t const * const motion_data); bool is_computed; } speed_calculator_t; void speed_calculator_init(speed_calculator_t * const speed_calculator, double pass_detection_threshold); void speed_calculator_start_in_moving_away_mode(speed_calculator_t * const speed_calculator); void speed_calculator_start_in_moving_toward_mode(speed_calculator_t * const speed_calculator); void speed_calculator_is_computed(speed_calculator_t const * const speed_calculator, bool * const is_computed); void speed_calculator_append_measurements(speed_calculator_t * const speed_calculator, motion_data_t const * const motion_data); int speed_calculator_get_average_speed(speed_calculator_t const * const speed_calculator, double * const average_speed); #endif
2.0625
2
2024-11-18T20:48:36.818231+00:00
2017-05-08T08:08:25
981d28fd4f6fc045dc472035a788dce2829d2643
{ "blob_id": "981d28fd4f6fc045dc472035a788dce2829d2643", "branch_name": "refs/heads/master", "committer_date": "2017-05-08T08:08:25", "content_id": "899e2f27a7a3aa30545bf85d38322937f7fe47e3", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "6267397c9208fb0d3a468a9c6ea8819c1d1d2d58", "extension": "c", "filename": "textdrv.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 89402943, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2739, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/kernel/drivers/textdrv.c", "provenance": "stackv2-0102.json.gz:69296", "repo_name": "wubbalubbadubdubonline/echidnaOS", "revision_date": "2017-05-08T08:08:25", "revision_id": "ba7097728336e9cef1a4418489843cfca85922ea", "snapshot_id": "1042643e39b6dbdc9292d68584cdf82cd574625f", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/wubbalubbadubdubonline/echidnaOS/ba7097728336e9cef1a4418489843cfca85922ea/kernel/drivers/textdrv.c", "visit_date": "2021-01-20T02:24:51.716936" }
stackv2
#include "textdrv.h" #include "system.h" /* internal defines */ #define VIDEO_ADDRESS 0xB8000 #define VIDEO_BOTTOM 0x1F3F #define ROWS 50 #define COLS 160 /* internal functions */ void clear_cursor(void); void draw_cursor(void); void scroll(void); /* internal global variables */ int cursor_offset = 0; int cursor_status = 1; char cursor_palette = 0x70; char text_palette = 0x07; /* internal functions */ void clear_cursor(void) { mem_store_b(VIDEO_ADDRESS+cursor_offset+1, text_palette); } void draw_cursor(void) { if (cursor_status) { mem_store_b(VIDEO_ADDRESS+cursor_offset+1, cursor_palette); } } void scroll(void) { int offset; // move the text up by one row for (offset=0; offset<=VIDEO_BOTTOM-COLS; offset++) { mem_store_b(VIDEO_ADDRESS+offset, mem_load_b(VIDEO_ADDRESS+offset+COLS)); } // clear the last line of the screen for (offset=VIDEO_BOTTOM; offset>VIDEO_BOTTOM-COLS; offset=offset-2) { mem_store_b(VIDEO_ADDRESS+offset, text_palette); mem_store_b(VIDEO_ADDRESS+offset-1, ' '); } } /* external functions */ void text_clear(void) { int offset; clear_cursor(); for (offset=0; offset<VIDEO_BOTTOM; offset=offset+2) { mem_store_b(VIDEO_ADDRESS+offset, ' '); mem_store_b(VIDEO_ADDRESS+offset+1, text_palette); } cursor_offset=0; draw_cursor(); } void text_enable_cursor(void) { cursor_status=1; draw_cursor(); } void text_disable_cursor(void) { cursor_status=0; clear_cursor(); } void text_putchar(char c) { if (c == 0x00) { } else if (c == 0x0A) { if (text_get_cursor_pos_y() == ROWS - 1) { clear_cursor(); scroll(); text_set_cursor_pos(0, ROWS - 1); } else text_set_cursor_pos(0, (text_get_cursor_pos_y()+1)); } else if (c == 0x08) { if (cursor_offset) { clear_cursor(); cursor_offset = cursor_offset-2; mem_store_b(VIDEO_ADDRESS+cursor_offset, ' '); draw_cursor(); } } else { clear_cursor(); mem_store_b(VIDEO_ADDRESS+cursor_offset, c); if (cursor_offset >= VIDEO_BOTTOM-1) { scroll(); cursor_offset = VIDEO_BOTTOM - (COLS-1); } else { cursor_offset = cursor_offset+2; } draw_cursor(); } } void text_putstring(const char *string) { int x; for (x=0; string[x]!=0; x++) { text_putchar(string[x]); } } void text_set_cursor_palette(char c) { cursor_palette = c; draw_cursor(); } char text_get_cursor_palette(void) { return cursor_palette; } void text_set_text_palette(char c) { text_palette = c; } char text_get_text_palette(void) { return text_palette; } int text_get_cursor_pos_x(void) { return (cursor_offset/2) % ROWS; } int text_get_cursor_pos_y(void) { return (cursor_offset/2) / (COLS/2); } void text_set_cursor_pos(int x, int y) { clear_cursor(); cursor_offset = (y*COLS)+(x*2); draw_cursor(); }
2.703125
3
2024-11-18T20:48:36.989157+00:00
2018-05-23T06:55:18
7d253a16ffd01bd098542e721c531074a6f27892
{ "blob_id": "7d253a16ffd01bd098542e721c531074a6f27892", "branch_name": "refs/heads/master", "committer_date": "2018-05-23T06:55:18", "content_id": "af2c3d9e18c74759befa1071abf3f729b05b6882", "detected_licenses": [ "MIT" ], "directory_id": "2bc3398063fd7251c46a2d93d2e301cd063befcd", "extension": "c", "filename": "santa.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": 6264, "license": "MIT", "license_type": "permissive", "path": "/nitan/kungfu/class/misc/santa.c", "provenance": "stackv2-0102.json.gz:69427", "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/kungfu/class/misc/santa.c", "visit_date": "2020-03-18T08:44:12.400598" }
stackv2
//Cracked by Kafei // kungfu/class/misc/santa.c // sdong, 12/24/98 #include <ansi.h> inherit NPC; inherit F_UNIQUE; string ask_gift(); void greeting(); void create() { seteuid(getuid()); set_name(HIR"圣诞老人"NOR, ({ "shengdan laoren","santa","laoren"}) ); set("gender", "男性" ); set("age", 63); set("long", HIR"一位红光满面,笑呵呵的白胡子老爷爷。\n"NOR); set("attitude", "peaceful"); set("str", 25); set("con", 25); set("int", 25); set("dex", 100); set("kar", 100); set("max_qi", 50000); set("max_jing", 100); set("neili", 50000); set("max_neili", 50000); set("shen_type", 1); set("env/yield","yes"); set("startroom","/d/city/wumiao"); set("combat_exp", 100000); set_skill("force", 400); set_skill("hand", 40); set_skill("sword", 50); set_skill("dodge", 400); set_skill("parry", 400); set_skill("huntian-qigong", 400); map_skill("force", "huntian-qigong"); set("chat_chance", 20); set("chat_msg", ({ "圣诞老人笑呵呵说道: 圣诞快乐!快乐!~~\n", "圣诞老人快活地唱道: 叮叮铛,叮叮铛,铃儿响叮铛~~\n", "圣诞老人笑呵呵说道: 想要礼物吗?我就是神派来送圣诞礼物的。 \n", "圣诞老人笑道: 只要是乖孩子,就有圣诞礼物。 \n", (: random_move :), (: greeting :), }) ); set("inquiry", ([ "gift" : (: ask_gift :), "圣诞礼物" : (: ask_gift:), "礼物" : (: ask_gift:), ]) ); setup(); ::create(); } void init() { object ob; ::init(); if( interactive(ob = this_player()) ) { remove_call_out("greeting"); call_out("greeting", 1); } } string ask_gift() { object ppl = this_player(); object santa = this_object(); object ob; if( ppl->query_condition("santa") ) { message_vision("$N对着$n笑道:你才拿到礼物,就又想要啦?\n",santa,ppl); random_move(); return "呵呵呵\n"; } if( query("combat_exp", ppl)<300 ) { random_move(); return "DUMMY是不需要礼物的:)"; } seteuid(getuid()); if (random(8) == 1) { ob = new("/clone/drug/lingzhi"); ob->move(santa); } else if (random(16) == 1) { ob = new("/clone/drug/puti-zi"); ob->move(ppl); } else if (random(16) == 1) { ob = new("/clone/drug/sheli-zi"); ob->move(santa); } else if (random(6) == 1) { ob = new("/clone/drug/xueteng"); ob->move(santa); } else if (random(6) == 1) { ob = new("/clone/drug/xuelian"); ob->move(santa); } else if (random(6) == 1) { ob = new("/clone/drug/cb_renshen"); ob->move(santa); } else if (random(6) != 1) { ob = new("/clone/drug/renshen_guo"); ob->move(santa); } else { ob=new("/clone/money/gold"); ob->set_amount( 3 + random(5) ); ob->move(santa); } command("pat"+query("id", ppl)); if( query("env/no_accept", ppl) ) { command("hmm"); command("say "+ppl->name()+"不想接受任何东西?"); } else command("give"+query("id", ob)+"to"+query("id", ppl)); ppl->apply_condition( "santa",20+random(10) ); return "祝你圣诞快乐!快乐!~~\n"; } void destroy_me(object me) { destruct(me); } void greeting() { object me = this_object(); command("say 祝你圣诞快乐!快乐~~\n"); if( strsrch(base_name(environment()), "/d/city/") == -1 ) { message_vision(HIY"$N"+HIY"乘坐风车凌空飞去,转眼就不见了.\n"NOR,me); me->move("d/city/wumiao"); message_vision(HIG"只听空中一阵铃铛声响,$N"+HIG"乘坐风车凌空飞来.\n"NOR,me); } if( strsrch(ctime(time()), "Dec 25") == -1 ) { message_vision(HIY"$N"+HIY"凄婉地说:圣诞节结束了,我也该回天堂了.\n"NOR,me); command("goodbye"); message_vision(HIY"$N"+HIY"乘坐风车凌空飞去,转眼就不见了.\n"NOR,me); call_out("destroy_me",1,me); } if( random(150) == 0 ) { message_vision(HIY"$N"+HIY"乘坐风车凌空飞去,转眼就不见了.\n"NOR,me); call_out("destroy_me",1,me); } } int accept_object(object me, object obj) { if( query("money_id", obj) && obj->value() >= 1){ command("smile"); command("say 多谢啦 ! 你好心必有好报的 !"); } return 0; } int accept_fight(object me) { command("say " + RANK_D->query_respect(me) + ",老头子我是不打架的:)ⅵ\n"); return 0; } int accept_kill(object victim) { object me = this_object(); object player = this_player(); int flag; command("say " + RANK_D->query_respect(player) + ",怎么这么凶?不该不该呀!\n"); command("benger"+query("id", player)); if( query("env/immortal", player) ) flag=1; delete("env/immortal", player); player->unconcious(); if( flag)set("env/immortal", 1, player); command("halt"); random_move(); return 0; }
2.09375
2
2024-11-18T20:48:37.462189+00:00
2018-01-18T09:29:31
928bd4bce48221c3ef20bac9796062b6d157f144
{ "blob_id": "928bd4bce48221c3ef20bac9796062b6d157f144", "branch_name": "refs/heads/master", "committer_date": "2018-01-18T09:29:31", "content_id": "00b6474851f3f3d426412887bb74fa85b3151357", "detected_licenses": [ "MIT" ], "directory_id": "d8d8f03d6acf20f3ec0ee1bccef89837d92f3042", "extension": "c", "filename": "node.c", "fork_events_count": 0, "gha_created_at": "2017-12-01T16:22:28", "gha_event_created_at": "2018-01-18T09:29:32", "gha_language": "C", "gha_license_id": "MIT", "github_id": 112761079, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3553, "license": "MIT", "license_type": "permissive", "path": "/src/node.c", "provenance": "stackv2-0102.json.gz:69941", "repo_name": "buoto/linda-file-semaphore", "revision_date": "2018-01-18T09:29:31", "revision_id": "9877cdc0299500a8d07f4a7c6510305ea122b337", "snapshot_id": "48438644410154f1d2c36ecf6b700cb385a07605", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/buoto/linda-file-semaphore/9877cdc0299500a8d07f4a7c6510305ea122b337/src/node.c", "visit_date": "2021-09-04T11:34:11.062116" }
stackv2
#include "node.h" struct node make_string_node(const char* string, unsigned size) { char* value = (char*) malloc(sizeof(char) * size); strncpy(value, string, size); return (struct node) { .type = STRING, .str_value = value, }; } struct node make_int_node(unsigned integer) { return (struct node) { .type = INTEGER, .int_value = integer, }; } void destroy_node(struct node* node) { if (node == NULL) { return; } if (node->type == STRING) { free(node->str_value); } node->str_value = NULL; } void print_node(struct node node) { switch (node.type) { case INTEGER: printf("%u\n", node.int_value); return; case STRING: printf("%s\n", node.str_value); return; } } bool match_node( const struct node *pattern, const struct node *value ) { if(pattern->type != value->type) { return false; } if(pattern->type == INTEGER) { return match_integer( pattern->matcher, pattern->int_value, value->int_value ); } else { return match_string( pattern->matcher, pattern->str_value, value->str_value ); } } bool match_integer( enum node_matcher matcher, unsigned pattern, unsigned value ) { switch(matcher) { case ANY: return true; case EQUAL: return value == pattern; case LESSER: return value < pattern; case LESSER_OR_EQUAL: return value <= pattern; case GREATER: return value > pattern; case GREATER_OR_EQUAL: return value >= pattern; default: return false; } } bool match_string( enum node_matcher matcher, const char *pattern, const char *value ) { switch(matcher) { case ANY: return true; case EQUAL: return match_pattern(pattern, value); case LESSER: return strcmp(value, pattern) < 0; case LESSER_OR_EQUAL: return strcmp(value, pattern) <= 0; case GREATER: return strcmp(value, pattern) > 0; case GREATER_OR_EQUAL: return strcmp(value, pattern) >= 0; default: return false; } } #define WILDCARD '*' bool match_pattern(const char *pattern, const char *value) { unsigned pattern_index = 0; unsigned value_index = 0; while(1) { char pattern_char = pattern[pattern_index]; char value_char = value[value_index]; switch(pattern_char) { case 0: return value_char == 0; case WILDCARD: if(match_pattern( &pattern[pattern_index+1], &value[value_index] )) { return true; } else { value_index++; break; } default: if(pattern_char != value_char) { return false; } pattern_index++; value_index++; } if(value_char == 0) { return false; } } } size_t node_length(const struct node n) { switch (n.type) { case INTEGER: return floor(log10(abs(n.int_value))) + 1; case STRING: return strlen(n.str_value); } return 0; }
3.265625
3
2024-11-18T20:48:37.916069+00:00
2018-01-23T23:54:32
884c00d3d3301c1387a802d3ebde164e050c0659
{ "blob_id": "884c00d3d3301c1387a802d3ebde164e050c0659", "branch_name": "refs/heads/master", "committer_date": "2018-01-23T23:54:32", "content_id": "8166b5db255c76af5ce544208dc8d702acae6d3a", "detected_licenses": [ "MIT" ], "directory_id": "77a220d181cddcdde98b1be4327d87147bed2acb", "extension": "c", "filename": "psu_thread_test.c", "fork_events_count": 0, "gha_created_at": "2018-04-03T16:05:53", "gha_event_created_at": "2018-04-03T16:05:53", "gha_language": null, "gha_license_id": null, "github_id": 127934065, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 990, "license": "MIT", "license_type": "permissive", "path": "/psu_thread_test.c", "provenance": "stackv2-0102.json.gz:70199", "repo_name": "DNALuo/DistributedSystem", "revision_date": "2018-01-23T23:54:32", "revision_id": "e3164540f3bc7988d473877886efb860d5a2ee4e", "snapshot_id": "f7859ff7ebae268fd6050cc26be1f96a97585b8c", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/DNALuo/DistributedSystem/e3164540f3bc7988d473877886efb860d5a2ee4e/psu_thread_test.c", "visit_date": "2020-03-08T04:54:41.083737" }
stackv2
// Sample Application 1 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "psu_thread.h" extern int main_svc (int argc, char **argv); char REMOTE_IP_ADDR[255]; void print_hostname() { char buffer[100]; int ret; if ((ret = gethostname(buffer, sizeof(buffer))) == -1) { perror("gethostname"); exit(1); } printf("Hostname: %s\n", buffer); } void* foo(void* arg) { int x = 1; print_hostname(); printf("Foo:Hello.....\n"); psu_thread_migrate(REMOTE_IP_ADDR); print_hostname(); printf("Variable x: %d\n", x); printf("Foo:.....World\n"); return NULL; } int main(int argc, char* argv[]) { if(argc < 2) { printf("Usage: toy_app1 <ip_addr_to_migrate_to>/server\n"); exit(1); } if(strcmp(argv[1], "server") == 0) main_svc(argc, argv); printf("Creating thread.\n"); strcpy(REMOTE_IP_ADDR, argv[1]); psu_thread_info_t t_info; psu_thread_create(&t_info, foo, NULL); printf("Thread created.\n"); }
3
3
2024-11-18T20:48:38.590986+00:00
2017-05-03T09:50:49
656af65134ec22a12a81cd8174463874e77b99fc
{ "blob_id": "656af65134ec22a12a81cd8174463874e77b99fc", "branch_name": "refs/heads/master", "committer_date": "2017-05-03T09:50:49", "content_id": "4d439016a3f413898cc5714cc43c93a3922eb77f", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "96e5e801f2e9f52b1df5dcb09a5e7cd936b7e58a", "extension": "c", "filename": "los_bsp_led.c", "fork_events_count": 0, "gha_created_at": "2017-05-03T09:37:14", "gha_event_created_at": "2020-01-20T09:03:13", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 90132637, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1931, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/platform/GD32F450i-EVAL/los_bsp_led.c", "provenance": "stackv2-0102.json.gz:70718", "repo_name": "nickfox-taterli/LiteOS_Kernel", "revision_date": "2017-05-03T09:50:49", "revision_id": "81f78926095a5d8e2171700249bb79cbc521cac2", "snapshot_id": "dcb222b8b1d069c60bd2951075c63802bc5c8cc5", "src_encoding": "ISO-8859-9", "star_events_count": 1, "url": "https://raw.githubusercontent.com/nickfox-taterli/LiteOS_Kernel/81f78926095a5d8e2171700249bb79cbc521cac2/platform/GD32F450i-EVAL/los_bsp_led.c", "visit_date": "2021-01-20T08:20:37.006085" }
stackv2
#include "los_bsp_led.h" #ifdef GD32F4XX //#include "gd32f4xx.h" #include "gd32f450i_eval.h" #endif void LOS_EvbLedInit(void) { #ifdef GD32F4XX gd_eval_led_init(LED1); gd_eval_led_init(LED2); gd_eval_led_init(LED3); #endif return; } /************************************************************************************************* * function£ºcontrol led on off * * param (1) index Led's index * * (2) cmd Led on or off * * return : None * * discription: * **************************************************************************************************/ void LOS_EvbLedControl(int index, int cmd) { #ifdef GD32F4XX switch (index) { case LOS_LED1: { if (cmd == LED_ON) { gd_eval_led_on(LED1); /*led1 on */ } else { gd_eval_led_off(LED1); /*led1 off */ } break; } case LOS_LED2: { if (cmd == LED_ON) { gd_eval_led_on(LED2); /*led2 on */ } else { gd_eval_led_off(LED2); /*led2 off */ } break; } case LOS_LED3: { if (cmd == LED_ON) { gd_eval_led_on(LED3); /*led3 on */ } else { gd_eval_led_off(LED3); /*led3 off */ } break; } default: { break; } } #endif return ; }
2.40625
2
2024-11-18T20:48:38.735060+00:00
2021-04-11T19:13:13
bbf0f2d83df118c25fdd0af39446a53635e3c7ee
{ "blob_id": "bbf0f2d83df118c25fdd0af39446a53635e3c7ee", "branch_name": "refs/heads/master", "committer_date": "2021-04-11T19:13:13", "content_id": "73b08d0c35d0d2809c367669732277200c9e2023", "detected_licenses": [ "MIT" ], "directory_id": "e0bedbb33ba76b7b8a86d2ab1dc48493e42fc57d", "extension": "c", "filename": "PSoC_serial_swTx.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 212177971, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5251, "license": "MIT", "license_type": "permissive", "path": "/PSoC/PSoC_serial_swTx.c", "provenance": "stackv2-0102.json.gz:70976", "repo_name": "TheCbac/micaOS", "revision_date": "2021-04-11T19:13:13", "revision_id": "14dd8cc77c4964b5f011c11442f22b15b1eb09b8", "snapshot_id": "3a04902e2587313fae5a8409507ff500795772b4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TheCbac/micaOS/14dd8cc77c4964b5f011c11442f22b15b1eb09b8/PSoC/PSoC_serial_swTx.c", "visit_date": "2021-06-24T22:44:59.216757" }
stackv2
/*************************************************************************** * MICA © 2019 * * * File: PSoC_serial_swTx.c * Workspace: micaOS * Project: micaOS * Version: 5.0.0 * Authors: C. Cheney * * PCB: N/A N/A * mcuType: PSoC * partNumber:N/A * * Brief: * API Wrapper for using a serial port on the PSoC using software transmit UART * * 2019.10.08 - Document Created ********************************************************************************/ #include "PSoC_serial_swTx.h" #include "micaCommon.h" #include "project.h" /******************************************************************************* * Function Name: uartPsocTx_start() ****************************************************************************//** * \brief Registers Serial functions * * \param uart [in/out] * Pointer to the state struct * * \return * Success *******************************************************************************/ uint32_t uartPsocTx_start(COMMS_UART_S* uart, uint32_t baud) { /* Baud rate set at compile time */ (void) baud; /* Register the Arduino commands and start */ uart->write = uartPsocTx_write; uart->print = uartPsocTx_print; uart->writeArray = uartPsocTx_writeArray; uart->read = uartPsocTx_read; uart->readArray = uartPsocTx_readArray; uart->getRxBufferSize = uartPsocTx_getRxBufferSize; uart->getTxBufferSize = uartPsocTx_getTxBufferSize; /* Start the serial port */ uartUsb_Start(); return COMMS_ERROR_NONE; } /******************************************************************************* * Function Name: uartPsocTx_write() ****************************************************************************//** * \brief Registers Write out a byte of data via UART * * \param val [in] * Value to write out * * \return * Success *******************************************************************************/ uint32_t uartPsocTx_write(uint8_t val){ uartUsb_PutChar(val); return COMMS_ERROR_NONE; } /******************************************************************************* * Function Name: uartPsocTx_print() ****************************************************************************//** * \brief Write out a null-pointer string * * \param str [in] * String to write out * * \return * Success *******************************************************************************/ uint32_t uartPsocTx_print(const char* str){ uartUsb_PutString(str); return COMMS_ERROR_NONE; } /******************************************************************************* * Function Name: uartPsocTx_writeArray() ****************************************************************************//** * \brief Write out an array of data * * \param str [in] * String to write out * * \return * Success *******************************************************************************/ uint32_t uartPsocTx_writeArray(uint8_t *array, uint16_t len){ uartUsb_PutArray(array, len); return COMMS_ERROR_NONE; } /******************************************************************************* * Function Name: uartPsocTx_read() ****************************************************************************//** * \brief Returns a byte of data from the RX buffer. Does nothing for * the Software TX UART * * \param result [out] * Pointer to the results structure * * \return * Success *******************************************************************************/ uint32_t uartPsocTx_read(uint8_t *result){ (void) result; return COMMS_ERROR_READ; } /******************************************************************************* * Function Name: uartPsocTx_readArray() ****************************************************************************//** * \brief Reads a specified number of bytes into the array * * \param resultArray [out] * Pointer to the results array * * \param len [in] * Number of bytes to read * * \return * Success *******************************************************************************/ uint32_t uartPsocTx_readArray(uint8_t *resultArray, uint16_t len){ (void) resultArray; (void) len; return COMMS_ERROR_READ_ARRAY; } /******************************************************************************* * Function Name: uartPsocTx_getRxBufferSize() ****************************************************************************//** * \brief Gets the number of bytes in the RX buffer * * \param resultArray [out] * Pointer to the results vale * * \return * Success *******************************************************************************/ uint32_t uartPsocTx_getRxBufferSize(uint8_t *result) { (void) result; return COMMS_ERROR_RXBUFFER; } /******************************************************************************* * Function Name: uartPsocTx_getTxBufferSize() ****************************************************************************//** * \brief Gets the number of bytes in the TX buffer * * \param resultArray [out] * Pointer to the results vale * * \return * Success *******************************************************************************/ uint32_t uartPsocTx_getTxBufferSize(uint8_t *result){ (void) result; return COMMS_ERROR_TXBUFFER; } /* [] END OF FILE */
2.078125
2
2024-11-18T20:48:39.000003+00:00
2019-11-25T04:23:25
2875ca0ef4f5efed4a9e2bb6615bf62a8205fb42
{ "blob_id": "2875ca0ef4f5efed4a9e2bb6615bf62a8205fb42", "branch_name": "refs/heads/master", "committer_date": "2019-11-25T04:23:25", "content_id": "0821ffdb5d8df099233f38a3f2d62cf1b887dc40", "detected_licenses": [ "MIT" ], "directory_id": "9888b161ced0b5a1d33502dc9d26a4d861cf7b16", "extension": "c", "filename": "string_binary.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 146616729, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 633, "license": "MIT", "license_type": "permissive", "path": "/Sem1/C/Week 9/string_binary.c", "provenance": "stackv2-0102.json.gz:71106", "repo_name": "nsudhanva/mca-code", "revision_date": "2019-11-25T04:23:25", "revision_id": "812348ce53edbe0f42f85a9c362bfc8aad64e1e7", "snapshot_id": "bef8c3b1b4804010b4bd282896e07e46f498b6f8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nsudhanva/mca-code/812348ce53edbe0f42f85a9c362bfc8aad64e1e7/Sem1/C/Week 9/string_binary.c", "visit_date": "2020-03-27T13:34:07.562016" }
stackv2
#include <stdio.h> #include <string.h> int main() { char letter, choice[2]; int ascii, len, binary[8], total, i; char str[100]; printf("Enter a string: \n"); scanf("%s", &str); len = strlen(str); for(i = 0; i < len; i++) { total = 0; letter = str[i]; ascii = letter; while(ascii > 0) { if((ascii % 2) == 0) { binary[total] = 0; ascii = ascii / 2; total++; } else { binary[total] = 1; ascii = ascii / 2; total++; } } total--; while(total >= 0) { printf("%d", binary[total]); total--; } printf("\n"); } }
3.265625
3
2024-11-18T20:48:39.224218+00:00
2016-05-03T20:01:43
859a3c249aa5d5942307bf5abdc65caf1bed137a
{ "blob_id": "859a3c249aa5d5942307bf5abdc65caf1bed137a", "branch_name": "refs/heads/master", "committer_date": "2016-05-03T20:01:43", "content_id": "00a1353715d5888a39fb2b7e703a5e37e803bd31", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c62e3ca27cd6638021099ff1e3f62bfeb16a3f6b", "extension": "c", "filename": "common_fds.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 57997689, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3022, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/os161/testbin/badcall/common_fds.c", "provenance": "stackv2-0102.json.gz:71363", "repo_name": "Mr-Grieves/os161", "revision_date": "2016-05-03T20:01:43", "revision_id": "15dce345d9ac762afca4a446f15b2a782fd529c7", "snapshot_id": "0a8b6f908883d284a30e5be4477bced4491a2619", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Mr-Grieves/os161/15dce345d9ac762afca4a446f15b2a782fd529c7/os161/testbin/badcall/common_fds.c", "visit_date": "2021-01-01T03:58:40.149978" }
stackv2
/* * Calls with invalid fds */ #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <errno.h> #include <err.h> #include "config.h" #include "test.h" static int read_badfd(int fd) { char buf[128]; return read(fd, buf, sizeof(buf)); } static int write_badfd(int fd) { char buf[128]; memset(buf, 'a', sizeof(buf)); return write(fd, buf, sizeof(buf)); } static int close_badfd(int fd) { return close(fd); } static int ioctl_badfd(int fd) { return ioctl(fd, 0, NULL); } static int lseek_badfd(int fd) { return lseek(fd, 0, SEEK_SET); } static int fsync_badfd(int fd) { return fsync(fd); } static int ftruncate_badfd(int fd) { return ftruncate(fd, 60); } static int fstat_badfd(int fd) { struct stat sb; return fstat(fd, &sb); } static int getdirentry_badfd(int fd) { char buf[32]; return getdirentry(fd, buf, sizeof(buf)); } static int dup2_badfd(int fd) { /* use the +1 to avoid doing dup2(CLOSED_FD, CLOSED_FD) */ return dup2(fd, CLOSED_FD+1); } static void dup2_cleanup(void) { close(CLOSED_FD+1); } //////////////////////////////////////////////////////////// static void any_badfd(int (*func)(int fd), void (*cleanup)(void), const char *callname, int fd, const char *fddesc) { char fulldesc[128]; int rv; snprintf(fulldesc, sizeof(fulldesc), "%s using %s", callname, fddesc); rv = func(fd); report_test(rv, errno, EBADF, fulldesc); if (cleanup) { cleanup(); } } static void runtest(int (*func)(int fd), void (*cleanup)(void), const char *callname) { /* * If adding cases, also see bad_dup2.c */ /* basic invalid case: fd -1 */ any_badfd(func, cleanup, callname, -1, "fd -1"); /* also try -5 in case -1 is special somehow */ any_badfd(func, cleanup, callname, -5, "fd -5"); /* try a fd we know is closed */ any_badfd(func, cleanup, callname, CLOSED_FD, "closed fd"); /* try a positive fd we know is out of range */ any_badfd(func, cleanup, callname, IMPOSSIBLE_FD, "impossible fd"); /* test for off-by-one errors */ #ifdef OPEN_MAX any_badfd(func, cleanup, callname, OPEN_MAX, "fd OPEN_MAX"); #else warnx("Warning: OPEN_MAX not defined, test skipped"); #endif } //////////////////////////////////////////////////////////// #define T(call) \ void \ test_##call##_fd(void) \ { \ runtest(call##_badfd, NULL, #call); \ } #define TC(call) \ void \ test_##call##_fd(void) \ { \ runtest(call##_badfd, call##_cleanup, #call);\ } T(read); T(write); T(close); T(ioctl); T(lseek); T(fsync); T(ftruncate); T(fstat); T(getdirentry); TC(dup2);
2.625
3
2024-11-18T20:48:39.336979+00:00
2018-12-22T20:20:32
ba680e81b5ec1e7eb2af4ec91f585b6f0ad3dd01
{ "blob_id": "ba680e81b5ec1e7eb2af4ec91f585b6f0ad3dd01", "branch_name": "refs/heads/master", "committer_date": "2018-12-22T20:20:32", "content_id": "826f8c50393e18ad7b5ccba2b42e4b6c03e6d36a", "detected_licenses": [ "MIT" ], "directory_id": "b3134aea30ab7362ec16590736935ea66c0716c4", "extension": "c", "filename": "app_error.c", "fork_events_count": 25, "gha_created_at": "2016-10-20T15:26:36", "gha_event_created_at": "2018-12-22T20:14:53", "gha_language": "C", "gha_license_id": "MIT", "github_id": 71476833, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3699, "license": "MIT", "license_type": "permissive", "path": "/jewelbots_solo_mode_v117/cores/JWB_nRF51822/ble-nrf51822-master/source/nordic_sdk/components/libraries/util/app_error.c", "provenance": "stackv2-0102.json.gz:71492", "repo_name": "Jewelbots/arduino-library", "revision_date": "2018-12-22T20:20:32", "revision_id": "b925fdbfd0ced1589defbe430780027c12fa02c4", "snapshot_id": "6bb0ccb1fef11caba80ccc030297124d74309efa", "src_encoding": "UTF-8", "star_events_count": 22, "url": "https://raw.githubusercontent.com/Jewelbots/arduino-library/b925fdbfd0ced1589defbe430780027c12fa02c4/jewelbots_solo_mode_v117/cores/JWB_nRF51822/ble-nrf51822-master/source/nordic_sdk/components/libraries/util/app_error.c", "visit_date": "2021-01-13T07:40:27.352014" }
stackv2
/* Copyright (c) 2014 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ /** @file * * @defgroup app_error Common application error handler * @{ * @ingroup app_common * * @brief Common application error handler. */ #include "nrf.h" #include <stdio.h> #include "app_error.h" #include "nordic_common.h" #include "sdk_errors.h" #include "nrf_log.h" #ifdef __cplusplus extern "C"{ #endif // __cplusplus /**@brief Function for error handling, which is called when an error has occurred. * * @warning This handler is an example only and does not fit a final product. You need to analyze * how your product is supposed to react in case of error. * * @param[in] error_code Error code supplied to the handler. * @param[in] line_num Line number where the handler is called. * @param[in] p_file_name Pointer to the file name. */ /*lint -save -e14 */ void app_error_handler(ret_code_t error_code, uint32_t line_num, const uint8_t * p_file_name) { error_info_t error_info = { .line_num = line_num, .p_file_name = p_file_name, .err_code = error_code, }; app_error_fault_handler(NRF_FAULT_ID_SDK_ERROR, 0, (uint32_t)(&error_info)); UNUSED_VARIABLE(error_info); } /*lint -save -e14 */ void app_error_handler_bare(ret_code_t error_code) { error_info_t error_info = { .line_num = 0, .p_file_name = NULL, .err_code = error_code, }; app_error_fault_handler(NRF_FAULT_ID_SDK_ERROR, 0, (uint32_t)(&error_info)); UNUSED_VARIABLE(error_info); } void app_error_save_and_stop(uint32_t id, uint32_t pc, uint32_t info) { /* static error variables - in order to prevent removal by optimizers */ static volatile struct { uint32_t fault_id; uint32_t pc; uint32_t error_info; assert_info_t * p_assert_info; error_info_t * p_error_info; ret_code_t err_code; uint32_t line_num; const uint8_t * p_file_name; } m_error_data = {0}; // The following variable helps Keil keep the call stack visible, in addition, it can be set to // 0 in the debugger to continue executing code after the error check. volatile bool loop = true; UNUSED_VARIABLE(loop); m_error_data.fault_id = id; m_error_data.pc = pc; m_error_data.error_info = info; switch (id) { case NRF_FAULT_ID_SDK_ASSERT: m_error_data.p_assert_info = (assert_info_t *)info; m_error_data.line_num = m_error_data.p_assert_info->line_num; m_error_data.p_file_name = m_error_data.p_assert_info->p_file_name; break; case NRF_FAULT_ID_SDK_ERROR: m_error_data.p_error_info = (error_info_t *)info; m_error_data.err_code = m_error_data.p_error_info->err_code; m_error_data.line_num = m_error_data.p_error_info->line_num; m_error_data.p_file_name = m_error_data.p_error_info->p_file_name; break; } UNUSED_VARIABLE(m_error_data); // If printing is disrupted, remove the irq calls, or set the loop variable to 0 in the debugger. __disable_irq(); while(loop); __enable_irq(); } /*lint -restore */ #ifdef __cplusplus } // extern "C" #endif // __cplusplus
2.03125
2
2024-11-18T20:48:39.541574+00:00
2023-04-18T15:11:09
d81ce6a2ce29a53ede128635c140055b626216fa
{ "blob_id": "d81ce6a2ce29a53ede128635c140055b626216fa", "branch_name": "refs/heads/master", "committer_date": "2023-04-18T15:11:09", "content_id": "41caa501984f2e2fa91ed23f0201df5e164262f4", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "5a2484e0977e4a451ee5e0e6bc83b8dc7c922eb8", "extension": "c", "filename": "uart_dev.c", "fork_events_count": 0, "gha_created_at": "2020-03-26T16:06:14", "gha_event_created_at": "2020-03-26T16:06:15", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 250306354, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3352, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/drivers/serial/uart_dev.c", "provenance": "stackv2-0102.json.gz:71752", "repo_name": "sha-ahammed/embox", "revision_date": "2023-04-18T15:11:09", "revision_id": "0bea524ab901545e231e4533b5d947f9a647a168", "snapshot_id": "a3030f0293af13000d2d38494f732c5da39b7fd7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sha-ahammed/embox/0bea524ab901545e231e4533b5d947f9a647a168/src/drivers/serial/uart_dev.c", "visit_date": "2023-04-30T16:45:26.520300" }
stackv2
/** * @file * @brief * * @author Anton Kozlov * @date 09.08.2013 */ #include <string.h> #include <stdio.h> #include <errno.h> #include <util/err.h> #include <util/log.h> #include <util/indexator.h> #include <util/dlist.h> #include <util/ring_buff.h> #include <kernel/irq.h> #include <mem/misc/pool.h> #include <drivers/device.h> #include <drivers/char_dev.h> #include <drivers/serial/uart_dev.h> DLIST_DEFINE(uart_list); struct dlist_head *uart_get_list(void) { return &uart_list; } static int uart_attach_irq(struct uart *uart) { int r; if (!(uart->params.uart_param_flags & UART_PARAM_FLAGS_USE_IRQ)) { return 0; } if (!uart->irq_handler) { return -EINVAL; } r = irq_attach(uart->irq_num, uart->irq_handler, 0, uart, uart->dev_name); log_debug("setup tty %s irq num %d result %d", uart->dev_name , uart->irq_num, r); return r; } static int uart_detach_irq(struct uart *uart) { if (uart->params.uart_param_flags & UART_PARAM_FLAGS_USE_IRQ) { return irq_detach(uart->irq_num, uart); } return 0; } static int uart_setup(struct uart *uart) { const struct uart_ops *uops = uart->uart_ops; if (uops->uart_setup) { log_debug("setup tty %s", uart->dev_name); return uops->uart_setup(uart, &uart->params); } return 0; } #define UART_MAX_N OPTION_GET(NUMBER,uart_max_n) INDEX_DEF(serial_indexator, 0, UART_MAX_N); extern int ttys_register(const char *name, void *dev_info); static void uart_internal_init(struct uart *uart) { if (uart_state_test(uart, UART_STATE_INITED)) { return; } uart_state_set(uart, UART_STATE_INITED); ring_buff_init(&uart->uart_rx_ring, sizeof(uart->uart_rx_buff[0]), UART_RX_BUFF_SZ, uart->uart_rx_buff); dlist_add_next(&uart->uart_lnk, &uart_list); } int uart_register(struct uart *uart, const struct uart_params *uart_defparams) { int res; uart->idx = index_alloc(&serial_indexator, INDEX_MIN); if(uart->idx < 0) { return -EBUSY; } snprintf(uart->dev_name, UART_NAME_MAXLEN, "ttyS%d", uart->idx); if (uart_defparams) { memcpy(&uart->params, uart_defparams, sizeof(struct uart_params)); } else { memset(&uart->params, 0, sizeof(struct uart_params)); } res = ttys_register(uart->dev_name, uart); if (0 != res) { log_error("Failed to register tty %s", uart->dev_name); index_free(&serial_indexator, uart->idx); return res; } return 0; } void uart_deregister(struct uart *uart) { dlist_del(&uart->uart_lnk); index_free(&serial_indexator, uart->idx); } int uart_open(struct uart *uart) { if (uart_state_test(uart, UART_STATE_OPEN)) { return -EINVAL; } uart_state_set(uart, UART_STATE_OPEN); uart_internal_init(uart); uart_setup(uart); return uart_attach_irq(uart); } int uart_close(struct uart *uart) { if (!uart_state_test(uart, UART_STATE_OPEN)) { return -EINVAL; } uart_state_clear(uart, UART_STATE_OPEN); return uart_detach_irq(uart); } int uart_set_params(struct uart *uart, const struct uart_params *params) { if (uart_state_test(uart, UART_STATE_OPEN)) { uart_detach_irq(uart); } memcpy(&uart->params, params, sizeof(struct uart_params)); if (uart_state_test(uart, UART_STATE_OPEN)) { uart_attach_irq(uart); uart_setup(uart); } return 0; } int uart_get_params(struct uart *uart, struct uart_params *params) { memcpy(params, &uart->params, sizeof(struct uart_params)); return 0; }
2.59375
3
2024-11-18T20:48:39.621759+00:00
2015-12-19T17:49:53
b50a9a249c2caf88178ee630b5cd0fa79f201ad3
{ "blob_id": "b50a9a249c2caf88178ee630b5cd0fa79f201ad3", "branch_name": "refs/heads/master", "committer_date": "2015-12-19T17:49:53", "content_id": "953ad1bd2eada20380856c3b3b3a4026e8936771", "detected_licenses": [ "MIT" ], "directory_id": "1f599a32417a5a3f9ab6e1722dd8f3513c0502ad", "extension": "c", "filename": "gauss-jordan.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 48291247, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3064, "license": "MIT", "license_type": "permissive", "path": "/gauss-jordan.c", "provenance": "stackv2-0102.json.gz:71880", "repo_name": "vntkumar8/Numerical-Methods", "revision_date": "2015-12-19T17:49:53", "revision_id": "d3133ac880ae67c02ce219d904833c4647e282dd", "snapshot_id": "f68bd58f47ba557b0ba04882898f9c274f341d31", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vntkumar8/Numerical-Methods/d3133ac880ae67c02ce219d904833c4647e282dd/gauss-jordan.c", "visit_date": "2021-01-10T01:33:14.901711" }
stackv2
// Solving set of linear equation by Gauss-Jordan elimination method #include<stdio.h> #include<stdlib.h> #include<math.h> float matrix[10][11]; void display(int); void partial_pivot(int,int); void pivot(int); void nopivot(int); int main(){ int i,j,k,n,choice; printf("Enter the number of variables\n"); scanf("%d",&n); if(n<1){ printf("Invalid number of equation\n"); exit(1); } float multi,sol; for(i=0;i<n;i++){ printf("\nEnter the coefficient of equation %d and its value: ",i+1); for(j=0;j<=n;j++) scanf("%f",&matrix[i][j]); } printf("The augmented matrix:\n\n"); display(n); printf("\n\n"); printf("Input choice\n 1. Without partial pivoting\n 2. With partial pivoting\n 3. Exit\n\n Choice: "); scanf("%d",&choice); switch(choice){ case 1: printf("\t\t\tWithout partial pivoting\n"); nopivot(n); break; case 2: printf("\t\t\tWith partial pivoting\n"); pivot(n); break; case 3: printf("\t\tTerminated!!"); exit(0); default: printf("Invalid choice number entered\n"); exit(2); } printf("The diagonal matrix :\n\n"); display(n); printf("\nThe values of variables are:\n\n"); for(i=0;i<n;i++){ sol=matrix[i][n]/matrix[i][i]; printf(" x%d = %f\n",i+1,sol); } return 0; } void display(int n){ int i,j; for(i=0;i<n;i++){ for(j=0;j<n+1;j++) printf("%10f ",matrix[i][j]); printf("\n"); } } void nopivot(int n){ int i,j,k,l,m; float multi; for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ multi=matrix[j][i]/matrix[i][i]; for(k=i;k<=n;k++) matrix[j][k]=matrix[j][k]-multi*matrix[i][k]; } for(l=0;l<i;l++){ multi=matrix[l][i]/matrix[i][i]; for(m=i;m<=n;m++) matrix[l][m]=matrix[l][m]-multi*matrix[i][m]; } //printf("after %d step matrix is \n",i+1); display(n); printf("\n"); } } void pivot(int n){ int i,j,k,l,m; float multi; for(i=0;i<n;i++){ printf("After Step %d matrix is \n",i+1); printf("Before pivoting row %d\n",i+1); display(n); printf("\n"); partial_pivot(i,n); printf("After pivoting row %d\n",i+1); display(n); printf("\n"); for(j=i+1;j<n;j++){ multi=matrix[j][i]/matrix[i][i]; for(k=i;k<=n;k++) matrix[j][k]=matrix[j][k]-multi*matrix[i][k]; } for(l=0;l<i;l++){ multi=matrix[l][i]/matrix[i][i]; for(m=i;m<=n;m++) matrix[l][m]=matrix[l][m]-multi*matrix[i][m]; } } } void partial_pivot(int i,int n){ //function for pivoting int j,k; float temp; for(j=i+1;j<n;j++){ if(fabs(matrix[i][i])<fabs(matrix[j][i])){ for(k=0;k<=n;k++){ temp=matrix[j][k]; matrix[j][k]=matrix[i][k]; matrix[i][k]=temp; } } } }
3.484375
3
2024-11-18T20:48:40.130093+00:00
2021-10-31T00:50:48
4a68196f1b122d5407ec3b8829bc4f9225fd3b06
{ "blob_id": "4a68196f1b122d5407ec3b8829bc4f9225fd3b06", "branch_name": "refs/heads/main", "committer_date": "2021-10-31T00:51:08", "content_id": "ea56019d7a3c60d4a87b3680525e9768580347c5", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "d9bb656bd11f85e6419ebd786aec6fe3f917cb73", "extension": "h", "filename": "filter.h", "fork_events_count": 10, "gha_created_at": "2021-07-14T19:52:15", "gha_event_created_at": "2021-07-22T23:28:45", "gha_language": "HTML", "gha_license_id": "NOASSERTION", "github_id": 386059959, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 987, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/tools/alignstats/filter.h", "provenance": "stackv2-0102.json.gz:72138", "repo_name": "spiralgenetics/biograph", "revision_date": "2021-10-31T00:50:48", "revision_id": "5f40198e95b0626ae143e021ec97884de634e61d", "snapshot_id": "55a91703a70429568107209ce20e71f6b96577df", "src_encoding": "UTF-8", "star_events_count": 21, "url": "https://raw.githubusercontent.com/spiralgenetics/biograph/5f40198e95b0626ae143e021ec97884de634e61d/tools/alignstats/filter.h", "visit_date": "2023-08-30T18:04:55.636103" }
stackv2
#ifndef _FILTER_H #define _FILTER_H #include "htslib/sam.h" #include "report.h" #include <stdint.h> /* Filter counter structure */ struct filter_counter { uint8_t min_qual; uint16_t filter_incl; uint16_t filter_excl; uint64_t r_filtered; uint64_t r_unfiltered; }; typedef struct filter_counter filter_counter_t; /* Is record filtered by qual? */ #define filter_test_qual(qual, min_qual) \ ((qual) < (min_qual)) /* Is record filtered by flag? */ #define filter_test_flag(flag, filter_incl, filter_excl) \ (((flag) & (filter_incl)) != (filter_incl) || \ ((flag) & (filter_excl)) != 0) filter_counter_t *filter_counter_init(uint8_t min_qual, uint16_t filter_incl, uint16_t filter_excl); void filter_counter_destroy(filter_counter_t *fc); /* Filter counter calculation */ void filter_counter_process_record(bam1_t *rec, filter_counter_t *fc); void filter_counter_report(report_t *report, filter_counter_t *fc); #endif /* _FILTER_H */
2
2
2024-11-18T20:48:40.202720+00:00
2020-12-23T16:34:36
3731f146bbab0ecfd500e9eb0b2911dd8ed46f75
{ "blob_id": "3731f146bbab0ecfd500e9eb0b2911dd8ed46f75", "branch_name": "refs/heads/master", "committer_date": "2020-12-23T16:34:36", "content_id": "76687bbc2f4fde1c1639c68dcfc506c942ef8628", "detected_licenses": [ "MIT" ], "directory_id": "eda1cd2428e95c1e53fa320bf2fb0ff04e34fd9c", "extension": "c", "filename": "matrix.c", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 234312913, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 737, "license": "MIT", "license_type": "permissive", "path": "/esame-29/matrix/matrix.c", "provenance": "stackv2-0102.json.gz:72266", "repo_name": "unimoreinginfo/esami-fdi1", "revision_date": "2020-12-23T16:34:36", "revision_id": "afb5bc8bc6247aaaa5452ebd32c0e69efe9e3b21", "snapshot_id": "121b9912aebd530032db9bb978e277ba48dfecf9", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/unimoreinginfo/esami-fdi1/afb5bc8bc6247aaaa5452ebd32c0e69efe9e3b21/esame-29/matrix/matrix.c", "visit_date": "2023-02-04T01:04:52.474589" }
stackv2
#include "matrix.h" struct matrix* scambia_diagonali(const struct matrix* m) { if (m == NULL || m->rows != m->cols) return NULL; struct matrix* res = malloc(sizeof(struct matrix) * 1); res->rows = m->rows; res->cols = m->cols; res->data = malloc(sizeof(double) * res->rows * res->cols); // copy for (size_t r = 0; r < m->rows; r++) { for (size_t c = 0; c < m->cols; c++) { res->data[r * res->cols + c] = m->data[r * m->cols + c]; } } // swap for (size_t d = 0; d < m->rows; d++) { size_t ad_r = d; size_t ad_c = res->rows - d - 1; double m_d = res->data[d * res->cols + d]; res->data[d * res->cols + d] = res->data[ad_r * res->cols + ad_c]; res->data[ad_r * res->cols + ad_c] = m_d; } return res; }
3
3
2024-11-18T20:48:40.270079+00:00
2023-08-31T14:51:12
c4179f4562ce4e03d78e1c5634711ed316a855d9
{ "blob_id": "c4179f4562ce4e03d78e1c5634711ed316a855d9", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T14:51:12", "content_id": "c6f41d28ee0f12feb07ae9ae12749b84e0e7de8c", "detected_licenses": [], "directory_id": "9de0cec678bc4a3bec2b4adabef9f39ff5b4afac", "extension": "c", "filename": "AddTaskJetRandomizer.C", "fork_events_count": 1150, "gha_created_at": "2016-06-21T19:31:29", "gha_event_created_at": "2023-09-14T18:48:45", "gha_language": "C++", "gha_license_id": "BSD-3-Clause", "github_id": 61661378, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1973, "license": "", "license_type": "permissive", "path": "/PWGJE/EMCALJetTasks/macros/AddTaskJetRandomizer.C", "provenance": "stackv2-0102.json.gz:72394", "repo_name": "alisw/AliPhysics", "revision_date": "2023-08-31T14:51:12", "revision_id": "5df28b2b415e78e81273b0d9bf5c1b99feda3348", "snapshot_id": "91bf1bd01ab2af656a25ff10b25e618a63667d3e", "src_encoding": "UTF-8", "star_events_count": 129, "url": "https://raw.githubusercontent.com/alisw/AliPhysics/5df28b2b415e78e81273b0d9bf5c1b99feda3348/PWGJE/EMCALJetTasks/macros/AddTaskJetRandomizer.C", "visit_date": "2023-08-31T20:41:44.927176" }
stackv2
// $Id$ AliJetRandomizerTask* AddTaskJetRandomizer( const char *tracksName = "Tracks", const char *clusName = "CaloClustersCorr", const char *taskName = "JetRandomizerTask", const Double_t minEta = -0.9, const Double_t maxEta = 0.9, const Double_t minPhi = 0, const Double_t maxPhi = TMath::Pi() * 2, const Int_t nTracks = 1, const Int_t nClus = 0, const Bool_t copyArray = kTRUE ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJetRandomizer", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJetRandomizer", "This task requires an input event handler"); return NULL; } //------------------------------------------------------- // Init the task and do settings //------------------------------------------------------- AliJetRandomizerTask *jetRand = new AliJetRandomizerTask(taskName); jetRand->SetTracksName(tracksName); jetRand->SetClusName(clusName); jetRand->SetEtaRange(minEta, maxEta); jetRand->SetPhiRange(minPhi, maxPhi); jetRand->SetCopyArray(copyArray); jetRand->SetNClusters(nClus); jetRand->SetNTracks(nTracks); //------------------------------------------------------- // Final settings, pass to manager and set the containers //------------------------------------------------------- mgr->AddTask(jetRand); // Create containers for input/output mgr->ConnectInput (jetRand, 0, mgr->GetCommonInputContainer() ); return jetRand; }
2.1875
2
2024-11-18T20:48:40.345956+00:00
2023-02-16T11:27:40
fa36064d63ab689831b248df83fe87cf0d748df2
{ "blob_id": "fa36064d63ab689831b248df83fe87cf0d748df2", "branch_name": "refs/heads/main", "committer_date": "2023-02-16T14:59:16", "content_id": "cdf0b295a8db39954c27287fc86b19d69c238c65", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493", "extension": "c", "filename": "socket_echo.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": 1929, "license": "Apache-2.0", "license_type": "permissive", "path": "/samples/net/sockets/echo/src/socket_echo.c", "provenance": "stackv2-0102.json.gz:72522", "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/samples/net/sockets/echo/src/socket_echo.c", "visit_date": "2023-09-04T00:20:35.217393" }
stackv2
/* * Copyright (c) 2017 Linaro Limited * * SPDX-License-Identifier: Apache-2.0 */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #ifndef __ZEPHYR__ #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #else #include <zephyr/net/socket.h> #include <zephyr/kernel.h> #endif #define BIND_PORT 4242 void main(void) { int serv; struct sockaddr_in bind_addr; static int counter; serv = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (serv < 0) { printf("error: socket: %d\n", errno); exit(1); } bind_addr.sin_family = AF_INET; bind_addr.sin_addr.s_addr = htonl(INADDR_ANY); bind_addr.sin_port = htons(BIND_PORT); if (bind(serv, (struct sockaddr *)&bind_addr, sizeof(bind_addr)) < 0) { printf("error: bind: %d\n", errno); exit(1); } if (listen(serv, 5) < 0) { printf("error: listen: %d\n", errno); exit(1); } printf("Single-threaded TCP echo server waits for a connection on " "port %d...\n", BIND_PORT); while (1) { struct sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); char addr_str[32]; int client = accept(serv, (struct sockaddr *)&client_addr, &client_addr_len); if (client < 0) { printf("error: accept: %d\n", errno); continue; } inet_ntop(client_addr.sin_family, &client_addr.sin_addr, addr_str, sizeof(addr_str)); printf("Connection #%d from %s\n", counter++, addr_str); while (1) { char buf[128], *p; int len = recv(client, buf, sizeof(buf), 0); int out_len; if (len <= 0) { if (len < 0) { printf("error: recv: %d\n", errno); } break; } p = buf; do { out_len = send(client, p, len, 0); if (out_len < 0) { printf("error: send: %d\n", errno); goto error; } p += out_len; len -= out_len; } while (len); } error: close(client); printf("Connection from %s closed\n", addr_str); } }
2.671875
3
2024-11-18T20:48:41.292828+00:00
2020-01-31T05:56:43
a377ff7f00ec339417d2bb5551f7a72ec031b081
{ "blob_id": "a377ff7f00ec339417d2bb5551f7a72ec031b081", "branch_name": "refs/heads/master", "committer_date": "2020-01-31T05:56:43", "content_id": "bd75bbcda915e965677aeb3c420c32adc7d618f5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "87975282a70cde78f15c887d83b8c99dae6ff41c", "extension": "c", "filename": "syscall.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": 1237, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/kernel/syscall.c", "provenance": "stackv2-0102.json.gz:72650", "repo_name": "reymontero/JSD-OS", "revision_date": "2020-01-31T05:56:43", "revision_id": "f47679b4a326083edf90f76feebe8d0aa9f74b67", "snapshot_id": "b55f250e1c863f029f2d314fb8649579443841ea", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/reymontero/JSD-OS/f47679b4a326083edf90f76feebe8d0aa9f74b67/kernel/syscall.c", "visit_date": "2022-04-07T02:24:08.716905" }
stackv2
#include "interrupt.h" #include "syscall.h" #include "filesystem.h" #include "task.h" #include "memorymanager.h" #include "../drivers/sysclock.h" #include "../drivers/kbrd.h" #include "../drivers/video.h" //A syscall is accomplished by //putting the arguments into EAX, ECX, EDX, EDI, ESI //put the system call index into EBX //int 0x80 //EAX has the return value SYSCALL_HANDLER int _empty() { return 0; } extern void handle_syscall(); const void* syscall_table[] = { filesystem_find_file_by_path, filesystem_open_file, filesystem_close_file, filesystem_read_file, exit_process, spawn_process, sysclock_get_master_time, sysclock_get_ticks, sysclock_get_utc_offset, memmanager_virtual_alloc, memmanager_free_pages, get_keypress, wait_and_get_keypress, filesystem_open_file_handle, filesystem_open_directory_handle, filesystem_get_file_in_dir, filesystem_get_file_info, filesystem_get_root_directory, set_video_mode, map_video_memory, filesystem_open_directory, filesystem_close_directory, set_cursor_offset, get_keystate }; const size_t num_syscalls = sizeof(syscall_table) / sizeof(void*); void setup_syscalls() { idt_install_handler(0x80, handle_syscall, IDT_SEGMENT_KERNEL, IDT_SOFTWARE_INTERRUPT); }
2.140625
2
2024-11-18T20:48:41.415361+00:00
2023-07-19T20:53:51
e96dc89385e2487644fa5843d4ff3936f6cf242b
{ "blob_id": "e96dc89385e2487644fa5843d4ff3936f6cf242b", "branch_name": "refs/heads/master", "committer_date": "2023-07-19T20:53:51", "content_id": "6a5f44a2ae80ceebcf6d2c0cc72dbe3b73324383", "detected_licenses": [ "MIT" ], "directory_id": "500204a4900d970909905fbd88f2736fa7d2f749", "extension": "c", "filename": "mfserstd.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 12344640, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5714, "license": "MIT", "license_type": "permissive", "path": "/mfstdsrc/mfserstd.c", "provenance": "stackv2-0102.json.gz:72778", "repo_name": "greymattr/StashHouse", "revision_date": "2023-07-19T20:53:51", "revision_id": "e177347fbc0b850e9869ae96fdb99af060a9eb92", "snapshot_id": "5533ccb1abe385e9aa249d0eff47bd8acaf1b7cc", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/greymattr/StashHouse/e177347fbc0b850e9869ae96fdb99af060a9eb92/mfstdsrc/mfserstd.c", "visit_date": "2023-07-24T15:52:15.055169" }
stackv2
/********************************************************************** * mfserstd.c - description: * --------------------------- * begin : Fri Aug 2 2002 * copyright : (C)2002 by Matthew Fatheree of Lantronix * email : Matthewf@lantronix.com * **********************************************************************/ /********************************************************************** * * Copyright 2001, Lantronix * * All rights reserved, The contents of this file may not be used * and/or copied in any form or by any means without the written * permission of Lantronix. * **********************************************************************/ #include "mfserstd.h" int init_ser( int p ) { int sd; switch( p ) { case 1: sd = open( "/dev/ttyE0", O_RDWR ); break; case 2: sd = open( "/dev/ttyE1", O_RDWR ); break; case 3: sd = open( "/dev/ttyE2", O_RDWR ); break; case 4: sd = open( "/dev/ttyE3", O_RDWR ); break; default: // add debug here printf( "serial port number %d not supported\n\r", p ); return -1; } if( sd < 0 ) { printf( "could not open serial port ( %d )\n\r", sd ); } else { /* set the port to blocking */ fcntl( sd, F_SETFL, 0 ); } return sd; } int init_file( char *name ) { int sd; sd = open( name, O_RDWR | O_CREAT | O_TRUNC, 0667 ); if( sd < 0 ) { printf( "could not open file %s (%d)\n\r", name, sd ); } return sd; } void non_block( int d ) { fcntl( d, F_SETFL, FNDELAY ); return ; } void block( int d ) { fcntl( d, F_SETFL, 0 ); return; } void set_baud( int sd, int baud ) { struct termios tmp; tcgetattr( sd, &tmp ); cfsetispeed( &tmp, baud ); cfsetospeed( &tmp, baud ); tcsetattr( sd, TCSAFLUSH, &tmp ); return; } void set_parity( int sd, int p ) { struct termios tmp; tcgetattr( sd, &tmp ); switch( p ) { case MF_NOPARITY: tmp.c_cflag &= ~PARENB; break; case MF_EVPARITY: tmp.c_cflag |= PARENB; tmp.c_cflag &= ~PARODD; break; case MF_ODPARITY: tmp.c_cflag |= PARENB; tmp.c_cflag |= PARODD; break; } tcsetattr( sd, TCSAFLUSH, &tmp ); return; } void set_maxread( int sd, int num ) { struct termios tmp; tcgetattr( sd, &tmp ); tmp.c_cc[VTIME] = 0; /* inter-character timer unused */ tmp.c_cc[VMIN] = num; /* blocking read until 5 chars received */ tcflush( sd, TCIFLUSH ); tcsetattr( sd,TCSANOW,&tmp ); return; } void set_max_char_delay( int sd, int num ) { struct termios tmp; tcgetattr( sd, &tmp ); tmp.c_cc[VTIME] = num; /* inter-character timer unused */ tmp.c_cc[VMIN] = 0; /* blocking read until 5 chars received */ tcflush( sd, TCIFLUSH ); tcsetattr( sd,TCSANOW,&tmp ); return; } void set_charsize( int sd, int size ) { struct termios tmp; tcgetattr( sd, &tmp ); switch( size ) { case MF_8BIT: tmp.c_cflag |= CS8; break; case MF_7BIT: tmp.c_cflag |= CS7; break; case MF_6BIT: tmp.c_cflag |= CS6; break; case MF_5BIT: tmp.c_cflag |= CS5; break; } tcsetattr( sd, TCSAFLUSH, &tmp ); return; } void set_flowctrl( int sd, int flow ) { struct termios tmp; tcgetattr( sd, &tmp ); switch( flow ) { case MF_NONE: tmp.c_cflag &= ~CRTSCTS; tmp.c_iflag &= ~( IXON | IXOFF | IXANY ); break; case MF_HARD: tmp.c_cflag |= CRTSCTS; break; case MF_SOFT: tmp.c_iflag |= ( IXON | IXOFF | IXANY ); break; } tcsetattr( sd, TCSAFLUSH, &tmp ); return; } int init_serial( char *p ) { int sd; struct termios options; sd = open( p, O_RDWR | O_NDELAY ); /* get the current options */ tcgetattr( sd, &options ); /* set raw input, 1 second timeout */ options.c_cflag |= ( CLOCAL | CREAD ); options.c_lflag &= ~( ICANON | ECHO | ECHOE | ISIG ); options.c_oflag &= ~OPOST; options.c_cc[VMIN] = 0; options.c_cc[VTIME] = 10; /* set the options */ tcsetattr( sd, TCSANOW, &options ); #ifdef _DEBUG if( sd < 0 ) { printf( "could not open serial port %s ( %d )\n\r",p, sd ); } #endif return sd; } int cd_hi( int sd ) { int status; ioctl( sd, TIOCMGET, &status ); status &= ~TIOCM_DTR; return ( ioctl( sd, TIOCMSET, &status ) ); } int rts_low( int sd ) { int status; ioctl( sd, TIOCMGET, &status ); status =+ TIOCM_DTR; return ( ioctl( sd, TIOCMSET, &status ) ); } int cts_low( int sd ) { int status; ioctl( sd, TIOCMGET, &status ); status += TIOCM_DSR; //status &= ~TIOCM_RTS; return ( ioctl( sd, TIOCMSET, &status ) ); } int cts_hi( int sd ) { int status; ioctl( sd, TIOCMGET, &status ); status +=TIOCM_RTS; return ( ioctl( sd, TIOCMSET, &status ) ); } int cd_low( int sd ) { int status; ioctl( sd, TIOCMGET, &status ); status &= ~TIOCM_RTS; return ( ioctl( sd, TIOCMSET, &status ) ); } unsigned int get_ser_stat( int ser ) { int st = 0; int status; ioctl( ser, TIOCMGET, &status ); if( status & TIOCM_CTS ) { st += SIG_CTS; } if( status & TIOCM_DTR ) { st += SIG_DTR; } if( status & TIOCM_LE ) { st += SIG_DTS; } if( status & TIOCM_RTS ) { st += SIG_RTS; } if( status & TIOCM_CD ) { st += SIG_CD; } return st; } int mwrite( int fd, char *buf, int size ) { int mbo = 0; int i; //fcntl(fd, F_SETFL, 0); while( mbo < size ) { i = write( fd, buf + mbo, size - mbo ); if( i > 0 ) { mbo += i; } //if( i < 0 ) return i; } //fcntl(fd, F_SETFL, O_NONBLOCK); return mbo; }
2.359375
2
2024-11-18T20:48:41.749119+00:00
2020-05-01T01:25:27
6817dbe48e55a359dd171bfdc70a128de6656c66
{ "blob_id": "6817dbe48e55a359dd171bfdc70a128de6656c66", "branch_name": "refs/heads/master", "committer_date": "2020-05-01T01:25:27", "content_id": "51aa2633397dade2a5829853be1cb0ade59cff68", "detected_licenses": [ "MIT" ], "directory_id": "33a63d78191eaf2342b5cdf1036448e7b6b38fc8", "extension": "c", "filename": "SRC.C", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 231872879, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 973, "license": "MIT", "license_type": "permissive", "path": "/src/SRC.C", "provenance": "stackv2-0102.json.gz:73037", "repo_name": "rururutan/xasm-w64", "revision_date": "2020-05-01T01:25:27", "revision_id": "2db595aa679c570174833ab2d847c54de16febfc", "snapshot_id": "d6a354f8c5f1a33fdb2160706ae408fa53cd8d51", "src_encoding": "SHIFT_JIS", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rururutan/xasm-w64/2db595aa679c570174833ab2d847c54de16febfc/src/SRC.C", "visit_date": "2020-12-04T18:51:18.927171" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> extern char srcfile[FILENAME_MAX]; static char inc_src[64]; static FILE *s[8]; static int filelevel=0; int open_src(void) { if((s[0]=fopen(srcfile,"rt")) == NULL) return 0; else return 1; } int open_inc(char *filename) { filelevel++; if((s[filelevel]=fopen(filename,"rt")) == NULL) return 0; else return 1; } void close_src(void) { do{ fclose(s[filelevel]); }while(filelevel--); } char *src_gets(char *buff,int n,int *level) { char *c; for(;;){ c=fgets(buff,n,s[filelevel]); if(c==NULL){ /* s[filelevel]が空だったら・・ */ if(filelevel==0){ /* filelevel==0ならおおもとのソースが空である */ *level=0; return NULL; }else{ /* で、なければ・・ */ fclose(s[filelevel]); /* s[filelevel]をクローズして */ filelevel--; /* filelevelを一つ落とす */ } }else{ break; } } *level= filelevel; return c; }
2.5625
3
2024-11-18T20:48:42.186305+00:00
2018-06-13T04:51:27
9a085833bacc5c5e7d03ac5ef510e2072cd79d11
{ "blob_id": "9a085833bacc5c5e7d03ac5ef510e2072cd79d11", "branch_name": "refs/heads/master", "committer_date": "2018-06-13T04:51:27", "content_id": "f58e8ba4568020734975a7bf863f64044121b3d4", "detected_licenses": [ "MIT" ], "directory_id": "0e3f8842258bf8bdb7241ff96fbf4088da269959", "extension": "c", "filename": "teste.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 130484250, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7345, "license": "MIT", "license_type": "permissive", "path": "/MyShell-Test/teste.c", "provenance": "stackv2-0102.json.gz:73553", "repo_name": "bfprivati/my-shell", "revision_date": "2018-06-13T04:51:27", "revision_id": "89163ae01fe2d778ab18ee8b619c4b5984699e48", "snapshot_id": "4324e5b3f244f17569b9ffcdfebf07fdedc94967", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bfprivati/my-shell/89163ae01fe2d778ab18ee8b619c4b5984699e48/MyShell-Test/teste.c", "visit_date": "2020-03-12T06:23:37.577727" }
stackv2
/* Bruno Vedoveto Leandro Giovanna Cazelato Pires Wesley Otto */ #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #define STR_MAX 255 void clear_input(char*); int create_process(char***, int); void ignore_handler(int); int test_stdin(char*); void replaceHomeDir(char*); void signal_handler(); void typePrompt(); int create_process(char***, int); int spawn_proc(int, int, char**); void clean_up_child_process (int signal_number) { /* Clean up the child process. */ int status; wait(&status); } int main() { char fullCommand[STR_MAX]; //fullCommand[0] = ' '; int firstArgCount; signal_handler(); while(1) { // Repeats forever // Reads and parser user input do{ typePrompt(); // Shows prompt on screen clear_input(fullCommand); //Clear stdin // Reads and parser user input fgets(fullCommand, sizeof(char) * STR_MAX, stdin); if (fullCommand[strlen(fullCommand)-1] == '\n') fullCommand[strlen(fullCommand)-1] = '\0'; }while(!(test_stdin(fullCommand))); // If the user types "exit" the shell is exited if (strcmp(fullCommand, "exit") == 0) exit(0); /* BEGIN -------------------------- building arg_list -------------------------- */ // Counts pipes char *token_p; char tokenFullCommand[STR_MAX]; strcpy(tokenFullCommand, fullCommand); int pipeCount = -1; for(token_p = strtok(tokenFullCommand, "|"); token_p != NULL; token_p = strtok(NULL, "|")) pipeCount++; // Allocate the arg_list for pipes char*** arg_list = (char***) malloc((pipeCount+1) * sizeof(char**)); // Allocate the command array char** command = (char**) malloc((pipeCount+1) * sizeof(char*)); int i_command = 0; strcpy(tokenFullCommand, fullCommand); for(token_p = strtok(tokenFullCommand, "|"); token_p != NULL; token_p = strtok(NULL, "|")) { command[i_command] = (char*) malloc(STR_MAX * sizeof(char)); strcpy(command[i_command], token_p); i_command++; } i_command = 0; strcpy(tokenFullCommand, fullCommand); while(i_command <= pipeCount) { // Counts tokens char *token; char tokenCommand[STR_MAX]; strcpy(tokenCommand, command[i_command]); int argCount = 0; for(token = strtok(tokenCommand, " "); token != NULL; token = strtok(NULL, " ")) argCount++; if (i_command == 0) firstArgCount = argCount; // Store to use in "Change Dir" (CD) part // Allocate the arg_list for commands arg_list[i_command] = (char**) malloc((argCount+1) * sizeof(char*)); // Copies the tokens values to arg_list int j_command = 0; strcpy(tokenCommand, command[i_command]); for(token = strtok(tokenCommand, " "); token != NULL; token = strtok(NULL, " ")) { // Allocate the arg_list for arguments arg_list[i_command][j_command] = (char*) malloc(STR_MAX * sizeof(char)); strcpy(arg_list[i_command][j_command], token); j_command++; } arg_list[i_command][j_command] = NULL; i_command++; } /* END -------------------------- building arg_list -------------------------- */ // Check for "Change Dir (CD)" if (strcmp(arg_list[0][0], "cd") == 0) { if (arg_list[0][1] == NULL) { char homeDir[50] = ""; strcpy(homeDir, getenv("HOME")); arg_list[0][1] = (char*) malloc(STR_MAX * sizeof(char)); strcpy(arg_list[0][1], homeDir); } if (chdir(arg_list[0][1]) != 0) fprintf(stderr, "cd: '%s' file or directory not found\n", arg_list[0][1]); continue; } int stdin_cp = STDIN_FILENO; int stdout_cp = STDOUT_FILENO; create_process(arg_list, pipeCount+1); // cmd count should be pipeCount+1 [Example: ls | cat ]. 1 pipe. 2 commands. wait(0); dup2(stdin_cp, STDIN_FILENO); dup2(stdout_cp, STDOUT_FILENO); } // END SHELL WHILE(1) } int create_process(char ***arg_list, int cmd_count) { int command_i; pid_t pid; int in, out, pipe_fd[2]; /* The first process should get its input from the original file descriptor STDIN_FILENO. */ in = STDIN_FILENO; /* Spawn all process here. */ for (command_i = 0; command_i < cmd_count; command_i++) { pipe(pipe_fd); /* The last process should write to the original file descriptor STDOUT_FILENO. */ if (command_i == cmd_count-1) out = STDOUT_FILENO; else out = pipe_fd[1]; /* pipe_fd[1] is the write end of the pipe, we carry "in" from the previous iteration. */ if ( (pid = spawn_proc(in, out, arg_list[command_i])) < 0 ) { fprintf(stderr, "Command '%s' not found\n", arg_list[command_i][0]); exit(-1); } /* No need for the write end of the pipe, the child will write here. */ close(pipe_fd[1]); /* Keep the read end of the pipe, the next child will read from there. */ in = pipe_fd[0]; } return pid; } int spawn_proc(int in, int out, char **command) { pid_t pid; if ((pid = fork()) == 0) { if (in != STDIN_FILENO) { dup2(in, STDIN_FILENO); close(in); } if (out != STDOUT_FILENO) { dup2(out, STDOUT_FILENO); close(out); } return execvp(command[0], command); } return pid; } void typePrompt(){ //Initiate prompt fprintf(stdout, "[MySh] "); //Prompt user and hostname char username[50] = ""; strcpy(username, getenv("USER")); char hostname[50] = ""; gethostname(hostname, sizeof(hostname)); fprintf(stdout, "%s@%s:", username, hostname); //Prompt current directory char currDir[STR_MAX] = ""; getcwd(currDir, sizeof(currDir)); replaceHomeDir(currDir); fprintf(stdout, "%s$ ", currDir); } void replaceHomeDir(char* currDir) { char homeDir[50] = ""; strcpy(homeDir, getenv("HOME")); char tmpCurrDir[STR_MAX] = ""; strcpy(tmpCurrDir, currDir); tmpCurrDir[strlen(homeDir)] = '\0'; if (strcmp(tmpCurrDir, homeDir) == 0) { strncpy(tmpCurrDir, currDir + strlen(homeDir), strlen(currDir) - strlen(homeDir) + 1); strcpy(currDir, "~"); strcat(currDir, tmpCurrDir); } } int test_stdin(char* fullCommand){ if (feof(stdin)) { // CTRL-D case strcpy(fullCommand, "exit"); } else if (ferror(stdin)) { // Clears the error indication flag and ^C, ^Z or any other unknown character clearerr(stdin); return 0; } return 1; } void signal_handler(){ // CTRL + C SIGNAL struct sigaction sigint_action; memset(&sigint_action, 0, sizeof(sigint_action)); sigint_action.sa_handler = &ignore_handler; sigaction(SIGINT, &sigint_action, NULL); // CTRL + Z SIGNAL struct sigaction sigstp_action; memset(&sigstp_action, 0, sizeof(sigstp_action)); sigstp_action.sa_handler = SIG_IGN; sigaction(SIGTSTP, &sigstp_action, NULL); /* Handle SIGCHLD by calling clean_up_child_process. */ struct sigaction sigchld_action; memset (&sigchld_action, 0, sizeof(sigchld_action)); sigchld_action.sa_handler = &clean_up_child_process; sigaction(SIGCHLD, &sigchld_action, NULL); } void ignore_handler(int signal_number){ fprintf(stdout, "\n"); return; } void clear_input(char* fullCommand) { fflush(stdin); fullCommand[0] = '\0'; }
3.015625
3
2024-11-18T20:48:42.457429+00:00
2016-06-04T05:01:09
c0ee3225c97cd3119192c135d401d348c4e163d7
{ "blob_id": "c0ee3225c97cd3119192c135d401d348c4e163d7", "branch_name": "refs/heads/master", "committer_date": "2016-06-04T05:01:09", "content_id": "26beb0d9d7840234dcf0bb107f8761330b8bb9f7", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "b987fbb7660d57ed66fafc3e38c70d681ead12ca", "extension": "c", "filename": "lcd_drv.c", "fork_events_count": 3, "gha_created_at": "2013-08-13T18:26:35", "gha_event_created_at": "2018-08-23T10:33:56", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 12089174, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2235, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/lcdtest/lcd_drv.c", "provenance": "stackv2-0102.json.gz:73681", "repo_name": "skeezix/zikzak", "revision_date": "2016-06-04T05:01:09", "revision_id": "db4b1c86519cd2738cfed3e646e058980c452d20", "snapshot_id": "13a769c27aad324a504efead0d8b45b1da3ebfeb", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/skeezix/zikzak/db4b1c86519cd2738cfed3e646e058980c452d20/lcdtest/lcd_drv.c", "visit_date": "2021-01-21T04:27:13.940002" }
stackv2
#include "main.h" #include "lcd_drv.h" uint8_t lcd_pos = LCD_LINE1; static void lcd_nibble( uint8_t d ) { LCD_D7 = 0; if( d & 1<<7 ) LCD_D7 = 1; LCD_D6 = 0; if( d & 1<<6 ) LCD_D6 = 1; LCD_D5 = 0; if( d & 1<<5 ) LCD_D5 = 1; LCD_D4 = 0; if( d & 1<<4 ) LCD_D4 = 1; LCD_E0 = 1; _delay_us( LCD_TIME_ENA ); LCD_E0 = 0; } static void lcd_byte( uint8_t d ) { lcd_nibble( d ); lcd_nibble( d<<4 ); _delay_us( LCD_TIME_DAT ); } void lcd_command( uint8_t d ) { LCD_RS = 0; lcd_byte( d ); switch( d ){ case 0 ... 3: // on longer commands _delay_us( LCD_TIME_CLR ); d = LCD_LINE1; case 0x80 ... 0xFF: // set position lcd_pos = d; } } void lcd_putchar( uint8_t d ) { LCD_RS = 1; lcd_byte( d ); switch( ++lcd_pos ){ case LCD_LINE1 + LCD_COLUMN: d = LCD_LINE2; break; case LCD_LINE2 + LCD_COLUMN: d = LCD_LINE1; break; default: return; } lcd_command( d ); } void lcd_puts( void *s ) // display string from SRAM { uint8_t *s1; for( s1 = s; *s1; s1++ ) // until zero byte lcd_putchar( *s1 ); } void lcd_blank( uint8_t len ) // blank n digits { while( len-- ) lcd_putchar( ' ' ); } void lcd_init( void ) { LCD_DDR_D4 = 1; // enable output pins LCD_DDR_D5 = 1; LCD_DDR_D6 = 1; LCD_DDR_D7 = 1; LCD_DDR_RS = 1; LCD_DDR_E0 = 1; LCD_E0 = 0; LCD_RS = 0; // send commands _delay_ms( 15 ); lcd_nibble( 0x30 ); _delay_ms( 4.1 ); lcd_nibble( 0x30 ); _delay_us( 100 ); lcd_nibble( 0x30 ); _delay_us( LCD_TIME_DAT ); lcd_nibble( 0x20 ); // 4 bit mode _delay_us( LCD_TIME_DAT ); lcd_command( 0x28 ); // 2 lines 5*7 lcd_command( 0x08 ); // display off lcd_command( 0x01 ); // display clear lcd_command( 0x06 ); // cursor increment lcd_command( 0x0C ); // on, no cursor, no blink }
2.921875
3
2024-11-18T20:48:42.637080+00:00
2022-01-27T22:44:08
f17cdbe298be08c19ccf04090f8e97d0f3dc5cad
{ "blob_id": "f17cdbe298be08c19ccf04090f8e97d0f3dc5cad", "branch_name": "refs/heads/master", "committer_date": "2022-01-27T22:44:08", "content_id": "17cd357a0698e568a3c7670ef9efbedf69237f16", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cfe4e142cbaef8097408138d89dc68803f17db75", "extension": "h", "filename": "traversal.h", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 128884942, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9683, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/kernel/bvh/traversal.h", "provenance": "stackv2-0102.json.gz:73941", "repo_name": "boberfly/cycles", "revision_date": "2022-01-27T22:44:08", "revision_id": "822f565393d3681e0b186e4196fe393b80e26990", "snapshot_id": "6abf10d2f77db95bbecc5257ad06ae7ccd87699c", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/boberfly/cycles/822f565393d3681e0b186e4196fe393b80e26990/src/kernel/bvh/traversal.h", "visit_date": "2022-03-01T21:28:20.283057" }
stackv2
/* * Adapted from code Copyright 2009-2010 NVIDIA Corporation, * and code copyright 2009-2012 Intel Corporation * * Modifications Copyright 2011-2013, Blender Foundation. * * 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. */ #if BVH_FEATURE(BVH_HAIR) # define NODE_INTERSECT bvh_node_intersect #else # define NODE_INTERSECT bvh_aligned_node_intersect #endif /* This is a template BVH traversal function, where various features can be * enabled/disabled. This way we can compile optimized versions for each case * without new features slowing things down. * * BVH_HAIR: hair curve rendering * BVH_POINTCLOUD: point cloud rendering * BVH_MOTION: motion blur rendering */ ccl_device_noinline bool BVH_FUNCTION_FULL_NAME(BVH)(KernelGlobals kg, ccl_private const Ray *ray, ccl_private Intersection *isect, const uint visibility) { /* todo: * - test if pushing distance on the stack helps (for non shadow rays) * - separate version for shadow rays * - likely and unlikely for if() statements * - test restrict attribute for pointers */ /* traversal stack in CUDA thread-local memory */ int traversal_stack[BVH_STACK_SIZE]; traversal_stack[0] = ENTRYPOINT_SENTINEL; /* traversal variables in registers */ int stack_ptr = 0; int node_addr = kernel_data.bvh.root; /* ray parameters in registers */ float3 P = ray->P; float3 dir = bvh_clamp_direction(ray->D); float3 idir = bvh_inverse_direction(dir); int object = OBJECT_NONE; #if BVH_FEATURE(BVH_MOTION) Transform ob_itfm; #endif isect->t = ray->t; isect->u = 0.0f; isect->v = 0.0f; isect->prim = PRIM_NONE; isect->object = OBJECT_NONE; /* traversal loop */ do { do { /* traverse internal nodes */ while (node_addr >= 0 && node_addr != ENTRYPOINT_SENTINEL) { int node_addr_child1, traverse_mask; float dist[2]; float4 cnodes = kernel_tex_fetch(__bvh_nodes, node_addr + 0); { traverse_mask = NODE_INTERSECT(kg, P, #if BVH_FEATURE(BVH_HAIR) dir, #endif idir, isect->t, node_addr, visibility, dist); } node_addr = __float_as_int(cnodes.z); node_addr_child1 = __float_as_int(cnodes.w); if (traverse_mask == 3) { /* Both children were intersected, push the farther one. */ bool is_closest_child1 = (dist[1] < dist[0]); if (is_closest_child1) { int tmp = node_addr; node_addr = node_addr_child1; node_addr_child1 = tmp; } ++stack_ptr; kernel_assert(stack_ptr < BVH_STACK_SIZE); traversal_stack[stack_ptr] = node_addr_child1; } else { /* One child was intersected. */ if (traverse_mask == 2) { node_addr = node_addr_child1; } else if (traverse_mask == 0) { /* Neither child was intersected. */ node_addr = traversal_stack[stack_ptr]; --stack_ptr; } } } /* if node is leaf, fetch triangle list */ if (node_addr < 0) { float4 leaf = kernel_tex_fetch(__bvh_leaf_nodes, (-node_addr - 1)); int prim_addr = __float_as_int(leaf.x); if (prim_addr >= 0) { const int prim_addr2 = __float_as_int(leaf.y); const uint type = __float_as_int(leaf.w); /* pop */ node_addr = traversal_stack[stack_ptr]; --stack_ptr; /* primitive intersection */ for (; prim_addr < prim_addr2; prim_addr++) { kernel_assert(kernel_tex_fetch(__prim_type, prim_addr) == type); const int prim_object = (object == OBJECT_NONE) ? kernel_tex_fetch(__prim_object, prim_addr) : object; const int prim = kernel_tex_fetch(__prim_index, prim_addr); if (intersection_skip_self_shadow(ray->self, prim_object, prim)) { continue; } switch (type & PRIMITIVE_ALL) { case PRIMITIVE_TRIANGLE: { if (triangle_intersect( kg, isect, P, dir, isect->t, visibility, prim_object, prim, prim_addr)) { /* shadow ray early termination */ if (visibility & PATH_RAY_SHADOW_OPAQUE) return true; } break; } #if BVH_FEATURE(BVH_MOTION) case PRIMITIVE_MOTION_TRIANGLE: { if (motion_triangle_intersect(kg, isect, P, dir, isect->t, ray->time, visibility, prim_object, prim, prim_addr)) { /* shadow ray early termination */ if (visibility & PATH_RAY_SHADOW_OPAQUE) return true; } break; } #endif /* BVH_FEATURE(BVH_MOTION) */ #if BVH_FEATURE(BVH_HAIR) case PRIMITIVE_CURVE_THICK: case PRIMITIVE_MOTION_CURVE_THICK: case PRIMITIVE_CURVE_RIBBON: case PRIMITIVE_MOTION_CURVE_RIBBON: { if ((type & PRIMITIVE_MOTION) && kernel_data.bvh.use_bvh_steps) { const float2 prim_time = kernel_tex_fetch(__prim_time, prim_addr); if (ray->time < prim_time.x || ray->time > prim_time.y) { break; } } const int curve_type = kernel_tex_fetch(__prim_type, prim_addr); const bool hit = curve_intersect( kg, isect, P, dir, isect->t, prim_object, prim, ray->time, curve_type); if (hit) { /* shadow ray early termination */ if (visibility & PATH_RAY_SHADOW_OPAQUE) return true; } break; } #endif /* BVH_FEATURE(BVH_HAIR) */ #if BVH_FEATURE(BVH_POINTCLOUD) case PRIMITIVE_POINT: case PRIMITIVE_MOTION_POINT: { if ((type & PRIMITIVE_MOTION) && kernel_data.bvh.use_bvh_steps) { const float2 prim_time = kernel_tex_fetch(__prim_time, prim_addr); if (ray->time < prim_time.x || ray->time > prim_time.y) { break; } } const int point_type = kernel_tex_fetch(__prim_type, prim_addr); const bool hit = point_intersect( kg, isect, P, dir, isect->t, prim_object, prim, ray->time, point_type); if (hit) { /* shadow ray early termination */ if (visibility & PATH_RAY_SHADOW_OPAQUE) return true; } break; } #endif /* BVH_FEATURE(BVH_POINTCLOUD) */ } } } else { /* instance push */ object = kernel_tex_fetch(__prim_object, -prim_addr - 1); #if BVH_FEATURE(BVH_MOTION) isect->t *= bvh_instance_motion_push(kg, object, ray, &P, &dir, &idir, &ob_itfm); #else isect->t *= bvh_instance_push(kg, object, ray, &P, &dir, &idir); #endif ++stack_ptr; kernel_assert(stack_ptr < BVH_STACK_SIZE); traversal_stack[stack_ptr] = ENTRYPOINT_SENTINEL; node_addr = kernel_tex_fetch(__object_node, object); } } } while (node_addr != ENTRYPOINT_SENTINEL); if (stack_ptr >= 0) { kernel_assert(object != OBJECT_NONE); /* instance pop */ #if BVH_FEATURE(BVH_MOTION) isect->t = bvh_instance_motion_pop(kg, object, ray, &P, &dir, &idir, isect->t, &ob_itfm); #else isect->t = bvh_instance_pop(kg, object, ray, &P, &dir, &idir, isect->t); #endif object = OBJECT_NONE; node_addr = traversal_stack[stack_ptr]; --stack_ptr; } } while (node_addr != ENTRYPOINT_SENTINEL); return (isect->prim != PRIM_NONE); } ccl_device_inline bool BVH_FUNCTION_NAME(KernelGlobals kg, ccl_private const Ray *ray, ccl_private Intersection *isect, const uint visibility) { return BVH_FUNCTION_FULL_NAME(BVH)(kg, ray, isect, visibility); } #undef BVH_FUNCTION_NAME #undef BVH_FUNCTION_FEATURES #undef NODE_INTERSECT
2.1875
2
2024-11-18T20:48:42.753617+00:00
2020-06-26T14:30:36
d6e68c9396850890b8abc4da891ee973199cd6f2
{ "blob_id": "d6e68c9396850890b8abc4da891ee973199cd6f2", "branch_name": "refs/heads/master", "committer_date": "2020-06-26T14:30:36", "content_id": "17928212acdde834265a0b41774fbc8f15f69104", "detected_licenses": [ "MIT" ], "directory_id": "9c952cb4e167f36c1ccfb76f5fb0e43549e9d569", "extension": "c", "filename": "arrq5.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 170106425, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 344, "license": "MIT", "license_type": "permissive", "path": "/Object_Oriented_Programming/arrq5.c", "provenance": "stackv2-0102.json.gz:74071", "repo_name": "NamanMathur77/programming_questions", "revision_date": "2020-06-26T14:30:36", "revision_id": "93353307bcca42ad83f8e587d0ccd6848f4a9ee4", "snapshot_id": "a31745c5e2acf373e611157c4d83a23f45409374", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/NamanMathur77/programming_questions/93353307bcca42ad83f8e587d0ccd6848f4a9ee4/Object_Oriented_Programming/arrq5.c", "visit_date": "2022-11-15T16:12:39.270533" }
stackv2
//Given an array,A of N integers, print each element in reverse order as a single line of space-separated integers. #include<stdio.h> main() { int n,i,arr[100]; printf("ENter the size of array"); scanf("%d",&n); printf("Enter the array elements"); for(i=0;i<n;i++) scanf("%d",&arr[i]); for(i=(n-1);i>=0;i--) printf("%d",*arr+i); return 0; }r
3.0625
3
2024-11-18T20:48:42.852146+00:00
2023-03-17T09:15:00
fd492c0f26c5c7e0494309855677c7ab3964b80a
{ "blob_id": "fd492c0f26c5c7e0494309855677c7ab3964b80a", "branch_name": "refs/heads/master", "committer_date": "2023-03-17T09:15:00", "content_id": "2e4d299f6af02da8774cd30acf1bb47fcf9870c6", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "7772f19f764c5760b2fcb1758e261a7aa600d464", "extension": "c", "filename": "test-options.c", "fork_events_count": 1, "gha_created_at": "2016-09-18T07:13:32", "gha_event_created_at": "2016-09-18T07:13:33", "gha_language": null, "gha_license_id": null, "github_id": 68503760, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1006, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/tests/test-options.c", "provenance": "stackv2-0102.json.gz:74200", "repo_name": "tsingakbar/cre2", "revision_date": "2023-03-17T09:15:00", "revision_id": "a1caa5c1d3607d37064e0b8de19d9373f96ef05c", "snapshot_id": "8ce394f344da0c052a7a530242b270ec3db68e02", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tsingakbar/cre2/a1caa5c1d3607d37064e0b8de19d9373f96ef05c/tests/test-options.c", "visit_date": "2023-03-20T11:32:12.702127" }
stackv2
/* Part of: CRE2 Contents: test for options Date: Mon Jan 2, 2012 Abstract Test file for options objects. Copyright (C) 2012, 2016 Marco Maggi <marco.maggi-ipsu@poste.it> See the COPYING file. */ #include <stdio.h> #include <stdlib.h> #include <cre2.h> #include "cre2-test.h" int main (int argc, const char *const argv[]) { cre2_options_t * opt; opt = cre2_opt_new(); { cre2_opt_set_posix_syntax(opt, 1); cre2_opt_set_longest_match(opt, 1); cre2_opt_set_log_errors(opt, 1); cre2_opt_set_literal(opt, 1); cre2_opt_set_never_nl(opt, 1); cre2_opt_set_dot_nl(opt, 1); cre2_opt_set_never_capture(opt, 1); cre2_opt_set_case_sensitive(opt, 1); cre2_opt_set_perl_classes(opt, 1); cre2_opt_set_word_boundary(opt, 1); cre2_opt_set_one_line(opt, 1); cre2_opt_set_encoding(opt, CRE2_UTF8); cre2_opt_set_encoding(opt, CRE2_Latin1); cre2_opt_set_max_mem(opt, 4096); } cre2_opt_delete(opt); exit(EXIT_SUCCESS); } /* end of file */
2.3125
2
2024-11-18T20:48:43.586988+00:00
2019-05-06T01:44:53
85357fb7df7b065068b5edc9ace1522cf1fe2e07
{ "blob_id": "85357fb7df7b065068b5edc9ace1522cf1fe2e07", "branch_name": "refs/heads/master", "committer_date": "2019-05-06T01:44:53", "content_id": "829aa07a394973f8f0ae731eb5bf8b8ee04bb4dc", "detected_licenses": [ "MIT" ], "directory_id": "b7e920541e6cef12da3a1f5d53acf49543e61cfb", "extension": "c", "filename": "bipolar_simple_stepper.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": 2343, "license": "MIT", "license_type": "permissive", "path": "/bipolar_simple_stepper.c", "provenance": "stackv2-0102.json.gz:74460", "repo_name": "mkollayan/Elegoo_Mega_2560", "revision_date": "2019-05-06T01:44:53", "revision_id": "2c158de67adf4e897f726646ec878b5de737494c", "snapshot_id": "6f333be86feca7697efa04886ec7093402d26ee8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mkollayan/Elegoo_Mega_2560/2c158de67adf4e897f726646ec878b5de737494c/bipolar_simple_stepper.c", "visit_date": "2023-04-02T08:29:08.408727" }
stackv2
//Copyright (c) 2017 Pratik M Tambe <enthusiasticgeek@gmail.com> #include <avr/io.h> #include <util/delay.h> #include <stdint.h> /* Position where 1st coil is connected. All other coils like 2nd,3rd and 4th must be connected in sequence after the 1st. For this configuration the connection is like:- AVR 10 - PB4 (IN1 on L293D board) -> Coil 1 (A1) AVR 11 - PB5 (IN2 on L293D board) -> Coil 2 (A2) AVR 12 - PB6 (IN3 on L293D board) -> Coil 3 (B1) AVR 13 - PB7 (IN4 on L293D board) -> Coil 4 (B2) Don't connect port pins directly to coil, use a driver like L293DA etc. bipolar stepper either 4 or 6 wires - like NEMA 17 stepper 5th wire connected to motor voltage e.g. 5V https://42bots.com/tutorials/bipolar-stepper-motor-control-with-arduino-and-an-h-bridge/ https://42bots.com/tutorials/stepper-motor-wiring-how-to/ https://dronebotworkshop.com/stepper-motors-with-arduino/ https://www.onetransistor.eu/2017/11/unipolar-stepper-motors-arduino-driver.html Batteries https://www.batteryspace.com/LiFePO4/LiFeMnPO4-Batteries.aspx */ int main(){ /* 0 => clockwise */ /* 1 => counter-clockwise */ uint8_t dir = 1; /* set pin 7 of PORTB for output*/ DDRB |= _BV(DDB4); DDRB |= _BV(DDB5); DDRB |= _BV(DDB6); DDRB |= _BV(DDB7); /* set output to 0 */ PORTB &= ~_BV(PORTB4); PORTB &= ~_BV(PORTB5); PORTB &= ~_BV(PORTB6); PORTB &= ~_BV(PORTB7); int8_t step=0; while(1){ switch(step){ case 0: PORTB &= ~_BV(PORTB4); PORTB |= _BV(PORTB5); PORTB |= _BV(PORTB6); PORTB &= ~_BV(PORTB7); break; case 1: PORTB &= ~_BV(PORTB4); PORTB |= &_BV(PORTB5); PORTB &= ~_BV(PORTB6); PORTB |= _BV(PORTB7); break; case 2: PORTB |= _BV(PORTB4); PORTB &= ~_BV(PORTB5); PORTB &= ~_BV(PORTB6); PORTB |= _BV(PORTB7); break; case 3: PORTB |= _BV(PORTB4); PORTB &= ~_BV(PORTB5); PORTB |= _BV(PORTB6); PORTB &= ~_BV(PORTB7); break; default: PORTB &= ~_BV(PORTB7); PORTB &= ~_BV(PORTB6); PORTB &= ~_BV(PORTB5); PORTB &= ~_BV(PORTB4); break; } if(dir > 0){ step++; }else{ step--; } if(step>3){ step=0; } if(step<0){ step=3; } _delay_ms(5); } return 0; }
2.796875
3
2024-11-18T20:48:43.698508+00:00
2016-12-24T15:49:54
4afd3a353e289a1f5f559217f4ddeb4143bd7e66
{ "blob_id": "4afd3a353e289a1f5f559217f4ddeb4143bd7e66", "branch_name": "refs/heads/master", "committer_date": "2016-12-24T15:49:54", "content_id": "7bfe019be3d943da015123b63f1ecaf395c96275", "detected_licenses": [ "MIT" ], "directory_id": "ecf38763ce1332f486cae54d3b3a8f848913a88c", "extension": "c", "filename": "keywordcheck.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": 3133, "license": "MIT", "license_type": "permissive", "path": "/sql2/keywordcheck.c", "provenance": "stackv2-0102.json.gz:74590", "repo_name": "barbiegirl2014/emlproj", "revision_date": "2016-12-24T15:49:54", "revision_id": "10975c5f485ecc7017e48f27b914bec72b2df6ef", "snapshot_id": "ad8f0d51b418d40438c22c90ed7ba3e1352c8571", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/barbiegirl2014/emlproj/10975c5f485ecc7017e48f27b914bec72b2df6ef/sql2/keywordcheck.c", "visit_date": "2020-04-25T19:35:20.967785" }
stackv2
#include "all.h" #include "assist.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include "dboperate.h" #include <dlfcn.h> #include <unistd.h> #include <sys/time.h> #include "mainall.h" #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <stdlib.h> #include <assert.h> /*memory set free*/ static int match_email(char* workspace,FetchRtePtr* keyworldsPtr) { int index, index2; char Ate=255; int backval; FetchRtePtr keyworlds=*keyworldsPtr; int (*dlfunc)(int argc, char* argv[]); void *handle; char command2[1024]={0}; char workpath[1024]= {0}; char dictpath[1024]={0}; sprintf(dictpath,"%s/userdict.txt",workspace); sprintf(workpath,"%s/temps",workspace); char * inputs[4]= {NULL,workpath,&Ate,dictpath}; FILE* fptr=fopen(dictpath,"wb");/*write to dictionary*/ for(index=0; index<keyworlds->row; index++) { memset(command2,0,sizeof(command2)); sprintf(command2,"SELECT keyword FROM strategy_keywords WHERE list_id = %s",keyworlds->dataPtr[index][0]); FetchRtePtr listids=sql_query(command2); for(index2=0; index2<listids->row; index2++) { char key[1024]={0}; if(fptr) { memset(key,0,sizeof(key)); sprintf(key,"%s\n",(listids->dataPtr)[index2][0]); fwrite(key,sizeof(char),strlen(key),fptr); } } free_memory(listids); } free_memory(keyworlds); *keyworldsPtr=NULL;/*set as zero*/ fclose(fptr); #ifdef __DEBUG printf("hello in ParseKeyChs\n"); #endif handle=dlopen("./spliter.so",RTLD_LAZY); #ifdef __DEBUG printf("in open libs\n"); #endif dlfunc=dlsym(handle,"SpliterMain"); if(!(handle&&dlfunc)) { printf("error in open dynamic libs %s\n",dlerror()); return 0; } return dlfunc(4,inputs); } CheckType keywordCheck(mimePtr email,char* owner,int direction) { int index=0,index2; if(!checkInGateway(owner)) return NONE; char command[1024]; //#1.user级处理 memset(command, 0, sizeof(command)); sprintf(command,"SELECT id FROM strategy_keywordlist WHERE owner= '%s' AND level = 0 AND direction = %d",owner,direction); FetchRtePtr user_listids=sql_query(command); if(match_email(email->workspace,&user_listids)) return CONFIRMED; //#2.domain级处理 char *domain = getDomain(owner);// #domain 在网关下 memset(command, 0, sizeof(command)); sprintf(command,"SELECT id FROM strategy_keywordlist WHERE owner= '%s' AND level = 1 AND direction = %d",domain,direction); FetchRtePtr domain_listids=sql_query(command); if(match_email(email->workspace,&domain_listids)) return CONFIRMED; //#3.网关级处理 memset(command, 0, sizeof(command)); sprintf(command,"SELECT id FROM strategy_keywordlist WHERE owner= '%s' AND level = 2 AND direction = %d","GLOBAL",direction); FetchRtePtr global_listids=sql_query(command); if(match_email(email->workspace,&global_listids)) return CONFIRMED; return OK; }
2.078125
2
2024-11-18T20:48:43.823286+00:00
2019-04-17T21:46:17
a1ba2dc686b427f156856e7fa692b5369fd12c39
{ "blob_id": "a1ba2dc686b427f156856e7fa692b5369fd12c39", "branch_name": "refs/heads/master", "committer_date": "2019-04-17T21:46:17", "content_id": "dd61ea5e3117faee90d1bed39a9669ba555dcc98", "detected_licenses": [ "MIT" ], "directory_id": "e9d3e37c5dd3e5edb050c9589b7ca5a61bf0ff85", "extension": "c", "filename": "3-mul.c", "fork_events_count": 25, "gha_created_at": "2018-09-12T17:30:28", "gha_event_created_at": "2022-04-24T23:12:05", "gha_language": "C", "gha_license_id": "MIT", "github_id": 148517012, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 403, "license": "MIT", "license_type": "permissive", "path": "/0x09-argc_argv/3-mul.c", "provenance": "stackv2-0102.json.gz:74719", "repo_name": "BennettDixon/holbertonschool-low_level_programming", "revision_date": "2019-04-17T21:46:17", "revision_id": "3005393bb484c73084767868a394e3254308ff9f", "snapshot_id": "b0304618050cbad7d72247e731be859338fd72bf", "src_encoding": "UTF-8", "star_events_count": 18, "url": "https://raw.githubusercontent.com/BennettDixon/holbertonschool-low_level_programming/3005393bb484c73084767868a394e3254308ff9f/0x09-argc_argv/3-mul.c", "visit_date": "2022-05-02T23:34:45.006326" }
stackv2
#include <stdio.h> #include <stdlib.h> /** * main - entry point for program * * @argc: count of args present * @argv: array of char * pointing to args * * Return: always 0 (success) */ int main(int argc, char *argv[]) { int i, product = 1; if (argc != 3) { printf("Error\n"); return (1); } for (i = 1; i < argc; i++) product *= atoi(argv[i]); printf("%d\n", product); return (0); }
3.1875
3
2024-11-18T20:48:43.904310+00:00
2020-10-17T05:15:48
731f16a680f1cb2838305633149d9adff27c5cd1
{ "blob_id": "731f16a680f1cb2838305633149d9adff27c5cd1", "branch_name": "refs/heads/main", "committer_date": "2020-10-17T05:15:48", "content_id": "4de230996c2597b0a6b0929f184d496c9c8db258", "detected_licenses": [ "MIT" ], "directory_id": "315e1433a80600bbaf1aa84d4f37857c00de937f", "extension": "c", "filename": "pfint.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 304802121, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4106, "license": "MIT", "license_type": "permissive", "path": "/PA3/mid_sub/csc501-lab3/paging/pfint.c", "provenance": "stackv2-0102.json.gz:74849", "repo_name": "dhanraj-vedanth/Xinu", "revision_date": "2020-10-17T05:15:48", "revision_id": "b93c7c7b4f933eca71b4c0e5a028e45d98085468", "snapshot_id": "fc73c7b6535cb9274695d3e625d27f48d3b573b6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dhanraj-vedanth/Xinu/b93c7c7b4f933eca71b4c0e5a028e45d98085468/PA3/mid_sub/csc501-lab3/paging/pfint.c", "visit_date": "2022-12-28T15:04:54.080914" }
stackv2
/* pfint.c - pfint */ #include <conf.h> #include <kernel.h> #include <paging.h> /*------------------------------------------------------------------------- * pfint - paging fault ISR *------------------------------------------------------------------------- */ SYSCALL pfint() { STATWORD ps; disable(ps); unsigned long virt_addr = read_cr2(); unsigned long pdbr = proctab[currpid].pdbr; int vpno_from_a = virt_addr/4096; int flag = -999; int i = 0; for (i;i<16;i++){ if (bsm_tab[i].bs_pid == currpid){ if (vpno_from_a >= bsm_tab[i].bs_vpno && vpno_from_a < (bsm_tab[i].bs_vpno + bsm_tab[i].bs_npages)){ flag = 1; } } } // If flag == 1 it means that a backing store for this search and this pid exists and is valid if (flag == -999){ restore(ps); printf("Illegal weapon bruh %d is bring killed ASAP\n",currpid); kill(currpid); return SYSERR; } int pd_offset = (virt_addr & 0XFFC00000) >> 22; int pt_offest = (virt_addr & 0X003FF000) >> 12; int actual_offset = (virt_addr & 0X00000FFF); int needed_dir = pdbr + pd_offset; //ANY changes? pd_t *dir_pointer; dir_pointer = needed_dir; if (dir_pointer->pd_pres == 0){ // Tells us that there is no page table present int new_frm; int retr = get_frm(&new_frm); if (retr == SYSERR){ restore(ps); return SYSERR; } int pg_table_location = FRAME0 + new_frm; dir_pointer->pd_pres = 1; dir_pointer->pd_write = 1; dir_pointer->pd_user = 0; dir_pointer->pd_pwt = 0; dir_pointer->pd_pcd = 0; dir_pointer->pd_acc = 0; dir_pointer->pd_mbz = 0; dir_pointer->pd_global = 0; dir_pointer-> pd_avail = 0; dir_pointer->pd_base = pg_table_location; // Now fill 1024 entires for the pg table we just obtained pt_t *pt_pointer; pt_pointer = pg_table_location *NBPG; int j = 0; for (j;j<1024;j++{ pt_pointer->pt_pres= 0; /* page is present? */ pt_pointer->pt_write= 0; /* page is writable? */ pt_pointer->pt_user = 0; /* is use level protection? */ pt_pointer->pt_pwt = 0; /* write through for this page? */ pt_pointer->pt_pcd = 0; /* cache disable for this page? */ pt_pointer->pt_acc = 0; /* page was accessed? */ pt_pointer->pt_dirty = 0; /* page was written? */ pt_pointer->pt_mbz = 0; /* must be zero */ pt_pointer->pt_global = 0; /* should be zero in 586 */ pt_pointer->pt_avail = 0; /* for programmer's use */ pt_pointer->pt_base = 0; /* location of page? */ } frm_tab[new_frm].fr_status = MAPPED; frm_tab[new_frm].fr_pid = currpid; frm_tab[new_frm].fr_type = FR_TBL; frm_tab[new_frm].fr_vpno = virt_addr/4096; } // Now there is a PD and a Page table, we need to check if the page is there and if it has the needed stuff // But clearly it wont be there else there wouldn't have been a page fault in the first place. int need_pt_entry = pg_table_location*NBPG + pt_offest; pt_t *pt_pointer2; pt_pointer2 = need_pt_entry; if (pt_pointer2->pt_pres == 0){ // Tells us that the needed page is indeed not there // Pull it from bsm, take a new frame and put it there frm_tab[pg_table_location-FRAME0].fr_fefcnt += 1; int bsm_id; int pg_offset; int retr = bsm_lookup(currpid,virt_addr, &bsm_id, &pg_offset); if (retr == SYSERR){ restore(ps); return SYSERR; } int new_frame; int retr2 = get_frm(&new_frame); if(retr2 == SYSERR){ restore(ps); return SYSERR; // Maybe page replacement here too? Not sure } frm_tab[new_frame].fr_status = MAPPED; frm_tab[new_frame].fr_pid = currpid; frm_tab[new_frame].fr_type = FR_PAGE; frm_tab[new_frame].fr_vpno = virt_addr/4096; new_frame_addr = (FRAME0 + new_frame) * NBPG; read_bs(new_frame_addr, bs_id, pg_offset); pt_pointer2->pt_pres = 1; pt_pointer2->pt_write = 1; pt_pointer2->pt_global = 0; pt_pointer2->pt_base = FRAME0 + new_frame; } restore(ps); // kprintf("To be implemented!\n"); return OK; }
2.21875
2
2024-11-18T20:48:44.448145+00:00
2011-06-20T02:07:20
cb4cb0858c2116f6e07286e8a62a8a9acb15bd34
{ "blob_id": "cb4cb0858c2116f6e07286e8a62a8a9acb15bd34", "branch_name": "refs/heads/master", "committer_date": "2011-06-20T02:07:20", "content_id": "07fd746b55f4a559e61ad54f7cb9bd92a39d6c5a", "detected_licenses": [ "Zlib" ], "directory_id": "5ef1004ff839c39ab7bfe6369167f27085e6c3d9", "extension": "c", "filename": "hexdump.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 32263941, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1141, "license": "Zlib", "license_type": "permissive", "path": "/tools/hexdump.c", "provenance": "stackv2-0102.json.gz:75236", "repo_name": "nagyistoce/planestupid", "revision_date": "2011-06-20T02:07:20", "revision_id": "fc2707ee3e6cda63c224c9e22e61eafebc3ea6f6", "snapshot_id": "a8ca1161ccea9d298ebe9be1e23ae92517d3b885", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nagyistoce/planestupid/fc2707ee3e6cda63c224c9e22e61eafebc3ea6f6/tools/hexdump.c", "visit_date": "2016-09-11T03:01:25.693327" }
stackv2
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> /* hexdump - reads a file and displays it in hex * usage: hexdump <file> * compile: gcc -Wall -O2 hexdump.c -o hexdump * * This is GPLv3 software, do whatever you please with it * (c) 2011 spaceape [[ spaceape99@gmail.com ]] */ static const int SZREAD = 16; int main(int argc, char** argv) { if (argc < 2) { fprintf(stderr, "Usage: hexdump <file>.\n" "Enjoy the ride\n"); } int f = open(argv[1], O_RDONLY); if (f < 0) { fprintf(stderr, "Failed.\n"); return -1; } int rd; int cnt = 0; char* data = malloc(SZREAD); while (rd = read(f, data, SZREAD)) { printf("\033[1;32m%.8x\033[0m ", cnt); int x; for (x = 0; x != rd; ++x) printf("%.2x ", (unsigned char)data[x]); printf("\n"); cnt += rd; if (rd < SZREAD) break; } printf("\033[1;32m%.8x\033[0m \033[1;31mEOL\033[0m\n", cnt); free(data); return 0; }
2.96875
3
2024-11-18T20:48:44.686221+00:00
2021-07-25T05:26:06
12785a06f99529b09b21fe61b0f5d0874b3af569
{ "blob_id": "12785a06f99529b09b21fe61b0f5d0874b3af569", "branch_name": "refs/heads/main", "committer_date": "2021-07-25T05:26:06", "content_id": "b5077f5fc008a3236afe11fbacc6f5b669f4a3d5", "detected_licenses": [ "MIT" ], "directory_id": "05168ccf77b76515830a2bf2c4574fe072f2a231", "extension": "c", "filename": "NestedStructure.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": 579, "license": "MIT", "license_type": "permissive", "path": "/Structures & Unions/NestedStructure.c", "provenance": "stackv2-0102.json.gz:75365", "repo_name": "Yasser-M-Abdalkader/C", "revision_date": "2021-07-25T05:26:06", "revision_id": "f603eef11ea14a730a5fb41e36b3dba5f852fe01", "snapshot_id": "d2a81e942f2de450073970a8372ca208a246bb99", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Yasser-M-Abdalkader/C/f603eef11ea14a730a5fb41e36b3dba5f852fe01/Structures & Unions/NestedStructure.c", "visit_date": "2023-06-25T10:37:00.888509" }
stackv2
#include <stdio.h> #include <string.h> struct employee{ int emp_id; char emp_name[20]; struct date{ int dd; int mm; int yyyy; }doj; }emp1; int main(){ //Assigning values emp1.emp_id = 121; strcpy(emp1.emp_name,"Paurav Shah"); emp1.doj.dd = 26; emp1.doj.mm = 1; emp1.doj.yyyy = 2021; //Accessing values printf("Employee Details:\n"); printf("ID: %d\n",emp1.emp_id); printf("Name: %s\n",emp1.emp_name); printf("Date of joining: %d-%d-%d",emp1.doj.dd,emp1.doj.mm,emp1.doj.yyyy); return 0; }
3.578125
4
2024-11-18T20:48:44.899833+00:00
2019-07-24T01:45:53
92e2219f4f611d1d275822d72dcb1b29eec510c6
{ "blob_id": "92e2219f4f611d1d275822d72dcb1b29eec510c6", "branch_name": "refs/heads/master", "committer_date": "2019-07-24T01:45:53", "content_id": "169e76c321cb94b31043feb9785e874d4bdf4d29", "detected_licenses": [ "CC0-1.0" ], "directory_id": "db6745afa2ebb949e5370e33ba8af2cd39c54f62", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 198533999, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4405, "license": "CC0-1.0", "license_type": "permissive", "path": "/test/test.c", "provenance": "stackv2-0102.json.gz:75751", "repo_name": "somnisoft/mkfifo", "revision_date": "2019-07-24T01:45:53", "revision_id": "b4e0abfdc4ac48e711157762471de3e9d3686dc3", "snapshot_id": "fce51685255a0a6cf64b167730266a5bc5da4a0e", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/somnisoft/mkfifo/b4e0abfdc4ac48e711157762471de3e9d3686dc3/test/test.c", "visit_date": "2020-06-23T05:43:43.079028" }
stackv2
/** * @file * @brief test suite * @author James Humphrey (humphreyj@somnisoft.com) * * This software has been placed into the public domain using CC0. */ #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "test.h" /** * Call @ref mkfifo_main with the given arguments. * * @param[in] mode_str Corresponds to the (-m mode) argument. * @param[in] extra_arg Add an invalid argument to the argument list. * @param[in] expect_exit_status Expected exit status code. * @param[in] file_list List of FIFO's to create. */ static void test_mkfifo_main(const char *const mode_str, const bool extra_arg, const int expect_exit_status, const char *const file_list, ...){ const size_t MAX_ARGS = 20; const size_t MAX_ARG_LEN = 255; size_t i; int exit_status; int status; pid_t pid; int argc; char **argv; const char *file; va_list ap; argc = 0; argv = malloc(MAX_ARGS * sizeof(argv)); assert(argv); for(i = 0; i < MAX_ARGS; i++){ argv[i] = malloc(MAX_ARG_LEN * sizeof(*argv)); assert(argv[i]); } strcpy(argv[argc++], "mkfifo"); if(extra_arg){ strcpy(argv[argc++], "-a"); } if(mode_str){ strcpy(argv[argc++], "-m"); strcpy(argv[argc++], mode_str); } va_start(ap, file_list); for(file = file_list; file; file = va_arg(ap, const char *const)){ strcpy(argv[argc++], file); } va_end(ap); pid = fork(); assert(pid >= 0); if(pid == 0){ exit_status = mkfifo_main(argc, argv); exit(exit_status); } assert(waitpid(pid, &status, 0) == pid); assert(WIFEXITED(status)); assert(WEXITSTATUS(status) == expect_exit_status); for(i = 0; i < MAX_ARGS; i++){ free(argv[i]); } free(argv); } /** * Ensure a FIFO file exists and then remove it. * * @param[in] path FIFO file to check. * @param[in] expect_perms Expected permission bits set in the file mode. */ static void test_check_and_remove_fifo(const char *const path, const mode_t expect_perms){ struct stat sb; mode_t perms; assert(stat(path, &sb) == 0); perms = sb.st_mode & (S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH); assert(S_ISFIFO(sb.st_mode)); assert(perms == expect_perms); assert(remove(path) == 0); } /** * Run all test cases for the mkfifo utility. */ static void test_all(void){ const char *const PATH_NOEXIST = "build/noexist/test-fifo"; const char *const PATH_MKFIFO = "build/fifo"; const char *const PATH_MKFIFO_2 = "build/fifo-2"; const mode_t default_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; remove(PATH_MKFIFO); remove(PATH_MKFIFO_2); /* No file arguments provided. */ test_mkfifo_main(NULL, false, EXIT_FAILURE, NULL); /* Invalid mode_str argument. */ test_mkfifo_main("abc", false, EXIT_FAILURE, PATH_MKFIFO, NULL); /* Unsupported argument. */ test_mkfifo_main(NULL, true, EXIT_FAILURE, PATH_MKFIFO, NULL); /* Does not have permission to create FIFO. */ test_mkfifo_main(NULL, false, EXIT_FAILURE, PATH_NOEXIST, NULL); /* Create one FIFO. */ test_mkfifo_main(NULL, false, EXIT_SUCCESS, PATH_MKFIFO, NULL); test_check_and_remove_fifo(PATH_MKFIFO, default_mode); /* Create multiple FIFO's. */ test_mkfifo_main(NULL, false, EXIT_SUCCESS, PATH_MKFIFO, PATH_MKFIFO_2, NULL); test_check_and_remove_fifo(PATH_MKFIFO, default_mode); test_check_and_remove_fifo(PATH_MKFIFO_2, default_mode); /* Try to create multiple FIFO's but one fails. */ test_mkfifo_main(NULL, false, EXIT_FAILURE, PATH_MKFIFO, PATH_NOEXIST, NULL); test_check_and_remove_fifo(PATH_MKFIFO, default_mode); /* Create FIFO with a different mode. */ test_mkfifo_main("123", false, EXIT_SUCCESS, PATH_MKFIFO, NULL); test_check_and_remove_fifo(PATH_MKFIFO, 0123); } /** * Test mkfifo utility. * * Usage: test * * @retval 0 All tests passed. */ int main(void){ test_all(); return 0; }
2.59375
3
2024-11-18T20:48:45.051017+00:00
2019-12-13T14:59:41
ae7ca24e2f86af7e1ea3cc2796c6dce8c28f0378
{ "blob_id": "ae7ca24e2f86af7e1ea3cc2796c6dce8c28f0378", "branch_name": "refs/heads/master", "committer_date": "2019-12-13T14:59:41", "content_id": "2e88c6a105f554db88e5135be60d56b35ad13f52", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f962f842013899340a0147662a410f55c6d26e07", "extension": "c", "filename": "CycleSort.c", "fork_events_count": 4, "gha_created_at": "2019-11-21T04:27:41", "gha_event_created_at": "2019-12-13T14:05:28", "gha_language": "C++", "gha_license_id": "Apache-2.0", "github_id": 223087912, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 760, "license": "Apache-2.0", "license_type": "permissive", "path": "/C/CycleSort/CycleSort.c", "provenance": "stackv2-0102.json.gz:75880", "repo_name": "19-2-SKKU-OSS/2019-2-OSS-L5", "revision_date": "2019-12-13T14:59:41", "revision_id": "2b55676c1bcd5d327fc9e304925a05cb70e25904", "snapshot_id": "f8cb328996848e935fb1a46d32d0d96c433f125d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/19-2-SKKU-OSS/2019-2-OSS-L5/2b55676c1bcd5d327fc9e304925a05cb70e25904/C/CycleSort/CycleSort.c", "visit_date": "2020-09-14T09:19:34.731638" }
stackv2
#include <stdio.h> #include <stdlib.h> void CycleSort(int* array, int length){ int cycle_start, element, index, tmp; for( cycle_start = 0; cycle_start < length - 1; cycle_start++ ){ element = array[cycle_start]; index = cycle_start; for( int i = cylce_start + 1; i < length; i++ ){ if( array[i] < element )index++; } if( index == cycle_start )continue; while( element == array[index] ) index++; tmp = array[index]; array[index] = element; element = tmp; while( index != cycle_start ){ index = cycle_start; for( int i = cycle_start + 1; i < length; i++ ){ if( array[i] < element ) index++; } while( element == array[index] ) index++; tmp = array[index]; array[index] = element; element = tmp; } } }
3.4375
3
2024-11-18T20:48:45.717749+00:00
2022-03-27T18:31:45
f3c23de089ba6ce78b7655d7388ccfe0da145f92
{ "blob_id": "f3c23de089ba6ce78b7655d7388ccfe0da145f92", "branch_name": "refs/heads/master", "committer_date": "2022-03-27T18:31:45", "content_id": "ffa96a286b27b2c6df9c6584b69ce7cfab2611fe", "detected_licenses": [ "MIT" ], "directory_id": "42cd5532b29bf55923e024058d95c4fe0f3182d2", "extension": "c", "filename": "esc_fire.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 190328859, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5280, "license": "MIT", "license_type": "permissive", "path": "/Tests/esc_fire.c", "provenance": "stackv2-0102.json.gz:76522", "repo_name": "Z-ach/Drone", "revision_date": "2022-03-27T18:31:45", "revision_id": "69ac8da8eca04d5648f82e70d1346b4496c4bd42", "snapshot_id": "a276e094c197a13bcfa9f5e57ba43efd7f34016b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Z-ach/Drone/69ac8da8eca04d5648f82e70d1346b4496c4bd42/Tests/esc_fire.c", "visit_date": "2022-05-12T23:16:08.626291" }
stackv2
/** * @file rc_test_esc.c * @example rc_test_esc * * * Demonstrates use of pru to control servos and ESCs with pulses. This program * operates in 4 different modes. See the option list below for how to select an * operational mode from the command line. * * SERVO: uses rc_servo_send_pulse_normalized() to set one or all servo * positions to a value from -1.5 to 1.5 corresponding to their extended range. * -1 to 1 is considered the "safe" normal range as some servos will not go * beyond this. Test your servos incrementally to find their safe range. * * ESC: For unidirectional brushless motor speed controllers specify a range * from 0 to 1 as opposed to the bidirectional servo range. Be sure to run the * calibrate_esc example first to make sure the ESCs are calibrated to the right * pulse range. This mode uses the rc_servo_send_esc_pulse_normalized() function. * * WIDTH: You can also specify your own pulse width in microseconds (us). * This uses the rc_servo_send_pulse_us() function. * * SWEEP: This is intended to gently sweep a servo back and forth about the * center position. Specify a range limit as a command line argument as * described below. This also uses the rc_servo_send_pulse_normalized() * function. * * * * @author James Strawson * @date 3/20/2018 */ #include <stdio.h> #include <getopt.h> #include <stdlib.h> // for atoi #include <signal.h> #include <rc/time.h> #include <rc/servo.h> static int running = 0; typedef enum test_mode_t{ DISABLED, NORM, WIDTH, SWEEP, RADIO }test_mode_t; static void __print_usage(void) { printf("\n"); printf(" Options\n"); printf(" -h Print this help messege \n\n"); printf(" -c {channel} Specify one channel to be driven from 1-8.\n"); printf(" Otherwise all channels will be driven equally\n"); printf(" -f {hz} Specify pulse frequency, otherwise 50hz is used\n"); printf(" -t {throttle} Throttle to send between -0.1 & 1.0\n"); printf(" -o Enable One-Shot mode\n"); printf(" -w {width_us} Send pulse width in microseconds (us)\n"); printf(" -s {max} Gently sweep throttle from 0 to {max} back to 0 again\n"); printf(" {max} can be between 0 & 1.0\n"); printf(" -m {min,max} Set the pulse width range in microseconds, default is 1000,2000\n"); printf(" if this option is not given. Use -m 1120,1920 for DJI ESCs.\n"); printf(" -p {period,value} Set the wakeup period (seconds) and value (normalized)\n"); printf(" default is 3.0,-0.1 if this option is not given.\n"); printf(" Use -p 3,0.0 for DJI ESCs.\n"); printf(" -d Disable the wakeup period for ESCs which do not require it\n"); printf("\n"); printf(" rc_test_esc -c 2 -r 1\n\n"); printf(" rc_test_esc -c 2 -r 1 -m 1120,1920 -p 1.0,0.0\n\n"); printf("sample use to sweep all ESC channels from 0 to quarter throttle with oneshot mode\n"); printf(" rc_test_esc -o -s 0.25\n\n"); } // interrupt handler to catch ctrl-c static void __signal_handler(__attribute__ ((unused)) int dummy) { running=0; return; } int main(int argc, char *argv[]) { int c,i,ret; // misc variables double thr = 0; // normalized throttle int width_us = 0; // pulse width in microseconds mode int ch = 0; // channel to test, 0 means all channels test_mode_t mode; // current operating mode int frequency_hz = 50; // default 50hz frequency to send pulses int wakeup_en = 1; // wakeup period enabled by default double wakeup_s = 1.5; // wakeup period in seconds double wakeup_val = -0.1;// wakeup value int min_us = RC_ESC_DEFAULT_MIN_US; int max_us = RC_ESC_DEFAULT_MAX_US; // start with mode as disabled mode = DISABLED; // set signal handler so the loop can exit cleanly signal(SIGINT, __signal_handler); running=1; // initialize PRU and make sure power rail is OFF if(rc_servo_init()) return -1; if(rc_servo_set_esc_range(min_us,max_us)) return -1; rc_servo_power_rail_en(0); // if driving an ESC, send throttle of 0 first // otherwise it will go into calibration mode if(wakeup_en){ printf("waking ESC up from idle for 3 seconds\n"); for(i=0;i<=frequency_hz*wakeup_s;i++){ if(running==0) return 0; if(rc_servo_send_esc_pulse_normalized(ch,wakeup_val)==-1) return -1; rc_usleep(1000000/frequency_hz); } printf("done with wakeup period\n"); } // Main loop runs at frequency_hz while(running){ rc_servo_send_esc_pulse_normalized(ch,thr); rc_usleep(1000000/frequency_hz); } // cleanup else rc_servo_send_esc_pulse_normalized(ch,-0.1); rc_usleep(50000); rc_servo_cleanup(); printf("\n"); return 0; }
2.734375
3
2024-11-18T20:48:46.160694+00:00
2023-08-28T21:32:20
eea321e0dc09e39c3ab7b0696a53b1b4eb5241c4
{ "blob_id": "eea321e0dc09e39c3ab7b0696a53b1b4eb5241c4", "branch_name": "refs/heads/master", "committer_date": "2023-08-28T21:32:20", "content_id": "eaa5485d2a2314c976e6a91c20494c3fd31981f3", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "directory_id": "72e57463384261722aa3ba909700eec5cc72c703", "extension": "c", "filename": "unions.c", "fork_events_count": 221, "gha_created_at": "2018-04-20T00:05:50", "gha_event_created_at": "2023-09-08T18:08:32", "gha_language": "Rust", "gha_license_id": "NOASSERTION", "github_id": 130285553, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1565, "license": "BSD-3-Clause,Apache-2.0", "license_type": "permissive", "path": "/tests/unions/src/unions.c", "provenance": "stackv2-0102.json.gz:77038", "repo_name": "immunant/c2rust", "revision_date": "2023-08-28T21:32:20", "revision_id": "f22c6923668f4fa1fe962a02c62ec6d0597dd794", "snapshot_id": "79c1c158252075bfd33870677a4a9d0c7fc168e1", "src_encoding": "UTF-8", "star_events_count": 3467, "url": "https://raw.githubusercontent.com/immunant/c2rust/f22c6923668f4fa1fe962a02c62ec6d0597dd794/tests/unions/src/unions.c", "visit_date": "2023-08-31T07:13:03.567937" }
stackv2
union my_union { int as_int; char as_chars[10]; }; union my_union_flipped { int as_int; char as_chars[10]; }; union empty_union { }; union union_with_anon_struct { struct { int a; }; }; union __attribute__((packed)) packed_union { int as_int; char as_chars[5]; }; void entry(const unsigned int buffer_size, int buffer[const]) { int i = 0; union my_union u1 = { .as_int = 1 }; union my_union u2 = { 2 }; union my_union u3 = { .as_chars = {3,4} }; union my_union_flipped u4 = { .as_int = 5 }; union my_union_flipped u5 = { 6 }; union my_union_flipped u6 = { .as_chars = {7,8} }; // Unions with anonymous structs would previously fail to init: union union_with_anon_struct anon; buffer[i++] = sizeof(union my_union); buffer[i++] = sizeof(union my_union_flipped); buffer[i++] = sizeof(union empty_union); buffer[i++] = sizeof(union packed_union); buffer[i++] = u1.as_int; buffer[i++] = u2.as_int; buffer[i++] = u3.as_chars[0]; buffer[i++] = u3.as_chars[1]; buffer[i++] = u3.as_chars[2]; buffer[i++] = u4.as_int; buffer[i++] = u5.as_int; buffer[i++] = u6.as_chars[0]; buffer[i++] = u6.as_chars[1]; buffer[i++] = u6.as_chars[2]; u1.as_int = 8; buffer[i++] = u1.as_int; u1.as_chars[0] = 9; buffer[i++] = u1.as_chars[0]; u4.as_int = 10; buffer[i++] = u4.as_int; u4.as_chars[1] = 12; buffer[i++] = u4.as_chars[1]; union my_union u7; u7 = (union my_union)i; buffer[i++] = u7.as_int; }
2.59375
3
2024-11-18T20:48:46.249417+00:00
2020-09-22T06:23:55
7f27592697e5195166852bead45b0ee04e9ed8bf
{ "blob_id": "7f27592697e5195166852bead45b0ee04e9ed8bf", "branch_name": "refs/heads/main", "committer_date": "2020-09-22T06:23:55", "content_id": "aeb18e1b492d29b5478e7db89efa879fb4513417", "detected_licenses": [ "MIT" ], "directory_id": "b2272f21f40671cbdfbd98626df353eaf919c371", "extension": "c", "filename": "Breakpoint.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 277071807, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8468, "license": "MIT", "license_type": "permissive", "path": "/NESx/Private/Debug/Breakpoint.c", "provenance": "stackv2-0102.json.gz:77167", "repo_name": "WhoBrokeTheBuild/NESx", "revision_date": "2020-09-22T06:23:55", "revision_id": "6d5d36647c271ed44eacc3f7181a6d83d228cd8d", "snapshot_id": "9d572435490687551e7503437f02edf93ab2c58d", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/WhoBrokeTheBuild/NESx/6d5d36647c271ed44eacc3f7181a6d83d228cd8d/NESx/Private/Debug/Breakpoint.c", "visit_date": "2022-12-19T10:20:49.173531" }
stackv2
#include "Breakpoint.h" #include <stdio.h> #include <stdlib.h> const char * nesx_breakpoint_numeric_target_string(int numericTarget) { switch (numericTarget) { case BREAKPOINT_NUMERIC_TARGET_PC: return "PC"; case BREAKPOINT_NUMERIC_TARGET_A: return "A"; case BREAKPOINT_NUMERIC_TARGET_X: return "X"; case BREAKPOINT_NUMERIC_TARGET_Y: return "Y"; case BREAKPOINT_NUMERIC_TARGET_S: return "S"; case BREAKPOINT_NUMERIC_TARGET_CPU_CYCLE: return "CPU Cycle"; case BREAKPOINT_NUMERIC_TARGET_PPU_CYCLE: return "PPU Cycle"; case BREAKPOINT_NUMERIC_TARGET_SCANLINE: return "Scanline"; case BREAKPOINT_NUMERIC_TARGET_AB: return "AB"; case BREAKPOINT_NUMERIC_TARGET_AD: return "AD"; case BREAKPOINT_NUMERIC_TARGET_DB: return "DB"; case BREAKPOINT_NUMERIC_TARGET_IR: return "IR"; } return "?"; } const char * nesx_breakpoint_numeric_comp_string(int numericComp) { switch (numericComp) { case BREAKPOINT_COMP_EQUAL: return "=="; case BREAKPOINT_COMP_NOT_EQUAL: return "!="; case BREAKPOINT_COMP_GREATER_OR_EQUAL: return ">="; case BREAKPOINT_COMP_LESS_OR_EQUAL: return "<="; case BREAKPOINT_COMP_GREATER: return ">"; case BREAKPOINT_COMP_LESS: return "<"; } return "?"; } const char * nesx_breakpoint_flag_target_string(int flagTarget) { switch (flagTarget) { case BREAKPOINT_FLAG_TARGET_IRQ: return "IRQ"; case BREAKPOINT_FLAG_TARGET_NMI: return "NMI"; case BREAKPOINT_FLAG_TARGET_VBLANK: return "VBlank"; case BREAKPOINT_FLAG_TARGET_FN: return "FN"; case BREAKPOINT_FLAG_TARGET_FV: return "FV"; case BREAKPOINT_FLAG_TARGET_FB: return "FB"; case BREAKPOINT_FLAG_TARGET_FD: return "FD"; case BREAKPOINT_FLAG_TARGET_FI: return "FI"; case BREAKPOINT_FLAG_TARGET_FZ: return "FZ"; case BREAKPOINT_FLAG_TARGET_FC: return "FC"; case BREAKPOINT_FLAG_TARGET_RW: return "RW"; case BREAKPOINT_FLAG_TARGET_SYNC: return "SYNC"; case BREAKPOINT_FLAG_TARGET_RDY: return "RDY"; case BREAKPOINT_FLAG_TARGET_RES: return "RES"; } return "?"; } const char * nesx_breakpoint_flag_trigger_string(int flagTrigger) { switch (flagTrigger) { case BREAKPOINT_STATE_CHANGED: return "Changed"; case BREAKPOINT_STATE_ON: return "On"; case BREAKPOINT_STATE_OFF: return "Off"; } return "?"; } NESxBreakpoint * nesx_breakpoint_list_add(NESxBreakpoint ** first) { NESxBreakpoint ** ptmp = first; while (*ptmp) { ptmp = &(*ptmp)->next; } *ptmp = (NESxBreakpoint *)malloc(sizeof(NESxBreakpoint)); (*ptmp)->next = NULL; return *ptmp; } void nesx_breakpoint_list_clear(NESxBreakpoint ** first) { NESxBreakpoint * tmp; while (*first) { tmp = (*first)->next; free(*first); *first = tmp; } *first = NULL; } void nesx_breakpoint_list_remove(NESxBreakpoint ** first, int index) { NESxBreakpoint * tmp; NESxBreakpoint ** ptmp = first; while (index > 0) { --index; if (!*ptmp) { return; } ptmp = &(*ptmp)->next; } tmp = *ptmp; if (tmp) { *ptmp = tmp->next; free(tmp); } } bool nesx_breakpoint_list_check(NESxBreakpoint * first, nesx_t * nes) { NESxBreakpoint * tmp = first; while (tmp) { if (tmp->type == BREAKPOINT_TYPE_NUMERIC) { int value; switch (tmp->numericTarget) { case BREAKPOINT_NUMERIC_TARGET_PC: value = nes->CPU.PC; break; case BREAKPOINT_NUMERIC_TARGET_A: value = nes->CPU.A; break; case BREAKPOINT_NUMERIC_TARGET_X: value = nes->CPU.X; break; case BREAKPOINT_NUMERIC_TARGET_Y: value = nes->CPU.Y; break; case BREAKPOINT_NUMERIC_TARGET_S: value = nes->CPU.S; break; case BREAKPOINT_NUMERIC_TARGET_CPU_CYCLE: value = nes->CPU.Cycles; break; case BREAKPOINT_NUMERIC_TARGET_PPU_CYCLE: value = nes->PPU.Cycle; break; case BREAKPOINT_NUMERIC_TARGET_SCANLINE: value = nes->PPU.Scanline; break; case BREAKPOINT_NUMERIC_TARGET_AB: value = nes->CPU.AB; break; case BREAKPOINT_NUMERIC_TARGET_AD: value = nes->CPU.AD; break; case BREAKPOINT_NUMERIC_TARGET_DB: value = nes->CPU.DB; break; case BREAKPOINT_NUMERIC_TARGET_IR: value = nes->CPU.IR; break; default: fprintf(stderr, "Invalid numeric breakpoint target: %d\n", tmp->numericTarget); return false; } bool result = false; switch (tmp->numericComp) { case BREAKPOINT_COMP_EQUAL: result = (value == tmp->value); break; case BREAKPOINT_COMP_NOT_EQUAL: result = (value != tmp->value); break; case BREAKPOINT_COMP_GREATER_OR_EQUAL: result = (value >= tmp->value); break; case BREAKPOINT_COMP_LESS_OR_EQUAL: result = (value <= tmp->value); break; case BREAKPOINT_COMP_GREATER: result = (value > tmp->value); break; case BREAKPOINT_COMP_LESS: result = (value < tmp->value); break; default: fprintf(stderr, "Invalid numeric comparison: %d\n", tmp->numericComp); return false; } if (result) { return true; } } else { bool state; switch (tmp->flagTarget) { case BREAKPOINT_FLAG_TARGET_IRQ: state = nes->CPU.IRQ; break; case BREAKPOINT_FLAG_TARGET_NMI: state = nes->CPU.NMI; break; case BREAKPOINT_FLAG_TARGET_VBLANK: state = nes->PPU.VBlank; break; case BREAKPOINT_FLAG_TARGET_FN: state = nes->CPU.FN; break; case BREAKPOINT_FLAG_TARGET_FV: state = nes->CPU.FV; break; case BREAKPOINT_FLAG_TARGET_FB: state = nes->CPU.FB; break; case BREAKPOINT_FLAG_TARGET_FD: state = nes->CPU.FD; break; case BREAKPOINT_FLAG_TARGET_FI: state = nes->CPU.FI; break; case BREAKPOINT_FLAG_TARGET_FZ: state = nes->CPU.FZ; break; case BREAKPOINT_FLAG_TARGET_FC: state = nes->CPU.FC; break; case BREAKPOINT_FLAG_TARGET_RW: state = nes->CPU.RW; break; case BREAKPOINT_FLAG_TARGET_SYNC: state = nes->CPU.SYNC; break; case BREAKPOINT_FLAG_TARGET_RDY: state = nes->CPU.RDY; break; case BREAKPOINT_FLAG_TARGET_RES: state = nes->CPU.RES; break; default: fprintf(stderr, "Invalid flag target: %d\n", tmp->flagTarget); return false; } bool result = false; switch (tmp->flagTrigger) { case BREAKPOINT_STATE_CHANGED: result = (state != tmp->lastState); break; case BREAKPOINT_STATE_ON: result = state; break; case BREAKPOINT_STATE_OFF: result = !state; break; } tmp->lastState = state; if (result) { return result; } } tmp = tmp->next; } return false; }
2.421875
2
2024-11-18T20:48:46.378924+00:00
2019-10-10T21:16:06
ba11b82d51ef15dbe7bef65c89e68adecd56c134
{ "blob_id": "ba11b82d51ef15dbe7bef65c89e68adecd56c134", "branch_name": "refs/heads/master", "committer_date": "2019-10-10T21:16:06", "content_id": "cab2c41f9054961b99bf9f8f302584edc280526a", "detected_licenses": [ "CC0-1.0" ], "directory_id": "b4c14849de5bcdaa26b885931cb41b5fc078de0b", "extension": "c", "filename": "cle.c", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 10106235, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20795, "license": "CC0-1.0", "license_type": "permissive", "path": "/cle.c", "provenance": "stackv2-0102.json.gz:77295", "repo_name": "dpwe/dpwelib", "revision_date": "2019-10-10T21:16:06", "revision_id": "d16121f06408ad0c28781d5d01117c8b301bb9bd", "snapshot_id": "031c1165194ca53ef474d807d6a379c87c99f0b2", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/dpwe/dpwelib/d16121f06408ad0c28781d5d01117c8b301bb9bd/cle.c", "visit_date": "2020-12-24T14:17:45.687589" }
stackv2
/***************************************************************\ * cle.c * * Table-driven command-line argument parsing * * orignally implemented for yympeg * * dpwe 1994dec12 * \***************************************************************/ #include "dpwelib.h" #include <assert.h> #include <math.h> /* atof */ #include <stdlib.h> /* atoi? */ #include <string.h> /* strdup() */ #include "cle.h" #define CLE_STRLEN 256 #ifndef HAVE_STRDUP extern char *strdup(const char *s1); #endif /* HAVE_STRDUP */ /* a couple of functions for printing nicely columnated output to a file/stream. */ static void coMoveToCol(FILE *stream, int *curcol, int targcol) { /* Write white-space to <stream> until the cursor is at <targcol>. Insert a newline if necessary. <curcol> is our 'private' state. */ if (*curcol > targcol) { fputc('\n', stream); (*curcol) = 0; } /* could use tab, but why bother? */ while (*curcol < targcol) { fputc(' ', stream); ++(*curcol); } } static int coWrapPrefix(char *s, int n, int *step) { /* return the length of a prefix of string <s>, not greater than <n>, which attempts to end just before a whitespace. In <step>, return the number of characters to advance in <s> to get to the following non-whitespace. */ char ws[] = " \t"; int len = 0; char *t = s; int nWs, nNonWs, nLastWs = 0; while (*t) { /* length of next non-ws */ nNonWs = strcspn(t, ws); /* length of subsequent ws */ nWs = strspn(t+nNonWs, ws); if (nNonWs+nWs == 0 /* end of string */ \ || (len > 0 && len+nLastWs+nNonWs > n) /* nonempty string abt to wrap */) { break; } else { /* include this bit in the string */ len += nLastWs+nNonWs; /* save the following Ws to add onto len next time around */ nLastWs = nWs; /* skip the string to the start of the next non-ws */ t += nNonWs+nWs; } } /* If we couldn't fit the wrap, len will be bigger than n; chop it if so */ if (len > n) { len = n; nLastWs = 0; /* no skip for following WS if truncated */ } /* <len> is how much to print. But len+nLastWs is how much to skip to get to the next non-WS to print. Return this in *step. */ if (step) { *step = len + nLastWs; } return len; } /* At what column to do wrapping */ #define RIGHT_MARGIN 76 static void coPrint(FILE *stream, int *curcol, const char *str, int first, int rest) { /* copy the string <s> to output <stream>. Start the first line at column <first>; perform word-wrapping, starting subsequent lines at column <rest>. */ int rm = RIGHT_MARGIN; int i, len, skip, crlen; int startcol = first; char partstr[CLE_STRLEN]; char *s; while (*str) { /* copy up to first carriage return */ crlen = strcspn(str, "\n"); assert(crlen < CLE_STRLEN); strncpy(partstr, str, crlen); partstr[crlen] = '\0'; s = partstr; while(*s) { /* move to the correct indent */ coMoveToCol(stream, curcol, startcol); /* find out how much we can print */ len = coWrapPrefix(s, rm - *curcol, &skip); /* print it out */ for (i=0; i < len; ++i) { fputc(s[i], stream); ++(*curcol); } /* fprintf(stderr, "\ncoPrint: s='%s' curcol=%d len=%d skip=%d\n", s, *curcol, len, skip); */ /* move on for rest */ s += skip; startcol = rest; } /* end of line. Should we <cr>? */ if (str[crlen] == '\n') { fputc('\n', stream); *curcol = 0; /* make sure we skip the <cr> too */ ++crlen; } /* move onto next line in string */ str += crlen; } } /* --- end of column-printout (co) routines --- */ static int cleNextPattern(const char *fmtstring, char* rtnstring, const char **state) { /* Convert a string containing multiple patterns of the form "-ras*ta|-R" into a succession of strings, "-rasta", "-R" on successive calls, also returning the minimum match lengths (4, 2). <rtnstring> points to pre-allocated return space to match; <state> is a string pointer used as state, which should initially contain NULL. Returns -1 when no more patterns. */ int firsttime = 0; int fldlen, patlen, minlen; char *s; /* check the state ptr is OK */ if (!state) { fprintf(stderr, "cleNextPat: <state> cannot be NULL\n"); exit(-1); } if (*state == NULL) { *state = fmtstring; firsttime = 1; } if (*state < fmtstring || *state > (fmtstring+strlen(fmtstring))) { fprintf(stderr, "cleNextPat: <state> is nonsense\n"); exit(-1); } if (!firsttime) { if (**state == '\0') { /* reached end of string */ return -1; } else if (**state != '|') { fprintf(stderr, "cleNextPat: unexpected <state>\n"); exit(-1); } /* step over the separator */ ++*state; } /* state is valid; extract the pattern */ rtnstring[0] = '\0'; fldlen = strlen(*state); if ( (s = strchr(*state, '|')) != NULL) { /* There's another field after this one */ fldlen = s - *state; } patlen = fldlen; minlen = fldlen; if ( (s = strchr(*state, '?')) != NULL \ && (s - (*state)) < fldlen ) { /* There's an optional part in this field */ minlen = s - (*state); /* copy it without the '?' */ strncpy(rtnstring, *state, minlen); strncpy(rtnstring+minlen, (*state)+minlen+1, fldlen-minlen-1); patlen = fldlen - 1; } else { patlen = fldlen; strncpy(rtnstring, *state, patlen); } rtnstring[patlen] = '\0'; /* advance the state */ *state += fldlen; return minlen; } static void cleMakeTokenVal(char *val, CLE_TOKEN *tktab) { /* make a value string of the form "{a|b|c}" from a token table */ CLE_TOKEN *tk = tktab; strcpy(val, "{"); while(tk->string != NULL) { strcat(val, tk->string); strcat(val, "|"); ++tk; } /* chop off the last bar */ val[strlen(val)-1] = '\0'; strcat(val, "}"); } static int cleScanTime(const char *val, float *secs) { /* convert a time in [[hh:]mm:]ss[.sss] into secs as a float. Return 0 if bad formatting, 1 on success */ const char *s; char *t; float x, y; int err; s = val; x = 0; while ( (t = strchr(s,':')) != NULL ) { y = strtol(s, &t, 10); if (*t != ':') { /* found something else */ fprintf(stderr, "cleScanTime: error at chr %ld of '%s'\n", (unsigned long) (t - s), s); return 0; } x = 60*x + y; /* start just beyond colon */ s = t+1; } /* rest is seconds */ err = (sscanf(s, "%f", &y) != 1); if (err) { return 0; } x = 60*x+y; *secs = x; return 1; } /* Column to start flag/values */ #define FLAG_COL 2 /* Column to start definitions */ #define DEFIN_COL 20 /* right-alignment column for default vals */ #define DFLTS_RCOL (RIGHT_MARGIN) void cleUsage(CLE_ENTRY *entries, const char *programName) { /* print a usage message to stderr, based on the CLE_ENTRY table */ CLE_ENTRY *ent = entries; char val[CLE_STRLEN], str[CLE_STRLEN]; const char *flag, *usage, *deflt; int curcol = 0; fprintf(stderr, "%s: command line flags (defaults in parens):\n", programName); while(ent->type != CLE_T_END) { flag = ent->flag; usage = ent->usage; deflt = ent->deflt; if (!flag) flag = ""; if (!usage) usage = ""; switch(ent->type) { case CLE_T_INT: strcpy(val, "<int>"); break; case CLE_T_LONG: strcpy(val, "<long>"); break; case CLE_T_FLOAT: strcpy(val, "<float>"); break; case CLE_T_TIME: strcpy(val, "<hh:mm:ss.sss>"); break; case CLE_T_BOOL: strcpy(val, ""); break; case CLE_T_INVBOOL: strcpy(val, ""); break; case CLE_T_STRING: strcpy(val, "<string>"); break; case CLE_T_SPECIAL: strcpy(val, "<arg>"); break; case CLE_T_TOKEN: cleMakeTokenVal(val, (CLE_TOKEN *)ent->specData); break; /* Totally ignore the flag portion of T_USAGE */ case CLE_T_USAGE: strcpy(val, ""); break; default: fprintf(stderr, "cleUsage: unknown type %d\n", ent->type); abort(); } sprintf(str, "%s %s", flag, val); coPrint(stderr, &curcol, str, FLAG_COL, 0); coPrint(stderr, &curcol, usage, DEFIN_COL, DEFIN_COL+2); if(deflt) { /* argument has default defined */ sprintf(str, "(%s)", deflt); /* figure col from strlen(str) for right-alignment */ coPrint(stderr, &curcol, str, DFLTS_RCOL-strlen(str), 0); } coPrint(stderr, &curcol, "\n", 0, 0); ++ent; } } int cleSetDefaults(CLE_ENTRY *entries) { /* go through whole entries table setting up the defaults first */ CLE_ENTRY *ent = entries; const char *arg; int err = 0; while(ent->type != CLE_T_END) { /* Boolean types have implicit defaults, regardless of the dflt fld */ if( (arg = ent->deflt) != NULL \ || ent->type == CLE_T_BOOL \ || ent->type == CLE_T_INVBOOL) { switch(ent->type) { case CLE_T_BOOL: *(int *)(ent->where) = 0; break; case CLE_T_INVBOOL: *(int *)(ent->where) = 1; break; case CLE_T_INT: { int i; err = (sscanf(arg, "%d", &i) != 1); if (!err) *(int *)(ent->where) = i; } break; case CLE_T_LONG: { long l; err = (sscanf(arg, "%ld", &l) != 1); if(!err) *(int *)(ent->where) = l; } break; case CLE_T_FLOAT: { float f; err = (sscanf(arg, "%f", &f) != 1); if(!err) *(float *)(ent->where) = f; } break; case CLE_T_TIME: { float f; err = (cleScanTime(arg, &f) != 1); if(!err) *(float *)(ent->where) = f; } break; case CLE_T_STRING: *(char **)(ent->where) = strdup(arg); break; case CLE_T_TOKEN: err = cleTokenSetFn(arg, ent->where, ent->flag, ent->specData); break; case CLE_T_SPECIAL: err = (*(ent->specialfn))(arg, ent->where, ent->flag, ent->specData); break; case CLE_T_USAGE: break; default: fprintf(stderr, "cleSetDefaults: unknown CLE_TYPE %d\n", ent->type); abort; } } ++ent; } return err; } static int cleMatchPat(const char *arg, const char *multipat, int *pused, char **ppat, int *pval) { /* do the necessary expansions to match arg against the multipat; return 1 if it actually matched else 0. Set *pused to 0 if the arg should not be consumed. Set *ppat to the actual pattern that matched. *pval takes the actual value for %d/%f flags. */ int minlen; const char *state = NULL; static char pat[CLE_STRLEN]; /* gets returned in *ppat, so make static ?? */ int found = 0; int arglen = (arg)?strlen(arg):0; /* Special cases: 1. token string like "abc?def" matches abc, abcd, abcde, abcdef BUT NOT a, ab, abce etc. 2. token string "" matches anything, but shouldn't be regarded as consuming the following token. xx 3. token string "abc*" matches abc followed by anything 4. token string "*T" matches "1", "true", "yes" 5. token string "*F" matches "0", "false", "no" 6. token string "%d" allows an argument as decimal string. */ while(!found && (minlen = cleNextPattern(multipat, pat, &state)) > -1) { if( (strcmp(pat, "*T")) == 0) { /* recurse on special patterns */ found = cleMatchPat(arg, "y?es|t?rue|1", pused, ppat, pval); } else if( (strcmp(pat, "*F")) == 0) { found = cleMatchPat(arg, "n?o|f?alse|0", pused, ppat, pval); } else if( (strcmp(pat, "%d")) == 0) { int val; if(arg && sscanf(arg, "%d", &val) == 1) { found = 1; if(pval) *(int*)pval = val; if(pused) *pused = (strlen(pat) > 0); if(ppat) *ppat = pat; } } else if( (strcmp(pat, "%f")) == 0) { float val; if(arg && sscanf(arg, "%f", &val) == 1) { found = 1; if(pval) *(float*)pval = val; if(pused) *pused = (strlen(pat) > 0); if(ppat) *ppat = pat; } } else if( strlen(pat) == 0 \ || (arglen >= minlen && strncmp(arg, pat, arglen)==0) ) { /* null string matches "no arg" - don't consume the arg */ found = 1; if(pused) *pused = (strlen(pat) > 0); if(ppat) *ppat = pat; } } return found; } int cleTokenSetFn(const char *arg, void *where, const char *fromflag, void *cle_tokens) { /* set an int value from a CLE_TOKEN table, return 1 if arg used, 0 if no arg used, -1 if error (unrecog) */ int *pint = (int *)where; CLE_TOKEN *tk = (CLE_TOKEN *)cle_tokens; int found = 0; int used; char *pat; while(!found && tk->string != NULL) { found = cleMatchPat(arg, tk->string, &used, &pat, pint); if( found && (strcmp(pat, "%d")) != 0) { if (strcmp(pat, "%f") == 0) { /* scale by argument and write as int */ *pint = tk->code * *(float *)pint; } else { *pint = tk->code; } } ++tk; } if(found) return used; else return -1; } int cleHandleArgs(CLE_ENTRY *entries, int argc, char *argv[]) { /* parse a set of command line arguments according to a structure */ int err = cleExtractArgs(entries, &argc, argv, 1); return err; } int cleExtractArgs(CLE_ENTRY *entries, int* pargc, char *argv[], int noExtraArgs) { /* parse a set of command line arguments according to a structure. If noExtraArgs is not set, allow for a variable number of arguments that we don't parse; return modified argc and argv pointing to the residue. Return value is number of actual error objected to. */ int i, j, errs = 0, anerr, rc, argUsed, tokDone, flaglen, toklen, minlen; int blankIndex = 0; /* use each blank index just once */ int blankCount; char *next, *arg, *tok; char tokbuf[CLE_STRLEN]; char flag[CLE_STRLEN]; CLE_ENTRY *ent; int outargc = 1; int argc = *pargc; char *pat; const char *state; int tokcontinued = 0; /* flag that reparsing remainder */ const char *programName = argv[0]; /* first, set all defaults - we can overwrite them later */ /* cleSetDefaults(entries); */ /* no, let program do this if it wants */ i = 0; while(i + 1 - tokcontinued<argc) { if (!tokcontinued) tok = argv[++i]; /* grab the next arg; preincrement ensures we skip argv[0] */ next = (i+1<argc)?argv[i+1]:NULL; ent = entries; blankCount = 0; argUsed = 0; tokDone = 0; anerr = 0; tokcontinued = 0; DBGFPRINTF((stderr, "cle(%d): testing '%s' (then '%s')\n", \ i, tok, next?next:"(NULL)")); while(!tokDone && ent->type != CLE_T_END) { state = NULL; while(!tokDone && ent->type != CLE_T_USAGE && \ (minlen = cleNextPattern(ent->flag, flag, &state)) > -1) { toklen = strlen(tok); flaglen = strlen(flag); DBGFPRINTF((stderr, "cle: trying '%s' ('%s', %d)\n", \ tok,flag,minlen)); if(flaglen == 0) ++blankCount; /* keep track of which blank field */ if( /* Allow empty flags (untagged args) to match any (new) string, but not if they start with '-' unless they are exactly "-" */ ( flaglen == 0 \ && blankCount > blankIndex \ && ( tok[0] != '-' || tok[1] == '\0' ) ) \ /* Match all the tok, at least up to minlen of the flag */ || ((toklen >= minlen) \ && (strncmp(tok, flag, toklen) == 0)) \ /* special case: 2-chr flags only need match first bit */ || ( flaglen == 2 \ && flag[0] == '-' \ && ( tok[0] == '-' && tok[1] == flag[1]) ) ) { /*** We matched a flag pattern ***/ tokDone = 1; if(flaglen == 0) { ++blankIndex; /* mark this blank field as used */ arg = tok; /* for blank flds, tok is arg */ } else if(flag[0]=='-' && flaglen==2 && strlen(tok)>flaglen) { /* simple "-X" flag was matched as prefix: separate out the remainder as an arg, or the next tok. */ arg = tok+flaglen; } else { arg = next; } switch(ent->type) { case CLE_T_INT: { int x; anerr = (arg==NULL) || (sscanf(arg, "%d", &x) != 1); if (!anerr) *(int *)(ent->where) = x; } argUsed = 1; break; case CLE_T_LONG: { long l; anerr = (arg==NULL) || (sscanf(arg, "%ld", &l) != 1); if(!anerr) *(int *)(ent->where) = l; } argUsed = 1; break; case CLE_T_FLOAT: { float f; anerr = (arg==NULL) || (sscanf(arg, "%f", &f) != 1); if(!anerr) *(float *)(ent->where) = f; } argUsed = 1; break; case CLE_T_TIME: { float f; anerr = (arg==NULL) || (cleScanTime(arg, &f) != 1); if(!anerr) *(float *)(ent->where) = f; } argUsed = 1; break; case CLE_T_STRING: if(arg==NULL) { anerr=1; } else { /* free any default value */ if (*(char **)ent->where) free(*(char **)ent->where); *(char **)(ent->where) = strdup(arg); argUsed = 1; } break; case CLE_T_BOOL: ++(*(int *)(ent->where)); break; case CLE_T_INVBOOL: --(*(int *)(ent->where)); break; case CLE_T_TOKEN: rc = cleTokenSetFn(arg,ent->where, tok, ent->specData); if(rc == 1) argUsed = 1; else if(rc != 0) anerr = 1; break; case CLE_T_SPECIAL: rc = (*(ent->specialfn))(arg, ent->where, tok, ent->specData); if(rc == 1) argUsed = 1; else if(rc != 0) anerr = 1; break; default: fprintf(stderr, "cleExtractArgs: unknown CLE_TYPE %d\n", ent->type); abort; } if(anerr) { fprintf(stderr, "%s: error reading '%s'(%s) as %s(%s)\n", programName, tok, (arg==NULL)?"NULL":arg, ent->flag, ent->usage); ++errs; } DBGFPRINTF((stderr, \ "cle(%d): matched %s %s as %s %s (%s %s)\n", \ i, tok, next?next:"(NULL)", flag, \ argUsed?arg:"", ent->flag, ent->usage)); } } ++ent; } if(!tokDone) { /* this token was not recognized at all */ float dummy; if(noExtraArgs \ || (tok[0] == '-' && strlen(tok) > 1 \ && sscanf(tok, "%f", &dummy) == 0) ) { /* report an error if we don't expect any unrecognized args - or even if we do, but the tok is of "-foo" form, *unless* it's a valid number (e.g. -123) */ fprintf(stderr, "%s: '%s' not recognized\n", programName, tok); ++errs; } else { /* just copy the missed tok to output */ argv[outargc] = tok; ++outargc; } } else if(!argUsed) { /* we recognized a token but it didn't use the arg - any arg is thus a candidate for the next token */ if(arg != next) { /* arg was not just the next token - so set it as a cont'n */ /* fakely prepend the '-' (or ...) */ tokbuf[0] = flag[0]; strcpy(tokbuf+1, arg); /* flag looptop not read next arg */ tokcontinued = 1; tok = tokbuf; } } else { /* tok used the arg. If it was the next tok, skip it */ if(arg == next) { ++i; } } } *pargc = outargc; /* if(errs) cleUsage(entries, argv[0]); */ return errs; } #ifdef MAIN /* test code */ CLE_TOKEN testTable[] = { { "*F", 0 }, /* -rasta no */ { "j?ah", 1 }, { "cj?ah", 2 }, { "*T|log|", 3 }, /* -rasta yes or -rasta log or -rasta */ { NULL, 0} }; enum {AWCMP_NONE, AWCMP_MPEG_LAYER_I, AWCMP_MPEG_LAYER_II, AWCMP_MULTIRATE}; CLE_TOKEN algoTable[] = { { "-|*F", AWCMP_NONE }, { "mpeg2|mp2", AWCMP_MPEG_LAYER_II }, { "mr" , AWCMP_MULTIRATE }, /* must come last because has null field (meaning no arg) */ { "*T|mpeg?1|mp1|", AWCMP_MPEG_LAYER_I }, { NULL, 0 } }; #define DFLT_ALGO "no" #define DFLT_FXBR 192000 int algoType; float fixedBR; int nokbd = -1; int debug = -99; char *inpath = NULL, *outpath; CLE_ENTRY clargs[] = { { "-A|--algo?rithm", CLE_T_TOKEN, "algorithm type", DFLT_ALGO, &algoType, NULL, algoTable }, { "-F?ixbr", CLE_T_FLOAT, "fixed bitrate", QUOTE(DFLT_FXBR), &fixedBR, NULL, NULL }, { "-K|-nokbd", CLE_T_BOOL, "ignore the keyboard interrupt", NULL, &nokbd, NULL, NULL }, { "-D|--de?bug", CLE_T_INT, "debug level", NULL, &debug, NULL, NULL }, { "", CLE_T_STRING, "input sound file name", NULL, &inpath, NULL, NULL }, { "", CLE_T_STRING, "output compressed file name", "", &outpath, NULL, NULL }, { "", CLE_T_END, NULL, NULL, NULL, NULL, NULL } }; int main(int argc, char **argv) { /* test that NULL means don't set a default, but "0" sets to zero */ debug = -99; nokbd = -1; fixedBR = -1.0; cleSetDefaults(clargs); if (debug != -99) { fprintf(stderr, "debug defaulted to %d\n", debug); exit(-1); } if (nokbd != 0) { /* implicit defaults for bools? */ fprintf(stderr, "nokbd defaulted to %d\n", nokbd); exit(-1); } if (fixedBR != DFLT_FXBR) { fprintf(stderr, "fixBR defaulted to %f\n", fixedBR); exit(-1); } if(cleHandleArgs(clargs, argc, argv)) { cleUsage(clargs, argv[0]); exit(-1); } printf("algoType=%d fixedBR=%.1f nokbd=%d debug=%d\n", algoType, fixedBR, nokbd, debug); printf("inpath=%s\n", inpath?inpath:"(NULL)"); printf("outpath=%s\n", outpath?outpath:"(NULL)"); exit(0); } #endif /* MAIN */
2.78125
3
2024-11-18T20:48:46.601791+00:00
2021-07-21T23:14:53
477deb726db7170e1f4ea59ae6608be03f03677a
{ "blob_id": "477deb726db7170e1f4ea59ae6608be03f03677a", "branch_name": "refs/heads/master", "committer_date": "2021-07-21T23:14:53", "content_id": "12133bdf2beb39f98e6f74605cd64f80c13f2a04", "detected_licenses": [ "BSD-2-Clause-Patent" ], "directory_id": "a29e0e317e23d1f991dda1b51c63be5433a6cc39", "extension": "c", "filename": "SpdmRequesterLibGetCapability.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": 7535, "license": "BSD-2-Clause-Patent", "license_type": "permissive", "path": "/Library/SpdmRequesterLib/SpdmRequesterLibGetCapability.c", "provenance": "stackv2-0102.json.gz:77552", "repo_name": "Wenxing-hou/openspdm", "revision_date": "2021-07-21T23:14:53", "revision_id": "05923893febc0582043ae350c2c1ba6a62d36dac", "snapshot_id": "1e430f6ea40d24a4630481f1b1202170c1054bd8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Wenxing-hou/openspdm/05923893febc0582043ae350c2c1ba6a62d36dac/Library/SpdmRequesterLib/SpdmRequesterLibGetCapability.c", "visit_date": "2023-06-20T00:22:55.775022" }
stackv2
/** @file SPDM common library. It follows the SPDM Specification. Copyright (c) 2020, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "SpdmRequesterLibInternal.h" #include <stdio.h> /** This function checks the compability of the received CAPABILITES flag. Some flags are mutually inclusive/exclusive. @param CapabilitiesFlag The received CAPABILITIES Flag. @param Version The SPMD message version. @retval True The received Capabilities flag is valid. @retval False The received Capabilities flag is invalid. **/ BOOLEAN SpdmCheckFlagCompability ( IN UINT32 CapabilitiesFlag, IN UINT8 Version ) { //UINT8 CACHE_CAP = (UINT8)(CapabilitiesFlag)&0x01; UINT8 CERT_CAP = (UINT8)(CapabilitiesFlag>>1)&0x01; //UINT8 CHAL_CAP = (UINT8)(CapabilitiesFlag>>2)&0x01; UINT8 MEAS_CAP = (UINT8)(CapabilitiesFlag>>3)&0x03; //UINT8 MEAS_FRESH_CAP = (UINT8)(CapabilitiesFlag>>5)&0x01; UINT8 ENCRYPT_CAP = (UINT8)(CapabilitiesFlag>>6)&0x01; UINT8 MAC_CAP = (UINT8)(CapabilitiesFlag>>7)&0x01; UINT8 MUT_AUTH_CAP = (UINT8)(CapabilitiesFlag>>8)&0x01; UINT8 KEY_EX_CAP = (UINT8)(CapabilitiesFlag>>9)&0x01; UINT8 PSK_CAP = (UINT8)(CapabilitiesFlag>>10)&0x03; UINT8 ENCAP_CAP = (UINT8)(CapabilitiesFlag>>12)&0x01; //UINT8 HBEAT_CAP = (UINT8)(CapabilitiesFlag>>13)&0x01; //UINT8 KEY_UPD_CAP = (UINT8)(CapabilitiesFlag>>14)&0x01; UINT8 HANDSHAKE_IN_THE_CLEAR_CAP = (UINT8)(CapabilitiesFlag>>15)&0x01; UINT8 PUB_KEY_ID_CAP = (UINT8)(CapabilitiesFlag>>16)&0x01; //UINT32 ReservedFlags = (UINT32)(CapabilitiesFlag>>17); switch (Version) { case SPDM_MESSAGE_VERSION_10: return TRUE; case SPDM_MESSAGE_VERSION_11: { //Encrypt_cap set and psk_cap+key_ex_cap cleared if(ENCRYPT_CAP!=0 && (PSK_CAP==0 && KEY_EX_CAP==0)){ return FALSE; } //MAC_cap set and psk_cap+key_ex_cap cleared if(MAC_CAP!=0 && (PSK_CAP==0 && KEY_EX_CAP==0)){ return FALSE; } //Key_ex_cap set and encrypt_cap+mac_cap cleared if(KEY_EX_CAP!=0 && (ENCRYPT_CAP==0 && MAC_CAP==0)){ return FALSE; } //PSK_cap set and encrypt_cap+mac_cap cleared if(PSK_CAP!=0 && (ENCRYPT_CAP==0 && MAC_CAP==0)){ return FALSE; } //Muth_auth_cap set and encap_cap cleared if(MUT_AUTH_CAP!=0 && ENCAP_CAP==0){ return FALSE; } //Handshake_in_the_clear_cap set and key_ex_cap cleared if(HANDSHAKE_IN_THE_CLEAR_CAP!=0 && KEY_EX_CAP==0){ return FALSE; } //Handshake_in_the_clear_cap set and encrypt_cap+mac_cap cleared if((ENCRYPT_CAP==0 && MAC_CAP==0) && HANDSHAKE_IN_THE_CLEAR_CAP!=0){ return FALSE; } //Pub_key_id_cap set and cert_cap set if(PUB_KEY_ID_CAP!=0 && CERT_CAP!=0){ return FALSE; } //Reserved values selected in Flags if(MEAS_CAP == 3 || PSK_CAP == 3){ return FALSE; } } return TRUE; default: return TRUE; } } /** This function sends GET_CAPABILITIES and receives CAPABILITIES. @param SpdmContext A pointer to the SPDM context. @retval RETURN_SUCCESS The GET_CAPABILITIES is sent and the CAPABILITIES is received. @retval RETURN_DEVICE_ERROR A device error occurs when communicates with the device. **/ RETURN_STATUS TrySpdmGetCapabilities ( IN SPDM_DEVICE_CONTEXT *SpdmContext ) { RETURN_STATUS Status; SPDM_GET_CAPABILITIES_REQUEST SpdmRequest; UINTN SpdmRequestSize; SPDM_CAPABILITIES_RESPONSE SpdmResponse; UINTN SpdmResponseSize; if (SpdmContext->ConnectionInfo.ConnectionState != SpdmConnectionStateAfterVersion) { return RETURN_UNSUPPORTED; } ZeroMem (&SpdmRequest, sizeof(SpdmRequest)); if (SpdmIsVersionSupported (SpdmContext, SPDM_MESSAGE_VERSION_11)) { SpdmRequest.Header.SPDMVersion = SPDM_MESSAGE_VERSION_11; SpdmRequestSize = sizeof(SpdmRequest); } else { SpdmRequest.Header.SPDMVersion = SPDM_MESSAGE_VERSION_10; SpdmRequestSize = sizeof(SpdmRequest.Header); } SpdmRequest.Header.RequestResponseCode = SPDM_GET_CAPABILITIES; SpdmRequest.Header.Param1 = 0; SpdmRequest.Header.Param2 = 0; SpdmRequest.CTExponent = SpdmContext->LocalContext.Capability.CTExponent; SpdmRequest.Flags = SpdmContext->LocalContext.Capability.Flags; Status = SpdmSendSpdmRequest (SpdmContext, NULL, SpdmRequestSize, &SpdmRequest); if (RETURN_ERROR(Status)) { return RETURN_DEVICE_ERROR; } // // Cache data // Status = SpdmAppendMessageA (SpdmContext, &SpdmRequest, SpdmRequestSize); if (RETURN_ERROR(Status)) { return RETURN_SECURITY_VIOLATION; } SpdmResponseSize = sizeof(SpdmResponse); ZeroMem (&SpdmResponse, sizeof(SpdmResponse)); Status = SpdmReceiveSpdmResponse (SpdmContext, NULL, &SpdmResponseSize, &SpdmResponse); if (RETURN_ERROR(Status)) { return RETURN_DEVICE_ERROR; } if (SpdmResponseSize < sizeof(SPDM_MESSAGE_HEADER)) { return RETURN_DEVICE_ERROR; } if (SpdmResponse.Header.RequestResponseCode == SPDM_ERROR) { ShrinkManagedBuffer(&SpdmContext->Transcript.MessageA, SpdmRequestSize); Status = SpdmHandleSimpleErrorResponse(SpdmContext, SpdmResponse.Header.Param1); if (RETURN_ERROR(Status)) { return Status; } } else if (SpdmResponse.Header.RequestResponseCode != SPDM_CAPABILITIES) { return RETURN_DEVICE_ERROR; } if (SpdmResponseSize < sizeof(SPDM_CAPABILITIES_RESPONSE)) { return RETURN_DEVICE_ERROR; } if (SpdmResponseSize > sizeof(SpdmResponse)) { return RETURN_DEVICE_ERROR; } //Check if received message version matches sent message version if (SpdmRequest.Header.SPDMVersion != SpdmResponse.Header.SPDMVersion) { return RETURN_DEVICE_ERROR; } SpdmResponseSize = sizeof(SPDM_CAPABILITIES_RESPONSE); if(!SpdmCheckFlagCompability(SpdmResponse.Flags,SpdmResponse.Header.SPDMVersion)){ return RETURN_DEVICE_ERROR; } // // Cache data // Status = SpdmAppendMessageA (SpdmContext, &SpdmResponse, SpdmResponseSize); if (RETURN_ERROR(Status)) { return RETURN_SECURITY_VIOLATION; } SpdmContext->ConnectionInfo.Capability.CTExponent = SpdmResponse.CTExponent; SpdmContext->ConnectionInfo.Capability.Flags = SpdmResponse.Flags; SpdmContext->ConnectionInfo.ConnectionState = SpdmConnectionStateAfterCapabilities; return RETURN_SUCCESS; } /** This function sends GET_CAPABILITIES and receives CAPABILITIES. @param SpdmContext A pointer to the SPDM context. @retval RETURN_SUCCESS The GET_CAPABILITIES is sent and the CAPABILITIES is received. @retval RETURN_DEVICE_ERROR A device error occurs when communicates with the device. **/ RETURN_STATUS EFIAPI SpdmGetCapabilities ( IN SPDM_DEVICE_CONTEXT *SpdmContext ) { UINTN Retry; RETURN_STATUS Status; Retry = SpdmContext->RetryTimes; do { Status = TrySpdmGetCapabilities(SpdmContext); if (RETURN_NO_RESPONSE != Status) { return Status; } } while (Retry-- != 0); return Status; }
2.125
2
2024-11-18T20:48:47.117518+00:00
2021-07-23T12:37:24
079fde12ef0c4386467665ecb8649cc51b55a231
{ "blob_id": "079fde12ef0c4386467665ecb8649cc51b55a231", "branch_name": "refs/heads/main", "committer_date": "2021-07-23T12:37:24", "content_id": "f008f53fda97a309821054a6fd9d65c0cfa24ce3", "detected_licenses": [ "MIT" ], "directory_id": "4e9f75e5b6952a340d5209e5119b93eaec893eb6", "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": 388735251, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 390, "license": "MIT", "license_type": "permissive", "path": "/02_oldez/main.c", "provenance": "stackv2-0102.json.gz:78068", "repo_name": "Enigmatrix/shellcode_examples", "revision_date": "2021-07-23T12:37:24", "revision_id": "576c318342c6cfb611e74ff5f14f46f995d1f22e", "snapshot_id": "c1674c5cdf4684306f341d33e82b2b8c7f29db32", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Enigmatrix/shellcode_examples/576c318342c6cfb611e74ff5f14f46f995d1f22e/02_oldez/main.c", "visit_date": "2023-06-27T07:20:55.827477" }
stackv2
#include <stdio.h> #include <unistd.h> int setup() { // turn off buffering, then printing to stdout etc will be better setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); } int main() { setup(); char name[0x40]; printf("Enter your name at %p: ", name); // OwO what's this read(0, name, 0x400); // uwu, too big? }
2.65625
3
2024-11-18T20:48:47.520959+00:00
2018-04-24T19:05:07
cce80a52018efbde90e3b4c8d342fcc17e1c4f78
{ "blob_id": "cce80a52018efbde90e3b4c8d342fcc17e1c4f78", "branch_name": "refs/heads/master", "committer_date": "2018-04-24T19:05:07", "content_id": "8d8e88a849815ffbd42310edd788535685279d1a", "detected_licenses": [ "MIT" ], "directory_id": "4e655840a27fba320caa380c582b04fb82e36b04", "extension": "c", "filename": "structures.c", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 119591283, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1192, "license": "MIT", "license_type": "permissive", "path": "/L04/structures.c", "provenance": "stackv2-0102.json.gz:78455", "repo_name": "nchalmer/CMDA3634SP18", "revision_date": "2018-04-24T19:05:07", "revision_id": "ef8a3bcfe680b630f9386f34c65257345cc9f63a", "snapshot_id": "12b4b9cb44ac61f4d29d856a92d586ee667d8844", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/nchalmer/CMDA3634SP18/ef8a3bcfe680b630f9386f34c65257345cc9f63a/L04/structures.c", "visit_date": "2021-05-08T20:00:35.044099" }
stackv2
#include<stdio.h> #include<stdlib.h> #include <math.h> //define a new data structure called 'point' typedef struct { float x; float y; float z; } point; //we can pass this structure to functions and access it's sub-variables void pointPrintPoint(point p) { printf("Point has coordinates (%f,%f,%f) \n", p.x,p.y,p.z); } //if we want to alter the structure inside a function, we need to pass its pointer void pointSetZero(point *p) { //(*p).x = 0.; //(*p).y = 0.; //(*p).z = 0.; //also valid //point pp = *p; //pp.x = 0.; //pp.y = 0.; //pp.z = 0.; //and so is this. -> is a kind of shift+dereferance operator p->x = 0.; p->y = 0.; p->z = 0.; } float pointDistanceToOrigin(point p) { float dist = sqrt(p.x*p.x+p.y*p.y+p.z*p.z); return dist; } void main() { //we can declare this new structure like any other variable point p; //access variables in stucture with '.' p.x = 1.0; p.y = 2.0; p.z = 3.0; float dist; //we can pass it to a function and return a value dist = pointDistanceToOrigin(p); printf("dist = %f\n",dist); //we pass its pointer so we can change it pointSetZero(&p); pointPrintPoint(p); }
3.625
4
2024-11-18T20:48:47.627214+00:00
2018-05-20T06:31:41
cc0e1fbcef0f4a94cd8c6011bc30d5b50dfeb4e9
{ "blob_id": "cc0e1fbcef0f4a94cd8c6011bc30d5b50dfeb4e9", "branch_name": "refs/heads/master", "committer_date": "2018-05-20T06:31:41", "content_id": "f7d13c86972c59395c60c6887d192f7d79bfedbe", "detected_licenses": [ "MIT" ], "directory_id": "b7a504e5f1709029e2334d0da29449fc523b347f", "extension": "c", "filename": "hello.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 134124251, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 97, "license": "MIT", "license_type": "permissive", "path": "/share2/hello.c", "provenance": "stackv2-0102.json.gz:78583", "repo_name": "orgteywu/linux_test", "revision_date": "2018-05-20T06:31:41", "revision_id": "0b9c7576b67297bb65c6994b60e4936bfd5d1522", "snapshot_id": "51ed8787b76799f19e07d7eb7db3b4632026b8cd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/orgteywu/linux_test/0b9c7576b67297bb65c6994b60e4936bfd5d1522/share2/hello.c", "visit_date": "2020-03-18T01:02:09.536080" }
stackv2
#include <stdio.h> void hello() { printf("hello\n"); } int add(int a, int b) { return a+b; }
2.015625
2
2024-11-18T20:48:47.708385+00:00
2016-03-01T04:03:28
cd9f18a30bbced2cab782830a6a1203857d1d079
{ "blob_id": "cd9f18a30bbced2cab782830a6a1203857d1d079", "branch_name": "refs/heads/master", "committer_date": "2016-03-01T04:03:28", "content_id": "f18a13875fd3252dee236bc77d64cb0a05067c10", "detected_licenses": [ "MIT" ], "directory_id": "58efb8fec4abe0668a367c7129910ce766db0b5d", "extension": "c", "filename": "input.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 51973112, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1939, "license": "MIT", "license_type": "permissive", "path": "/src/input.c", "provenance": "stackv2-0102.json.gz:78714", "repo_name": "matheus-msr/morsetrainer", "revision_date": "2016-03-01T04:03:28", "revision_id": "ea46c39f65be1953f23e981906d76b133c7a5684", "snapshot_id": "f481e1b878e15834a38e3afb7695f60d7093a4b8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/matheus-msr/morsetrainer/ea46c39f65be1953f23e981906d76b133c7a5684/src/input.c", "visit_date": "2021-01-10T07:15:44.688536" }
stackv2
#include <string.h> #include <SDL2/SDL.h> #include "graphics.h" #include "input.h" int clicked(SDL_Event ev, SDL_Rect pos) { int mx, my; SDL_GetMouseState(&mx, &my); if(ev.type == SDL_MOUSEBUTTONDOWN) { // test if the mouse is inside the buttons boundaries if((mx > pos.x && (mx < (pos.x + pos.w))) && (my > pos.y && (my < (pos.y + pos.h)))) { wait_unpress(&ev); // wait until user releases the button return CLICKED; } } return NOT_CLICKED; } int wait_unpress(SDL_Event *ev) { // wait until the user has released the button SDL_Delay(1); // Sets the event as a mouse button unclicked ev->type = SDL_MOUSEBUTTONUP; return 0; } int get_text(struct s_context *cxt, const char * msg, char * input_text) { int got_text = 0; const Uint8 *keybrd = NULL; char tmp[8] = {""}; SDL_Rect txt; SDL_Rect input_box; SDL_Event ev; txt.x = 140; txt.y = 180; input_box.h = 40; input_box.w = 100; input_box.x = 100; input_box.y = 250; clear_screen(cxt); blit_text(cxt, 30, msg, "res/font.ttf", txt); SDL_FillRect(cxt->screen, &input_box, SDL_MapRGB(cxt->screen->format, 255, 255, 255)); while(!got_text) { while(SDL_PollEvent(&ev)) { keybrd = SDL_GetKeyboardState(NULL); if(keybrd[SDL_SCANCODE_BACKSPACE] && strlen(tmp) > 0){ tmp[strlen(tmp) - 1] = '\0'; SDL_FillRect(cxt->screen, &input_box, SDL_MapRGB(cxt->screen->format, 255, 255, 255)); blit_text(cxt, 30, tmp, "res/font.ttf", input_box); } else if(keybrd[SDL_SCANCODE_RETURN]) { got_text = 1; } if(ev.type == SDL_TEXTINPUT && strlen(tmp) < 5 && ev.text.text != NULL) { strcat(tmp, ev.text.text); SDL_FillRect(cxt->screen, &input_box, SDL_MapRGB(cxt->screen->format, 255, 255, 255)); blit_text(cxt, 30, tmp, "res/font.ttf", input_box); } else if(ev.type == SDL_QUIT) { return SDL_QUIT; } } SDL_Delay(1000/30); show(*cxt); } sscanf(tmp, "%s", input_text); return 0; }
2.65625
3
2024-11-18T20:48:51.682204+00:00
2019-03-27T15:50:35
7263bde978ddd4cf0eaa099856df3008b628f6cb
{ "blob_id": "7263bde978ddd4cf0eaa099856df3008b628f6cb", "branch_name": "refs/heads/master", "committer_date": "2019-03-27T15:50:35", "content_id": "e14563bad92d5c23cece039deb504ac94b6125d7", "detected_licenses": [ "MIT" ], "directory_id": "596626032c35261a800daf78f0fc9447585d88bc", "extension": "c", "filename": "tbd.c", "fork_events_count": 0, "gha_created_at": "2017-03-15T18:23:50", "gha_event_created_at": "2017-03-15T18:23:50", "gha_language": null, "gha_license_id": null, "github_id": 85106916, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8430, "license": "MIT", "license_type": "permissive", "path": "/src/tbd.c", "provenance": "stackv2-0102.json.gz:84093", "repo_name": "swigger/tbd", "revision_date": "2019-03-27T15:50:35", "revision_id": "06ff2dad00053422017a70a96809eef69b6226fa", "snapshot_id": "7d2ccafd88188312204deb62c9087e0a3d5cf34a", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/swigger/tbd/06ff2dad00053422017a70a96809eef69b6226fa/src/tbd.c", "visit_date": "2021-01-22T18:42:54.250992" }
stackv2
// // src/tbd.c // tbd // // Created by inoahdev on 11/22/18. // Copyright © 2018 - 2019 inoahdev. All rights reserved. // #include <stdlib.h> #include <stdio.h> #include <string.h> #include "tbd.h" #include "tbd_write.h" /* * Have the symbols array be sorted first into groups of matching arch-lists. * The arch-lists themselves are sorted to where arch-lists with more archs are * "greater", than those without. * Arch-lists with the same number of archs are just compared numberically. * * Within each arch-list group, the symbols are then organized by their types. * Within each type group, the symbols are then finally organized * alphabetically. * * This is done to make the creation of export-groups later on easier, as no * the symbols are already organized by their arch-lists, and then their types, * all alphabetically. */ int tbd_export_info_no_archs_comparator(const void *const array_item, const void *const item) { const struct tbd_export_info *const array_info = (const struct tbd_export_info *)array_item; const struct tbd_export_info *const info = (const struct tbd_export_info *)item; const enum tbd_export_type array_type = array_info->type; const enum tbd_export_type type = info->type; if (array_type != type) { return (int)(array_type - type); } const uint64_t array_length = array_info->length; const uint64_t length = info->length; /* * We try to avoid iterating and comparing over the whole string, so we * could check to ensure their lengths match up. * * However, we don't want to symbols to ever be organized by their length, * which would be the case if `(array_length - length)` was returned. * * So instead, we use separate memcmp() calls for when array_length and * length don't match, depending on which is bigger. * * This stops us from having to use strcmp(), which would be the case since * the lengths don't match. * * Add one to also compare the null-terminator. */ if (array_length > length) { return memcmp(array_info->string, info->string, length + 1); } else if (array_length < length) { return memcmp(array_info->string, info->string, array_length + 1); } const char *const array_string = array_info->string; const char *const string = info->string; return memcmp(array_string, string, length); } int tbd_export_info_comparator(const void *const array_item, const void *const item) { const struct tbd_export_info *const array_info = (const struct tbd_export_info *)array_item; const struct tbd_export_info *const info = (const struct tbd_export_info *)item; const uint64_t array_archs_count = array_info->archs_count; const uint64_t archs_count = info->archs_count; if (array_archs_count > archs_count) { return 1; } else if (array_archs_count < archs_count) { return -1; } const uint64_t array_archs = array_info->archs; const uint64_t archs = info->archs; if (array_archs > archs) { return 1; } else if (array_archs < archs) { return -1; } const enum tbd_export_type array_type = array_info->type; const enum tbd_export_type type = info->type; if (array_type != type) { return (int)(array_type - type); } const uint64_t array_length = array_info->length; const uint64_t length = info->length; /* * We try to avoid iterating and comparing over the whole string, so we * could check to ensure their lengths match up. * * However, we don't want to symbols to ever be organized by their length, * which would be the case if `(array_length - length)` was returned. * * So instead, we use separate memcmp() calls for when array_length and * length don't match, depending on which is bigger. * * This stops us from having to use strcmp(), which would be the case since * the lengths don't match. * * Add one to also compare the null-terminator. */ if (array_length > length) { return memcmp(array_info->string, info->string, length + 1); } else if (array_length < length) { return memcmp(array_info->string, info->string, array_length + 1); } const char *const array_string = array_info->string; const char *const string = info->string; return memcmp(array_string, string, length); } int tbd_uuid_info_comparator(const void *const array_item, const void *const item) { const struct tbd_uuid_info *const array_uuid_info = (const struct tbd_uuid_info *)array_item; const struct tbd_uuid_info *const uuid_info = (const struct tbd_uuid_info *)item; const struct arch_info *const array_arch_info = array_uuid_info->arch; const struct arch_info *const arch_info = uuid_info->arch; if (array_arch_info > arch_info) { return 1; } else if (array_arch_info < arch_info) { return -1; } return 0; } enum tbd_create_result tbd_create_with_info(const struct tbd_create_info *const info, FILE *const file, const uint64_t options) { const enum tbd_version version = info->version; if (tbd_write_magic(file, version)) { return E_TBD_CREATE_WRITE_FAIL; } if (tbd_write_archs_for_header(file, info->archs)) { return E_TBD_CREATE_WRITE_FAIL; } if (!(options & O_TBD_CREATE_IGNORE_UUIDS)) { if (version != TBD_VERSION_V1) { if (tbd_write_uuids(file, &info->uuids)) { return E_TBD_CREATE_WRITE_FAIL; } } } if (tbd_write_platform(file, info->platform)) { return E_TBD_CREATE_WRITE_FAIL; } if (version != TBD_VERSION_V1) { if (!(options & O_TBD_CREATE_IGNORE_FLAGS)) { if (tbd_write_flags(file, info->flags_field)) { return E_TBD_CREATE_WRITE_FAIL; } } } if (tbd_write_install_name(file, info)) { return E_TBD_CREATE_WRITE_FAIL; } if (!(options & O_TBD_CREATE_IGNORE_CURRENT_VERSION)) { if (tbd_write_current_version(file, info->current_version)) { return E_TBD_CREATE_WRITE_FAIL; } } if (!(options & O_TBD_CREATE_IGNORE_COMPATIBILITY_VERSION)) { const uint32_t compatibility_version = info->compatibility_version; if (tbd_write_compatibility_version(file, compatibility_version)) { return E_TBD_CREATE_WRITE_FAIL; } } if (version != TBD_VERSION_V1) { if (!(options & O_TBD_CREATE_IGNORE_SWIFT_VERSION)) { if (tbd_write_swift_version(file, version, info->swift_version)) { return E_TBD_CREATE_WRITE_FAIL; } } if (!(options & O_TBD_CREATE_IGNORE_OBJC_CONSTRAINT)) { if (tbd_write_objc_constraint(file, info->objc_constraint)) { return E_TBD_CREATE_WRITE_FAIL; } } if (!(options & O_TBD_CREATE_IGNORE_PARENT_UMBRELLA)) { if (tbd_write_parent_umbrella(file, info)) { return E_TBD_CREATE_WRITE_FAIL; } } } if (!(options & O_TBD_CREATE_IGNORE_EXPORTS)) { if (tbd_write_exports(file, &info->exports, version)) { return E_TBD_CREATE_WRITE_FAIL; } } if (tbd_write_footer(file)) { return E_TBD_CREATE_WRITE_FAIL; } return E_TBD_CREATE_OK; } static void destroy_exports_array(struct array *const list) { struct tbd_export_info *info = list->data; const struct tbd_export_info *const end = list->data_end; for (; info != end; info++) { free(info->string); } array_destroy(list); } void tbd_create_info_destroy(struct tbd_create_info *const info) { if (info->flags & F_TBD_CREATE_INFO_STRINGS_WERE_COPIED) { free((char *)info->install_name); free((char *)info->parent_umbrella); } info->version = 0; info->archs = 0; info->flags = 0; info->platform = 0; info->objc_constraint = 0; info->install_name = NULL; info->parent_umbrella = NULL; info->current_version = 0; info->compatibility_version = 0; info->swift_version = 0; destroy_exports_array(&info->exports); array_destroy(&info->uuids); }
2.640625
3
2024-11-18T20:48:53.188990+00:00
2023-03-10T12:33:23
b090bfd867a82ce44c2e8d7629f98fc7a6c9083f
{ "blob_id": "b090bfd867a82ce44c2e8d7629f98fc7a6c9083f", "branch_name": "refs/heads/main", "committer_date": "2023-03-10T12:33:23", "content_id": "0df264753b8500dd20928d885761de5eb0495f1e", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "57d0f7e4c74f2f50fa9c4dc4e8227e4c014b4414", "extension": "h", "filename": "detox_struct.h", "fork_events_count": 23, "gha_created_at": "2017-02-23T04:38:21", "gha_event_created_at": "2023-09-13T10:13:15", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 82884753, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1882, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/detox_struct.h", "provenance": "stackv2-0102.json.gz:84612", "repo_name": "dharple/detox", "revision_date": "2023-03-10T12:33:23", "revision_id": "df0c0781b76c1f96b0018d8f376d4674f0cb607f", "snapshot_id": "4e568272b7ea5c8d1c1acda3f0ca48b2debf9583", "src_encoding": "UTF-8", "star_events_count": 252, "url": "https://raw.githubusercontent.com/dharple/detox/df0c0781b76c1f96b0018d8f376d4674f0cb607f/src/detox_struct.h", "visit_date": "2023-03-24T06:09:24.417994" }
stackv2
/** * This file is part of the Detox package. * * Copyright (c) Doug Harple <detox.dharple@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #ifndef __DETOX_STRUCT_H #define __DETOX_STRUCT_H #include <stdlib.h> #define MAX_PATH_LEN 256 enum { FILTER_ISO8859_1 = 1, FILTER_LOWER, FILTER_MAX_LENGTH, FILTER_SAFE, FILTER_UNCGI, FILTER_UTF_8, FILTER_WIPEUP }; typedef struct { char **files; int max; int count; int ptr; } filelist_t; typedef struct { unsigned int key; char *data; } table_row_t; typedef struct { int length; int used; int max_data_length; char *default_translation; table_row_t *rows; int hits; int misses; int overwrites; int seeks; int use_hash; int builtin; int max_key; } table_t; typedef struct filter_t_ref { struct filter_t_ref *next; int cleaner; char *filename; char *builtin; int remove_trailing; size_t max_length; table_t *table; } filter_t; /* * Holds information about all of the defined sequences */ typedef struct sequence_t_ref { struct sequence_t_ref *next; char *name; filter_t *filters; char *source_filename; } sequence_t; /* * Holds the result of a config file parse */ typedef struct { sequence_t *sequences; filelist_t *files_to_ignore; } config_file_t; /** * Holds options that affect the entire operation of the program. */ typedef struct { int dry_run; int is_inline_bin; int is_inline_mode; int list_sequences; int recurse; int special; int verbose; sequence_t *sequence_to_use; filelist_t *files_to_ignore; char *sequence_name; char *check_config_file; filelist_t *files; } options_t; #endif /* __DETOX_STRUCT_H */
2.078125
2
2024-11-18T20:48:53.546346+00:00
2021-11-10T14:46:27
a03b922478d74311eea3254e401844170be0d832
{ "blob_id": "a03b922478d74311eea3254e401844170be0d832", "branch_name": "refs/heads/main", "committer_date": "2021-11-10T14:46:27", "content_id": "44719938b906ab931a5eedc1d098a7ab35f6dec1", "detected_licenses": [ "MIT" ], "directory_id": "d9784392798083e20fcadba6ad1f81ea934103f0", "extension": "c", "filename": "Window.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": 1250, "license": "MIT", "license_type": "permissive", "path": "/src/Graphics/Window.c", "provenance": "stackv2-0102.json.gz:85001", "repo_name": "TheArduinoBoy/Radical-OS", "revision_date": "2021-11-10T14:46:27", "revision_id": "2703e5a30ac69fc4f0e26278c14de1a95bac32bc", "snapshot_id": "bfd4e4c0e2804f70bdcedc3387d742a1dd7bae2c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TheArduinoBoy/Radical-OS/2703e5a30ac69fc4f0e26278c14de1a95bac32bc/src/Graphics/Window.c", "visit_date": "2023-09-02T07:47:17.545433" }
stackv2
#include <Drivers/Screen.h> #include <Graphics/Graphics.h> #include <Util/string.h> #include <System/IO.h> char *screen = (char *)0xFFFFFFF; void makeWindow(char *window_name) { for (int i = 0; i < 160 * 25; i++) { screen[i] = Screen->vga[i]; } clearScreen(); for (int i = 0; i < 80; i++) { printChar(' ', 0x1f); setCharAt(i, 24, ' ', 0x1f); } for (int i = 0; i < 25; i++) { setCharAt(0, i, ' ', 0x1f); setCharAt(79, i, ' ', 0x1f); } printCenter(0, window_name, 0x1f); Screen->cursorX = 2; Screen->cursorY = 1; printAt(0, 24, " Press ESC to exit", 0x1f); printAt(0, 24, " Press ESC to exit", 0x1f); } void printStringInWindow(char *text) { for (int i = 0; i < length(text); i++) { if (Screen->cursorX % 160 == 0) { Screen->cursorX += 2; } if (Screen->cursorX % 158 == 0) { Screen->cursorX += 4; } printC(text[i]); } } void start_window_system() { int running = 1; while (running) if (inportb(0x60) == 0x01) running = 0; clearFullScreen(); } void clearWindow() { for (int i = 160; i < 1840; i += 2) { Screen->vga[i] = 0; } Screen->cursorX = 2; Screen->cursorY = 1; }
2.328125
2
2024-11-18T20:48:53.880881+00:00
2020-02-18T20:20:02
d4b010b19b08db9ef812c54f17d3aa8c2d003a0f
{ "blob_id": "d4b010b19b08db9ef812c54f17d3aa8c2d003a0f", "branch_name": "refs/heads/master", "committer_date": "2020-02-18T20:20:02", "content_id": "ff2e2f91f1755b40e0b956c746b464bbbe6d4467", "detected_licenses": [ "MIT" ], "directory_id": "13644ab2c8453603d0731d168c24e552db124387", "extension": "c", "filename": "07_DiaDoAno_3V.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 238496127, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2255, "license": "MIT", "license_type": "permissive", "path": "/C/Filipe Correia/04_testeAvaliacao/07_DiaDoAno_3V.c", "provenance": "stackv2-0102.json.gz:85515", "repo_name": "TheMarques/Atec", "revision_date": "2020-02-18T20:20:02", "revision_id": "a61409d7cfeab91f45528696ce914fa730366282", "snapshot_id": "0379efcd3f25f017f5fb9b1baf32117cd6e0d446", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TheMarques/Atec/a61409d7cfeab91f45528696ce914fa730366282/C/Filipe Correia/04_testeAvaliacao/07_DiaDoAno_3V.c", "visit_date": "2020-12-29T06:41:48.292539" }
stackv2
#include <stdio.h> /* Pretende-se que este programa identifique quantos dias já passaram de um determinado ano, quando o utilizador introduz uma desterminada data(dia,mês e ano). Exemplo: O utilizador introduz: dia:20 mês:2 ano: 2016, O programa irá devolver: dia 51 do ano de 2016 Ou seja 31 dias de Janeiro mais 20 de Fevereiro. Não esquecer que os anos bisextos(4 em 4 anos) são multiplos de 4 ( Ano%4==0), têm 29 dias em Fevereiro. Boa Sorte */ int CalculateMissingDays(int missingMonths, int missingDays){ int i; for(i = 0; i < missingMonths; i++){ if(i % 2 == 1 && i != 9 && i != 11 || i == 8 || i == 10 || i == 12) { missingDays += 31; } else { missingDays += 30; } } return missingDays; } int main() { int day; int month; int year; int missingDays = 0; int missingMonths = 0; int dayLimit = 0; do{ printf("\nInsert a day, month and year."); printf("--->"); scanf("%d%d%d",&day,&month,&year); while(month >= 13 || month <= 0){ printf("\nInsert a month between 1 and 12"); printf("--->"); scanf("%d",&month); } missingMonths = month; while(day >= 32 || day <= 0){ printf("\nInsert a day between 1 and 29"); printf("--->"); scanf("%d",&day); } if (year %4 == 0){ if (month == 2){ dayLimit = 29; while (day >= 30 && day <= 0){ printf("\nInsert a day between 1 and 29"); printf("--->"); scanf("%d",&day); } } } else { if (month == 2){ dayLimit = 28; while (day >= 29 && day <= 0){ printf("\nInsert a day between 1 and 28"); printf("--->"); scanf("%d",&day); } } } missingDays = CalculateMissingDays(missingMonths, (day-dayLimit)); printf("Missing Days = %d", (missingDays-1)); }while(missingDays = 0); return 0; }
3.59375
4
2024-11-18T20:48:54.285918+00:00
2021-01-04T22:02:42
219d4311e5fe032cd90aaf6460c9325cd730485b
{ "blob_id": "219d4311e5fe032cd90aaf6460c9325cd730485b", "branch_name": "refs/heads/main", "committer_date": "2021-01-04T22:02:42", "content_id": "dbe96d57af7fa8884a9534744c861f5fc675728c", "detected_licenses": [ "MIT" ], "directory_id": "a601aa934df17ec4b74d7c23d8620532ed9213b2", "extension": "c", "filename": "hello.c", "fork_events_count": 0, "gha_created_at": "2021-01-04T20:41:41", "gha_event_created_at": "2021-01-04T20:54:57", "gha_language": null, "gha_license_id": "MIT", "github_id": 326802719, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 648, "license": "MIT", "license_type": "permissive", "path": "/src/hello.c", "provenance": "stackv2-0102.json.gz:86157", "repo_name": "mcufari/MultiCoreC", "revision_date": "2021-01-04T22:02:42", "revision_id": "06259cf31e7656164343efbac8feb56daa005049", "snapshot_id": "b5b51d49a81a66b1253a9eacf6a8dad73a5874af", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mcufari/MultiCoreC/06259cf31e7656164343efbac8feb56daa005049/src/hello.c", "visit_date": "2023-02-13T09:45:15.069716" }
stackv2
/* * A simple Hello World From Thread 0 Program * * Author: Matt Cufari * Version: 1.0.0 * Date Created: Jan 4 2021 * Date Last Modified: Jan 4 2021 * * */ #include <stdio.h> #include <omp.h> int main(){ #pragma omp parallel //Create a parallel block { int ID = omp_get_thread_num(); //Set the ID printf("Hello (%d) ", ID); //Hello (ID) printf("world (%d) \n", ID); //World (ID) /* * The output of this program will look nonsenical because threads do not execute * one-after another * * How do we modify this program so that the threads aren't racing against one another? */ // Mutual Exlcusion! } return 0; }
2.96875
3
2024-11-18T20:48:54.550872+00:00
2020-01-25T01:13:36
665b56e4d51cf58fd53c92cf1dba1d1c8a903115
{ "blob_id": "665b56e4d51cf58fd53c92cf1dba1d1c8a903115", "branch_name": "refs/heads/master", "committer_date": "2020-01-25T01:13:36", "content_id": "7663e1906053c5a90ceefd927547366f25dc55a8", "detected_licenses": [ "MIT" ], "directory_id": "282253bac9119ab5f0014fd3a9cfb1a75409df4b", "extension": "h", "filename": "stdio.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 228566347, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1010, "license": "MIT", "license_type": "permissive", "path": "/STL/stdio.h", "provenance": "stackv2-0102.json.gz:86544", "repo_name": "coltersnyder/Pi-EMUOS", "revision_date": "2020-01-25T01:13:36", "revision_id": "3190df47261db3f3ad725561dbada7407823ed74", "snapshot_id": "a1b2583d5f889383593af2c3f4f951750491b01d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/coltersnyder/Pi-EMUOS/3190df47261db3f3ad725561dbada7407823ed74/STL/stdio.h", "visit_date": "2020-11-25T07:57:59.661284" }
stackv2
#ifndef _STDIO_H #define _STDIO_H 1 #include "../kernel.h" #define BUFSIZ 1024 #define EOF (-1) #define FILENAME_MAX #define FOPEN_MAX #define L_tmpnam #define NULL #define TMP_MAX #define _IOFBF #define _IOLBF #define _IONBF #define SEEK_CUR #define SEEK_END #define SEEK_SET typedef struct FILE{ }; typedef struct fpos_t{ }; typedef struct size_t{ }; //File Opporations int remove ( const char * filename ); int rename ( const char * oldname, const char * newname); FILE * tmpfile ( void ); char * tmpnam ( char * str ); //File Access int fclose ( FILE * stream ); int fflush ( FILE * stream ); FILE * fopen ( const char * filename, const char * mode ); FILE * freopen ( const char * filename, const char * mode, FILE * stream); void setbuf ( FILE * stream, char * buffer); int setvbuf ( FILE * stream, char * buffer, int mode, size_t size); //Formated input/output int fgetc ( FILE * stream ); int fscanf ( FILE * stream, const char * format, ...); int printf ( const char * format, ...); #endif
2.15625
2
2024-11-18T20:48:54.680734+00:00
2014-12-12T21:39:46
f4a4a4bb2d9a4b0fb1f9d14401559520eb165b9f
{ "blob_id": "f4a4a4bb2d9a4b0fb1f9d14401559520eb165b9f", "branch_name": "refs/heads/master", "committer_date": "2014-12-12T21:39:46", "content_id": "69a061d1221af918048f393c2b751a674199f6ec", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "58405ac2e9cdc4b5e79f0dce4ac2c8a79b52c536", "extension": "h", "filename": "udp46.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 19307949, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1922, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/udp46.h", "provenance": "stackv2-0102.json.gz:86801", "repo_name": "fingon/minimalist-pcproxy", "revision_date": "2014-12-12T21:39:46", "revision_id": "2d6d1b0b0a3b79a9b4a9b0a7606a84600a967bcb", "snapshot_id": "3fc76387b773afd37063a8bdf9cdc03bc390790d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/fingon/minimalist-pcproxy/2d6d1b0b0a3b79a9b4a9b0a7606a84600a967bcb/udp46.h", "visit_date": "2021-01-19T09:28:13.986225" }
stackv2
/* * $Id: udp46.h $ * * Author: Markus Stenberg <markus stenberg@iki.fi> * * Copyright (c) 2014 cisco Systems, Inc. * * Created: Thu May 15 12:16:06 2014 mstenber * Last modified: Thu May 15 13:55:33 2014 mstenber * Edit time: 22 min * */ #ifndef UDP46_H #define UDP46_H #include <stdint.h> #include <sys/socket.h> #include <netinet/in.h> /** * * As dual-stack IPv6 (listening) UDP sockets are broken on many * platforms, this module provides an abstraction of a socket that is * actually _two_ sockets underneath: IPv4-only one, and IPv6-only * one, with convenience APIs for sending and receiving packets. * * All structures coming in and out are sockaddr_in6's. sockaddr_in * (and in_addr) are hidden. */ typedef struct udp46_t *udp46; /** * Create/open a new socket. * * Effectively combination of socket(), bind(). * * Port is the port it is bound to, or 0 if left up to library. (The * library will get same port # for both IPv4 and IPv6 sockets it * creates underneath). */ udp46 udp46_create(uint16_t port); /** * Get the socket fds. */ void udp46_get_fds(udp46 s, int *fd1, int *fd2); /** * Receive a packet. * * Equivalent of socket type specific recvmsg() + magic to handle * source and destination addresses. -1 is returned if no packet * available. src and dst are optional. */ ssize_t udp46_recv(udp46 s, struct sockaddr_in6 *src, struct sockaddr_in6 *dst, void *buf, size_t buf_size); /** * Send a packet. * * Equivalent of socket type specific sendmsg() + magic to handle * source and destination addresses. **/ int udp46_send_iovec(udp46 s, const struct sockaddr_in6 *src, const struct sockaddr_in6 *dst, struct iovec *iov, int iov_len); /** * Destroy/close a socket. */ void udp46_destroy(udp46 s); #endif /* UDP46_H */
2.1875
2
2024-11-18T20:48:54.747087+00:00
2022-08-27T10:26:13
d0c6a5725c1d42931b96416abf7514b14ffd2158
{ "blob_id": "d0c6a5725c1d42931b96416abf7514b14ffd2158", "branch_name": "refs/heads/master", "committer_date": "2022-08-27T10:26:13", "content_id": "b4938dc9d4f21c3499ca9b6c7f4945c50a06abcf", "detected_licenses": [ "MIT" ], "directory_id": "1fe02fddae8ae2db76f9d3d7c0d9f782050457cf", "extension": "h", "filename": "fingerprintio.h", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 224826387, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1958, "license": "MIT", "license_type": "permissive", "path": "/fingerprintio.h", "provenance": "stackv2-0102.json.gz:86933", "repo_name": "gurushida/mnemophonix", "revision_date": "2022-08-27T10:26:13", "revision_id": "99c9c1ac87c14605e4976135412936ed83b94db4", "snapshot_id": "ee658a789e4d51a0f8106e17f2f703da585051fc", "src_encoding": "UTF-8", "star_events_count": 24, "url": "https://raw.githubusercontent.com/gurushida/mnemophonix/99c9c1ac87c14605e4976135412936ed83b94db4/fingerprintio.h", "visit_date": "2022-09-22T06:31:21.867177" }
stackv2
#ifndef _FINGERPRINTIO_H #define _FINGERPRINTIO_H #include <stdio.h> #include "errors.h" #include "minhash.h" /** * This structure represents one entry in a fingerprint database. */ struct index_entry { char* filename; char* artist; char* track_title; char* album_title; struct signatures* signatures; }; /** * This structure represents a fingerprint database. */ struct index { // Then number of entries unsigned int n_entries; // The entries struct index_entry** entries; }; /** * Saves the given signature to the given file using the following text format. * A fingerprint entry starts with 5 lines of text: * - name of the original .wav file * - artist (may be empty) * - track title (may be empty) * - album title (may be empty) * - number of hashes * * This is followed by one line per hash, where each hash line consists of the hexadecimal representation * of the 100 bytes that constitute a hash. * * @param f The file to save to * @param fingerprint The fingerprint to save * @param wavname The name of the .wav file that was fingerprinted * @param artist If not NULL, the artist name to save * @param track_title If not NULL, the track title to save * @param album_title If not NULL, the album title to save */ void save(FILE* f, struct signatures* fingerprint, const char* wavname, const char* artist, const char* track_title, const char* album_title); /** * Loads the index contained in the given file. * * @param filename The file to load * @param index Where to store the results * @return SUCCESS on success * MEMORY_ERROR in case of memory allocation error * CANNOT_READ_FILE if the file cannot be read * DECODING_ERROR if the file cannot be parsed correctly */ int read_index(const char* filename, struct index* *index); /** * Frees all the memory associated to the given index. */ void free_index(struct index* index); #endif
2.578125
3
2024-11-18T20:48:54.952521+00:00
2015-02-05T07:52:35
730e9c42f41c0a37abdfc57e9924190090db9628
{ "blob_id": "730e9c42f41c0a37abdfc57e9924190090db9628", "branch_name": "refs/heads/master", "committer_date": "2015-02-05T07:52:35", "content_id": "8849fd04cb6b0fe089f5db039761d4191c72989f", "detected_licenses": [ "MIT" ], "directory_id": "86dfc62b5e077957691c126dd812056c0465a456", "extension": "h", "filename": "xfile.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": 10954, "license": "MIT", "license_type": "permissive", "path": "/extlib/benz/include/picrin/xfile.h", "provenance": "stackv2-0102.json.gz:87192", "repo_name": "yahkawp/picrin", "revision_date": "2015-02-05T07:52:35", "revision_id": "e7946902c148fbbe8bc8e531a70eadd3217eb576", "snapshot_id": "32fd3877807451a11226eca8f9f1d056a9244cd7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yahkawp/picrin/e7946902c148fbbe8bc8e531a70eadd3217eb576/extlib/benz/include/picrin/xfile.h", "visit_date": "2021-01-18T18:48:29.346497" }
stackv2
#ifndef XFILE_H #define XFILE_H #if defined(__cplusplus) extern "C" { #endif typedef struct { int ungot; int flags; /* operators */ struct { void *cookie; int (*read)(void *, char *, int); int (*write)(void *, const char *, int); long (*seek)(void *, long, int); int (*flush)(void *); int (*close)(void *); } vtable; } xFILE; /* generic file constructor */ PIC_INLINE xFILE *xfunopen(void *cookie, int (*read)(void *, char *, int), int (*write)(void *, const char *, int), long (*seek)(void *, long, int), int (*flush)(void *), int (*close)(void *)); /* resource aquisition */ PIC_INLINE xFILE *xfpopen(FILE *); PIC_INLINE xFILE *xmopen(); PIC_INLINE xFILE *xfopen(const char *, const char *); PIC_INLINE int xfclose(xFILE *); /* buffer management */ PIC_INLINE int xfflush(xFILE *); /* direct IO with buffering */ PIC_INLINE size_t xfread(void *, size_t, size_t, xFILE *); PIC_INLINE size_t xfwrite(const void *, size_t, size_t, xFILE *); /* indicator positioning */ PIC_INLINE long xfseek(xFILE *, long offset, int whence); PIC_INLINE long xftell(xFILE *); PIC_INLINE void xrewind(xFILE *); /* stream status */ PIC_INLINE void xclearerr(xFILE *); PIC_INLINE int xfeof(xFILE *); PIC_INLINE int xferror(xFILE *); /* character IO */ PIC_INLINE int xfgetc(xFILE *); PIC_INLINE char *xfgets(char *, int, xFILE *); PIC_INLINE int xfputc(int, xFILE *); PIC_INLINE int xfputs(const char *, xFILE *); PIC_INLINE int xgetc(xFILE *); PIC_INLINE int xgetchar(void); PIC_INLINE int xputc(int, xFILE *); PIC_INLINE int xputchar(int); PIC_INLINE int xputs(const char *); PIC_INLINE int xungetc(int, xFILE *); /* formatted I/O */ PIC_INLINE int xprintf(const char *, ...); PIC_INLINE int xfprintf(xFILE *, const char *, ...); PIC_INLINE int xvfprintf(xFILE *, const char *, va_list); /* standard I/O */ #define xstdin (xstdin_()) #define xstdout (xstdout_()) #define xstderr (xstderr_()) /* private */ #define XF_EOF 1 #define XF_ERR 2 PIC_INLINE xFILE * xfunopen(void *cookie, int (*read)(void *, char *, int), int (*write)(void *, const char *, int), long (*seek)(void *, long, int), int (*flush)(void *), int (*close)(void *)) { xFILE *file; file = (xFILE *)malloc(sizeof(xFILE)); if (! file) { return NULL; } file->ungot = -1; file->flags = 0; /* set vtable */ file->vtable.cookie = cookie; file->vtable.read = read; file->vtable.write = write; file->vtable.seek = seek; file->vtable.flush = flush; file->vtable.close = close; return file; } /* * Derieved xFILE Classes */ PIC_INLINE int xf_file_read(void *cookie, char *ptr, int size) { FILE *file = cookie; int r; r = (int)fread(ptr, 1, (size_t)size, file); if (r < size && ferror(file)) { return -1; } if (r == 0 && feof(file)) { clearerr(file); } return r; } PIC_INLINE int xf_file_write(void *cookie, const char *ptr, int size) { FILE *file = cookie; int r; r = (int)fwrite(ptr, 1, (size_t)size, file); if (r < size) { return -1; } return r; } PIC_INLINE long xf_file_seek(void *cookie, long pos, int whence) { return fseek(cookie, pos, whence); } PIC_INLINE int xf_file_flush(void *cookie) { return fflush(cookie); } PIC_INLINE int xf_file_close(void *cookie) { return fclose(cookie); } PIC_INLINE xFILE * xfpopen(FILE *fp) { xFILE *file; file = xfunopen(fp, xf_file_read, xf_file_write, xf_file_seek, xf_file_flush, xf_file_close); if (! file) { return NULL; } return file; } #define XF_FILE_VTABLE xf_file_read, xf_file_write, xf_file_seek, xf_file_flush, xf_file_close PIC_INLINE xFILE * xstdin_() { static xFILE x = { -1, 0, { NULL, XF_FILE_VTABLE } }; if (! x.vtable.cookie) { x.vtable.cookie = stdin; } return &x; } PIC_INLINE xFILE * xstdout_() { static xFILE x = { -1, 0, { NULL, XF_FILE_VTABLE } }; if (! x.vtable.cookie) { x.vtable.cookie = stdout; } return &x; } PIC_INLINE xFILE * xstderr_() { static xFILE x = { -1, 0, { NULL, XF_FILE_VTABLE } }; if (! x.vtable.cookie) { x.vtable.cookie = stderr; } return &x; } struct xf_membuf { char *buf; long pos, end, capa; }; PIC_INLINE int xf_mem_read(void *cookie, char *ptr, int size) { struct xf_membuf *mem; mem = (struct xf_membuf *)cookie; if (size > (int)(mem->end - mem->pos)) size = (int)(mem->end - mem->pos); memcpy(ptr, mem->buf + mem->pos, size); mem->pos += size; return size; } PIC_INLINE int xf_mem_write(void *cookie, const char *ptr, int size) { struct xf_membuf *mem; mem = (struct xf_membuf *)cookie; if (mem->pos + size >= mem->capa) { mem->capa = (mem->pos + size) * 2; mem->buf = realloc(mem->buf, (size_t)mem->capa); } memcpy(mem->buf + mem->pos, ptr, size); mem->pos += size; if (mem->end < mem->pos) mem->end = mem->pos; return size; } PIC_INLINE long xf_mem_seek(void *cookie, long pos, int whence) { struct xf_membuf *mem; mem = (struct xf_membuf *)cookie; switch (whence) { case SEEK_SET: mem->pos = pos; break; case SEEK_CUR: mem->pos += pos; break; case SEEK_END: mem->pos = mem->end + pos; break; } return mem->pos; } PIC_INLINE int xf_mem_flush(void *cookie) { (void)cookie; return 0; } PIC_INLINE int xf_mem_close(void *cookie) { struct xf_membuf *mem; mem = (struct xf_membuf *)cookie; free(mem->buf); free(mem); return 0; } PIC_INLINE xFILE * xmopen() { struct xf_membuf *mem; mem = (struct xf_membuf *)malloc(sizeof(struct xf_membuf)); mem->buf = (char *)malloc(BUFSIZ); mem->pos = 0; mem->end = 0; mem->capa = BUFSIZ; return xfunopen(mem, xf_mem_read, xf_mem_write, xf_mem_seek, xf_mem_flush, xf_mem_close); } #undef XF_FILE_VTABLE PIC_INLINE xFILE * xfopen(const char *filename, const char *mode) { FILE *fp; xFILE *file; fp = fopen(filename, mode); if (! fp) { return NULL; } file = xfpopen(fp); if (! file) { return NULL; } return file; } PIC_INLINE int xfclose(xFILE *file) { int r; r = file->vtable.close(file->vtable.cookie); if (r == EOF) { return -1; } free(file); return 0; } PIC_INLINE int xfflush(xFILE *file) { return file->vtable.flush(file->vtable.cookie); } PIC_INLINE size_t xfread(void *ptr, size_t block, size_t nitems, xFILE *file) { char cbuf[256], *buf; char *dst = (char *)ptr; size_t i, offset; int n; if (block <= 256) { buf = cbuf; } else { buf = malloc(block); } for (i = 0; i < nitems; ++i) { offset = 0; if (file->ungot != -1 && block > 0) { buf[0] = (char)file->ungot; offset += 1; file->ungot = -1; } while (offset < block) { n = file->vtable.read(file->vtable.cookie, buf + offset, (int)(block - offset)); if (n < 0) { file->flags |= XF_ERR; goto exit; } if (n == 0) { file->flags |= XF_EOF; goto exit; } offset += (unsigned)n; } memcpy(dst, buf, block); dst += block; } exit: if (cbuf != buf) { free(buf); } return i; } PIC_INLINE size_t xfwrite(const void *ptr, size_t block, size_t nitems, xFILE *file) { char *dst = (char *)ptr; size_t i, offset; int n; for (i = 0; i < nitems; ++i) { offset = 0; while (offset < block) { n = file->vtable.write(file->vtable.cookie, dst + offset, (int)(block - offset)); if (n < 0) { file->flags |= XF_ERR; goto exit; } offset += (unsigned)n; } dst += block; } exit: return i; } PIC_INLINE long xfseek(xFILE *file, long offset, int whence) { file->ungot = -1; return file->vtable.seek(file->vtable.cookie, offset, whence); } PIC_INLINE long xftell(xFILE *file) { return xfseek(file, 0, SEEK_CUR); } PIC_INLINE void xrewind(xFILE *file) { xfseek(file, 0, SEEK_SET); } PIC_INLINE void xclearerr(xFILE *file) { file->flags = 0; } PIC_INLINE int xfeof(xFILE *file) { return file->flags & XF_EOF; } PIC_INLINE int xferror(xFILE *file) { return file->flags & XF_ERR; } PIC_INLINE int xfgetc(xFILE *file) { char buf[1]; xfread(buf, 1, 1, file); if (xfeof(file) || xferror(file)) { return EOF; } return buf[0]; } PIC_INLINE int xgetc(xFILE *file) { return xfgetc(file); } PIC_INLINE char * xfgets(char *str, int size, xFILE *file) { int c = EOF, i; for (i = 0; i < size - 1 && c != '\n'; ++i) { if ((c = xfgetc(file)) == EOF) { break; } str[i] = (char)c; } if (i == 0 && c == EOF) { return NULL; } if (xferror(file)) { return NULL; } str[i] = '\0'; return str; } PIC_INLINE int xungetc(int c, xFILE *file) { file->ungot = c; if (c != EOF) { file->flags &= ~XF_EOF; } return c; } PIC_INLINE int xgetchar(void) { return xfgetc(xstdin); } PIC_INLINE int xfputc(int c, xFILE *file) { char buf[1]; buf[0] = (char)c; xfwrite(buf, 1, 1, file); if (xferror(file)) { return EOF; } return buf[0]; } PIC_INLINE int xputc(int c, xFILE *file) { return xfputc(c, file); } PIC_INLINE int xputchar(int c) { return xfputc(c, xstdout); } PIC_INLINE int xfputs(const char *str, xFILE *file) { size_t len; len = strlen(str); xfwrite(str, len, 1, file); if (xferror(file)) { return EOF; } return 0; } PIC_INLINE int xputs(const char *s) { return xfputs(s, xstdout); } PIC_INLINE int xprintf(const char *fmt, ...) { va_list ap; int n; va_start(ap, fmt); n = xvfprintf(xstdout, fmt, ap); va_end(ap); return n; } PIC_INLINE int xfprintf(xFILE *stream, const char *fmt, ...) { va_list ap; int n; va_start(ap, fmt); n = xvfprintf(stream, fmt, ap); va_end(ap); return n; } static void xfile_printint(xFILE *stream, long x, int base) { static char digits[] = "0123456789abcdef"; char buf[20]; int i, neg; neg = 0; if (x < 0) { neg = 1; x = -x; } i = 0; do { buf[i++] = digits[x % base]; } while ((x /= base) != 0); if (neg) { buf[i++] = '-'; } while (i-- > 0) { xputc(buf[i], stream); } } PIC_INLINE int xvfprintf(xFILE *stream, const char *fmt, va_list ap) { const char *p; char *sval; int ival; double dval; void *vp; long seekr = xftell(stream); for (p = fmt; *p; p++) { if (*p != '%') { xputc(*p, stream); continue; } switch (*++p) { case 'd': case 'i': ival = va_arg(ap, int); xfile_printint(stream, ival, 10); break; case 'f': dval = va_arg(ap, double); xfile_printint(stream, dval, 10); xputc('.', stream); xfile_printint(stream, fabs((dval - (int)dval) * 1e4), 10); break; case 's': sval = va_arg(ap, char*); xfputs(sval, stream); break; case 'p': vp = va_arg(ap, void*); xfputs("0x", stream); xfile_printint(stream, (int)vp, 16); break; default: xputc(*(p-1), stream); break; } } return xftell(stream) - seekr; } #if defined(__cplusplus) } #endif #endif
2.265625
2
2024-11-18T20:48:55.391504+00:00
2019-05-01T18:47:14
dc49a69219d0875ebbcaecbb6408e2b3540a1ae0
{ "blob_id": "dc49a69219d0875ebbcaecbb6408e2b3540a1ae0", "branch_name": "refs/heads/master", "committer_date": "2019-05-01T18:47:14", "content_id": "0868b2dc11abe19c0585f1eec4133adbbdfda458", "detected_licenses": [ "MIT" ], "directory_id": "2f9228199a0259ab3766e6bf6f25609d33c96072", "extension": "h", "filename": "graph.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 168039794, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1425, "license": "MIT", "license_type": "permissive", "path": "/mp6/graph.h", "provenance": "stackv2-0102.json.gz:87450", "repo_name": "Kur1su0/ece2230", "revision_date": "2019-05-01T18:47:14", "revision_id": "8c04a66b64f94143d2cb2ab99b4a274da0404fb0", "snapshot_id": "3d3ba8bbc2543fbd013f4c8f6f619df389642496", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Kur1su0/ece2230/8c04a66b64f94143d2cb2ab99b4a274da0404fb0/mp6/graph.h", "visit_date": "2020-04-19T07:37:43.393015" }
stackv2
/* graph.h * Lab6: Dijkstra. * ECE 2230, Fall 2018 * Zice Wei * C73880993 * Purpose and assumptions: This file contains structures and function prototypes * * * No bugs */ #define TRUE 1 #define FALSE 0 typedef int bool; // Matrix desinged. typedef struct Vertex{ double weight; double distance; double x; double y; //bool confirm; }Vertex; typedef struct graph_t_tag{ int size; Vertex** vertex; }graph_t; typedef struct PathRes{ double dist; int prede; }PathRes; typedef struct confirm_array{ int total; int current; int* confirm; }confirm_array; typedef struct max_cost{ int s; int d; double cost; }max_cost; typedef struct analysis{ int max; int min; double avg; int total; }analysis; //prototype void valid_check(int g, int n, int a, int h, int s, int d); graph_t* construct(int size); void graph_destruct(graph_t* G); void print_col_tag(int size, int curr); void graph_print_array(graph_t* G); void graph_add_edge(graph_t* G, int src, int dest, double weight); void graph_add_distance(graph_t* G, int src, int dest, double distance); PathRes* ShortestPath(graph_t* G, int source); void res_table_print(graph_t* G, PathRes* res, int source); void res_table_destruct(PathRes* res); int res_find_shortest_path(graph_t* G, PathRes* res, int source, int dest); void find_max_dest(graph_t* G); //void find_multi_path(graph_t* G);
2.25
2
2024-11-18T20:48:56.381365+00:00
2021-03-22T10:37:11
06c1f7c2f65bc76d4de288f6f20c09c2fa6e06a6
{ "blob_id": "06c1f7c2f65bc76d4de288f6f20c09c2fa6e06a6", "branch_name": "refs/heads/master", "committer_date": "2021-03-22T10:37:11", "content_id": "41f4bb0849be41aedced8cd3bb9253d889eea33a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e608b98bad20a2496b2698ad0979fa54d7b51498", "extension": "c", "filename": "task3.c", "fork_events_count": 0, "gha_created_at": "2020-09-15T11:04:15", "gha_event_created_at": "2020-12-28T21:49:50", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 295700166, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 869, "license": "Apache-2.0", "license_type": "permissive", "path": "/homework2/task3.c", "provenance": "stackv2-0102.json.gz:87836", "repo_name": "IgorFilimonov/spbu_2020_c_homeworks", "revision_date": "2021-03-22T10:37:11", "revision_id": "4e8aa72d168b760792a61e29a25f60cf36b24821", "snapshot_id": "040477d9ad3d261bdb2a72a15c8a142d578c475d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/IgorFilimonov/spbu_2020_c_homeworks/4e8aa72d168b760792a61e29a25f60cf36b24821/homework2/task3.c", "visit_date": "2023-03-25T22:45:45.706077" }
stackv2
#include "../library/commonUtils/numericOperations.h" #include <stdio.h> #include <stdlib.h> int* readInputData(int* n) { printf("Enter n:\n"); scanf("%d", n); printf("Enter an array:\n"); int* array = (int*)calloc(*n, sizeof(int)); for (int i = 0; i < *n; ++i) scanf("%d", &array[i]); return array; } void printOutput(int* array, int n) { printf("Here is the changed array:\n"); for (int i = 0; i < n; ++i) printf("%d ", array[i]); printf("\n"); } int main() { int n = 0; int* array = readInputData(&n); int indexOfNextZero = n - 1; for (int i = 0; i < indexOfNextZero;) { if (array[i] != 0) { ++i; continue; } swap(&array[i], &array[indexOfNextZero]); --indexOfNextZero; } printOutput(array, n); free(array); return 0; }
3.390625
3
2024-11-18T21:28:17.554672+00:00
2023-07-21T14:01:28
1a22eb9c34a7078618af7c260c50090d698baa17
{ "blob_id": "1a22eb9c34a7078618af7c260c50090d698baa17", "branch_name": "refs/heads/master", "committer_date": "2023-07-21T14:01:28", "content_id": "625865a884b4db1b9b0ea249e429666e7751ea45", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "020ef13aa76bde79e045e170db391f056ea204df", "extension": "c", "filename": "gcm_alt.c", "fork_events_count": 40, "gha_created_at": "2019-11-22T11:53:18", "gha_event_created_at": "2023-09-01T11:11:17", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 223393131, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20027, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/lib/ext/cryptocell-312-runtime/codesafe/src/mbedtls_api/gcm_alt.c", "provenance": "stackv2-0104.json.gz:14728", "repo_name": "zephyrproject-rtos/trusted-firmware-m", "revision_date": "2023-07-21T14:01:28", "revision_id": "bad0696f388d6f713742c5da8dfce426ec17ef20", "snapshot_id": "fb64570748a092034aee0a556abb24f47295d315", "src_encoding": "UTF-8", "star_events_count": 19, "url": "https://raw.githubusercontent.com/zephyrproject-rtos/trusted-firmware-m/bad0696f388d6f713742c5da8dfce426ec17ef20/lib/ext/cryptocell-312-runtime/codesafe/src/mbedtls_api/gcm_alt.c", "visit_date": "2023-08-04T05:41:13.657474" }
stackv2
/* * Copyright (c) 2001-2022, Arm Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ /* * Definition of GCM: * http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf * Recommendation for Block Cipher Modes of Operation: * Galois/Counter Mode (GCM) and GMAC * * The API supports AES-GCM as defined in NIST SP 800-38D. * */ #include "mbedtls/build_info.h" #if defined(MBEDTLS_GCM_C) && defined(MBEDTLS_GCM_ALT) #include "cc_pal_types.h" #include "cc_pal_mem.h" #include "cc_pal_abort.h" #include "cc_common.h" #include "aesgcm_driver.h" #include "mbedtls_common.h" #include "mbedtls/gcm.h" #include "mbedtls/error.h" /*! AES GCM data in maximal size in bytes. */ #define MBEDTLS_AESGCM_DATA_IN_MAX_SIZE_BYTES 0xFFFF // (64KB - 1) /*! AES GCM IV maximal size in bytes. */ #define MBEDTLS_AESGCM_IV_MAX_SIZE_BYTES 0xFFFF // (64KB - 1) /*! AES GCM AAD maximal size in bytes. */ #define MBEDTLS_AESGCM_AAD_MAX_SIZE_BYTES 0xFFFF // (64KB - 1) /*! AES GCM 96 bits size IV. */ #define MBEDTLS_AESGCM_IV_96_BITS_SIZE_BYTES 12 /*! AES GCM Tag size: 4 bytes. */ #define MBEDTLS_AESGCM_TAG_SIZE_4_BYTES 4 /*! AES GCM Tag size: 8 bytes. */ #define MBEDTLS_AESGCM_TAG_SIZE_8_BYTES 8 /*! AES GCM Tag size: 12 bytes. */ #define MBEDTLS_AESGCM_TAG_SIZE_12_BYTES 12 /*! AES GCM Tag size: 13 bytes. */ #define MBEDTLS_AESGCM_TAG_SIZE_13_BYTES 13 /*! AES GCM Tag size: 14 bytes. */ #define MBEDTLS_AESGCM_TAG_SIZE_14_BYTES 14 /*! AES GCM Tag size: 15 bytes. */ #define MBEDTLS_AESGCM_TAG_SIZE_15_BYTES 15 /*! AES GCM Tag size: 16 bytes. */ #define MBEDTLS_AESGCM_TAG_SIZE_16_BYTES 16 /* * Initialize a context */ void mbedtls_gcm_init(mbedtls_gcm_context *ctx) { if (NULL == ctx) { CC_PalAbort("!!!!GCM context is NULL!!!\n"); } if (sizeof(mbedtls_gcm_context) < sizeof(AesGcmContext_t)) { CC_PalAbort("!!!!GCM context sizes mismatch!!!\n"); } mbedtls_zeroize_internal(ctx, sizeof(mbedtls_gcm_context)); } int mbedtls_gcm_setkey(mbedtls_gcm_context *ctx, mbedtls_cipher_id_t cipher, const unsigned char *key, unsigned int keybits) { AesGcmContext_t *aes_gcm_ctx ; if (ctx == NULL || key == NULL) { CC_PAL_LOG_ERR("Null pointer, ctx or key are NULL\n"); return MBEDTLS_ERR_GCM_BAD_INPUT; } if (cipher != MBEDTLS_CIPHER_ID_AES) { /* No real use case for GCM other then AES*/ CC_PAL_LOG_ERR("Only AES cipher id is supported\n"); return MBEDTLS_ERR_GCM_BAD_INPUT; } aes_gcm_ctx = (AesGcmContext_t *)ctx; switch (keybits) { case 128: aes_gcm_ctx->keySizeId = KEY_SIZE_128_BIT; break; case 192: aes_gcm_ctx->keySizeId = KEY_SIZE_192_BIT; break; case 256: aes_gcm_ctx->keySizeId = KEY_SIZE_256_BIT; break; default: return MBEDTLS_ERR_GCM_BAD_INPUT; } /* Copy user key to context */ CC_PalMemCopy(aes_gcm_ctx->keyBuf, key, (keybits/8)); return(0); } /* * Free context */ void mbedtls_gcm_free(mbedtls_gcm_context *ctx) { mbedtls_zeroize_internal(ctx, sizeof(mbedtls_gcm_context)); } static int gcm_calc_h(mbedtls_gcm_context *ctx) { AesGcmContext_t *pAesGcmCtx = NULL; drvError_t rc; CCBuffInfo_t inBuffInfo; CCBuffInfo_t outBuffInfo; /* set pointer to user context */ pAesGcmCtx = (AesGcmContext_t *)ctx; /* Set process mode to 'CalcH' */ pAesGcmCtx->processMode = DRV_AESGCM_Process_CalcH; /* set data buffers structures */ rc = SetDataBuffersInfo((uint8_t*)(pAesGcmCtx->tempBuf), CC_AESGCM_GHASH_DIGEST_SIZE_BYTES, &inBuffInfo, (uint8_t*)(pAesGcmCtx->H), AES_128_BIT_KEY_SIZE, &outBuffInfo); if (rc != 0) { CC_PAL_LOG_ERR("illegal data buffers\n"); return MBEDTLS_ERR_GCM_AUTH_FAILED; } /* Calculate H */ rc = ProcessAesGcm(pAesGcmCtx, &inBuffInfo, &outBuffInfo, CC_AES_BLOCK_SIZE_IN_BYTES); if (rc != AES_DRV_OK) { CC_PAL_LOG_ERR("calculating H failed with error code %d\n", rc); return MBEDTLS_ERR_GCM_AUTH_FAILED; } return (0); } static int gcm_init(mbedtls_gcm_context *ctx, cryptoDirection_t encryptDecryptFlag, const uint8_t* pIv, size_t ivSize, const uint8_t* pAad, size_t aadSize, const uint8_t* pDataIn, size_t dataSize, uint8_t* pDataOut, const uint8_t* pTag, size_t tagSize) { AesGcmContext_t *pAesGcmCtx = NULL; drvError_t rc; /* Check the Encrypt / Decrypt flag validity */ if (CRYPTO_DIRECTION_NUM_OF_ENC_MODES <= encryptDecryptFlag) { return MBEDTLS_ERR_GCM_BAD_INPUT; } /* Check the data in size validity */ if (MBEDTLS_AESGCM_DATA_IN_MAX_SIZE_BYTES < dataSize) { return MBEDTLS_ERR_GCM_BAD_INPUT; } if (0 != dataSize) { /* Check dataIn pointer */ if (NULL == pDataIn) { return MBEDTLS_ERR_GCM_BAD_INPUT; } /* Check dataOut pointer */ if (NULL == pDataOut) { return MBEDTLS_ERR_GCM_BAD_INPUT; } } /* Check the IV size validity */ if ((MBEDTLS_AESGCM_IV_MAX_SIZE_BYTES < ivSize) || (0 == ivSize)) { return MBEDTLS_ERR_GCM_BAD_INPUT; } /* Check iv pointer */ if (NULL == pIv) { return MBEDTLS_ERR_GCM_BAD_INPUT; } /* Check the AAD size validity */ if (MBEDTLS_AESGCM_AAD_MAX_SIZE_BYTES < aadSize) { return MBEDTLS_ERR_GCM_BAD_INPUT; } /* Check aad pointer */ if ((NULL == pAad) && (aadSize != 0)) { return MBEDTLS_ERR_GCM_BAD_INPUT; } /* Check the Tag size validity */ if ((MBEDTLS_AESGCM_TAG_SIZE_4_BYTES != tagSize) && (MBEDTLS_AESGCM_TAG_SIZE_8_BYTES != tagSize) && (MBEDTLS_AESGCM_TAG_SIZE_12_BYTES != tagSize) && (MBEDTLS_AESGCM_TAG_SIZE_13_BYTES != tagSize) && (MBEDTLS_AESGCM_TAG_SIZE_14_BYTES != tagSize) && (MBEDTLS_AESGCM_TAG_SIZE_15_BYTES != tagSize) && (MBEDTLS_AESGCM_TAG_SIZE_16_BYTES != tagSize)) { return MBEDTLS_ERR_GCM_BAD_INPUT; } /* Check Tag pointer */ if (NULL == pTag) { return MBEDTLS_ERR_GCM_BAD_INPUT; } /* set pointer to user context */ pAesGcmCtx = (AesGcmContext_t *)ctx; /* Set direction of operation: enc./dec. */ pAesGcmCtx->dir = MBEDTLS_2_DRIVER_DIRECTION(encryptDecryptFlag); pAesGcmCtx->dataSize = dataSize; pAesGcmCtx->ivSize = ivSize; pAesGcmCtx->aadSize = aadSize; pAesGcmCtx->tagSize = tagSize; /******************************************************/ /*** Calculate H ***/ /******************************************************/ rc = gcm_calc_h(ctx); if (rc != AES_DRV_OK) { CC_PAL_LOG_ERR("calculating H failed with error code %d\n", rc); return MBEDTLS_ERR_GCM_AUTH_FAILED; } return 0; } static int gcm_process_j0(mbedtls_gcm_context *ctx, const uint8_t* pIv) { AesGcmContext_t *pAesGcmCtx = NULL; drvError_t rc; CCBuffInfo_t inBuffInfo; CCBuffInfo_t outBuffInfo; /* set pointer to user context */ pAesGcmCtx = (AesGcmContext_t *)ctx; if (MBEDTLS_AESGCM_IV_96_BITS_SIZE_BYTES == pAesGcmCtx->ivSize) { // Concatenate IV||0(31)||1 CC_PalMemCopy(pAesGcmCtx->J0, pIv, MBEDTLS_AESGCM_IV_96_BITS_SIZE_BYTES); pAesGcmCtx->J0[3] = SWAP_ENDIAN(0x00000001); } else { /***********************************************/ /* Calculate GHASH over the first phase buffer */ /***********************************************/ /* Set process mode to 'CalcJ0' */ pAesGcmCtx->processMode = DRV_AESGCM_Process_CalcJ0_FirstPhase; /* set data buffers structures */ rc = SetDataBuffersInfo(pIv, pAesGcmCtx->ivSize, &inBuffInfo, NULL, 0, &outBuffInfo); if (rc != 0) { CC_PAL_LOG_ERR("illegal data buffers\n"); return MBEDTLS_ERR_GCM_AUTH_FAILED; } /* Calculate J0 - First phase */ rc = ProcessAesGcm(pAesGcmCtx, &inBuffInfo, &outBuffInfo, pAesGcmCtx->ivSize); if (rc != AES_DRV_OK) { CC_PAL_LOG_ERR("calculating J0 (phase 1) failed with error code 0x%X\n", rc); return MBEDTLS_ERR_GCM_AUTH_FAILED; } /*********************************************/ /* Build & Calculate the second phase buffer */ /*********************************************/ CC_PalMemSetZero(pAesGcmCtx->tempBuf, sizeof(pAesGcmCtx->tempBuf)); pAesGcmCtx->tempBuf[3] = (pAesGcmCtx->ivSize << 3) & BITMASK(CC_BITS_IN_32BIT_WORD); pAesGcmCtx->tempBuf[3] = SWAP_ENDIAN(pAesGcmCtx->tempBuf[3]); /* Set process mode to 'CalcJ0' */ pAesGcmCtx->processMode = DRV_AESGCM_Process_CalcJ0_SecondPhase; /* set data buffers structures */ rc = SetDataBuffersInfo((uint8_t*)(pAesGcmCtx->tempBuf), CC_AESGCM_GHASH_DIGEST_SIZE_BYTES, &inBuffInfo, NULL, 0, &outBuffInfo); if (rc != 0) { CC_PAL_LOG_ERR("illegal data buffers\n"); return MBEDTLS_ERR_GCM_AUTH_FAILED; } /* Calculate J0 - Second phase */ rc = ProcessAesGcm(pAesGcmCtx, &inBuffInfo, &outBuffInfo, CC_AESGCM_GHASH_DIGEST_SIZE_BYTES); if (rc != AES_DRV_OK) { CC_PAL_LOG_ERR("calculating J0 (phase 2) failed with error code %d\n", rc); return MBEDTLS_ERR_GCM_AUTH_FAILED; } } return 0; } static int gcm_process_aad(mbedtls_gcm_context *ctx, const uint8_t* pAad) { AesGcmContext_t *pAesGcmCtx = NULL; drvError_t rc = 0; CCBuffInfo_t inBuffInfo; CCBuffInfo_t outBuffInfo; /* set pointer to user context */ pAesGcmCtx = (AesGcmContext_t *)ctx; /* Clear Ghash result buffer */ CC_PalMemSetZero(pAesGcmCtx->ghashResBuf, sizeof(pAesGcmCtx->ghashResBuf)); if (0 == pAesGcmCtx->aadSize) { return rc; } /* Set process mode to 'Process_A' */ pAesGcmCtx->processMode = DRV_AESGCM_Process_A; /* set data buffers structures */ rc = SetDataBuffersInfo(pAad, pAesGcmCtx->aadSize, &inBuffInfo, NULL, 0, &outBuffInfo); if (rc != 0) { CC_PAL_LOG_ERR("illegal data buffers\n"); return MBEDTLS_ERR_GCM_AUTH_FAILED; } /* Calculate GHASH(A) */ rc = ProcessAesGcm(pAesGcmCtx, &inBuffInfo, &outBuffInfo, pAesGcmCtx->aadSize); if (rc != AES_DRV_OK) { CC_PAL_LOG_ERR("processing AAD failed with error code %d\n", rc); return MBEDTLS_ERR_GCM_AUTH_FAILED; } return 0; } static int gcm_process_cipher(mbedtls_gcm_context *ctx, const uint8_t* pTextDataIn, uint8_t* pTextDataOut) { AesGcmContext_t *pAesGcmCtx = NULL; drvError_t rc; CCBuffInfo_t inBuffInfo; CCBuffInfo_t outBuffInfo; /* set pointer to user context */ pAesGcmCtx = (AesGcmContext_t *)ctx; /* Must NOT perform in this case */ if (0 == pAesGcmCtx->dataSize) { return 0; } /* Set process mode to 'Process_DataIn' */ pAesGcmCtx->processMode = DRV_AESGCM_Process_DataIn; /* set data buffers structures */ rc = SetDataBuffersInfo(pTextDataIn, pAesGcmCtx->dataSize, &inBuffInfo, pTextDataOut, pAesGcmCtx->dataSize, &outBuffInfo); if (rc != 0) { CC_PAL_LOG_ERR("illegal data buffers\n"); return MBEDTLS_ERR_GCM_AUTH_FAILED; } rc = ProcessAesGcm(pAesGcmCtx, &inBuffInfo, &outBuffInfo, pAesGcmCtx->dataSize); if (rc != AES_DRV_OK) { CC_PAL_LOG_ERR("processing cipher failed with error code %d\n", rc); return MBEDTLS_ERR_GCM_AUTH_FAILED; } return 0; } static int gcm_process_lenA_lenC(mbedtls_gcm_context *ctx) { AesGcmContext_t *pAesGcmCtx = NULL; drvError_t rc; CCBuffInfo_t inBuffInfo; CCBuffInfo_t outBuffInfo; /* set pointer to user context */ pAesGcmCtx = (AesGcmContext_t *)ctx; /* Build buffer */ pAesGcmCtx->tempBuf[1] = (pAesGcmCtx->aadSize << 3) & BITMASK(CC_BITS_IN_32BIT_WORD); pAesGcmCtx->tempBuf[1] = SWAP_ENDIAN(pAesGcmCtx->tempBuf[1]); pAesGcmCtx->tempBuf[0] = 0; pAesGcmCtx->tempBuf[3] = (pAesGcmCtx->dataSize << 3) & BITMASK(CC_BITS_IN_32BIT_WORD); pAesGcmCtx->tempBuf[3] = SWAP_ENDIAN(pAesGcmCtx->tempBuf[3]); pAesGcmCtx->tempBuf[2] = 0; /* Set process mode to 'Process_LenA_LenC' */ pAesGcmCtx->processMode = DRV_AESGCM_Process_LenA_LenC; /* set data buffers structures */ rc = SetDataBuffersInfo((uint8_t*)(pAesGcmCtx->tempBuf), CC_AESGCM_GHASH_DIGEST_SIZE_BYTES, &inBuffInfo, NULL, 0, &outBuffInfo); if (rc != 0) { CC_PAL_LOG_ERR("illegal data buffers\n"); return MBEDTLS_ERR_GCM_AUTH_FAILED; } /* Calculate GHASH(LenA || LenC) */ rc = ProcessAesGcm(pAesGcmCtx, &inBuffInfo, &outBuffInfo, CC_AESGCM_GHASH_DIGEST_SIZE_BYTES); if (rc != AES_DRV_OK) { CC_PAL_LOG_ERR("processing Lengths of AAD and Cipher failed with error code %d\n", rc); return MBEDTLS_ERR_GCM_AUTH_FAILED; } return 0; } static int gcm_finish(mbedtls_gcm_context *ctx, uint8_t* pTag) { AesGcmContext_t *pAesGcmCtx = NULL; int rc; CCBuffInfo_t inBuffInfo; CCBuffInfo_t outBuffInfo; /* set pointer to user context */ pAesGcmCtx = (AesGcmContext_t *)ctx; /* Set process mode to 'Process_GctrFinal' */ pAesGcmCtx->processMode = DRV_AESGCM_Process_GctrFinal; /* set data buffers structures */ rc = SetDataBuffersInfo((uint8_t*)(pAesGcmCtx->tempBuf), CC_AESGCM_GHASH_DIGEST_SIZE_BYTES, &inBuffInfo, pAesGcmCtx->preTagBuf, CC_AESGCM_GHASH_DIGEST_SIZE_BYTES, &outBuffInfo); if (rc != 0) { CC_PAL_LOG_ERR("illegal data buffers\n"); return MBEDTLS_ERR_GCM_AUTH_FAILED; } /* Calculate Encrypt and Calc. Tag */ rc = ProcessAesGcm(pAesGcmCtx, &inBuffInfo, &outBuffInfo, CC_AESGCM_GHASH_DIGEST_SIZE_BYTES); if (rc != AES_DRV_OK) { CC_PAL_LOG_ERR("Finish operation failed with error code %d\n", rc); return MBEDTLS_ERR_GCM_AUTH_FAILED; } if (CRYPTO_DIRECTION_ENCRYPT == pAesGcmCtx->dir) { CC_PalMemCopy(pTag, pAesGcmCtx->preTagBuf, pAesGcmCtx->tagSize); rc = 0; } else { if (0 == CC_PalMemCmp(pAesGcmCtx->preTagBuf, pTag, pAesGcmCtx->tagSize)) { rc = 0; } else { rc = MBEDTLS_ERR_GCM_AUTH_FAILED; } } return rc; } static int gcm_crypt_and_tag(mbedtls_gcm_context *ctx, int mode, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *aad, size_t aad_len, const unsigned char *input, unsigned char *output, size_t tag_len, unsigned char *tag) { AesGcmContext_t *pAesGcmCtx = NULL; int rc; /* check for user context */ if (NULL == ctx) { return MBEDTLS_ERR_GCM_BAD_INPUT; } /* Aes-GCM Initialization function */ rc = gcm_init(ctx, (cryptoDirection_t)mode, iv, iv_len, aad, aad_len, input, length, output, tag, tag_len); if (0 != rc) { goto gcm_crypt_and_tag_END; } /* Aes-GCM Process J0 function */ rc = gcm_process_j0(ctx, iv); if (0 != rc) { goto gcm_crypt_and_tag_END; } /* Aes-GCM Process AAD function */ rc = gcm_process_aad(ctx, aad); if (0 != rc) { goto gcm_crypt_and_tag_END; } /* Aes-GCM Process Cipher function */ rc = gcm_process_cipher(ctx, input, output); if (0 != rc) { goto gcm_crypt_and_tag_END; } /* Aes-GCM Process LenA||LenC function */ rc = gcm_process_lenA_lenC(ctx); if (0 != rc) { goto gcm_crypt_and_tag_END; } rc = gcm_finish(ctx, tag); gcm_crypt_and_tag_END: /* set pointer to user context and clear the output in case of failure*/ pAesGcmCtx = (AesGcmContext_t *)ctx; if ((CRYPTO_DIRECTION_DECRYPT == pAesGcmCtx->dir) && (MBEDTLS_ERR_GCM_AUTH_FAILED == rc)) { CC_PalMemSetZero(output, pAesGcmCtx->dataSize); } /* Clear working context */ CC_PalMemSetZero(ctx->buf, sizeof(mbedtls_gcm_context)); return rc; } int mbedtls_gcm_crypt_and_tag(mbedtls_gcm_context *ctx, int mode, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *input, unsigned char *output, size_t tag_len, unsigned char *tag) { int rc; rc = gcm_crypt_and_tag(ctx, mode, length, iv, iv_len, add, add_len, input, output, tag_len, tag); return rc; } int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *tag, size_t tag_len, const unsigned char *input, unsigned char *output ) { int rc; rc = gcm_crypt_and_tag(ctx, 0, length, iv, iv_len, add, add_len, input, output, tag_len, (unsigned char *)tag); return rc; } /**************************************************************************************************/ /****** UN-Supported API's **************************/ /**************************************************************************************************/ int mbedtls_gcm_starts(mbedtls_gcm_context *ctx, int mode, const unsigned char *iv, size_t iv_len) { CC_UNUSED_PARAM(ctx); CC_UNUSED_PARAM(mode); CC_UNUSED_PARAM(iv); CC_UNUSED_PARAM(iv_len); return (MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED); } int mbedtls_gcm_update(mbedtls_gcm_context *ctx, const unsigned char *input, size_t input_length, unsigned char *output, size_t output_size, size_t *output_length) { CC_UNUSED_PARAM(ctx); CC_UNUSED_PARAM(input); CC_UNUSED_PARAM(input_length); CC_UNUSED_PARAM(output); CC_UNUSED_PARAM(output_size); CC_UNUSED_PARAM(output_length); return (MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED); } int mbedtls_gcm_finish(mbedtls_gcm_context *ctx, unsigned char *output, size_t output_size, size_t *output_length, unsigned char *tag, size_t tag_len) { CC_UNUSED_PARAM(ctx); CC_UNUSED_PARAM(output); CC_UNUSED_PARAM(output_size); CC_UNUSED_PARAM(output_length); CC_UNUSED_PARAM(tag); CC_UNUSED_PARAM(tag_len); return (MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED); } int mbedtls_gcm_update_ad(mbedtls_gcm_context *ctx, const unsigned char *add, size_t add_len) { CC_UNUSED_PARAM(ctx); CC_UNUSED_PARAM(add); CC_UNUSED_PARAM(add_len); return (MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED); } /**************************************************************************************************/ #endif
2.125
2
2024-11-18T21:28:17.651092+00:00
2016-02-23T11:07:34
59bff1464ce0cc08b32ca4768fc3ea567e0c3b5f
{ "blob_id": "59bff1464ce0cc08b32ca4768fc3ea567e0c3b5f", "branch_name": "refs/heads/master", "committer_date": "2016-02-23T11:07:34", "content_id": "3b356fb197f3b89bd0c3d5b43a6b17fea7f9b964", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "7bef20e2d0ad857be16359cb7fe5b7c920aebb31", "extension": "c", "filename": "bst.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 43281477, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7675, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/src/bst.c", "provenance": "stackv2-0104.json.gz:14856", "repo_name": "jhxie/procnanny", "revision_date": "2016-02-23T11:07:34", "revision_id": "bd96aa7810dbc806c2353875431c4238406145d7", "snapshot_id": "e74df6d308344d68bd51ff320251878f73af6ded", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jhxie/procnanny/bd96aa7810dbc806c2353875431c4238406145d7/src/bst.c", "visit_date": "2021-01-18T11:09:22.622630" }
stackv2
/* *Note: this implementation is mostly based on the code examples from *http://www.eternallyconfuzzled.com/tuts/datastructures/jsw_tut_bst1.aspx *the code is modified extensively to suit the need of procnanny. */ #ifdef _POSIX_C_SOURCE #undef _POSIX_C_SOURCE #define _POSIX_C_SOURCE 200809L #endif #include <errno.h> #include <limits.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> /*MAX_SIZE definition*/ #include <string.h> #include "bst.h" #include "cfgparser.h" #include "procclient.h" #include "procserver.h" #include "pwlog.h" #include "pwwrapper.h" #include "memwatch.h" struct bst *bst_init(void) { struct bst *new_bst = calloc_or_die(1, sizeof(struct bst)); /*redundant but logical*/ new_bst->numnode = 0; new_bst->root = NULL; return new_bst; } void *bst_find(struct bst *current_bst, long key) { /* *avoid undefined behavior by returning directly *rather than trying to dereference a NULL pointer */ if (NULL == current_bst) { errno = EINVAL; return NULL; } enum bst_link_dir dir = BST_LEFT; struct bst_node_ *tmp_ptr = current_bst->root; while (NULL != tmp_ptr) { if (key == tmp_ptr->key) { break; } else { dir = key > tmp_ptr->key; tmp_ptr = tmp_ptr->link[dir]; } } return (NULL == tmp_ptr) ? NULL : tmp_ptr->memblk; } void *bst_add(struct bst *current_bst, long key, size_t blknum, size_t blksize) { if (NULL == current_bst) { errno = EINVAL; return NULL; } struct bst_node_ *bstnode = calloc_or_die(1, sizeof(struct bst_node_)); if (SIZE_MAX == current_bst->numnode) { #ifndef NDEBUG const char *const err_msg = "bst: max node count reached\n"; write(STDERR_FILENO, err_msg, strlen(err_msg)); #endif free(bstnode); errno = EOVERFLOW; return NULL; } bstnode->key = key; bstnode->memblk = calloc_or_die(blknum, blksize); bstnode->blknum = blknum; bstnode->blksize = blksize; /*again, redundant*/ bstnode->link[BST_LEFT] = NULL; bstnode->link[BST_RIGHT] = NULL; /* *start to insert the new node into the bst */ if (NULL == current_bst->root) { current_bst->root = bstnode; } else { enum bst_link_dir dir = BST_LEFT; struct bst_node_ *tmp_ptr = current_bst->root; while (true) { /*note that duplicate keys are NOT allowed*/ if (bstnode->key == tmp_ptr->key) { free(bstnode); return NULL; } dir = bstnode->key > tmp_ptr->key; if (NULL == tmp_ptr->link[dir]) break; tmp_ptr = tmp_ptr->link[dir]; } tmp_ptr->link[dir] = bstnode; } current_bst->numnode++; return bstnode->memblk; } long bst_rootkey(struct bst *current_bst) { if (NULL == current_bst || NULL == current_bst->root) { errno = EINVAL; return -1; } return current_bst->root->key; } int bst_del(struct bst *current_bst, long key) { if (NULL == current_bst) { errno = EINVAL; return -1; } if (NULL != current_bst->root) { struct bst_node_ head = {}; struct bst_node_ *tmp_ptr = &head; struct bst_node_ *p_ptr, *f_ptr = NULL; enum bst_link_dir dir = BST_RIGHT; /*make the new node's right chain pointer point to the root*/ tmp_ptr->link[BST_RIGHT] = current_bst->root; while (NULL != tmp_ptr->link[dir]) { p_ptr = tmp_ptr; tmp_ptr = tmp_ptr->link[dir]; dir = key >= tmp_ptr->key; if (key == tmp_ptr->key) { f_ptr = tmp_ptr; } } if (NULL != f_ptr) { f_ptr->key = tmp_ptr->key; f_ptr->blknum = tmp_ptr->blknum; f_ptr->blksize = tmp_ptr->blksize; free(f_ptr->memblk); f_ptr->memblk = tmp_ptr->memblk; p_ptr->link[tmp_ptr == p_ptr->link[BST_RIGHT]] = tmp_ptr->link[NULL == tmp_ptr->link[BST_LEFT]]; free(tmp_ptr); current_bst->numnode--; } current_bst->root = head.link[BST_RIGHT]; } return 0; } int bst_destroy(struct bst **current_bst, enum bst_type type) { if (NULL == current_bst || NULL == *current_bst) { errno = EINVAL; return -1; } struct pw_pid_info *pid_info_ptr; struct pw_idle_info *idle_info_ptr; struct bst_node_ *tmp_ptr = (*current_bst)->root; struct bst_node_ *saveptr; char writebuf[PW_CHILD_READ_SIZE] = {}; memset(writebuf, 0, PW_CHILD_READ_SIZE); pid_t *pid_ptr = (pid_t *)writebuf; *pid_ptr = -1; ssize_t tmp __attribute__((unused)) = 0; while (NULL != tmp_ptr) { if (NULL != tmp_ptr->link[BST_LEFT]) { saveptr = tmp_ptr->link[BST_LEFT]; tmp_ptr->link[BST_LEFT] = saveptr->link[BST_RIGHT]; saveptr->link[BST_RIGHT] = tmp_ptr; } else { saveptr = tmp_ptr->link[BST_RIGHT]; switch (type) { case PW_PID_BST: pid_info_ptr = tmp_ptr->memblk; close(pid_info_ptr->ipc_fdes[0]); tmp = write(pid_info_ptr->ipc_fdes[1], writebuf, PW_CHILD_READ_SIZE); close(pid_info_ptr->ipc_fdes[1]); break; case PW_IDLE_BST: idle_info_ptr = tmp_ptr->memblk; close(idle_info_ptr->ipc_fdes[0]); tmp = write(idle_info_ptr->ipc_fdes[1], writebuf, PW_CHILD_READ_SIZE); close(idle_info_ptr->ipc_fdes[1]); break; case PW_CLIENT_BST: /* *the client case has already been taken care *of by pw_client_bst_report_helper() */ break; } free(tmp_ptr->memblk); free(tmp_ptr); } tmp_ptr = saveptr; } free(*current_bst); *current_bst = NULL; return 0; }
2.8125
3
2024-11-18T21:28:17.811151+00:00
2020-08-27T04:30:59
f5abc8014bec47581214569169e9cf6220cc4a1b
{ "blob_id": "f5abc8014bec47581214569169e9cf6220cc4a1b", "branch_name": "refs/heads/master", "committer_date": "2020-08-27T04:30:59", "content_id": "88a90f2c62a90253d05b0048c1cc9e13238e9aa2", "detected_licenses": [ "MIT" ], "directory_id": "30214b22d4e78b138fb5d9070cea2e3ed4c4ed52", "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": 207430146, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 617, "license": "MIT", "license_type": "permissive", "path": "/week03/d/main.c", "provenance": "stackv2-0104.json.gz:14984", "repo_name": "4amup/C-Programming-Language-Practice", "revision_date": "2020-08-27T04:30:59", "revision_id": "6b134cadfacd02349c910b42eea9b8a77f40c62c", "snapshot_id": "3de44abe0315d557b11259b8eb8e76ecfada0672", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/4amup/C-Programming-Language-Practice/6b134cadfacd02349c910b42eea9b8a77f40c62c/week03/d/main.c", "visit_date": "2021-07-18T05:26:51.273483" }
stackv2
#include<stdio.h> #include<math.h> int main() { int x,y,a,b; int result; int unit,ten,hundred,thousand; int temp; printf("Input x:\n"); scanf("%d",&x); //计算过程 x = abs(x); temp = x; thousand = temp/1000; temp = temp-thousand*1000; hundred = temp/100; temp = temp-hundred*100; ten = temp/10; unit = temp%10; y = unit*1000+ten*100+hundred*10+thousand; a = unit*10+ten; b = hundred*10+thousand; result = pow(a,2)+pow(b,2); printf("y=%d\n",y); printf("a=%d,b=%d\n",a,b); printf("result=%d\n",result); return 0; }
3.0625
3
2024-11-18T21:28:18.044323+00:00
2023-08-27T15:21:42
42c928628c128c591b8c2f6ab31fad2649221f97
{ "blob_id": "42c928628c128c591b8c2f6ab31fad2649221f97", "branch_name": "refs/heads/master", "committer_date": "2023-08-27T15:22:31", "content_id": "c7a77ab78f1c98339c052a15c53183168e839a0b", "detected_licenses": [ "MIT" ], "directory_id": "49ee49ee34fa518b0df934081f5ea44a0faa3451", "extension": "c", "filename": "udp_server_nix.c", "fork_events_count": 16, "gha_created_at": "2015-09-22T01:27:05", "gha_event_created_at": "2023-09-09T07:33:29", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 42903588, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2784, "license": "MIT", "license_type": "permissive", "path": "/explore-socket/socket-abc/udp_server_nix.c", "provenance": "stackv2-0104.json.gz:15242", "repo_name": "kingsamchen/Eureka", "revision_date": "2023-08-27T15:21:42", "revision_id": "e38774cab5cf757ed858547780a8582951f117b4", "snapshot_id": "a9458fcc7d955910bf2cefad3a1561cec3559702", "src_encoding": "UTF-8", "star_events_count": 28, "url": "https://raw.githubusercontent.com/kingsamchen/Eureka/e38774cab5cf757ed858547780a8582951f117b4/explore-socket/socket-abc/udp_server_nix.c", "visit_date": "2023-09-01T11:32:35.575951" }
stackv2
/* * udpserver.c - A simple UDP echo server * usage: udpserver <port> */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define BUFSIZE 1024 /* * error - wrapper for perror */ void error(char *msg) { perror(msg); exit(1); } int main(int argc, char **argv) { int sockfd; /* socket */ int portno; /* port to listen on */ int clientlen; /* byte size of client's address */ struct sockaddr_in serveraddr; /* server's addr */ struct sockaddr_in clientaddr; /* client addr */ struct hostent *hostp; /* client host info */ char *buf; /* message buf */ char *hostaddrp; /* dotted decimal host addr string */ int optval; /* flag value for setsockopt */ int n; /* message byte size */ /* * check command line arguments */ if (argc != 2) { fprintf(stderr, "usage: %s <port>\n", argv[0]); exit(1); } portno = atoi(argv[1]); /* * socket: create the parent socket */ sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) error("ERROR opening socket"); /* setsockopt: Handy debugging trick that lets * us rerun the server immediately after we kill it; * otherwise we have to wait about 20 secs. * Eliminates "ERROR on binding: Address already in use" error. */ optval = 1; setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof(int)); /* * build the server's Internet address */ bzero((char *)&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons((unsigned short)portno); /* * bind: associate the parent socket with a port */ if (bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) error("ERROR on binding"); /* * main loop: wait for a datagram, then echo it */ clientlen = sizeof(clientaddr); while (1) { /* * recvfrom: receive a UDP datagram from a client */ buf = malloc(BUFSIZE); n = recvfrom(sockfd, buf, BUFSIZE, 0, (struct sockaddr *)&clientaddr, &clientlen); if (n < 0) error("ERROR in recvfrom"); /* * gethostbyaddr: determine who sent the datagram */ hostp = gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET); if (hostp == NULL) error("ERROR on gethostbyaddr"); hostaddrp = inet_ntoa(clientaddr.sin_addr); if (hostaddrp == NULL) error("ERROR on inet_ntoa\n"); /*printf("server received %d bytes\n", n); */ /* * sendto: echo the input back to the client */ n = sendto(sockfd, buf, n, 0, (struct sockaddr *)&clientaddr, clientlen); if (n < 0) error("ERROR in sendto"); } }
3.140625
3
2024-11-18T22:09:26.031260+00:00
2021-02-10T16:49:15
c144a5cff3864f34b10011452a50b3fef8d5dd34
{ "blob_id": "c144a5cff3864f34b10011452a50b3fef8d5dd34", "branch_name": "refs/heads/main", "committer_date": "2021-02-10T16:49:15", "content_id": "56eede978501e42fc0965660da824a44a109a695", "detected_licenses": [ "MIT" ], "directory_id": "2989cd0e9bf8d48ca79fa7be4399cd79f1d9f555", "extension": "h", "filename": "NSSTFuncs.h", "fork_events_count": 0, "gha_created_at": "2021-02-10T20:08:08", "gha_event_created_at": "2021-02-10T20:08:08", "gha_language": null, "gha_license_id": "MIT", "github_id": 337840459, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5344, "license": "MIT", "license_type": "permissive", "path": "/Form_NSST/Form_Empty/NSSTFuncs.h", "provenance": "stackv2-0106.json.gz:32899", "repo_name": "uzunb/NSST_Optimum_Focused_Image_Generate", "revision_date": "2021-02-10T16:49:15", "revision_id": "91c603a6b872893c757528d96e96973f2ac3960c", "snapshot_id": "42c1ead118a1314eeea6cf3541e9a31eeefe2a3f", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/uzunb/NSST_Optimum_Focused_Image_Generate/91c603a6b872893c757528d96e96973f2ac3960c/Form_NSST/Form_Empty/NSSTFuncs.h", "visit_date": "2023-03-08T21:35:42.831541" }
stackv2
#pragma once #include "Container.h" /// <summary> /// This function generates the xand y vectors that contain the i, j coordinates to extract radial slices /// </summary> /// <param name="n : "> /// n is the order of the block to be used /// </param> /// <returns> /// ** return [x1n, y1n, x2n, y2n, D] ** <para></para> /// x1, y1 are the i, j values that correspond to the radial slices from the endpoints 1, 1 to n, 1 through the origin <para></para> /// x2, y2 are the i, j values that correspond to the radial slices from the endpoints 1, 1 to 1, n through the origin <para></para> /// D is the matrix that contains the number of times the polar grid points go through the rectangular grid /// </returns> Matrix* GenXYCoordinates(int n); /// <summary> /// This function computes the directional / shearing filters using the Meyer window function. /// </summary> /// <param name="n : "> /// n indicates the supports size of the directional filter is n1xn1 level indicates that the number of directions is 2 ^ level /// </param> /// <param name="level : "> /// level indicates /// </param> /// <returns> /// a sequence of 2D directional/shearing filters w_s where the third index determines which directional filter is used /// </returns> Matrix* ShearingFiltersMyer(int n, int level); // This function computes the Meyer window function of signal x float MeyerWind(float x); // This function computes L band sequence of a Meyer windowed signal. Matrix* Windowing(float* x, int lenghtX, int L); /// <summary> /// This funcion re - assembles the radial slice into block. /// </summary> /// <param name="l : "> /// l is the radial slice matrix /// </param> /// <param name="n : "> /// n is the order of the matrix that is to be re - assembled /// x1, y1, x2, y2 are the polar coordinates generated from function /// </param> /// <param name="gen : "> /// D is the matrix containing common polar grid points /// </param> /// <returns> /// C is the re - assembled block matrix /// </returns> Matrix* RecFromPol(Matrix* l, int n, Matrix* gen); /// <summary> /// Performs symmetric extension for image x, filter h. <para></para> /// The filter h is assumed have odd dimensions. <para></para> /// If the filter has horizontaland vertical symmetry, then the nonsymmetric part of conv2(h, x) has the same size of x. /// </summary> /// <param name="x : "> /// mxn image /// </param> /// <param name="h : "> /// 2 - D filter coefficients /// </param> /// <param name="shift : "> /// optional shift /// </param> /// <returns> /// yT image symetrically extended(H / V symmetry) /// </returns> Matrix* symext(Matrix* x, Matrix* h, float* shift); // upsample filter by 2^power Matrix* Upsample2df(const Matrix* mat, int power); /// <summary> /// This function does not actually upsample the filter, /// it computes the convolution as if the filter had been upsampled. /// This is the ultimate optimized version. Further optimized for separable(diagonal) upsampling matrices. /// </summary> /// <param name="signal : "> /// A 2D Signal /// </param> /// <param name="filter : "> /// 2D filter /// </param> /// <param name="upMatrix : "> /// separable upsampling matrix /// </param> /// <returns> /// 2D result of convolution with filter upsampled by a m, only the 'valid' part is returned. <para></para> /// Similar to conv2(x, h, 'valid'), where h is the upsampled filter. /// </returns> Matrix* Atrousc(Matrix* signal, Matrix* filter, float* upMatrix); /// <summary> /// ATROUSDEC - computes the 2 - D atrous decomposition using symmetric extension. /// </summary> /// <param name="image : "> /// input image /// </param> /// <param name="filters : "> /// can be any filter available in the function atrousfilters /// </param> /// <param name="level : "> /// N levels - number of decomposition levels /// </param> /// <returns> /// y->[0] => LFC (Low frequency coefficients /// <para></para> /// y->[1..4] => HFC (High frequency coefficients) /// </returns> Cont* AtrousDec(Matrix* image, Cont* filters, int level); /// <summary> /// ATROUSFILTERS Generate pyramid 2D filters /// </summary> /// <param name="fname : "> /// 'maxflat': Filters derived from 1-D using maximally flat mapping function with 4 vanishing moments /// </param> /// <returns> /// h0, h1, g0, g1: pyramid filters for 2-D nonsubsampled filter bank (lowpass and highpass) /// </returns> Cont* AtrousFilters(const char* fname); /// <summary> /// SATROUSREC - computes the inverse of 2 - D atrous decomposition computed with ATROUSDEC /// </summary> /// <param name="y : "> /// image /// </param> /// <param name="lpfilt : "> /// can be any filter available in the function atrousfilters /// </param> /// <returns> /// x : reconstructed image /// </returns> Matrix* AtrousRec(Cont* y, const char* lpfilt); /// <summary> /// This function generates the matrix that contains the number of times the polar grid points go through the rectangular grid /// </summary> /// <param name="L : "> /// L is the order of the block matrix /// </param> /// <returns> /// D is the common grid point values /// </returns> float* AvgPol(int L, float* x1, float* y1, float* x2, float* y2);
2.640625
3
2024-11-18T22:09:26.276649+00:00
2020-09-09T09:34:03
d352058dd28c1b6c96f09bedc63f553051010f00
{ "blob_id": "d352058dd28c1b6c96f09bedc63f553051010f00", "branch_name": "refs/heads/master", "committer_date": "2020-09-09T09:34:03", "content_id": "020460e3c9631329d57bb6bdf3b6236b4c5775b5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e33390d12bacf498d0bc3563aa83758e6e22b003", "extension": "c", "filename": "solution.c", "fork_events_count": 1, "gha_created_at": "2017-09-26T01:59:35", "gha_event_created_at": "2020-09-09T09:34:04", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 104823030, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3134, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/leetcode/142-linked-list-cycle-ii/solution.c", "provenance": "stackv2-0106.json.gz:33030", "repo_name": "dantin/daylight", "revision_date": "2020-09-09T09:34:03", "revision_id": "812859a982da666daecedbb1197afed21485a432", "snapshot_id": "27acdf434112d6e9388df119b64c35a29eed0041", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dantin/daylight/812859a982da666daecedbb1197afed21485a432/leetcode/142-linked-list-cycle-ii/solution.c", "visit_date": "2022-12-10T21:49:42.371814" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> struct Object { int *nums; int len; int pos; }; struct ListNode { int val; struct ListNode *next; }; void print_nums(int *nums, int size) { char *s = ""; int i; printf("["); for (i = 0; i < size; i++) { printf("%s%d", s, nums[i]); s = ", "; } printf("]"); } int node_index(struct ListNode *head, struct ListNode *node) { int i = 0; while (head != node) { i++; head = head->next; } return i; } struct ListNode *make_list(int *nums, int size, int pos, struct ListNode **tail) { struct ListNode *prev; struct ListNode dummy; dummy.next = NULL; prev = &dummy; int i; for (i = 0; i < size; i++) { struct ListNode *node = malloc(sizeof(*node)); node->val = nums[i]; node->next = NULL; prev->next = node; prev = node; } if (pos >= 0) { struct ListNode *head = dummy.next; for (i = 0; i < pos; i++) { head = head->next; } prev->next = head; } *tail = prev; return dummy.next; } void free_list(struct ListNode *head, struct ListNode *tail) { struct ListNode *tmp; while (head != tail) { tmp = head; head = head->next; free(tmp); } free(tail); } struct ListNode *detect_cycle(struct ListNode *head) { if (head == NULL || head->next == NULL) { return NULL; } bool first = true; struct ListNode *p0, *p1; for (p0 = head, p1 = head; p1 != NULL && p1->next != NULL; p0 = p0->next, p1 = p1->next->next) { if (p0 == p1 && !first) { p0 = head; while (p0 != p1) { p0 = p0->next; p1 = p1->next; } return p0; } first = false; } return NULL; } int main(int argc, char **argv) { int nums1[] = { 3, 2, 0, -4 }, len1 = sizeof(nums1) / sizeof(int); int pos1 = 1; int nums2[] = { 1, 2 }, len2 = sizeof(nums2) / sizeof(int); int pos2 = 0; int nums3[] = { 1 }, len3 = sizeof(nums3) / sizeof(int); int pos3 = -1; struct Object inputs[] = { { .nums = nums1, .len = len1, .pos = pos1 }, { .nums = nums2, .len = len2, .pos = pos2 }, { .nums = nums3, .len = len3, .pos = pos3 }, }; int i, len = sizeof(inputs) / sizeof(struct Object); struct ListNode *tail = NULL; for (i = 0; i < len; i++) { int *nums = inputs[i].nums; int size = inputs[i].len; int pos = inputs[i].pos; printf("\n Input: head = "); print_nums(nums, size); printf(", pos = %d", pos); struct ListNode *head = make_list(nums, size, pos, &tail); struct ListNode *join_node = detect_cycle(head); printf("\n Output: "); if (join_node == NULL) { printf("no cycle"); } else { printf("tail connects to node index %d", node_index(head, join_node)); } printf("\n"); free_list(head, tail); } return EXIT_SUCCESS; }
3.59375
4
2024-11-18T22:09:26.376091+00:00
2023-09-01T14:02:39
b8454dc37da3f8ed5b6aff6764f3931eaa954152
{ "blob_id": "b8454dc37da3f8ed5b6aff6764f3931eaa954152", "branch_name": "refs/heads/master", "committer_date": "2023-09-01T14:02:39", "content_id": "c706da4c71feac8d3e4e771f5608deb99fff8336", "detected_licenses": [ "Apache-2.0", "BSD-3-Clause" ], "directory_id": "49f394ccd6c3729e9c382a3fe09415344ca98874", "extension": "h", "filename": "size-negotiation-controls.h", "fork_events_count": 12, "gha_created_at": "2016-10-05T18:13:51", "gha_event_created_at": "2020-08-28T14:04:59", "gha_language": "C++", "gha_license_id": "NOASSERTION", "github_id": 70086454, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12125, "license": "Apache-2.0,BSD-3-Clause", "license_type": "permissive", "path": "/docs/content/programming-guide/size-negotiation-controls.h", "provenance": "stackv2-0106.json.gz:33160", "repo_name": "dalihub/dali-toolkit", "revision_date": "2023-09-01T14:02:39", "revision_id": "4dec2735f5e5b5ed74f70a402c9a008d6c21af05", "snapshot_id": "69ccb4c71904fdc9f1d88e0a1fedeaa2691213f8", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/dalihub/dali-toolkit/4dec2735f5e5b5ed74f70a402c9a008d6c21af05/docs/content/programming-guide/size-negotiation-controls.h", "visit_date": "2023-09-03T05:02:34.534108" }
stackv2
/*! \page size-negotiation-controls Size Negotiation for Controls * <h2 class="pg">Overview</h2> This document details how to create controls using the size negotiation API and is intended for UI control writters. For an introduction to size negotiation please see the <i>Size Negotiation Programming Guide</i>. The topics covered are: - The Relayout Controller - Resize Policies - Creating a Control: Popups - Size Negotiation API - Creating a Control: TableView <h2 class="pg">The Relayout Controller</h2> <h3>Overview</h3> The RelayoutController is an object that is private in DALi Core. It's main job is to take relayout requests from actors. It can be enabled or disabled internally. If disabled, then all relayout requests are ignored. By default the relayout controller is disabled until just after the initial application initialize. This allows the scene for an application to be created without generating many relayout requests. After the application has initialized the scene, then the relayout controller is automatically enabled and a relayout request is called on the root of the scene. This request spreads down the scene hierarchy and requests relayout on all actors that have size negotiation enabled. Relayout requests are put in automatically when a property is changed on an actor or a change to the stage hierarchy is made and manual requests are usually not necessary. <h2 class="pg">Resize Policies</h2> In addition to the resize policies detailed in the Size Negotiation Programming Guide there is one additional policy available to control writers: - ResizePolicy::USE_ASSIGNED_SIZE: Tells the actor to use the size that was passed into the size negotiation algorithm for it. This is used in the OnRelayout method derived from Actor when passing back controls to be negotiated using the container argument to the method. <h2 class="pg">Creating a Control: Popups</h2> <h3>Initialization</h3> Size negotiation is enabled on controls by default. If a control is desired to not have size negotiation enabled then simply pass in the DISABLE_SIZE_NEGOTIATION flag into the Control constructor. The other step to perform is to set default resize policies for width and height. <h3>A Simple Example: Popup</h3> This example shows how to set up a popup for use with size negotiation. The popup contains a layer to raise it above all other controls, a semi-transparent full-screen backing image to dim the screen, a background image with a shadow border, and buttons that are positioned and resized by the popup. The following screen shot shows an example popup. \image html size-negotiation/PopupExample.png The first step is to set the default resize policies. This is done in the OnInitialize method. In the following snippet the popup is set to have a height resize policy of ResizePolicy::FIT_TO_CHILDREN. This assumes that the width of the popup will be specified by the user of the popup and that the desired behaviour is to fit the height of the popup to the size of its content. @code void Popup::OnInitialize() ... Actor self = Self(); self.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::HEIGHT ); @endcode The popup will use a layer to place its content in. The layer is created and specified to fill the whole screen by using the following command. @code mLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); @endcode A half transparent backing image is added to the layer and told to fill the layer with the following. @code mBacking.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); @endcode The popup control is added to the layer and a background image is specified to fill the size of the popup and add a border by the following. @code mBackgroundImage.SetResizePolicy( ResizePolicy::SIZE_FIXED_OFFSET_FROM_PARENT, Dimension::ALL_DIMENSIONS ); Vector3 border( mPopupStyle->backgroundOuterBorder.x, mPopupStyle->backgroundOuterBorder.z, 0.0f ); mBackgroundImage.SetProperty( Actor::Property::SIZE_MODE_FACTOR, border ); @endcode A table view is added to the popup to specify layout. It will fill to the width of the popup and expand/contract around its children cell heights. @code mPopupLayout.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH ); mPopupLayout.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT ); @endcode Override the OnRelayout method to position and resize the buttons. @code void Popup::OnRelayout( const Vector2& size, RelayoutContainer& container ) ... @endcode Another aspect to the popup is that depending which resize policies are active on it then the inner table view requires different resize policies itself. OnSetResizePolicy can be overridden to receive notice that the resize policy has changed on the control and action can be taken. @code void Popup::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension ) ... if( policy == ResizePolicy::FIT_TO_CHILDREN ) { // Make content fit to children mPopupLayout.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, dimension ); if( dimension & Dimension::HEIGHT ) { mPopupLayout.SetFitHeight( 1 ); } } else { mPopupLayout.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, dimension ); // Make the content cell fill the whole of the available space if( dimension & Dimension::HEIGHT ) { mPopupLayout.SetRelativeHeight( 1, 1.0f ); } } @endcode Popup also implements the following methods for use with the relevant resize policies: - GetNaturalSize - GetHeightForWidth - GetWidthForHeight <h2 class="pg">Size Negotiation API</h2> <h3>Base Class Methods</h3> The base class methods are used to call functionality held in Actor and are defined in CustomActorImpl. There is a RelayoutRequest method defined. This method is available for deriving controls to call when they would like themselves to be relaid out. @code void RelayoutRequest() @endcode <h3>Overridable Methods</h3> These overridable methods in control provide customization points for the size negotiation algorithm. <h4>Responding to the Change of Size on a Control</h4> OnRelayout is called during the relayout process at the end of the frame immediately after the new size has been set on the actor. If the actor has calculated the size of child actors then add them to container with their desired size and set the ResizePolicy::USE_ASSIGNED_SIZE resize policy on them. At this point the size of the actor has been calculated so it is a good place to calculate positions of child actors etc. @code virtual void OnRelayout( const Vector2& size, RelayoutContainer& container ) @endcode The OnRelayoutSignal signal is raised after SetSize and OnRelayout have been called during the relayout processing at the end of the frame. If the control is deriving from Control then the OnRelayout virtual is preferred over this signal. The signal is provided for instance when custom code needs to be run on the children of an actor that is not a control. @code OnRelayoutSignalType& OnRelayoutSignal() @endcode The OnCalculateRelayoutSize is called right before the size is calculated for an actor's dimension during the size negotiation phase. At this point all other actors this actor is dependent on have been negotiated so calculations depending on these actors can be performed before the size for this actor is calculated. Useful for container size calculations. @code virtual void OnCalculateRelayoutSize( Dimension::Type dimension ) @endcode OnLayoutNegotiated is called right after the size in a given dimension has been negotiated for an actor. This allows calculations to be performed in response to the change in a given dimension but before OnRelayout is called. @code virtual void OnLayoutNegotiated( float size, Dimension::Type dimension ) @endcode <h4>Calculating Sizes</h4> Calculate the natural size for this control. This will be called when a control's resize policy is set to USE_NATURAL_SIZE. For example, TableView will calculated the size of the table given its various cell properties. @code virtual Vector3 GetNaturalSize() @endcode Given an input width return the correct height for this control. This will be called when the resize policy is set to ResizePolicy::DIMENSION_DEPENDENCY and height has a dependency on width. @code virtual float GetHeightForWidth( float width ) @endcode Given the input height return the correct width for this control. This will be called when the resize policy is set to ResizePolicy::DIMENSION_DEPENDENCY and width has a dependency on height. @code virtual float GetWidthForHeight( float height ) @endcode <h4>Relayout Dependencies</h4> Return true from this method if this control is dependent on any of its children to calculate its own size. All relayout containers that can be dependent on their children for their own size need to return true from this. @code virtual bool RelayoutDependentOnChildren( Dimension::Type dimension = Dimension::ALL_DIMENSIONS ) @endcode This will be called by children when they are using the ResizePolicy::FILL_TO_PARENT resize policy. It is the parent's responsibility to calculate the child's correct size. @code virtual float CalculateChildSize( const Dali::Actor& child, Dimension::Type dimension ) @endcode <h4>Events</h4> OnSetResizePolicy is called when the resize policy is set on an actor. Allows deriving actors to respond to changes in resize policy. @code virtual void OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension ) @endcode <h2 class="pg">Creating a Control: TableView</h2> This section demonstrates how size negotiation may be used when creating a table view. First we define some policies for how table row and columns may resize. These are: - Fixed: Use a fixed size - Relative: Use a ratio size of empty remaining space - Fill: Fill up to all remaining space, distributing evenly between all "fill" row or columns A data structure is defined to hold information for each row and column regarding their cell size policy and their assigned and calculated sizes. We need to be able to calculate the fixed sizes of all actors placed into table cells. The place to do this is in OnCalculateRelayoutSize. When this is called every actor the table view is dependent on has already had their sizes calculated. Calculations can be made that the main calculation for the actor can then use. @code void TableView::OnCalculateRelayoutSize( Dimension::Type dimension ) ... CalculateRowColumnData(); if( dimension & Dimension::WIDTH ) { CalculateFixedSizes( mColumnData, Dimension::WIDTH ); mFixedTotals.width = CalculateTotalFixedSize( mColumnData ); } if( dimension & Dimension::HEIGHT ) { CalculateFixedSizes( mRowData, Dimension::HEIGHT ); mFixedTotals.height = CalculateTotalFixedSize( mRowData ); } ... @endcode An important override is GetNaturalSize. This will simply return the total sum of the fixed cells for each row and column. @code Vector3 TableView::GetNaturalSize() ... return Vector3( mFixedTotals.width, mFixedTotals.height, 1.0f ); ... @endcode When the time comes to calculate the size of each child in the table cells the following method will be called. @code float TableView::CalculateChildSize( const Actor& child, Dimension::Type dimension ) ... // Use cell data to calculate child size @endcode The table view is dependent on its children if its size policy is set to USE_NATURAL_SIZE or a row or column is set to "fit" an actor. The following code shows calling the base class RelayoutDependentOnChildren to check the resize policy and then searches for fit row or columns. @code bool TableView::RelayoutDependentOnChildren( Dimension::Type dimension ) { if ( Control::RelayoutDependentOnChildren( dimension ) ) { return true; } return FindFit( mRowData ) || FindFit( mColumnData ); } @endcode With the cell sizes already calculated, the job of OnRelayout is to position all the actors in the table view in their respective positions. @code void TableView::OnRelayout( const Vector2& size, RelayoutContainer& container ) ... // Find each actor and position it, taking padding into account @endcode * */
2.546875
3
2024-11-18T22:09:26.446252+00:00
2019-01-03T11:00:54
44d522238f60ecceb2205bf8721b63267c7a2265
{ "blob_id": "44d522238f60ecceb2205bf8721b63267c7a2265", "branch_name": "refs/heads/master", "committer_date": "2019-01-03T11:00:54", "content_id": "e9362b8fd54e8d3fdc9fc212327a5921510766dd", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9ea0ecd20e2aed61690869cf674570f5bae09a58", "extension": "c", "filename": "mgos_pca9685_i2c.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 163960352, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3391, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/mgos_pca9685_i2c.c", "provenance": "stackv2-0106.json.gz:33288", "repo_name": "mamuesp/pca9685-i2c", "revision_date": "2019-01-03T11:00:54", "revision_id": "fe83d23800b823eb8ba9e3adef2e5f0060f5b608", "snapshot_id": "74c8742f851ea4f1b9bfd553f74999fe06dbba19", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mamuesp/pca9685-i2c/fe83d23800b823eb8ba9e3adef2e5f0060f5b608/src/mgos_pca9685_i2c.c", "visit_date": "2020-04-14T16:45:15.113742" }
stackv2
#include "mgos_pca9685_i2c.h" mgos_pca9685* mgos_pca9685_create(uint8_t addr) { mgos_pca9685* newPwm; newPwm = calloc(1, sizeof(mgos_pca9685)); newPwm->addr = addr; newPwm->i2c = mgos_i2c_get_global(); return newPwm; } bool mgos_pca9685_free(mgos_pca9685* pwm) { memset(pwm, 0, sizeof(mgos_pca9685)); free(pwm); pwm = NULL; return true; } mgos_pca9685* mgos_pca9685_get_global() { return globalPwm; } bool mgos_pca9685_write8(mgos_pca9685* pwm, uint8_t address, uint8_t data) { char cmd[2]; cmd[0] = address; cmd[1] = data; return mgos_i2c_write(pwm->i2c, pwm->addr, cmd, 2, true); } uint8_t mgos_pca9685_read8(mgos_pca9685* pwm, char address) { uint8_t rtn; mgos_i2c_write(pwm->i2c, pwm->addr, &address, 1, true); mgos_i2c_read(pwm->i2c, pwm->addr, &rtn, 1, true); return rtn; } bool mgos_pca9685_reset(mgos_pca9685* pwm) { bool result; result = mgos_pca9685_write8(pwm, MODE1, 0x0); LOG(LL_DEBUG, ("mgos_pca9685_reset: result <%s>", result ? "TRUE" : "FALSE")); return result; } int mgos_pca9685_set_freq(mgos_pca9685* pwm, float freq) { freq *= 0.9; // Correct for some overflow in the frequency setting. float prescale = floor((((CLOCK_FREQ / 4096) / freq)) + 0.5) - 1; LOG(LL_DEBUG, ("mgos_pca9685 - Final pre-scale: %f", prescale)); uint8_t oldMode = mgos_pca9685_read8(pwm, MODE1); uint8_t newMode = (oldMode & 0x7F) | 0x10; // sleep mgos_pca9685_write8(pwm, MODE1, newMode); mgos_msleep(5); mgos_pca9685_write8(pwm, PRE_SCALE, prescale); mgos_pca9685_write8(pwm, MODE1, oldMode); mgos_msleep(5); mgos_pca9685_write8(pwm, MODE1, oldMode | 0xa1); return prescale; } void mgos_pca9685_set_pwm(mgos_pca9685* pwm, uint8_t num, uint16_t on, uint16_t off) { uint8_t cmd[5]; cmd[0] = LED0_ON_L + 4 * num; cmd[1] = on; cmd[2] = on >> 8; cmd[3] = off; cmd[4] = off >> 8; mgos_i2c_write(pwm->i2c, pwm->addr, cmd, 5, true); LOG(LL_DEBUG, ("mgos_pca9685 - Setting PWM %d: 'on' - %d, 'off' - %d", num, on, off)); } uint32_t mgos_pca9685_get_pwm(mgos_pca9685* pwm, uint8_t num) { uint16_t on, off; on = mgos_pca9685_read8(pwm, LED0_ON_H + (num << 2)); on = (on & 0xf) << 8; on += mgos_pca9685_read8(pwm, LED0_ON_L + (num << 2)); off = mgos_pca9685_read8(pwm, LED0_OFF_H + (num << 2)); off = (off & 0xf) << 8; off += mgos_pca9685_read8(pwm, LED0_OFF_L + (num << 2)); return (on << 16) + off; } void mgos_pca9685_set_pin(mgos_pca9685* pwm, uint8_t pin, uint16_t val, bool invert) { uint16_t on, off; val = MIN(val, 0x1000); switch (val) { case 0: on = invert ? 0x1000 : 0; off = invert ? 0 : 0x1000; break; case 4096: on = invert ? 0 : 0x1000; off = invert ? 0x1000 : 0; break; default: on = 0; off = invert ? 0x0FFF - val : val; break; } mgos_pca9685_set_pwm(pwm, pin, on, off); } bool mgos_pca9685_i2c_init(void) { if (mgos_sys_config_get_pca9685_enable()) { int addr = mgos_sys_config_get_pca9685_addr(); if (addr != 0) { globalPwm = mgos_pca9685_create(addr); mgos_pca9685_reset(globalPwm); } else { LOG(LL_ERROR, ("mgos_pca9685 - I2C address is not configured correctly!")); } } return true; }
2.671875
3
2024-11-18T22:09:26.548258+00:00
2021-03-24T18:24:01
5d6090c1638726746307e79177fb8b15390cf7e9
{ "blob_id": "5d6090c1638726746307e79177fb8b15390cf7e9", "branch_name": "refs/heads/main", "committer_date": "2021-03-24T18:24:01", "content_id": "65315d74c6e3081e5f496b099f25ff4344fead04", "detected_licenses": [ "MIT" ], "directory_id": "8d75b9dde2af996c060be2632fb56f95c909ef33", "extension": "c", "filename": "Lista.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 351182831, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1981, "license": "MIT", "license_type": "permissive", "path": "/Atividade 11/Lista.c", "provenance": "stackv2-0106.json.gz:33417", "repo_name": "suchorski/Listas-de-Exercicios-em-C", "revision_date": "2021-03-24T18:24:01", "revision_id": "c723c57500637c39642c478489af682e32300c3b", "snapshot_id": "333d08c68487d135ab01b1688c3339c1b4e91f4b", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/suchorski/Listas-de-Exercicios-em-C/c723c57500637c39642c478489af682e32300c3b/Atividade 11/Lista.c", "visit_date": "2023-03-25T10:27:23.803272" }
stackv2
#include <stdio.h> #include <stdlib.h> struct lista { char info; struct lista *prox; }; typedef struct lista TLista; TLista* inicializa() { return NULL; } TLista* insere(TLista* l, char c) { TLista* novo = (TLista*) malloc(sizeof(TLista)); novo->info = c; novo->prox = l; return novo; } void imprime(TLista* l) { TLista* aux; for (aux=l; aux != NULL; aux = aux->prox) { printf("info = %c\n", aux->info); } } void imprimeInvertido(TLista* l) { if (!l->prox) { printf("info = %c\n", l->info); return; } imprimeInvertido(l->prox); printf("info = %c\n", l->info); } int tamanho(TLista* l) { int tamanho = 0; TLista *pl = l; #ifdef HARDCORE for (; pl; pl = pl->prox, tamanho++); #else while (pl) { tamanho++; pl = pl->prox; } #endif return tamanho; } TLista* retira(TLista* l, char c) { TLista *pl = l, *aux = l; if (!pl) { return NULL; } else if (pl->info == c) { pl = pl->prox; free(aux); return pl; } else { while ((aux = pl->prox) != NULL) { if (aux->info == c) { pl->prox = aux->prox; free(aux); break; } pl = aux; } } return l; } TLista* limpar(TLista* l) { #ifdef HARDCORE while ((l = retira(l, l->info))); #else while (l) { l = retira(l, l->info); } #endif return NULL; } int main (int argc, char* argv[]) { TLista* Listax; Listax = inicializa(); Listax = insere(Listax, 'D'); Listax = insere(Listax, 'I'); Listax = insere(Listax, 'O'); Listax = insere(Listax, 'L'); Listax = insere(Listax, 'A'); Listax = insere(Listax, 'X'); Listax = insere(Listax, 'O'); printf("Tamanho: %d\n", tamanho(Listax)); Listax = retira(Listax,'D'); Listax = retira(Listax,'I'); Listax = retira(Listax,'X'); Listax = retira(Listax,'O'); printf("Tamanho: %d\n", tamanho(Listax)); Listax = retira(Listax,'Z'); printf("Tamanho: %d\n", tamanho(Listax)); imprime(Listax); imprimeInvertido(Listax); Listax = limpar(Listax); printf("Tamanho: %d\n", tamanho(Listax)); return 0; }
3.40625
3
2024-11-18T22:09:26.785586+00:00
2020-03-12T04:43:55
36fa9a146b7ecbf2076d237df602606370e6c9c8
{ "blob_id": "36fa9a146b7ecbf2076d237df602606370e6c9c8", "branch_name": "refs/heads/master", "committer_date": "2020-03-12T04:43:55", "content_id": "751d39a70e3eee41821681ae786a68aab846394c", "detected_licenses": [ "MIT" ], "directory_id": "2a7b7bd81c96f7d2e48aa2e3d6ca3a5eebb9b4b7", "extension": "c", "filename": "status_tvcc_power.c", "fork_events_count": 0, "gha_created_at": "2019-11-05T07:38:09", "gha_event_created_at": "2019-11-05T07:38:12", "gha_language": null, "gha_license_id": null, "github_id": 219685081, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6645, "license": "MIT", "license_type": "permissive", "path": "/User/app/src/status_tvcc_power.c", "provenance": "stackv2-0106.json.gz:33548", "repo_name": "Xavier1989/H7-TOOL_STM32H7_App", "revision_date": "2020-03-12T04:43:55", "revision_id": "d42e58f3b7903d51a9c3d1174eb2a81c64b03ed6", "snapshot_id": "c3925a818ff3f7cec6d161ea502c482eb0c65809", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Xavier1989/H7-TOOL_STM32H7_App/d42e58f3b7903d51a9c3d1174eb2a81c64b03ed6/User/app/src/status_tvcc_power.c", "visit_date": "2020-09-04T07:28:29.844494" }
stackv2
/* ********************************************************************************************************* * * 模块名称 : 微型数控电源 * 文件名称 : status_TVccPower.c * 版 本 : V1.0 * 说 明 : 通过TVCC输出可调电压。电压范围1.2-5.0V,电流限制400mA * 修改记录 : * 版本号 日期 作者 说明 * V1.0 2019-11-04 armfly 正式发布1 * * Copyright (C), 2018-2030, 安富莱电子 www.armfly.com * ********************************************************************************************************* */ #include "bsp.h" #include "main.h" static void DispTVccVoltCurr(void); static void DispTVccSetting(uint16_t _volt, uint8_t _mode); /* ********************************************************************************************************* * 函 数 名: status_TVCCPower * 功能说明: 微型电源状态。TVCC引脚输出电压可调,电流可以监视。400mA限流。 * 形 参: 无 * 返 回 值: 无 ********************************************************************************************************* */ void status_TVCCPower(void) { uint8_t ucKeyCode; /* 按键代码 */ uint8_t fRefresh; uint8_t ucAdjustMode = 0; uint16_t NowVolt; /* 当前设置电压 mV */ DispHeader("微型数控电源"); DispHelpBar("TVCC输出1.2-5.0V,限流400mA", "长按S进入调节状态"); fRefresh = 1; NowVolt = 3300; DispTVccSetting(NowVolt, 0); bsp_StartAutoTimer(0, 300); while (g_MainStatus == MS_TVCC_POWER) { if (fRefresh) /* 刷新整个界面 */ { fRefresh = 0; bsp_SetTVCC(NowVolt); DispTVccVoltCurr(); } bsp_Idle(); if (bsp_CheckTimer(0)) { fRefresh = 1; } ucKeyCode = bsp_GetKey(); /* 读取键值, 无键按下时返回 KEY_NONE = 0 */ if (ucKeyCode != KEY_NONE) { /* 有键按下 */ switch (ucKeyCode) { case KEY_DOWN_S: /* S键按下 */ break; case KEY_UP_S: /* S键释放 */ if (ucAdjustMode == 0) /* 测量模式 */ { g_MainStatus = LastStatus(MS_TVCC_POWER); } else /* 设置电压的模式 */ { if (NowVolt < 5000) { NowVolt += 100; DispTVccSetting(NowVolt, 1); } else { if (g_tParam.KeyToneEnable != 0) { BEEP_Start(5, 5, 3); /* 叫50ms,停50ms,循环3次 */ } } } break; case KEY_LONG_DOWN_S: /* S键长按 */ if(ucAdjustMode == 0) { ucAdjustMode = 1; if (g_tParam.KeyToneEnable != 0) { PlayKeyTone(); } DispTVccSetting(NowVolt, 1); } break; case KEY_DOWN_C: /* C键按下 */ break; case KEY_UP_C: /* C键释放 */ if (ucAdjustMode == 0) { g_MainStatus = NextStatus(MS_TVCC_POWER); } else { if (NowVolt > 1200) { NowVolt -= 100; DispTVccSetting(NowVolt, 1); } else { if (g_tParam.KeyToneEnable != 0) { BEEP_Start(5,5,3); /* 叫50ms,停50ms,循环3次 */ } } } break; case KEY_LONG_DOWN_C: /* C键长按 */ if(ucAdjustMode == 1) { ucAdjustMode = 0; if (g_tParam.KeyToneEnable != 0) { PlayKeyTone(); } DispTVccSetting(NowVolt, 0); } break; default: break; } } } bsp_StopTimer(0); bsp_SetTVCC(3300); /* 退出时还原为3.3V */ } /* ********************************************************************************************************* * 函 数 名: DispTVccVoltCurr * 功能说明: 显示电压电流 * 形 参: 无 * 返 回 值: 无 ********************************************************************************************************* */ static void DispTVccVoltCurr(void) { char buf[32]; sprintf(buf, "%8.3f", g_tVar.TVCCVolt ); DispMeasBar(0, "电 压:", buf, "V"); sprintf(buf, "%7.2f", g_tVar.TVCCCurr); DispMeasBar(1, "电 流:", buf, "mA"); sprintf(buf, "%8.3f", g_tVar.TVCCVolt * g_tVar.TVCCCurr / 1000); DispMeasBar(2, "功 率:", buf, "W"); } /* ********************************************************************************************************* * 函 数 名: DispTVccSetting * 功能说明: 显示设置电压 * 形 参: _volt : mV (1200 - 5000) * _mode : 1表示设置模式 0 表示测量模式。 两个模式就是底色不同 * 返 回 值: 无 ********************************************************************************************************* */ static void DispTVccSetting(uint16_t _volt, uint8_t _mode) { char buf[64]; uint16_t color; sprintf(buf, " %d.%dV", _volt / 1000, (_volt % 1000) / 100); if (_mode == 1) { color = CL_YELLOW; } else { color = MEAS_BACK_COLOR; } DispMeasBarEx(3, "设 置:", buf, "", color); } /***************************** 安富莱电子 www.armfly.com (END OF FILE) *********************************/
2.46875
2
2024-11-18T22:09:26.864215+00:00
2015-03-04T17:13:15
17cac05f86d99084129f111863fa6d8e25fe0339
{ "blob_id": "17cac05f86d99084129f111863fa6d8e25fe0339", "branch_name": "refs/heads/master", "committer_date": "2015-03-04T17:13:15", "content_id": "045ffa7579d28c2afef960b7508ed2cae2801a8e", "detected_licenses": [ "MIT" ], "directory_id": "330e5371011e774ac1954763bdf196e97b93aa72", "extension": "c", "filename": "gc.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 30190435, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17861, "license": "MIT", "license_type": "permissive", "path": "/gc.c", "provenance": "stackv2-0106.json.gz:33677", "repo_name": "nyuichi/benz-gaia", "revision_date": "2015-03-04T17:13:15", "revision_id": "198780a5458132589f6496539c52816fff53a74d", "snapshot_id": "21ee12836134ec13e841e841880e2da5215496f0", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/nyuichi/benz-gaia/198780a5458132589f6496539c52816fff53a74d/gc.c", "visit_date": "2020-04-12T13:58:04.956432" }
stackv2
/** * See Copyright Notice in picrin.h */ #include "picrin.h" #include "picrin/gc.h" #include "picrin/pair.h" #include "picrin/string.h" #include "picrin/vector.h" #include "picrin/irep.h" #include "picrin/proc.h" #include "picrin/port.h" #include "picrin/blob.h" #include "picrin/cont.h" #include "picrin/error.h" #include "picrin/macro.h" #include "picrin/lib.h" #include "picrin/data.h" #include "picrin/dict.h" #include "picrin/record.h" #include "picrin/read.h" #include "picrin/symbol.h" union header { struct { union header *ptr; size_t size; char mark; } s; long alignment[2]; }; struct heap_page { union header *basep, *endp; struct heap_page *next; }; struct pic_heap { union header base, *freep; struct heap_page *pages; }; static void heap_init(struct pic_heap *heap) { heap->base.s.ptr = &heap->base; heap->base.s.size = 0; /* not 1, since it must never be used for allocation */ heap->base.s.mark = PIC_GC_UNMARK; heap->freep = &heap->base; heap->pages = NULL; #if GC_DEBUG printf("freep = %p\n", (void *)heap->freep); #endif } struct pic_heap * pic_heap_open(pic_state *pic) { struct pic_heap *heap; heap = pic_calloc(pic, 1, sizeof(struct pic_heap)); heap_init(heap); return heap; } void pic_heap_close(pic_state *pic, struct pic_heap *heap) { struct heap_page *page; while (heap->pages) { page = heap->pages; heap->pages = heap->pages->next; pic_free(pic, page); } } static void gc_free(pic_state *, union header *); static void add_heap_page(pic_state *pic) { union header *up, *np; struct heap_page *page; size_t nu; #if GC_DEBUG puts("adding heap page!"); #endif nu = (PIC_HEAP_PAGE_SIZE + sizeof(union header) - 1) / sizeof(union header) + 1; up = pic_calloc(pic, 1 + nu + 1, sizeof(union header)); up->s.size = nu + 1; up->s.mark = PIC_GC_UNMARK; gc_free(pic, up); np = up + 1; np->s.size = nu; np->s.ptr = up->s.ptr; up->s.size = 1; up->s.ptr = np; page = pic_alloc(pic, sizeof(struct heap_page)); page->basep = up; page->endp = up + nu + 1; page->next = pic->heap->pages; pic->heap->pages = page; } void * pic_alloc(pic_state *pic, size_t size) { void *ptr; ptr = pic->allocf(NULL, size); if (ptr == NULL && size > 0) { pic_panic(pic, "memory exhausted"); } return ptr; } void * pic_realloc(pic_state *pic, void *ptr, size_t size) { ptr = pic->allocf(ptr, size); if (ptr == NULL && size > 0) { pic_panic(pic, "memory exhausted"); } return ptr; } void * pic_calloc(pic_state *pic, size_t count, size_t size) { void *ptr; size *= count; ptr = pic->allocf(NULL, size); if (ptr == NULL && size > 0) { pic_panic(pic, "memory exhausted"); } memset(ptr, 0, size); return ptr; } void pic_free(pic_state *pic, void *ptr) { PIC_UNUSED(pic); pic->allocf(ptr, 0); } static void gc_protect(pic_state *pic, struct pic_object *obj) { if (pic->arena_idx >= pic->arena_size) { pic->arena_size = pic->arena_size * 2 + 1; pic->arena = pic_realloc(pic, pic->arena, sizeof(struct pic_object *) * pic->arena_size); } pic->arena[pic->arena_idx++] = obj; } pic_value pic_gc_protect(pic_state *pic, pic_value v) { struct pic_object *obj; if (pic_vtype(v) != PIC_VTYPE_HEAP) { return v; } obj = pic_obj_ptr(v); gc_protect(pic, obj); return v; } size_t pic_gc_arena_preserve(pic_state *pic) { return pic->arena_idx; } void pic_gc_arena_restore(pic_state *pic, size_t state) { pic->arena_idx = state; } static void * gc_alloc(pic_state *pic, size_t size) { union header *freep, *p, *prevp; size_t nunits; #if GC_DEBUG assert(size > 0); #endif nunits = (size + sizeof(union header) - 1) / sizeof(union header) + 1; prevp = freep = pic->heap->freep; for (p = prevp->s.ptr; ; prevp = p, p = p->s.ptr) { if (p->s.size >= nunits) break; if (p == freep) { return NULL; } } #if GC_DEBUG { unsigned char *c; size_t s, i, j; if (p->s.size == nunits) { c = (unsigned char *)(p + p->s.size - nunits + 1); s = nunits - 1; } else { c = (unsigned char *)(p + p->s.size - nunits); s = nunits; } for (i = 0; i < s; ++i) { for (j = 0; j < sizeof(union header); ++j) { assert(c[i * sizeof(union header) + j] == 0xAA); } } } #endif if (p->s.size == nunits) { prevp->s.ptr = p->s.ptr; } else { p->s.size -= nunits; p += p->s.size; p->s.size = nunits; } pic->heap->freep = prevp; p->s.mark = PIC_GC_UNMARK; #if GC_DEBUG memset(p+1, 0, sizeof(union header) * (nunits - 1)); p->s.ptr = (union header *)0xcafebabe; #endif return (void *)(p + 1); } static void gc_free(pic_state *pic, union header *bp) { union header *freep, *p; #if GC_DEBUG assert(bp != NULL); assert(bp->s.size > 1); #endif #if GC_DEBUG memset(bp + 1, 0xAA, (bp->s.size - 1) * sizeof(union header)); #endif freep = pic->heap->freep; for (p = freep; ! (bp > p && bp < p->s.ptr); p = p->s.ptr) { if (p >= p->s.ptr && (bp > p || bp < p->s.ptr)) { break; } } if (bp + bp->s.size == p->s.ptr) { bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; #if GC_DEBUG memset(p->s.ptr, 0xAA, sizeof(union header)); #endif } else { bp->s.ptr = p->s.ptr; } if (p + p->s.size == bp && p->s.size > 1) { p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; #if GC_DEBUG memset(bp, 0xAA, sizeof(union header)); #endif } else { p->s.ptr = bp; } pic->heap->freep = p; } static void gc_mark(pic_state *, pic_value); static void gc_mark_object(pic_state *pic, struct pic_object *obj); static bool gc_is_marked(union header *p) { return p->s.mark == PIC_GC_MARK; } static bool gc_obj_is_marked(struct pic_object *obj) { union header *p; p = ((union header *)obj) - 1; return gc_is_marked(p); } static void gc_unmark(union header *p) { p->s.mark = PIC_GC_UNMARK; } static void gc_mark_winder(pic_state *pic, struct pic_winder *wind) { if (wind->prev) { gc_mark_object(pic, (struct pic_object *)wind->prev); } if (wind->in) { gc_mark_object(pic, (struct pic_object *)wind->in); } if (wind->out) { gc_mark_object(pic, (struct pic_object *)wind->out); } } static void gc_mark_object(pic_state *pic, struct pic_object *obj) { union header *p; p = ((union header *)obj) - 1; if (gc_is_marked(p)) return; p->s.mark = PIC_GC_MARK; switch (obj->tt) { case PIC_TT_PAIR: { gc_mark(pic, ((struct pic_pair *)obj)->car); gc_mark(pic, ((struct pic_pair *)obj)->cdr); break; } case PIC_TT_ENV: { struct pic_env *env = (struct pic_env *)obj; int i; for (i = 0; i < env->regc; ++i) { gc_mark(pic, env->regs[i]); } if (env->up) { gc_mark_object(pic, (struct pic_object *)env->up); } break; } case PIC_TT_PROC: { struct pic_proc *proc = (struct pic_proc *)obj; if (proc->env) { gc_mark_object(pic, (struct pic_object *)proc->env); } if (pic_proc_irep_p(proc)) { gc_mark_object(pic, (struct pic_object *)proc->u.irep); } else { gc_mark_object(pic, (struct pic_object *)proc->u.func.name); } break; } case PIC_TT_PORT: { break; } case PIC_TT_ERROR: { struct pic_error *err = (struct pic_error *)obj; gc_mark_object(pic, (struct pic_object *)err->type); gc_mark_object(pic, (struct pic_object *)err->msg); gc_mark(pic, err->irrs); gc_mark_object(pic, (struct pic_object *)err->stack); break; } case PIC_TT_STRING: { break; } case PIC_TT_VECTOR: { size_t i; for (i = 0; i < ((struct pic_vector *)obj)->len; ++i) { gc_mark(pic, ((struct pic_vector *)obj)->data[i]); } break; } case PIC_TT_BLOB: { break; } case PIC_TT_SENV: { struct pic_senv *senv = (struct pic_senv *)obj; if (senv->up) { gc_mark_object(pic, (struct pic_object *)senv->up); } gc_mark(pic, senv->defer); gc_mark_object(pic, (struct pic_object *)senv->map); break; } case PIC_TT_LIB: { struct pic_lib *lib = (struct pic_lib *)obj; gc_mark(pic, lib->name); gc_mark_object(pic, (struct pic_object *)lib->env); gc_mark_object(pic, (struct pic_object *)lib->exports); break; } case PIC_TT_IREP: { struct pic_irep *irep = (struct pic_irep *)obj; size_t i; gc_mark_object(pic, (struct pic_object *)irep->name); for (i = 0; i < irep->ilen; ++i) { gc_mark_object(pic, (struct pic_object *)irep->irep[i]); } for (i = 0; i < irep->plen; ++i) { gc_mark(pic, irep->pool[i]); } for (i = 0; i < irep->slen; ++i) { gc_mark_object(pic, (struct pic_object *)irep->syms[i]); } break; } case PIC_TT_DATA: { struct pic_data *data = (struct pic_data *)obj; xh_entry *it; for (it = xh_begin(&data->storage); it != NULL; it = xh_next(it)) { gc_mark(pic, xh_val(it, pic_value)); } if (data->type->mark) { data->type->mark(pic, data->data, gc_mark); } break; } case PIC_TT_DICT: { struct pic_dict *dict = (struct pic_dict *)obj; xh_entry *it; for (it = xh_begin(&dict->hash); it != NULL; it = xh_next(it)) { gc_mark_object(pic, (struct pic_object *)xh_key(it, pic_sym *)); gc_mark(pic, xh_val(it, pic_value)); } break; } case PIC_TT_RECORD: { struct pic_record *rec = (struct pic_record *)obj; gc_mark_object(pic, (struct pic_object *)rec->data); break; } case PIC_TT_SYMBOL: { struct pic_symbol *sym = (struct pic_symbol *)obj; gc_mark_object(pic, (struct pic_object *)sym->str); break; } case PIC_TT_NIL: case PIC_TT_BOOL: #if PIC_ENABLE_FLOAT case PIC_TT_FLOAT: #endif case PIC_TT_INT: case PIC_TT_CHAR: case PIC_TT_EOF: case PIC_TT_UNDEF: pic_panic(pic, "logic flaw"); } } static void gc_mark(pic_state *pic, pic_value v) { struct pic_object *obj; if (pic_vtype(v) != PIC_VTYPE_HEAP) return; obj = pic_obj_ptr(v); gc_mark_object(pic, obj); } #define M(x) gc_mark_object(pic, (struct pic_object *)pic->x) static void gc_mark_global_symbols(pic_state *pic) { M(sDEFINE); M(sLAMBDA); M(sIF); M(sBEGIN); M(sQUOTE); M(sSETBANG); M(sQUASIQUOTE); M(sUNQUOTE); M(sUNQUOTE_SPLICING); M(sDEFINE_SYNTAX); M(sIMPORT); M(sEXPORT); M(sDEFINE_LIBRARY); M(sIN_LIBRARY); M(sCOND_EXPAND); M(sAND); M(sOR); M(sELSE); M(sLIBRARY); M(sONLY); M(sRENAME); M(sPREFIX); M(sEXCEPT); M(sCONS); M(sCAR); M(sCDR); M(sNILP); M(sSYMBOLP); M(sPAIRP); M(sADD); M(sSUB); M(sMUL); M(sDIV); M(sMINUS); M(sEQ); M(sLT); M(sLE); M(sGT); M(sGE); M(sNOT); M(sREAD); M(sFILE); M(sCALL); M(sTAILCALL); M(sCALL_WITH_VALUES); M(sTAILCALL_WITH_VALUES); M(sGREF); M(sLREF); M(sCREF); M(sRETURN); M(rDEFINE); M(rLAMBDA); M(rIF); M(rBEGIN); M(rQUOTE); M(rSETBANG); M(rDEFINE_SYNTAX); M(rIMPORT); M(rEXPORT); M(rDEFINE_LIBRARY); M(rIN_LIBRARY); M(rCOND_EXPAND); } static void gc_mark_phase(pic_state *pic) { pic_value *stack; pic_callinfo *ci; struct pic_proc **xhandler; size_t j; xh_entry *it; struct pic_object *obj; /* winder */ if (pic->wind) { gc_mark_winder(pic, pic->wind); } /* stack */ for (stack = pic->stbase; stack != pic->sp; ++stack) { gc_mark(pic, *stack); } /* callinfo */ for (ci = pic->ci; ci != pic->cibase; --ci) { if (ci->env) { gc_mark_object(pic, (struct pic_object *)ci->env); } } /* exception handlers */ for (xhandler = pic->xpbase; xhandler != pic->xp; ++xhandler) { gc_mark_object(pic, (struct pic_object *)*xhandler); } /* arena */ for (j = 0; j < pic->arena_idx; ++j) { gc_mark_object(pic, pic->arena[j]); } /* mark reserved symbols */ gc_mark_global_symbols(pic); /* global variables */ if (pic->globals) { gc_mark_object(pic, (struct pic_object *)pic->globals); } /* macro objects */ if (pic->macros) { gc_mark_object(pic, (struct pic_object *)pic->macros); } /* error object */ gc_mark(pic, pic->err); /* features */ gc_mark(pic, pic->features); /* library table */ gc_mark(pic, pic->libs); /* standard I/O ports */ if (pic->xSTDIN) { gc_mark_object(pic, (struct pic_object *)pic->xSTDIN); } if (pic->xSTDOUT) { gc_mark_object(pic, (struct pic_object *)pic->xSTDOUT); } if (pic->xSTDERR) { gc_mark_object(pic, (struct pic_object *)pic->xSTDERR); } /* attributes */ do { j = 0; for (it = xh_begin(&pic->attrs); it != NULL; it = xh_next(it)) { if (gc_obj_is_marked(xh_key(it, struct pic_object *))) { obj = (struct pic_object *)xh_val(it, struct pic_dict *); if (! gc_obj_is_marked(obj)) { gc_mark_object(pic, obj); ++j; } } } } while (j > 0); } static void gc_finalize_object(pic_state *pic, struct pic_object *obj) { #if GC_DEBUG printf("* finalizing object: %s", pic_type_repr(pic_type(pic_obj_value(obj)))); // pic_debug(pic, pic_obj_value(obj)); puts(""); #endif switch (obj->tt) { case PIC_TT_PAIR: { break; } case PIC_TT_ENV: { break; } case PIC_TT_PROC: { break; } case PIC_TT_VECTOR: { pic_free(pic, ((struct pic_vector *)obj)->data); break; } case PIC_TT_BLOB: { pic_free(pic, ((struct pic_blob *)obj)->data); break; } case PIC_TT_STRING: { pic_rope_decref(pic, ((struct pic_string *)obj)->rope); break; } case PIC_TT_PORT: { break; } case PIC_TT_ERROR: { break; } case PIC_TT_SENV: { break; } case PIC_TT_LIB: { break; } case PIC_TT_IREP: { struct pic_irep *irep = (struct pic_irep *)obj; pic_free(pic, irep->code); pic_free(pic, irep->irep); pic_free(pic, irep->pool); pic_free(pic, irep->syms); break; } case PIC_TT_DATA: { struct pic_data *data = (struct pic_data *)obj; data->type->dtor(pic, data->data); xh_destroy(&data->storage); break; } case PIC_TT_DICT: { struct pic_dict *dict = (struct pic_dict *)obj; xh_destroy(&dict->hash); break; } case PIC_TT_RECORD: { break; } case PIC_TT_SYMBOL: { break; } case PIC_TT_NIL: case PIC_TT_BOOL: #if PIC_ENABLE_FLOAT case PIC_TT_FLOAT: #endif case PIC_TT_INT: case PIC_TT_CHAR: case PIC_TT_EOF: case PIC_TT_UNDEF: pic_panic(pic, "logic flaw"); } } static void gc_sweep_symbols(pic_state *pic) { xh_entry *it; xvect_t(xh_entry *) xv; size_t i; char *cstr; xv_init(xv); for (it = xh_begin(&pic->syms); it != NULL; it = xh_next(it)) { if (! gc_obj_is_marked((struct pic_object *)xh_val(it, pic_sym *))) { xv_push(xh_entry *, xv, it); } } for (i = 0; i < xv_size(xv); ++i) { cstr = xh_key(xv_A(xv, i), char *); xh_del_str(&pic->syms, cstr); pic_free(pic, cstr); } } static void gc_sweep_page(pic_state *pic, struct heap_page *page) { #if GC_DEBUG static union header *NIL = (union header *)0xdeadbeef; #else static union header *NIL = NULL; #endif union header *bp, *p, *s = NIL, *t = NIL; #if GC_DEBUG int c = 0; #endif for (bp = page->basep; ; bp = bp->s.ptr) { for (p = bp + bp->s.size; p != bp->s.ptr; p += p->s.size) { if (p == page->endp) { goto escape; } if (! gc_is_marked(p)) { if (s == NIL) { s = p; } else { t->s.ptr = p; } t = p; t->s.ptr = NIL; /* For dead objects we can safely reuse ptr field */ } gc_unmark(p); } } escape: /* free! */ while (s != NIL) { t = s->s.ptr; gc_finalize_object(pic, (struct pic_object *)(s + 1)); gc_free(pic, s); s = t; #if GC_DEBUG c++; #endif } #if GC_DEBUG printf("freed objects count: %d\n", c); #endif } static void gc_sweep_phase(pic_state *pic) { struct heap_page *page = pic->heap->pages; xh_entry *it, *next; do { for (it = xh_begin(&pic->attrs); it != NULL; it = next) { next = xh_next(it); if (! gc_obj_is_marked(xh_key(it, struct pic_object *))) { xh_del_ptr(&pic->attrs, xh_key(it, struct pic_object *)); } } } while (it != NULL); gc_sweep_symbols(pic); while (page) { gc_sweep_page(pic, page); page = page->next; } } void pic_gc_run(pic_state *pic) { #if GC_DEBUG struct heap_page *page; #endif if (! pic->gc_enable) { return; } #if DEBUG printf("gc run!"); #endif gc_mark_phase(pic); gc_sweep_phase(pic); #if GC_DEBUG for (page = pic->heap->pages; page; page = page->next) { union header *bp, *p; unsigned char *c; for (bp = page->basep; ; bp = bp->s.ptr) { for (c = (unsigned char *)(bp+1); c != (unsigned char *)(bp + bp->s.size); ++c) { assert(*c == 0xAA); } for (p = bp + bp->s.size; p != bp->s.ptr; p += p->s.size) { if (p == page->endp) { /* if (page->next) */ /* assert(bp->s.ptr == page->next->basep); */ /* else */ /* assert(bp->s.ptr == &pic->heap->base); */ goto escape; } assert(! gc_is_marked(p)); } } escape: ((void)0); } puts("not error on heap found! gc successfully finished"); #endif } struct pic_object * pic_obj_alloc_unsafe(pic_state *pic, size_t size, enum pic_tt tt) { struct pic_object *obj; #if GC_DEBUG printf("*allocating: %s\n", pic_type_repr(tt)); #endif #if GC_STRESS pic_gc_run(pic); #endif obj = (struct pic_object *)gc_alloc(pic, size); if (obj == NULL) { pic_gc_run(pic); obj = (struct pic_object *)gc_alloc(pic, size); if (obj == NULL) { add_heap_page(pic); obj = (struct pic_object *)gc_alloc(pic, size); if (obj == NULL) pic_panic(pic, "GC memory exhausted"); } } obj->tt = tt; return obj; } struct pic_object * pic_obj_alloc(pic_state *pic, size_t size, enum pic_tt tt) { struct pic_object *obj; obj = pic_obj_alloc_unsafe(pic, size, tt); gc_protect(pic, obj); return obj; }
2.59375
3
2024-11-18T22:09:27.003493+00:00
2023-08-16T08:50:33
38b25ae97b304cd271ed40d41643916bf373b0a8
{ "blob_id": "38b25ae97b304cd271ed40d41643916bf373b0a8", "branch_name": "refs/heads/master", "committer_date": "2023-08-18T09:13:27", "content_id": "700653698e0c1cd5258fdaddb287432e05048a2b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "55540f3e86f1d5d86ef6b5d295a63518e274efe3", "extension": "c", "filename": "monitor.c", "fork_events_count": 101, "gha_created_at": "2020-10-26T11:16:30", "gha_event_created_at": "2023-08-28T06:29:02", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 307347250, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 598, "license": "Apache-2.0", "license_type": "permissive", "path": "/components/network/ble/blestack/src/host/monitor.c", "provenance": "stackv2-0106.json.gz:33933", "repo_name": "bouffalolab/bl_iot_sdk", "revision_date": "2023-08-16T08:50:33", "revision_id": "b90664de0bd4c1897a9f1f5d9e360a9631d38b34", "snapshot_id": "bc5eaf036b70f8c65dd389439062b169f8d09daa", "src_encoding": "UTF-8", "star_events_count": 244, "url": "https://raw.githubusercontent.com/bouffalolab/bl_iot_sdk/b90664de0bd4c1897a9f1f5d9e360a9631d38b34/components/network/ble/blestack/src/host/monitor.c", "visit_date": "2023-08-31T03:38:03.369853" }
stackv2
/** @file * @brief Custom logging over UART */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #if defined(CONFIG_BT_DEBUG_MONITOR) #include <zephyr.h> #include <buf.h> #include "monitor.h" #include "log.h" void bt_monitor_send(uint16_t opcode, const void *data, size_t len) { const uint8_t *buf = data; unsigned int key = irq_lock(); BT_WARN("[Hci]:pkt_type:[0x%x],pkt_data:[%s]\r\n",opcode,bt_hex(buf,len)); irq_unlock(key); } void bt_monitor_new_index(uint8_t type, uint8_t bus, bt_addr_t *addr, const char *name) { } #endif
2.125
2
2024-11-18T22:09:27.364358+00:00
2023-08-16T11:44:49
9388fa42ebbc9b80abdc7020eda3b3bd388869f8
{ "blob_id": "9388fa42ebbc9b80abdc7020eda3b3bd388869f8", "branch_name": "refs/heads/master", "committer_date": "2023-08-16T11:44:49", "content_id": "fc8177873cde1e5701cb6c4b6f06d4fec36db104", "detected_licenses": [ "Apache-2.0" ], "directory_id": "45400bf1909326a9cb932b9cfc4e19187cb3c30a", "extension": "c", "filename": "vfs.c", "fork_events_count": 0, "gha_created_at": "2022-05-01T15:43:52", "gha_event_created_at": "2022-05-01T15:43:53", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 487576029, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16361, "license": "Apache-2.0", "license_type": "permissive", "path": "/system/basic/libs/libc/sys/src/vfs.c", "provenance": "stackv2-0106.json.gz:34322", "repo_name": "tonytsangzen/EwokOS", "revision_date": "2023-08-16T11:44:49", "revision_id": "f298275b28367157aa794d85fcfcc797e00eda79", "snapshot_id": "f46cd99435ccea213ebb14fb05a6a2f057e6907b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tonytsangzen/EwokOS/f298275b28367157aa794d85fcfcc797e00eda79/system/basic/libs/libc/sys/src/vfs.c", "visit_date": "2023-08-17T20:50:44.551533" }
stackv2
#include <sys/vfs.h> #include <string.h> #include <sys/syscall.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <sys/mstr.h> #include <sys/shm.h> #include <sys/ipc.h> #include <sys/vfsc.h> #include <sys/proc.h> #ifdef __cplusplus extern "C" { #endif typedef struct { int fd; fsinfo_t info; } fsinfo_buffer_t; #define MAX_FINFO_BUFFER 8 static fsinfo_buffer_t _fsinfo_buffers[MAX_FINFO_BUFFER]; void vfs_init(void) { for(uint32_t i=0; i<MAX_FINFO_BUFFER; i++) _fsinfo_buffers[i].fd = -1; } static int vfs_get_by_fd_raw(int fd, fsinfo_t* info) { proto_t in, out; PF->init(&in)->addi(&in, fd); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_GET_BY_FD, &in, &out); PF->clear(&in); if(res == 0) { if(info != NULL) proto_read_to(&out, info, sizeof(fsinfo_t)); } PF->clear(&out); return res; } static inline void vfs_set_info_buffer(int fd, fsinfo_t* info) { for(uint32_t i=0; i<MAX_FINFO_BUFFER; i++) { if(_fsinfo_buffers[i].fd < 0) { _fsinfo_buffers[i].fd = fd; memcpy(&_fsinfo_buffers[i].info, info, sizeof(fsinfo_t)); return; } } } static inline void vfs_clear_info_buffer(int fd) { for(uint32_t i=0; i<MAX_FINFO_BUFFER; i++) { if(_fsinfo_buffers[i].fd == fd) { _fsinfo_buffers[i].fd = -1; return; } } } static inline int vfs_fetch_info_buffer(int fd, fsinfo_t* info) { for(uint32_t i=0; i<MAX_FINFO_BUFFER; i++) { if(_fsinfo_buffers[i].fd == fd) { memcpy(info, &_fsinfo_buffers[i].info, sizeof(fsinfo_t)); return 0; } } return -1; } int vfs_get_by_fd(int fd, fsinfo_t* info) { if(vfs_fetch_info_buffer(fd, info) == 0) return 0; int res = vfs_get_by_fd_raw(fd, info); if(res == 0 && fd > 3) { vfs_set_info_buffer(fd, info); } return res; } int vfs_new_node(fsinfo_t* info) { proto_t in, out; PF->init(&in)->add(&in, info, sizeof(fsinfo_t)); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_NEW_NODE, &in, &out); PF->clear(&in); if(res == 0) proto_read_to(&out, info, sizeof(fsinfo_t)); PF->clear(&out); return res; } const char* vfs_fullname(const char* fname) { str_t* fullname = str_new(""); if(fname[0] == '/') { str_cpy(fullname, fname); } else { char pwd[FS_FULL_NAME_MAX]; getcwd(pwd, FS_FULL_NAME_MAX-1); str_cpy(fullname, pwd); if(pwd[1] != 0) str_addc(fullname, '/'); str_add(fullname, fname); } static char ret[FS_FULL_NAME_MAX]; strncpy(ret, fullname->cstr, FS_FULL_NAME_MAX-1); str_free(fullname); return ret; } int vfs_open(fsinfo_t* info, int oflag) { proto_t in, out; PF->init(&in)->add(&in, info, sizeof(fsinfo_t))->addi(&in, oflag); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_OPEN, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); vfs_set_info_buffer(res, info); } PF->clear(&out); return res; } static int read_pipe(fsinfo_t* info, void* buf, uint32_t size, bool block) { proto_t in, out; PF->init(&in)->add(&in, info, sizeof(fsinfo_t))->addi(&in, size)->addi(&in, block?1:0); PF->init(&out); int vfsd_pid = get_vfsd_pid(); int res = ipc_call(vfsd_pid, VFS_PIPE_READ, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); if(res > 0) res = proto_read_to(&out, buf, size); } PF->clear(&out); if(res == 0 && block == 1) {//empty , do retry proc_block(vfsd_pid, info->node); } return res; } static int write_pipe(fsinfo_t* info, const void* buf, uint32_t size, bool block) { proto_t in, out; PF->init(&in)->add(&in, info, sizeof(fsinfo_t))->add(&in, buf, size)->addi(&in, block?1:0); PF->init(&out); int vfsd_pid = get_vfsd_pid(); int res = ipc_call(vfsd_pid, VFS_PIPE_WRITE, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); } PF->clear(&out); if(res == 0 && block == 1) {//empty , do retry proc_block(vfsd_pid, info->node); } return res; } int vfs_dup(int fd) { proto_t in, out; PF->init(&in)->addi(&in, fd); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_DUP, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); } PF->clear(&out); return res; } int vfs_close(int fd) { proto_t in; PF->init(&in)->addi(&in, fd); int res = ipc_call(get_vfsd_pid(), VFS_CLOSE, &in, NULL); PF->clear(&in); vfs_clear_info_buffer(fd); return res; } int vfs_dup2(int fd, int to) { proto_t in, out; PF->init(&in)->addi(&in, fd)->addi(&in, to); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_DUP2, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); } PF->clear(&out); return res; } int vfs_open_pipe(int fd[2]) { proto_t out; PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_PIPE_OPEN, NULL, &out); if(res == 0) { if(proto_read_int(&out) == 0) { fd[0] = proto_read_int(&out); fd[1] = proto_read_int(&out); } else { res = -1; } } PF->clear(&out); return res; } int vfs_get(const char* fname, fsinfo_t* info) { fname = vfs_fullname(fname); proto_t in, out; PF->init(&in)->adds(&in, fname); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_GET_BY_NAME, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); //res = node if(res != 0) { if(info != NULL) proto_read_to(&out, info, sizeof(fsinfo_t)); res = 0; } else res = -1; } PF->clear(&out); return res; } int vfs_access(const char* fname) { return vfs_get(fname, NULL); } fsinfo_t* vfs_kids(fsinfo_t* info, uint32_t *num) { proto_t in, out; PF->init(&in)->add(&in, info, sizeof(fsinfo_t)); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_GET_KIDS, &in, &out); PF->clear(&in); fsinfo_t* ret = NULL; if(res == 0) { uint32_t n = proto_read_int(&out); *num = n; if(n > 0) { ret = (fsinfo_t*)malloc(n * sizeof(fsinfo_t)); proto_read_to(&out, ret, n * sizeof(fsinfo_t)); } } PF->clear(&out); return ret; } int vfs_set(fsinfo_t* info) { proto_t in, out; PF->init(&in)->add(&in, info, sizeof(fsinfo_t)); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_SET_FSINFO, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); } PF->clear(&out); return res; } int vfs_add(fsinfo_t* to, fsinfo_t* info) { proto_t in, out; PF->init(&in)-> add(&in, to, sizeof(fsinfo_t))-> add(&in, info, sizeof(fsinfo_t)); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_ADD, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); } PF->clear(&out); return res; } int vfs_del(fsinfo_t* info) { proto_t in, out; PF->init(&in)->add(&in, info, sizeof(fsinfo_t)); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_DEL, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); } PF->clear(&out); return res; } /* int vfs_get_mount(fsinfo_t* info, mount_t* mount) { proto_t in, out; PF->init(&in)->add(&in, info, sizeof(fsinfo_t)); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_GET_MOUNT, &in, &out); PF->clear(&in); if(res == 0) { proto_read_to(&out, mount, sizeof(mount_t)); } PF->clear(&out); return res; } */ int vfs_get_mount_by_id(int id, mount_t* mount) { proto_t in, out; PF->init(&in)->addi(&in, id); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_GET_MOUNT_BY_ID, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); if(res == 0) proto_read_to(&out, mount, sizeof(mount_t)); } PF->clear(&out); return res; } int vfs_mount(fsinfo_t* mount_to, fsinfo_t* info) { proto_t in, out; PF->init(&in)-> add(&in, mount_to, sizeof(fsinfo_t))-> add(&in, info, sizeof(fsinfo_t)); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_MOUNT, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); } PF->clear(&out); return res; } int vfs_umount(fsinfo_t* info) { proto_t in, out; PF->init(&in)->add(&in, info, sizeof(fsinfo_t)); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_UMOUNT, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); } PF->clear(&out); return res; } int vfs_tell(int fd) { proto_t in, out; PF->init(&in)->addi(&in, fd); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_TELL, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); } PF->clear(&out); return res; } int vfs_seek(int fd, int offset) { proto_t in, out; PF->init(&in)->addi(&in, fd)->addi(&in, offset); PF->init(&out); int res = ipc_call(get_vfsd_pid(), VFS_SEEK, &in, &out); PF->clear(&in); if(res == 0) { res = proto_read_int(&out); } PF->clear(&out); if(res >= 0) return 0; return -1; } void* vfs_readfile(const char* fname, int* rsz) { fname = vfs_fullname(fname); fsinfo_t info; if(vfs_get(fname, &info) != 0 || info.size <= 0) return NULL; void* buf = malloc(info.size+1); //one more char for string end. if(buf == NULL) return NULL; char* p = (char*)buf; int fd = open(fname, O_RDONLY); int fsize = info.size; if(fd >= 0) { while(fsize > 0) { int sz = read(fd, p, fsize); if(sz < 0 && errno != EAGAIN) break; if(sz > 0) { fsize -= sz; p += sz; } } close(fd); } if(fsize != 0) { free(buf); return NULL; } if(rsz != NULL) *rsz = info.size; return buf; } int vfs_create(const char* fname, fsinfo_t* ret, int type, bool vfs_node_only, bool autodir) { str_t *dir = str_new(""); str_t *name = str_new(""); vfs_parse_name(fname, dir, name); fsinfo_t info_to; if(vfs_get(CS(dir), &info_to) != 0) { int res_dir = -1; if(autodir) res_dir = vfs_create(CS(dir), &info_to, FS_TYPE_DIR, false, autodir); if(res_dir != 0) { str_free(dir); str_free(name); return -1; } } /*mount_t mount; if(vfs_get_mount(&info_to, &mount) != 0) { str_free(dir); str_free(name); return -1; } */ memset(ret, 0, sizeof(fsinfo_t)); strcpy(ret->name, CS(name)); ret->type = type; str_free(name); str_free(dir); vfs_new_node(ret); if(vfs_add(&info_to, ret) != 0) { vfs_del(ret); return -1; } if(vfs_node_only) return 0; if(type == FS_TYPE_DIR) ret->size = 1024; ret->mount_pid = info_to.mount_pid; proto_t in, out; PF->init(&out); PF->init(&in)-> add(&in, &info_to, sizeof(fsinfo_t))-> add(&in, ret, sizeof(fsinfo_t)); int res = -1; if(ipc_call(info_to.mount_pid, FS_CMD_CREATE, &in, &out) != 0) { vfs_del(ret); } else { res = proto_read_int(&out); if(res == 0) { proto_read_to(&out, ret, sizeof(fsinfo_t)); res = vfs_set(ret); } else vfs_del(ret); } PF->clear(&in); PF->clear(&out); return res; } int vfs_parse_name(const char* fname, str_t* dir, str_t* name) { str_t* fullstr = str_new(vfs_fullname(fname)); char* full = (char*)CS(fullstr); int i = strlen(full); while(i >= 0) { if(full[i] == '/') { full[i] = 0; break; } --i; } str_cpy(dir, full); str_cpy(name, full+i+1); if(CS(dir)[0] == 0) str_cpy(dir, "/"); str_free(fullstr); return 0; } int vfs_fcntl(int fd, int cmd, proto_t* arg_in, proto_t* arg_out) { fsinfo_t info; if(vfs_get_by_fd(fd, &info) != 0) return -1; proto_t in; PF->init(&in)-> addi(&in, fd)-> add(&in, &info, sizeof(fsinfo_t))-> addi(&in, cmd); if(arg_in == NULL) PF->add(&in, NULL, 0); else PF->add(&in, arg_in->data, arg_in->size); int res = -1; if(arg_out != NULL) { proto_t out; PF->init(&out); if(ipc_call(info.mount_pid, FS_CMD_CNTL, &in, &out) == 0) { res = proto_read_int(&out); if(arg_out != NULL) { int32_t sz; void *p = proto_read(&out, &sz); PF->copy(arg_out, p, sz); } } PF->clear(&in); PF->clear(&out); } else { res = ipc_call(info.mount_pid, FS_CMD_CNTL, &in, NULL); PF->clear(&in); } return res; } int vfs_dma(int fd, int* size) { fsinfo_t info; if(vfs_get_by_fd(fd, &info) != 0) return -1; proto_t in, out; PF->init(&out); PF->init(&in)-> addi(&in, fd)-> add(&in, &info, sizeof(fsinfo_t)); int shm_id = -1; if(ipc_call(info.mount_pid, FS_CMD_DMA, &in, &out) == 0) { shm_id = proto_read_int(&out); if(size != NULL) *size = proto_read_int(&out); } PF->clear(&in); PF->clear(&out); return shm_id; } int vfs_flush(int fd, bool wait) { fsinfo_t info; if(vfs_get_by_fd(fd, &info) != 0) return 0; //error proto_t in; PF->init(&in)-> addi(&in, fd)-> add(&in, &info, sizeof(fsinfo_t)); int res = -1; if(wait) ipc_call_wait(info.mount_pid, FS_CMD_FLUSH, &in, NULL); else ipc_call(info.mount_pid, FS_CMD_FLUSH, &in, NULL); PF->clear(&in); return res; } int vfs_write_block(int pid, const void* buf, uint32_t size, int32_t index) { proto_t in, out; PF->init(&out); PF->init(&in)-> add(&in, buf, size)-> addi(&in, index); int res = -1; if(ipc_call(pid, FS_CMD_WRITE_BLOCK, &in, &out) == 0) { int r = proto_read_int(&out); res = r; if(res == -2) { errno = EAGAIN; res = -1; } } PF->clear(&in); PF->clear(&out); return res; } int vfs_read_block(int pid, void* buf, uint32_t size, int32_t index) { int32_t shm_id = -1; void* shm = NULL; shm_id = shm_alloc(size, SHM_PUBLIC); if(shm_id < 0) return -1; shm = shm_map(shm_id); if(shm == NULL) return -1; proto_t in, out; PF->init(&out); PF->init(&in)-> addi(&in, size)-> addi(&in, index)-> addi(&in, shm_id); int res = -1; if(ipc_call(pid, FS_CMD_READ_BLOCK, &in, &out) == 0) { int rd = proto_read_int(&out); res = rd; if(rd > 0) { memcpy(buf, shm, rd); } if(res == ERR_RETRY) { errno = EAGAIN; res = -1; } } PF->clear(&in); PF->clear(&out); shm_unmap(shm_id); return res; } int vfs_read_pipe(fsinfo_t* info, void* buf, uint32_t size, bool block) { int res = read_pipe(info, buf, size, block); if(res == 0) { // pipe empty, do retry errno = EAGAIN; return -1; } if(res > 0) { return res; } return 0; //res < 0 , pipe closed, return 0. } #define SHM_ON 32 int vfs_read(int fd, fsinfo_t *info, void* buf, uint32_t size) { /*mount_t mount; if(vfs_get_mount(info, &mount) != 0) return -1; */ int offset = 0; if(info->type == FS_TYPE_FILE) { offset = vfs_tell(fd); if(offset < 0) offset = 0; } int32_t shm_id = -1; void* shm = NULL; if(size >= SHM_ON) { shm_id = shm_alloc(size, SHM_PUBLIC); if(shm_id < 0) return -1; shm = shm_map(shm_id); if(shm == NULL) return -1; } proto_t in, out; PF->init(&out); PF->init(&in)->addi(&in, fd)->add(&in, info, sizeof(fsinfo_t))->addi(&in, size)->addi(&in, offset)->addi(&in, shm_id); int res = -1; if(ipc_call(info->mount_pid, FS_CMD_READ, &in, &out) == 0) { int rd = proto_read_int(&out); res = rd; if(rd > 0) { if(shm != NULL) memcpy(buf, shm, rd); else proto_read_to(&out, buf, size); offset += rd; if(info->type == FS_TYPE_FILE) vfs_seek(fd, offset); } if(res == ERR_RETRY) { errno = EAGAIN; res = -1; } else if(res == ERR_RETRY_NON_BLOCK) { errno = EAGAIN_NON_BLOCK; res = -1; } } PF->clear(&in); PF->clear(&out); if(shm != NULL) shm_unmap(shm_id); return res; } int vfs_write_pipe(fsinfo_t* info, const void* buf, uint32_t size, bool block) { int res = write_pipe(info, buf, size, block); if(res == 0) { // pipe not empty, do retry errno = EAGAIN; return -1; } if(res > 0) return res; return 0; //res < 0 , pipe closed, return 0. } int vfs_write(int fd, fsinfo_t* info, const void* buf, uint32_t size) { if(info->type == FS_TYPE_DIR) return -1; /*mount_t mount; if(vfs_get_mount(info, &mount) != 0) return -1; */ int offset = 0; if(info->type == FS_TYPE_FILE) { offset = vfs_tell(fd); if(offset < 0) offset = 0; } int32_t shm_id = -1; void* shm = NULL; if(size >= SHM_ON) { shm_id = shm_alloc(size, SHM_PUBLIC); if(shm_id < 0) return -1; shm = shm_map(shm_id); if(shm == NULL) return -1; memcpy(shm, buf, size); } proto_t in, out; PF->init(&out); PF->init(&in)-> addi(&in, fd)-> add(&in, info, sizeof(fsinfo_t))-> addi(&in, offset)-> addi(&in, shm_id); if(shm_id < 0) PF->add(&in, buf, size); else PF->addi(&in, size); int res = -1; if(ipc_call(info->mount_pid, FS_CMD_WRITE, &in, &out) == 0) { int r = proto_read_int(&out); res = r; if(r > 0) { offset += r; if(info->type == FS_TYPE_FILE) vfs_seek(fd, offset); } if(res == -2) { errno = EAGAIN; res = -1; } } PF->clear(&in); PF->clear(&out); if(shm != NULL) shm_unmap(shm_id); return res; } #ifdef __cplusplus } #endif
2.4375
2
2024-11-18T22:09:27.876716+00:00
2020-10-13T23:48:21
eb02ec233bd7c7ecddf91a862451fac29eb2e46e
{ "blob_id": "eb02ec233bd7c7ecddf91a862451fac29eb2e46e", "branch_name": "refs/heads/master", "committer_date": "2020-10-13T23:48:21", "content_id": "735447edc509b929629bf2aeb162d3de57b47be0", "detected_licenses": [ "MIT" ], "directory_id": "4313bed1e5ff66a9ef9ef01dfa6bbd969e6b4f77", "extension": "h", "filename": "rts.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": 2166, "license": "MIT", "license_type": "permissive", "path": "/inc/rts.h", "provenance": "stackv2-0106.json.gz:34709", "repo_name": "MaryChek/RT_metal", "revision_date": "2020-10-13T23:48:21", "revision_id": "9c48ff633a59bc35a9790b4c7351032fd80c584b", "snapshot_id": "d3bbbd3e1e51b3f2e3a1b4fbe11110a77d8f3b4c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MaryChek/RT_metal/9c48ff633a59bc35a9790b4c7351032fd80c584b/inc/rts.h", "visit_date": "2022-12-30T10:44:31.608813" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rt_s.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kcharla <kcharla@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/07 13:17:15 by kcharla #+# #+# */ /* Updated: 2020/10/13 00:58:26 by kcharla ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef RTS_H # define RTS_H /* ** RT Struct */ # include "libft.h" # include "mlx.h" # include "rtc_scn.h" /* ** We cannot store (char *) values in structs ** because we cannot use pointer types in objects ** that we want to pass to GPU. ** So we store unique ID that corresponds ** to some string and/or other CPU resources */ /* ** Мы не можем хранить строки в объектах для видеокарты, ** так как в это указатели. ** Поэтому мы храним ID каждого объекта в самом объекте ** и по этому ID ищем ресуры (например имя) для каждого объекта ** в хранилище на оперативной памяти. */ typedef struct s_id_manager { int current_id; int (*next_id)(struct s_id_manager *manager); } t_idm; int id_manager_next_id(struct s_id_manager *manager); //flags settings here as bit field //typedef struct s_settings //{ // int flag_1 : 1; // int flag_2 : 1; // int flag_3 : 1; //} t_settings; //TODO define in mlx typedef void t_mlx; typedef struct s_rts { t_idm idm; t_mlx *mgx; t_scn *scene; } t_rts; int rts_free(t_rts *rts); int rts_init(t_rts **rts); #endif
2.15625
2
2024-11-18T22:09:31.455942+00:00
2020-06-14T18:11:49
9a1ec7a3fd2af003ec52aaf6c63f95fb0814311b
{ "blob_id": "9a1ec7a3fd2af003ec52aaf6c63f95fb0814311b", "branch_name": "refs/heads/master", "committer_date": "2020-06-14T18:11:49", "content_id": "fcc28e97b8b171c590c9c513551f20fb215d92ab", "detected_licenses": [ "MIT" ], "directory_id": "5b0ed333ba26589d0467c51e297e5c5c33630ad2", "extension": "c", "filename": "expandable_array.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": 3876, "license": "MIT", "license_type": "permissive", "path": "/src/expandable_array.c", "provenance": "stackv2-0106.json.gz:34966", "repo_name": "intentionally-left-nil/cuckoo_hash", "revision_date": "2020-06-14T18:11:49", "revision_id": "3fe7340beee264712b2287b6de13114544cb6b3e", "snapshot_id": "7be1ecfa1ef7e21d00aa8694469444243bed0182", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/intentionally-left-nil/cuckoo_hash/3fe7340beee264712b2287b6de13114544cb6b3e/src/expandable_array.c", "visit_date": "2022-10-20T23:48:10.501063" }
stackv2
#include "expandable_array.h" #include <stddef.h> #include <string.h> #include <math.h> #include <stdio.h> typedef struct _ExpandableArray { void **levels; size_t num_levels; size_t item_size; } _ExpandableArray; static void *createLevel(size_t item_size, size_t capacity) { void *level = malloc(item_size * capacity); if (level) { memset(level, 0, item_size * capacity); } return level; } ExpandableArray *createExpandableArray(size_t item_size) { _ExpandableArray *expandableArray = malloc(sizeof(_ExpandableArray)); void *firstLevel = createLevel(item_size, 1); void **levels = malloc(sizeof(void *)); if (expandableArray && firstLevel && levels) { expandableArray->levels = levels; expandableArray->levels[0] = firstLevel; expandableArray->num_levels = 1; expandableArray->item_size = item_size; } else { free(expandableArray); free(firstLevel); free(levels); expandableArray = NULL; } return expandableArray; } static bool ensureCapacity(ExpandableArray *array, int index) { while (index >= getCapacityOfExpandableArray(array)) { const size_t new_num_levels = array->num_levels + 1; const size_t next_level_capacity = 1 << array->num_levels; void *next_level = createLevel(array->item_size, next_level_capacity); if (!next_level) { return false; } void **new_levels = realloc(array->levels, sizeof(void *) * new_num_levels); if (!new_levels) { free(next_level); return false; } new_levels[new_num_levels - 1] = next_level; array->levels = new_levels; array->num_levels = new_num_levels; } return true; } // This isn't marked as static so we can unit test it size_t getLevelIndexForIndexInExpandableArray(size_t index) { return (size_t)log2(index + 1); } // This isn't marked as static so we can unit test it size_t getLevelOffsetForIndexInExpandedArray(size_t index, size_t level_index) { if (index == 0) { return 0; } // The previous levels could hold 2^n - 1 items size_t base = (1 << level_index) - 1; return index - base; } void freeExpandableArray(ExpandableArray *array) { if (array) { for (size_t i = 0; i < array->num_levels; ++i) { free(array->levels[i]); } free(array->levels); free(array); } } void *getValueInExpandableArray(ExpandableArray *array, size_t index) { void *value = NULL; size_t level_index = getLevelIndexForIndexInExpandableArray(index); if (level_index < array->num_levels) { void *level = array->levels[level_index]; size_t offset = getLevelOffsetForIndexInExpandedArray(index, level_index); // This has potential portability risks, but suffices for now value = ((char *)level) + offset * array->item_size; } return value; } bool setValueInExpandableArray(ExpandableArray *array, size_t index, void const *value) { if (!ensureCapacity(array, index)) { return false; } void *dest = getValueInExpandableArray(array, index); if (dest) { memcpy(dest, value, array->item_size); } return true; } void deleteValueInExpandableArray(ExpandableArray *array, size_t index) { void *dest = getValueInExpandableArray(array, index); if (dest) { memset(dest, 0, array->item_size); } } size_t getCapacityOfExpandableArray(ExpandableArray *array) { return (1 << array->num_levels) - 1; } void decreaseCapacityOfExpandableArray(ExpandableArray *array, size_t desired_capacity) { while (array->num_levels > 1) { size_t level_capacity = 1 << (array->num_levels - 1); size_t previous_capacity = getCapacityOfExpandableArray(array) - level_capacity; if (previous_capacity < desired_capacity) { break; } void *level = array->levels[array->num_levels - 1]; free(level); array->levels[array->num_levels - 1] = NULL; array->num_levels--; } }
3.40625
3
2024-11-18T22:09:31.540797+00:00
2019-04-06T22:08:23
993da07aa26bae60640c108c77b596602a17bd58
{ "blob_id": "993da07aa26bae60640c108c77b596602a17bd58", "branch_name": "refs/heads/master", "committer_date": "2019-04-06T22:08:23", "content_id": "fd4a8c1fdaefc1b87f072748b2a20a577dd5d171", "detected_licenses": [ "MIT" ], "directory_id": "45e8cc21ce51103b093d8778452580ff122336fa", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 179891325, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 93265, "license": "MIT", "license_type": "permissive", "path": "/src/test.c", "provenance": "stackv2-0106.json.gz:35094", "repo_name": "fjpena/genesis-zx", "revision_date": "2019-04-06T22:08:23", "revision_id": "78ec682415f51179e928fe37bd75c6f1e75d987a", "snapshot_id": "99c401af3b0672946c356b863b44cc3eed5548aa", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/fjpena/genesis-zx/78ec682415f51179e928fe37bd75c6f1e75d987a/src/test.c", "visit_date": "2020-05-05T09:06:30.011306" }
stackv2
#include "structs.h" #include "movement.h" #include "behavior.h" #include "constants.h" #include "sprdefs.h" #include "engine.h" #pragma output STACKPTR=24600 // Game variables unsigned char ship_x; unsigned char ship_y; char speed_x; char speed_y; unsigned char frames_to_shoot; // Can we shoot now? unsigned char frames_fire_pressed; // Number of frames where the FIRE button is pressed: when pressed for 6 frames, we will launch the BFB (if available) unsigned char current_weapon; // What is our current weapon? unsigned char current_weapon_sprite; // Sprite for our current weapon unsigned char current_weapon_energy; // Energy for the current weapon unsigned char available_superbombs; // Number of available superbombs (kill everything on screen) unsigned char life_counter; // How many lifes do we have? unsigned char credit_counter; // Start with 3 credits! unsigned char end_game; // Game will be really over at this time unsigned char current_screen; unsigned char map_xpos; unsigned char respawn_xpos; // xpos to respawn after dying unsigned char map_displacement; // Displacement in tile: 0000YYXX, where XX is the displacement in pixels (0, 1==2, 2==4, 3==6), and YY is the displacement in chars (0-2). unsigned char max_shoots; // Maximum number of shoots allowed with the current weapon unsigned char mayday; // We have been shot! unsigned char current_level; // level we are playing unsigned char previous_level; // level we were at before getting killed or moved to a new level unsigned char level_color; // Color for the current level unsigned int score; // Need we say more? unsigned int hiscore; // Highest score unsigned int next_extralife; // Score to get the next extra life unsigned char update_score; // We must update the score at the next frame or two unsigned char update_superb; // We must update the number of superbombs unsigned char update_life; // We must update the number of lifess // Final enemy unsigned char final_enemy_active; unsigned char final_enemy_components; // How many sprites in the enemy unsigned char fenemy_defeat; // Have we beaten it? unsigned char fenemy_activation_counter; // Ship sprites, used for dying animation unsigned char ship0spr; // Temporary definition of structs. If they work as-is, we will move them to an include file unsigned char CurLevel_XLength; // Length in X of the current level unsigned char CurLevel_NTiles; // Number of tiles for the current level unsigned int keys[]={KEY_Q,KEY_A,KEY_O,KEY_P,KEY_SPACE}; unsigned char joy; unsigned char joystick_type; // Which joystick are we using unsigned char inertia_cheat; // are we cheating? unsigned char border_color; // For some silly effects // Array of existing enemies and shoots (max 8 enemies for now) struct Entity active_enemies[MAX_ENEMIES]; struct Entity my_active_shoots[MAX_ENEMIES]; struct Entity enemy_active_shoots[MAX_ENEMIES]; struct Entity power_up; // Only one powerup active at a time... // Array of enemy locations in the game // We use the same Entity structure, with just one difference: X now means the tile //struct Enemy enemy_locations[128]; // up to 128 enemies per level, 8 bytes per enemy: 1K struct Enemy *enemy_locations = 0xF800; // up to 256 enemies per level, 8 bytes per enemy: 2K, WARNING: this is placed in RAM 4 unsigned char new_enemy; // Loop counters and temporary variables unsigned char sound_selection; unsigned char dummy_b; unsigned int dummy_i; unsigned char frameskip_counter; int __FASTCALL__ read_joystick(int joytype) { #asm ld a, l ld hl, _keys call get_joystick ld h,0 ld l,a #endasm } // WYZ player functions void wyz_load_music (unsigned char mzk_number) { #asm ld hl, 2 add hl, sp ld a, (hl) ; A gets the song number push af di call CARGA_CANCION ei ld a, 3 ld (SOUND_SFX), a ; by default we select sound and sfx, unless changed later pop af ld c, a ; C gets the song number ld b, 0 ld hl, _fxchannel_music add hl, bc ld a, (hl) ld (FX_CHANNEL),a call STOP_FX #endasm } void wyz_stop_music(void) { #asm di CALL STOP_PLAYER ei halt #endasm } void wyz_play(void) { #asm call WYZ_PLAY #endasm } void wyz_effect(unsigned char effect) { #asm ld a, (23388) and $07 ; keep low bits push af ; save current state ld b, 0 di call setrambank ; go to ram bank 0 to play FX ei ld hl, 4 add hl, sp ld b, (hl) ; B gets the effect number call LOAD_FX di pop af ; recover RAM bank state ld b, a call setrambank ; go back to normal state ei #endasm } void gameISR(void) { joy=read_joystick(joystick_type); #asm ld a,r jp p, noscreenswitch ; the highest bit of R is 0, no screen switch yet call switchscreen ; switch screen ld a, r and $7f ld r,a ; clear the highest bit of the R register. It will be used to flag for a screen switch .noscreenswitch ld a, (23388) and $07 ; keep low bits push af ; save current state ld b, 0 call setrambank ; go to ram bank 0 for the music ISR call WYZ_PLAY pop af ld b, a call setrambank ; go back to normal state ld a, (_frameskip_counter) inc a ld (_frameskip_counter), a ld a, (_border_color) and a ret z dec a ld (_border_color), a out ($fe), a #endasm } // Print large char on screen (2x1), from a base number 0..9 // INPUT: // B: position in X (pixels) // C: position in Y (pixels) // A: number to print #asm .PrintLargeNumber push af call CalcScreenPos_Char ; Screen position in HL ex de, hl ld hl, _number_font pop af rlca rlca rlca and $f8 ; multiply by 8 ld c, a ld b, 0 add hl, bc ex de, hl ; HL points to the screen position, DE to the first row of the number push hl ld b, 4 .printlarge_loop1 ld a, (de) inc de ld (hl), a inc h ld (hl), a inc h djnz printlarge_loop1 pop hl ld bc, 32 add hl, bc ld b, 4 .printlarge_loop2 ld a, (de) inc de ld (hl), a inc h ld (hl), a inc h djnz printlarge_loop2 ret #endasm // Decompose a 5-digit number in single digits // INPUT: HL: number // IX: pointer to string where the individual numbers will be located #asm ; Divide HL by BC ; ; HL: number ; BC: divider ; DE: result (HL / BC) ; HL: remainder .divide_large xor a ld de, 0 .divide_loop sbc hl, bc jp c, divide_completed inc de jp divide_loop .divide_completed add hl, bc ret .decompose_5digit ld bc, 10000 ; get the fifth digit call divide_large ; E has the result, HL the remainder ld (ix+0), e ld bc, 1000 call divide_large ld (ix+1), e ld bc, 100 call divide_large ld (ix+2), e ld bc, 10 call divide_large ld (ix+3), e ld (ix+4), l ; L has the last remainder ret #endasm unsigned char numbers[5]; // 5 chars is the maximum number of digits we will print // Print 2-digit number, large // INPUT: // B: position in X (pixels) // C: position in Y (pixels) // A: number to print #asm .PrintLarge_2 push bc ld e, a ld d, 10 call Div8 ; A = number /10 (first digit), D = remainder (second digit) ld hl, _numbers ld (hl), a inc hl ld (hl), d pop bc push bc push hl call PrintLargeNumber ; Print first number pop hl pop bc ld a, 8 add a, b ld b, a ; move 8 pixels right ld a, (hl) ; get second digit call PrintLargeNumber ; Print second number ret #endasm // Print large char on screen (2x1), from a base number 0..9, on a screen based at $4000 // INPUT: // B: position in X (pixels) // C: position in Y (pixels) // A: number to print #asm .PrintLargeNumber_4000 push af call CalcScreenPos_Char ; Screen position in HL ld a, h sub $80 ld h, a ex de, hl ld hl, _number_font pop af rlca rlca rlca and $f8 ; multiply by 8 ld c, a ld b, 0 add hl, bc ex de, hl ; HL points to the screen position, DE to the first row of the number push hl ld b, 4 .printlarge4000_loop1 ld a, (de) inc de ld (hl), a inc h ld (hl), a inc h djnz printlarge4000_loop1 pop hl ld bc, 32 add hl, bc ld b, 4 .printlarge4000_loop2 ld a, (de) inc de ld (hl), a inc h ld (hl), a inc h djnz printlarge4000_loop2 ret #endasm // Print 2-digit number, large, on a screen based at $4000 // INPUT: // B: position in X (pixels) // C: position in Y (pixels) // A: number to print #asm .PrintLarge_2_4000 push bc ld e, a ld d, 10 call Div8 ; A = number /10 (first digit), D = remainder (second digit) ld hl, _numbers ld (hl), a inc hl ld (hl), d pop bc push bc push hl call PrintLargeNumber_4000 ; Print first number pop hl pop bc ld a, 8 add a, b ld b, a ; move 8 pixels right ld a, (hl) ; get second digit call PrintLargeNumber_4000 ; Print second number ret #endasm // Print 5-digit number, large // INPUT: // B: position in X (pixels) // C: position in Y (pixels) // HL: number to print #asm .PrintLarge_5 ld ix, _numbers push bc call decompose_5digit pop bc ld a, (ix+0) push bc call PrintLargeNumber pop bc ld a, 8 add a, b ld b, a ld a, (ix+1) push bc call PrintLargeNumber pop bc ld a, 8 add a, b ld b, a ld a, (ix+2) push bc call PrintLargeNumber pop bc ld a, 8 add a, b ld b, a ld a, (ix+3) push bc call PrintLargeNumber pop bc ld a, 8 add a, b ld b, a ld a, (ix+4) call PrintLargeNumber ret #endasm // Print 5-digit number, small // INPUT: // B: position in X (pixels) // C: position in Y (pixels) // HL: number to print #asm .PrintSmall_5 ld ix, _numbers push bc call decompose_5digit pop bc ld a, (ix+0) push bc call PrintNumber pop bc ld a, 8 add a, b ld b, a ld a, (ix+1) push bc call PrintNumber pop bc ld a, 8 add a, b ld b, a ld a, (ix+2) push bc call PrintNumber pop bc ld a, 8 add a, b ld b, a ld a, (ix+3) push bc call PrintNumber pop bc ld a, 8 add a, b ld b, a ld a, (ix+4) call PrintNumber ret ; Print normal char on screen (1x1), from a base number 0..9 ; INPUT: ; B: position in X (pixels) ; C: position in Y (pixels) ; A: number to print .PrintNumber push af call CalcScreenPos_Char ; Screen position in HL ex de, hl ld hl, _number_font pop af rlca rlca rlca and $f8 ; multiply by 8 ld c, a ld b, 0 add hl, bc ex de, hl ; HL points to the screen position, DE to the first row of the number ld b, 8 .printnum_loop ld a, (de) inc de ld (hl), a inc h djnz printnum_loop ret ; Print normal char on screen (1x1), from a base number 0..9 ; Use $4000 as the base screen address ; INPUT: ; B: position in X (pixels) ; C: position in Y (pixels) ; A: number to print .PrintNumber_4000 push af call CalcScreenPos_Char ; Screen position in HL ld a, h sub $80 ld h, a ex de, hl ld hl, _number_font pop af rlca rlca rlca and $f8 ; multiply by 8 ld c, a ld b, 0 add hl, bc ex de, hl ; HL points to the screen position, DE to the first row of the number ld b, 8 .printnum_4000_loop ld a, (de) inc de ld (hl), a inc h djnz printnum_4000_loop ret #endasm // Load a block of sprites to the current working set // dstspr (0-63): first sprite to load // sourcespr (0-448): source to load from // numspr (1-64): number of sprites to load void LoadSprBlock(unsigned char dstspr, unsigned int sourcespr, unsigned char numspr) { #asm di ld a, (23388) and $07 ; keep low bits push af ; save current state ld b, 1 call setrambank ; go to ram bank 1 to manage the sprites ld hl, 8 add hl, sp ld e, (hl) dec hl ld d, (hl) ; DE gets dstspr dec hl ld c, (hl) dec hl ld b, (hl) ; BC gets sourcespr dec hl ld a, (hl) ; A gets numspr ld h, b ld l, c ; HL gets sourcespr now ; basically, we copy (numspr * 32) bytes, from (49152 + 2048 + (sourcespr*32)) to 49152 + (firstspr*32) rrca rrca rrca ld c, a and $1f ld b, a ld a, c and $e0 ld c, a ; BC = numspr *32 ld a, e rrca rrca rrca ld e, a and $1f ld d, a ld a, e and $e0 ld e, a ; DE = firstspr*32 push hl ld hl, 49152 add hl, de ex de, hl ; DE = (firstspr*32) + 49152 pop hl push de ; we will need DE for some calculations ld a, l rrca rrca rrca ld e, a and $1f ld d, a ld a, e and $e0 ld e, a ; DE = (low byte of sourcespr)*32 ld a, h rrca rrca rrca and $e0 or d ld h, a ld l, e ld de, 49152+2048 add hl, de ; HL = 49152 + 2048 + (sourcespr*32)) pop de ldir ; copy all stuff pop af ; recover RAM bank state ld b, a call setrambank ; go back to normal state ei #endasm } // Levels have compressed data, let's see how it goes when loading them unsigned char *level_pointer; unsigned int *int_pointer; unsigned int length_tiles; unsigned int length_map; void load_level(unsigned char level) { #asm di push bc ld b, 4 call setrambank ; Levels in RAM4 pop bc #endasm level_pointer=(unsigned char*)level_address[level]; CurLevel_NTiles = *(level_pointer)++; CurLevel_XLength = *(level_pointer)++; // Load the basic level data int_pointer=level_pointer; length_tiles = *(int_pointer); level_pointer+=2; int_pointer=level_pointer; length_map = *(int_pointer); level_pointer+=2; // Prepare tiles, preshift them, store them in their final location // We will use the map area as decompression buffer #asm ld de, $a000 ld hl, (_level_pointer) call depack ld de, $a000 ld a, (_CurLevel_NTiles) ld b,a call CreaTablaTiles #endasm // now, copy the map (uncompress) to its final location level_pointer += length_tiles; #asm ld de, $a000 ld hl, (_level_pointer) call depack #endasm // Copy enemy table level_pointer=(unsigned char*)enemy_address[level]; dummy_i = *level_pointer; // Number of enemies in level level_pointer++; dummy_i *= sizeof (struct Enemy); #asm ld de, (_enemy_locations) ld hl, (_level_pointer) ld bc, (_dummy_i) ldir ld b, 0 call setrambank ; vuelta a la normalidad ei #endasm } #asm .CleanSCRC000 ld hl, $C000 ld de, $C001 ld (hl),0 ld bc, 4095 ldir ld hl, $d800 ld de, $d801 ld a, (_level_color) ld (hl), a ld bc, 511 ldir ret #endasm void clean_screen(void) { #asm di ld b, 5 call setrambank ; la ponemos en $c000 - $ffff call CleanSCRC000 ld b, 7 call setrambank ; la ponemos en $c000 - $ffff call CleanSCRC000 ld b, 0 call setrambank ; vuelta a la normalidad ei #endasm } void load_background(void) { #asm di ld b, 3 ; Static images in RAM3 call setrambank ; la ponemos en $c000 - $ffff ld hl, $c000 ld de, 16384 call depack ld b, 7 call setrambank ; la ponemos en $c000 - $ffff ld hl, 16384 ld de, $c000 ld bc, 6912 ldir ; copy the background to the alternate screen ; Print number of remaining lives, current score, high score and current level ld b, 72 ld c, 136 ld a, (_life_counter) call PrintLarge_2 ld b, 72 ld c, 152 ld a, (_available_superbombs) call PrintLarge_2 ld b, 120 ld c, 144 ld hl, (_score) call PrintLarge_5 ld b, 184 ld c, 152 ld hl, (_hiscore) call PrintSmall_5 ld b, 80 ld c, 176 ld a, (_current_level) inc a call PrintNumber ; Same on the other screen! ld b, 5 call setrambank ; la ponemos en $c000 - $ffff ld b, 72 ld c, 136 ld a, (_life_counter) call PrintLarge_2 ld b, 72 ld c, 152 ld a, (_available_superbombs) call PrintLarge_2 ld b, 120 ld c, 144 ld hl, (_score) call PrintLarge_5 ld b, 184 ld c, 152 ld hl, (_hiscore) call PrintSmall_5 ld b, 80 ld c, 176 ld a, (_current_level) inc a call PrintNumber ld b, 0 call setrambank ; back to reality ei #endasm } void DrawGameMap(void) { #asm ld a, (_current_screen) ; cargamos la pantalla ld b, a call setrambank ; la ponemos el $c000 - $ffff ld a, (_current_screen) xor 2 ; 5 xor 2 = 7; 7 xor 2 = 5 ld (_current_screen), a ; intercambiamos la pantalla en la que vamos a escribir ld a, (_CurLevel_XLength) ld h,0 ld l,a ld d, $a0 ld a, (_map_xpos) ld e, a ; the map will always start at $a000, so the displacement will always be in E ld a, (_map_displacement) and $03 ld c, a ; displacement in pixels within tile ld a, (_map_displacement) and $0C rrca rrca ld b, a ; displacement in chars within tile call DrawMap #endasm } void DrawShip(void) { // First draw the ship #asm ld a, (_ship_x) ld b, a ld a, (_ship_y) ld c,a ld a, (_ship0spr) ld d, 0 ld e, a ; _ship01 call drawsprite_ship call _CheckShipCollision ld a, (_ship_x) add a,16 ld b, a ld a, (_ship_y) ld c,a ld a, (_ship0spr) inc a ld d, 0 ld e, a ;_ship02 call drawsprite_ship call _CheckShipCollision ld a, (_max_shoots) ld b, a ld hl, _my_active_shoots .drawshoots_loop push bc inc hl inc hl ld a, (hl) and a jr z, loop_shoots ld d, 0 ld e, (hl) dec hl ld c, (hl) dec hl ld b, (hl); bc = (x << 8) | y push hl call drawsprite pop hl inc hl inc hl .loop_shoots ld bc, 10 ; 12 = sizeof(struct Entity) add hl, bc pop bc djnz drawshoots_loop ; continue loop .draw_powerups ld hl, _power_up inc hl inc hl ld a, (hl) and a ret z ; if the power up is not active, just quit ld d, 0 ld e, (hl) dec hl ld c, (hl) dec hl ld b, (hl); bc = (x << 8) | y call drawsprite ; draw the power up, and that is it #endasm /* for(i=0;i<max_shoots;i++) { if (my_active_shoots[i].sprnum) // This shoot is active { dummy_i = my_active_shoots[i].x; dummy_i <<= 8; // Move X to the upper byte dummy_i |= my_active_shoots[i].y; dummy_i2 = my_active_shoots[i].sprnum; #asm ld bc, (_dummy_i) ld de, (_dummy_i2) call drawsprite #endasm } }*/ } void DrawEnemies(void) { // Now, display all enemies, shoots, etc #asm ld b, MAX_ENEMIES ld ix, _active_enemies ld iy, _enemy_active_shoots .drawenemy_loop push bc ld a, (ix+2) and a jr z, loop_enemy_shoot ld b, (ix+0) ld c, (ix+1) ; bc = (x << 8) | y ld d, 0 ld e, (ix+2) push ix call drawsprite pop ix .loop_enemy_shoot ld a, (iy+2) and a jr z, loop_enemy_continue ld b, (iy+0) ld c, (iy+1) ; bc = (x << 8) | y ld d, 0 ld e, (iy+2) push ix call drawsprite pop ix .loop_enemy_continue ld bc, 12 ; 12 = sizeof(struct Entity) add ix, bc add iy, bc ; go to the next entity pop bc djnz drawenemy_loop ; continue loop #endasm /* for(i=0;i<MAX_ENEMIES;i++) { if (active_enemies[i].sprnum) // This enemy is active { dummy_i = active_enemies[i].x; dummy_i <<= 8; // Move X to the upper byte dummy_i |= active_enemies[i].y; dummy_i2 = active_enemies[i].sprnum; #asm ld bc, (_dummy_i) ld de, (_dummy_i2) call drawsprite #endasm } if (enemy_active_shoots[i].sprnum) // This enemy shot is active { dummy_i = enemy_active_shoots[i].x; dummy_i <<= 8; // Move X to the upper byte dummy_i |= enemy_active_shoots[i].y; dummy_i2 = enemy_active_shoots[i].sprnum; #asm ld bc, (_dummy_i) ld de, (_dummy_i2) call drawsprite #endasm } }*/ } void activate_final_enemy(void) { if(!fenemy_activation_counter) { #asm di push bc ld b, 4 call setrambank ; Levels in RAM4 pop bc #endasm level_pointer=(unsigned char*)finalenemy_address[current_level]; dummy_i = final_enemy_components = *(level_pointer)++; // Load the basic final enemy data // Copy to enemy table (we are overwriting, which should not be a problem) dummy_i *= sizeof (struct Enemy); #asm ld de, (_enemy_locations) ld hl, (_level_pointer) ld bc, (_dummy_i) ldir #endasm #asm ld a, (_final_enemy_components) ld b, a ld hl, _active_enemies ld de, (_enemy_locations) .initfenemyloop ld a, (de) ; fenemy->x ld (hl), a ; active_enemies[i].x=fenemy->x; inc hl inc de inc de ld a, (de) ; fenemy->y ld (hl), a ; active_enemies[i].y=fenemy->y; inc hl inc de ld (hl), EXPLOSION_SPR ;active_enemies[i].sprnum=EXPLOSION_SPR; inc hl ld a, (de) ; fenemy->enemy_type ld (hl),a ; active_enemies[i].type= fenemy->enemy_type; inc hl inc de ld (hl), MOVE_EXPLOSION ; active_enemies[i].movement=MOVE_EXPLOSION; inc hl inc de ; ld a, (de) ; fenemy->energy; ; ld (hl), a ; active_enemies[i].energy = fenemy->energy; ld (hl), 0 ; active_enemies[i].energy = 0, so the enemy is only vulnerable after the explosions inc hl inc de ld (hl), 4 ;active_enemies[i].param1=4; inc hl inc de ld a, (de) ld (hl), a ; active_enemies[i].param2=fenemy->param2; inc hl inc de ; DE now points to the next enemy ld (hl), 0 ; active_enemies[i].param3=0; inc hl ld (hl), 0 ; active_enemies[i].param4=0; inc hl ld (hl), BEHAV_DO_NOTHING ; active_enemies[i].behavior = BEHAV_DO_NOTHING; inc hl ld (hl), 0 ; active_enemies[i].behav_param=0; inc hl ; HL now points to the next enemy djnz initfenemyloop #endasm /* for(i=0;i<final_enemy_components;i++) { active_enemies[i].sprnum=EXPLOSION_SPR; // exploding! active_enemies[i].movement=MOVE_EXPLOSION; active_enemies[i].param1=4; // 4 frames to explode fenemy = &(enemy_locations[i]); active_enemies[i].type= fenemy->enemy_type; active_enemies[i].behavior = BEHAV_DO_NOTHING; active_enemies[i].x=fenemy->x; active_enemies[i].y=fenemy->y; active_enemies[i].energy = fenemy->energy; active_enemies[i].param2=fenemy->param2; active_enemies[i].param3=0; active_enemies[i].param4=0; active_enemies[i].behav_param=0; }*/ #asm ld b, 0 call setrambank ; vuelta a la normalidad ei #endasm // Load the sprite block for the final enemy LoadSprBlock(22,finalspr[current_level],finalspr_count[current_level]); #asm call InitSprCacheList ; finally, re-initialize sprite cache list to ensure there are no problems! #endasm wyz_stop_music(); wyz_load_music(finalenemy_music[current_level]); #asm ld a, (_sound_selection) ld (SOUND_SFX), a #endasm } #asm ld a, (_fenemy_activation_counter) inc a ld (_fenemy_activation_counter), a and $3 jp nz, checkifcounteris60 ld a, (_final_enemy_components) ld b, a ld ix, _active_enemies ld de, 12 .renewexplosion_counter ld (ix+2), EXPLOSION_SPR ; exploding ld (ix+4), MOVE_EXPLOSION ld (ix+6), 4 ; 4 frames to explode add ix, de djnz renewexplosion_counter .checkifcounteris60 #endasm /* fenemy_activation_counter++; if((fenemy_activation_counter & 3) == 0) { for(i=0;i<final_enemy_components;i++) { active_enemies[i].sprnum=EXPLOSION_SPR; // exploding! active_enemies[i].movement=MOVE_EXPLOSION; active_enemies[i].param1=4; // 4 frames to explode } } */ if (fenemy_activation_counter == 60) { #asm di push bc ld b, 4 call setrambank ; Levels in RAM4 pop bc #endasm #asm ld a, (_final_enemy_components) ld b, a ld hl, _active_enemies ld ix, (_enemy_locations) .initfenemyloop_part2 inc hl inc hl push hl ld hl, _finalenemy_sprites ld a, (ix+3) ; fenemy->enemy_type ld e, a ld d, 0 add hl, de ld a, (hl) ; A = finalenemy_sprites[fenemy->enemy_type]; pop hl ld (hl), a ; active_enemies[i].sprnum=finalenemy_sprites[fenemy->enemy_type]; inc hl inc hl ld a, (ix+4) ld (hl), a ; active_enemies[i].movement=fenemy->movement; inc hl ld a, (ix+5) ld (hl), a ; active_enemies[i].energy=fenemy->energy; inc hl ld a, (ix+6) ld (hl), a ; active_enemies[i].param1=fenemy->param1; ld de, 8 add ix, de ; enemy_locations[i+1] ld de, 6 add hl, de ; active_enemies[i+1] djnz initfenemyloop_part2 #endasm /* for(i=0;i<final_enemy_components;i++) { fenemy = &(enemy_locations[i]); active_enemies[i].sprnum=finalenemy_sprites[fenemy->enemy_type]; active_enemies[i].movement=fenemy->movement; active_enemies[i].param1=fenemy->param1; }*/ final_enemy_active=1; #asm ld b, 0 call setrambank ; vuelta a la normalidad ei #endasm } } // Calculate the number of available shoots unsigned char AvailShoots(void) { #asm ld hl, _my_active_shoots+2 ld a, (_max_shoots) ld b, a ld c, 0 ld de, 12 ; sizeof (struct Entity) .availshoots_loop ld a, (hl) and a jr nz, shoot_active inc c .shoot_active add hl, de djnz availshoots_loop ld h, 0 ld l, c ret #endasm } struct Entity * NewShoot(unsigned char x, unsigned char y) { #asm ld hl, 4 add hl, sp ld a, (hl) and a jp z, nonewshoot ; Cannot create a shoot at X=0, it means we are at the end of the screen ld hl, 2 add hl, sp ld a, (hl) cp 113 jp nc, nonewshoot ; If Y > 112, also skip the shoot creation ld ix, _my_active_shoots ld a, (_max_shoots) ld b, a .searchshoot_loop ld a, (ix+2) and a jr nz, next_searchshoot ; sprnum is 0, so a candidate was found ld a, (_current_weapon_sprite) ld (ix+2), a ;current_e->sprnum = current_weapon_sprite; ld hl, 4 add hl, sp ld a, (hl) ld (ix+0), a ; current_e->x = x; dec hl dec hl ; hl points to Y ld a, (hl) ld (ix+1), a ; current_e->y = y ld a, MOVE_RIGHT ld (ix+4), a ; current_e->movement = MOVE_RIGHT; ld a, (_current_weapon) ld hl, _shoot_speed ld e, a ld d, 0 add hl, de ld a, (hl) ; A= shoot_speed[current_weapon] ; ld a, 8 ld (ix+6), a ; current_e->param1 = shoot_speed[current_weapon]; // Fast for now, let's see the rest ld a, ixh ld h, a ld a, ixl ld l, a ; HL points to the entity created ret .next_searchshoot ld de, 12 add ix, de djnz searchshoot_loop .nonewshoot ld hl, 0 ; return NULL if all shoots are in use #endasm /* if(!x) return; // Cannot create a shoot at X=0, it means we are at the end of the screen for (i=0;i<max_shoots;i++) { current_e=&my_active_shoots[i]; if(current_e->sprnum == 0) // Found a candidate { current_e->sprnum = current_weapon_sprite; // FIXME: Substitute with some variable holding the current shoot, defining shoot energy, etc current_e->x = x; current_e->y = y; current_e->movement = MOVE_RIGHT; current_e->param1 = 8; // Fast for now, let's see the rest return; } }*/ } #asm ._NewEnemyShoot_FX ld hl, FX_DOUBLE_SHOOT push hl call _wyz_effect pop hl #endasm struct Entity * NewEnemyShoot(unsigned char x, unsigned char y, unsigned char movement, unsigned char sprite) { #asm ld hl, 8 add hl, sp ld a, (hl) and a jr z, nonewenemy ; Cannot create a shoot at X=0, it means we are at the end of the screen ld hl, 6 add hl, sp ld a, (hl) cp 113 jr nc, nonewenemy ; If Y > 112, also skip the shoot creation ld ix, _enemy_active_shoots ld a, MAX_ENEMIES ld b, a .searchenemyshoot_loop ld a, (ix+2) and a jr nz, next_searchenemyshoot ; sprnum is 0, so a candidate was found ld hl, 8 add hl, sp ld a, (hl) ld (ix+0), a ; current_e->x = x; dec hl dec hl ; hl points to Y ld a, (hl) ld (ix+1), a ; current_e->y = y dec hl dec hl ld a, (hl) ; ld (ix+4), a ; current_e->movement = movement; ld a, 8 ld (ix+6), a ; current_e->param1 = 8; // Fast for now, let's see the rest dec hl dec hl ld a, (hl) ld (ix+2), a ; current_e->sprnum = sprnum; ld a, ixh ld h, a ld a, ixl ld l, a ; HL points to the entity created ret .next_searchenemyshoot ld de, 12 add ix, de djnz searchenemyshoot_loop .nonewenemy ld hl, 0 ; return NULL if all shoots are in use #endasm /* if(!x) return; // Cannot create a shoot at X=0, it means we are at the end of the screen for (i=0;i<MAX_ENEMIES;i++) { current_e=&enemy_active_shoots[i]; if(current_e->sprnum == 0) // Found a candidate { current_e->sprnum = current_weapon; // FIXME: Substitute with some variable holding the current shoot, defining shoot energy, etc current_e->x = x; current_e->y = y; current_e->movement = type; current_e->param1 = 8; // Fast for now, let's see the rest return; } }*/ } // Generate the enemies starting from "first"... Useful for final enemies struct Entity * NewEnemy(struct Enemy *e, unsigned char first) { #asm ld hl, 2 add hl, sp ld b, (hl) ; B = first inc hl inc hl ld e, (hl) inc hl ld d, (hl) ld ixh, d ld ixl, e ; IX = e ld hl, _active_enemies-12 ld de, 12 ld a, b ; Save first in A inc b .gotofirst add hl, de djnz, gotofirst ld b, a inc hl inc hl .findemptyenemy ld a, (hl) and a jp nz, enemynotempty ; Empty slot found, populate it! dec hl dec hl ; point to e->X push hl ; Save HL ld a, (_map_xpos) neg add a, (ix+0) ; A = e->x - map_xpos ld l, a ld h, 0 xor a rl l rl h rl l rl h rl l rl h ; HL = HL*8 ld d, h ld e, l add hl, de add hl, de ; HL = HL*24, (e->x - map_xpos) * 24) ld e, (ix+1) ld d, 0 ; DE=e->e_xdesp add hl, de ; HL = (e->x - map_xpos) * 24) + e->x_desp ld a, (_map_displacement) rlca ; the highest bit of map_displacement is always 0, so in effect it is << 1 ld e, a sbc hl, de ; HL = ((e->x - map_xpos) * 24) + e->x_desp - (map_displacement<<1), it should be less than 256 ex de, hl pop hl ld (hl), e ; active_enemies[i].x=((e->x - map_xpos) * 24) + e->x_desp - (map_displacement<<1); inc hl ld a, (ix+2) ld (hl), a ; active_enemies[i].y=e->y; inc hl push hl ld hl, _enemy_sprites ld a, (ix+3) ; e->enemy_type ld e, a ld d, 0 add hl, de ld a, (hl) ; A = enemy_sprites[e->enemy_type] pop hl ld (hl), a ; active_enemies[i].sprnum=enemy_sprites[e->enemy_type]; inc hl ld a, (ix+3) ; e->enemy_type ld (hl), a ; active_enemies[i].type= e->enemy_type; inc hl ld a, (ix+4) ; e->movement ld (hl), a ; active_enemies[i].movement=e->movement; inc hl ld a, (ix+5) ld (hl), a ; active_enemies[i].energy = e->energy; inc hl ld a, (ix+6) ld (hl), a ; active_enemies[i].param1=e->param1; inc hl ld a, (ix+7) ld (hl), a ; active_enemies[i].param1=e->param2; xor a inc hl ld (hl), a ; active_enemies[i].param3=0; inc hl ld (hl), a ; active_enemies[i].param4=0; inc hl ld a, (ix+3) ; e->enemy_type push hl ld hl, _behavior_types ld e, a add hl, de ld a, (hl) ; A = behavior_types[e->enemy_type]; pop hl ld (hl), a ; active_enemies[i].behavior = behavior_types[e->enemy_type]; inc hl xor a ld (hl), a ; active_enemies[i].behav_param=0; ld de, -11 add hl, de ret ; return &(active_enemies[i]) .enemynotempty ld de, 12 add hl, de inc b ld a, MAX_ENEMIES-1 cp b jp nc, findemptyenemy ld hl, 0 ; return 0 if no empty enemy was found #endasm /* for(i=first;i<MAX_ENEMIES;i++) { if(active_enemies[i].sprnum == 0) { active_enemies[i].sprnum=enemy_sprites[e->enemy_type]; active_enemies[i].type= e->enemy_type; active_enemies[i].behavior = behavior_types[e->enemy_type]; active_enemies[i].x=((e->x - map_xpos) * 24) + e->x_desp - (map_displacement<<1); active_enemies[i].y=e->y; active_enemies[i].energy = e->energy; active_enemies[i].movement=e->movement; active_enemies[i].param1=e->param1; active_enemies[i].param2=e->param2; active_enemies[i].param3=0; active_enemies[i].param4=0; active_enemies[i].behav_param=0; return &(active_enemies[i]); } } return (struct Entity *)0;*/ } char shoot_xchar, shoot_ychar; //char enemy_xchar, enemy_ychar; unsigned char shoot_hits_enemy(struct Entity *shoot) { #asm pop bc pop hl push hl push bc ; HL holds the pointer to the shoot struct ld a, (hl) rrca rrca rrca and $1f ld (_shoot_xchar), a ; shoot_xchar = shoot->x / 8 inc hl ld a, (hl) rrca rrca rrca and $1f ld (_shoot_ychar), a ; shoot_ychar = shoot->y / 8 ld hl,_active_enemies ld b, MAX_ENEMIES ld c, 0 ; C will serve as an enemy counter .loop_hitenemy push bc inc hl inc hl ld a, (hl) dec hl dec hl and a jr z, cont_loop_hitenemy ; not zero, so this is an active enemy ld a, (hl) ; current_e->x rrca rrca rrca and $1f ld ix, _shoot_xchar sub (ix+0) ld d, a ; D = (current_e->x) / 8 - shoot_xchar inc hl ; current_e->y ld a, (hl) ; current_e->y dec hl rrca rrca rrca and $1f ld ix, _shoot_ychar sub (ix+0) ld e, a ; E = (current_e->y) / 8 - shoot_ychar ; we want to check if abs(D) and abs(E) is 0 or 1. So we add one, and if the value as ; unsigned is less than 3, we got it inc d inc e ld a, 2 cp d jr c, cont_loop_hitenemy cp e jr c, cont_loop_hitenemy ; our shoot has hit an enemy, so we exit with the enemy value pop bc ; to restore the stack ld h, 0 ld l, c ret .cont_loop_hitenemy ld bc, 12 add hl, bc pop bc inc c ; next enemy djnz loop_hitenemy ld h, 0 ld l, 255 ret #endasm /* shoot_xchar = (shoot->x) / 8; shoot_ychar = (shoot->y) / 8; for(j=0;j<MAX_ENEMIES;j++) // For now, a crude bounding box collision detection. If it works... { current_e = &active_enemies[j]; if(current_e->sprnum) // This is a real active enemy { enemy_xchar = (current_e->x) / 8; enemy_ychar = (current_e->y) / 8; enemy_xchar -= shoot_xchar; enemy_ychar -= shoot_ychar; if((enemy_xchar < 2) && (enemy_xchar > -2)) { if((enemy_ychar < 2) && (enemy_ychar > -2)) return j; } } } return 255; */ } // Go to every enemy on screen and substract 5 to its energy // Sould kill them all! void Do_Superbomb(void) { #asm ld a, 7 ld (_border_color), a ; set border effect ld b, MAX_ENEMIES ld hl, _active_enemies+2 ld de, 12 ; sizeof (struct enemy) .superbomb_loop ld a, (hl) and a jr z, continue_loop_superbomb inc hl inc hl inc hl ; energy ld a, (hl) and a ; If energy is 0, ignore (not killable or already dead) jr z, superbomb_shot_completed sub 5 jr c, superbomb_enemy_dead jr z, superbomb_enemy_dead ; if the energy is 0 or < 0, it is dead ld (hl), a ; new energy jr superbomb_shot_completed .superbomb_enemy_dead ld (hl), 0 ; enemy is dead inc hl ; param1 ld (hl), 4 dec hl dec hl ; movement ld (hl), MOVE_EXPLOSION dec hl dec hl ; sprnum ld (hl), EXPLOSION_SPR .continue_loop_superbomb add hl, de djnz superbomb_loop ret .superbomb_shot_completed dec hl dec hl dec hl jr continue_loop_superbomb ; make sure we are at energy before adding 12 #endasm } #asm ; Input: ; B: X position ; C: Y position ; Output: ; HL: screen address ; B: bit position .CalcScreenPos ld a, c and $07 ; 7 <-the 3 lowest bits are the line within a char ld h,a ; 4 ld a,c ; 4 <- the top 2 bits are the screen third rra ; 4 rra ; 4 rra ; 4 and $18 ; 7 or h ; 4 or $C0 ; 4 <- If the start address is 16384, this should be $40 ld h,a ; 4 (total 50 t-states) H has the high byte of the address ld a, b ;4 rra ;4 rra ;4 rra ;4 and $1f ;7 <- the top 5 bits are the char pos. The low 3 bits are the pixel pos ld l,a ;4 ld a,c ;4 rla ;4 rla ;4 and $e0 ;7 or l ;4 ld l,a ;4 (total 54 t-states) L has the low byte of the address ; HL has the address in RAM of the char ld a, b and $07 ; the lowest three bits are the bit position inc a ld b,a ; b has the number of bits to shift 1 ld a,$80 dec b jr z, postloop .shiftloop rrca dec b jr nz, shiftloop .postloop ld b, a ret ; Input: ; B: X position ; C: Y position ; Output: ; HL: screen address .CalcScreenPos_Char ld a,c ; 4 <- the top 2 bits are the screen third rra ; 4 rra ; 4 rra ; 4 and $18 ; 7 or $C0 ; 4 <- If the start address is 16384, this should be $40 ld h,a ; 4 (total 31 t-states) H has the high byte of the address ld a, b ;4 rra ;4 rra ;4 rra ;4 and $1f ;7 <- the top 5 bits are the char pos. The low 3 bits are the pixel pos ld l,a ;4 ld a,c ;4 rla ;4 rla ;4 and $e0 ;7 or l ;4 ld l,a ;4 (total 54 t-states) L has the low byte of the address ; HL has the address in RAM of the char ret ;Divide 8-bit values ;In: Divide E by divider D ;Out: A = result, D = rest ; .Div8 xor a ld b,8 .Div8_Loop rl e rla sub d jr nc,Div8_NoAdd add a,d .Div8_NoAdd djnz Div8_Loop ld d,a ld a,e rla cpl ret #endasm /* void CheckShipCollision(void) { #asm ld a, (_ship_x) add a, 2 ld b, a ld a, (_ship_y) add a, 3 ld c,a call CalcScreenPos ; check upper left corner ld a, (hl) and b jp nz, collision inc hl ld a, (hl) and a jp nz, collision ; middle char inc hl inc hl ; the upper right corner is always 3 characters to the right ld a, (hl) and b jp nz, collision ld a, (_ship_x) add a, 2 ld b, a inc c inc c call CalcScreenPos ; check the 5th pixel ld a, (hl) and b jp nz, collision inc hl ld a, (hl) and a jp nz, collision ; middle char inc hl inc hl ; the upper right corner is always 3 characters to the right ld a, (hl) and b jp nz, collision ld a, (_ship_x) add a, 2 ld b, a inc c inc c call CalcScreenPos ; check the 7th pixel ld a, (hl) and b jp nz, collision inc hl ld a, (hl) and a jp nz, collision ; middle char inc hl inc hl ; the upper right corner is always 3 characters to the right ld a, (hl) and b jp nz, collision ld a, (_ship_x) add a, 2 ld b, a inc c inc c call CalcScreenPos ; check the 9th pixel ld a, (hl) and b jr nz, collision inc hl ld a, (hl) and a jp nz, collision ; middle char inc hl inc hl ; the upper right corner is always 3 characters to the right ld a, (hl) and b jr nz, collision ld a, (_ship_x) add a, 2 ld b, a inc c inc c call CalcScreenPos ; check the 11th pixel ld a, (hl) and b jr nz, collision inc hl ld a, (hl) and a jp nz, collision ; middle char inc hl inc hl ; the upper right corner is always 3 characters to the right ld a, (hl) and b jr nz, collision ld a, (_ship_x) add a, 2 ld b, a inc c inc c call CalcScreenPos ; check the 13th pixel (lower left corner) ld a, (hl) and b jr nz, collision inc hl ld a, (hl) and a jp nz, collision ; middle char inc hl inc hl ; the upper right corner is always 3 characters to the right ld a, (hl) and b jr nz, collision ld a, (_ship_x) add a, 15 ld b, a ld a, (_ship_y) add a, 3 ld c,a call CalcScreenPos ; check upper center ld a, (hl) and b jr nz, collision ld a, (_ship_x) add a, 15 ld b, a ld a, (_ship_y) add a, 7 ld c,a call CalcScreenPos ; check middle center ld a, (hl) and b jr nz, collision ld a, (_ship_x) add a, 15 ld b, a ld a, (_ship_y) add a, 13 ld c,a call CalcScreenPos ; check lower center ld a, (hl) and b jr nz, collision ret ; no collision .collision ld a, (_mayday) and a ret nz ; if mayday is already non zero, do not duplicate ; inc a ; NORMAL BEHAVIOR nop ; CHEAT!!!!! ld (_mayday),a ; mayday, we have been hit! #endasm }*/ void CheckShipCollision(void) { #asm ld a, (Ship_Collision) and a ret z .collision ld a, (_mayday) and a ret nz ; if mayday is already non zero, do not duplicate .cheathere inc a ; NORMAL BEHAVIOR ; nop ; CHEAT!!!!! ld (_mayday),a ; mayday, we have been hit! #endasm } void CheckShootCollision(void) { #asm ld ix, _my_active_shoots ; pointer to the structure ld a, (_max_shoots) ld iyh, a ; IYh will be the counter call checkshootloop ld ix, _enemy_active_shoots ld a, MAX_ENEMIES ld iyh, a call checkshootloop ; check the same, for the enemy shoots #endasm } #asm .checkshootloop ld a, (ix+2) ; get sprnum and a jp z, continue_collisionloop ; ignore non-existing shoots ld a, (ix+0) add a, 12 ld e, a ; E == shoot_x ld d, 24 call Div8 ; A holds x /24, D holds x % 24 ld e, a ld a, (_map_xpos) add a, e ld c, a ; C = x_tile = map_xpos + x/24 ld a, (_map_displacement) add a, a ; a * 2 add a, d ; a = map_disp + x %24 cp 24 jp c, no_overflow ; a < 24 inc c ; if a >= 24, increment x_tile .no_overflow ld a, (ix+1) ; a = shoot_y, c = shoot_x (in tile terms) add a, 4 ; middle of the shoot sra a sra a sra a ; a = shoot_y (in tile terms), c = shoot_x (in tile terms) ld h, $a0 ld l, c ; hl holds the position of shoot_x (in tile terms) in the map ex af, af ld a, (_CurLevel_XLength) ld e,a xor a ld d, a ex af, af ; we need to add DE shoot_y times and a jp z, endloop_addde ; if a is zero, no need to add .loop_addde add hl, de dec a jr nz, loop_addde ; at the end, HL has the tile address .endloop_addde ld a, (hl) and a jr z, noshootcollision1 xor a ld (ix+2), a ; my_active_shoots[i].sprnum=0 jp continue_collisionloop .noshootcollision1 ; now check again, for the lower side of the shoot ld a, (ix+1) ; a = shoot_y, c = shoot_x (in tile terms) add a, 12 ; middle of the shoot sra a sra a sra a ; a = shoot_y (in tile terms), c = shoot_x (in tile terms) ld h, $a0 ld l, c ; hl holds the position of shoot_x (in tile terms) in the map ex af, af ld a, (_CurLevel_XLength) ld e,a xor a ld d, a ex af, af ; we need to add DE shoot_y times and a jp z, endloop_addde2 ; if a is zero, no need to add .loop_addde2 add hl, de dec a jr nz, loop_addde2 ; at the end, HL has the tile address .endloop_addde2 ld a, (hl) and a jr z, continue_collisionloop xor a ld (ix+2), a ; my_active_shoots[i].sprnum=0 .continue_collisionloop ld bc, 12 ; 12 == sizeof (struct Entity) add ix, bc dec iyh jp nz, checkshootloop ret #endasm void ShowBombBar(void) { #asm ld hl, 56025 ; position in memory for the attributes of the progress bar ld a, (_frames_fire_pressed) sra a ; and divide by 2 .bar_onloop and a jr z, bar_off ld (hl), 0x03 inc hl dec a jr bar_onloop .bar_off ld a, (_frames_fire_pressed) sub 12 neg sra a .bar_offloop and a ret z ld (hl), 0x01 inc hl dec a jr bar_offloop #endasm } void gameloop(void) { while(mayday<7) { #asm waitvblank: ld a,r jp m, waitvblank ; while the screen has not been switched, we cannot continue waitframeskip: ld a, (_frameskip_counter) cp 2 jp c, waitframeskip ; we must wait until enough frames has passed xor a ld (_frameskip_counter), a ;halt di call _DrawGameMap ; draw map, interrupts must be disabled ld a, (_current_level) cp 2 jr z, noduplicatewyzplay ld b, 0 call setrambank ; we have missed one interrupt for sure, so call player call WYZ_PLAY .noduplicatewyzplay ld a, (_current_screen) xor 2 ; 5 xor 2 = 7; 7 xor 2 = 5 ld b, a call setrambank ; restore the previous paging state ei call _DrawEnemies ; draw enemies and enemy shoots (also valid for final enemies and their shoots) call _DrawShip ; draw ship, my shoots and power ups: at the same time, check ship collision ; call _CheckShipCollision ; check HERE if the ship hits the background or an enemy call _CheckShootCollision call MoveStarfield ; update starfield call Display_starfield ; now display it call _ShowBombBar ; display progress bar for superbomb ; Do we need to update the score? ld a, (_update_score) and a jr z, noupdatescore dec a ld (_update_score), a ld b, 120 ld c, 144 ld hl, (_score) call PrintLarge_5 .noupdatescore ; Do we need to update the number of superbombs? ld a, (_update_superb) and a jr z, noupdatesuperb dec a ld (_update_superb), a ld b, 72 ld c, 152 ld a, (_available_superbombs) call PrintLarge_2 .noupdatesuperb ; Do we need to update the number of lifes? ld a, (_update_life) and a jr z, noupdatelife dec a ld (_update_life), a ld b, 72 ld c, 136 ld a, (_life_counter) call PrintLarge_2 .noupdatelife ld a,r or $80 ld r,a ; set the highest bit of R to 1, so switch screen!!!! di ld b, 0 call setrambank ; leave the RAM bank 0 in place before continuing ei #endasm if(!mayday) // only check joystick if we are not dying { if(ship0spr == 6) ship0spr = 8; else ship0spr=0; if(inertia_cheat) { if(joy & JOY_UP) { speed_y = -4; ship0spr=2; } else if(joy & JOY_DOWN) { speed_y=4; ship0spr=4; } else speed_y=0; if(joy & JOY_LEFT) speed_x = -4; else if(joy & JOY_RIGHT) speed_x = 4; else speed_x=0; } else { if(joy & JOY_UP) { if(speed_y > -4) speed_y --; ship0spr=2; } else if(joy & JOY_DOWN) { if(speed_y < 4) speed_y ++; ship0spr=4; } else if(speed_y > 0) speed_y--; // No keys pressed, decrease speed else if(speed_y < 0) speed_y++; if(joy & JOY_LEFT) { if(speed_x > -4) speed_x --; } else if(joy & JOY_RIGHT) { if(speed_x < 4) speed_x++; } else if(speed_x > 0) speed_x--; else if(speed_x < 0) speed_x++; } if (joy & JOY_FIRE) { #asm ; increment frames_fire_pressed, unless it is 12 already ld a, (_frames_fire_pressed) inc a cp 13 jr nz, store_frames_fire_pressed dec a .store_frames_fire_pressed ld (_frames_fire_pressed), a #endasm if(!frames_to_shoot) { dummy_b = 1; #asm ld a, (_current_weapon) and a jp z, shot_case0 cp 1 jp z, shot_case1 cp 2 jp z, shot_case2 cp 3 jp z, shot_case3 cp 4 jp z, shot_case4 cp 5 jp nz, shot_noshoot .shot_case5 ; Megashot call _AvailShoots ld a, l cp 8 jp c, shot_noshoot ; less than 8 shoots available ; Play sound ld b, FX_DISPARO_MULTI call LOAD_FX ld a, SHOT_BASIC ld (_current_weapon_sprite), a ld a, (_ship_x) add a, 20 ld h, 0 ld l, a push hl ld a, (_ship_y) ld l, a push hl call _NewShoot ;NewShoot(ship_x+20, ship_y) pop de pop hl ld a, SHOT_MEGA ld (_current_weapon_sprite), a ld a, (_ship_x) add a, 20 ld h, 0 ld l, a push hl ; ship_x+20 ld a, (_ship_y) sub 12 jr c, case5_skip_shot2 ld l, a ; ship_y-12 push hl call _NewShoot ;NewShoot(ship_x+20, ship_y-12) ld a, l or h jr z, case5_shot2_not_created ; if the shot was not created, skip inc hl inc hl inc hl inc hl ld (HL), MOVE_UPRIGHT .case5_shot2_not_created pop bc .case5_skip_shot2 pop bc ld a, (_ship_x) add a, 20 ld h, 0 ld l, a push hl ; ship_x+20 ld a, (_ship_y) add a, 12 ; ship_y +12 ld l, a push hl call _NewShoot ;NewShoot(ship_x+20, ship_y+12) ld a, l or h jr z, case5_shot3_not_created ; if the shot was not created, skip inc hl inc hl inc hl inc hl ld (HL), MOVE_DOWNRIGHT inc hl inc hl inc hl ld (hl), 8 ; e->param2=8 .case5_shot3_not_created pop de pop bc ld a, (_ship_x) ld h, 0 ld l, a push hl ; ship_x ld a, (_ship_y) sub 12 jr c, case5_skip_shot4 ld l, a push hl ; ship_y-12 call _NewShoot ;NewShoot(ship_x, ship_y-12) ld a, l or h jr z, case5_shot4_not_created ; if the shot was not created, skip inc hl inc hl inc hl inc hl ld (HL), MOVE_UPLEFT inc hl inc hl inc hl ld (hl), 8 ; e->param2=8 .case5_shot4_not_created pop de .case5_skip_shot4 pop bc ld a, (_ship_x) ld h, 0 ld l, a push hl ; ship_x ld a, (_ship_y) add a, 12 ; ship_y +12 ld l, a push hl call _NewShoot ;NewShoot(ship_x, ship_y+12) ld a, l or h jr z, case5_shot5_not_created ; if the shot was not created, skip inc hl inc hl inc hl inc hl ld (HL), MOVE_DOWNLEFT inc hl inc hl inc hl ld (hl), 8 ; e->param2=8 .case5_shot5_not_created pop de pop bc ld a, (_ship_x) sub 12 jr c, case5_skip_shot6 ld h, 0 ld l, a push hl ; ship_x-12 ld a, (_ship_y) ld l, a push hl ; ship_y call _NewShoot ;NewShoot(ship_x-12, ship_y) ld a, l or h jr z, case5_shot6_not_created ; if the shot was not created, skip inc hl inc hl inc hl inc hl ld (HL), MOVE_LEFT .case5_shot6_not_created pop de pop bc .case5_skip_shot6 ld a, (_ship_x) add a, 12 ld h, 0 ld l, a push hl ; ship_x+12 ld a, (_ship_y) sub 12 jr c, case5_skip_shot7 ld l, a push hl ; ship_y-12 call _NewShoot ;NewShoot(ship_x+12, ship_y-12) ld a, l or h jr z, case5_shot7_not_created ; if the shot was not created, skip inc hl inc hl inc hl inc hl ld (HL), MOVE_UP .case5_shot7_not_created pop de .case5_skip_shot7 pop bc ld a, (_ship_x) add a, 12 ld h, 0 ld l, a push hl ; ship_x+12 ld a, (_ship_y) add a, 12 ld l, a push hl call _NewShoot ;NewShoot(ship_x+12, ship_y+12) ld a, l or h jr z, case5_shot8_not_created ; if the shot was not created, skip inc hl inc hl inc hl inc hl ld (HL), MOVE_DOWNLEFT inc hl inc hl inc hl ld (hl), 2 ; e->param2=2 .case5_shot8_not_created pop de pop de jp shot_endcase .shot_case0 ; Basic shot call _AvailShoots ld a, l and a jp z, shot_noshoot ; no available shoots ld a, (_ship_x) add a, 20 ld h, 0 ld l, a push hl ld a, (_ship_y) ld l, a push hl call _NewShoot ;NewShoot(ship_x+20, ship_y) pop hl pop hl ; Play sound ld b, FX_SINGLE_SHOOT call LOAD_FX jp shot_endcase .shot_case1 ; triple shoot call _AvailShoots ld a, l cp 3 jp c, shot_noshoot ; less than 3 shoots available ld a, (_ship_x) add a, 20 ld h, 0 ld l, a push hl ld a, (_ship_y) sub 12 jr c, case1_skip_shot1 ld l, a push hl call _NewShoot ;NewShoot(ship_x+20, ship_y-12) pop hl .case1_skip_shot1 pop hl ld a, (_ship_x) add a, 20 ld h, 0 ld l, a push hl ld a, (_ship_y) add a, 12 ld l, a push hl call _NewShoot ;NewShoot(ship_x+20, ship_y+12) pop hl pop hl ld a, (_ship_x) add a, 20 ld h, 0 ld l, a push hl ld a, (_ship_y) ld l, a push hl call _NewShoot ;NewShoot(ship_x+20, ship_y) pop hl pop hl ; Play sound ld b, FX_TRIPLE_SHOOT call LOAD_FX jp shot_endcase .shot_case2 ; Laser call _AvailShoots ld a, l cp 2 jp c, shot_noshoot ; less than 2 shoots available ld a, (_ship_x) add a, 20 ld h, 0 ld l, a push hl ld a, (_ship_y) ld l, a push hl call _NewShoot ;NewShoot(ship_x+20, ship_y) pop hl pop hl ; Play sound ld b, FX_LASER call LOAD_FX ld a, (_ship_x) add a, 36 cp 208 jr nc, case2_skip_shot2 ld h, 0 ld l, a push hl ld a, (_ship_y) ld l, a push hl call _NewShoot ;NewShoot(ship_x+36, ship_y) pop hl pop hl .case2_skip_shot2 jp shot_endcase .shot_case3 ; homing missile call _AvailShoots ld a, l and a jp z, shot_noshoot ; no available shoots ld a, (_ship_x) add a, 20 ld h, 0 ld l, a push hl ld a, (_ship_y) ld l, a push hl call _NewShoot ;NewShoot(ship_x+20, ship_y) pop de pop de ; HL holds the pointer to the new shoot ld de, 4 add hl, de ; HL points to e->movement ld (hl), MOVE_HOMING ; now go find the first available active enemy exx ld c, 0 ; C will serve as counter for the enemies ld hl, _active_enemies+2 ; go for the sprnums ld de, 12 ; sizeof (struct Entity) .loop_case3 ld a, (hl) and a jr nz, found_case3 add hl, de inc c ld a, MAX_ENEMIES cp c jr nz, loop_case3 ld c, 0 ; we got out of the loop without finding any active enemies .found_case3 ld a, c exx inc hl inc hl inc hl ld (hl), a ; param2 ; Play sound ld b, FX_DISPARO_HOMMING call LOAD_FX jp shot_endcase .shot_case4 ; bomb call _AvailShoots ld a, l cp 2 jp c, shot_noshoot ; less than 2 shoots available ; Play sound ld b, FX_DISPARO_HOMMING call LOAD_FX ld a, SHOT_BASIC ld (_current_weapon_sprite), a ld a, (_ship_x) add a, 20 ld h, 0 ld l, a push hl ld a, (_ship_y) ld l, a push hl call _NewShoot ;NewShoot(ship_x+20, ship_y) pop de pop de ld a, SHOT_BOMB ld (_current_weapon_sprite), a ld a, (_ship_x) add a, 10 ld h, 0 ld l, a push hl ld a, (_ship_y) add a, 10 ld l, a push hl call _NewShoot ;NewShoot(ship_x, ship_y+20) pop de pop de ; HL now holds the received entity ld a, h or l jr z, shot_endcase ; If the new shoot is NULL, do not touch ld bc, 4 add hl, bc ld (hl), MOVE_DOWNRIGHT inc hl inc hl ld (hl), 4 inc hl ld (hl), 0 jp shot_endcase .shot_noshoot xor a ld (_dummy_b), a .shot_endcase #endasm /* switch(current_weapon) { case 0: // Basic shot dummy_i=NewShoot(ship_x+20, ship_y); break; case 1: // Double shot if(AvailShoots() > 1) { NewShoot(ship_x+20, ship_y-4); NewShoot(ship_x+20, ship_y+4); } break; case 2: // Triple shot if (AvailShoots() > 2) { NewShoot(ship_x+20, ship_y-12); NewShoot(ship_x+20, ship_y); NewShoot(ship_x+20, ship_y+12); } break; case 3: // ray if (AvailShoots() > 1) { NewShoot(ship_x+20, ship_y); NewShoot(ship_x+36, ship_y); } break; case 4: // homing missile if (AvailShoots()) { current_e=NewShoot(ship_x+20, ship_y); current_e->movement = MOVE_HOMING; // Find the first available active enemy. This must be FIXME in assembler for(i=0;i<MAX_ENEMIES;i++) { if(active_enemies[i].sprnum) { current_e->param2 = i; break; } } } break; case 5: // basic + bomb if (AvailShoots() > 1) { current_weapon_sprite=SHOT_BASIC; NewShoot(ship_x+20, ship_y); current_weapon_sprite=SHOT_BOMB; current_e = NewShoot(ship_x, ship_y+20); current_e->movement = MOVE_DOWNLEFT; current_e->param1 = 4; current_e->param2 = 1; } break; case 6: // Megashoot if (AvailShoots() > 7) { current_weapon_sprite=SHOT_BASIC; NewShoot(ship_x+20, ship_y); current_weapon_sprite=SHOT_MEGA; current_e = NewShoot(ship_x+20, ship_y-12); // up right current_e->movement = MOVE_UPRIGHT; current_e = NewShoot(ship_x+20, ship_y+12); // down right - not yet implemented FIXME current_e->movement = MOVE_DOWNRIGHT; current_e->param2 = 8; current_e = NewShoot(ship_x, ship_y-12); // up left current_e->movement = MOVE_UPLEFT; current_e = NewShoot(ship_x, ship_y+12); current_e->movement = MOVE_DOWNLEFT; current_e->param2 = 8; current_e = NewShoot(ship_x-12, ship_y); // left current_e->movement = MOVE_LEFT; current_e = NewShoot(ship_x+12, ship_y-12); // up - not yet implemented FIXME current_e->movement = MOVE_UP; current_e = NewShoot(ship_x+12, ship_y+12); // down current_e->movement = MOVE_DOWNLEFT; current_e->param2 = 2; } break; }*/ if (dummy_b) if (( joy & (JOY_UP | JOY_DOWN)) == 0) ship0spr=6; if (frames_fire_pressed < 5) frames_to_shoot=5; else frames_to_shoot=15; } } else // Fire is not pressed. Check here if we are about to launch the BFB (big f*cking bomb) { if ((frames_fire_pressed > 11) && (available_superbombs)) { Do_Superbomb(); available_superbombs--; update_superb=2; #asm ld b, FX_BLAST call LOAD_FX #endasm } frames_fire_pressed=0; } } // Update ship speed if needed ship_x += speed_x; if (ship_x > 208) { if(speed_x > 0) ship_x = 208; else ship_x=0; } ship_y += speed_y; if (ship_y > 112) { if(speed_y > 0) ship_y = 112; else ship_y=0; } // Move map to new position if((map_xpos < (CurLevel_XLength - 11)) || (map_displacement < 0x04)) { map_displacement++; if (map_displacement > 0xb) { map_displacement = 0; map_xpos++; } /* if (current_level == 2) { map_displacement++; if (map_displacement > 0xb) { map_displacement = 0; map_xpos++; } } */ } else if(!final_enemy_active) // Reached the end of the level, time to activate the final enemy!!!! { activate_final_enemy(); } // Move active enemies and shoots #asm ld a, (23388) and $07 ; keep low bits push af ; save current state ld b, 6 di call setrambank ; go to ram bank 1 to manage the sprites ei ld b, MAX_ENEMIES ld ix, _active_enemies ld de, _enemy_active_shoots ld iy, _my_active_shoots .moveenemy_loop push bc ld a, (ix+2) and a jp z, loop_move_shoot ld hl, _movement_funcs ld c, (ix+4) ld b, 0 ; BC == my_active_shoots[i].movement add hl, bc add hl, bc ; HL == &movement_funcs[my_active_shoots[i].movement] ld c, (hl) inc hl ld b, (hl) ld (call_moveenemy + 1), bc push ix pop hl ; HL == active_enemies[i] push ix push iy push de .call_moveenemy call 0 ; is there any way to do this without self-modifying code?? a kind of call (de) or so pop de pop iy pop ix .loop_move_shoot ld a, (iy+2) and a jr z, loop_move_enemyshoot ld hl, _movement_funcs ld c, (iy+4) ld b, 0 ; BC == my_active_shoots[i].movement add hl, bc add hl, bc ; HL == &movement_funcs[my_active_shoots[i].movement] ld c, (hl) inc hl ld b, (hl) ld (call_moveshoot + 1), bc push iy pop hl ; HL == my_active_shoots[i] push ix push iy push de .call_moveshoot call 0 ; is there any way to do this without self-modifying code?? a kind of call (de) or so pop de pop iy pop ix .loop_move_enemyshoot push ix ld a, d ld ixh, a ld a, e ld ixl, a ld a, (ix+2) and a jr z, loop_move_continue ld hl, _movement_funcs ld a, (ix+4) ld c, a ld b, 0 ; BC == enemy_active_shoots[i].movement add hl, bc add hl, bc ; HL == &movement_funcs[enemy_active_shoots[i].movement] ld c, (hl) inc hl ld b, (hl) ld (call_moveenemyshoot + 1), bc push ix pop hl ; HL == enemy_active_shoots[i] push iy push de .call_moveenemyshoot call 0 ; is there any way to do this without self-modifying code?? a kind of call (de) or so pop de pop iy .loop_move_continue pop ix ld bc, 12 ; 12 = sizeof(struct Entity) add ix, bc ; go to the next entity add iy, bc ld hl, 12 add hl, de ex de, hl pop bc dec b jp nz, moveenemy_loop ; continue loop #endasm // Move enemies with follow_* movement types, only if current_level is 6 // Actually we are executing this twice, but it is not a big issue. This just // ensures that, if the reference enemy is located later in the active_enemies // table, continuity is done properly, as the one following must be processed later #asm ld a, (_current_level) cp 6 jp nz, nolevel7 ld b, MAX_ENEMIES ld ix, _active_enemies .moveenemyfollow_loop push bc push ix ld a, (ix+2) and a jp z, loop_movefollow_continue ld hl, _movement_funcs ld a, (ix+4) cp 22 ;MOVE_FOLLOW_RIGHT jr z, do_follow_movement cp 23 ; MOVE_FOLLOW_DOWN jr z, do_follow_movement cp 24 ; MOVE_FOLLOW_DOWNRIGHT jr nz, loop_movefollow_continue .do_follow_movement ld c, (ix+4) ld b, 0 ; BC == my_active_shoots[i].movement add hl, bc add hl, bc ; HL == &movement_funcs[my_active_shoots[i].movement] ld c, (hl) inc hl ld b, (hl) ld (call_moveenemyfollow + 1), bc pop hl ; HL == active_enemies[i] push ix .call_moveenemyfollow call 0 ; is there any way to do this without self-modifying code?? a kind of call (de) or so .loop_movefollow_continue pop ix ld bc, 12 ; 12 = sizeof(struct Entity) add ix, bc ; go to the next entity pop bc dec b jp nz, moveenemyfollow_loop ; continue loop .nolevel7 #endasm // Move power up #asm ld de, _power_up inc de inc de ld a, (de) and a jp z, ignore_move_powerup ld hl, _movement_funcs inc de inc de ld a, (de) ld c, a ld b, 0 ; BC == my_active_shoots[i].movement add hl, bc add hl, bc ; HL == &movement_funcs[power_up.movement] ld c, (hl) inc hl ld b, (hl) ld (call_powerup + 1), bc ld hl, _power_up .call_powerup call 0 ; is there any way to do this without self-modifying code?? a kind of call (de) or so ; Now, check if the power up is colliding with the ship. If so, get power up! ld a, (_ship_x) rrca rrca rrca and $1f ld (_shoot_xchar), a ; shoot_xchar = ship_x / 8 ld a, (_ship_y) rrca rrca rrca and $1f ld (_shoot_ychar), a ; shoot_ychar = ship_y / 8 ld hl, _power_up ld a, (hl) rrca rrca rrca and $1f ld hl, _shoot_xchar sub (hl) ld d, a ; D = power_up->x / 8 - shoot_xchar ld hl, _power_up+1 ld a, (hl) rrca rrca rrca and $1f ld hl, _shoot_ychar sub (hl) ld e, a ; E = power_up->y / 8 - shoot_ychar ; we want to check if abs(D) is -1, 0, 1, 2 or 3, and abs(E) is 0 or 1. ; So we add one to E, and if the value as unsigned is less than 3, we got it ; and add one to D, and if the value as unsigned is less than 5, we got it inc d inc e ld a, 4 cp d jr c, ignore_move_powerup ld a, 2 cp e jr c, ignore_move_powerup ; Not ignoring, so... We got the power up!!!!!!! ; Play power up sound ld hl, FX_POWERUP push hl call _wyz_effect pop hl ; Increase score ld hl, (_score) ld de, 20 ; 200 more points add hl, de ld (_score), hl ; increment score and store ld a, 2 ld (_update_score), a ; We need yo update the score twice ld hl, _power_up + 2 ld (hl), 0 ld bc, 5 add hl, bc ld a, (hl) ; A holds the power up + 57 sub 57 ; get the right one and a jr z, powerup_more_superbombs dec a jr z, powerup_more_firepower ld (_current_weapon), a ; This is a normal powerup, starting at 59 ld hl, _shoot_sprites ld c, a ld b, 0 add hl, bc ld a, (hl) ld (_current_weapon_sprite), a ; current_weapon_sprite = shoot_sprites[current_weapon]; ld hl, _shoot_energy add hl, bc ld a, (hl) ld (_current_weapon_energy), a ; current_weapon_energy = shoot_energy[current_weapon]; ld hl, _shoot_max_number add hl, bc ld a, (hl) ld (_max_shoots), a ; max_shoots=shoot_max_number[current_weapon]; jr ignore_move_powerup .powerup_more_firepower ld a, (_max_shoots) rlca ; max_shoots * 2 cp 9 jr nc, ignore_move_powerup ; if the upgraded number of shoots is greater than 8, ignore ld (_max_shoots), a jr ignore_move_powerup .powerup_more_superbombs ld a, (_available_superbombs) inc a ld (_available_superbombs), a ld a, 2 ld (_update_superb), a .ignore_move_powerup di pop af ; recover RAM bank state ld b, a call setrambank ; go back to normal state ei #endasm /* for(i=0;i<MAX_ENEMIES;i++) { if (active_enemies[i].sprnum) // This enemy is active { (movement_funcs[active_enemies[i].movement])(&active_enemies[i]); // Process enemy movement } if (my_active_shoots[i].sprnum) // This shoot is active { (movement_funcs[my_active_shoots[i].movement])(&my_active_shoots[i]); // Process shoot movement } if (enemy_active_shoots[i].sprnum) // This enemy shoot is active { (movement_funcs[enemy_active_shoots[i].movement])(&enemy_active_shoots[i]); // Process enemy shoot movement } }*/ // Activate/deactivate new enemies // while(enemy_locations[new_enemy].x < (map_xpos+11)) #asm di ld b, 4 call setrambank ; go to ram bank 4 to manage the enemy locations ei #endasm while (((int)((enemy_locations[new_enemy].x - map_xpos) * 24) - (map_displacement<<1) + enemy_locations[new_enemy].x_desp) < 256) { NewEnemy(&enemy_locations[new_enemy],0); new_enemy++; } #asm di ld b, 0 call setrambank ; go back to normal state ei #endasm // Process shoots if (frames_to_shoot) frames_to_shoot--; // Less time to wait #asm ld a, (_max_shoots) ld b, a ld ix, _my_active_shoots .checkshoots_loop push bc ld a, (ix+2) and a jr z, continue_loop_shoots ; This shoot is active, check collisions push ix call _shoot_hits_enemy ; HL will hold the result, pop ix ld a, 255 cp l jr z, continue_loop_shoots ; if != 255, we have found a collision ld a, l inc a ld bc, 12 ld hl, _active_enemies - 12 .loop_multiply_12 add hl, bc dec a jr nz, loop_multiply_12 ; HL is now active_enemies[dummy_n] ; we need to substract the current weapon energy from the enemy energy ld bc, 5 add hl, bc ; energy ld a, (_current_weapon_energy) ld c, a ld a, (hl) and a ; If energy is 0, ignore (not killable or already dead) jr z, shot_completed sub c jr c, enemy_dead jr z, enemy_dead ; if the energy is 0 or < 0, it is dead ld (hl), a ; new energy ; Play enemy hit sound ld b, FX_DAMAGE call LOAD_FX jr shot_completed .enemy_dead ld (hl), 0 ; enemy is dead inc hl ; param1 ld (hl), 4 dec hl dec hl ; movement ld (hl), MOVE_EXPLOSION dec hl ld a, (hl) ; type dec hl ; sprnum ld (hl), EXPLOSION_SPR ; Play enemy explosion sound ld b, FX_EXPLOSION call LOAD_FX ; increment score according to enemy killed ld hl, _enemy_score ld e, a ld d, 0 add hl, de ; DE points to the score earned by killing this enemy ld e, (hl) ; ld d, 0 ld hl, (_score) add hl, de ld (_score), hl ; increment score and store ld a, 2 ld (_update_score), a ; We need yo update the score twice ; check if we get an extra life ld de, (_next_extralife) sbc hl, de ; if there is no carry, we get an extra life jr c, shot_completed .extralife ld a, (_life_counter) inc a ld (_life_counter), a ld a, 2 ld (_update_life), a ; extra life, and update scoreboard ld hl, (_next_extralife) ld de, 200 add hl, de ld (_next_extralife), hl ; update the score to get the next extra life .shot_completed xor a ld (ix+2), a ; my_active_shoots[i].sprnum = 0; .continue_loop_shoots ld bc, 12 ; 12 = sizeof(struct Entity) add ix, bc pop bc dec b jp nz, checkshoots_loop ; djnz checkshoots_loop ; continue loop #endasm /* for(i=0;i<max_shoots;i++) { if (my_active_shoots[i].sprnum) // This shoot is active { dummy_b = shoot_hits_enemy(&(my_active_shoots[i])); if(dummy_b != 255) // This shoot has hit an enemy { active_enemies[dummy_b].sprnum=EXPLOSION_SPR; // exploding! active_enemies[dummy_b].movement=MOVE_EXPLOSION; active_enemies[dummy_b].param1=4; // 4 frames to explode my_active_shoots[i].sprnum = 0; } } } */ // Process enemy behavior, only if the final enemy is not active #asm ld a, (23388) and $07 ; keep low bits push af ; save current state ld b, 6 di call setrambank ; go to ram bank 6 to manage the sprites ei ld a, (_final_enemy_active) and a jp nz, finalenemy_behavior ld b, MAX_ENEMIES ld ix, _active_enemies .behavenemy_loop push bc ld a, (ix+2) and a jr z, loop_behav_continue ; continue if sprnum = 0 ; skip explosion detection if this is a power up or an asteroid ld a, (ix+3) cp 8 ; ENEMY_POWERUP jr z, behav_skip_expl cp 15 jr z, behav_skip_expl ; ENEMY_ASTEROID ld a, (ix+4) cp MOVE_EXPLOSION jr z, loop_behav_continue ; and also if the enemy is exploding .behav_skip_expl ld hl, _behavior_funcs ld c, (ix+10) ld b, 0 ; BC == my_active_shoots[i].behavior add hl, bc add hl, bc ; HL == &behavior_funcs[my_active_enemies[i].behavior] ld c, (hl) inc hl ld b, (hl) ld (call_behav + 1), bc push ix pop hl ; HL == active_enemies[i] push ix .call_behav call 0 ; is there any way to do this without self-modifying code?? a kind of call (de) or so pop ix .loop_behav_continue ld bc, 12 ; 12 = sizeof(struct Entity) add ix, bc ; go to the next entity pop bc dec b jp nz, behavenemy_loop ; continue loop jp behav_complete // Process final enemy behavior, when it is active .finalenemy_behavior ld a, (_current_level) add a, a ld c, a ld b, 0 ld hl, _fenemy_behavior_funcs add hl, bc ; HL == &fenemy_behavior_funcs[current_level] ld c, (hl) inc hl ld b, (hl) ld (call_fenemy_behav + 1), bc ld hl, _active_enemies ; Pass the active_enemies array, so we have some variables to play with .call_fenemy_behav call 0 ; is there any way to do this without self-modifying code?? a kind of call (de) or so ; check if we have beaten the final enemy ld a, (_fenemy_defeat) cp 10 jr c, behav_complete cp 110 jr nc, end_behav ld de, 1 ld hl, (_score) add hl, de ld (_score), hl ; increment score and store ; Play effect ld hl, FX_SCORE push hl call _wyz_effect pop hl ld a, 2 ld (_update_score), a ; We need yo update the score twice ; check if we get an extra life ld de, (_next_extralife) sbc hl, de ; if there is no carry, we get an extra life jr c, behav_complete .endlevel_extralife ld a, (_life_counter) inc a ld (_life_counter), a ld a, 2 ld (_update_life), a ; extra life, and update scoreboard ld hl, (_next_extralife) ld de, 200 add hl, de ld (_next_extralife), hl ; update the score to get the next extra life .end_behav ; we won! ld a, (_current_level) inc a ld (_current_level), a ld a, 7 ld (_mayday), a ; end current level xor a ld (_respawn_xpos), a ; next level has to start at X=0 .behav_complete di pop af ; recover RAM bank state ld b, a call setrambank ; go back to normal state ei #endasm if(fenemy_defeat == 1) { wyz_stop_music(); #asm ld b, FX_EXPLOSION call LOAD_FX #endasm } // Check collisions with enemies if(mayday==1) { ship0spr = MAINSHIP_EXPLOSION; life_counter--; mayday++; if (map_xpos >= level_checkpoints[(current_level <<2)+3]) respawn_xpos = level_checkpoints[(current_level <<2)+3]; else if (map_xpos >= level_checkpoints[(current_level <<2)+2]) respawn_xpos = level_checkpoints[(current_level <<2)+2]; else if (map_xpos >= level_checkpoints[(current_level <<2)+1]) respawn_xpos = level_checkpoints[(current_level <<2)+1]; else respawn_xpos = level_checkpoints[(current_level <<2)]; wyz_stop_music(); #asm ld b, FX_EXPLOSION call LOAD_FX #endasm } else if(mayday) { ship0spr+=2; mayday++; } } } void init_level(void) { wyz_load_music(level_music[current_level]); #asm ld a, (_sound_selection) ld (SOUND_SFX), a #endasm load_level(current_level); // Load specific sprites for this level LoadSprBlock(22,levelsprites[current_level],28); // The sprite block for each level will always be placed starting on sprite number 22, with a length of 28 sprites if(current_level == 6) LoadSprBlock(0,193,10); // For the last level, load the GENESIS sprites #asm call InitSprCacheList ; initialize sprite cache list #endasm // init everything ship_x=0; map_xpos=respawn_xpos; map_displacement=0; ship_y=64; speed_x=speed_y=frames_to_shoot=frames_fire_pressed=0; available_superbombs=1; final_enemy_active=0; fenemy_defeat=0; fenemy_activation_counter=0; level_color=levelcolors[current_level]; load_background(); clean_screen(); mayday=0; // not dying... yet current_weapon = 0; current_weapon_sprite = shoot_sprites[current_weapon]; current_weapon_energy = shoot_energy[current_weapon]; max_shoots=shoot_max_number[current_weapon]; ship0spr=0; update_score=0; update_superb=0; update_life=0; //for (i=0;i<MAX_ENEMIES;i++) active_enemies[i].sprnum=my_active_shoots[i].sprnum=enemy_active_shoots[i].sprnum=0; #asm ld de, _active_enemies+1 ld hl, _active_enemies ld (hl), 0 ld bc, 95 ldir ld de, _my_active_shoots ld hl, _active_enemies ld bc, 96 ldir ld de, _enemy_active_shoots ld hl, _active_enemies ld bc, 96 ldir #endasm power_up.sprnum=0; frameskip_counter=0; // Activate enemies new_enemy=0; #asm di ld b, 4 call setrambank ; go to ram bank 4 to manage the enemy locations #endasm while((map_xpos+10) > enemy_locations[new_enemy].x) new_enemy++; #asm ld b, 0 call setrambank ; go back to normal state ei #endasm } #asm .cleanattr ld hl, 16384+6144 ld (hl), 0 ld de, 16384+6145 ld bc, 767 ldir ; clean screen quickly ret #endasm unsigned char gameover(void) { #asm di call cleanattr ld b, 3 ; Static images in RAM3 call setrambank ; la ponemos en $c000 - $ffff ld hl, GAMEOVER_SCR ld de, 16384 call depack ld b, 0 call setrambank ei #endasm // Print credits counter #asm ld b, 152 ld c, 184 ld a, (_credit_counter) call PrintNumber_4000 #endasm if(credit_counter) { // Print "Press C to Continue" #asm ld hl, 23207 ld b, 19 .say_pressc ld (hl), $43 inc hl djnz say_pressc #endasm } else { // Print "Press Fire" #asm ld hl, 23179 ld b, 10 .say_pressfire ld (hl), $43 inc hl djnz say_pressfire #endasm } wyz_load_music(MUSIC_GAMEOVER); if(credit_counter) { #asm ld a, 150 ; will wait for 15 seconds .loop_wait_credit halt halt halt halt halt ; this is 1/10 of a second push af ld e, a ld d, 10 call Div8 ; A = number /10 (first digit), D = remainder (second digit) ld b, 120 ld c, 8 call PrintLarge_2_4000 ld BC, KEY_C call GET_KEY_STATE and a jr nz, end_check_continue ld a, (_credit_counter) dec a ld (_credit_counter), a call _wyz_stop_music ; Play sound ld b, FX_START_GAME call LOAD_FX ld b, 50 .delay_continue halt djnz delay_continue pop af ld hl, 0 ld (_score), hl ret ; return 0, meaning that we chose to continue .end_check_continue pop af dec a jr nz, loop_wait_credit #endasm } else { while ((joy & JOY_FIRE)==0) { } // Wait until fire is pressed while (joy & JOY_FIRE) {} // Wait until fire is released } wyz_stop_music(); return 1; } void happyend(void) { if (current_screen == 5) { current_screen=7; #asm di call switchscreen ei #endasm } #asm di call cleanattr ld b, 3 ; Static images in RAM3 call setrambank ; la ponemos en $c000 - $ffff ld hl, GAME_END_SCR ld de, 16384 call depack ld hl, GAME_END_ATTR ld de, $A000 ; use $a000 as the decompression point, as we do not need the map here... call depack ld b, 0 call setrambank ei #endasm if (inertia_cheat) wyz_load_music(MUSIC_HAPPYEND_CHEATER); else wyz_load_music(MUSIC_HAPPYEND_OK); // Fade for the message #asm ld c, 16 ; loop Y 16 times ld hl, 16384+6144+128 ; attribute for char X=0, Y=4 .fademessage_loopY push hl ld a, 5 ; loop 5 colors .fademessage_loopcolor ld b, 16 ; loop X 16 times halt halt halt halt halt halt push af push hl .fademessage_loopX ld a, (hl) cp 5 jp z, fademessage_equal inc (hl) .fademessage_equal inc hl djnz fademessage_loopX pop hl pop af dec a jp nz, fademessage_loopcolor pop hl ld de, 32 add hl, de dec c jp nz, fademessage_loopY #endasm // Fade for the egg #asm ld a, 7 ; loop 7 colors .fadeegg_outerloop halt halt halt halt halt halt halt halt push af ld c, 15 ; loop Y 15 times ld hl, 16384+6144+128+17 ; attribute for char X=17, Y=4 ld de, $a000+128+17 ; attribute for char X=17, Y=4 in the buffer .fadeegg_loopY ld b, 15 ; loop X 15 times push hl push de .fadeegg_loopX ld a, (de) inc de cp (hl) jp z, fadeegg_equal inc (hl) .fadeegg_equal inc hl djnz fadeegg_loopX pop de pop hl push bc ld bc, 32 add hl, bc ex de, hl add hl, bc ex de, hl ; add 32 to both counters pop bc dec c jp nz, fadeegg_loopY pop af dec a jp nz, fadeegg_outerloop #endasm // Wait for 2 seconds, then fade out message and fade in alien #asm ld b, 100 .loopwait halt djnz loopwait ; Now fade out message, all together ld a, 5 ; loop 5 colors .fadeout_outerloop halt halt halt halt halt halt halt halt push af ld c, 16 ; loop Y 16 times ld hl, 16384+6144+128 ; attribute for char X=0, Y=4 .fadeout_loopY ld b, 16 ; loop X 16 times push hl .fadeout_loopX ld a, (hl) and a jp z, fadeout_equal dec (hl) .fadeout_equal inc hl djnz fadeout_loopX pop hl ld de, 32 add hl, de ; add 32 to the counters dec c jp nz, fadeout_loopY pop af dec a jp nz, fadeout_outerloop ; Wait for 2 more seconds ld b, 100 .loopwait2 halt djnz loopwait2 ; Decompress and fade in alien di ld b, 3 ; Static images in RAM3 call setrambank ; la ponemos en $c000 - $ffff ei ld hl, ALIEN_END_SCR ld de, $A000 ; use $a000 as the decompression buffer, as we do not need the map here... call depack ld hl, ALIEN_END_ATTR ld de, $B800 ; use $B800 as the decompression point, as we do not need the tiles here... call depack di ld b, 0 call setrambank ei ; Copy the alien ld a, 192 ld de, 16384 ld hl, $A000 .alien_copy_loop ld bc, 18 ldir ld bc, 14 add hl, bc ex de, hl add hl, bc ex de, hl dec a jr nz, alien_copy_loop ; Copy alien attributes ld a, 24 ld de, 16384+6144 ld hl, $B800 .alien_copy_attr_loop ld bc, 18 ldir ld bc, 14 add hl, bc ex de, hl add hl, bc ex de, hl dec a jr nz, alien_copy_attr_loop #endasm if(inertia_cheat) { #asm ld hl, 23186 ld b, 12 .you_cheater1 ld (hl), $47 inc hl djnz you_cheater1 ld hl, 23186+32 ld b, 12 .you_cheater2 ld (hl), $47 inc hl djnz you_cheater2 ld hl, 23186+64 ld b, 12 .you_cheater3 ld (hl), $47 inc hl djnz you_cheater3 ld hl, 23186+96 ld b, 12 .you_cheater4 ld (hl), $47 inc hl djnz you_cheater4 #endasm } while ((joy & JOY_FIRE)==0) {} // Wait until fire is pressed while (joy & JOY_FIRE) {} // Wait until fire is released wyz_stop_music(); } unsigned char blink_startx[5]={14,6,12,15,19}; unsigned char blink_starty[5]={2,11,10,10,11}; unsigned char blink_width[5]={3,6,3,4,7}; unsigned char blink_height[5]={8,8,12,12,8}; unsigned char blink_color; #asm .PaintShipFull ld ix, _blink_startx ld iy, _blink_starty ld de, _blink_width exx ld de, _blink_height exx .loop_changecolour push af ld hl, 16384+6144 ld a, (iy+0) ld c, a ld b, 0 xor a rl c rl b rl c rl b rl c rl b rl c rl b rl c rl b ; multiply Y * 32 add hl, bc ld a, (ix+0) ld c, a ld b, 0 add hl, bc ; HL = first position to change exx ld a, (de) exx ld b, a ; B= height push hl .innerloopY_changecolour ld a, (de) ld c, a ; C = width .innerloopX_changecolour ld a, (_blink_color) ld (hl), a ; as a test inc hl dec c jr nz, innerloopX_changecolour pop hl push bc ld bc, 32 add hl, bc pop bc push hl djnz innerloopY_changecolour pop hl pop af inc ix inc iy inc de exx inc de exx dec a jp nz, loop_changecolour ret .PaintShip ld ix, _blink_startx ld iy, _blink_starty ld de, _blink_width exx ld de, _blink_height exx dec a jr z, loop_changecolour2 .loop_increment inc ix inc iy inc de exx inc de exx dec a jr nz, loop_increment .loop_changecolour2 ld hl, 16384+6144 ld a, (iy+0) ld c, a ld b, 0 xor a rl c rl b rl c rl b rl c rl b rl c rl b rl c rl b ; multiply Y * 32 add hl, bc ld a, (ix+0) ld c, a ld b, 0 add hl, bc ; HL = first position to change exx ld a, (de) exx ld b, a ; B= height push hl .innerloopY_changecolour2 ld a, (de) ld c, a ; C = width .innerloopX_changecolour2 ld a, (_blink_color) ld (hl), a ; as a test inc hl dec c jr nz, innerloopX_changecolour2 pop hl push bc ld bc, 32 add hl, bc pop bc push hl djnz innerloopY_changecolour2 pop hl ret #endasm void show_genesis_pieces(void) { if (current_screen == 5) { current_screen=7; #asm di call switchscreen ei #endasm } #asm halt di call cleanattr ld b, 3 ; Static images in RAM3 call setrambank ; la ponemos en $c000 - $ffff ld hl, SHIP_PIECES_SCR ld de, 16384 call depack ld b, 0 call setrambank ei #endasm // here we should do the changing colours effect!! #asm ; Play SFX call ASSEMBLE_EFFECT ; first, if previous_level == 5, we display the genesis assembled message ld a, (_previous_level) cp 5 jr nz, startpaint ld hl, 22758 ld b, 7 .say_genesis ld (hl), $C4 inc hl djnz say_genesis ld hl, 22769 ld b, 9 .say_assembled ld (hl), $C4 inc hl djnz say_assembled .startpaint ld a, 5 ld (_blink_color), a ld a, (_previous_level) call PaintShipFull ld b, 5 .blinkloop push bc ld a, 1 ld (_blink_color), a ld a, (_previous_level) call PaintShip ld b, 50 .sillyloop halt djnz sillyloop ld a, 5 ld (_blink_color), a ld a, (_previous_level) call PaintShip ld b, 50 .sillyloop2 halt djnz sillyloop2 pop bc djnz blinkloop #endasm wyz_stop_music(); // while ((joy & JOY_FIRE)==0) {} // Wait until fire is pressed // while (joy & JOY_FIRE) {} // Wait until fire is released } void main() { #asm ld a, r and $7f ld r,a ; clear the highest bit of the R register. It will be used to flag for a screen switch ld a, 0x8a ld hl, 0x8000 ld de, _gameISR call SetIM2 #endasm current_screen = 7; score=0; credit_counter=3; // 3 credits for(;;) { wyz_load_music(MUSIC_MAINMENU); #asm call cleanattr di ld b, 6 call setrambank ; go to ram bank 6 for the menu ei ld de, (_score) ; get the score, to see if we have a high score! call MAINMENU ld a, (SELECTED_JOYSTICK) ld (_joystick_type),a ; store selected joystick ld a, (INERTIA_CHEAT) ld (_inertia_cheat),a ; store cheat status ld a, (SOUND_SELECTION) ld (_sound_selection), a ; store sound and/or sfx selection ld hl, (HIGH_SCORE) ld (_hiscore), hl ; store high score di ld b, 0 call setrambank ; go back to ram bank 0 for the menu ei call _wyz_stop_music call cleanattr #endasm #asm call GenStarfield ; generate starfield #endasm previous_level=current_level=0; respawn_xpos=0; score=0; next_extralife=200; // Load the common sprites, used everywhere LoadSprBlock(0, 0, 22); LoadSprBlock(50,50,14); end_game=0; while(!end_game) { life_counter=5; // 5 lives to start with while(life_counter != 255) { if(current_level == 7) // We won!!! { happyend(); life_counter=255; end_game=1; } else { if(previous_level != current_level) { if ((current_level > 1) && (current_level < 7)) show_genesis_pieces(); previous_level=current_level; } init_level(); gameloop(); #asm ld b, 25 .waitloop_endgame halt djnz waitloop_endgame #endasm wyz_stop_music(); /* // Very simple effect to clean the screen, left to right #asm di ld a, (_current_screen) xor 2 ld b, a call setrambank ei ld hl, 49152+6144 ; start of atribute zone ld a, 32 .outercleanloop halt ld b, 16 ld de, 32 push hl .innercleanloop ld (hl), 0 add hl, de djnz innercleanloop pop hl inc hl dec a jr nz, outercleanloop di ld b, 0 call setrambank ei #endasm*/ // Simple fade out effect #asm di ld a, (_current_screen) xor 2 ld b, a call setrambank ei ld c, 7 .outercleanloop halt halt ld hl, 49152+6144 ; start of atribute zone ld b,0 ld e,2 .innercleanloop1 ld a, (hl) and $f8 ld d, a ld a, (hl) and $7 jr z, continueinner1 dec a or d ld (hl), a .continueinner1 inc hl djnz innercleanloop1 dec e jr nz, innercleanloop1 dec c jr nz, outercleanloop di ld b, 0 call setrambank ei #endasm } } if (current_screen == 5) { current_screen=7; #asm di call switchscreen ei #endasm } // Display the game over screen, with its music and all stuff. if (!end_game) { end_game=gameover(); #asm call cleanattr #endasm } } } } // Here is the aplib depack routine, for now #asm ; aPPack decompressor ; original source by dwedit ; very slightly adapted by utopian ; optimized by Metalbrain ;hl = source ;de = dest .depack ld ixl,128 .apbranch1 ldi .aploop0 ld ixh,1 ;LWM = 0 .aploop call ap_getbit jr nc,apbranch1 call ap_getbit jr nc,apbranch2 ld b,0 call ap_getbit jr nc,apbranch3 ld c,16 ;get an offset .apget4bits call ap_getbit rl c jr nc,apget4bits jr nz,apbranch4 ld a,b .apwritebyte ld (de),a ;write a 0 inc de jr aploop0 .apbranch4 and a ex de,hl ;write a previous byte (1-15 away from dest) sbc hl,bc ld a,(hl) add hl,bc ex de,hl jr apwritebyte .apbranch3 ld c,(hl) ;use 7 bit offset, length = 2 or 3 inc hl rr c ret z ;if a zero is encountered here, it is EOF ld a,2 adc a,b push hl ld iyh,b ld iyl,c ld h,d ld l,e sbc hl,bc ld c,a jr ap_finishup2 .apbranch2 call ap_getgamma ;use a gamma code * 256 for offset, another gamma code for length dec c ld a,c sub ixh jr z,ap_r0_gamma ;if gamma code is 2, use old r0 offset, dec a ;do I even need this code? ;bc=bc*256+(hl), lazy 16bit way ld b,a ld c,(hl) inc hl ld iyh,b ld iyl,c push bc call ap_getgamma ex (sp),hl ;bc = len, hl=offs push de ex de,hl ld a,4 cp d jr nc,apskip2 inc bc or a .apskip2 ld hl,127 sbc hl,de jr c,apskip3 inc bc inc bc .apskip3 pop hl ;bc = len, de = offs, hl=junk push hl or a .ap_finishup sbc hl,de pop de ;hl=dest-offs, bc=len, de = dest .ap_finishup2 ldir pop hl ld ixh,b jr aploop .ap_r0_gamma call ap_getgamma ;and a new gamma code for length push hl push de ex de,hl ld d,iyh ld e,iyl jr ap_finishup .ap_getbit ld a,ixl add a,a ld ixl,a ret nz ld a,(hl) inc hl rla ld ixl,a ret .ap_getgamma ld bc,1 .ap_getgammaloop call ap_getbit rl c rl b call ap_getbit jr c,ap_getgammaloop ret #endasm
2.015625
2
2024-11-18T22:09:31.751145+00:00
2015-06-10T00:29:38
1af3b8023099ac805236ee7f5b92e6ea7156a435
{ "blob_id": "1af3b8023099ac805236ee7f5b92e6ea7156a435", "branch_name": "refs/heads/master", "committer_date": "2015-06-10T00:29:38", "content_id": "21dcead412aab3a56689e7e3c09055229cf7273c", "detected_licenses": [ "MIT" ], "directory_id": "4ec59cefb34a851ea69fd3ab517c693691c37701", "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": 8474, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0106.json.gz:35222", "repo_name": "cotaprecoarchive/qdecl", "revision_date": "2015-06-10T00:29:38", "revision_id": "0daf6e329c9f457b94dbfff16391bddf62acc8e6", "snapshot_id": "d3f4b5aeb3bafc80695827aaeb2da458a09a1d88", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cotaprecoarchive/qdecl/0daf6e329c9f457b94dbfff16391bddf62acc8e6/main.c", "visit_date": "2020-12-11T09:15:38.127641" }
stackv2
/* * Copyright (c) 2015 Cota Preço * * 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. */ /** * @author Andrey K. Vital <andreykvital@gmail.com> */ #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <amqp_tcp_socket.h> #include <amqp.h> #include <amqp_framing.h> /** * @param argc * @param argv * @param args * @return int (1 if requirements wasn't fulfilled 0 otherwise) */ int ensure_exchange_requirements(int argc, char *argv[], int args) { if (args == 0) { printf("You must specify exchange name and type\n"); return 1; } if (args == 1) { printf( "You must specify exchange type: direct, topic, fanout or headers for exchange `%s`\n", argv[argc - args] ); return 1; } char *exchange_name = argv[argc - args + 0]; char *exchange_type = argv[argc - args + 1]; int invalid_ex_type = ( strcmp(exchange_type, "direct") != 0 && strcmp(exchange_type, "topic") != 0 && strcmp(exchange_type, "fanout") != 0 && strcmp(exchange_type, "headers") != 0 ); if (invalid_ex_type) { printf( "%s%s%s. Got `%s`\n", "You've provided an invalid exchange type, only `direct`, ", "`topic`, `fanout`, `headers` ", "are acceptable", exchange_type ); return 1; } return 0; } /** * @param connection * @param channel */ void close_connection_and_channel(amqp_connection_state_t connection, int channel) { amqp_channel_close(connection, channel, AMQP_REPLY_SUCCESS); amqp_connection_close(connection, AMQP_REPLY_SUCCESS); } /** * @param connection * @return int (AMQP_RESPONSE_NORMAL|AMQP_RESPONSE_SERVER_EXCEPTION|AMQP_RESPONSE_LIBRARY_EXCEPTION) */ int get_reply_type(amqp_connection_state_t connection) { amqp_rpc_reply_t reply; reply = amqp_get_rpc_reply(connection); return reply.reply_type; } int main(int argc, char *argv[]) { static int durable, internal, auto_delete, exclusive, declare_exchange, declare_queue; enum { ARG_AMQP_HOST = 255, ARG_AMQP_PORT, ARG_AMQP_USER, ARG_AMQP_PASSWORD }; char const *amqp_host = "localhost", *amqp_user = "guest", *amqp_password = "guest"; int amqp_port = 5672; for (;;) { int c, opt_index = 0; static struct option long_opts[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"durable", no_argument, &durable, 'd'}, {"internal", no_argument, &internal, 'i'}, {"auto-delete", no_argument, &auto_delete, 'a'}, {"exclusive", no_argument, &exclusive, 'x'}, {"exchange", no_argument, &declare_exchange, 'e'}, {"queue", no_argument, &declare_queue, 'q'}, {"host", required_argument, 0, ARG_AMQP_HOST}, {"port", required_argument, 0, ARG_AMQP_PORT}, {"user", required_argument, 0, ARG_AMQP_USER}, {"password", required_argument, 0, ARG_AMQP_PASSWORD}, {0, 0, 0, 0} }; c = getopt_long(argc, argv, ":hvdiaxeq", long_opts, &opt_index); if (c == -1) { break; } switch (c) { case 'h': // TODO: display available [OPTIONS]! printf("Usage: qdecl [...OPTIONS] [exchange-name exchange-type | queue-name]\n"); return 0; case 'v': printf("Version %s, build %s\n", VERSION, GIT_COMMIT); return 0; case ARG_AMQP_HOST: amqp_host = optarg; break; case ARG_AMQP_PORT: amqp_port = atoi(optarg); break; case ARG_AMQP_USER: amqp_user = optarg; break; case ARG_AMQP_PASSWORD: amqp_password = optarg; break; case '?': default: break; } } if (! (declare_queue || declare_exchange)) { printf( "%s. %s\n", "You must choose declare a queue or an exchange", "See `qdecl -h` for more information!" ); } // printf("%s %s %s %d\n", amqp_host, amqp_user, amqp_password, amqp_port); int status; amqp_socket_t *socket = NULL; amqp_connection_state_t amqp_connection; amqp_connection = amqp_new_connection(); socket = amqp_tcp_socket_new(amqp_connection); status = amqp_socket_open(socket, amqp_host, amqp_port); // @link http://alanxz.github.io/rabbitmq-c/docs/0.4.0/amqp_8h.html#a05dadc32b3a59918206ac38a53606723 if (status == AMQP_STATUS_SOCKET_ERROR) { printf("Unable to connect :(\n"); return 1; } amqp_rpc_reply_t login_reply; login_reply = amqp_login( amqp_connection, "/", 0, /* channel_max */ 131072, /* frame_max */ 0, /* heartbeat */ AMQP_SASL_METHOD_PLAIN, amqp_user, amqp_password ); // @link http://alanxz.github.io/rabbitmq-c/docs/0.2/amqp_8h.html#ace098ed2a6aacbffd96cf9f7cd9f6465 if (login_reply.reply_type != AMQP_RESPONSE_NORMAL) { printf("Unable to authenticate :(\n"); return 1; } amqp_channel_open(amqp_connection, 1); if (get_reply_type(amqp_connection) != AMQP_RESPONSE_NORMAL) { printf("Unable to open channel :(\n"); return 1; } int args = (argc - optind); if (declare_exchange && ensure_exchange_requirements(argc, argv, args) != 0) { return 1; } if (declare_exchange) { char *exchange = argv[argc - args + 0]; char *exchange_type = argv[argc - args + 1]; // @link https://github.com/alanxz/rabbitmq-c/blob/master/librabbitmq/amqp_framing.h#L785-L793 amqp_exchange_declare( amqp_connection, 1, /* channel */ amqp_cstring_bytes(exchange), amqp_cstring_bytes(exchange_type), 0, /* passive */ durable, auto_delete, internal, amqp_empty_table ); int result = get_reply_type(amqp_connection) == AMQP_RESPONSE_NORMAL ? 0 : 1; close_connection_and_channel(amqp_connection, 1); return result; } if (! declare_queue) { return 0; } char *queue_name = argv[argc - args + 0]; if (! queue_name) { printf("You haven't provided the queue name to declare\n"); return 1; } // @link https://github.com/alanxz/rabbitmq-c/blob/master/librabbitmq/amqp_framing.h#L842-L850 amqp_queue_declare( amqp_connection, 1, /* channel */ amqp_cstring_bytes(queue_name), 0, /* passive */ durable, 0, /* exclusive */ auto_delete, amqp_empty_table ); int result = get_reply_type(amqp_connection) == AMQP_RESPONSE_NORMAL ? 0 : 1; close_connection_and_channel(amqp_connection, 1); return result; }
2.15625
2
2024-11-18T22:09:31.862658+00:00
2019-02-27T19:37:30
5c480cadc9aa25ebcfa1d149c80f8465ddb5eba6
{ "blob_id": "5c480cadc9aa25ebcfa1d149c80f8465ddb5eba6", "branch_name": "refs/heads/master", "committer_date": "2019-02-27T19:37:30", "content_id": "d1ca257a32604bf4f4ba9a0d03904f5f4711943d", "detected_licenses": [ "MIT" ], "directory_id": "a294bab81969833571c18e14873009b86529dc01", "extension": "h", "filename": "atomic.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": 13729, "license": "MIT", "license_type": "permissive", "path": "/Sources/CLoobeeCore/include/atomic.h", "provenance": "stackv2-0106.json.gz:35350", "repo_name": "qRoC/Loobee-OldRepository", "revision_date": "2019-02-27T19:37:30", "revision_id": "af5ee9c6983957d56c14460d811a8da4359af4ed", "snapshot_id": "7b837950d7ebc4407c3e4cdeb552d422a10c19c2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/qRoC/Loobee-OldRepository/af5ee9c6983957d56c14460d811a8da4359af4ed/Sources/CLoobeeCore/include/atomic.h", "visit_date": "2021-10-20T12:34:37.176394" }
stackv2
// This file is part of the Loobee package. // // (c) Andrey Savitsky <contact@qroc.pro> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #pragma once #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <assert.h> #define SWIFT_ENUM(args...) enum { args } /// enum CLoobeeCoreAtomic typedef SWIFT_ENUM( c_loobee_core_atomic_order_relaxed __attribute((swift_name("relaxed"))) = __ATOMIC_RELAXED, c_loobee_core_atomic_order_consume __attribute((swift_name("consume"))) = __ATOMIC_CONSUME, c_loobee_core_atomic_order_acquire __attribute((swift_name("acquire"))) = __ATOMIC_ACQUIRE, c_loobee_core_atomic_order_release __attribute((swift_name("release"))) = __ATOMIC_RELEASE, c_loobee_core_atomic_order_acq_rel __attribute((swift_name("acqRel"))) = __ATOMIC_ACQ_REL, c_loobee_core_atomic_order_seq_cst __attribute((swift_name("seqCst"))) = __ATOMIC_SEQ_CST ) c_loobee_core_atomic_order_t __attribute((swift_newtype(enum))) __attribute((swift_name("CLoobeeCoreAtomicOrder"))); /// let CLoobeeCoreAtomic#TYPE#_isLockFree #define LOOBEE_ATOMIC_IS_LOCK_FREE(id, cType, swiftType) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_isLockFree"))) /* */ static const bool c_loobee_core_atomic_##id##_is_lock_free = __atomic_always_lock_free(sizeof(cType), 0); /// func CLoobeeCoreAtomic#TYPE#_store #define LOOBEE_ATOMIC_STORE(id, cType, swiftType) /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_store(_:desired:order:)"))) /* */ void c_loobee_core_atomic_##id##_store( /* */ volatile cType *_Nonnull self, /* */ cType desired, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ assert(order == c_loobee_core_atomic_order_relaxed || /* */ order == c_loobee_core_atomic_order_seq_cst || /* */ order == c_loobee_core_atomic_order_release); /* */ __atomic_store_n(self, desired, order); /* */ } /// func CLoobeeCoreAtomic#TYPE#_load #define LOOBEE_ATOMIC_LOAD(id, cType, swiftType, qualifier) /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_load(_:order:)"))) /* */ qualifier cType c_loobee_core_atomic_##id##_load( /* */ const volatile cType *_Nonnull self, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ assert(order == c_loobee_core_atomic_order_relaxed || /* */ order == c_loobee_core_atomic_order_seq_cst || /* */ order == c_loobee_core_atomic_order_acquire || /* */ order == c_loobee_core_atomic_order_consume); /* */ return __atomic_load_n(self, order); /* */ } /// func CLoobeeCoreAtomic#TYPE#_exchange #define LOOBEE_ATOMIC_EXCHANGE(id, cType, swiftType, qualifier) /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_exchange(_:desired:order:)"))) /* */ qualifier cType c_loobee_core_atomic_##id##_exchange( /* */ volatile cType *_Nonnull self, /* */ cType desired, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ assert(order == c_loobee_core_atomic_order_relaxed || /* */ order == c_loobee_core_atomic_order_seq_cst || /* */ order == c_loobee_core_atomic_order_acquire || /* */ order == c_loobee_core_atomic_order_release || /* */ order == c_loobee_core_atomic_order_acq_rel); /* */ return __atomic_exchange_n(self, desired, order); /* */ } /// func CLoobeeCoreAtomic#TYPE#_compareExchangeWeak /// func CLoobeeCoreAtomic#TYPE#_compareExchangeStrong #define LOOBEE_ATOMIC_COMPARE_EXCHANGE(id, cType, swiftType, qualifier) /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_compareExchangeWeak(_:expected:desired:successOrder:failureOrder:)"))) /* */ bool c_loobee_core_atomic_##id##_compare_exchange_weak( /* */ volatile cType *_Nonnull self, /* */ qualifier cType *_Nonnull expected, /* */ cType desired, /* */ c_loobee_core_atomic_order_t successOrder, /* */ c_loobee_core_atomic_order_t failureOrder /* */ ) { /* */ assert(failureOrder == c_loobee_core_atomic_order_relaxed || /* */ failureOrder == c_loobee_core_atomic_order_consume || /* */ failureOrder == c_loobee_core_atomic_order_acquire || /* */ failureOrder == c_loobee_core_atomic_order_seq_cst || /* */ failureOrder <= successOrder); /* */ return __atomic_compare_exchange_n(self, expected, desired, true, successOrder, failureOrder); /* */ } /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_compareExchangeStrong(_:expected:desired:successOrder:failureOrder:)"))) /* */ bool c_loobee_core_atomic_##id##_compare_exchange_strong( /* */ volatile cType *_Nonnull self, /* */ qualifier cType *_Nonnull expected, /* */ cType desired, /* */ c_loobee_core_atomic_order_t successOrder, /* */ c_loobee_core_atomic_order_t failureOrder /* */ ) { /* */ assert(failureOrder == c_loobee_core_atomic_order_relaxed || /* */ failureOrder == c_loobee_core_atomic_order_consume || /* */ failureOrder == c_loobee_core_atomic_order_acquire || /* */ failureOrder == c_loobee_core_atomic_order_seq_cst); /* */ return __atomic_compare_exchange_n(self, expected, desired, false, successOrder, failureOrder); /* */ } /// func CLoobeeCoreAtomic#TYPE#_fetchAndAdd /// func CLoobeeCoreAtomic#TYPE#_fetchAndSub /// func CLoobeeCoreAtomic#TYPE#_addAndFetch /// func CLoobeeCoreAtomic#TYPE#_subAndFetch #define LOOBEE_ATOMIC_MATH(id, cType, cTypeOp, swiftType, qualifier) /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_fetchAndAdd(_:op:order:)"))) /* */ qualifier cType c_loobee_core_atomic_##id##_fetch_and_add( /* */ volatile cType *_Nonnull self, /* */ cTypeOp op, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ return __atomic_fetch_add(self, op, order); /* */ } /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_fetchAndSub(_:op:order:)"))) /* */ qualifier cType c_loobee_core_atomic_##id##_fetch_and_sub( /* */ volatile cType *_Nonnull self, /* */ cTypeOp op, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ return __atomic_fetch_sub(self, op, order); /* */ } /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_addAndFetch(_:op:order:)"))) /* */ qualifier cType c_loobee_core_atomic_##id##_add_and_fetch( /* */ volatile cType *_Nonnull self, /* */ cTypeOp op, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ return __atomic_add_fetch(self, op, order); /* */ } /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_subAndFetch(_:op:order:)"))) /* */ qualifier cType c_loobee_core_atomic_##id##_sub_and_fetch( /* */ volatile cType *_Nonnull self, /* */ cTypeOp op, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ return __atomic_sub_fetch(self, op, order); /* */ } /// func CLoobeeCoreAtomic#TYPE#_fetchAndBitAnd /// func CLoobeeCoreAtomic#TYPE#_fetchAndBitOr /// func CLoobeeCoreAtomic#TYPE#_fetchAndBitXor /// func CLoobeeCoreAtomic#TYPE#_bitAndAndFetch /// func CLoobeeCoreAtomic#TYPE#_bitOrAndFetch /// func CLoobeeCoreAtomic#TYPE#_bitXorAndFetch #define LOOBEE_ATOMIC_BIT(id, cType, swiftType) /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_fetchAndBitAnd(_:op:order:)"))) /* */ cType c_loobee_core_atomic_##id##_fetch_and_and( /* */ volatile cType *_Nonnull self, /* */ cType op, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ return __atomic_fetch_and(self, op, order); /* */ } /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_fetchAndBitOr(_:op:order:)"))) /* */ cType c_loobee_core_atomic_##id##_fetch_and_or( /* */ volatile cType *_Nonnull self, /* */ cType op, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ return __atomic_fetch_or(self, op, order); /* */ } /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_fetchAndBitXor(_:op:order:)"))) /* */ cType c_loobee_core_atomic_##id##_fetch_and_xor( /* */ volatile cType *_Nonnull self, /* */ cType op, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ return __atomic_fetch_xor(self, op, order); /* */ } /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_bitAndAndFetch(_:op:order:)"))) /* */ cType c_loobee_core_atomic_##id##_and_and_fetch( /* */ volatile cType *_Nonnull self, /* */ cType op, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ return __atomic_and_fetch(self, op, order); /* */ } /* */ static __inline__ __attribute__((__always_inline__)) /* */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_bitOrAndFetch(_:op:order:)"))) /* */ cType c_loobee_core_atomic_##id##_or_and_fetch( /* */ volatile cType *_Nonnull self, /* */ cType op, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ return __atomic_or_fetch(self, op, order); /* */ } /* */ static __inline__ __attribute__((__always_inline__)) /*s */ __attribute((swift_name("CLoobeeCoreAtomic"#swiftType"_bitXorAndFetch(_:op:order:)"))) /* */ cType c_loobee_core_atomic_##id##_xor_and_fetch( /* */ volatile cType *_Nonnull self, /* */ cType op, /* */ c_loobee_core_atomic_order_t order /* */ ) { /* */ return __atomic_xor_fetch(self, op, order); /* */ } // ===================================================================================================================== LOOBEE_ATOMIC_IS_LOCK_FREE(bool, bool, Bool) LOOBEE_ATOMIC_STORE(bool, bool, Bool) LOOBEE_ATOMIC_LOAD(bool, bool, Bool,) LOOBEE_ATOMIC_EXCHANGE(bool, bool, Bool,) LOOBEE_ATOMIC_COMPARE_EXCHANGE(bool, bool, Bool,) #define LOOBEE_ATOMIC_SCALAR(id, cType, swiftType) /* */ LOOBEE_ATOMIC_IS_LOCK_FREE(id, cType, swiftType) /* */ LOOBEE_ATOMIC_STORE(id, cType, swiftType) /* */ LOOBEE_ATOMIC_LOAD(id, cType, swiftType,) /* */ LOOBEE_ATOMIC_EXCHANGE(id, cType, swiftType,) /* */ LOOBEE_ATOMIC_COMPARE_EXCHANGE(id, cType, swiftType,) /* */ LOOBEE_ATOMIC_MATH(id, cType, cType, swiftType,) /* */ LOOBEE_ATOMIC_BIT(id, cType, swiftType) LOOBEE_ATOMIC_SCALAR(uint8, uint8_t, UInt8) LOOBEE_ATOMIC_SCALAR(int8, int8_t, Int8) LOOBEE_ATOMIC_SCALAR(uint16, uint16_t, UInt16) LOOBEE_ATOMIC_SCALAR(int16, int16_t, Int16) LOOBEE_ATOMIC_SCALAR(uint32, uint32_t, UInt32) LOOBEE_ATOMIC_SCALAR(int32, int32_t, Int32) LOOBEE_ATOMIC_SCALAR(uint64, uint64_t, UInt64) LOOBEE_ATOMIC_SCALAR(int64, int64_t, Int64) LOOBEE_ATOMIC_SCALAR(uint, unsigned long int, UInt) LOOBEE_ATOMIC_SCALAR(int, long int, Int) #undef LOOBEE_ATOMIC_IS_LOCK_FREE #undef LOOBEE_ATOMIC_STORE #undef LOOBEE_ATOMIC_LOAD #undef LOOBEE_ATOMIC_EXCHANGE #undef LOOBEE_ATOMIC_COMPARE_EXCHANGE #undef LOOBEE_ATOMIC_MATH #undef LOOBEE_ATOMIC_BIT #undef LOOBEE_ATOMIC_SCALAR
2.078125
2
2024-11-18T22:09:31.934386+00:00
2023-08-09T20:37:17
f52353cc3d5bcf31eb5528bd7369a45300782fbb
{ "blob_id": "f52353cc3d5bcf31eb5528bd7369a45300782fbb", "branch_name": "refs/heads/master", "committer_date": "2023-08-09T20:37:17", "content_id": "5b0f58f588b5e0f145930802c1c438ee6e0bd6bc", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "e40786750384853affb3439b51dbb59b06e28561", "extension": "c", "filename": "progress.c", "fork_events_count": 23, "gha_created_at": "2018-09-26T19:38:29", "gha_event_created_at": "2023-08-09T20:37:18", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 150480638, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1137, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/progress.c", "provenance": "stackv2-0106.json.gz:35478", "repo_name": "Polarisru/updiprog", "revision_date": "2023-08-09T20:37:17", "revision_id": "10c5057409e2e6e57055ee36ebe9873be37053d6", "snapshot_id": "0784405dd426654744c11e0d36e074d1360066bb", "src_encoding": "UTF-8", "star_events_count": 32, "url": "https://raw.githubusercontent.com/Polarisru/updiprog/10c5057409e2e6e57055ee36ebe9873be37053d6/progress.c", "visit_date": "2023-08-17T02:17:27.198971" }
stackv2
#include <stdio.h> #include <string.h> #include "progress.h" /** \brief Print progress bar with prefix * * \param [in] iteration Current iteration * \param [in] total Total number of iterations * \param [in] prefix Prefix text * \param [in] fill Char to use for filling the bar * \return Noting * */ void PROGRESS_Print(uint16_t iteration, uint16_t total, char *prefix, char fill) { uint8_t filledLength; float percent; char bar[PROGRESS_BAR_LENGTH + 1]; char bar2[PROGRESS_BAR_LENGTH + 1]; memset(bar, fill, PROGRESS_BAR_LENGTH); bar[PROGRESS_BAR_LENGTH] = 0; memset(bar2, ' ', PROGRESS_BAR_LENGTH); bar2[PROGRESS_BAR_LENGTH] = 0; percent = (float)iteration / total * 100; filledLength = (uint8_t)(PROGRESS_BAR_LENGTH * iteration / total); printf("\r%s [%.*s%.*s] %.1f%%", prefix, filledLength, bar, PROGRESS_BAR_LENGTH - filledLength, bar2, percent); fflush(stdout); // Print New Line on Complete if (iteration >= total) printf("\n"); } /** \brief Do break in the output * * \return Nothing * */ void PROGRESS_Break(void) { printf("\n"); }
3.125
3
2024-11-18T22:09:32.006655+00:00
2015-04-17T17:56:20
4917a7a2277c8bcba38675f873be4f72d953f0bd
{ "blob_id": "4917a7a2277c8bcba38675f873be4f72d953f0bd", "branch_name": "refs/heads/master", "committer_date": "2015-04-17T17:56:20", "content_id": "2dc96b30474cc5e9b1c66e3b501144ddc9eacca1", "detected_licenses": [ "ISC" ], "directory_id": "66bdc05e3e7e0a2069cbf59a8dad1fdf7a52caef", "extension": "c", "filename": "com.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 7389536, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10650, "license": "ISC", "license_type": "permissive", "path": "/gcc/linux/com.c", "provenance": "stackv2-0106.json.gz:35606", "repo_name": "razzlefratz/MotleyTools", "revision_date": "2015-04-17T17:56:20", "revision_id": "3c69c574351ce6f4b7e687c13278d4b6cbb200f3", "snapshot_id": "5e44f1315baa1be6fe5221916ccc834a96b59ca6", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/razzlefratz/MotleyTools/3c69c574351ce6f4b7e687c13278d4b6cbb200f3/gcc/linux/com.c", "visit_date": "2020-05-19T05:01:58.992424" }
stackv2
#include <termios.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/signal.h> #include <sys/types.h> #define BAUDRATE B38400 #define MODEMDEVICE "/dev/ttyS1" #define _POSIX_SOURCE 1 //POSIX compliant source #define FALSE 0 #define TRUE 1 volatile int STOP=FALSE; void signal_handler_IO (int status); //definition of signal handler int wait_flag=TRUE; //TRUE while no signal received char devicename [80]; long Baud_Rate = 38400; // default Baud Rate (110 through 38400) long BAUD; // derived baud rate from command line long DATABITS; long STOPBITS; long PARITYON; long PARITY; int Data_Bits = 8; // Number of data bits int Stop_Bits = 1; // Number of stop bits int Parity = 0; // Parity as follows:// 00 = NONE, 01 = Odd, 02 = Even, 03 = Mark, 04 = Space int Format = 4; FILE *input; FILE *output; int status; main (int Parm_Count, char *Parms []) { char version [80] = " POSIX compliant Communications test program version 1.00 4-25-1999\r\n"; char version1 [80] = " Copyright(C) Mark Zehner/Peter Baumann 1999\r\n"; char version2 [80] = " This code is based on a DOS based test program by Mark Zehner and a Serial\r\n"; char version3 [80] = " Programming POSIX howto by Peter Baumann, integrated by Mark Zehner\r\n"; char version4 [80] = " This program allows you to send characters out the specified port by typing\r\n"; char version5 [80] = " on the keyboard. Characters typed will be echoed to the console, and \r\n"; char version6 [80] = " characters received will be echoed to the console.\r\n"; char version7 [80] = " The setup parameters for the device name, receive data format, baud rate\r\n"; char version8 [80] = " and other serial port parameters must be entered on the command line \r\n"; char version9 [80] = " To see how to do this, just type the name of this program. \r\n"; char version10 [80] = " This program is free software; you can redistribute it and/or modify it\r\n"; char version11 [80] = " under the terms of the GNU General Public License as published by the \r\n"; char version12 [80] = " Free Software Foundation, version 2.\r\n"; char version13 [80] = " This program comes with ABSOLUTELY NO WARRANTY.\r\n"; char instr [100] ="\r\nOn the command you must include six items in the following order, they are:\r\n"; char instr1 [80] =" 1. The device name Ex: ttyS0 for com1, ttyS1 for com2, etc\r\n"; char instr2 [80] =" 2. Baud Rate Ex: 38400 \r\n"; char instr3 [80] =" 3. Number of Data Bits Ex: 8 \r\n"; char instr4 [80] =" 4. Number of Stop Bits Ex: 0 or 1\r\n"; char instr5 [80] =" 5. Parity Ex: 0=none, 1=odd, 2=even\r\n"; char instr6 [80] =" 6. Format of data received: 1=hex, 2=dec, 3=hex/asc, 4=dec/asc, 5=asc\r\n"; char instr7 [80] =" Example command line: com ttyS0 38400 8 0 0 4 \r\n"; char Param_strings [7][80]; char message [90]; int fd, tty, c, res, i, error; char In1, Key; struct termios oldtio, newtio; //place for old and new port settings for serial port struct termios oldkey, newkey; //place tor old and new port settings for keyboard teletype struct sigaction saio; //definition of signal action char buf [255]; //buffer for where data is put input = fopen ("/dev/tty", "r"); //open the terminal keyboard output = fopen ("/dev/tty", "w"); //open the terminal screen if (!input || !output) { fprintf (stderr, "Unable to open /dev/tty\n"); exit (1); } error=0; fputs (version, output); //display the program introduction fputs (version1, output); fputs (version2, output); fputs (version3, output); fputs (version4, output); fputs (version5, output); fputs (version6, output); fputs (version7, output); fputs (version8, output); fputs (version9, output); fputs (version10, output); fputs (version11, output); fputs (version12, output); fputs (version13, output); //read the parameters from the command line //if there are the right number of parameters on the command lineif (Parm_Count==7) { // for all wild search parametersfor (i=1; i < Parm_Count; i++) { strcpy (Param_strings [i-1], Parms [i]); } i=sscanf (Param_strings [0], "%s", devicename); if (i != 1) error=1; i=sscanf (Param_strings [1], "%li", &Baud_Rate); if (i != 1) error=1; i=sscanf (Param_strings [2], "%i", &Data_Bits); if (i != 1) error=1; i=sscanf (Param_strings [3], "%i", &Stop_Bits); if (i != 1) error=1; i=sscanf (Param_strings [4], "%i", &Parity); if (i != 1) error=1; i=sscanf (Param_strings [5], "%i", &Format); if (i != 1) error=1; sprintf (message, "Device=%s, Baud=%li\r\n", devicename, Baud_Rate); //output the received setup parameters fputs (message, output); sprintf (message, "Data Bits=%i Stop Bits=%i Parity=%i Format=%i\r\n", Data_Bits, Stop_Bits, Parity, Format); fputs (message, output); } //end of if param_count==7 //if the command line entries were correctif ((Parm_Count==7) && (error==0)) { //run the program tty = open ("/dev/tty", O_RDWR | O_NOCTTY | O_NONBLOCK); //set the user console port up tcgetattr (tty, &oldkey); // save current port settings //so commands are interpreted right for this program// set new port settings for non-canonical input processing //must be NOCTTY newkey.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD; newkey.c_iflag = IGNPAR; newkey.c_oflag = 0; newkey.c_lflag = 0; //ICANON; newkey.c_cc [VMIN]=1; newkey.c_cc [VTIME]=0; tcflush (tty, TCIFLUSH); tcsetattr (tty, TCSANOW, &newkey); switch (Baud_Rate) { case 38400: default: BAUD = B38400; break; case 19200: BAUD = B19200; break; case 9600: BAUD = B9600; break; case 4800: BAUD = B4800; break; case 2400: BAUD = B2400; break; case 1800: BAUD = B1800; break; case 1200: BAUD = B1200; break; case 600: BAUD = B600; break; case 300: BAUD = B300; break; case 200: BAUD = B200; break; case 150: BAUD = B150; break; case 134: BAUD = B134; break; case 110: BAUD = B110; break; case 75: BAUD = B75; break; case 50: BAUD = B50; break; } //end of switch baud_rate switch (Data_Bits) { case 8: default: DATABITS = CS8; break; case 7: DATABITS = CS7; break; case 6: DATABITS = CS6; break; case 5: DATABITS = CS5; break; } //end of switch data_bits switch (Stop_Bits) { case 1: default: STOPBITS = 0; break; case 2: STOPBITS = CSTOPB; break; } //end of switch stop bits switch (Parity) { case 0: default: //none PARITYON = 0; PARITY = 0; break; case 1: //odd PARITYON = PARENB; PARITY = PARODD; break; case 2: //even PARITYON = PARENB; PARITY = 0; break; } //end of switch parity//open the device(com port) to be non-blocking (read will return immediately) fd = open (devicename, O_RDWR | O_NOCTTY | O_NONBLOCK); if (fd < 0) { perror (devicename); exit (-1); } //install the serial handler before making the device asynchronous saio.sa_handler = signal_handler_IO; sigemptyset (&saio.sa_mask); //saio.sa_mask = 0; saio.sa_flags = 0; saio.sa_restorer = NULL; sigaction (SIGIO, &saio, NULL); // allow the process to receive SIGIO fcntl (fd, F_SETOWN, getpid ()); // Make the file descriptor asynchronous (the manual page says only// O_APPEND and O_NONBLOCK, will work with F_SETFL...) fcntl (fd, F_SETFL, FASYNC); tcgetattr (fd, &oldtio); // save current port settings// set new port settings for canonical input processing newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD; newtio.c_iflag = IGNPAR; newtio.c_oflag = 0; newtio.c_lflag = 0; //ICANON; newtio.c_cc [VMIN]=1; newtio.c_cc [VTIME]=0; tcflush (fd, TCIFLUSH); tcsetattr (fd, TCSANOW, &newtio); // loop while waiting for input. normally we would do something useful here while (STOP==FALSE) { status = fread (&Key, 1, 1, input); //if a key was hitif (status==1) { switch (Key) { /* branch to appropiate key handler */ case 0x1b: /* Esc */ STOP=TRUE; break; default: fputc ((int) Key, output); // sprintf(message,"%x ",Key); //debug// fputs(message,output); write (fd, &Key, 1); //write 1 byte to the port break; } //end of switch key } //end if a key was hit// after receiving SIGIO, wait_flag = FALSE, input is available and can be read //if input is availableif (wait_flag==FALSE) { res = read (fd, buf, 255); if (res.) { //for all chars in stringfor (i=0; i<res; i++) { In1 = buf [i]; switch (Format) { case 1: //hex sprintf (message, "%x ", In1); fputs (message, output); break; case 2: //decimal sprintf (message, "%d ", In1); fputs (message, output); break; case 3: //hex and asc if ((In1.) || (In1.)) { sprintf (message, "%x", In1); fputs (message, output); } else fputc ((int) In1, output); break; case 4: //decimal and asc default: if ((In1.) || (In1.)) { sprintf (message, "%d", In1); fputs (message, output); } else fputc ((int) In1, output); break; case 5: //asc fputc ((int) In1, output); break; } //end of switch format } //end of for all chars in string } //end if res.// buf[res]=0;// printf(":%s:%d\n", buf, res);// if (res==1) STOP=TRUE; /* stop loop if only a CR was input */ wait_flag = TRUE; /* wait for new input */ } //end if wait flag == FALSE } //while stop==FALSE// restore old port settings tcsetattr (fd, TCSANOW, &oldtio); tcsetattr (tty, TCSANOW, &oldkey); close (tty); close (fd); //close the com port } //end if command line entrys were correct //give instructions on how to use the command lineelse { fputs (instr, output); fputs (instr1, output); fputs (instr2, output); fputs (instr3, output); fputs (instr4, output); fputs (instr5, output); fputs (instr6, output); fputs (instr7, output); } fclose (input); fclose (output); } //end of main/*************************************************************************** * signal handler.sets wait_flag to FALSE, to indicate above loop that * * characters have been received.* ***************************************************************************/ void signal_handler_IO (int status) { // printf("received SIGIO signal.\n"); wait_flag = FALSE; }
2.4375
2
2024-11-18T22:09:32.086075+00:00
2012-12-28T02:50:52
4fcfa4ce87531c545e6b3bdd64da555a78b5c15e
{ "blob_id": "4fcfa4ce87531c545e6b3bdd64da555a78b5c15e", "branch_name": "refs/heads/master", "committer_date": "2012-12-28T02:50:52", "content_id": "6488ceb01614cf272fa30c46707f7e46c4929ffe", "detected_licenses": [ "MIT" ], "directory_id": "2c378ab9a3099d9286df6bbf7abe2ee3aa69ddcb", "extension": "h", "filename": "UIScroll.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 8725602, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2034, "license": "MIT", "license_type": "permissive", "path": "/old_bak/SMYS_CLIENT_IPHONE/SMClasses/UICommon/UIScroll.h", "provenance": "stackv2-0106.json.gz:35735", "repo_name": "kerasking/HHHH", "revision_date": "2012-12-28T02:50:52", "revision_id": "3c53a7e753ccf60c8c95121b3c4871df0aad315b", "snapshot_id": "524bbbaabc26443cda7b29ca19aef7e9c1047a42", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/kerasking/HHHH/3c53a7e753ccf60c8c95121b3c4871df0aad315b/old_bak/SMYS_CLIENT_IPHONE/SMClasses/UICommon/UIScroll.h", "visit_date": "2021-05-26T18:18:43.087367" }
stackv2
/* * UIScroll.h * SMYS * * Created by jhzheng on 12-2-10. * Copyright 2012 __MyCompanyName__. All rights reserved. * */ #ifndef _UI_SCROLL_H_ZJH_ #define _UI_SCROLL_H_ZJH_ #include "UIMovableLayer.h" using namespace NDEngine; typedef enum { UIScrollStyleBegin = 0, UIScrollStyleHorzontal = UIScrollStyleBegin, UIScrollStyleVerical, UIScrollStyleEnd, }UIScrollStyle; typedef struct tagUIMoveInfo { CGPoint pos; double time; tagUIMoveInfo() { pos = CGPointZero; time = 0.0f; } tagUIMoveInfo(CGPoint pos, double time) { this->pos = pos; this->time = time; } }UIMoveInfo; class CUIScroll : public CUIMovableLayer { DECLARE_CLASS(CUIScroll) CUIScroll(); ~CUIScroll(); public: void Initialization(bool bAccerate=false); override void SetScrollStyle(int style); bool IsCanAccerate(); bool IsInAccceratState(); void StopAccerate(); UIScrollStyle GetScrollStyle(); void SetContainer(NDUILayer* layer); protected: void draw(); override bool TouchBegin(NDTouch* touch); override bool TouchEnd(NDTouch* touch); override bool CanHorizontalMove(float& hDistance); override bool CanVerticalMove(float& vDistance); override bool OnLayerMoveOfDistance(NDUILayer* uiLayer, float hDistance, float vDistance); override private: enum { MAX_MOVES = 12, }; enum { STATE_BEGIN = 100, STATE_STOP = STATE_BEGIN, STATE_FIRST, STATE_SECOND, STATE_THREE, STATE_END, }; UIMoveInfo m_moveInfos[MAX_MOVES]; unsigned int m_uiCurMoveIndex; unsigned int m_uiFirstMoveIndex; double m_clockT0; float m_fV0; float m_fOldS; bool m_bMoveInfoEmpty; bool m_bUp; bool m_bAccerate; int m_nState; UIScrollStyle m_style; CAutoLink<NDUILayer> m_linkContainer; private: void ResetMoveData(); void ResetMove(); void SwitchStateTo(int nToState); void PushMove(UIMoveInfo& move); void SetMoveParam(); void SetMoveSpeed(); float GetMoveDistance(); double ClockTimeMinus(double sec, double fir); void OnMove(); }; #endif // _UI_SCROLL_H_ZJH_
2.09375
2
2024-11-18T22:09:32.367424+00:00
2018-12-21T06:35:49
226fa6950b14f116bae7b5613066d74a5010ce4c
{ "blob_id": "226fa6950b14f116bae7b5613066d74a5010ce4c", "branch_name": "refs/heads/master", "committer_date": "2018-12-21T06:35:49", "content_id": "b99c0083a60d85adc6c67c1201f3b0ad3255d2ef", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9f810076a43fb109d2e88414044451e45e8b25c3", "extension": "h", "filename": "rmt_mbuf.h", "fork_events_count": 22, "gha_created_at": "2018-12-12T06:05:08", "gha_event_created_at": "2018-12-12T06:05:09", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 161440558, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2057, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/rmt_mbuf.h", "provenance": "stackv2-0106.json.gz:35994", "repo_name": "tanruixing88/redis-migrate-tool", "revision_date": "2018-12-21T06:35:49", "revision_id": "291aa17eb8c43fb1aec03fd90d145b2b085cf907", "snapshot_id": "f557a16e206336fbb7c3da89cdbb00c228173cc4", "src_encoding": "UTF-8", "star_events_count": 79, "url": "https://raw.githubusercontent.com/tanruixing88/redis-migrate-tool/291aa17eb8c43fb1aec03fd90d145b2b085cf907/src/rmt_mbuf.h", "visit_date": "2020-04-11T02:17:06.312868" }
stackv2
#ifndef _RMT_MBUF_H_ #define _RMT_MBUF_H_ typedef struct mbuf_base{ size_t mbuf_chunk_size; /* mbuf chunk size - header + data (const) */ size_t mbuf_offset; /* mbuf offset in chunk (const) */ uint64_t ntotal_mbuf; /* total mbuf count */ mttlist *free_mbufs; /* free mbuf list */ }mbuf_base; struct mbuf { mbuf_base *mb; uint32_t magic; /* mbuf magic (const) */ uint8_t *pos; /* read marker */ uint8_t *last; /* write marker */ uint8_t *start; /* start of buffer (const) */ uint8_t *end; /* end of buffer (const) */ }; typedef void (*mbuf_copy_t)(struct mbuf *, void *); #define MBUF_MAGIC 0xdeadbeef #define MBUF_HSIZE sizeof(struct mbuf) //48 #define MBUF_MIN_SIZE 128 #define MBUF_MAX_SIZE 16777216 #define MBUF_SIZE 16384 static inline int mbuf_empty(struct mbuf *mbuf) { return mbuf->pos == mbuf->last ? 1 : 0; } static inline int mbuf_full(struct mbuf *mbuf) { return mbuf->last == mbuf->end ? 1 : 0; } mbuf_base *mbuf_base_create(size_t mbuf_chunk_size, mttlist_init fn); void mbuf_base_destroy(mbuf_base *mb); struct mbuf *mbuf_get(mbuf_base *mb); int mbuf_put(struct mbuf *mbuf); void mbuf_rewind(struct mbuf *mbuf); uint32_t mbuf_storage_length(struct mbuf *mbuf); uint32_t mbuf_length(struct mbuf *mbuf); uint32_t mbuf_size(struct mbuf *mbuf); size_t mbuf_data_size(mbuf_base *mb); void mbuf_copy(struct mbuf *mbuf, const uint8_t *pos, size_t n); struct mbuf *mbuf_split(struct mbuf *mbuf, uint8_t *pos); int mbuf_move(struct mbuf *mbuf_f, struct mbuf *mbuf_t, uint32_t n); int mbuf_list_push_head(list *l, struct mbuf *mbuf); int mbuf_list_push(list *l, struct mbuf *mbuf); struct mbuf *mbuf_list_pop(list *l); void mbuf_list_dump_all(list *mbufs, int level); void mbuf_list_dump(list *mbufs, int level); #ifdef RMT_MEMORY_TEST int mbuf_used_init(void); void mbuf_used_deinit(void); long long mbuf_used_count(void); int mbuf_used_up(void); int mbuf_used_down(void); #endif #endif
2.265625
2
2024-11-18T22:09:32.447596+00:00
2019-07-10T00:28:44
21fc3f752f8f7d4ada9357c5f06ccf80917c11db
{ "blob_id": "21fc3f752f8f7d4ada9357c5f06ccf80917c11db", "branch_name": "refs/heads/master", "committer_date": "2019-07-10T00:28:44", "content_id": "643ec7150ae226a6bf5bef4e5343335525d7bbe0", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8947ffbde820db28d57dff143e3105f5a856ab75", "extension": "c", "filename": "Logger.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": 1349, "license": "Apache-2.0", "license_type": "permissive", "path": "/kinesis-video-pic/src/utils/src/Logger.c", "provenance": "stackv2-0106.json.gz:36123", "repo_name": "godsonk/amazon-kinesis-video-streams-producer-sdk-cpp", "revision_date": "2019-07-10T00:28:44", "revision_id": "5eedbb489a3b7a24416162178478092ffbcdfc01", "snapshot_id": "c7dd27fd30807c5abc80c6dcd369749ffcff0986", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/godsonk/amazon-kinesis-video-streams-producer-sdk-cpp/5eedbb489a3b7a24416162178478092ffbcdfc01/kinesis-video-pic/src/utils/src/Logger.c", "visit_date": "2020-06-21T20:37:26.190759" }
stackv2
#include "Include_i.h" UINT32 gLoggerLogLevel = LOG_LEVEL_WARN; // // Default logger function // VOID defaultLogPrint(UINT32 level, PCHAR tag, PCHAR fmt, ...) { /* space for "yyyy-mm-dd HH:MM:SS\0" */ CHAR timeString[MAX_TIMESTAMP_FORMAT_STR_LEN + 1]; CHAR logString[MAX_LOG_LENGTH + 1]; #ifdef ENABLE_LOG_THREAD_ID TID threadId; #endif UINT32 timeStrLen = 0; STATUS retStatus = STATUS_SUCCESS; UNUSED_PARAM(tag); if (level >= gLoggerLogLevel) { /* if something fails in getting time, still print the log, just without timestamp */ retStatus = generateTimestampStr(globalGetTime(), "%F %H:%M:%S", timeString, SIZEOF(timeString), &timeStrLen); if (STATUS_FAILED(retStatus)) { PRINTF("Fail to get time with status code is %08x\n", retStatus); SNPRINTF(logString, SIZEOF(logString), "\n%s", fmt); } else { SNPRINTF(logString, SIZEOF(logString), "\n%s %s", timeString, fmt); } #ifdef ENABLE_LOG_THREAD_ID threadId = globalGetThreadId(); SNPRINTF(logString, SIZEOF(logString), "\n%s (thread-0x%" PRIx64 ") %s", timeString, threadId, fmt); #endif va_list valist; va_start(valist, fmt); vprintf(logString, valist); va_end(valist); } } logPrintFunc globalCustomLogPrintFn = defaultLogPrint;
2.359375
2
2024-11-18T22:09:32.677653+00:00
2016-03-08T04:55:31
a7da5b93d0cdb84783c22d08bda86bb125965bfd
{ "blob_id": "a7da5b93d0cdb84783c22d08bda86bb125965bfd", "branch_name": "refs/heads/master", "committer_date": "2016-03-08T04:55:31", "content_id": "c47a21d6ebc8cc45644a4c4d8afbf7331913dcf2", "detected_licenses": [ "MIT" ], "directory_id": "329e3702790b1ad08a995d293c307dfebf59601e", "extension": "c", "filename": "count_lines.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 53383582, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 397, "license": "MIT", "license_type": "permissive", "path": "/count_lines.c", "provenance": "stackv2-0106.json.gz:36251", "repo_name": "ckm2k1/c_programming_exercises", "revision_date": "2016-03-08T04:55:31", "revision_id": "42b544ce31a17532a21bd1e09da69568c863f768", "snapshot_id": "b33c5a1b24f0a3e8506a43c592cf4a993350bf99", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ckm2k1/c_programming_exercises/42b544ce31a17532a21bd1e09da69568c863f768/count_lines.c", "visit_date": "2021-01-10T13:07:10.414711" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <ctype.h> int main(int argc, char const *argv[]) { FILE *fp; if ((fp = fopen(argv[1], "r")) == NULL) { printf("missing file arg"); exit(EXIT_FAILURE); } long long int count = 1; int ch; while((ch = fgetc(fp)) != EOF) if (ch == '\n') ++count; printf("The file contains %lld lines", count); return 0; }
2.828125
3
2024-11-18T22:09:32.820113+00:00
2021-10-13T21:28:46
4ab562903bdc576e7ba15aaa2b5489d1d6153b12
{ "blob_id": "4ab562903bdc576e7ba15aaa2b5489d1d6153b12", "branch_name": "refs/heads/main", "committer_date": "2021-10-13T21:28:46", "content_id": "91dfcb0508aae9eb464673f13fa0b270c8228e79", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "9a279e120a5717df1cc4bbfc9ea8a56accd2c380", "extension": "c", "filename": "fd.c", "fork_events_count": 0, "gha_created_at": "2021-10-10T01:11:47", "gha_event_created_at": "2021-10-10T01:11:47", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 415456948, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14782, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/backend/failure_detector/fd.c", "provenance": "stackv2-0106.json.gz:36509", "repo_name": "Mvmo/acton", "revision_date": "2021-10-13T21:28:46", "revision_id": "34f274cf8af04e6b1bd6a954207ef6aae0248a7d", "snapshot_id": "9fe0c6c78b15a51511e984050a08f814e6edf496", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Mvmo/acton/34f274cf8af04e6b1bd6a954207ef6aae0248a7d/backend/failure_detector/fd.c", "visit_date": "2023-08-23T09:51:25.808514" }
stackv2
/* * Copyright (C) 2019-2021 Deutsche Telekom AG * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * fd.c * Author: aagapi */ #include "fd.h" #include "db_messages.pb-c.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> /* Node description: */ void init_ns_msg_from_description(NodeStateMessage * ns_msg, node_description * nd) { ns_msg->status = nd->status; ns_msg->node_id = nd->node_id; ns_msg->rack_id = nd->rack_id; ns_msg->dc_id = nd->dc_id; ns_msg->port = nd->portno; assert(nd->hostname != NULL); ns_msg->hostname.len = strnlen(nd->hostname, 256) + 1; ns_msg->hostname.data = malloc(ns_msg->hostname.len); memcpy(ns_msg->hostname.data, nd->hostname, ns_msg->hostname.len); } int copy_node_description(node_description * nd, int status, int node_id, int rack_id, int dc_id, char * hostname, unsigned short portno) { nd->status = status; nd->node_id = node_id; nd->rack_id = rack_id; nd->dc_id = dc_id; nd->portno = portno; bzero((void *) &nd->address, sizeof(struct sockaddr_in)); nd->hostname = NULL; if(hostname != NULL) { struct hostent * host = gethostbyname(hostname); if (host == NULL) { fprintf(stderr, "ERROR, no such host %s\n", hostname); assert(0); return -1; } nd->address.sin_family = AF_INET; bcopy((char *)host->h_addr, (char *)&(nd->address.sin_addr.s_addr), host->h_length); nd->address.sin_port = htons(portno); nd->hostname = strndup(hostname, strnlen(hostname, 256) + 1); } return 0; } node_description * init_node_description(int status, int node_id, int rack_id, int dc_id, char * hostname, unsigned short portno) { node_description * nd = (node_description *) malloc(sizeof(node_description)); copy_node_description(nd, status, node_id, rack_id, dc_id, hostname, portno); return nd; } void free_node_description(node_description * nd) { if(nd->hostname != NULL) free(nd->hostname); free(nd); } int equals_node_description(node_description * nd1, node_description * nd2) { return nd1->node_id == nd2->node_id && nd1->rack_id == nd2->rack_id && nd1->dc_id == nd2->dc_id; } char * to_string_node_description(node_description * nd, char * msg_buff) { sprintf(msg_buff, "Node(status=%d, node_id=%d, rack_id=%d, dc_id=%d, hostname=%s, port=%d)", nd->status, nd->node_id, nd->rack_id, nd->dc_id, (nd->hostname != NULL)?(nd->hostname):"NULL", nd->portno); return msg_buff; } /* Gossip state: */ gossip_state * init_gossip_state(int status, int node_id, int rack_id, int dc_id, char * hostname, unsigned short portno, vector_clock * vc) { gossip_state * gs = (gossip_state *) malloc(sizeof(struct gossip_state)); bzero(gs, sizeof(struct gossip_state)); copy_node_description(&(gs->nd), status, node_id, rack_id, dc_id, hostname, portno); gs->vc = (vc != NULL)?vc:init_vc(0, NULL, NULL, 0); return gs; } void free_gossip_state(gossip_state * gs) { free_vc(gs->vc); free(gs); } void free_gossip_msg(GossipMessage * msg) { free_vc_msg(msg->vc); } void init_ns_msg(NodeStateMessage * ns_msg, gossip_state * gs) { init_ns_msg_from_description(ns_msg, &(gs->nd)); } int serialize_gs(gossip_state * gs, void ** buf, unsigned * len) { GossipMessage msg = GOSSIP_MESSAGE__INIT; VectorClockMessage vc_msg = VECTOR_CLOCK_MESSAGE__INIT; init_vc_msg(&vc_msg, gs->vc); NodeStateMessage ns_msg = NODE_STATE_MESSAGE__INIT; init_ns_msg(&ns_msg, gs); msg.vc = &vc_msg; msg.node_state = &ns_msg; *len = gossip_message__get_packed_size (&msg); *buf = malloc (*len); gossip_message__pack (&msg, *buf); free_gossip_msg(&msg); return 0; } int deserialize_gs(void * buf, unsigned msg_len, gossip_state ** gs) { GossipMessage * msg = gossip_message__unpack(NULL, msg_len, buf); if (msg == NULL) { // Something failed fprintf(stderr, "error unpacking gossip_state message\n"); return 1; } vector_clock * vc = init_vc_from_msg(msg->vc); *gs = init_gossip_state(msg->node_state->status, msg->node_state->node_id, msg->node_state->rack_id, msg->node_state->dc_id, (char *) msg->node_state->hostname.data, msg->node_state->port, vc); return 0; } int equals_gs(gossip_state * gs1, gossip_state * gs2) { return equals_node_description(&(gs1->nd), &(gs2->nd)) && gs1->nd.status == gs2->nd.status && compare_vc(gs1->vc, gs2->vc) == 0; } char * to_string_gs(gossip_state * gs, char * msg_buff) { sprintf(msg_buff, "GS(node_description="); to_string_node_description(&(gs->nd), msg_buff + strlen(msg_buff)); sprintf(msg_buff, ", vc="); to_string_vc(gs->vc, msg_buff + strlen(msg_buff)); sprintf(msg_buff + strlen(msg_buff), ")"); return msg_buff; } /* Membership: */ membership_state * init_membership_state(int no_nodes, node_description * membership, vector_clock * view_id) { membership_state * ms = (membership_state *) malloc(sizeof(membership_state)); ms->no_nodes = no_nodes; ms->membership = membership; ms->view_id = view_id; return ms; } membership_state * clone_membership(membership_state * m) { membership_state * ms = (membership_state *) malloc(sizeof(membership_state)); ms->no_nodes = m->no_nodes; ms->membership = (node_description *) malloc(m->no_nodes * sizeof(node_description)); for(int i=0;i<m->no_nodes;i++) copy_node_description(ms->membership + i, m->membership[i].status, m->membership[i].node_id, m->membership[i].rack_id, m->membership[i].dc_id, m->membership[i].hostname, m->membership[i].portno); ms->view_id = (m->view_id != NULL)?(copy_vc(m->view_id)):(NULL); return ms; } void free_membership_state(membership_state * ms) { free(ms->membership); free_vc(ms->view_id); free(ms); } void free_membership_msg(MembershipViewMessage * msg) { free_vc_msg(msg->view_id); for(int i=0;i<msg->n_membership;i++) free(msg->membership[i]); free(msg->membership); } void init_membership_msg(MembershipViewMessage * msg, membership_state * m, VectorClockMessage * view_id_msg) { NodeStateMessage **membership_v = (NodeStateMessage **) malloc (m->no_nodes * sizeof (NodeStateMessage*)); msg->view_id = view_id_msg; for(int i = 0; i < m->no_nodes; i++) { membership_v[i] = malloc (sizeof (NodeStateMessage)); node_state_message__init(membership_v[i]); init_ns_msg_from_description(membership_v[i], m->membership+i); } msg->n_membership = m->no_nodes; msg->membership = membership_v; } int serialize_membership_state(membership_state * m, void ** buf, unsigned * len) { MembershipViewMessage msg = MEMBERSHIP_VIEW_MESSAGE__INIT; VectorClockMessage view_id_msg = VECTOR_CLOCK_MESSAGE__INIT; init_vc_msg(&view_id_msg, m->view_id); init_membership_msg(&msg, m, &view_id_msg); *len = membership_view_message__get_packed_size (&msg); *buf = malloc (*len); membership_view_message__pack (&msg, *buf); free_membership_msg(&msg); return 0; } membership_state * init_membership_from_msg(MembershipViewMessage * msg) { vector_clock * view_id = init_vc_from_msg(msg->view_id); node_description * membership = (node_description *) malloc(msg->n_membership * sizeof(node_description)); for(int i=0;i<msg->n_membership;i++) copy_node_description(membership+i, msg->membership[i]->status, msg->membership[i]->node_id, msg->membership[i]->rack_id, msg->membership[i]->dc_id, (char *) msg->membership[i]->hostname.data, (unsigned short) msg->membership[i]->port); return init_membership_state(msg->n_membership, membership, view_id); } int deserialize_membership_state(void * buf, unsigned msg_len, membership_state ** ms) { MembershipViewMessage * msg = membership_view_message__unpack(NULL, msg_len, buf); if (msg == NULL) { fprintf(stderr, "error unpacking membership view message\n"); return 1; } *ms = init_membership_from_msg(msg); return 0; } int equals_membership_state(membership_state * gs1, membership_state * gs2) { if(gs1->no_nodes != gs2->no_nodes) return 0; for(int i=0;i<gs1->no_nodes;i++) if(!equals_node_description(gs1->membership + i, gs2->membership + i)) return 0; return 1; } char * to_string_membership_state(membership_state * gs, char * msg_buff) { char * crt_ptr = msg_buff; sprintf(crt_ptr, "Membership("); crt_ptr += strlen(crt_ptr); for(int i=0;i<gs->no_nodes;i++) { to_string_node_description(gs->membership+i, crt_ptr); crt_ptr += strlen(crt_ptr); sprintf(crt_ptr, ", "); crt_ptr += 2; } return msg_buff; } /* Membership agreement messages: */ membership_agreement_msg * init_membership_agreement_msg(int msg_type, int ack_status, membership_state * membership, int64_t nonce, vector_clock * vc) { membership_agreement_msg * ma = (membership_agreement_msg *) malloc(sizeof(membership_agreement_msg)); ma->msg_type = msg_type; ma->ack_status = ack_status; ma->membership = membership; ma->nonce = nonce; ma->vc = vc; return ma; } membership_agreement_msg * get_membership_propose_msg(int ack_status, membership_state * membership, int64_t nonce, vector_clock * vc) { return init_membership_agreement_msg(MEMBERSHIP_AGREEMENT_PROPOSE, ack_status, membership, nonce, vc); } membership_agreement_msg * get_membership_response_msg(int ack_status, membership_state * membership, int64_t nonce, vector_clock * vc) { return init_membership_agreement_msg(MEMBERSHIP_AGREEMENT_RESPONSE, ack_status, membership, nonce, vc); } membership_agreement_msg * get_membership_notify_msg(int ack_status, membership_state * membership, int64_t nonce, vector_clock * vc) { return init_membership_agreement_msg(MEMBERSHIP_AGREEMENT_NOTIFY, ack_status, membership, nonce, vc); } membership_agreement_msg * get_membership_notify_ack_msg(int ack_status, int64_t nonce, vector_clock * vc) { return init_membership_agreement_msg(MEMBERSHIP_AGREEMENT_NOTIFY_ACK, ack_status, NULL, nonce, vc); } membership_agreement_msg * get_membership_join_msg(int status, int rack_id, int dc_id, char * hostname, unsigned short portno, int64_t nonce, vector_clock * vc) { node_description * nd = init_node_description(status, -1, rack_id, dc_id, hostname, portno); nd->node_id = get_node_id((struct sockaddr *) &(nd->address)); membership_state * membership = init_membership_state(1, nd, copy_vc(vc)); return init_membership_agreement_msg(MEMBERSHIP_AGREEMENT_JOIN, status, membership, nonce, vc); } void free_membership_agreement(membership_agreement_msg * ma) { if(ma->membership != NULL) free_membership_state(ma->membership); if(ma->vc != NULL) free_vc(ma->vc); free(ma); } void free_membership_agreement_msg(MembershipAgreementMessage * msg) { if(msg->vc != NULL) free_vc_msg(msg->vc); if(msg->view != NULL) free_membership_msg(msg->view); } int serialize_membership_agreement_msg(membership_agreement_msg * ma, void ** buf, unsigned * len) { MembershipAgreementMessage msg = MEMBERSHIP_AGREEMENT_MESSAGE__INIT; VectorClockMessage vc_msg = VECTOR_CLOCK_MESSAGE__INIT; init_vc_msg(&vc_msg, ma->vc); msg.vc = &vc_msg; if(ma->membership != NULL) { MembershipViewMessage mview_msg = MEMBERSHIP_VIEW_MESSAGE__INIT; VectorClockMessage view_id_msg = VECTOR_CLOCK_MESSAGE__INIT; init_vc_msg(&view_id_msg, ma->membership->view_id); init_membership_msg(&mview_msg, ma->membership, &view_id_msg); msg.view = &mview_msg; } else { msg.view = NULL; } msg.msg_type = ma->msg_type; msg.ack_status = ma->ack_status; msg.nonce = ma->nonce; *len = membership_agreement_message__get_packed_size (&msg); *len = (*len) + sizeof(int); *buf = malloc (*len); memset(*buf, 0 , *len); *((int *)(*buf)) = (*len) - sizeof(int); membership_agreement_message__pack (&msg, (void *) ((int *)(*buf) + 1)); free_membership_agreement_msg(&msg); return 0; } int deserialize_membership_agreement_msg(void * buf, unsigned msg_len, membership_agreement_msg ** ma) { MembershipAgreementMessage * msg = membership_agreement_message__unpack(NULL, msg_len, buf); if (msg == NULL) { fprintf(stderr, "error unpacking membership agreement message\n"); return 1; } vector_clock * vc = init_vc_from_msg(msg->vc); membership_state * membership = (msg->view != NULL)?(init_membership_from_msg(msg->view)):(NULL); *ma = init_membership_agreement_msg(msg->msg_type, msg->ack_status, membership, msg->nonce, vc); return 0; } int equals_membership_agreement_msg(membership_agreement_msg * ma1, membership_agreement_msg * ma2) { if(ma1->nonce != ma2->nonce || ma1->msg_type != ma2->msg_type || ma1->ack_status != ma2->ack_status) return 0; if((ma1->membership != NULL && ma2->membership == NULL) || (ma1->membership == NULL && ma2->membership != NULL) || !equals_membership_state(ma1->membership, ma2->membership)) return 0; if(compare_vc(ma1->vc, ma2->vc) != 0) return 0; return 1; } char * to_string_membership_agreement_msg(membership_agreement_msg * ma, char * msg_buff) { char * crt_ptr = msg_buff; sprintf(crt_ptr, "Membership_agreement_msg(type=%d, ack_status=%d, nonce=%" PRId64 ", ", ma->msg_type, ma->ack_status, ma->nonce); crt_ptr += strlen(crt_ptr); if(ma->membership != NULL) { to_string_membership_state(ma->membership, crt_ptr); crt_ptr += strlen(crt_ptr); sprintf(crt_ptr, ", "); crt_ptr += 2; } if(ma->vc != NULL) { to_string_vc(ma->vc, crt_ptr); crt_ptr += strlen(crt_ptr); } sprintf(crt_ptr, ")"); return msg_buff; }
2.171875
2
2024-11-18T22:09:32.989113+00:00
2022-12-01T08:19:12
37eba0f1f0805dfd862699cd514cf884ae9e1745
{ "blob_id": "37eba0f1f0805dfd862699cd514cf884ae9e1745", "branch_name": "refs/heads/master", "committer_date": "2022-12-01T08:19:12", "content_id": "c7add9960b23bd6ca21df81d40b8a727228ad3fb", "detected_licenses": [ "MIT" ], "directory_id": "ba4959e109ff0257444c036802f1ac1c360f7d95", "extension": "c", "filename": "Literal.c", "fork_events_count": 13, "gha_created_at": "2017-03-30T17:34:11", "gha_event_created_at": "2020-11-20T11:49:20", "gha_language": "C", "gha_license_id": "MIT", "github_id": 86730515, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2483, "license": "MIT", "license_type": "permissive", "path": "/src/Literal.c", "provenance": "stackv2-0106.json.gz:36638", "repo_name": "hillerlab/CESAR2.0", "revision_date": "2022-12-01T08:19:12", "revision_id": "84b5fc739523c5407bb23e4ead1c5af778fec587", "snapshot_id": "7d98c705259ee3e1e6bb3dc58fb3571435816cdf", "src_encoding": "UTF-8", "star_events_count": 29, "url": "https://raw.githubusercontent.com/hillerlab/CESAR2.0/84b5fc739523c5407bb23e4ead1c5af778fec587/src/Literal.c", "visit_date": "2022-12-12T12:10:49.874628" }
stackv2
/** * Literal definition. * Copyright 2017 MPI-CBG/MPI-PKS Peter Schwede */ #include "Logging.h" #include "Literal.h" /** * Given a character, return its Literal representation. * An invalid character causes this function to kill the process (die). * @param c a character. * @return the according Literal. */ Literal Literal__from_char(char c) { switch (c) { case 'a': case 'A': return LITERAL_A; case 'c': case 'C': return LITERAL_C; case 'g': case 'G': return LITERAL_G; case 't': case 'T': return LITERAL_T; case 'n': case 'N': return LITERAL_N; default: die("Unkown literal 0x%x=%c", c, c); } return LITERAL_N; } /** * Given a Literal, return its character representation. * This function kills the process if the literal is unknown (die). * @param literal a Literal. * @return character representation. */ char Literal__char(Literal literal) { switch (literal) { case LITERAL_A: return 'A'; case LITERAL_C: return 'C'; case LITERAL_G: return 'G'; case LITERAL_T: return 'T'; case LITERAL_N: return 'N'; default: die("Unknown literal 0x%x", literal); } return 'N'; } /** * Given an array of literals, fill a string with character representations. * @param length the number of Literals. * @param literals the array of Literals. * @param result the string buffer that will contain the string representation. */ void Literal__str(size_t length, Literal literals[length], char result[length+1]) { for (size_t i=0; i < length; i++) { result[i] = Literal__char(literals[i]); } result[length] = '\0'; } /** * Convert an array of literals to an unsigned int. * @param length size of the array. * @param array the array of literals. * @return an uint8_fastest. */ EMISSION_ID_T Literal__uint(uint16_t length, Literal array[length]) { EMISSION_ID_T byte = 0; for (uint16_t i=0; i < length; i++) { if (array[i] == LITERAL_N) { warn("N literal found."); } byte <<= 2; byte += array[i]; } return byte; } /** * Count the number of N-Literals in a given array. * @param length length of the given array. * @param array an array of Literals. * @return the number of N-Literals. */ uint16_t Literal__Ns(uint16_t length, Literal array[length]) { uint16_t count = 0; for (uint16_t i=0; i < length; i++) { count += array[i] == LITERAL_N; } return count; }
3.015625
3
2024-11-18T22:09:33.167863+00:00
2020-11-25T23:00:06
71734538e09672eaa452895bd5d50d4a9f4c55f9
{ "blob_id": "71734538e09672eaa452895bd5d50d4a9f4c55f9", "branch_name": "refs/heads/main", "committer_date": "2020-11-25T23:00:06", "content_id": "0fa67ab30b293b847fba2b288f408095bc980dab", "detected_licenses": [ "MIT" ], "directory_id": "fa77e147314cd93f7a8dd868a2b13f140ced7206", "extension": "c", "filename": "Test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 316071602, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 838, "license": "MIT", "license_type": "permissive", "path": "/Test.c", "provenance": "stackv2-0106.json.gz:36768", "repo_name": "rodrigozero0/projeto.", "revision_date": "2020-11-25T23:00:06", "revision_id": "42cee8ee1656c3b08a8484a2aa67a16614698f0f", "snapshot_id": "1c3a5ef1ba647f6953f41d3d5035be43e91619a0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rodrigozero0/projeto./42cee8ee1656c3b08a8484a2aa67a16614698f0f/Test.c", "visit_date": "2023-01-19T05:26:04.143806" }
stackv2
#include <stdio.h> #include <stdlib.h> int main() { int valor; int valor2; printf("(1)GESTOR. \n(2)ENGENHEIRO. \n(3)MESTRE DE OBRA. \n(4)FORNECEDOR."); printf ("\nQuem é você nesse bloco: "); scanf("%d", &valor); switch ( valor ) { case 1 : printf("Bem vindo, agora escolha: \n(1)Solicitar nova Obra. \n(2)Verificar custo da obra. \n(3)Verificar histórico da obra"); switch (valor2){ case 1 : printf("Já estamos iniciando ua nova obra"); break; case 2 : printf("Iniciando verificação"); break; case 3 : printf("Obra está andando com calma e eficiencia"); break; default : printf ("\nValor invalido!"); } break; default : printf ("Valor invalido!"); } return 0; }
3.328125
3
2024-11-18T22:09:33.895194+00:00
2018-07-18T06:28:39
5f4864b7ce5423c37243e42844c25bd529791bbf
{ "blob_id": "5f4864b7ce5423c37243e42844c25bd529791bbf", "branch_name": "refs/heads/master", "committer_date": "2018-07-18T06:28:39", "content_id": "6013c12f868eb7f30aa1c53e5cb0d14b1b501153", "detected_licenses": [ "MIT" ], "directory_id": "5833e84a928aaa30999eec0e1ffe8f7eaace0b0a", "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": 777, "license": "MIT", "license_type": "permissive", "path": "/as3/main.c", "provenance": "stackv2-0106.json.gz:37155", "repo_name": "minhoe1017/cmpt433-1", "revision_date": "2018-07-18T06:28:39", "revision_id": "0c358f02c4cbfc8620b8fc35093b225afd9a533a", "snapshot_id": "dd6ee09ec785ea0009479015153c2546b6ed94d9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/minhoe1017/cmpt433-1/0c358f02c4cbfc8620b8fc35093b225afd9a533a/as3/main.c", "visit_date": "2020-03-23T09:29:27.117458" }
stackv2
#include "RusHourBeats.h" #include "joystick.h" #include "server.h" int main() { AudioMixer_init(); pthread_t playbackId; pthread_t serverID; pthread_t joystickID; pthread_t beatID; pthread_attr_t attributes; pthread_attr_init(&attributes); printf("Initialize attributes\n"); pthread_create(&beatID, NULL, beatThread, NULL); pthread_create(&playbackId, NULL, playbackThread, NULL); pthread_create(&serverID, &attributes, listen_for_command, NULL); pthread_create(&joystickID, &attributes, startJoystickThread, NULL); printf("Create threads\n"); pthread_join(beatID, NULL); pthread_join(playbackId, NULL); pthread_join(serverID, NULL); pthread_join(joystickID, NULL); printf("Join threads\n"); AudioMixer_cleanup(); printf("Clean up\n"); return 0; }
2.296875
2
2024-11-18T22:09:34.102814+00:00
2022-12-10T05:31:04
94efddf3c43d7b14dd0109c3fa2c2f006b590bf4
{ "blob_id": "94efddf3c43d7b14dd0109c3fa2c2f006b590bf4", "branch_name": "refs/heads/master", "committer_date": "2022-12-10T05:31:04", "content_id": "689f158b00b1e83fd4cb985dcb3f1f6e41acb711", "detected_licenses": [ "MIT" ], "directory_id": "d782f4de145f17f27147332b7dc7a84bf091dc0e", "extension": "c", "filename": "blk.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 179116612, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 930, "license": "MIT", "license_type": "permissive", "path": "/core/blk/blk.c", "provenance": "stackv2-0106.json.gz:37414", "repo_name": "libunicycle/unicycle", "revision_date": "2022-12-10T05:31:04", "revision_id": "928c49cea8f15bf5be4ad7f3058c5d5a41479eaa", "snapshot_id": "6d6082439b50f74d5986fb63e7f687676d138ef0", "src_encoding": "UTF-8", "star_events_count": 16, "url": "https://raw.githubusercontent.com/libunicycle/unicycle/928c49cea8f15bf5be4ad7f3058c5d5a41479eaa/core/blk/blk.c", "visit_date": "2022-12-21T02:22:16.365811" }
stackv2
// SPDX-License-Identifier: MIT #include "blk.h" #include "queue.h" #include "stdio.h" SLIST_HEAD(, blk_device) devices = SLIST_HEAD_INITIALIZER(&devices); void blk_dev_register(struct blk_device *dev) { SLIST_INSERT_HEAD(&devices, dev, next); } struct blk_device *blk_dev_get(size_t idx) { size_t i = 0; struct blk_device *dev; // find idx element in the list SLIST_FOREACH(dev, &devices, next) { if (i == idx) { return dev; } i++; } return NULL; } void blk_read(struct blk_device *blk, void *data, size_t size, size_t start_sector, blk_op_callback on_complete, void *context) { blk->send(blk, data, size, start_sector, false, on_complete, context); } void blk_write(struct blk_device *blk, void *data, size_t size, size_t start_sector, blk_op_callback on_complete, void *context) { blk->send(blk, data, size, start_sector, true, on_complete, context); }
2.59375
3
2024-11-18T22:09:35.455789+00:00
2023-07-20T10:07:52
e3367610e2005ba465d226833b73cb409f90b035
{ "blob_id": "e3367610e2005ba465d226833b73cb409f90b035", "branch_name": "refs/heads/master", "committer_date": "2023-07-20T10:07:52", "content_id": "2d678232acf85d4870020132a865fe80d8ee58a4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "73e6cfe18dd52725f3f3859e81755dfd32a61844", "extension": "c", "filename": "test_string.c", "fork_events_count": 6, "gha_created_at": "2016-10-03T17:17:24", "gha_event_created_at": "2023-05-01T20:15:00", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 69892828, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 884, "license": "Apache-2.0", "license_type": "permissive", "path": "/test/test_string.c", "provenance": "stackv2-0106.json.gz:37671", "repo_name": "IITDBGroup/gprom", "revision_date": "2023-07-20T10:07:52", "revision_id": "0d964a8b3ca6d4a5d344bb856626d47c95bac890", "snapshot_id": "a0c41dda321681e7976299549e039fb845588d73", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/IITDBGroup/gprom/0d964a8b3ca6d4a5d344bb856626d47c95bac890/test/test_string.c", "visit_date": "2023-08-31T17:31:52.085716" }
stackv2
/*----------------------------------------------------------------------------- * * test_string.c * * * AUTHOR: lord_pretzel * * * *----------------------------------------------------------------------------- */ #include "test_main.h" #include "model/node/nodetype.h" static rc testStringConstruction(void); rc testString(void) { RUN_TEST(testStringConstruction(), "Test extensible string (StringInfo)"); return PASS; } static rc testStringConstruction (void) { char *concat; char *a = "a"; char *b = "b"; char *c = "c"; StringInfo str; str = makeStringInfo(); appendStringInfoStrings(str,a,b,c,NULL); ASSERT_EQUALS_STRING(str->data,"abc", "string concatenation result is abc"); concat = CONCAT_STRINGS(a,b,c); ASSERT_EQUALS_STRING(concat,"abc", "string concatenation result is abc"); return PASS; }
2.140625
2