added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T22:09:35.536518+00:00
| 2021-07-19T18:31:20 |
00b021fc70c334d2fdbb0c7006787d3b24401012
|
{
"blob_id": "00b021fc70c334d2fdbb0c7006787d3b24401012",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-19T18:31:20",
"content_id": "18856dd4798be4d760b417cf911638c9aa8c34d4",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ac18bb4fb245bf1fe0e8804d7e26fde5d8445b52",
"extension": "c",
"filename": "sha1_alt.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 387553038,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2632,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/net/mbedtls-2.2.0/library/sha1_alt.c",
"provenance": "stackv2-0106.json.gz:37799",
"repo_name": "tony-fav/FavTuyaXR3",
"revision_date": "2021-07-19T18:31:20",
"revision_id": "7d5e75986175b8cf1c8276adeca42c8c3e3a3f8d",
"snapshot_id": "4970a2c0bd9868f46b0b07ae212df9940fcde245",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/tony-fav/FavTuyaXR3/7d5e75986175b8cf1c8276adeca42c8c3e3a3f8d/src/net/mbedtls-2.2.0/library/sha1_alt.c",
"visit_date": "2023-06-23T01:37:32.761007"
}
|
stackv2
|
/*
* FIPS-180-1 compliant SHA-1 implementation
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* The SHA-1 standard was published by NIST in 1993.
*
* http://www.itl.nist.gov/fipspubs/fip180-1.htm
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_SHA1_C)
#include "mbedtls/sha1.h"
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#if defined(MBEDTLS_SHA1_ALT)
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = v; while( n-- ) *p++ = 0;
}
void mbedtls_sha1_init( mbedtls_sha1_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_sha1_context ) );
}
void mbedtls_sha1_free( mbedtls_sha1_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_zeroize( ctx, sizeof( mbedtls_sha1_context ) );
}
void mbedtls_sha1_clone( mbedtls_sha1_context *dst,
const mbedtls_sha1_context *src )
{
*dst = *src;
}
/*
* SHA-1 context setup
*/
void mbedtls_sha1_starts( mbedtls_sha1_context *ctx )
{
HAL_SHA1_Init(&ctx->sha1, CE_CTL_IVMODE_SHA_MD5_FIPS180, NULL);
}
#if !defined(MBEDTLS_SHA1_PROCESS_ALT)
void mbedtls_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[64] )
{
}
#endif /* !MBEDTLS_SHA1_PROCESS_ALT */
/*
* SHA-1 process buffer
*/
void mbedtls_sha1_update( mbedtls_sha1_context *ctx, const unsigned char *input, size_t ilen )
{
HAL_SHA1_Append(&ctx->sha1, (uint8_t*)input, ilen);
}
/*
* SHA-1 final digest
*/
void mbedtls_sha1_finish( mbedtls_sha1_context *ctx, unsigned char output[20] )
{
HAL_SHA1_Finish(&ctx->sha1, (uint32_t*)output);
}
#endif /* !MBEDTLS_SHA1_ALT */
#endif /* MBEDTLS_SHA1_C */
| 2.140625 | 2 |
2024-11-18T22:09:35.735044+00:00
| 2019-11-18T12:20:36 |
1171353c78094b37c66f49f2c837016a8d0cdaec
|
{
"blob_id": "1171353c78094b37c66f49f2c837016a8d0cdaec",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-18T12:20:36",
"content_id": "d4116dc9f15974e41e4f33d6e144b4f76f16db64",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cd5d345ff6f5a82ccf68910a2fd268344d0d5e94",
"extension": "c",
"filename": "gameLogic.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 181756559,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 29592,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Arkanoid/Server/gameLogic.c",
"provenance": "stackv2-0106.json.gz:38055",
"repo_name": "rmcsilva/ArkanoidSO2",
"revision_date": "2019-11-18T12:20:36",
"revision_id": "e296cb4297922278a87c5421fa9b0f7c1b340683",
"snapshot_id": "e74bf718616575207eba9724a6e453b18d0dda29",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/rmcsilva/ArkanoidSO2/e296cb4297922278a87c5421fa9b0f7c1b340683/Arkanoid/Server/gameLogic.c",
"visit_date": "2020-05-14T10:08:42.540338"
}
|
stackv2
|
#define _CRT_RAND_S
#define _10MILLISECONDS -100000LL
#define _100MILLISECONDS -100000LL
#define _1SECOND -10000000LL
#include "stdafx.h"
#include "gameLogic.h"
#include "gameStructs.h"
#include "messages.h"
#include <stdlib.h>
#include "setup.h"
TCHAR debugText[MAX];
unsigned int random;
HANDLE hBallControlMutex;
HANDLE hBonusMutex;
HANDLE hBrickMovementMutex;
HANDLE hBonusEvent;
HANDLE hBonusTimeoutEvent[MAX_BONUS];
int bonusCounter = 0;
DWORD WINAPI GameLogic(LPVOID lpParam)
{
GameVariables* pGameVariables = (GameVariables*)lpParam;
GameData* pGameData = pGameVariables->pGameData;
HANDLE hGameWait;
LARGE_INTEGER timeToWait;
HANDLE hBonusThread;
DWORD dwBonusThreadID;
timeToWait.QuadPart = _10MILLISECONDS;
// Create an unnamed waitable timer.
hGameWait = CreateWaitableTimer(NULL, TRUE, NULL);
if (hGameWait == NULL)
{
_tprintf(TEXT("CreateWaitableTimer failed (%d)\n"), GetLastError());
return -1;
}
//Initialize Game Variables
initializeGame(pGameVariables);
//Thread to handle the bonus logic
hBonusThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
BonusLogic, // thread function name
(LPVOID)pGameVariables, // argument to thread function
0, // use default creation flags
&dwBonusThreadID); // returns the thread identifier
if (hBonusThread == NULL)
{
_tprintf(TEXT("\nError creating bonus thread!\n\n"));
ExitProcess(3);
}
while (pGameData->gameStatus != GAME_OVER)
{
// Set a timer to wait.
if (!SetWaitableTimer(hGameWait, &timeToWait, 0, NULL, NULL, 0))
{
_tprintf(TEXT("SetWaitableTimer failed (%d)\n"), GetLastError());
return -1;
}
if (getInGamePlayers(pGameData) == 0)
{
_tprintf(TEXT("\n\nGame Over!! No players in the game!\n\n"));
break;
}
if (pGameData->lives == 0)
{
_tprintf(TEXT("\n\nGame Over!! Out of lives! Bad luck, try again!\n\n"));
break;
}
else if (pGameVariables->gameConfigs.levels < pGameData->level)
{
_tprintf(TEXT("\n\nGame Over!! All levels cleared! Niceee\n\n"));
break;
}
if (pGameData->numBricks == 0)
{
advanceLevel(pGameVariables);
continue;
}
ballMovement(pGameVariables);
sendGameUpdate(*pGameVariables);
if (WaitForSingleObject(hGameWait, INFINITE) != WAIT_OBJECT_0) {
_tprintf(TEXT("WaitForSingleObject failed (%d)\n"), GetLastError());
return -1;
}
}
//Game is over
gameOver(pGameData);
saveGameScoresAndOrderTop10(pGameVariables);
pGameData->gameStatus = GAME_OVER;
sendGameUpdate(*pGameVariables);
if (pGameData->numBonus == 0)
{
SetEvent(hBonusEvent);
}
WaitForSingleObject(hBonusThread, INFINITE);
CloseHandle(hGameWait);
return 1;
}
DWORD WINAPI BonusLogic(LPVOID lpParam)
{
GameVariables* pGameVariables = (GameVariables*)lpParam;
GameData* pGameData = pGameVariables->pGameData;
HANDLE hBonusWait;
LARGE_INTEGER timeToWait;
HANDLE hBonusDurationThread;
DWORD hBonusDurationThreadID;
HANDLE hBrickMovementThread;
DWORD hBrickMovementThreadID;
timeToWait.QuadPart = _100MILLISECONDS;
// Create an unnamed waitable timer for the bonus movement.
hBonusWait = CreateWaitableTimer(NULL, TRUE, NULL);
if (hBonusWait == NULL)
{
_tprintf(TEXT("CreateWaitableTimer failed (%d)\n"), GetLastError());
return -1;
}
//Thread to handle the bonus logic
hBonusDurationThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
BonusDuration, // thread function name
(LPVOID)pGameVariables, // argument to thread function
0, // use default creation flags
&hBonusDurationThreadID); // returns the thread identifier
if (hBonusDurationThread == NULL)
{
_tprintf(TEXT("\nError creating bonus duration thread!\n\n"));
ExitProcess(3);
}
//Thread to handle the bricks movement logic
hBrickMovementThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
BricksMovementLogic, // thread function name
(LPVOID)pGameVariables, // argument to thread function
0, // use default creation flags
&hBrickMovementThreadID); // returns the thread identifier
if (hBrickMovementThread == NULL)
{
_tprintf(TEXT("\nError creating brick movement thread!\n\n"));
ExitProcess(3);
}
while (pGameData->gameStatus != GAME_OVER)
{
if (pGameData->numBonus == 0)
{
WaitForSingleObject(hBonusEvent, INFINITE);
}
if (!SetWaitableTimer(hBonusWait, &timeToWait, 0, NULL, NULL, 0))
{
_tprintf(TEXT("SetWaitableTimer failed (%d)\n"), GetLastError());
return -1;
}
for (int i = 0; i < pGameVariables->gameConfigs.maxBonus; i++)
{
if (pGameData->bonus[i].status == BONUS_IN_PLAY)
{
pGameData->bonus[i].position.y += pGameVariables->gameConfigs.movementSpeed;
int yStart = pGameData->bonus[i].position.y;
int yEnd = pGameData->bonus[i].position.y + GAME_BONUS_HEIGHT;
int status;
//Check if bonus is in the player barrier area
if ((yEnd >= GAME_BARRIER_Y && yEnd <= DIM_Y_FRAME) || (yStart >= GAME_BARRIER_Y && yStart <= DIM_Y_FRAME))
{
int x = pGameData->bonus[i].position.x + GAME_BONUS_WIDTH / 2;
//Check if bonus got caught
for (int j = 0; j < pGameData->numPlayers; j++)
{
//Checks if bonus hit a barrier
int barrierDimension = pGameData->barrierDimensions * pGameData->barrier[j].sizeRatio;
if (x >= pGameData->barrier[j].position.x && x <= pGameData->barrier[j].position.x + barrierDimension)
{
switch (pGameData->bonus[i].type)
{
case BONUS_SPEED_UP:
if (ballBonusIncrease(pGameData) == TRUE)
{
status = BONUS_CAUGHT;
SetEvent(hBonusTimeoutEvent[i]);
} else
{
status = BONUS_INACTIVE;
pGameData->numBonus--;
}
break;
case BONUS_SLOW_DOWN:
if (ballBonusDecrease(pGameData) == TRUE)
{
status = BONUS_CAUGHT;
SetEvent(hBonusTimeoutEvent[i]);
} else
{
status = BONUS_INACTIVE;
pGameData->numBonus--;
}
break;
case BONUS_EXTRA_LIFE:
status = BONUS_INACTIVE;
pGameData->numBonus--;
if(pGameData->lives < pGameVariables->gameConfigs.initialLives)
{
pGameData->lives++;
}
break;
case BONUS_TRIPLE_BALL:
tripleBallBonus(pGameData);
status = BONUS_INACTIVE;
pGameData->numBonus--;
break;
}
//Change bonus status
WaitForSingleObject(hBonusMutex, INFINITE);
pGameData->bonus[i].status = status;
ReleaseMutex(hBonusMutex);
OutputDebugString(TEXT("\nPlayer catched a bonus!!\n"));
break;
}
}
}
else if (yStart >= DIM_Y_FRAME)
{
WaitForSingleObject(hBonusMutex, INFINITE);
//Bonus is out of the screen
pGameData->bonus[i].status = BONUS_INACTIVE;
pGameData->numBonus--;
ReleaseMutex(hBonusMutex);
}
}
}
if (WaitForSingleObject(hBonusWait, INFINITE) != WAIT_OBJECT_0) {
_tprintf(TEXT("WaitForSingleObject failed (%d)\n"), GetLastError());
return -1;
}
}
SetEvent(hBonusTimeoutEvent[0]);
WaitForSingleObject(hBonusDurationThread, INFINITE);
WaitForSingleObject(hBrickMovementThread, INFINITE);
CloseHandle(hBonusWait);
return 1;
}
DWORD WINAPI BonusDuration(LPVOID lpParam)
{
GameVariables* pGameVariables = (GameVariables*)lpParam;
GameData* pGameData = pGameVariables->pGameData;
BonusTimerVariables bonusTimerVariables[MAX_BONUS];
HANDLE hBonusEffectTimer[MAX_BONUS];
LARGE_INTEGER bonusEffectTime;
int maxBonus = pGameVariables->gameConfigs.maxBonus;
bonusEffectTime.QuadPart = _1SECOND * pGameVariables->gameConfigs.bonusDuration;
for (int i = 0; i < maxBonus; i++)
{
// Create unnamed auto-reset waitable timer to control the bonus duration;
hBonusEffectTimer[i] = CreateWaitableTimer(NULL, FALSE, NULL);
//Create event
hBonusTimeoutEvent[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
}
DWORD dwWait, i;
while (pGameData->gameStatus != GAME_OVER)
{
dwWait = WaitForMultipleObjectsEx(maxBonus, hBonusTimeoutEvent, FALSE, INFINITE, TRUE);
//The wait was ended by one or more user-mode asynchronous procedure calls (APC) queued to the thread
if (dwWait == WAIT_IO_COMPLETION)
{
continue;
}
// determines which timer is to be set
i = dwWait - WAIT_OBJECT_0;
if (i < 0 || i > (maxBonus - 1))
{
continue;
}
bonusTimerVariables[i].pGameVariables = pGameVariables;
bonusTimerVariables[i].bonusIndex = i;
SetWaitableTimer(
hBonusEffectTimer[i], // Handle to the timer object
&bonusEffectTime, // When timer will become signaled
0, // Non-Periodic timer
BonusEffectAPCProc, // Completion routine
&bonusTimerVariables[i], // Argument to the completion routine
FALSE); // Do not restore a suspended system
}
for (int i = 0; i < maxBonus; i++)
{
CloseHandle(hBonusEffectTimer[i]);
CloseHandle(hBonusTimeoutEvent[i]);
}
return 1;
}
VOID CALLBACK BonusEffectAPCProc(
LPVOID lpArg, // Data value
DWORD dwTimerLowValue, // Timer low value
DWORD dwTimerHighValue) // Timer high value
{
// Formal parameters not used.
UNREFERENCED_PARAMETER(dwTimerLowValue);
UNREFERENCED_PARAMETER(dwTimerHighValue);
BonusTimerVariables* pBonusTimerVariables = (BonusTimerVariables*)lpArg;
GameData* pGameData = pBonusTimerVariables->pGameVariables->pGameData;
if (pGameData->bonus[pBonusTimerVariables->bonusIndex].status == BONUS_CAUGHT)
{
switch (pGameData->bonus[pBonusTimerVariables->bonusIndex].type)
{
case BONUS_SPEED_UP:
//Reduce ball speed according to the value it was increased
ballBonusDecrease(pGameData);
break;
case BONUS_SLOW_DOWN:
//Raise ball speed according to the value it was decreased
ballBonusIncrease(pGameData);
break;
default:
return;
}
WaitForSingleObject(hBonusMutex, INFINITE);
pGameData->bonus[pBonusTimerVariables->bonusIndex].status = BONUS_INACTIVE;
pGameData->numBonus--;
ReleaseMutex(hBonusMutex);
OutputDebugString(TEXT("\nBonus timed out:\n\n"));
MessageBeep(0);
} else
{
OutputDebugString(TEXT("\nInvalid bonus:\n\n"));
}
}
DWORD WINAPI BricksMovementLogic(LPVOID lpParam)
{
GameVariables* pGameVariables = (GameVariables*)lpParam;
GameData* pGameData = pGameVariables->pGameData;
HANDLE hBrickMovementWait;
LARGE_INTEGER timeToWait;
int movementSpeed = pGameVariables->gameConfigs.movementSpeed;
timeToWait.QuadPart = _100MILLISECONDS * pGameVariables->gameConfigs.bricksMovementTime;
// Create an unnamed waitable timer for the bonus movement.
hBrickMovementWait = CreateWaitableTimer(NULL, TRUE, NULL);
if (hBrickMovementWait == NULL)
{
_tprintf(TEXT("CreateWaitableTimer failed (%d)\n"), GetLastError());
return -1;
}
int index;
while (pGameData->gameStatus != GAME_OVER)
{
if (!SetWaitableTimer(hBrickMovementWait, &timeToWait, 0, NULL, NULL, 0))
{
_tprintf(TEXT("SetWaitableTimer failed (%d)\n"), GetLastError());
return -1;
}
//Check bricks direction
if (pGameData->bricksDirectionX == DIRECTION_X_RIGHT)
{
//Bricks are going to the right so check if collision happened
if (pGameData->brick[MAX_BRICKS_IN_LINE - 1].position.x + BRICKS_WIDTH >= GAME_BORDER_RIGHT)
{
pGameData->bricksDirectionX = DIRECTION_X_LEFT;
movementSpeed *= -1;
}
} else if(pGameData->bricksDirectionX == DIRECTION_X_LEFT)
{
//Bricks are going to the left so check if collision happened
if (pGameData->brick[0].position.x <= GAME_BORDER_LEFT)
{
pGameData->bricksDirectionX = DIRECTION_X_RIGHT;
movementSpeed *= -1;
}
}
WaitForSingleObject(hBrickMovementMutex, INFINITE);
for (int i = 0; i < MAX_BRICK_LINES; i++)
{
for (int j = 0; j < MAX_BRICKS_IN_LINE; j++)
{
index = j + i * MAX_BRICKS_IN_LINE;
pGameData->brick[index].position.x += movementSpeed;
}
}
ReleaseMutex(hBrickMovementMutex);
if (WaitForSingleObject(hBrickMovementWait, INFINITE) != WAIT_OBJECT_0) {
_tprintf(TEXT("WaitForSingleObject failed (%d)\n"), GetLastError());
return -1;
}
}
CloseHandle(hBrickMovementWait);
return 1;
}
BOOL ballBonusIncrease(GameData* pGameData)
{
BOOL bonusActivated = FALSE;
WaitForSingleObject(hBallControlMutex, INFINITE);
for (int i = 0; i < MAX_BALLS; ++i)
{
if (pGameData->ball[i].inPlay == TRUE)
{
if (pGameData->ball[i].velocityRatio < SPEED_UP_ACTIVATE_VALUE)
{
pGameData->ball[i].velocityRatio += SPEED_UP_INCREASE;
bonusActivated = TRUE;
}
}
}
ReleaseMutex(hBallControlMutex);
return bonusActivated;
}
BOOL ballBonusDecrease(GameData* pGameData)
{
BOOL bonusActivated = FALSE;
WaitForSingleObject(hBallControlMutex, INFINITE);
for (int i = 0; i < MAX_BALLS; ++i)
{
if (pGameData->ball[i].inPlay == TRUE)
{
if (pGameData->ball[i].velocityRatio > SLOW_DOWN_ACTIVATE_VALUE)
{
pGameData->ball[i].velocityRatio -= SLOW_DOWN_DECREASE;
bonusActivated = TRUE;
}
}
}
ReleaseMutex(hBallControlMutex);
return bonusActivated;
}
void tripleBallBonus(GameData* pGameData)
{
WaitForSingleObject(hBallControlMutex, INFINITE);
for (int i = 0; i < MAX_BALLS; ++i)
{
if (pGameData->ball[i].inPlay == FALSE)
{
resetBall(&pGameData->ball[i]);
pGameData->ball[i].inPlay = TRUE;
pGameData->numBalls++;
randomizeBallPosition(&pGameData->ball[i]);
}
}
ReleaseMutex(hBallControlMutex);
}
void randomizeBallPosition(Ball* ball)
{
rand_s(&random);
ball->position.x = random % GAME_BOARD_WIDTH + GAME_BORDER_LEFT;
rand_s(&random);
ball->position.y = random % GAME_BALL_RANDOM_AREA_Y + GAME_BRICKS_BOTTOM;
}
void initializeGame(GameVariables* pGameVariables)
{
GameData* pGameData = pGameVariables->pGameData;
pGameData->gameStatus = GAME_ACTIVE;
pGameData->level = 1;
pGameData->lives = pGameVariables->gameConfigs.initialLives;
pGameData->numBalls = 1;
for (int i = 0; i < MAX_BALLS; i++)
{
resetBall(&pGameData->ball[i]);
}
pGameData->ball[0].inPlay = TRUE;
pGameData->bricksDirectionX = DIRECTION_X_RIGHT;
pGameData->numBricks = 0;
initializeBricks(pGameVariables);
//Initialize bonus
hBonusEvent = CreateEvent(
NULL, // default security attributes
FALSE, // auto-reset event
FALSE, // initial state is nonsignaled
NULL // unnamed event
);
hBallControlMutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
NULL); // unnamed mutex
hBonusMutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
NULL); // unnamed mutex
hBrickMovementMutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
NULL); // unnamed mutex
pGameData->numBonus = 0;
for (int i = 0; i < pGameVariables->gameConfigs.maxBonus; i++)
{
pGameData->bonus[i].status = BONUS_INACTIVE;
}
}
void resetBall(Ball* ball)
{
ball->velocityRatio = 100;
rand_s(&random);
ball->directionY = random % 2 == 1
? 1
: -1;
rand_s(&random);
ball->directionX = random % 2 == 1
? 1
: -1;
ball->playerIndex = UNDEFINED_ID;
ball->position.x = GAME_BOARD_WIDTH / 2 + GAME_BORDER_LEFT;
ball->position.y = GAME_BOARD_HEIGHT / 2 + GAME_BORDER_TOP;
ball->inPlay = FALSE;
}
void initializeBricks(GameVariables* pGameVariables)
{
GameData* pGameData = pGameVariables->pGameData;
int index;
int maxResistance = pGameData->level > BRICKS_MAX_RESISTANCE
? BRICKS_MAX_RESISTANCE
: pGameData->level;
int probability;
for (int i = 0; i < MAX_BRICK_LINES; i++)
{
for (int j = 0; j < MAX_BRICKS_IN_LINE; j++)
{
if (pGameData->numBricks == pGameVariables->gameConfigs.numBricks)
{
break;
}
pGameData->numBricks++;
index = j + i * MAX_BRICKS_IN_LINE;
//Setup brick position
pGameData->brick[index].position.x = (BRICKS_WIDTH + GAME_BRICKS_MARGIN) * j + GAME_BORDER_LEFT;
pGameData->brick[index].position.y = BRICKS_HEIGHT * i + GAME_BORDER_TOP;
pGameData->brick[index].hasBonus = FALSE;
rand_s(&random);
pGameData->brick[index].resistance = (random % maxResistance) + 1;
//Setup bonus
rand_s(&random);
probability = (random % 100) + 1;
if (probability <= pGameVariables->gameConfigs.bonusProbability)
{
pGameData->brick[index].hasBonus = TRUE;
rand_s(&random);
pGameData->brick[index].bonusType = random % TOTAL_BONUS;
pGameData->brick[index].resistance = 1;
}
}
}
}
void advanceLevel(GameVariables* pGameVariables)
{
GameData* pGameData = pGameVariables->pGameData;
pGameData->level++;
WaitForSingleObject(hBallControlMutex, INFINITE);
pGameData->numBalls = 1;
for (int i = 0; i < MAX_BALLS; i++)
{
resetBall(&pGameData->ball[i]);
}
pGameData->ball[0].inPlay = TRUE;
ReleaseMutex(hBallControlMutex);
pGameData->numBricks = 0;
initializeBricks(pGameVariables);
pGameData->numBonus = 0;
WaitForSingleObject(hBonusMutex, INFINITE);
for (int i = 0; i < pGameVariables->gameConfigs.maxBonus; i++)
{
pGameData->bonus[i].status = BONUS_INACTIVE;
}
ReleaseMutex(hBonusMutex);
}
void sendGameUpdate(GameVariables gameVariables)
{
if (!SetEvent(gameVariables.hGameUpdateEvent))
{
_tprintf(TEXT("SetEvent GameUpdate failed (%d)\n"), GetLastError());
return;
}
ResetEvent(gameVariables.hGameUpdateEvent);
for (int i = 0; i < gameVariables.gameConfigs.maxPlayers; i++)
{
if (gameVariables.namedPipesData[i].userID != UNDEFINED_ID)
{
sendGameNamedPipe(*gameVariables.pGameData, &gameVariables.namedPipesData[i]);
}
}
}
void ballMovement(GameVariables* pGameVariables)
{
GameData* pGameData = pGameVariables->pGameData;
WaitForSingleObject(hBallControlMutex, INFINITE);
for (int i = 0, j = 0; j < pGameData->numBalls; i++)
{
if (pGameData->ball[i].inPlay == TRUE)
{
//Advance ball according to speed
int velocity = pGameVariables->gameConfigs.movementSpeed * pGameData->ball[i].velocityRatio / 100;
pGameData->ball[i].position.x += velocity * pGameData->ball[i].directionX;
pGameData->ball[i].position.y += velocity * pGameData->ball[i].directionY;
detectBallCollision(pGameVariables, i);
_stprintf_s(debugText, MAX, TEXT("\nBall %d position x: %d y: %d\n"), i, pGameData->ball[i].position.x, pGameData->ball[i].position.y);
OutputDebugString(debugText);
j++;
}
}
ReleaseMutex(hBallControlMutex);
}
void detectBallCollision(GameVariables* pGameVariables, int index)
{
GameData* pGameData = pGameVariables->pGameData;
Ball* ball = &pGameData->ball[index];
//Game Border Right or Left Collisions
if (ball->position.x + GAME_BALL_WIDTH >= GAME_BORDER_RIGHT)
{
//Right border hit -> Move left instead
ball->directionX = DIRECTION_X_LEFT;
}
else if (ball->position.x <= GAME_BORDER_LEFT)
{
//Left border hit -> Move right instead
ball->directionX = DIRECTION_X_RIGHT;
}
//Game Border Top or Bottom Collisions
if (ball->position.y <= GAME_BORDER_TOP)
{
//Top border hit -> Move down instead
ball->directionY = DIRECTION_Y_DOWN;
}
else if (ball->position.y + GAME_BALL_HEIGHT >= DIM_Y_FRAME)
{
//Bottom border hit -> Move up instead
//Resets the ball
resetBall(ball);
//If it was the last ball removes a life and puts the ball back in play
if (pGameData->numBalls == 1)
{
pGameData->lives--;
ball->inPlay = TRUE;
//Invalidate all bonus that were caught
WaitForSingleObject(hBonusMutex, INFINITE);
for(int i = 0; i < MAX_BONUS; i++)
{
if (pGameData->bonus[i].status == BONUS_CAUGHT)
{
pGameData->bonus[i].status = BONUS_INACTIVE;
pGameData->numBonus--;
}
}
ReleaseMutex(hBonusMutex);
} else
{
pGameData->numBalls--;
}
return;
}
int direction;
//Brick collisions
//Check if ball is going up or down
int y = ball->position.y, x = ball->position.x;
if (ball->directionY == DIRECTION_Y_UP)
{
if (ball->directionX == DIRECTION_X_RIGHT)
{
//Ball is going up and right
y += GAME_BALL_HITBOX;
x += GAME_BALL_WIDTH - GAME_BALL_HITBOX;
direction = DIRECTION_LEFT_TO_RIGHT;
ballAndBrickCollision(pGameVariables, index, x, y, direction);
}
else if (ball->directionX == DIRECTION_X_LEFT)
{
//Ball is going up and left
y += GAME_BALL_HITBOX;
x += GAME_BALL_HITBOX;
direction = DIRECTION_RIGHT_TO_LEFT;
ballAndBrickCollision(pGameVariables, index, x, y, direction);
}
}
else if (ball->directionY == DIRECTION_Y_DOWN)
{
if (ball->directionX == DIRECTION_X_RIGHT)
{
//Ball is going down and right
x += GAME_BALL_WIDTH - GAME_BALL_HITBOX;
y += GAME_BALL_HEIGHT - GAME_BALL_HITBOX;
direction = DIRECTION_LEFT_TO_RIGHT;
ballAndBrickCollision(pGameVariables, index, x, y, DIRECTION_LEFT_TO_RIGHT);
}
else if (ball->directionX == DIRECTION_X_LEFT)
{
//Ball is going down and left
y += GAME_BALL_HEIGHT - GAME_BALL_HITBOX;
direction = DIRECTION_RIGHT_TO_LEFT;
ballAndBrickCollision(pGameVariables, index, x, y, DIRECTION_RIGHT_TO_LEFT);
}
}
if (y >= GAME_BARRIER_Y)
{
ballAndBarrierCollision(pGameVariables, index, x, y, direction);
}
//TODO: Check bonus collision
}
void ballAndBrickCollision(GameVariables* pGameVariables, int index, int x, int y, int directionX)
{
GameData* pGameData = pGameVariables->pGameData;
Ball* ball = &pGameData->ball[index];
if (ball->position.y >= GAME_BORDER_TOP && ball->position.y <= GAME_BRICKS_BOTTOM)
{
//Convert ball position to brick index
int brickIndexY = (y - GAME_BORDER_TOP) / BRICKS_HEIGHT;
int brickIndex;
Brick* brick = NULL;
//Find brickIndexX
WaitForSingleObject(hBrickMovementMutex, INFINITE);
for(int i = 0; i < MAX_BRICKS_IN_LINE; i++)
{
brickIndex = i + (brickIndexY - 1) * MAX_BRICKS_IN_LINE;
brick = &pGameData->brick[brickIndex];
if(x >= brick->position.x && x <= brick->position.x + BRICKS_WIDTH + GAME_BRICKS_MARGIN)
{
break;
}
}
ReleaseMutex(hBrickMovementMutex);
if(brick == NULL)
{
OutputDebugString(TEXT("Could not find brick!!"));
return;
}
if (brick->resistance > 0)
{
//Hit was from below the brick
if (y <= brick->position.y + BRICKS_HEIGHT / 2)
{
ball->directionY *= -1;
}
//Hit was from above the brick
if (y >= brick->position.y + BRICKS_HEIGHT / 2)
{
ball->directionY *= -1;
}
//Hit was on left
if (x <= brick->position.x + GAME_BRICK_HITBOX)
{
//Switch direction if the hit was going from left to the right
if (directionX == DIRECTION_LEFT_TO_RIGHT)
{
ball->directionX = DIRECTION_X_LEFT;
}
}
//Hit was on right
if (x >= brick->position.x + BRICKS_WIDTH / 2 + GAME_BRICK_HITBOX)
{
//Switch direction if the hit was from the right too
if (directionX == DIRECTION_RIGHT_TO_LEFT)
{
ball->directionX = DIRECTION_X_RIGHT;
}
}
brick->resistance--;
pGameData->numBricks--;
//If a valid player hit the ball increase scoreboard
if (ball->playerIndex != UNDEFINED_ID)
{
pGameData->player[ball->playerIndex].score += 1;
}
//Check if brick has bonus
if (brick->hasBonus == TRUE)
{
if (pGameData->numBonus < pGameVariables->gameConfigs.maxBonus)
{
if (pGameData->numBonus == 0)
{
SetEvent(hBonusEvent);
}
for (int i = 0; i < pGameVariables->gameConfigs.maxBonus; i++)
{
WaitForSingleObject(hBonusMutex, INFINITE);
if (pGameData->bonus[i].status == BONUS_INACTIVE)
{
pGameData->bonus[i].status = BONUS_IN_PLAY;
pGameData->bonus[i].position.x = brick->position.x;
pGameData->bonus[i].position.y = brick->position.y;
pGameData->bonus[i].type = brick->bonusType;
pGameData->numBonus++;
ReleaseMutex(hBonusMutex);
return;
}
ReleaseMutex(hBonusMutex);
}
}
}
}
}
}
void ballAndBarrierCollision(GameVariables* pGameVariables, int index, int x, int y, int directionX)
{
GameData* pGameData = pGameVariables->pGameData;
for (int i = 0; i < pGameData->numPlayers; i++)
{
if (pGameData->player[i].inGame == TRUE)
{
//Checks if ball hit a barrier
int barrierDimension = pGameData->barrierDimensions * pGameData->barrier[i].sizeRatio;
if (x >= pGameData->barrier[i].position.x && x <= pGameData->barrier[i].position.x + barrierDimension) {
int hitbox = pGameData->barrierDimensions / 8;
//Check which side of the barrier was hit
WaitForSingleObject(pGameVariables->hGameLogicMutex, INFINITE);
if (x <= pGameData->barrier[i].position.x + hitbox)
{
//Left side was hit
if (directionX == DIRECTION_LEFT_TO_RIGHT)
{
pGameData->ball[index].directionX = DIRECTION_X_LEFT;
}
}
else if (x >= pGameData->barrier[i].position.x + pGameData->barrierDimensions - hitbox)
{
//Right side was hit
if (directionX == DIRECTION_RIGHT_TO_LEFT)
{
pGameData->ball[index].directionX = DIRECTION_X_RIGHT;
}
}
ReleaseMutex(pGameVariables->hGameLogicMutex);
pGameData->ball[index].directionY = DIRECTION_Y_UP;
pGameData->ball[index].playerIndex = i;
return;
}
}
}
}
void assignUsersToGame(GameData* pGameData, Player* users, int currentUsers)
{
pGameData->numPlayers = currentUsers;
int maxDimension = BARRIER_AREA / pGameData->numPlayers;
pGameData->barrierDimensions = maxDimension - maxDimension * BARRIER_MARGIN_PERCENTAGE;
int barrierStartPosition = GAME_BORDER_LEFT + ((maxDimension + BARRIER_REMAINDER) / 2) - pGameData->barrierDimensions / 2;
for (int i = 0; i < currentUsers; i++)
{
//Setup Player
_tcscpy_s(pGameData->player[i].username, TAM, users[i].username);
pGameData->player[i].id = users[i].id;
pGameData->player[i].inGame = TRUE;
pGameData->player[i].score = 0;
//Setup Barrier
pGameData->barrier[i].playerID = pGameData->player[i].id;
pGameData->barrier[i].sizeRatio = 1;
pGameData->barrier[i].position.x = barrierStartPosition;
barrierStartPosition += maxDimension;
pGameData->barrier[i].position.y = GAME_BARRIER_Y;
}
}
void gameOver(GameData* pGameData)
{
//Update user status from game
for (int i = 0; i < pGameData->numPlayers; ++i)
{
pGameData->player[i].inGame = FALSE;
}
}
int getPlayerToTheRight(GameData gameData, int userPosition)
{
for (int i = userPosition; i < gameData.numPlayers - 1; i++)
{
if (gameData.player[i + 1].inGame == TRUE)
{
return i + 1;
}
}
return -1;
}
int getPlayerToTheLeft(GameData gameData, int userPosition)
{
for (int i = userPosition; i > 0; i--)
{
if (gameData.player[i - 1].inGame == TRUE)
{
return i - 1;
}
}
return -1;
}
void saveGameScoresAndOrderTop10(GameVariables* pGameVariables)
{
GameData* pGameData = pGameVariables->pGameData;
TopPlayer* pTopPlayers = pGameVariables->topPlayers;
DWORD* top10PlayerCount = pGameVariables->top10PlayerCount;
TopPlayer topPlayerTemp;
int counter = 0;
for (int i = 0; i < MAX_TOP_PLAYERS; i++)
{
for (int j = 0; j < pGameData->numPlayers; j++)
{
if (pTopPlayers[i].topScore < pGameData->player[j].score)
{
//Copy value to temporary
topPlayerTemp.topScore = pTopPlayers[i].topScore;
_tcscpy_s(topPlayerTemp.username, TAM, pTopPlayers[i].username);
//Replace top10 value with player value
pTopPlayers[i].topScore = pGameData->player[j].score;
_tcscpy_s(pTopPlayers[i].username, TAM, pGameData->player[j].username);
//Replace player value with top player and continue ordering
pGameData->player[j].score = topPlayerTemp.topScore;
_tcscpy_s(pGameData->player[j].username, TAM, topPlayerTemp.username);
}
}
if (pTopPlayers[i].topScore != 0)
{
counter++;
}
}
*top10PlayerCount = counter;
convertTopPlayersToString(pTopPlayers, pGameVariables->top10Value, top10PlayerCount);
//Create value "TOP10" = "top10Value"
RegSetValueEx(pGameVariables->hResgistryTop10Key, TOP10_REGISTRY_VALUE, 0, REG_SZ, (LPBYTE)pGameVariables->top10Value, _tcslen(pGameVariables->top10Value) * sizeof(TCHAR));
//Create value "TOP10PlayerCount" = top10PlayerCount
RegSetValueEx(pGameVariables->hResgistryTop10Key, TOP10_PLAYER_COUNT, 0, REG_DWORD, (LPBYTE)*top10PlayerCount, sizeof(DWORD));
}
int getInGamePlayers(GameData* pGameData)
{
int counter = 0;
for (int i = 0; i < pGameData->numPlayers; ++i)
{
if (pGameData->player[i].inGame == TRUE)
{
counter++;
}
}
return counter;
}
| 2.15625 | 2 |
2024-11-18T22:09:36.103168+00:00
| 2023-08-30T23:56:13 |
5b707850accec08e9be4e17fa56b6673cafe1c72
|
{
"blob_id": "5b707850accec08e9be4e17fa56b6673cafe1c72",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-30T23:56:13",
"content_id": "aebdd72ae2fd6eee5930f0c77451a13f41ee08d8",
"detected_licenses": [
"MIT"
],
"directory_id": "51de1ebe7fa09fb262e015fb454829987ed5fc83",
"extension": "c",
"filename": "iothub_security_factory.c",
"fork_events_count": 902,
"gha_created_at": "2016-10-14T17:54:57",
"gha_event_created_at": "2023-09-06T17:41:38",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 70934373,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5106,
"license": "MIT",
"license_type": "permissive",
"path": "/provisioning_client/src/iothub_security_factory.c",
"provenance": "stackv2-0106.json.gz:38575",
"repo_name": "Azure/azure-iot-sdk-c",
"revision_date": "2023-08-30T23:56:13",
"revision_id": "1f3d95b4dae09927ae4bbe479e52d48acef1f93c",
"snapshot_id": "54bf46938f5b8089ba06081cb4d7967fa3a8f777",
"src_encoding": "UTF-8",
"star_events_count": 629,
"url": "https://raw.githubusercontent.com/Azure/azure-iot-sdk-c/1f3d95b4dae09927ae4bbe479e52d48acef1f93c/provisioning_client/src/iothub_security_factory.c",
"visit_date": "2023-08-31T03:36:13.694208"
}
|
stackv2
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include <stdlib.h>
#include "azure_prov_client/iothub_security_factory.h"
#include "azure_prov_client/prov_security_factory.h"
#include "azure_c_shared_utility/xlogging.h"
#include "azure_c_shared_utility/crt_abstractions.h"
#include "hsm_client_data.h"
static IOTHUB_SECURITY_TYPE g_security_type = IOTHUB_SECURITY_TYPE_UNKNOWN;
static char* g_symm_key = NULL;
static char* g_symm_key_reg_name = NULL;
static SECURE_DEVICE_TYPE get_secure_device_type(IOTHUB_SECURITY_TYPE sec_type)
{
SECURE_DEVICE_TYPE ret;
switch (sec_type)
{
#if defined(HSM_TYPE_SAS_TOKEN) || defined(HSM_AUTH_TYPE_CUSTOM)
case IOTHUB_SECURITY_TYPE_SAS:
ret = SECURE_DEVICE_TYPE_TPM;
break;
#endif
#if defined(HSM_TYPE_X509) || defined(HSM_TYPE_RIOT) || defined(HSM_AUTH_TYPE_CUSTOM)
case IOTHUB_SECURITY_TYPE_X509:
ret = SECURE_DEVICE_TYPE_X509;
break;
#endif
#if defined(HSM_TYPE_SYMM_KEY) || defined(HSM_AUTH_TYPE_CUSTOM)
case IOTHUB_SECURITY_TYPE_SYMMETRIC_KEY:
ret = SECURE_DEVICE_TYPE_SYMMETRIC_KEY;
break;
#endif
#ifdef HSM_TYPE_HTTP_EDGE
case IOTHUB_SECURITY_TYPE_HTTP_EDGE:
ret = SECURE_DEVICE_TYPE_HTTP_EDGE;
break;
#endif
default:
ret = SECURE_DEVICE_TYPE_UNKNOWN;
break;
}
return ret;
}
int iothub_security_init(IOTHUB_SECURITY_TYPE sec_type)
{
int result;
SECURE_DEVICE_TYPE secure_device_type_from_caller = get_secure_device_type(sec_type);
if (secure_device_type_from_caller == SECURE_DEVICE_TYPE_UNKNOWN)
{
LogError("Security type %d is not supported in this SDK build", sec_type);
result = MU_FAILURE;
}
else
{
g_security_type = sec_type;
SECURE_DEVICE_TYPE security_device_type_from_prov = prov_dev_security_get_type();
if (security_device_type_from_prov == SECURE_DEVICE_TYPE_UNKNOWN)
{
result = prov_dev_security_init(secure_device_type_from_caller);
}
else if (secure_device_type_from_caller != security_device_type_from_prov)
{
LogError("Security type from caller %d (which maps to security device type %d) does not match already specified security device type %d", sec_type, secure_device_type_from_caller, security_device_type_from_prov);
result = MU_FAILURE;
}
else
{
result = 0;
}
if (result == 0)
{
result = initialize_hsm_system();
}
}
return result;
}
void iothub_security_deinit()
{
if (g_symm_key != NULL)
{
free(g_symm_key);
g_symm_key = NULL;
}
if (g_symm_key_reg_name != NULL)
{
free(g_symm_key_reg_name);
g_symm_key_reg_name = NULL;
}
deinitialize_hsm_system();
if (prov_dev_get_symmetric_key() != NULL || prov_dev_get_symm_registration_name() != NULL)
{
prov_dev_security_deinit();
}
}
IOTHUB_SECURITY_TYPE iothub_security_type()
{
return g_security_type;
}
int iothub_security_set_symmetric_key_info(const char* registration_name, const char* symmetric_key)
{
int result;
if (registration_name == NULL || symmetric_key == NULL)
{
LogError("Invalid parameter specified reg_name: %p, symm_key: %p", registration_name, symmetric_key);
result = MU_FAILURE;
}
else
{
char* temp_key;
char* temp_name;
if (mallocAndStrcpy_s(&temp_name, registration_name) != 0)
{
LogError("Failure allocating registration name");
result = MU_FAILURE;
}
else if (mallocAndStrcpy_s(&temp_key, symmetric_key) != 0)
{
LogError("Failure allocating symmetric key");
free(temp_name);
result = MU_FAILURE;
}
else
{
if (g_symm_key != NULL)
{
free(g_symm_key);
}
if (g_symm_key_reg_name != NULL)
{
free(g_symm_key_reg_name);
}
g_symm_key_reg_name = temp_name;
g_symm_key = temp_key;
// Sync iothub with dps
if (prov_dev_get_symmetric_key() == NULL || prov_dev_get_symm_registration_name() == NULL)
{
if (prov_dev_set_symmetric_key_info(g_symm_key_reg_name, g_symm_key) != 0)
{
LogError("Failure syncing dps & IoThub key information");
result = MU_FAILURE;
}
else
{
result = 0;
}
}
else
{
result = 0;
}
}
}
return result;
}
const char* iothub_security_get_symmetric_key()
{
return g_symm_key;
}
const char* iothub_security_get_symm_registration_name()
{
return g_symm_key_reg_name;
}
| 2.078125 | 2 |
2024-11-18T22:09:36.249670+00:00
| 2023-06-29T14:40:32 |
50dcac9044eb38a9bc0eb0c74d0eae895da6a2d2
|
{
"blob_id": "50dcac9044eb38a9bc0eb0c74d0eae895da6a2d2",
"branch_name": "refs/heads/main",
"committer_date": "2023-06-29T14:40:32",
"content_id": "91f1f2521f725cfef95a595d58e1693db0781736",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ffaa662396301e25ea308ef9fcc64175b7646de3",
"extension": "c",
"filename": "phoneme_code.c",
"fork_events_count": 19,
"gha_created_at": "2019-05-03T00:24:37",
"gha_event_created_at": "2023-04-09T22:08:49",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 184677120,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 24663,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/extras/references/taps/phoneme_code.c",
"provenance": "stackv2-0106.json.gz:38833",
"repo_name": "google/audio-to-tactile",
"revision_date": "2023-06-29T14:40:32",
"revision_id": "c13611b7a8d2ea80349be24bf54b2b50b9431347",
"snapshot_id": "b0f8006b0ddf0cd7a33b3d73bd941b0cd4149cc4",
"src_encoding": "UTF-8",
"star_events_count": 92,
"url": "https://raw.githubusercontent.com/google/audio-to-tactile/c13611b7a8d2ea80349be24bf54b2b50b9431347/extras/references/taps/phoneme_code.c",
"visit_date": "2023-09-04T12:16:32.657563"
}
|
stackv2
|
/* Copyright 2019 Google LLC
*
* 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
*
* https://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 "extras/references/taps/phoneme_code.h"
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "src/dsp/math_constants.h"
#include "extras/tools/util.h"
#define kNumChannels 24
/* kScale is half the max amplitude, set to match what Purdue did. The max value
* for legal signals in [-1, 1] is kScale = 0.5f.
*/
static const float kScale = 0.0765f;
/* Evaluate a squared Tukey window, nonzero over 0 < t < `window_duration` and
* having transitions of length `transition`.
*/
static float Window(float window_duration, float transition, float t) {
const float result = TukeyWindow(window_duration, transition, t);
return result * result;
}
/* 60Hz sine wave with a squared Tukey window. */
static float Pulse60Hz(float t, float duration) {
return sin(2.0 * M_PI * 60.0 * t) * Window(duration, 0.005f, t);
}
/* 300Hz sine wave with a squared Tukey window. */
static float Pulse300Hz(float t, float duration) {
return sin(2.0 * M_PI * 300.0 * t) * Window(duration, 0.005f, t);
}
/* 300Hz pulse with modulation. Used in B, D, DH, G, I, OO, and others. */
static float ModulatedBuzz(float t, float duration, float modulation_hz) {
return Pulse300Hz(t, duration) * kScale *
(1 + 0.5 * sin(2 * M_PI * modulation_hz * t));
}
/* 300Hz pulse with a gentle squared Hann window. Used in OE. */
static float OEPulse(float t) {
const float kDuration = 0.12f;
return sin(2.0 * M_PI * 300.0 * t) * Window(kDuration, kDuration / 2, t);
}
/* 60Hz pulse with 4Hz modulation. Pulse used in M, N, and NG. */
static float NasalPhonemeBuzz(float t) {
return kScale * Pulse60Hz(t, 0.4f) * (1 + sin(2.0 * M_PI * 8 * t));
}
/* Generate AE phoneme code (0 <= t <= 0.4s). "Twinkle" sensation. */
static void PhonemeAE(float t, float* frame) {
int c;
for (c = 0; c < 24; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.03333f;
frame[0] = kScale * (Pulse300Hz(t - 0.1332f, kDuration) +
Pulse300Hz(t - 0.3332f, kDuration));
frame[1] = kScale * (Pulse300Hz(t - 0.1f, kDuration) +
Pulse300Hz(t - 0.3f, kDuration));
frame[4] = kScale * (Pulse300Hz(t - 0.1660f, kDuration) +
Pulse300Hz(t - 0.3660f, kDuration));
frame[5] = kScale * (Pulse300Hz(t - 0.0666f, kDuration) +
Pulse300Hz(t - 0.2666f, kDuration));
frame[8] =
kScale * (Pulse300Hz(t, kDuration) + Pulse300Hz(t - 0.2f, kDuration));
frame[9] = kScale * (Pulse300Hz(t - 0.0333f, kDuration) +
Pulse300Hz(t - 0.2333f, kDuration));
}
/* Generate AH phoneme code (0 <= t <= 0.4s). Wide movement sensation. */
static void PhonemeAH(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.06667f;
frame[0] = kScale * Pulse60Hz(t, kDuration);
frame[1] = frame[0];
frame[4] = kScale * Pulse60Hz(t - 0.0666f, kDuration);
frame[5] = frame[4];
frame[8] = kScale * Pulse60Hz(t - 0.1332f, kDuration);
frame[9] = frame[8];
frame[12] = kScale * Pulse60Hz(t - 0.2f, kDuration);
frame[13] = frame[12];
frame[16] = kScale * Pulse60Hz(t - 0.2666f, kDuration);
frame[17] = frame[16];
frame[20] = kScale * Pulse60Hz(t - 0.3333f, kDuration);
frame[21] = frame[20];
}
/* Generate AW phoneme code (0 <= t <= 0.4s). "Twinkle" sensation. */
static void PhonemeAW(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.03333f;
frame[14] = kScale * (Pulse300Hz(t - 0.1332f, kDuration) +
Pulse300Hz(t - 0.3332f, kDuration));
frame[15] = kScale * (Pulse300Hz(t - 0.1f, kDuration) +
Pulse300Hz(t - 0.3f, kDuration));
frame[18] = kScale * (Pulse300Hz(t - 0.1660f, kDuration) +
Pulse300Hz(t - 0.3660f, kDuration));
frame[19] = kScale * (Pulse300Hz(t - 0.0666f, kDuration) +
Pulse300Hz(t - 0.2666f, kDuration));
frame[22] = kScale * (Pulse300Hz(t, kDuration) +
Pulse300Hz(t - 0.2f, kDuration));
frame[23] = kScale * (Pulse300Hz(t - 0.0333f, kDuration) +
Pulse300Hz(t - 0.2333f, kDuration));
}
/* Generate AY phoneme code (0 <= t <= 0.4s). Rumbling sensation. */
static void PhonemeAY(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.05f;
const float kModulationHz = 30.0f;
frame[8] = ModulatedBuzz(t, kDuration, kModulationHz);
frame[9] = ModulatedBuzz(t - 0.3495f, kDuration, kModulationHz);
frame[12] = ModulatedBuzz(t - 0.05f, kDuration, kModulationHz);
frame[13] = ModulatedBuzz(t - 0.3f, kDuration, kModulationHz);
frame[16] = ModulatedBuzz(t - 0.1f, kDuration, kModulationHz);
frame[17] = ModulatedBuzz(t - 0.25f, kDuration, kModulationHz);
frame[20] = ModulatedBuzz(t - 0.15f, kDuration, kModulationHz);
frame[21] = ModulatedBuzz(t - 0.2f, kDuration, kModulationHz);
}
/* Generate B phoneme code (0 <= t <= 0.14s). */
static void PhonemeB(float t, float* frame) {
const float buzz = ModulatedBuzz(t, 0.14f, 30.0f);
int c;
/* For a loop like this with a static number of iterations, Clang with -O2 or
* GCC with -O3 will unroll it and evaluate the `c == 16 || c == 17 || ...`
* conditional at compile time [https://godbolt.org/z/x6wwST].
*/
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 16 || c == 17 || c == 20 || c == 21) ? buzz : 0.0f;
}
}
/* Generate CH phoneme code (0 <= t <= 0.4s). */
static void PhonemeCH(float t, float* frame) {
const float buzz =
kScale * sin(2.0 * M_PI * 300.0 * t) * Window(0.4f, 0.2f, t);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 0 || c == 1 || c == 20 || c == 21) ? buzz : 0.0f;
}
}
/* Generate D phoneme code (0 <= t <= 0.14s). */
static void PhonemeD(float t, float* frame) {
const float buzz = ModulatedBuzz(t, 0.14f, 30.0f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 10 || c == 11 || c == 14 || c == 15) ? buzz : 0.0f;
}
}
/* Generate DH phoneme code (0 <= t <= 0.4s). */
static void PhonemeDH(float t, float* frame) {
const float buzz = ModulatedBuzz(t, 0.4f, 8.0f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 8 || c == 9 || c == 12 || c == 13) ? buzz : 0.0f;
}
}
/* Generate EE phoneme code (0 <= t <= 0.4s). Smooth movement sensation. */
static void PhonemeEE(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.09333f;
frame[0] = kScale * Pulse300Hz(t - 0.3063f, kDuration);
frame[4] = kScale * Pulse300Hz(t - 0.2448f, kDuration);
frame[8] = kScale * Pulse300Hz(t - 0.1836f, kDuration);
frame[12] = kScale * Pulse300Hz(t - 0.1224f, kDuration);
frame[16] = kScale * Pulse300Hz(t - 0.0612f, kDuration);
frame[20] = kScale * Pulse300Hz(t, kDuration);
}
/* Generate EH phoneme code (0 <= t <= 0.24s). Grabbing sensation. */
static void PhonemeEH(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.09603f;
frame[0] = kScale * Pulse300Hz(t, kDuration);
frame[1] = frame[0];
frame[2] = frame[0];
frame[3] = frame[0];
frame[12] = kScale * Pulse300Hz(t - 0.14395f, kDuration);
frame[13] = frame[12];
frame[14] = frame[12];
frame[15] = frame[12];
}
/* Generate ER phoneme code (0 <= t <= 0.4s). "Twinkle" sensation. */
static void PhonemeER(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.03333f;
frame[2] = kScale * (Pulse300Hz(t - 0.1f, kDuration) +
Pulse300Hz(t - 0.3f, kDuration));
frame[3] = kScale * (Pulse300Hz(t - 0.1332f, kDuration) +
Pulse300Hz(t - 0.3332f, kDuration));
frame[6] = kScale * (Pulse300Hz(t - 0.0666f, kDuration) +
Pulse300Hz(t - 0.2666f, kDuration));
frame[7] = kScale * (Pulse300Hz(t - 0.1660f, kDuration) +
Pulse300Hz(t - 0.3660f, kDuration));
frame[10] = kScale * (Pulse300Hz(t - 0.0333f, kDuration) +
Pulse300Hz(t - 0.2333f, kDuration));
frame[11] = kScale * (Pulse300Hz(t, kDuration) +
Pulse300Hz(t - 0.2f, kDuration));
}
/* Generate F phoneme code (0 <= t <= 0.4s). */
static void PhonemeF(float t, float* frame) {
const float buzz = kScale * Pulse300Hz(t, 0.4f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c >= 20) ? buzz : 0.0f;
}
}
/* Generate G phoneme code (0 <= t <= 0.14s). */
static void PhonemeG(float t, float* frame) {
const float buzz = ModulatedBuzz(t, 0.14f, 30.0f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 0 || c == 1 || c == 4 || c == 5) ? buzz : 0.0f;
}
}
/* Generate H phoneme code (0 <= t <= 0.4s). */
static void PhonemeH(float t, float* frame) {
const float buzz =
kScale * sin(2.0 * M_PI * 60.0 * t) * Window(0.4f, 0.2f, t);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (12 <= c && c < 20) ? buzz : 0.0f;
}
}
/* Generate I phoneme code (0 <= t <= 0.4s). Rumbling sensation. */
static void PhonemeI(float t, float* frame) {
const float kDuration = 0.05f;
const float kModulationHz = 30.0f;
frame[0] = ModulatedBuzz(t - 0.3495f, kDuration, kModulationHz);
frame[1] = frame[0];
frame[2] = ModulatedBuzz(t, kDuration, kModulationHz);
frame[3] = frame[2];
frame[4] = ModulatedBuzz(t - 0.3f, kDuration, kModulationHz);
frame[5] = frame[4];
frame[6] = ModulatedBuzz(t - 0.05f, kDuration, kModulationHz);
frame[7] = frame[6];
frame[8] = ModulatedBuzz(t - 0.25f, kDuration, kModulationHz);
frame[9] = frame[8];
frame[10] = ModulatedBuzz(t - 0.1f, kDuration, kModulationHz);
frame[11] = frame[10];
frame[12] = ModulatedBuzz(t - 0.2f, kDuration, kModulationHz);
frame[13] = frame[12];
frame[14] = ModulatedBuzz(t - 0.15f, kDuration, kModulationHz);
frame[15] = frame[14];
int c;
for (c = 16; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
}
/* Generate IH phoneme code (0 <= t <= 0.24s). Quick smooth movement. */
static void PhonemeIH(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
if (c != 0 && c != 4 && c != 8 && c != 12) {
frame[c] = 0.0f;
}
}
const float kDuration = 0.06f;
frame[0] = kScale * Pulse300Hz(t, kDuration);
frame[4] = kScale * Pulse300Hz(t - 0.06f, kDuration);
frame[8] = kScale * Pulse300Hz(t - 0.12f, kDuration);
frame[12] = kScale * Pulse300Hz(t - 0.18f, kDuration);
}
/* Generate J phoneme code (0 <= t <= 0.4s). */
static void PhonemeJ(float t, float* frame) {
const float buzz =
Pulse300Hz(t, 0.4f) *
(0.0155 + (0.1375 - 0.0155) * (1 + sin(2 * M_PI * 8.0 * t)) / 2);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 0 || c == 1 || c == 20 || c == 21) ? buzz : 0.0f;
}
}
/* Generate K phoneme code (0 <= t <= 0.14s). */
static void PhonemeK(float t, float* frame) {
const float buzz = kScale * Pulse300Hz(t, 0.14f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 0 || c == 1 || c == 4 || c == 5) ? buzz : 0.0f;
}
}
/* Generate L phoneme code (0 <= t <= 0.4s). */
static void PhonemeL(float t, float* frame) {
const float buzz = ModulatedBuzz(t, 0.4f, 30.0f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 18 || c == 19 || c == 22 || c == 23) ? buzz : 0.0f;
}
}
/* Generate M phoneme code (0 <= t <= 0.4s). */
static void PhonemeM(float t, float* frame) {
const float buzz = NasalPhonemeBuzz(t);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 16 || c == 17 || c == 20 || c == 21) ? buzz : 0.0f;
}
}
/* Generate N phoneme code (0 <= t <= 0.4s). */
static void PhonemeN(float t, float* frame) {
const float buzz = NasalPhonemeBuzz(t);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 10 || c == 11 || c == 14 || c == 15) ? buzz : 0.0f;
}
}
/* Generate NG phoneme code (0 <= t <= 0.4s). */
static void PhonemeNG(float t, float* frame) {
const float buzz = NasalPhonemeBuzz(t);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 0 || c == 1 || c == 4 || c == 5) ? buzz : 0.0f;
}
}
/* Generate OE phoneme code (0 <= t <= 0.4s). Smooth circular ring. */
static void PhonemeOE(float t, float* frame) {
int c;
for (c = 0; c < 8; ++c) {
frame[c] = 0.0f;
}
frame[8] = kScale * (OEPulse(t) + OEPulse(t - 0.28f));
frame[9] = kScale * OEPulse(t - 0.07f);
frame[10] = kScale * OEPulse(t - 0.14f);
frame[11] = kScale * OEPulse(t - 0.21f);
frame[12] = frame[8];
frame[13] = frame[9];
frame[14] = frame[10];
frame[15] = frame[11];
for (c = 16; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
}
/* Generate OO phoneme code (0 <= t <= 0.4s). Rumbling sensation. */
static void PhonemeOO(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.0667f;
const float kModulationHz = 30.0f;
frame[2] = ModulatedBuzz(t - 0.3333f, kDuration, kModulationHz);
frame[3] = frame[2];
frame[6] = ModulatedBuzz(t - 0.2666f, kDuration, kModulationHz);
frame[7] = frame[6];
frame[10] = ModulatedBuzz(t - 0.2f, kDuration, kModulationHz);
frame[11] = frame[10];
frame[14] = ModulatedBuzz(t - 0.1333f, kDuration, kModulationHz);
frame[15] = frame[14];
frame[18] = ModulatedBuzz(t - 0.0666f, kDuration, kModulationHz);
frame[19] = frame[18];
frame[22] = ModulatedBuzz(t, kDuration, kModulationHz);
frame[23] = frame[22];
}
/* Generate OW phoneme code (0 <= t <= 0.4s). Tapping sensation. */
static void PhonemeOW(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.024f;
frame[4] =
kScale *
(Pulse300Hz(t - 0.2824f, kDuration) + Pulse300Hz(t - 0.3295f, kDuration) +
Pulse300Hz(t - 0.3767f, kDuration)) *
Window(0.4f, 0.005f, t);
frame[12] = kScale * (Pulse300Hz(t - 0.1412f, kDuration) +
Pulse300Hz(t - 0.1888f, kDuration) +
Pulse300Hz(t - 0.2360f, kDuration));
frame[20] =
kScale * (Pulse300Hz(t, kDuration) + Pulse300Hz(t - 0.0472f, kDuration) +
Pulse300Hz(t - 0.0939f, kDuration));
}
/* Generate OY phoneme code (0 <= t <= 0.4s). Tapping sensation. */
static void PhonemeOY(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.024f;
frame[6] =
kScale * (Pulse300Hz(t, kDuration) + Pulse300Hz(t - 0.0472f, kDuration) +
Pulse300Hz(t - 0.0939f, kDuration));
frame[14] = kScale * (Pulse300Hz(t - 0.1412f, kDuration) +
Pulse300Hz(t - 0.1888f, kDuration) +
Pulse300Hz(t - 0.2360f, kDuration));
frame[22] =
kScale *
(Pulse300Hz(t - 0.2824f, kDuration) + Pulse300Hz(t - 0.3295f, kDuration) +
Pulse300Hz(t - 0.3767f, kDuration)) *
Window(0.4f, 0.005f, t);
}
/* Generate P phoneme code (0 <= t <= 0.14s). */
static void PhonemeP(float t, float* frame) {
const float buzz = kScale * Pulse300Hz(t, 0.14f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 16 || c == 17 || c == 20 || c == 21) ? buzz : 0.0f;
}
}
/* Generate R phoneme code (0 <= t <= 0.4s). */
static void PhonemeR(float t, float* frame) {
const float buzz = ModulatedBuzz(t, 0.4f, 30.0f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 2 || c == 3 || c == 6 || c == 7) ? buzz : 0.0f;
}
}
/* Generate S phoneme code (0 <= t <= 0.4s). */
static void PhonemeS(float t, float* frame) {
const float buzz = kScale * Pulse300Hz(t, 0.4f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c < 4) ? buzz : 0.0f;
}
}
/* Generate SH phoneme code (0 <= t <= 0.4s). */
static void PhonemeSH(float t, float* frame) {
const float buzz = kScale * Pulse300Hz(t, 0.4f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 18 || c == 19 || c == 22 || c == 23) ? buzz : 0.0f;
}
}
/* Generate T phoneme code (0 <= t <= 0.14s). */
static void PhonemeT(float t, float* frame) {
const float buzz = kScale * Pulse300Hz(t, 0.14f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 10 || c == 11 || c == 14 || c == 15) ? buzz : 0.0f;
}
}
/* Generate TH phoneme code (0 <= t <= 0.4s). */
static void PhonemeTH(float t, float* frame) {
const float buzz = kScale * Pulse300Hz(t, 0.4f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 8 || c == 9 || c == 12 || c == 13) ? buzz : 0.0f;
}
}
/* Generate UH phoneme code (0 <= t <= 0.24s). Grabbing sensation. */
static void PhonemeUH(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.09604f;
frame[8] = kScale * Pulse300Hz(t - 0.1439f, kDuration);
frame[9] = frame[8];
frame[10] = frame[8];
frame[11] = frame[8];
frame[20] = kScale * Pulse300Hz(t, kDuration);
frame[21] = frame[20];
frame[22] = frame[20];
frame[23] = frame[20];
}
/* Generate UU phoneme code (0 <= t <= 0.24s). Rumbling sensation. */
static void PhonemeUU(float t, float* frame) {
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = 0.0f;
}
const float kDuration = 0.06f;
const float kModulationHz = 30.0f;
frame[2] = ModulatedBuzz(t, kDuration, kModulationHz);
frame[3] = frame[2];
frame[6] = ModulatedBuzz(t - 0.06f, kDuration, kModulationHz);
frame[7] = frame[6];
frame[10] = ModulatedBuzz(t - 0.12f, kDuration, kModulationHz);
frame[11] = frame[10];
frame[14] = ModulatedBuzz(t - 0.18f, kDuration, kModulationHz);
frame[15] = frame[14];
}
/* Generate V phoneme code (0 <= t <= 0.4s). */
static void PhonemeV(float t, float* frame) {
const float buzz = ModulatedBuzz(t, 0.4f, 8.0f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c >= 20) ? buzz : 0.0f;
}
}
/* Generate W phoneme code (0 <= t <= 0.4s). */
static void PhonemeW(float t, float* frame) {
const float buzz = NasalPhonemeBuzz(t);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c % 2 == 0 && c >= 8) ? buzz : 0.0f;
}
}
/* Generate Y phoneme code (0 <= t <= 0.4s). */
static void PhonemeY(float t, float* frame) {
const float buzz = kScale * Pulse60Hz(t, 0.4f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c % 2 == 0 && c >= 8) ? buzz : 0.0f;
}
}
/* Generate Z phoneme code (0 <= t <= 0.4s). */
static void PhonemeZ(float t, float* frame) {
const float buzz = ModulatedBuzz(t, 0.4f, 8.0f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c < 4) ? buzz : 0.0f;
}
}
/* Generate ZH phoneme code (0 <= t <= 0.4s). */
static void PhonemeZH(float t, float* frame) {
const float buzz = ModulatedBuzz(t, 0.4f, 8.0f);
int c;
for (c = 0; c < kNumChannels; ++c) {
frame[c] = (c == 2 || c == 3 || c == 6 || c == 7) ? buzz : 0.0f;
}
}
const PhonemeCode kPhonemeCodebook[] = {
/* Fields: phoneme, fun, duration. */
{"AE", PhonemeAE, 0.4f}, {"AH", PhonemeAH, 0.4f}, {"AW", PhonemeAW, 0.4f},
{"AY", PhonemeAY, 0.4f}, {"B", PhonemeB, 0.14f}, {"CH", PhonemeCH, 0.4f},
{"D", PhonemeD, 0.14f}, {"DH", PhonemeDH, 0.4f}, {"EE", PhonemeEE, 0.4f},
{"EH", PhonemeEH, 0.24f}, {"ER", PhonemeER, 0.4f}, {"F", PhonemeF, 0.4f},
{"G", PhonemeG, 0.14f}, {"H", PhonemeH, 0.4f}, {"I", PhonemeI, 0.4f},
{"IH", PhonemeIH, 0.24f}, {"J", PhonemeJ, 0.4f}, {"K", PhonemeK, 0.14f},
{"L", PhonemeL, 0.4f}, {"M", PhonemeM, 0.4f}, {"N", PhonemeN, 0.4f},
{"NG", PhonemeNG, 0.4f}, {"OE", PhonemeOE, 0.4f}, {"OO", PhonemeOO, 0.4f},
{"OW", PhonemeOW, 0.4f}, {"OY", PhonemeOY, 0.4f}, {"P", PhonemeP, 0.14f},
{"R", PhonemeR, 0.4f}, {"S", PhonemeS, 0.4f}, {"SH", PhonemeSH, 0.4f},
{"T", PhonemeT, 0.14f}, {"TH", PhonemeTH, 0.4f}, {"UH", PhonemeUH, 0.24f},
{"UU", PhonemeUU, 0.24f}, {"V", PhonemeV, 0.4f}, {"W", PhonemeW, 0.4f},
{"Y", PhonemeY, 0.4f}, {"Z", PhonemeZ, 0.4f}, {"ZH", PhonemeZH, 0.4f},
};
const int kPhonemeCodebookSize =
sizeof(kPhonemeCodebook) / sizeof(*kPhonemeCodebook);
const PhonemeCode* PhonemeCodeByName(const char* name) {
/* Convert `name` to uppercase, stopping at the first non-alphanumeric char.
* Since all phoneme names are at most 2 chars, we stop and return NULL if
* the result would be longer than that.
*/
char phoneme[3];
int i;
for (i = 0; i < 3; ++i) {
if (!isalnum(name[i])) {
phoneme[i] = '\0';
break;
} else if (i < 2) {
phoneme[i] = toupper(name[i]);
} else {
return NULL; /* Name longer than 2 chars is invalid. */
}
}
/* Find and return codebook entry with matching phoneme name. */
for (i = 0; i < kPhonemeCodebookSize; ++i) {
if (!strcmp(phoneme, kPhonemeCodebook[i].phoneme)) {
return &kPhonemeCodebook[i];
}
}
return NULL; /* Not found. */
}
/* Finds start of next phoneme or NULL in a comma-delimited phonemes string. */
static const char* NextPhoneme(const char* phonemes) {
phonemes = strchr(phonemes, ',');
if (phonemes) {
++phonemes;
} /* Increment past the comma. */
return phonemes;
}
/* Computes the length in seconds for a phonemes string. */
static float PhonemeSignalLength(const char* phonemes, float spacing) {
float t = 0.0f;
float length = 0.0f;
const char* p;
int num_phonemes = 0;
for (p = phonemes; p; p = NextPhoneme(p)) {
const PhonemeCode* signal = PhonemeCodeByName(p);
if (signal == NULL) {
return -1.0f;
}
if (num_phonemes > 0) {
t += spacing;
}
/* Force nonnegative t, in case `spacing` is negative. */
if (t < 0.0f) {
t = 0.0f;
}
t += signal->duration;
if (t > length) {
length = t; /* Compute length as the maximum value of t. */
}
++num_phonemes;
}
return length;
}
float* GeneratePhonemeSignal(const char* phonemes, float spacing,
const char* emphasized_phoneme,
float emphasis_gain, float sample_rate_hz,
int* num_frames) {
const float length = PhonemeSignalLength(phonemes, spacing);
if (length < 0.0f) {
return NULL;
}
*num_frames = (int)(sample_rate_hz * length + 0.5f);
/* Allocate output samples. */
float* samples = (float*)malloc(kNumChannels * *num_frames * sizeof(float));
if (samples == NULL) {
return NULL;
}
int i;
for (i = 0; i < kNumChannels * *num_frames; ++i) {
samples[i] = 0.0f;
}
const int spacing_num_frames = (int)(sample_rate_hz * spacing);
int write_frame = 0;
float frame[kNumChannels];
for (; phonemes; phonemes = NextPhoneme(phonemes)) {
const PhonemeCode* signal = PhonemeCodeByName(phonemes);
float gain = 1.0f;
if (emphasized_phoneme && !strcmp(signal->phoneme, emphasized_phoneme)) {
gain = emphasis_gain;
}
int phoneme_num_frames = (int)(sample_rate_hz * signal->duration + 0.5f);
/* Make sure that phoneme signal stays within the allocated array. */
if (phoneme_num_frames > *num_frames - write_frame) {
phoneme_num_frames = *num_frames - write_frame;
}
/* Output the signal for one phoneme. */
float* dest = samples + kNumChannels * write_frame;
for (i = 0; i < phoneme_num_frames; ++i, dest += kNumChannels) {
const float t = i / sample_rate_hz;
signal->fun(t, frame);
int c;
for (c = 0; c < kNumChannels; ++c) {
dest[c] += gain * frame[c];
}
}
write_frame += phoneme_num_frames + spacing_num_frames;
/* Force nonnegative write_frame, in case `spacing` is negative. */
if (write_frame < 0) {
write_frame = 0;
}
}
return samples;
}
int PhonemeStringIsValid(const char* phonemes) {
for (; phonemes; phonemes = NextPhoneme(phonemes)) {
if (PhonemeCodeByName(phonemes) == NULL) {
return 0;
}
}
return 1;
}
| 2.125 | 2 |
2024-11-18T22:09:36.525372+00:00
| 2019-12-07T19:35:30 |
428c83f797a13a519cb38b3b357a49da23adae7b
|
{
"blob_id": "428c83f797a13a519cb38b3b357a49da23adae7b",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-07T19:35:30",
"content_id": "b8ada9c60c3538e3f16e49e4500e8caa2be61998",
"detected_licenses": [
"MIT"
],
"directory_id": "45b92e1c6e475d256dd36f3195738cdc138f9068",
"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": 219624792,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 364,
"license": "MIT",
"license_type": "permissive",
"path": "/chapter_3/graph.h",
"provenance": "stackv2-0106.json.gz:39090",
"repo_name": "leusgalvan/tardos",
"revision_date": "2019-12-07T19:35:30",
"revision_id": "51dc0c61c8b22622390cbce1ab28383fce7c0197",
"snapshot_id": "bcf77e13fe5e84495fa5f23b591a95537c25c5a8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/leusgalvan/tardos/51dc0c61c8b22622390cbce1ab28383fce7c0197/chapter_3/graph.h",
"visit_date": "2020-09-04T00:59:52.460496"
}
|
stackv2
|
#ifndef GRAPH_H
#define GRAPH_H
#include "doubly_linked_list.h"
typedef struct {
int n;
doubly_linked_list **adj;
} graph;
graph *g_create(int n);
void g_add_edge(graph *g, int v, int w);
void g_print(graph *g);
doubly_linked_list *get_neighbors(graph *g, int v);
void g_remove_edge(graph *g, int v, int w);
graph *g_copy(graph *g);
#endif // GRAPH_H
| 2.015625 | 2 |
2024-11-18T22:09:38.307411+00:00
| 2020-12-22T02:12:18 |
18547579de1dbc7857d270675447bc7f9c070fe3
|
{
"blob_id": "18547579de1dbc7857d270675447bc7f9c070fe3",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-22T02:12:18",
"content_id": "c5c6553a52c06685e934d6d1abf1fb7145035895",
"detected_licenses": [
"ISC",
"MIT"
],
"directory_id": "5d7b6cc06ea6a89796b9e67d4c51e8be0c68f58f",
"extension": "h",
"filename": "theft_bloom.h",
"fork_events_count": 0,
"gha_created_at": "2019-10-13T22:07:14",
"gha_event_created_at": "2019-10-13T22:07:14",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 214901061,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 852,
"license": "ISC,MIT",
"license_type": "permissive",
"path": "/deps/theft/theft_bloom.h",
"provenance": "stackv2-0106.json.gz:39474",
"repo_name": "gpanders/fzy",
"revision_date": "2020-12-22T02:12:18",
"revision_id": "06537e25c36f6d8905e4789b8de0024a4dd40825",
"snapshot_id": "c58123bb3b19053697e679574a2f2c8a07f70b3c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/gpanders/fzy/06537e25c36f6d8905e4789b8de0024a4dd40825/deps/theft/theft_bloom.h",
"visit_date": "2021-07-05T00:53:41.632747"
}
|
stackv2
|
#ifndef THEFT_BLOOM_H
#define THEFT_BLOOM_H
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
struct theft_bloom {
uint8_t bit_count;
size_t size;
uint8_t bits[];
};
/* Initialize a bloom filter. */
struct theft_bloom *theft_bloom_init(uint8_t bit_size2);
/* Hash data and mark it in the bloom filter. */
void theft_bloom_mark(struct theft_bloom *b, uint8_t *data, size_t data_size);
/* Check whether the data's hash is in the bloom filter. */
bool theft_bloom_check(struct theft_bloom *b, uint8_t *data, size_t data_size);
/* Free the bloom filter. */
void theft_bloom_free(struct theft_bloom *b);
/* Dump the bloom filter's contents. (Debugging.) */
void theft_bloom_dump(struct theft_bloom *b);
/* Recommend a bloom filter size for a given number of trials. */
uint8_t theft_bloom_recommendation(int trials);
#endif
| 2.171875 | 2 |
2024-11-18T22:09:38.593691+00:00
| 2013-07-03T11:34:48 |
32de2f5c07666e18f9de1de4a3b5a5e3128d55e7
|
{
"blob_id": "32de2f5c07666e18f9de1de4a3b5a5e3128d55e7",
"branch_name": "refs/heads/master",
"committer_date": "2013-07-03T11:34:48",
"content_id": "8e1f01ee30e28a14dc9eecf3b535655344351ab1",
"detected_licenses": [
"Zlib"
],
"directory_id": "5fc1edf1cd349e28732deef2fdbb9c256bf44f50",
"extension": "c",
"filename": "edit.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": 661,
"license": "Zlib",
"license_type": "permissive",
"path": "/Usermode/Applications/gui_ate_src/edit.c",
"provenance": "stackv2-0106.json.gz:39864",
"repo_name": "berkus/acess2",
"revision_date": "2013-07-03T11:34:48",
"revision_id": "e36d7e1874e8c68853da234636d70f45f86e4348",
"snapshot_id": "eb96911e5a75d8f9e8fa0999fae531cc2ff5c58d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/berkus/acess2/e36d7e1874e8c68853da234636d70f45f86e4348/Usermode/Applications/gui_ate_src/edit.c",
"visit_date": "2023-07-10T22:00:34.505389"
}
|
stackv2
|
/*
* Acess Text Editor (ATE)
* - By John Hodge (thePowersGang)
*
* edit.c
* - File Loading / Manipulation
*/
#include <stdio.h>
#include "include/file.h"
#include "include/syntax.h"
// === CODE ===
tFile *File_New(void)
{
tFile *ret = malloc(sizeof(tFile) + 1);
ret->Handle = NULL;
ret->nLines = 0;
ret->Lines = NULL;
ret->NameOfs = 0;
ret->Path[0] = 0;
return ret;
}
tFile *File_Load(const char *Path)
{
return NULL;
}
int File_Save(tFile *File)
{
//file->bIsDirty = 0;
return -1;
}
int File_Close(tFile *File, int bDiscard)
{
//if( file->bIsDirty && !bDiscard )
// return 1;
if( file->Handle )
fclose(File->Handle);
return 0;
}
| 2.296875 | 2 |
2024-11-18T22:09:38.707757+00:00
| 2023-07-05T20:55:51 |
e92eada55c4959d15457d50b180b5ede773b7587
|
{
"blob_id": "e92eada55c4959d15457d50b180b5ede773b7587",
"branch_name": "refs/heads/main",
"committer_date": "2023-07-05T20:55:51",
"content_id": "d5ef1b4b192960112298907bdd9fc8df1f4a45bf",
"detected_licenses": [
"MIT"
],
"directory_id": "11d231d29b7939c4345a3eff6279990a826ce270",
"extension": "c",
"filename": "lcd_lpwm.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 349760384,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5768,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/lcd_lpwm.c",
"provenance": "stackv2-0106.json.gz:39996",
"repo_name": "achilikin/N76E003-SDCC-BSP",
"revision_date": "2023-07-05T20:55:51",
"revision_id": "afc99a5896cc84a6e1a90dce1b3a24132cfc1a83",
"snapshot_id": "2729ef77152c83ba664848f31c10f3bd427a8dec",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/achilikin/N76E003-SDCC-BSP/afc99a5896cc84a6e1a90dce1b3a24132cfc1a83/lib/lcd_lpwm.c",
"visit_date": "2023-07-07T05:35:47.507040"
}
|
stackv2
|
/*
The MIT License (MIT)
Simple driver for LCD installed on XY-LPWM and some others
devices driven by N76E003.
*/
#include <N76E003.h>
#include "ht1621.h"
#include "lcd_lpwm.h"
#include "uart.h"
#define LCD_BUF_SIZE (LCD_NUM_SEGMENTS / 2)
static __xdata uint8_t lcd_buf[LCD_BUF_SIZE];
void lcd_buf_init(uint8_t fill)
{
for (uint8_t i = 0; i < LCD_BUF_SIZE; i++) {
lcd_buf[i] = fill;
ht1621_write_data(i*2, fill);
}
}
/**
* @param fill character to fill memory with
*/
void lcd_init(uint8_t fill)
{
ht1621_init(HT1621_BIAS_2 | HT1621_COM_4);
lcd_buf_init(fill);
}
void _set_sign(uint8_t sign, bool set)
{
uint8_t idx = sign >> 4;
uint8_t data = lcd_buf[idx];
uint8_t mask = 1;
mask <<= sign & 0x0F;
if (set)
data |= mask;
else
data &= ~mask;
lcd_buf[idx] = data;
ht1621_write_data(idx * 2, data);
}
/**
* signs:
* '0', '1', '2', '3', '4', '5', '6', '7': dots indexes
* ':': colon (same as '7')
* 'I': IN
* 'O': OUT
* 'S': SET
* 'C': C
* 'V': V (same as '3')
* 'W': W
* '%': %
* 'A': A
* 'h': h
*/
static const uint8_t lcd_signs[] = {
LCD_SIG_DOT0, 0x77, LCD_SIG_DOT1, 0x67,
LCD_SIG_DOT2, 0x57, LCD_SIG_DOT3, 0x47,
LCD_SIG_DOT4, 0x07, LCD_SIG_DOT5, 0x17,
LCD_SIG_DOT6, 0x27, LCD_SIG_DOT7, 0x37,
LCD_SIG_V, 0x47, LCD_SIG_COLON, 0x37,
LCD_SIG_IN, 0x84, LCD_SIG_OUT, 0x85,
LCD_SIG_CGRAD, 0x87, LCD_SIG_W, 0x40,
LCD_SIG_PERCENT, 0x41, LCD_SIG_A, 0x43,
LCD_SIG_h, 0x42, LCD_SIG_SET, 0x86,
};
void lcd_set_sign(uint8_t sign, bool set)
{
for (uint8_t idx = 0; idx < sizeof(lcd_signs); idx += 2) {
if (lcd_signs[idx] == sign) {
_set_sign(lcd_signs[++idx], set);
return;
}
}
return;
}
void lcd_set_dot(uint8_t idx, bool set)
{
if (idx < LCD_NUM_DIGITS)
lcd_set_sign('0' + idx, set);
}
/* map segment addresses for the digits */
static const uint8_t digit_addr[LCD_NUM_DIGITS] = {
15, 13, 11, 9, 0, 2, 4, 6
};
/**
* get one data byte starting from the given segment index/
* for odd segments the data is split between two bytes
* @param seg start map segment for a digit
*/
static uint8_t lcd_get_digit(uint8_t seg)
{
if (!(seg & 0x01))
return lcd_buf[seg >> 1];
seg >>= 1;
uint8_t data = lcd_buf[seg];
data &= 0xF0;
data |= lcd_buf[seg + 1] & 0x0F;
return data;
}
/* display digit but preserve corresponding 'dot' value */
static void _set_digit(uint8_t idx, uint8_t val)
{
uint8_t data;
idx = digit_addr[idx]; /* get digit's start map segment index */
data = lcd_get_digit(idx); /* get buffer data for this segment */
data &= 0x80; /* keep the highest bit unchanged - it stores 'dot' for the digit */
data |= val;
if (idx > 6)
data = swap8(data);
ht1621_write_data(idx, data);
/* idx is a segment address */
/* for line 0 we need to translate it to bytes */
idx >>= 1; /* byte index in the buffer */
data = lcd_buf[idx];
if (idx > 3) {
data &= 0x8F;
data |= val & 0x70;
lcd_buf[idx] = data;
idx += 1;
data = lcd_buf[idx];
data &= 0xF0;
data |= val & 0x0F;
} else {
data &= 0x80;
data |= val;
}
lcd_buf[idx] = data;
return;
}
/* hexadecimal digits */
static const uint8_t lcd_digit[16] = {
0x5F, 0x50, 0x3D, 0x79, /* 0x0 to 0x3 */
0x72, 0x6B, 0x6F, 0x51, /* 0x4 to 0x7 */
0x7F, 0x7B, 0x77, 0x6E, /* 0x8 to 0xB */
0x0F, 0x7C, 0x2F, 0x27 /* 0xC to 0xF */
};
/* supported characters defined in pairs and terminated by 0 */
static const uint8_t lcd_alpha[] = {
'0', 0x5F, '1', 0x50, '2', 0x3D, '3', 0x79, /* 0x0 to 0x4 */
'4', 0x72, '5', 0x6B, '6', 0x6F, '7', 0x51, /* 0x5 to 0x8 */
'8', 0x7F, '9', 0x7B, 'A', 0x77, 'B', 0x6E, /* 0x9 to 0xC */
'C', 0x0F, 'D', 0x7C, 'E', 0x2F, 'F', 0x27, /* 0xD to 0xF */
'G', 0x4F, 'H', 0x76, 'I', 0x06, 'J', 0x5C,
'L', 0x0E, 'O', 0x5F, 'P', 0x37, 'R', 0x07,
'S', 0x6B, 'T', 0x2E, 'U', 0x5E, 'Y', 0x7A,
'a', 0x77, 'b', 0x6E, 'c', 0x2C, 'd', 0x7C,
'e', 0x2F, 'f', 0x27, 'g', 0x4F, 'h', 0x66,
'i', 0x04, 'j', 0x48, 'l', 0x0C, 'm', 0x65,
'n', 0x64, 'o', 0x6C, 'p', 0x37, 'r', 0x24,
's', 0x6B, 't', 0x2E, 'u', 0x4C, 'y', 0x7a,
'-', 0x20, '=', 0x28, '>', 0x26, '<', 0x70,
'?', 0x35, '!', 0x06, '"', 0x12, '#', 0x29,
' ', 0x00, '_', 0x08, '^', 0x01, '\'', 0x10,
',', 0x40, '/', 0x34, '\\', 0x62,
0,
};
void lcd_set_symbol(uint8_t idx, uint8_t val)
{
uint8_t data;
if (idx >= LCD_NUM_DIGITS)
return;
if (val < 16) {
_set_digit(idx, lcd_digit[val]);
return;
}
for (data = 0; lcd_alpha[data] != 0; data+=2) {
if (lcd_alpha[data] == val) {
_set_digit(idx, lcd_alpha[++data]);
return;
}
}
return;
}
void lcd_printn(uint16_t num, uint8_t dstart, uint8_t width)
{
uint8_t n;
uint16_t div = 1;
if (width > 4) width = 4;
for (n = 1; n < width; n++)
div *= 10;
if (num > 999) {
n = 4;
if (num > 9999)
num = 9999;
} else if (num > 99)
n = 3;
else if (num > 9)
n = 2;
else
n = 1;
for (; width; dstart++) {
if (width > n)
lcd_set_symbol(dstart & 0x07, ' ');
else
lcd_set_digit(dstart & 0x07, num / div);
num %= div;
div /= 10;
width--;
}
}
#ifdef LCD_DEBUG
void lcd_dump(void)
{
for (uint8_t i = 0; i < LCD_BUF_SIZE; i++) {
uart_putc(' ');
uart_puth(lcd_buf[i]);
}
uart_putc('\n');
}
void lcd_set_raw(uint8_t idx, uint8_t val)
{
if (idx >= LCD_NUM_DIGITS)
return;
idx = digit_addr[idx]; /* get digit's start map segment index */
if (idx > 6)
val = swap8(val);
ht1621_write_data(idx, val);
/* idx is a segment address */
/* for line 0 we need to translate it to bytes */
idx >>= 1; /* byte index in the buffer */
uint8_t data = lcd_buf[idx];
if (idx > 3) {
data &= 0x0F;
data |= val & 0xF0;
lcd_buf[idx] = data;
idx += 1;
data = lcd_buf[idx];
data &= 0xF0;
data |= val & 0x0F;
} else {
data = val;
}
lcd_buf[idx] = data;
return;
}
#endif
| 3.046875 | 3 |
2024-11-18T22:09:39.869721+00:00
| 2019-10-05T10:08:29 |
22fca873aaaae2357ad17dbc6811e47532c9d864
|
{
"blob_id": "22fca873aaaae2357ad17dbc6811e47532c9d864",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-05T10:08:29",
"content_id": "ad899c1707efd99c0fc73ddcd677518f72b2068d",
"detected_licenses": [
"MIT"
],
"directory_id": "c5d313b0be54baef0b40e72c427665fc3a05f5d1",
"extension": "c",
"filename": "object.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 212978567,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 585,
"license": "MIT",
"license_type": "permissive",
"path": "/ex_06/object.c",
"provenance": "stackv2-0106.json.gz:40383",
"repo_name": "quan-dang/Artificial-Intelligence-Undergraduate-UoA",
"revision_date": "2019-10-05T10:08:29",
"revision_id": "b99416b5312bfd4c1f9b1f649c7122a6dfbeb173",
"snapshot_id": "7444aa83c5e5aeae8ca11a4e1ed9d5cae8e409f7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/quan-dang/Artificial-Intelligence-Undergraduate-UoA/b99416b5312bfd4c1f9b1f649c7122a6dfbeb173/ex_06/object.c",
"visit_date": "2020-08-06T12:41:51.350627"
}
|
stackv2
|
/**
* @file object.c
* @date 2016/10/21
* @author Yuta Kobiyama (m5191140@u-aizu.ac.jp)
* @brief object object implementation.
* @details
* Artificial Intelligence, 6th Exercise\n
* Copyright (C) 2016 System Intelligence Laboratory All Rights Reserved.
*/
#include <string.h>
#include "object.h"
static char const* get_name(void const*);
Object* construct_object(Object* self, char const* name)
{
strcpy(self->name, name);
self->get_name = get_name;
return self;
}
static char const* get_name(void const* self)
{
return ((Object const*)self)->name;
}
| 2.359375 | 2 |
2024-11-18T22:09:42.705255+00:00
| 2019-11-12T07:04:24 |
9e9bb7adac23218124546ad3151602c2c40eb844
|
{
"blob_id": "9e9bb7adac23218124546ad3151602c2c40eb844",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-12T07:04:24",
"content_id": "f5fa54079f2607fb0189ecb7856144dc1acf1e60",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "6b090dfe77e8d8bf937100e70341cb190213d710",
"extension": "h",
"filename": "esl_avx.h",
"fork_events_count": 0,
"gha_created_at": "2019-11-12T08:16:49",
"gha_event_created_at": "2019-11-12T08:16:54",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 221165219,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6719,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/esl_avx.h",
"provenance": "stackv2-0106.json.gz:41030",
"repo_name": "smsaladi/easel",
"revision_date": "2019-11-12T07:04:24",
"revision_id": "d7679b5a4155bd32017e9b4fe2c8f1f316d15b6b",
"snapshot_id": "58f0a0e89059135db146d896735b615de32d16de",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/smsaladi/easel/d7679b5a4155bd32017e9b4fe2c8f1f316d15b6b/esl_avx.h",
"visit_date": "2020-09-08T14:54:52.494856"
}
|
stackv2
|
/* Vectorized routines for x86 Advanced Vector Extensions (AVX).
*
* This header file, unusually, provides many complete function
* implementations so they can be inlined by the compiler.
*
* Contents:
* 1. Function declarations for esl_avx.c
* 2. Inlined functions: horizontal max, sum
* 3. Inlined functions: left and right shifts
* 4. Inlined functions: any_gt
*/
#ifndef eslAVX_INCLUDED
#define eslAVX_INCLUDED
#include "esl_config.h"
#ifdef eslENABLE_AVX
#include "easel.h"
#include <stdio.h>
#include <x86intrin.h>
/*****************************************************************
* 1. Function declarations for esl_avx.c
*****************************************************************/
extern void esl_avx_dump_256i_hex4(simde__m256i v);
/*****************************************************************
* 2. Inlined functions: horizontal max, sum
*****************************************************************/
/* Function: esl_avx_hmax_epu8()
* Synopsis: Return max of 32 uint8_t elements in epu8 vector.
*
* Note: benchmark on wumpus, 0.8s (200M) => 4.0 ns/call
*/
static inline uint8_t
esl_avx_hmax_epu8(simde__m256i a)
{
a = _mm256_max_epu8(a, _mm256_permute2x128_si256(a, a, 0x01));
a = _mm256_max_epu8(a, _mm256_shuffle_epi32 (a, 0x4e));
a = _mm256_max_epu8(a, _mm256_shuffle_epi32 (a, 0xb1));
a = _mm256_max_epu8(a, _mm256_shufflelo_epi16 (a, 0xb1));
a = _mm256_max_epu8(a, _mm256_srli_si256 (a, 1));
return _mm256_extract_epi8(a, 0); // epi8 is fine here. gets cast properly to uint8_t on return.
}
/* Function: esl_avx_hmax_epi8()
* Synopsis: Return max of the 32 int8_t elements in epi8 vector.
* Incept: SRE, Tue May 23 09:42:02 2017
*
* Note: benchmark on wumpus, ~0.6s (200M) => 3.0 ns/call
*/
static inline int8_t
esl_avx_hmax_epi8(simde__m256i a)
{
a = _mm256_max_epi8(a, _mm256_permute2x128_si256(a, a, 0x01));
a = _mm256_max_epi8(a, _mm256_shuffle_epi32 (a, 0x4e));
a = _mm256_max_epi8(a, _mm256_shuffle_epi32 (a, 0xb1));
a = _mm256_max_epi8(a, _mm256_shufflelo_epi16 (a, 0xb1));
a = _mm256_max_epi8(a, _mm256_srli_si256 (a, 1));
return _mm256_extract_epi8(a, 0);
}
/* Function: esl_avx_hmax_epi16()
* Synopsis: Return max of 16 int16_t elements in epi16 vector.
*
* Note: benchmark on wumpus, 0.6s (200M) => 3.0 ns/call
*/
static inline int16_t
esl_avx_hmax_epi16(simde__m256i a)
{
a = _mm256_max_epi16(a, _mm256_permute2x128_si256(a, a, 0x01));
a = _mm256_max_epi16(a, _mm256_shuffle_epi32 (a, 0x4e));
a = _mm256_max_epi16(a, _mm256_shuffle_epi32 (a, 0xb1));
a = _mm256_max_epi16(a, _mm256_shufflelo_epi16 (a, 0xb1));
return _mm256_extract_epi16(a, 0);
}
/* Function: esl_avx_hsum_ps()
* Synopsis: Takes the horizontal sum of elements in a vector.
*
* Purpose: Add the four float elements in vector <a>; return
* that sum in <*ret_sum>.
*/
static inline void
esl_avx_hsum_ps(simde__m256 a, float *ret_sum)
{
simde__m256 temp1_AVX = (simde__m256) _mm256_permute2x128_si256((simde__m256i) a, (simde__m256i) a, 0x01);
// Swap the 128-bit halves from a into temp1
simde__m256 temp2_AVX = _mm256_add_ps(a, temp1_AVX);
// low 128 bits of temp2_AVX have the sum of the corresponding floats from the high, low
// 128 bits of a
temp1_AVX = (simde__m256) _mm256_shuffle_epi32((simde__m256i) temp2_AVX, 0x4e); // Swap the 64-bit halves of each 128-bit half of a
temp2_AVX = _mm256_add_ps(temp1_AVX, temp2_AVX); // low 64 bits of temp2_AVX now have the sums of the
// corresponding floats from the quarters of a
temp1_AVX = (simde__m256) _mm256_shuffle_epi32((simde__m256i) temp2_AVX, 0xb1); // Swap the 32-bit halves of each 64-bit quarter of temp2_AVX
temp2_AVX = _mm256_add_ps(temp1_AVX, temp2_AVX); // low 32 bits of temp2_AVX now have the sum of the floats in a
int *retint_ptr = (int *) ret_sum; // This is a horrible hack because there isn't an intrinsic to extract a float from
// an simde__m256. Do this to avoid casting an int back to a float and screwing it up
*retint_ptr = _mm256_extract_epi32((simde__m256i) temp2_AVX, 0);
}
/******************************************************************
* 3. Inlined functions: left and right shift
******************************************************************/
/* Function: esl_avx_rightshift_int8()
* Synopsis: Shift int8 vector elements to the right, shifting a -inf on.
* Incept: SRE, Sun Jun 4 17:12:07 2017
* See: esl_sse.h::esl_sse_rightshift_int8()
*/
static inline simde__m256i
esl_avx_rightshift_int8(simde__m256i v, simde__m256i neginfmask)
{
return _mm256_or_si256(_mm256_alignr_epi8(v, _mm256_permute2x128_si256(v, v, SIMDE_MM_SHUFFLE(0,0,3,0)), 15), neginfmask);
}
/* Function: esl_avx_rightshift_int16()
* Synopsis: Shift int16 vector elements to the right, shifting a -inf on.
* Incept: SRE, Sun Jun 4 17:13:58 2017
* See: esl_sse.h::esl_sse_rightshift_int16()
*/
static inline simde__m256i
esl_avx_rightshift_int16(simde__m256i v, simde__m256i neginfmask)
{
return _mm256_or_si256(_mm256_alignr_epi8(v, _mm256_permute2x128_si256(v, v, SIMDE_MM_SHUFFLE(0,0,3,0)), 14), neginfmask);
}
/* Function: esl_avx_rightshiftz_float()
* Synopsis: Shift float vector elements to the right, shifting zero on.
* Incept: SRE, Sun Jun 4 17:16:42 2017
* See: esl_sse.h::esl_sse_rightshiftz_float()
*/
static inline simde__m256
esl_avx_rightshiftz_float(simde__m256 v)
{
return ((simde__m256) _mm256_alignr_epi8((simde__m256i) v, _mm256_permute2x128_si256((simde__m256i) v, (simde__m256i) v, SIMDE_MM_SHUFFLE(0,0,3,0) ), 12));
}
/* Function: esl_avx_leftshiftz_float()
* Synopsis: Shift float vector elements to the left, shifting zero on.
* Incept: SRE, Sun Jun 4 17:27:52 2017
* See: esl_sse.h::esl_sse_leftshiftz_float()
*/
static inline simde__m256
esl_avx_leftshiftz_float(simde__m256 v)
{
//permute result has vector[255:128] in low 128 bits, 0 in high 128
return ((simde__m256) _mm256_alignr_epi8(_mm256_permute2x128_si256((simde__m256i) v, (simde__m256i) v, 0x81), (simde__m256i) v, 4));
}
/******************************************************************
* 4. Inlined functions: any_gt
******************************************************************/
/* Function: esl_avx_any_gt_epi16()
* Synopsis: Return >0 if any a[z] > b[z]
*/
static inline int
esl_avx_any_gt_epi16(simde__m256i a, simde__m256i b)
{
return (_mm256_movemask_epi8(_mm256_cmpgt_epi16(a,b)) != 0);
}
#endif /*eslAVX_INCLUDED*/
#endif // eslENABLE_AVX
| 2.46875 | 2 |
2024-11-18T22:09:43.173522+00:00
| 2021-03-26T09:36:25 |
737e2d8a2b58743d97435b9a31a79001bd31eb9e
|
{
"blob_id": "737e2d8a2b58743d97435b9a31a79001bd31eb9e",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-26T09:36:25",
"content_id": "5aa179bfd4b17255749f58c0ecb8b2976b91d596",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f915829dbcfc78d9af152a778366dd6ecf451ebb",
"extension": "c",
"filename": "util.c",
"fork_events_count": 1,
"gha_created_at": "2018-04-25T12:19:24",
"gha_event_created_at": "2021-02-03T07:06:33",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 131001861,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2505,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/util.c",
"provenance": "stackv2-0106.json.gz:41419",
"repo_name": "roboticeyes/openrex",
"revision_date": "2021-03-26T09:36:25",
"revision_id": "8649399050d545ba5f241628d45f7780827c7de9",
"snapshot_id": "b4bb75900360c71624cb6e6e539a212b6ca01c80",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/roboticeyes/openrex/8649399050d545ba5f241628d45f7780827c7de9/src/util.c",
"visit_date": "2021-06-02T00:59:28.748410"
}
|
stackv2
|
/*
* Copyright 2018 Robotic Eyes GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.*
*/
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#if defined(WIN32) || defined(WIN64) || defined(_WINDOWS)
// Copied from linux libc sys/stat.h:
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#endif
#include "util.h"
static void verr (const char *fmt, va_list ap)
{
vfprintf (stderr, fmt, ap);
if (fmt[0] && fmt[strlen (fmt) - 1] == ':')
{
fputc (' ', stderr);
perror (NULL);
}
else
fputc ('\n', stderr);
}
void warn (const char *fmt, ...)
{
va_list ap;
va_start (ap, fmt);
verr (fmt, ap);
va_end (ap);
}
void die (const char *fmt, ...)
{
va_list ap;
va_start (ap, fmt);
verr (fmt, ap);
va_end (ap);
exit (1);
}
int dir_exists (const char *folder)
{
struct stat sb;
if (stat (folder, &sb) == 0 && S_ISDIR (sb.st_mode))
return 1;
return 0;
}
char *read_file_ascii (const char *filename)
{
FILE *f = fopen (filename, "rt");
if (f == NULL) return NULL;
fseek (f, 0, SEEK_END);
long length = ftell (f);
fseek (f, 0, SEEK_SET);
char *buffer = (char *) malloc (length + 1);
buffer[length] = '\0';
fread (buffer, 1, length, f);
fclose (f);
return buffer;
}
uint8_t *read_file_binary (const char *filename, long *sz)
{
FILE *f = fopen (filename, "rb");
if (f == NULL) return NULL;
fseek (f, 0, SEEK_END);
*sz = ftell (f);
fseek (f, 0, SEEK_SET);
uint8_t *buffer = (uint8_t *) malloc (*sz);
size_t ret = fread (buffer, 1, *sz, f);
if (ret != *sz)
{
FREE (buffer);
fclose (f);
return NULL;
}
fclose (f);
return buffer;
}
inline char separator()
{
#ifdef WIN32
return '\\';
#else
return '/';
#endif
}
| 2.453125 | 2 |
2024-11-18T22:09:43.271050+00:00
| 2023-08-09T18:19:32 |
7e689cba2dcc3e2ad6489c5a4369873ca44b2d5a
|
{
"blob_id": "7e689cba2dcc3e2ad6489c5a4369873ca44b2d5a",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-09T18:19:32",
"content_id": "06710eddd670fa7177667ae1ed3a234d3668509c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a4a96286d9860e2661cd7c7f571d42bfa04c86cf",
"extension": "h",
"filename": "uart_periph.h",
"fork_events_count": 1,
"gha_created_at": "2020-01-23T18:05:37",
"gha_event_created_at": "2020-01-23T18:05:38",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 235855012,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1553,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/components/soc/include/soc/uart_periph.h",
"provenance": "stackv2-0106.json.gz:41547",
"repo_name": "KollarRichard/esp-idf",
"revision_date": "2023-08-09T18:19:32",
"revision_id": "3befd5fff72aa6980514454a50233037718b611f",
"snapshot_id": "1a3c314b37c763bdd231d974c9e16b9c7588e42c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/KollarRichard/esp-idf/3befd5fff72aa6980514454a50233037718b611f/components/soc/include/soc/uart_periph.h",
"visit_date": "2023-08-16T20:32:50.823995"
}
|
stackv2
|
/*
* SPDX-FileCopyrightText: 2019-2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "soc/soc_caps.h"
#include "soc/periph_defs.h"
#include "soc/gpio_sig_map.h"
#include "soc/io_mux_reg.h"
#include "soc/uart_pins.h"
#ifdef __cplusplus
extern "C" {
#endif
#define SOC_UART_TX_PIN_IDX (0)
#define SOC_UART_RX_PIN_IDX (1)
#define SOC_UART_RTS_PIN_IDX (2)
#define SOC_UART_CTS_PIN_IDX (3)
/**
* @brief Macro that can be used to retrieve the signal of a certain pin for a
* certain UART.
*/
#define UART_PERIPH_SIGNAL(IDX, PIN) (uart_periph_signal[(IDX)].pins[(PIN)].signal)
typedef struct {
/* Default GPIO number for this UART pin in the IOMUX.
* This value can be -1 if there is no default GPIO for a pin.
* For example, ESP32-C3 doesn't have any default GPIO for
* U0CTS and U0RTS. */
int32_t default_gpio : 15;
/* Func which should be assigned to the GPIO to be used as UART */
int32_t iomux_func : 4;
/* Marks if the current UART pin is input (or not) */
uint32_t input : 1;
/* Signal in the GPIO signal map. */
uint32_t signal : 12;
} uart_periph_sig_t;
typedef struct {
const uart_periph_sig_t pins[SOC_UART_PINS_COUNT];
const uint8_t irq;
union {
const periph_module_t module;
#if (SOC_UART_LP_NUM >= 1)
const lp_periph_module_t lp_module;
#endif
};
} uart_signal_conn_t;
extern const uart_signal_conn_t uart_periph_signal[SOC_UART_NUM];
#ifdef __cplusplus
}
#endif
| 2.28125 | 2 |
2024-11-18T22:09:43.898643+00:00
| 2023-09-01T16:10:59 |
d5de17e805ca76849d1d12c51ae2d444511674bc
|
{
"blob_id": "d5de17e805ca76849d1d12c51ae2d444511674bc",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-01T16:10:59",
"content_id": "006ca3126e69005465360e625b2372c00945ae2c",
"detected_licenses": [
"ISC",
"MIT"
],
"directory_id": "54c67306d63bb69a5cf381d12108d3dc98ae0f5d",
"extension": "h",
"filename": "Format.h",
"fork_events_count": 131,
"gha_created_at": "2020-08-22T23:55:21",
"gha_event_created_at": "2023-09-14T13:27:47",
"gha_language": "Common Lisp",
"gha_license_id": "ISC",
"github_id": 289585720,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12115,
"license": "ISC,MIT",
"license_type": "permissive",
"path": "/third-party/zydis/dependencies/zycore/include/Zycore/Format.h",
"provenance": "stackv2-0106.json.gz:41675",
"repo_name": "open-goal/jak-project",
"revision_date": "2023-09-01T16:10:59",
"revision_id": "d96dce27149fbf58586160cfecb634614f055943",
"snapshot_id": "adf30a3459c24afda5b180e3abe1583c93458a37",
"src_encoding": "UTF-8",
"star_events_count": 1826,
"url": "https://raw.githubusercontent.com/open-goal/jak-project/d96dce27149fbf58586160cfecb634614f055943/third-party/zydis/dependencies/zycore/include/Zycore/Format.h",
"visit_date": "2023-09-01T21:51:16.736237"
}
|
stackv2
|
/***************************************************************************************************
Zyan Core Library (Zycore-C)
Original Author : Florian Bernd
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
***************************************************************************************************/
/**
* @file
* Provides helper functions for performant number to string conversion.
*/
#ifndef ZYCORE_FORMAT_H
#define ZYCORE_FORMAT_H
#include <Zycore/Status.h>
#include <Zycore/String.h>
#include <Zycore/Types.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ============================================================================================== */
/* Exported functions */
/* ============================================================================================== */
/* ---------------------------------------------------------------------------------------------- */
/* Helpers */
/* ---------------------------------------------------------------------------------------------- */
/**
* Get the absolute value of a 64 bit int.
*
* @param x The value to process.
* @return The absolute, unsigned value.
*
* This gracefully deals with the special case of `x` being `INT_MAX`.
*/
ZYAN_INLINE ZyanU64 ZyanAbsI64(ZyanI64 x)
{
// INT_MIN special case. Can't use the value directly because GCC thinks
// it's too big for an INT64 literal, however is perfectly happy to accept
// this expression. This is also hit INT64_MIN is defined in `stdint.h`.
if (x == (-0x7fffffffffffffff - 1))
{
return 0x8000000000000000u;
}
return (ZyanU64)(x < 0 ? -x : x);
}
/* ---------------------------------------------------------------------------------------------- */
/* Insertion */
/* ---------------------------------------------------------------------------------------------- */
/**
* Inserts formatted text in the destination string at the given `index`.
*
* @param string The destination string.
* @param index The insert index.
* @param format The format string.
* @param ... The format arguments.
*
* @return A zyan status code.
*
* This function will fail, if the `ZYAN_STRING_IS_IMMUTABLE` flag is set for the specified
* `ZyanString` instance.
*/
ZYAN_PRINTF_ATTR(3, 4)
ZYCORE_EXPORT ZyanStatus ZyanStringInsertFormat(ZyanString* string, ZyanUSize index,
const char* format, ...);
/* ---------------------------------------------------------------------------------------------- */
/**
* Formats the given unsigned ordinal `value` to its decimal text-representation and
* inserts it to the `string`.
*
* @param string A pointer to the `ZyanString` instance.
* @param index The insert index.
* @param value The value.
* @param padding_length Padds the converted value with leading zeros, if the number of chars is
* less than the `padding_length`.
*
* @return A zyan status code.
*
* This function will fail, if the `ZYAN_STRING_IS_IMMUTABLE` flag is set for the specified
* `ZyanString` instance.
*/
ZYCORE_EXPORT ZyanStatus ZyanStringInsertDecU(ZyanString* string, ZyanUSize index, ZyanU64 value,
ZyanU8 padding_length);
/**
* Formats the given signed ordinal `value` to its decimal text-representation and
* inserts it to the `string`.
*
* @param string A pointer to the `ZyanString` instance.
* @param index The insert index.
* @param value The value.
* @param padding_length Padds the converted value with leading zeros, if the number of chars is
* less than the `padding_length`.
* @param force_sign Set `ZYAN_TRUE`, to force printing of the `+` sign for positive numbers.
* @param prefix The string to use as prefix or `ZYAN_NULL`, if not needed.
*
* @return A zyan status code.
*
* This function will fail, if the `ZYAN_STRING_IS_IMMUTABLE` flag is set for the specified
* `ZyanString` instance.
*/
ZYCORE_EXPORT ZyanStatus ZyanStringInsertDecS(ZyanString* string, ZyanUSize index, ZyanI64 value,
ZyanU8 padding_length, ZyanBool force_sign, const ZyanString* prefix);
/**
* Formats the given unsigned ordinal `value` to its hexadecimal text-representation and
* inserts it to the `string`.
*
* @param string A pointer to the `ZyanString` instance.
* @param index The insert index.
* @param value The value.
* @param padding_length Padds the converted value with leading zeros, if the number of chars is
* less than the `padding_length`.
* @param uppercase Set `ZYAN_TRUE` to use uppercase letters ('A'-'F') instead of lowercase
* ones ('a'-'f').
*
* @return A zyan status code.
*
* This function will fail, if the `ZYAN_STRING_IS_IMMUTABLE` flag is set for the specified
* `ZyanString` instance.
*/
ZYCORE_EXPORT ZyanStatus ZyanStringInsertHexU(ZyanString* string, ZyanUSize index, ZyanU64 value,
ZyanU8 padding_length, ZyanBool uppercase);
/**
* Formats the given signed ordinal `value` to its hexadecimal text-representation and
* inserts it to the `string`.
*
* @param string A pointer to the `ZyanString` instance.
* @param index The insert index.
* @param value The value.
* @param padding_length Padds the converted value with leading zeros, if the number of chars is
* less than the `padding_length`.
* @param uppercase Set `ZYAN_TRUE` to use uppercase letters ('A'-'F') instead of lowercase
* ones ('a'-'f').
* @param force_sign Set `ZYAN_TRUE`, to force printing of the `+` sign for positive numbers.
* @param prefix The string to use as prefix or `ZYAN_NULL`, if not needed.
*
* @return A zyan status code.
*
* This function will fail, if the `ZYAN_STRING_IS_IMMUTABLE` flag is set for the specified
* `ZyanString` instance.
*/
ZYCORE_EXPORT ZyanStatus ZyanStringInsertHexS(ZyanString* string, ZyanUSize index, ZyanI64 value,
ZyanU8 padding_length, ZyanBool uppercase, ZyanBool force_sign, const ZyanString* prefix);
/* ---------------------------------------------------------------------------------------------- */
/* Appending */
/* ---------------------------------------------------------------------------------------------- */
#ifndef ZYAN_NO_LIBC
/**
* Appends formatted text to the destination string.
*
* @param string The destination string.
* @param format The format string.
* @param ... The format arguments.
*
* @return A zyan status code.
*
* This function will fail, if the `ZYAN_STRING_IS_IMMUTABLE` flag is set for the specified
* `ZyanString` instance.
*/
ZYAN_PRINTF_ATTR(2, 3)
ZYCORE_EXPORT ZYAN_REQUIRES_LIBC ZyanStatus ZyanStringAppendFormat(
ZyanString* string, const char* format, ...);
#endif // ZYAN_NO_LIBC
/* ---------------------------------------------------------------------------------------------- */
/**
* Formats the given unsigned ordinal `value` to its decimal text-representation and
* appends it to the `string`.
*
* @param string A pointer to the `ZyanString` instance.
* @param value The value.
* @param padding_length Padds the converted value with leading zeros, if the number of chars is
* less than the `padding_length`.
*
* @return A zyan status code.
*
* This function will fail, if the `ZYAN_STRING_IS_IMMUTABLE` flag is set for the specified
* `ZyanString` instance.
*/
ZYCORE_EXPORT ZyanStatus ZyanStringAppendDecU(ZyanString* string, ZyanU64 value,
ZyanU8 padding_length);
/**
* Formats the given signed ordinal `value` to its decimal text-representation and
* appends it to the `string`.
*
* @param string A pointer to the `ZyanString` instance.
* @param value The value.
* @param padding_length Padds the converted value with leading zeros, if the number of chars is
* less than the `padding_length`.
* @param force_sign Set `ZYAN_TRUE`, to force printing of the `+` sign for positive numbers.
* @param prefix The string to use as prefix or `ZYAN_NULL`, if not needed.
*
* @return A zyan status code.
*
* This function will fail, if the `ZYAN_STRING_IS_IMMUTABLE` flag is set for the specified
* `ZyanString` instance.
*/
ZYCORE_EXPORT ZyanStatus ZyanStringAppendDecS(ZyanString* string, ZyanI64 value,
ZyanU8 padding_length, ZyanBool force_sign, const ZyanStringView* prefix);
/**
* Formats the given unsigned ordinal `value` to its hexadecimal text-representation and
* appends it to the `string`.
*
* @param string A pointer to the `ZyanString` instance.
* @param value The value.
* @param padding_length Padds the converted value with leading zeros, if the number of chars is
* less than the `padding_length`.
* @param uppercase Set `ZYAN_TRUE` to use uppercase letters ('A'-'F') instead of lowercase
* ones ('a'-'f').
*
* @return A zyan status code.
*
* This function will fail, if the `ZYAN_STRING_IS_IMMUTABLE` flag is set for the specified
* `ZyanString` instance.
*/
ZYCORE_EXPORT ZyanStatus ZyanStringAppendHexU(ZyanString* string, ZyanU64 value,
ZyanU8 padding_length, ZyanBool uppercase);
/**
* Formats the given signed ordinal `value` to its hexadecimal text-representation and
* appends it to the `string`.
*
* @param string A pointer to the `ZyanString` instance.
* @param value The value.
* @param padding_length Padds the converted value with leading zeros, if the number of chars is
* less than the `padding_length`.
* @param uppercase Set `ZYAN_TRUE` to use uppercase letters ('A'-'F') instead of lowercase
* ones ('a'-'f').
* @param force_sign Set `ZYAN_TRUE`, to force printing of the `+` sign for positive numbers.
* @param prefix The string to use as prefix or `ZYAN_NULL`, if not needed.
*
* @return A zyan status code.
*
* This function will fail, if the `ZYAN_STRING_IS_IMMUTABLE` flag is set for the specified
* `ZyanString` instance.
*/
ZYCORE_EXPORT ZyanStatus ZyanStringAppendHexS(ZyanString* string, ZyanI64 value,
ZyanU8 padding_length, ZyanBool uppercase, ZyanBool force_sign, const ZyanStringView* prefix);
/* ---------------------------------------------------------------------------------------------- */
/* ============================================================================================== */
#ifdef __cplusplus
}
#endif
#endif // ZYCORE_FORMAT_H
| 2.34375 | 2 |
2024-11-18T22:09:44.263038+00:00
| 2018-04-08T13:35:44 |
3f71c64a688b8e2a61b7baf0bad90e3f490c9a10
|
{
"blob_id": "3f71c64a688b8e2a61b7baf0bad90e3f490c9a10",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-08T13:35:44",
"content_id": "94f2d679a8f26a12aa3afb11e861c53cfd3c6275",
"detected_licenses": [
"ISC"
],
"directory_id": "e0ecc133b9ca04d91cb01a7a37cab1c844f7f647",
"extension": "c",
"filename": "server.c",
"fork_events_count": 0,
"gha_created_at": "2016-09-22T10:55:18",
"gha_event_created_at": "2018-04-04T13:26:27",
"gha_language": "C",
"gha_license_id": "ISC",
"github_id": 68912487,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6154,
"license": "ISC",
"license_type": "permissive",
"path": "/src/server.c",
"provenance": "stackv2-0106.json.gz:41932",
"repo_name": "enfiskutensykkel/cuda-rdma-bench",
"revision_date": "2018-04-08T13:35:44",
"revision_id": "ace549d68dbca981acbb7d52db5d4032c8ef335f",
"snapshot_id": "f09edc01fbef3692f992d5fcd7d34239586554db",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/enfiskutensykkel/cuda-rdma-bench/ace549d68dbca981acbb7d52db5d4032c8ef335f/src/server.c",
"visit_date": "2020-07-14T20:35:10.810430"
}
|
stackv2
|
#include <stdint.h>
#include <stdlib.h>
#include <sisci_api.h>
#include <pthread.h>
#include <string.h>
#include <signal.h>
#include "reporting.h"
#include "common.h"
#include "util.h"
#include "bench.h"
#include "gpu.h"
#include "ram.h"
#ifdef __GNUC__
#define UNUSED(x) x __attribute__((unused))
#else
#define UNUSED(x) x
#endif
/* Buffer info */
typedef struct {
const gpu_info_t* gpu;
void* ptr;
size_t len;
uint8_t val;
} buf_info_t;
/* Should we keep running? */
static volatile int keep_running = 1;
static pthread_cond_t queue = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void stop_server()
{
log_info("Stopping server...");
pthread_mutex_lock(&lock);
keep_running = 0;
pthread_cond_signal(&queue);
pthread_mutex_unlock(&lock);
}
static sci_callback_action_t validate_buffer(void* buf_info, sci_local_interrupt_t UNUSED(irq), sci_error_t status)
{
if (status == SCI_ERR_OK)
{
buf_info_t* bi = (buf_info_t*) buf_info;
uint8_t byte;
if (bi->ptr == NULL && bi->len == 0)
{
log_error("Interrupt callback called before segment was initialized");
return SCI_CALLBACK_CANCEL;
}
if (bi->gpu != NULL)
{
gpu_memcpy_buffer_to_local(bi->gpu->id, bi->ptr, &byte, 1);
}
else
{
byte = *((uint8_t*) bi->ptr);
}
report_buffer_change(stdout, bi->val, byte);
bi->val = byte;
}
return SCI_CALLBACK_CONTINUE;
}
static void run_server(unsigned adapter, sci_local_segment_t ci_segment, const conn_info_t* ci, buf_info_t* bi)
{
sci_error_t err;
sci_desc_t sd;
// Create SISCI descriptor
SCIOpen(&sd, 0, &err);
if (err != SCI_ERR_OK)
{
log_error("Failed to open SISCI descriptor");
return;
}
// Create transfer segment
sci_local_segment_t segment;
sci_map_t mapping;
void* buffer;
uint8_t byte = random_byte_value();
log_debug("Creating buffer and filling with random value %02x", byte);
if (ci->gpu != NO_GPU)
{
err = make_gpu_segment(sd, adapter, ci->segment_id, &segment, ci->size, &ci->gpu_info, &buffer, ci->global);
gpu_memset(ci->gpu, buffer, ci->size, byte);
}
else
{
err = make_ram_segment(sd, adapter, ci->segment_id, &segment, ci->size, &mapping, &buffer, ci->global);
ram_memset(buffer, ci->size, byte);
}
if (err != SCI_ERR_OK)
{
log_error("Failed to create segment");
goto close_desc;
}
// Set transfer segment available
SCISetSegmentAvailable(segment, adapter, 0, &err);
if (err != SCI_ERR_OK)
{
log_error("Failed to set transfer segment available: %s", SCIGetErrorString(err));
goto free_segment;
}
bi->gpu = ci->gpu != NO_GPU ? &ci->gpu_info : NULL;
bi->ptr = buffer;
bi->len = ci->size;
bi->val = byte;
// Set connection info segment available
SCISetSegmentAvailable(ci_segment, adapter, 0, &err);
if (err != SCI_ERR_OK)
{
log_error("Failed to set buffer info segment available: %s", SCIGetErrorString(err));
goto free_segment;
}
signal(SIGINT, (sig_t) &stop_server);
signal(SIGTERM, (sig_t) &stop_server);
signal(SIGPIPE, (sig_t) &stop_server);
// Run until we're killed
log_info("Running server...");
pthread_mutex_lock(&lock);
while (keep_running)
{
pthread_cond_wait(&queue, &lock);
}
pthread_mutex_unlock(&lock);
log_info("Server stopped");
// Do clean up
SCISetSegmentUnavailable(ci_segment, adapter, 0, &err);
SCISetSegmentUnavailable(segment, adapter, 0, &err);
free_segment:
if (ci->gpu != NO_GPU)
{
free_gpu_segment(segment, ci->gpu, buffer);
}
else
{
free_ram_segment(segment, mapping);
}
close_desc:
SCIClose(sd, 0, &err);
}
void server(unsigned adapter, int gpu, unsigned id, size_t size, int global)
{
sci_error_t err = SCI_ERR_OK;
sci_desc_t sd;
SCIOpen(&sd, 0, &err);
if (err != SCI_ERR_OK)
{
log_error("Failed to initialize SISCI descriptor: %s", SCIGetErrorString(err));
return;
}
unsigned local_node = 0;
SCIGetLocalNodeId(adapter, &local_node, 0, &err);
if (err != SCI_ERR_OK)
{
SCIClose(sd, 0, &err);
return;
}
// Create connection info segment
sci_local_segment_t gi_segment;
sci_map_t gi_mapping;
conn_info_t* conn_info;
err = make_ram_segment(sd, adapter, id & ID_MASK, &gi_segment, sizeof(conn_info_t), &gi_mapping, (void**) &conn_info, 0);
if (err != SCI_ERR_OK)
{
log_error("Failed to create buffer info segment");
SCIClose(sd, 0, &err);
return;
}
conn_info->intr_no = 0;
conn_info->global = global;
conn_info->size = size;
conn_info->node_id = local_node;
conn_info->segment_id = ((unsigned long long) id) << ID_MASK_BITS;
conn_info->gpu = gpu;
memset(&conn_info->gpu_info, 0xff, sizeof(gpu_info_t));
conn_info->gpu_info.id = NO_GPU;
// Get local GPU information
if (gpu != NO_GPU && gpu_info(gpu, &conn_info->gpu_info) != 1)
{
log_error("Failed to get GPU info, aborting...");
goto leave;
}
// Create interrupt to trigger validation of the buffer
sci_local_interrupt_t validate_irq;
buf_info_t buf_info = { .gpu = NULL, .ptr = NULL, .len = 0, .val = 0 };
SCICreateInterrupt(sd, &validate_irq, adapter, &conn_info->intr_no, &validate_buffer, &buf_info, SCI_FLAG_USE_CALLBACK, &err);
if (err != SCI_ERR_OK)
{
log_error("Failed to create interrupt: %s", SCIGetErrorString(err));
goto leave;
}
log_debug("Validation IRQ %u", conn_info->intr_no);
// Run server
run_server(adapter, gi_segment, conn_info, &buf_info);
do
{
SCIRemoveInterrupt(validate_irq, 0, &err);
}
while (err == SCI_ERR_BUSY);
leave:
free_ram_segment(gi_segment, gi_mapping);
SCIClose(sd, 0, &err);
}
| 2.390625 | 2 |
2024-11-18T22:09:51.607013+00:00
| 2019-01-15T17:31:45 |
96111348d4d9a9bd5da2f8a067bf13e569e88696
|
{
"blob_id": "96111348d4d9a9bd5da2f8a067bf13e569e88696",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-15T17:31:45",
"content_id": "f6d18be23fc637de1f8a888682fdfe403f4f49f6",
"detected_licenses": [
"MIT"
],
"directory_id": "ebd75ce3a518d9901684c71d48400567dbdedccf",
"extension": "c",
"filename": "opengl_impl.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 165424018,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4466,
"license": "MIT",
"license_type": "permissive",
"path": "/src/opengl_impl.c",
"provenance": "stackv2-0106.json.gz:42189",
"repo_name": "Givup/cpong",
"revision_date": "2019-01-15T17:31:45",
"revision_id": "5233c4be456fe23a3659bc40135ef971e43f91a2",
"snapshot_id": "53f43c4e7abfbea6fb643f2d7727fc0e6c13d352",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Givup/cpong/5233c4be456fe23a3659bc40135ef971e43f91a2/src/opengl_impl.c",
"visit_date": "2020-04-16T08:24:32.839161"
}
|
stackv2
|
#include <assert.h>
#include "opengl_impl.h"
// Macro define
#define LOAD_FUNC(f, n) (f = get_gl_func_address(context, n)); assert("Failed to bind OpenGL function call" && f)
/*
Function pointers
*/
// General
GLenum(__cdecl *f_glGetError)();
GLubyte*(__cdecl *f_glGetString)(GLenum);
void(__cdecl *f_glClear)(GLbitfield);
void(__cdecl *f_glEnable)(GLenum);
void(__cdecl *f_glDisable)(GLenum);
// Buffer
void(__cdecl *f_glGenBuffers)(GLsizei, GLuint*);
void(__cdecl *f_glBindBuffer)(GLenum, GLuint);
void(__cdecl *f_glBufferData)(GLenum, GLsizeiptr, const GLvoid*, GLenum);
void(__cdecl *f_glDeleteBuffers)(GLsizei, const GLuint*);
// Vertex
void(__cdecl *f_glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid*);
void(__cdecl *f_glEnableVertexAttribArray)(GLuint);
void(__cdecl *f_glDisableVertexAttribArray)(GLuint);
void(__cdecl *f_glGenVertexArrays)(GLsizei, GLuint*);
void(__cdecl *f_glBindVertexArray)(GLuint);
void(__cdecl *f_glDeleteVertexArrays)(GLsizei, GLuint*);
// Shader
void(__cdecl *f_glGetShaderiv)(GLuint, GLenum, GLint*);
void(__cdecl *f_glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GLuint(__cdecl *f_glCreateProgram)();
GLuint(__cdecl *f_glCreateShader)(GLenum);
void(__cdecl *f_glShaderSource)(GLuint shader, GLsizei count, const GLchar** string, const GLint* length);
void(__cdecl *f_glCompileShader)(GLuint shader);
void(__cdecl *f_glAttachShader)(GLuint program, GLuint shader);
void(__cdecl *f_glLinkProgram)(GLuint program);
void(__cdecl *f_glUseProgram)(GLuint program);
void(__cdecl *f_glDeleteShader)(GLuint shader);
// Drawcall
void(__cdecl *f_glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat);
void(__cdecl *f_glViewport)(GLint, GLint, GLsizei, GLsizei);
void(__cdecl *f_glDrawArrays)(GLenum, GLint, GLsizei);
void(__cdecl *f_glDrawElements)(GLenum, GLsizei, GLenum, const GLvoid*);
// Uniform
GLint(__cdecl *f_glGetUniformLocation)(GLuint, const GLchar*);
void(__cdecl *f_glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*);
void(__cdecl *f_glUniform4fv)(GLint, GLsizei, const GLfloat*);
// Load opengl function dynamically from opengl32.dll
void* get_gl_func_address(OpenGLFunctions* context, const char* func_name) {
void* p = (void*)wglGetProcAddress(func_name);
if(p == 0 || p == (void*)1 || p == (void*)2 ||p == (void*)3 || p == (void*)-1) {
p = (void*)GetProcAddress(context->gl_library, func_name);
}
return p;
};
// Load library and load all required function pointers
void initialize_opengl_functions(OpenGLFunctions* context) {
HMODULE library = LoadLibrary("opengl32.dll");
context->gl_library = library;
// General
LOAD_FUNC(f_glGetError, "glGetError");
LOAD_FUNC(f_glGetString, "glGetString");
LOAD_FUNC(f_glClear, "glClear");
LOAD_FUNC(f_glEnable, "glEnable");
LOAD_FUNC(f_glDisable, "glDisable");
// Buffer
LOAD_FUNC(f_glGenBuffers, "glGenBuffers");
LOAD_FUNC(f_glBindBuffer, "glBindBuffer");
LOAD_FUNC(f_glBufferData, "glBufferData");
LOAD_FUNC(f_glDeleteBuffers, "glDeleteBuffers");
// Vertex
LOAD_FUNC(f_glVertexAttribPointer, "glVertexAttribPointer");
LOAD_FUNC(f_glEnableVertexAttribArray, "glEnableVertexAttribArray");
LOAD_FUNC(f_glDisableVertexAttribArray, "glDisableVertexAttribArray");
LOAD_FUNC(f_glGenVertexArrays, "glGenVertexArrays");
LOAD_FUNC(f_glBindVertexArray, "glBindVertexArray");
LOAD_FUNC(f_glDeleteVertexArrays, "glDeleteVertexArrays");
// Shader
LOAD_FUNC(f_glGetShaderiv, "glGetShaderiv");
LOAD_FUNC(f_glGetShaderInfoLog, "glGetShaderInfoLog");
LOAD_FUNC(f_glCreateProgram, "glCreateProgram");
LOAD_FUNC(f_glCreateShader, "glCreateShader");
LOAD_FUNC(f_glShaderSource, "glShaderSource");
LOAD_FUNC(f_glCompileShader, "glCompileShader");
LOAD_FUNC(f_glAttachShader, "glAttachShader");
LOAD_FUNC(f_glLinkProgram, "glLinkProgram");
LOAD_FUNC(f_glUseProgram, "glUseProgram");
LOAD_FUNC(f_glDeleteShader, "glDeleteShader");
// Drawcall
LOAD_FUNC(f_glClearColor, "glClearColor");
LOAD_FUNC(f_glViewport, "glViewport");
LOAD_FUNC(f_glDrawArrays, "glDrawArrays");
LOAD_FUNC(f_glDrawElements, "glDrawElements");
// Uniform
LOAD_FUNC(f_glGetUniformLocation, "glGetUniformLocation");
LOAD_FUNC(f_glUniformMatrix4fv, "glUniformMatrix4fv");
LOAD_FUNC(f_glUniform4fv, "glUniform4fv");
};
// Free loaded library
void free_opengl_functions(OpenGLFunctions* context) {
if(context->gl_library != NULL) {
FreeLibrary(context->gl_library);
}
};
| 2.203125 | 2 |
2024-11-18T22:09:52.263954+00:00
| 2021-09-07T04:43:27 |
fdb65d14c6478eb53b81c36db9500d9ec089a29c
|
{
"blob_id": "fdb65d14c6478eb53b81c36db9500d9ec089a29c",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-07T04:43:27",
"content_id": "4c56fa49ae97c86a2895cea2128d7eecded1e1a9",
"detected_licenses": [
"MIT"
],
"directory_id": "6b6469992339e6635f9f33ae8336fb24f861765f",
"extension": "c",
"filename": "load.c",
"fork_events_count": 0,
"gha_created_at": "2016-11-29T07:37:07",
"gha_event_created_at": "2017-06-10T12:07:19",
"gha_language": "C",
"gha_license_id": null,
"github_id": 75055602,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2214,
"license": "MIT",
"license_type": "permissive",
"path": "/load.c",
"provenance": "stackv2-0106.json.gz:42576",
"repo_name": "SaitoLab/plain_loader",
"revision_date": "2021-09-07T04:43:27",
"revision_id": "c6ed4cc216e0ec12b53483e53fa02b28d6584caf",
"snapshot_id": "299192fbf9fee9de387a5097f7b1739603dbe0b7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/SaitoLab/plain_loader/c6ed4cc216e0ec12b53483e53fa02b28d6584caf/load.c",
"visit_date": "2021-09-08T18:18:59.910564"
}
|
stackv2
|
/*
Copyright (c) 2016 Meiji University Information Security Laboratory (SaitoLab)
Released under the MIT license
http://opensource.org/licenses/mit-license.php
We developed this software by making some changes and additions to Shinichiro Hamaji's one, which is also released under the MIT license.
The original copyright and license are shown below:
Copyright (c) 2015 Shinichiro Hamaji
Released under the MIT license
http://opensource.org/licenses/mit-license.php
Here is Shinichiro Hamaji's license page:
https://github.com/shinh/tel_ldr/blob/master/LICENSE
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <elf.h>
#include <sys/mman.h>
#include "values.h"
#include "el.h"
#include "print.h"
void load(Elf32_Phdr *phdr, int fd){
Elf32_Phdr *tmp = malloc(sizeof(Elf32_Phdr));
unsigned int pafsize;
if (so_flag == 1) {
phdr->p_vaddr += so_base;
}
int prot= 0;
if (phdr->p_flags & PF_X)
prot |= PROT_EXEC;
if (phdr->p_flags & PF_W)
prot |= PROT_WRITE;
if (phdr->p_flags & PF_R)
prot |= PROT_READ;
tmp->p_memsz = phdr->p_memsz + ( phdr->p_vaddr & 0xfff );
tmp->p_filesz = phdr->p_filesz + ( phdr->p_vaddr & 0xfff );
tmp->p_offset = phdr->p_offset - (phdr->p_vaddr & 0xfff);
tmp->p_vaddr = phdr->p_vaddr & ~0xfff;
pafsize = (tmp->p_filesz + 0xfff ) & ~0xfff;
tmp->p_memsz = ( tmp->p_memsz + 0xfff ) & ~0xfff;
el_print("PT_LOAD memsz=%d filesz=%d flags=%d vaddr=%x prot=%d offset=%d\n",
tmp->p_memsz, tmp->p_filesz, phdr->p_flags, tmp->p_vaddr, prot, tmp->p_offset);
if (mmap((void*)tmp->p_vaddr, pafsize, prot, MAP_FILE|MAP_PRIVATE|MAP_FIXED,
fd, tmp->p_offset) == MAP_FAILED) {
el_error("mmap(file)");
}
if ((prot & PROT_WRITE)) {
el_print("%p\n", (char*)tmp->p_vaddr);
for (; tmp->p_filesz < pafsize; tmp->p_filesz++) {
char* p= (char*)tmp->p_vaddr;
p[tmp->p_filesz]= 0;
}
if (tmp->p_filesz != tmp->p_memsz) {
if (mmap((void*)(tmp->p_vaddr + tmp->p_filesz),
tmp->p_memsz - tmp->p_filesz, prot, MAP_ANON|MAP_PRIVATE,
-1, 0) == MAP_FAILED) {
el_error("mmap(anon)");
}
}
}
}
| 2.5 | 2 |
2024-11-18T22:09:52.494581+00:00
| 2022-11-29T16:16:49 |
a889ef197714f4fdc29d5e925cf4bd6a2ac84e46
|
{
"blob_id": "a889ef197714f4fdc29d5e925cf4bd6a2ac84e46",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-29T16:16:49",
"content_id": "1f34b16a812143a1982ba4b6b443e1e1821ebe9f",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "39af51abe4b3ab04018d1e01b7dccdb868f0e76f",
"extension": "c",
"filename": "maincode.c",
"fork_events_count": 10,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 40411791,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3423,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/UPC Microcontroladores 2021-0/Semana 05/20210_relojupc.X/maincode.c",
"provenance": "stackv2-0106.json.gz:42834",
"repo_name": "tocache/Microchip-PIC18F4550",
"revision_date": "2022-11-29T16:16:49",
"revision_id": "3573d38e1447d47b6d6a6934bbb80015bf014323",
"snapshot_id": "403feb6228423d86a9ed091ba67411628ac6e223",
"src_encoding": "WINDOWS-1250",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/tocache/Microchip-PIC18F4550/3573d38e1447d47b6d6a6934bbb80015bf014323/UPC Microcontroladores 2021-0/Semana 05/20210_relojupc.X/maincode.c",
"visit_date": "2022-12-08T15:05:14.857696"
}
|
stackv2
|
// PIC18F4550 Configuration Bit Settings
#pragma config PLLDIV = 1 // PLL Prescaler Selection bits (No prescale (4 MHz oscillator input drives PLL directly))
#pragma config CPUDIV = OSC4_PLL6// System Clock Postscaler Selection bits ([Primary Oscillator Src: /4][96 MHz PLL Src: /6])
#pragma config FOSC = XTPLL_XT // Oscillator Selection bits (XT oscillator, PLL enabled (XTPLL))
#pragma config PWRT = ON // Power-up Timer Enable bit (PWRT enabled)
#pragma config BOR = OFF // Brown-out Reset Enable bits (Brown-out Reset disabled in hardware and software)
#pragma config BORV = 3 // Brown-out Reset Voltage bits (Minimum setting 2.05V)
#pragma config WDT = OFF // Watchdog Timer Enable bit (WDT disabled (control is placed on the SWDTEN bit))
#pragma config WDTPS = 32768 // Watchdog Timer Postscale Select bits (1:32768)
#pragma config CCP2MX = ON // CCP2 MUX bit (CCP2 input/output is multiplexed with RC1)
#pragma config PBADEN = OFF // PORTB A/D Enable bit (PORTB<4:0> pins are configured as digital I/O on Reset)
#pragma config LPT1OSC = OFF // Low-Power Timer 1 Oscillator Enable bit (Timer1 configured for higher power operation)
#pragma config MCLRE = ON // MCLR Pin Enable bit (MCLR pin enabled; RE3 input pin disabled)
#pragma config LVP = OFF // Single-Supply ICSP Enable bit (Single-Supply ICSP disabled)
#include <xc.h>
#include "LCD.h"
#define _XTAL_FREQ 16000000UL
//Declaracion de variables globales
unsigned int d_millar = 0;
unsigned int millar = 0;
unsigned int centena = 0;
unsigned int decena = 0;
unsigned int unidad = 0;
unsigned char ticks = 0;
unsigned char segundos = 0;
unsigned char minutos = 35;
unsigned char horas = 12;
void lcd_init(void){
TRISD = 0x00;
LCD_CONFIG();
__delay_ms(15);
BORRAR_LCD();
CURSOR_HOME();
CURSOR_ONOFF(OFF);
}
void convierte(unsigned int numero){
d_millar = numero / 10000;
millar = (numero %10000) /1000;
centena = (numero % 1000) / 100;
decena = (numero % 100) / 10;
unidad = numero % 10;
}
void configure(void){
lcd_init();
T1CON = 0x31; //Timer1 Fosc/4, PSC 1:8
CCP1CON = 0x0B; //Modo comparador evento especial de disparo
CCPR1H = 0xC3; //El valor de comparación es de 50000 (0xC350)
CCPR1L = 0x50;
PIE1 = 0x04; //CCP1IE habilitado
INTCON = 0xC0; //PEIE y GIE habilitados
}
void main(void) {
configure();
POS_CURSOR(1,0);
ESCRIBE_MENSAJE(" Reloj UPCINO",14);
while(1){
POS_CURSOR(2,3);
convierte(horas);
ENVIA_CHAR(decena+0x30);
ENVIA_CHAR(unidad+0x30);
ENVIA_CHAR(':');
convierte(minutos);
ENVIA_CHAR(decena+0x30);
ENVIA_CHAR(unidad+0x30);
ENVIA_CHAR(':');
convierte(segundos);
ENVIA_CHAR(decena+0x30);
ENVIA_CHAR(unidad+0x30);
}
}
void __interrupt() CCP1_ISR(void){
if(ticks == 9){
ticks = 0;
if(segundos == 59){
segundos = 0;
if(minutos == 59){
minutos = 0;
if(horas == 23){
horas = 0;
}
else{
horas++;
}
}
else{
minutos++;
}
}
else{
segundos++;
}
}
else{
ticks++;
}
PIR1bits.CCP1IF = 0;
}
| 2.328125 | 2 |
2024-11-18T22:09:52.671690+00:00
| 2021-06-09T04:09:51 |
d2a291122ba7e464cc494cee628e3946ee09e526
|
{
"blob_id": "d2a291122ba7e464cc494cee628e3946ee09e526",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-09T04:09:51",
"content_id": "b448fbb2409738ab4ea2777fe13691691bc704f5",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "2e302e1e6e2be731df07171a487912d02df8ada6",
"extension": "c",
"filename": "rm.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": 1703,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/Assignment1/1.2/rm.c",
"provenance": "stackv2-0106.json.gz:42962",
"repo_name": "V15hnu24/OS-Assignments",
"revision_date": "2021-06-09T04:09:51",
"revision_id": "6cf70652c18a4bb80e62064a1efbccb44a5d0733",
"snapshot_id": "55ae7fac21e4a7bdb334693e299815f4e55dec37",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/V15hnu24/OS-Assignments/6cf70652c18a4bb80e62064a1efbccb44a5d0733/Assignment1/1.2/rm.c",
"visit_date": "2023-05-13T09:29:17.195040"
}
|
stackv2
|
/*********************************************************************************
* Name: Pritish Wadhwa *
* Section: B *
* Roll NUmber: 2019440 *
********************************************************************************/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
void rmFile(char fileName[1000])
{
if (unlink(fileName) != 0)
{
perror(fileName);
}
}
void rmFileD(char fileName[1000])
{
if (rmdir(fileName) != 0)
{
perror(fileName);
}
}
void rmFileV(char fileName[1000])
{
if (unlink(fileName) == 0)
{
printf("removed '%s'\n", fileName);
}
else
{
perror(fileName);
}
}
int main(int argc, char *argv[])
{
char commandName[10] = "";
char flag[10] = "";
char *token = strtok(argv[1], " ");
strcpy(commandName, token);
token = strtok(NULL, " ");
if (token[0] == '-')
{
strcpy(flag, token);
token = strtok(NULL, " ");
}
while (token != NULL)
{
char fileName[1000] = "";
strcpy(fileName, token);
if (flag[0] == '\0')
{
rmFile(fileName);
}
else if (flag[1] == 'd')
{
rmFileD(fileName);
}
else if (flag[1] == 'v')
{
rmFileV(fileName);
}
else
{
printf("Invalid Input -- %s\n", flag);
return 1;
}
token = strtok(NULL, " ");
}
return 0;
}
| 2.765625 | 3 |
2024-11-18T22:09:52.826774+00:00
| 2023-07-05T20:55:51 |
e6b552fce252f0bf84b09ff85caad3d2644f0761
|
{
"blob_id": "e6b552fce252f0bf84b09ff85caad3d2644f0761",
"branch_name": "refs/heads/main",
"committer_date": "2023-07-05T20:55:51",
"content_id": "07fb3a6392cb220e0330dc71e5702784ed079c2a",
"detected_licenses": [
"MIT"
],
"directory_id": "11d231d29b7939c4345a3eff6279990a826ce270",
"extension": "h",
"filename": "ps2k.h",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 349760384,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2290,
"license": "MIT",
"license_type": "permissive",
"path": "/xsamples/bsp-test/ps2k.h",
"provenance": "stackv2-0106.json.gz:43221",
"repo_name": "achilikin/N76E003-SDCC-BSP",
"revision_date": "2023-07-05T20:55:51",
"revision_id": "afc99a5896cc84a6e1a90dce1b3a24132cfc1a83",
"snapshot_id": "2729ef77152c83ba664848f31c10f3bd427a8dec",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/achilikin/N76E003-SDCC-BSP/afc99a5896cc84a6e1a90dce1b3a24132cfc1a83/xsamples/bsp-test/ps2k.h",
"visit_date": "2023-07-07T05:35:47.507040"
}
|
stackv2
|
/**
* Example of pin iterrupt processing using PS/2 keyboard as interrupt source
*
* https://wiki.osdev.org/PS/2_Keyboard
*
* Commands reply usually 0xFA (ACK) or 0xFE (Resend)
*
* cmd data description
* xED led Set LEDs: 0x01 Scroll, 0x02 Num, 0x04 Caps lock
* xEE Echo, reply 0xEE (Echo) or 0xFE (Resend)
* xF0 code Get/Set current code set. 0 - get, 1 to 3 - set scan code set 1 to 3
* xF2 Identify keyboard
* xF4 Enable scanning (keyboard will send scan codes)
* xF5 Disable scanning (keyboard won't send scan codes)
* xF6 Set default parameters
* xF7 Set all keys to typematic/autorepeat only (scancode set 3 only)
* xF8 Set all keys to make/release (scancode set 3 only)
* xF9 Set all keys to make only (scancode set 3 only)
* xFA Set all keys to typematic/autorepeat/make/release (scancode set 3 only)
* xFB scode Set specific key to typematic/autorepeat only (scancode set 3 only)
* xFC scode Set specific key to make/release (scancode set 3 only)
* xFD scode Set specific key to make only (scancode set 3 only)
* xFE Resend last byte
* xFF Reset and start self-test
*/
#ifndef PS2_KBD_H
#define PS2_KBD_H
#include <stdint.h>
#include <event.h>
/* keyboard events */
#define EVT_KBD_SCAN 0x80 /** scan code event */
#define EVT_KBD_ERROR 0x81 /** error event */
#define EVT_KBD_EPARITY 0x00
#define EVT_KBD_EACK 0x01
#define EVT_KBD_ESTART 0x02
#define EVT_KBD_ESTOP 0x03
#define EVT_KBD_CMD_ACK 0x82 /** command ack event */
#define KBD_CLOCK_PIN 4
#define KBD_CLOCK P04 /** ps2 clock pin */
#define KBD_DATA P03 /** ps2 data pin */
/* most common command */
#define KBD_CMD_LED 0xED /* expects argument - LED lock mask */
#define KBD_LED_SCROLL 0x01
#define KBD_LED_NUM 0x02
#define KBD_LED_CAPS 0x04
#define KBD_CMD_ECHO 0xEE
#define KBD_CMD_ID 0xF2
#define KBD_CMD_ENABLE 0xF4
#define KBD_CMD_DISABLE 0xF5
#define KBD_CMD_RESET 0xFF
#define KBD_CMD_ACK 0xFA
#define KBD_CMD_RESEND 0xFE
/**
* send command to the keyboard
* @param cmd command or data to send
*/
void kbd_send_cmd(uint8_t cmd);
/** returns non zero if command is pending */
uint8_t kbd_cmd_pending(void);
/** keyboard event handler */
void kbd_event(uint8_t type, uint8_t data);
#endif
| 2.640625 | 3 |
2024-11-18T22:09:52.899238+00:00
| 2020-12-12T17:17:43 |
ef897f3ed0a2925fdffa05924c45ff223507cabd
|
{
"blob_id": "ef897f3ed0a2925fdffa05924c45ff223507cabd",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-12T17:17:43",
"content_id": "2f559d1ff72c82197bd8461a21d4f79d14b3d731",
"detected_licenses": [
"MIT"
],
"directory_id": "51f64022f52fa87e73222c22054981c664f8c977",
"extension": "c",
"filename": "CmpITG3205.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 202503426,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4329,
"license": "MIT",
"license_type": "permissive",
"path": "/hexapod/Cmps/CmpITG3205.c",
"provenance": "stackv2-0106.json.gz:43351",
"repo_name": "berryerlouis/Hexapod",
"revision_date": "2020-12-12T17:17:43",
"revision_id": "8a436f2b2f12596852b3192ef511fa68d5f59642",
"snapshot_id": "2b1c7f3d942140da0cc363a056328b0db40f8099",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/berryerlouis/Hexapod/8a436f2b2f12596852b3192ef511fa68d5f59642/hexapod/Cmps/CmpITG3205.c",
"visit_date": "2023-07-10T14:15:37.109254"
}
|
stackv2
|
/*
* CmpITG3205.c
*
* Created: 03/07/2012 13:48:49
* Author: berryer
*/
/////////////////////////////////////////////INCLUDES/////////////////////////////////////////////
#include "CmpITG3205.h"
#include "Drv/DrvTwi.h"
#include "Drv/DrvTick.h"
#include "Drv/DrvEeprom.h"
////////////////////////////////////////PRIVATE DEFINES///////////////////////////////////////////
//samples to calib
#define NB_SAMPLE_TO_CALIB_ITG3205 100
//limit for glitch
#define GYRO_GLITCH_LIMIT 800
//value for smoothing
#define GYRO_SMOOTHING_X 20
#define GYRO_SMOOTHING_Y 20
#define GYRO_SMOOTHING_Z 3
////////////////////////////////////////PRIVATE VARIABLES/////////////////////////////////////////
Int16S previous_reading[ 3U ] = { 0U, 0U, 0U };
Int16S gyro_smooth_value[ 3U ] = { 0U, 0U, 0U };
Int8U loop_calibration_itg3205 = 0U;
Int16S gyro_calib_itg3205[ 3U ] = { 0, 0, 0 };
////////////////////////////////////////PRIVATE FUNCTIONS/////////////////////////////////////////
//fonction init du capteur
Boolean CmpITG3205Init(void)
{
Boolean conf = FALSE;
Boolean o_success = FALSE;
Int8U datum = 0U;
DrvTwiReadReg(ITG3205_TWI_ADDRESS, ITG3205_RA_WHO_AM_I, &datum );
if(ITG3205_RA_I_AM == datum)
{
DrvTwiWriteReg(ITG3205_TWI_ADDRESS, ITG3205_RA_PWR_MGM, ITG3205_PWR_H_RESET_BIT);
DrvTickDelayUs(200);
DrvTwiWriteReg(ITG3205_TWI_ADDRESS, ITG3205_RA_SMPLRT_DIV, NO_SMPLRT_DIV);
DrvTickDelayUs(200);
DrvTwiWriteReg(ITG3205_TWI_ADDRESS, ITG3205_RA_DLPF_FS, FS_RANGE_2000 | LPFBW_256HZ );
DrvTickDelayUs(200);
DrvTwiWriteReg(ITG3205_TWI_ADDRESS, ITG3205_RA_PWR_MGM, PLL_ZGYRO_REF );
DrvTickDelayUs(200);
//Calibration du capteur
//si l'eeprom est configué
conf = DrvEepromIsConfigured();
if(conf == FALSE)
{
loop_calibration_itg3205 = NB_SAMPLE_TO_CALIB_ITG3205;
gyro_calib_itg3205[ 0U ] = 0;
gyro_calib_itg3205[ 1U ] = 0;
gyro_calib_itg3205[ 2U ] = 0;
}
else
{
loop_calibration_itg3205 = 0U;
DrvEepromReadGyro(gyro_calib_itg3205);
}
o_success = TRUE;
}
return o_success;
}
Boolean CmpITG3205IsCalibrate(void)
{
if(loop_calibration_itg3205 == 0)
{
DrvEepromWriteGyro(gyro_calib_itg3205);
return TRUE;
}
return FALSE;
}
//Rotation X Y Z
Boolean CmpITG3205GetRotation(Gyroscope *rot)
{
Int8U buffer[ 6U ] = { 0, 0, 0, 0, 0, 0 };
if(DrvTwiReadRegBuf(ITG3205_TWI_ADDRESS, ITG3205_RA_GYRO_XOUT_H, buffer, 6U) != TRUE )
{
return FALSE;
}
else
{
//read gyro value
rot->rawData.x = (Int16S)((Int16U) buffer[0U] << 8U) | ((Int16U) buffer[1U]);
rot->rawData.y = (Int16S)((Int16U) buffer[2U] << 8U) | ((Int16U) buffer[3U]);
rot->rawData.z = (Int16S)((Int16U) buffer[4U] << 8U) | ((Int16U) buffer[5U]);
//anti gyro glitch
//rot->x = SetLimits( rot->x, previous_reading[ 0 ] - GYRO_GLITCH_LIMIT ,previous_reading[ 0 ] + GYRO_GLITCH_LIMIT );
//rot->y = SetLimits( rot->y, previous_reading[ 1 ] - GYRO_GLITCH_LIMIT ,previous_reading[ 1 ] + GYRO_GLITCH_LIMIT );
//rot->z = SetLimits( rot->z, previous_reading[ 2 ] - GYRO_GLITCH_LIMIT ,previous_reading[ 2 ] + GYRO_GLITCH_LIMIT );
if(loop_calibration_itg3205 > 0U)
{
if( loop_calibration_itg3205 == 1U )
{
gyro_calib_itg3205[0U] = gyro_calib_itg3205[0U] / (NB_SAMPLE_TO_CALIB_ITG3205 - 1);
gyro_calib_itg3205[1U] = gyro_calib_itg3205[1U] / (NB_SAMPLE_TO_CALIB_ITG3205 - 1);
gyro_calib_itg3205[2U] = gyro_calib_itg3205[2U] / (NB_SAMPLE_TO_CALIB_ITG3205 - 1);
}
else
{
gyro_calib_itg3205[0U] += rot->rawData.x;
gyro_calib_itg3205[1U] += rot->rawData.y;
gyro_calib_itg3205[2U] += rot->rawData.z;
}
loop_calibration_itg3205--;
}
else
{
//read data - zero offset
rot->rawData.x -= gyro_calib_itg3205[0U];
rot->rawData.y -= gyro_calib_itg3205[1U];
rot->rawData.z -= gyro_calib_itg3205[2U];
//smooth gyro value
/*rot->x = (Int16S) ( ( (Int32S)((Int32S)gyro_smooth_value[0] * (GYRO_SMOOTHING_X - 1) ) + rot->x + 1 ) / GYRO_SMOOTHING_X);
gyro_smooth_value[0] = rot->x;
rot->y = (Int16S) ( ( (Int32S)((Int32S)gyro_smooth_value[1] * (GYRO_SMOOTHING_Y - 1) ) + rot->y + 1 ) / GYRO_SMOOTHING_Y);
gyro_smooth_value[1] = rot->y;
rot->z = (Int16S) ( ( (Int32S)((Int32S)gyro_smooth_value[2] * (GYRO_SMOOTHING_Z - 1) ) + rot->z + 1 ) / GYRO_SMOOTHING_Z);
gyro_smooth_value[2] = rot->z;*/
}
return TRUE;
}
}
| 2.09375 | 2 |
2024-11-18T22:09:54.997662+00:00
| 2021-09-19T21:19:30 |
ea263f1e4d019bf10aa208ff7d7a466f007e3441
|
{
"blob_id": "ea263f1e4d019bf10aa208ff7d7a466f007e3441",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-19T21:19:30",
"content_id": "202549eeded11c18a14b4eadbe4ca7c9d73c16a0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ab7d8ff6dd3c27b96c5cecb961e18343591b14eb",
"extension": "h",
"filename": "i2c_device.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 408239331,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2240,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Healthy-Toilet/components/core2forAWS/i2c_bus/i2c_device.h",
"provenance": "stackv2-0106.json.gz:43995",
"repo_name": "taifur20/IoT-Healthy-Toilet-Project",
"revision_date": "2021-09-19T21:19:30",
"revision_id": "a4ff6c9d3951facae7d153b1c8d1591e221cce85",
"snapshot_id": "d640916ad206b4dd4eb21066b95e7824f5f782ff",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/taifur20/IoT-Healthy-Toilet-Project/a4ff6c9d3951facae7d153b1c8d1591e221cce85/Healthy-Toilet/components/core2forAWS/i2c_bus/i2c_device.h",
"visit_date": "2023-08-10T18:27:07.993467"
}
|
stackv2
|
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "esp_log.h"
#include "driver/gpio.h"
#include "driver/i2c.h"
// Know reg update value
// #define I2C_DEVICE_DEBUG_REG
// Know write or read success and now i2c device status
// #define I2C_DEVICE_DEBUG_INFO
// Know write or read failed
// #define I2C_DEVICE_DEBUG_ERROR
typedef void * I2CDevice_t;
I2CDevice_t i2c_malloc_device(i2c_port_t i2c_num, gpio_num_t sda, gpio_num_t scl, uint32_t freq, uint8_t device_addr);
void i2c_free_device(I2CDevice_t i2c_device);
esp_err_t i2c_apply_bus(I2CDevice_t i2c_device);
void i2c_free_bus(I2CDevice_t i2c_device);
esp_err_t i2c_device_change_freq(I2CDevice_t i2c_device, uint32_t freq);
esp_err_t i2c_read_bytes(I2CDevice_t i2c_device, uint8_t reg_addr, uint8_t *data, uint16_t length);
esp_err_t i2c_read_byte(I2CDevice_t i2c_device, uint8_t reg_addr, uint8_t* data);
esp_err_t i2c_read_bit(I2CDevice_t i2c_device, uint8_t reg_addr, uint8_t *data, uint8_t bit_pos);
/*
Read bits from 8 bit reg
bit_pos = 4, bit_length = 3
read -> 0b|1|0|1|0|1|1|0|0|
0b|-|x|x|x|-|-|-|-|
data = 0b00000010
*/
esp_err_t i2c_read_bits(I2CDevice_t i2c_device, uint8_t reg_addr, uint8_t *data, uint8_t bit_pos, uint8_t bit_length);
esp_err_t i2c_write_bytes(I2CDevice_t i2c_device, uint8_t reg_addr, uint8_t *data, uint16_t length);
esp_err_t i2c_read_bytes_no_stop(I2CDevice_t i2c_device, uint8_t reg_addr, uint8_t *data, uint16_t length);
esp_err_t i2c_write_byte(I2CDevice_t i2c_device, uint8_t reg_addr, uint8_t data);
esp_err_t i2c_write_bit(I2CDevice_t i2c_device, uint8_t reg_addr, uint8_t data, uint8_t bit_pos);
/*
Read before bits from 8 bit reg, then update write bits
1. Read data 0b10101100
2. write, 0b0101, bit_pos = 4, bit_length = 3
read -> 0b|1|0|1|0|1|1|0|0|
0b|-|x|x|x|-|-|-|-|
write -> 0b|1|1|0|1|1|1|0|0|
data = 0b00000101
*/
esp_err_t i2c_write_bits(I2CDevice_t i2c_device, uint8_t reg_addr, uint8_t data, uint8_t bit_pos, uint8_t bit_length);
esp_err_t i2c_device_valid(I2CDevice_t i2c_device);
BaseType_t i2c_take_port(i2c_port_t i2c_num, uint32_t timeout);
BaseType_t i2c_free_port(i2c_port_t i2c_num);
#ifdef __cplusplus
}
#endif
| 2.015625 | 2 |
2024-11-18T22:09:55.142690+00:00
| 2021-04-06T22:28:50 |
5e0190652a0b03d66a7bb9e9389043fa1eea20b1
|
{
"blob_id": "5e0190652a0b03d66a7bb9e9389043fa1eea20b1",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-06T22:28:50",
"content_id": "ea5bcbbf589a1c90f93bc251b54f0820835aaa7a",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "5ad2c22a2f8b9ce07d38b71fbec2be6546c2d452",
"extension": "h",
"filename": "shado.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 355345600,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6349,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/old/shado.h",
"provenance": "stackv2-0106.json.gz:44254",
"repo_name": "Shadorain/ShadoEditor_TestZone",
"revision_date": "2021-04-06T22:28:50",
"revision_id": "29829db2e2dc213bb29b82c22949db3527a1b1a8",
"snapshot_id": "143e364a777ec4b0db6af59a2cfd0f72273415e1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Shadorain/ShadoEditor_TestZone/29829db2e2dc213bb29b82c22949db3527a1b1a8/old/shado.h",
"visit_date": "2023-03-31T10:10:34.661989"
}
|
stackv2
|
/* -------------------------------- shado.h --------------------------------- */
/* -- Includes -- {{{ */
#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#define _GNU_SOURCE
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
/*}}}*/
/* -- Externs -- {{{ */
extern struct GlobalState E;
extern struct Stack *undo;
extern struct Stack *redo;
/*}}}*/
/* -- Macros -- {{{ */
#define SHADO_VERSION "0.0.1"
#define DEBUG 1
#define TAB_STOP 4
#define SHOW_BAR 1
#define QUIT_TIMES 1
#define HL_HIGHLIGHT_NUMS (1<<0)
#define HL_HIGHLIGHT_STRINGS (1<<1)
#define CTRL_KEY(k) ((k) & 0x1f)
#define LEN(v) (int)(sizeof(v) / sizeof(*v))
#define HLDB_ENTRIES (sizeof(HLDB)) / sizeof(HLDB[0])
/* Modes */
#define NORMAL 0
#define INSERT 1
#define VISUAL 2
#define REPLACE 3
#define MISC 10
/*}}}*/
/* -- Data -- {{{ */
/* --- Append buffer --- {{{ */
struct abuf {
char *b;
int len;
};
#define ABUF_INIT { NULL, 0 }
/* }}} */
/* --- Row --- {{{ */
typedef struct erow {
int idx;
int size;
int rsize;
int hl_open_comment;
char *chars;
char *render;
unsigned char *hl;
} erow;
/* }}} */
/* --- Mapping --- {{{ */
typedef void (*handle)(void);
struct mapping {
int c;
handle cmd_func;
};
/* }}} */
/* --- Stack --- {{{ */
typedef struct Stack Stack;
struct Stack {
struct GlobalState *snap;
Stack *next;
};
/* }}} */
/* --- Copy Register --- {{{ */
typedef struct CopyRegister CopyRegister; /* easier since so often used */
struct CopyRegister {
/*TODO: linked list*/
char *line;
CopyRegister *next;
};
/* }}} */
/* --- Global State --- {{{ */
/* TODO: mutli files, maybe a new struct that holds a `focus` keyword for
currently focused file, and holds the diff global state structs */
struct GlobalState {
int cx, cy;
int rx;
int rowoff;
int coloff;
int screenrows;
int screencols;
int numrows;
int dirty;
char *filename;
char stsmsg[80];
time_t stsmsg_time;
struct editorSyntax *syntax;
struct termios orig_termios;
erow *row;
/* 0: normal, 1: insert, 2: visual, 3: visual_line,
* 4: visual_blk, 5: sreplace, 6: mrerplace, 10: misc */
int mode;
/* Makes sure not to print escape code keys */
int print_flag;
/* Global copy register */
CopyRegister *cpyhead;
CopyRegister *cpycurr;
};
/* }}} */
/* --- Syntax --- {{{ */
enum term_colors {
TERM_BLACK = 30, TERM_RED = 31,
TERM_GREEN = 32, TERM_YELLOW = 33,
TERM_BLUE = 34, TERM_MAGENTA = 35,
TERM_CYAN = 36, TERM_WHITE = 37,
TERM_BRIGHT_BLACK = 90, TERM_BRIGHT_RED = 91,
TERM_BRIGHT_GREEN = 92, TERM_BRIGHT_YELLOW = 93,
TERM_BRIGHT_BLUE = 94, TERM_BRIGHT_MAGENTA = 95,
TERM_BRIGHT_CYAN = 96, TERM_BRIGHT_WHITE = 97,
};
struct editorSyntax {
char *filetype;
char **filematch;
char **keywords;
char *singleline_comment_start;
char *multiline_comment_start;
char *multiline_comment_end;
int flags;
};
enum editorHighlight {
HL_NORMAL = 0,
HL_COMMENT,
HL_MLCOMMENT,
HL_KEYWORD1,
HL_KEYWORD2,
HL_NUMBER,
HL_STRING,
HL_MATCH,
};
/* }}} */
/* --- Keys --- {{{ */
#define LEFT 'h'
#define DOWN 'j'
#define UP 'k'
#define RIGHT 'l'
/* #define ARROW_LEFT 1000 */
/* #define ARROW_DOWN 1001 */
/* #define ARROW_UP 1002 */
/* #define ARROW_RIGHT 1003 */
/* #define DEL_KEY 53 */
/* #define BACKSPACE 53 */
/* #define HOME_KEY 53 */
/* #define END_KEY 53 */
/* #define PAGE_UP 53 */
/* #define PAGE_DOWN 53 */
enum ARROW_editorKey {
BACKSPACE = 127,
/* LEFT = 'h', */
/* DOWN = 'j', */
/* UP = 'k', */
/* RIGHT = 'l', */
ARROW_LEFT = 1000,
ARROW_DOWN = 1001,
ARROW_UP = 1002,
ARROW_RIGHT = 1003,
DEL_KEY = 1004,
HOME_KEY = 1005,
END_KEY = 1006,
PAGE_UP = 1007,
PAGE_DOWN = 1008,
};
/* }}} */
/* --- Char type --- {{{*/
enum char_type {
CHAR_AZ09 = 0,
CHAR_SYM,
CHAR_WHITESPACE,
CHAR_NL,
};
/* }}} */
/*}}}*/
/* -- Prototypes -- {{{ */
struct GlobalState *make_snapshot ();
void print_debug ();
void set_sts_msg (const char *fmt, ...);
void refresh_screen ();
char *prompt_line(char *prompt, void (*callback)(char *, int));
/* |>- s_abuf.c -<| */
void ab_append(struct abuf *ab, const char *s, int len);
void ab_free(struct abuf *ab);
/* |>- s_synhl.c -<| */
void update_syntax (erow *row);
int syntax_to_color (int hl);
void select_syntax_hl ();
int is_separator (int c);
/* |>- s_term.c -<| */
void kill (const char *s);
void disable_raw ();
void enable_raw ();
int read_keypress ();
void quit ();
int get_curs_pos (int *rows, int *cols);
int get_win_size (int *rows, int *cols);
/* |>- s_rows.c -<| */
int row_cx_to_rx (erow *row, int cx);
int row_rx_to_cx (erow *row, int rx);
void update_row (erow *row);
void insert_row (int at, char *s, size_t len);
void free_row (erow *row);
void delete_row (int at);
void insert_char_row (erow *row, int at, int c);
void delete_char_row(erow *row, int at);
void append_string_row (erow *row, char *s, size_t len);
struct erow *copy_append_row (erow *row, char *s, size_t len);
/* |>- s_ops.c -<| */
void insert_char (int c);
void delete_char ();
void insert_nl ();
int get_char_type ();
/* |>- s_bar.c -<| */
void draw_sts_bar (struct abuf *ab);
void draw_msg_bar (struct abuf *ab);
void set_sts_msg (const char *fmt, ...);
/* |>- s_io.c -<| */
char *rows_to_string (int *buflen);
void open_file (char *filename);
void save_file ();
/* |>- s_search.c -<| */
void search_callback (char *query, int key);
void search ();
/* |>- s_input.c -<| */
char *prompt_line (char *prompt, void (*callback)(char *, int));
void move_cursor (int key);
/* |>- s_output.c -<| */
void scroll ();
void draw_rows (struct abuf *ab);
void refresh_screen ();
void set_cursor_type ();
/* |>- s_modes.c -<| */
void process_keypress ();
/* |>- s_copyreg.c -<| */
void cpy_append (char *line);
void cpy_prepend (char *line);
void cpy_print();
/* |>- s_stack.c -<| */
void push (Stack **top, struct GlobalState *state);
struct GlobalState *pop (Stack **top);
struct GlobalState *peek (Stack *top);
/*}}}*/
/* -------------------------------------------------------------------------- */
| 2.15625 | 2 |
2024-11-18T22:09:55.425773+00:00
| 2020-06-05T15:57:11 |
dbf66a854093eaa2df99de9181bd54ed42481e4b
|
{
"blob_id": "dbf66a854093eaa2df99de9181bd54ed42481e4b",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-05T15:57:11",
"content_id": "b85fa5a07220925e41d9312f9405b127e03acc47",
"detected_licenses": [
"MIT"
],
"directory_id": "d999cd188d834c43d910c30d8927a1af7dbc0472",
"extension": "c",
"filename": "user_view.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 265261445,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5984,
"license": "MIT",
"license_type": "permissive",
"path": "/src/user_view.c",
"provenance": "stackv2-0106.json.gz:44383",
"repo_name": "LinLorry/StudentInfoSystem",
"revision_date": "2020-06-05T15:57:11",
"revision_id": "d6e2a38a772030a7915636151e8e84e9f1320263",
"snapshot_id": "0040eb7b3d3a577f7521efcc39ebc54626c2e424",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/LinLorry/StudentInfoSystem/d6e2a38a772030a7915636151e8e84e9f1320263/src/user_view.c",
"visit_date": "2022-09-20T16:38:39.806323"
}
|
stackv2
|
#include <stdio.h>
#include <student_info_system/util.h>
#include <student_info_system/user.h>
#include <util.h>
#include <user_view.h>
const char admin_str[] = "Admin";
const char user_str[] = "User";
int show_user();
int create_user();
int update_user_view();
int change_password_view();
int remove_user();
int user_manage()
{
const menu menus[] = {
{"show users", show_user},
{"create user", create_user},
{"update user", update_user_view},
{"change password", change_password_view},
{"remove user", remove_user},
};
if (ADMIN_LEVEL_VALUE == get_current_level())
{
return show_menu(menus, 5, NULL);
}
else
{
return show_menu(menus, 1, NULL);
}
}
int show_user()
{
CLEAR();
printf("Show User:\n");
print_users();
printf("Press any key continue.");
CLEAR_STDIN();
return 0;
}
int create_user()
{
int tmp;
char tmp_str[256];
int level;
char username[USERNAME_BUFFER_SIZE];
char password[PASSWORD_BUFFER_SIZE];
CLEAR();
printf("Create User:\n");
printf("What type user you want to create(Admin or User)? [a/U]: ");
tmp = getchar();
CLEAR_STDIN_WITH_PRE(tmp);
if (tmp == 'a' || tmp == 'A')
{
level = ADMIN_LEVEL_VALUE;
}
else
{
level = USER_LEVEL_VALUE;
}
sprintf(tmp_str, "Username length must less then %d\n", USERNAME_MAX_LENGTH);
input_str(
username, USERNAME_MAX_LENGTH,
"Please input new username: ",
"Please input new username again: ",
tmp_str);
sprintf(tmp_str, "Password length must less then %d\n", PASSWORD_MAX_LENGTH);
input_str(
password, PASSWORD_MAX_LENGTH,
"Please input new user password: ",
"Please input new user password again: ",
tmp_str);
if (!add_user(level, username, password))
{
printf("Create user success\n");
}
printf("Press any key continue.");
CLEAR_STDIN();
return 0;
}
int update_user_view()
{
int tmp;
unsigned long id;
char tmp_str[256];
unsigned char level;
char username[USERNAME_BUFFER_SIZE];
const_user_info *user_info_p;
CLEAR();
printf("Update User:\n");
print_users();
printf("Please input user id which you want to update: ");
tmp = scanf("%ld", &id);
CLEAR_STDIN();
while (tmp != 1 || id < 1 || (user_info_p = get_user(id)) == NULL)
{
printf("Please input valid id: ");
tmp = scanf("%ld", &id);
CLEAR_STDIN();
}
level = user_info_p->level;
printf(
"User original info:\nlevel: %s\nusername: %s\n",
level == ADMIN_LEVEL_VALUE ? admin_str : user_str,
user_info_p->username);
if (level == ADMIN_LEVEL_VALUE)
{
printf("Change this user type to user[y/N]?");
tmp = getchar();
CLEAR_STDIN_WITH_PRE(tmp);
if (tmp == 'y' || tmp == 'Y')
{
level = USER_LEVEL_VALUE;
}
}
else
{
printf("Change this user type to admin[y/N]?");
tmp = getchar();
CLEAR_STDIN_WITH_PRE(tmp);
if (tmp == 'y' || tmp == 'Y')
{
level = ADMIN_LEVEL_VALUE;
}
}
sprintf(tmp_str, "Username length must less then %d\n", USERNAME_MAX_LENGTH);
input_str(
username, USERNAME_MAX_LENGTH,
"Please input new username: ",
"Please input new username again: ",
tmp_str
);
if (!update_user(id, level, username, NULL))
{
printf("Update user success!\n");
}
printf("Press any key continue.");
CLEAR_STDIN();
return 0;
}
int change_password_view()
{
int tmp;
unsigned long id;
char tmp_str[256];
char password[PASSWORD_BUFFER_SIZE];
CLEAR();
printf("Change Password:\n");
print_users();
printf("Please input user id which you want to update: ");
tmp = scanf("%ld", &id);
CLEAR_STDIN();
while (tmp != 1 || id < 1)
{
printf("Please input valid id: ");
tmp = scanf("%ld", &id);
CLEAR_STDIN();
}
sprintf(tmp_str, "Password length must less then %d\n", PASSWORD_MAX_LENGTH);
input_str(
password, PASSWORD_MAX_LENGTH,
"Please input new password: ",
"Please input new password again: ",
tmp_str
);
if (!update_user(id, NULL_LEVEL_VALUE, NULL, password))
{
printf("Update password success!\n");
}
printf("Press any key continue.");
CLEAR_STDIN();
return 0;
}
int remove_user()
{
int tmp;
long id;
const unsigned long current_id = get_current_id();
CLEAR();
printf("Remove User:\n");
print_users();
printf("Please input user id which you want to remove: ");
tmp = scanf("%ld", &id);
CLEAR_STDIN();
while (tmp != 1 || id < 1 || id == current_id)
{
if (id == current_id)
{
printf("You can't delete yourself!\n");
}
printf("Please input valid id: ");
tmp = scanf("%ld", &id);
CLEAR_STDIN();
}
if (!delete_user(id))
{
printf("Delete user success!\n");
}
printf("Press any key continue.");
CLEAR_STDIN();
return 0;
}
int print_users()
{
const unsigned long user_number = get_user_number();
const_user_info *user_infos = get_user_infos();
const_user_info *user_info_end = user_infos + user_number;
const_user_info *user_info_p;
printf("+-------------------------+\n");
printf("| id\t type\t username|\n");
printf("+-------------------------+\n");
for (user_info_p = user_infos; user_info_p != user_info_end; ++user_info_p)
{
printf(
"|%4ld\t%6s\t%10s|\n",
user_info_p->id,
user_info_p->level == ADMIN_LEVEL_VALUE ? admin_str : user_str,
user_info_p->username);
}
printf("+-------------------------+\n");
return 0;
}
| 2.84375 | 3 |
2024-11-18T22:09:56.030221+00:00
| 2015-07-01T12:00:49 |
aaafd0cfa3f51f16c6ec41bfa6dbd8cbf3bb53c5
|
{
"blob_id": "aaafd0cfa3f51f16c6ec41bfa6dbd8cbf3bb53c5",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-01T12:00:49",
"content_id": "26b209c67cbce35526c42bcd77ef77bf953bb463",
"detected_licenses": [
"Zlib"
],
"directory_id": "92142a67b124f59794bb04514579ced94bb0b078",
"extension": "h",
"filename": "texture.h",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 20568999,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4191,
"license": "Zlib",
"license_type": "permissive",
"path": "/include/texture.h",
"provenance": "stackv2-0106.json.gz:45029",
"repo_name": "danyalzia/CIrrlicht",
"revision_date": "2015-07-01T12:00:49",
"revision_id": "45adb0e26e85f792adb569f5c5b40479c4d2b8fd",
"snapshot_id": "44df17111366b303bcdaed927fa6691e62152234",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/danyalzia/CIrrlicht/45adb0e26e85f792adb569f5c5b40479c4d2b8fd/include/texture.h",
"visit_date": "2021-01-22T10:18:39.788627"
}
|
stackv2
|
/*
CIrrlicht - C Bindings for Irrlicht Engine
Copyright (C) 2014- Danyal Zia (catofdanyal@yahoo.com)
This software is provided 'as-is', without any express or
implied warranty. In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
*/
#pragma once
//! Enumeration flags telling the video driver in which format textures should be created.
enum E_TEXTURE_CREATION_FLAG
{
/** Forces the driver to create 16 bit textures always, independent of
which format the file on disk has. When choosing this you may lose
some color detail, but gain much speed and memory. 16 bit textures can
be transferred twice as fast as 32 bit textures and only use half of
the space in memory.
When using this flag, it does not make sense to use the flags
ETCF_ALWAYS_32_BIT, ETCF_OPTIMIZED_FOR_QUALITY, or
ETCF_OPTIMIZED_FOR_SPEED at the same time. */
ETCF_ALWAYS_16_BIT = 0x00000001,
/** Forces the driver to create 32 bit textures always, independent of
which format the file on disk has. Please note that some drivers (like
the software device) will ignore this, because they are only able to
create and use 16 bit textures.
When using this flag, it does not make sense to use the flags
ETCF_ALWAYS_16_BIT, ETCF_OPTIMIZED_FOR_QUALITY, or
ETCF_OPTIMIZED_FOR_SPEED at the same time. */
ETCF_ALWAYS_32_BIT = 0x00000002,
/** Lets the driver decide in which format the textures are created and
tries to make the textures look as good as possible. Usually it simply
chooses the format in which the texture was stored on disk.
When using this flag, it does not make sense to use the flags
ETCF_ALWAYS_16_BIT, ETCF_ALWAYS_32_BIT, or ETCF_OPTIMIZED_FOR_SPEED at
the same time. */
ETCF_OPTIMIZED_FOR_QUALITY = 0x00000004,
/** Lets the driver decide in which format the textures are created and
tries to create them maximizing render speed.
When using this flag, it does not make sense to use the flags
ETCF_ALWAYS_16_BIT, ETCF_ALWAYS_32_BIT, or ETCF_OPTIMIZED_FOR_QUALITY,
at the same time. */
ETCF_OPTIMIZED_FOR_SPEED = 0x00000008,
/** Automatically creates mip map levels for the textures. */
ETCF_CREATE_MIP_MAPS = 0x00000010,
/** Discard any alpha layer and use non-alpha color format. */
ETCF_NO_ALPHA_CHANNEL = 0x00000020,
//! Allow the Driver to use Non-Power-2-Textures
/** BurningVideo can handle Non-Power-2 Textures in 2D (GUI), but not in 3D. */
ETCF_ALLOW_NON_POWER_2 = 0x00000040,
/** This flag is never used, it only forces the compiler to compile
these enumeration values to 32 bit. */
ETCF_FORCE_32_BIT_DO_NOT_USE = 0x7fffffff
};
//! Enum for the mode for texture locking. Read-Only, write-only or read/write.
enum E_TEXTURE_LOCK_MODE
{
//! The default mode. Texture can be read and written to.
ETLM_READ_WRITE = 0,
//! Read only. The texture is downloaded, but not uploaded again.
/** Often used to read back shader generated textures. */
ETLM_READ_ONLY,
//! Write only. The texture is not downloaded and might be uninitialised.
/** The updated texture is uploaded to the GPU.
Used for initialising the shader from the CPU. */
ETLM_WRITE_ONLY
};
//! Where did the last IVideoDriver::getTexture call find this texture
enum E_TEXTURE_SOURCE
{
//! IVideoDriver::getTexture was never called (texture created otherwise)
ETS_UNKNOWN,
//! Texture has been found in cache
ETS_FROM_CACHE,
//! Texture had to be loaded
ETS_FROM_FILE
};
typedef struct irr_ITexture irr_ITexture;
| 2.0625 | 2 |
2024-11-18T22:09:56.142837+00:00
| 2019-04-11T00:36:53 |
60801849eba381de5c7c7cb7291d164179ef21ce
|
{
"blob_id": "60801849eba381de5c7c7cb7291d164179ef21ce",
"branch_name": "refs/heads/develop",
"committer_date": "2019-04-11T00:36:53",
"content_id": "fcd7dcf5fb249ec2bd106cdfcc52f9360409271b",
"detected_licenses": [
"MIT"
],
"directory_id": "c8f53bec9f81a4441f14dfd4d9fe522f61591dbb",
"extension": "c",
"filename": "led.c",
"fork_events_count": 0,
"gha_created_at": "2019-04-05T20:54:51",
"gha_event_created_at": "2019-04-05T22:55:25",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 179753628,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1018,
"license": "MIT",
"license_type": "permissive",
"path": "/sam4s/sample_apps/atmel_studio_template/MyApp/drivers/led.c",
"provenance": "stackv2-0106.json.gz:45158",
"repo_name": "TRACE-InfluX/oslab4",
"revision_date": "2019-04-11T00:36:53",
"revision_id": "af1565c0618d0121efcaef4db2a8e26d492213bd",
"snapshot_id": "6fc06b724b347cfe1eed6c77699a4bbbd4ca5907",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TRACE-InfluX/oslab4/af1565c0618d0121efcaef4db2a8e26d492213bd/sam4s/sample_apps/atmel_studio_template/MyApp/drivers/led.c",
"visit_date": "2020-05-05T05:28:21.142395"
}
|
stackv2
|
/*
* led.c
*
* LEDs
*/
#include "../minilib/pio.h"
#include "led.h"
void led_write( tLedNum led_num, bool state ){
tPioPin led_pin;
//get pin and set direction
switch(led_num){
case Led0: pio_create_pin( &led_pin, PioC, 23 ); break;
case Led1: pio_create_pin( &led_pin, PioC, 20 ); break;
case Led2: pio_create_pin( &led_pin, PioA, 16 ); break;
case Led3: pio_create_pin( &led_pin, PioC, 22 ); break;
case Led4: pio_create_pin( &led_pin, PioC, 19 ); break;
}
//set direction
pio_set_pin_dir( &led_pin, PioPinDirOutput );
//write
pio_write_pin( &led_pin, state );
}
bool led_read( tLedNum led_num ){
tPioPin led_pin;
//get pin
switch(led_num){
case Led0: pio_create_pin( &led_pin, PioC, 23 ); break;
case Led1: pio_create_pin( &led_pin, PioC, 20 ); break;
case Led2: pio_create_pin( &led_pin, PioA, 16 ); break;
case Led3: pio_create_pin( &led_pin, PioC, 22 ); break;
case Led4: pio_create_pin( &led_pin, PioC, 19 ); break;
}
return pio_read_pin( &led_pin );
}
| 2.84375 | 3 |
2024-11-18T22:09:56.615923+00:00
| 2023-08-15T02:59:58 |
851d859e3e642ddd137da3efb446839e3926e500
|
{
"blob_id": "851d859e3e642ddd137da3efb446839e3926e500",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-15T02:59:58",
"content_id": "69c6d7237410d6673b68d501715556fc97c79701",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a7eb942de712b5e60a99aab2d76512be75816f5c",
"extension": "c",
"filename": "flushTestReader.c",
"fork_events_count": 17,
"gha_created_at": "2016-12-15T03:07:59",
"gha_event_created_at": "2023-05-21T21:53:25",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 76519082,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3397,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/iotests/flushTestReader.c",
"provenance": "stackv2-0106.json.gz:45672",
"repo_name": "dr-who/stutools",
"revision_date": "2023-08-15T02:59:58",
"revision_id": "455469e56f26954c96529eef6514116e88dd2c8b",
"snapshot_id": "6d0013ec9099cf5a29dc0147e7c46824ddd13b0d",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/dr-who/stutools/455469e56f26954c96529eef6514116e88dd2c8b/iotests/flushTestReader.c",
"visit_date": "2023-08-24T11:02:51.085267"
}
|
stackv2
|
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <getopt.h>
#include <sys/uio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include "utils.h"
#include "logSpeed.h"
#define NEEDLE "!!!### 3.14159265 ###!!!"
#define READCHUNK (10*1024*1024)
typedef struct {
int threadid;
char *path;
size_t total;
size_t startPosition;
size_t exclusive;
logSpeedType logSpeed;
} threadInfoType;
int keepRunning = 1;
void intHandler(int d) {
(void)d;
fprintf(stderr,"got signal\n");
}
static void *runThread(void *arg) {
threadInfoType *threadContext = (threadInfoType*)arg; // grab the thread threadContext args
int mode = O_RDONLY | O_DIRECT;
int fd = open(threadContext->path, mode);
if (fd < 0) {
perror(threadContext->path);
return NULL;
}
char *haystack;
CALLOC(haystack, READCHUNK, 1);
//= aligned_alloc(4096, READCHUNK); // 10MB to skip superblock
double lastnum = 0;
double maxdelta = 0;
double totaldelta = 0;
double totalN = 0;
while (1) {
lseek(fd, 0, SEEK_SET);
int bytes = read(fd, haystack, READCHUNK);
double readtime = timedouble();
if (bytes < 0) {
perror("read");
}
char actualneed[100];
sprintf(actualneed, "%s%2d", NEEDLE, threadContext->threadid);
char *pos = memmem(haystack, bytes, actualneed, strlen(actualneed));
if (pos) {
double r = atof(pos - 24);
if (r != lastnum) {
// fprintf(stderr,"read '%s'\n", s);
double delta = readtime - r;
if (delta < 87600) {
totalN++;
totaldelta += delta;
if (delta > maxdelta) {
maxdelta = delta;
}
}
fprintf(stderr,"thread %d, pos=%10zd read %f (delta from now %f, avg delta %f, max delta %f)\n", threadContext->threadid, pos - haystack, r, delta, totaldelta/totalN, maxdelta);
lastnum = r;
}
usleep(10);
}
}
free(haystack);
return NULL;
}
void startThreads(int argc, char *argv[]) {
if (argc > 0) {
size_t threads = argc - 1;
pthread_t *pt = (pthread_t*) calloc((size_t) threads, sizeof(pthread_t));
if (pt==NULL) {fprintf(stderr, "OOM(pt): \n");exit(-1);}
threadInfoType *threadContext = (threadInfoType*) calloc(threads, sizeof(threadInfoType));
if (threadContext == NULL) {fprintf(stderr,"OOM(threadContext): \n");exit(-1);}
int startP = 0;
for (size_t i = 0; i < threads; i++) {
if (argv[i + 1][0] != '-') {
threadContext[i].path = argv[i + 1];
threadContext[i].threadid = i;
threadContext[i].exclusive = 0;
threadContext[i].startPosition = (1024L*1024*1024) * startP;
threadContext[i].total = 0;
logSpeedInit(&threadContext[i].logSpeed);
pthread_create(&(pt[i]), NULL, runThread, &(threadContext[i]));
}
}
size_t allbytes = 0;
double maxtime = 0;
double allmb = 0;
for (size_t i = 0; i < threads; i++) {
if (argv[i + 1][0] != '-') {
pthread_join(pt[i], NULL);
allbytes += threadContext[i].total;
allmb += logSpeedMean(&threadContext[i].logSpeed) / 1024.0 / 1024;
if (logSpeedTime(&threadContext[i].logSpeed) > maxtime) {
maxtime = logSpeedTime(&threadContext[i].logSpeed);
}
logSpeedFree(&threadContext[i].logSpeed);
}
}
free(threadContext);
free(pt);
}
}
int main(int argc, char *argv[]) {
startThreads(argc, argv);
return 0;
}
| 2.53125 | 3 |
2024-11-18T22:09:56.715697+00:00
| 2021-05-30T11:46:34 |
3cdabff9ecafa388d4696311abe8a678fb03377f
|
{
"blob_id": "3cdabff9ecafa388d4696311abe8a678fb03377f",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-30T11:46:34",
"content_id": "c0b9996457738f06f6db019aced90e3ae2623bdb",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "71e58f96e2e4a885179829c5fea71e50075f3722",
"extension": "c",
"filename": "ballblob.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 149999147,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2455,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/ballblob.c",
"provenance": "stackv2-0106.json.gz:45802",
"repo_name": "b3lial/amiga-starlight-framework",
"revision_date": "2021-05-30T11:46:34",
"revision_id": "d173c40d5417cb53b2421c3e2d9ba5512e0eef10",
"snapshot_id": "820e063f5bb7750c13c440fbbc7516af0ab17a6e",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/b3lial/amiga-starlight-framework/d173c40d5417cb53b2421c3e2d9ba5512e0eef10/ballblob.c",
"visit_date": "2021-06-01T18:53:57.461710"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <exec/types.h>
#include <proto/graphics.h>
#include <proto/exec.h>
#include <graphics/displayinfo.h>
#include <graphics/gfxbase.h>
#include <graphics/videocontrol.h>
#include <dos/dos.h>
#include "starlight/starlight.h"
#include "ballblob.h"
#include "main.h"
struct BitMap* ballBlob = NULL;
struct BitMap* ballBlobScreen = NULL;
void initBallBlob(void){
UWORD colortable0[] = { BLACK, RED, GREEN, BLUE, BLACK, RED, GREEN, BLUE };
BYTE i = 0;
writeLog("\n== Initialize View: BallBlob ==\n");
//Load Boingball Blob Sprite and its Colors
ballBlob = loadBlob("img/ball_207_207_3.RAW", VIEW_BALLBLOB_DEPTH,
VIEW_BALLBLOB_BALL_WIDTH, VIEW_BALLBLOB_BALL_HEIGHT);
if(ballBlob == NULL){
writeLog("Error: Payload BallBlob, could not load ball blob\n");
exitStarlight();
exitBallBlob();
exit(RETURN_ERROR);
}
writeLogFS("Ballblob BitMap: BytesPerRow: %d, Rows: %d, Flags: %d, pad: %d\n",
ballBlob->BytesPerRow, ballBlob->Rows, ballBlob->Flags,
ballBlob->pad);
loadColorMap("img/ball_207_207_3.CMAP", colortable0, VIEW_BALLBLOB_COLORS);
//Create View and ViewExtra memory structures
createNewView();
//Create Bitmap for ViewPort
ballBlobScreen = createBitMap(VIEW_BALLBLOB_DEPTH, VIEW_BALLBLOB_WIDTH,
VIEW_BALLBLOB_HEIGHT);
for(i=0; i<VIEW_BALLBLOB_DEPTH; i++){
BltClear(ballBlobScreen->Planes[i],
(ballBlobScreen->BytesPerRow) * (ballBlobScreen->Rows), 1);
}
writeLogFS("Screen BitMap: BytesPerRow: %d, Rows: %d, Flags: %d, pad: %d\n",
ballBlobScreen->BytesPerRow, ballBlobScreen->Rows,
ballBlobScreen->Flags, ballBlobScreen->pad);
//Add previously created BitMap to ViewPort so its shown on Screen
addViewPort(ballBlobScreen, NULL, colortable0, VIEW_BALLBLOB_COLORS, FALSE,
0, 0, VIEW_BALLBLOB_WIDTH, VIEW_BALLBLOB_HEIGHT, 0, 0);
//Copy Ball into ViewPort
BltBitMap(ballBlob, 0, 0, ballBlobScreen, 60, 20, VIEW_BALLBLOB_BALL_WIDTH,
VIEW_BALLBLOB_BALL_HEIGHT, 0xC0, 0xff, 0);
//Make View visible
startView();
}
// just a wrapper because we do not have business logic here
// just quit on mouse click
BOOL executeBallBlob(void){
return ((BOOL) !mouseClick());
}
void exitBallBlob(void){
cleanBitMap(ballBlobScreen);
cleanBitMap(ballBlob);
}
| 2.34375 | 2 |
2024-11-18T22:09:57.631842+00:00
| 2018-07-26T08:09:31 |
c44eab7b457d0a570ee342ecc064e720fc8d64a1
|
{
"blob_id": "c44eab7b457d0a570ee342ecc064e720fc8d64a1",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-26T08:09:31",
"content_id": "74635b127b16292dbb9e961867968a06b5adf58b",
"detected_licenses": [
"MIT"
],
"directory_id": "e08400f1f5b56e0fd6b736e4e1280dfee16fb752",
"extension": "c",
"filename": "decodingtoyuv.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 95170740,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4478,
"license": "MIT",
"license_type": "permissive",
"path": "/decodingtoyuv.c",
"provenance": "stackv2-0106.json.gz:45931",
"repo_name": "GinRyan/ff_simple_tutorial",
"revision_date": "2018-07-26T08:09:31",
"revision_id": "9a4053a37d12a3b2a6c2a2e381d3d749b1463c63",
"snapshot_id": "57d6052f567f6e05e65b852c389ed4e1436b5034",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/GinRyan/ff_simple_tutorial/9a4053a37d12a3b2a6c2a2e381d3d749b1463c63/decodingtoyuv.c",
"visit_date": "2020-04-05T12:36:09.502488"
}
|
stackv2
|
#include "videodecodingheader.h"
#define INBUF_SIZE 4096;
FILE* pFin = NULL;
FILE* pFout = NULL;
AVCodec* pCodec = NULL;
AVCodecContext* pContext = NULL;
AVCodecParserContext* pCodecParserCtx = NULL;
AVFrame* frame =NULL;
AVPacket pkt;
/**
* ./DecodeToYUV out.h264 out2.yuv
*
* @brief open_input_output_file
* @param argv
* @return
*/
static int open_input_output_file(char **argv){
//buffer size with padding
const char* inputFileName = argv[1];
const char* outputFilename= argv[2];
pFin = fopen(inputFileName,"rb+");
if (!pFin) {
printf("Error:open input file failed\n");
return -1;
}
pFout = fopen(outputFilename,"wb+");
if (!pFout) {
printf("Error:open output file failed\n");
return -1;
}
}
/**
* @brief open_decoder
* @return
*/
static int open_decoder(){
avcodec_register_all();
av_init_packet(&pkt);//init packet
pCodec = avcodec_find_decoder(AV_CODEC_ID_H264);
if (!pCodec) {
printf("Find codec error\n");
return -1;
}
pContext = avcodec_alloc_context3(pCodec);
if (!pContext) {
printf("Error: avcodec_alloc_context3 failed\n");
return -1;
}
if (pCodec->capabilities & AV_CODEC_CAP_TRUNCATED) {
pContext->flags |= AV_CODEC_CAP_TRUNCATED;//
}
pCodecParserCtx = av_parser_init(AV_CODEC_ID_H264);
if (!pCodecParserCtx) {
printf("Error: av_parser_init failed\n");
return -1;
}
if (avcodec_open2(pContext,pCodec,NULL) < 0) {
printf("Error: avcodec_open2 failed\n");
return -1;
}
frame = av_frame_alloc();
if (!frame) {
printf("Error: av_frame_alloc failed\n");
return -1;
}
return 0;
}
/**
* @brief write_out_yuv_frame
* @param frame
*/
static void write_out_yuv_frame(const AVFrame* frame){
uint8_t **pBuf = frame->data;
int * pStride= frame->linesize;
for (int color_idx=0;color_idx < 3; color_idx++) {
int nWidth = color_idx ==0?frame->width:frame->width / 2;
int nHeight = color_idx ==0? frame->height:frame->height / 2;
for (int idx=0;idx < nHeight; idx++) {//write by line
fwrite(pBuf[color_idx],1,nWidth,pFout);
pBuf[color_idx] += pStride[color_idx];
}
fflush(pFout);
}
}
static void closeAll(){
fclose(pFin);
fclose(pFout);
avcodec_close(pContext);
av_free(pContext);
av_frame_free(&frame);
}
int main(int argc, char *argv[]){
int buffS = INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE;
uint8_t inbuf[buffS];
if (open_input_output_file(argv)<0) {
return -1;
}else {
printf("ok: open_input_output_file ok\n");
}
if (open_decoder() < 0) {
return -1;
}else {
printf("ok: open_decoder ok\n");
}
int uDataSize = 0;
int len = 0;
int got_frame = 0;
uint8_t* pDataPtr = NULL;
int buffsize=INBUF_SIZE;
while (1) {
uDataSize = fread(inbuf,1,buffsize,pFin);
printf("ok: fread ok\n");
if (uDataSize == 0) {
break;
}
pDataPtr = inbuf;
//parse to pkg
while (uDataSize > 0) {
len = av_parser_parse2(pCodecParserCtx,pContext,
&pkt.data,&pkt.size,
pDataPtr,uDataSize,
AV_NOPTS_VALUE,AV_NOPTS_VALUE,AV_NOPTS_VALUE
);
pDataPtr += len;
uDataSize -= len;
if (pkt.size == 0) {
continue;
}
//parse ok
printf("parse 1 packet\n");
int duration = pCodecParserCtx->duration;
int dts = pCodecParserCtx->cur_frame_dts;
int pts = pCodecParserCtx->cur_frame_pts;
printf("Duration: %d PTS:%d, DTS: %d\n" , duration, pts, dts);
int ret = avcodec_send_packet(pContext,&pkt);
if (ret < 0) {
return -1;
}
int outret = avcodec_receive_frame(pContext,frame);
if (outret < 0) {
if (outret == AVERROR_EOF) {
printf("decode finished");
break;
}
}
printf("Decode 1 frame OK~: width:%d height:%d \n",frame->width,frame->height);
write_out_yuv_frame(frame);
}
}
closeAll();
return EXIT_SUCCESS;
}
| 2.46875 | 2 |
2024-11-18T22:09:58.182839+00:00
| 2020-11-19T17:37:39 |
3bd5cd335729d769ed3d28a3d9337d263843d617
|
{
"blob_id": "3bd5cd335729d769ed3d28a3d9337d263843d617",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-19T17:37:39",
"content_id": "0079bc49e32f12d149200d9fdea5bc3f08aaa888",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "4f26239e80fb4849380852ff3de3340ea0620477",
"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": 2778,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/ambiente_globale/produttore_consumatore/produttore-consumatore_asimmetrico_con_vettore_di_stato/main.c",
"provenance": "stackv2-0106.json.gz:46188",
"repo_name": "aspo98/esercizi_linux",
"revision_date": "2020-11-19T17:37:39",
"revision_id": "48cae68815775bc94b68777454232460413f504c",
"snapshot_id": "11b2e3abcf418467ee40f13699cce558419b16fe",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aspo98/esercizi_linux/48cae68815775bc94b68777454232460413f504c/ambiente_globale/produttore_consumatore/produttore-consumatore_asimmetrico_con_vettore_di_stato/main.c",
"visit_date": "2023-01-12T14:39:21.740097"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include "header.h"
// PRIMA SOLUZIONE AL PASSAGGIO DI PARAMETRI:
// Passaggio tramite una struttura dati
// (sia per l'istanza di monitor, sia per l'identificativo)
typedef struct {
int identificativo;
GestioneVoli * g;
} parametri;
// SECONDA SOLUZIONE AL PASSAGGIO DI PARAMETRI:
// Uso di una variabile globale
// (per l'istanza di monitor)
//GestioneVoli * g;
void * thread_gestori(void * p) {
// PRIMA SOLUZIONE AL PASSAGGIO DI PARAMETRI:
// Passaggio tramite una struttura dati
parametri * param = (parametri *)p;
int identificativo = param->identificativo;
GestioneVoli * g = param->g;
// SECONDA SOLUZIONE:
// Cast del puntatore ad un intero
// (per l'identificativo del thread)
//int identificativo = (int) (long)p;
printf("[THREAD %d] Inserimento\n\n", identificativo);
InserisciVolo(g, identificativo);
printf("[THREAD %d] Aggiornamento (1000)\n\n", identificativo);
AggiornaVolo(g, identificativo, 1000);
printf("[THREAD %d] Aggiornamento (2000)\n\n", identificativo);
AggiornaVolo(g, identificativo, 2000);
printf("[THREAD %d] Aggiornamento (1000)\n\n", identificativo);
AggiornaVolo(g, identificativo, 1000);
printf("[THREAD %d] Rimozione\n\n", identificativo);
RimuoviVolo(g, identificativo);
pthread_exit(0);
}
int main() {
pthread_t threads[5];
pthread_attr_t attr;
int i, ret;
// PRIMA SOLUZIONE:
// Passaggio di parametri tramite una struttura
GestioneVoli * g = (GestioneVoli *)malloc(sizeof(GestioneVoli));
// SECONDA SOLUZIONE:
// Uso di una variabile globale
// (per l'istanza di monitor)
//g = (GestioneVoli *)malloc(sizeof(GestioneVoli));
pthread_mutex_init( &(g->mutex), NULL );
pthread_cond_init( &(g->produttori), NULL );
g->num_liberi = NUMERO_BUFFER;
for(i=0; i<NUMERO_BUFFER; i++) {
g->vettore_stato[i] = LIBERO;
}
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
// PRIMA SOLUZIONE:
// Passaggio di parametri tramite una struttura
parametri param[5];
for(i=0; i<5; i++) {
// PRIMA SOLUZIONE:
// Passaggio di parametri tramite una struttura
param[i].identificativo = i;
param[i].g = g;
ret = pthread_create( &threads[i], &attr, thread_gestori, ¶m[i]);
// SECONDA SOLUZIONE:
// Cast da intero a puntatore
// (per l'identificativo del thread)
//ret = pthread_create( &threads[i], &attr, thread_gestori, (void*) (long)i);
if(ret) {
printf("Errore creazione thread (%d)\n", ret);
exit(-1);
}
}
for(i=0; i<5; i++) {
ret = pthread_join( threads[i], NULL );
if(ret) {
printf("Errore join thread (%d)\n", ret);
exit(-1);
}
}
free(g);
}
| 2.984375 | 3 |
2024-11-18T22:09:58.321877+00:00
| 2021-07-18T10:48:14 |
432dfbcc28c9c4914d2f5a2901e643e2b7a78bf1
|
{
"blob_id": "432dfbcc28c9c4914d2f5a2901e643e2b7a78bf1",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-18T10:48:14",
"content_id": "d99cf01d76fb76de77478b3eb3a503440e7c4e92",
"detected_licenses": [
"MIT"
],
"directory_id": "772a6d9500c9f5b46485b3412647d24c09c90bfe",
"extension": "c",
"filename": "test-client.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": 2206,
"license": "MIT",
"license_type": "permissive",
"path": "/stream-server-snippet/test-client.c",
"provenance": "stackv2-0106.json.gz:46444",
"repo_name": "ww117w/code-snippets",
"revision_date": "2021-07-18T10:48:14",
"revision_id": "b263a1371a7e8cf2d914b756d62ff75d731d069f",
"snapshot_id": "0f9316774a7de0313265af883c2f51e477d751c7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ww117w/code-snippets/b263a1371a7e8cf2d914b756d62ff75d731d069f/stream-server-snippet/test-client.c",
"visit_date": "2023-06-26T00:13:36.445232"
}
|
stackv2
|
/*
* A simple TCP client to be used to capture data from the robot tracker application.
* The server stream out data using the format: XPOS,YPOS,HEADING,ITER,TIMESTAMP
* usage: tcpclient <host> <port>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define BUFSIZE 10
/* buffer to store incoming data */
char buf[BUFSIZE];
/* socket fd */
int sockfd;
/* initialize the connection to the server */
int init_client(char *hostname, int portno){
/* server vars */
struct sockaddr_in serveraddr;
struct hostent *server;
/* create the socket */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0) {
printf("ERROR opening socket!\n");
return -1;
}
/* get the server's DNS entry */
if ((server = gethostbyname(hostname)) == NULL) {
printf("ERROR, no such server %s!\n", hostname);
return -2;
}
/* build the server's structs */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(portno);
/* connect: create a connection with the server */
if (connect(sockfd,(struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0){
printf("ERROR connecting!\n");
return -3;
}
return 0;
}
int main(int argc, char **argv) {
/* number of bytes read */
int numbytes = 0;
/* check command line arguments */
if (argc != 3) {
fprintf(stderr,"usage: %s <hostname> <port>\n", argv[0]);
exit(EXIT_SUCCESS);
}
/* initialize client connection */
if(init_client(argv[1], atoi(argv[2]))!=0){
printf("Exiting.\n");
goto out;
}
/* print the server stream */
while(1){
/* clean the buffer */
bzero(buf, BUFSIZE);
/* read from socket */
if((numbytes = read(sockfd, buf, BUFSIZE))<0){
printf("ERROR reading from socket\n");
goto out;
}
/* for proper printing*/
buf[BUFSIZE]='\0';
printf("%s", buf);
}
out:
close(sockfd);
return (EXIT_SUCCESS);
}
| 3.0625 | 3 |
2024-11-18T22:09:58.655861+00:00
| 2023-05-31T23:22:47 |
db8f0cd0cf4491ca2745ddadc90e2c9e92261e1c
|
{
"blob_id": "db8f0cd0cf4491ca2745ddadc90e2c9e92261e1c",
"branch_name": "refs/heads/main",
"committer_date": "2023-05-31T23:22:47",
"content_id": "0d9c27989213bd40d02de61ef6dde1c448d41a6a",
"detected_licenses": [
"MIT"
],
"directory_id": "4a727ce379e9d21826895699d09164cdac4836d5",
"extension": "c",
"filename": "beezy.c",
"fork_events_count": 95,
"gha_created_at": "2018-11-09T22:21:21",
"gha_event_created_at": "2022-11-26T19:09:25",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 156924419,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1013,
"license": "MIT",
"license_type": "permissive",
"path": "/sample_exams/Exam1-202130/exam_code/beezy.c",
"provenance": "stackv2-0106.json.gz:46960",
"repo_name": "RHIT-CSSE/csse332",
"revision_date": "2023-05-31T23:22:47",
"revision_id": "7b9e292381062d25934c18210e6bbe7241392cdc",
"snapshot_id": "83e58d6c377e67d4cfcc37e2f20f18991c5063bf",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/RHIT-CSSE/csse332/7b9e292381062d25934c18210e6bbe7241392cdc/sample_exams/Exam1-202130/exam_code/beezy.c",
"visit_date": "2023-06-08T11:16:43.095931"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <string.h>
#include "say_hello.h"
#define MAX_HEATING_DEMONS 2
#define MAX_REPAIR_DEMONS 4
int
main(int argc, char **argv)
{
/* Let beezy say hello to you, he's a polite devil! */
/* say_hello(); */
/* you code goes here.... */
for(int i = 0; i < MAX_REPAIR_DEMONS; i++) {
int pid = fork();
if(pid == 0) {
// MANAGER
pid = fork();
if(pid == 0) {
// GRANDCHILD: REPAIR DEMON
// spwan the repair demon
execlp("./repair_demon", "./repair_demon", NULL);
perror("PANIC:");
exit(EXIT_FAILURE);
} else {
// MANAGER
int status;
wait(&status);
if(WEXITSTATUS(status) == 0) {
printf("SUCCESS\n");
} else {
printf("FAILURE\n");
}
exit(EXIT_SUCCESS);
}
} else {
// PARENT: BEEZY
// do nothing and continue with the loop
}
}
}
| 2.5 | 2 |
2024-11-18T22:09:58.835083+00:00
| 2021-01-27T07:05:25 |
171b6c3c632b0b4358d9f4af0d585898cf30ac6a
|
{
"blob_id": "171b6c3c632b0b4358d9f4af0d585898cf30ac6a",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-27T07:05:25",
"content_id": "a68dfbacc2e151e8f26da7181778cb32e88ab48a",
"detected_licenses": [
"MIT"
],
"directory_id": "abf04ca106526ed604fd0b1919e81c3848385a97",
"extension": "c",
"filename": "Drv7SegLed.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 333334165,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7723,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Drv7SegLed.c",
"provenance": "stackv2-0106.json.gz:47220",
"repo_name": "GitYun/lib_38decoder_7seg_led",
"revision_date": "2021-01-27T07:05:25",
"revision_id": "cc0f31226c68be02d7b42bfedfbf641eb576c301",
"snapshot_id": "3dc56339a34f2cc404d20c35f3fd5b6e4480dc35",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/GitYun/lib_38decoder_7seg_led/cc0f31226c68be02d7b42bfedfbf641eb576c301/src/Drv7SegLed.c",
"visit_date": "2023-02-22T04:09:40.768522"
}
|
stackv2
|
/**
* \file Drv7SegLed.c
* \author vEmagic (admin@vemagic.com)
* \brief
* \version 0.0.1
* \date 2020-11-01
*
* @copyright Copyright (c) 2020, Sichuan Deyang DeYi Electronic Instrument Co., Ltd.
*
*/
#include "main.h"
#include "Drv38Decoder.h"
#include "Lib.7SegLed.h"
/* TODO: 延时1ms刷新数码管 */
/* 由于此驱动对应的硬件需要逐段点亮数码管的LED, 故在点亮一段数码管的LED后延时100us,
* 利用余辉效应,看起来就如一个数码管的每段被同时点亮了; 一个数码管最多延时8x0.1ms=0.8ms */
#define DRV_ONE_7SEG_LED_DELAY_1MS() SysTick_uDelay(100)
/*< TODO: 38译码器到数码管映射的数量 */
#define NUMBER_38DECODER_TO_7SEG_LED_MAP 6
/*< TODO: 38译码器的A2A1A0输入到驱动数码管的输出编码 */
#define SSL_a 0x03
#define SSL_b 0x01
#define SSL_c 0x02
#define SSL_d 0x05
#define SSL_e 0x07
#define SSL_f 0x04
#define SSL_g 0x06
#define SSL_dp 0x0
#define SSL_off 0xFF
static const uint8_t pui8SSL_0[] = {SSL_a, SSL_b, SSL_c, SSL_d, SSL_e, SSL_f, SSL_dp};
static const uint8_t pui8SSL_1[] = {SSL_b, SSL_c, SSL_dp};
static const uint8_t pui8SSL_2[] = {SSL_a, SSL_b, SSL_d, SSL_e, SSL_g, SSL_dp};
static const uint8_t pui8SSL_3[] = {SSL_a, SSL_b, SSL_c, SSL_d, SSL_g, SSL_dp};
static const uint8_t pui8SSL_4[] = {SSL_b, SSL_c, SSL_f, SSL_g, SSL_dp};
static const uint8_t pui8SSL_5[] = {SSL_a, SSL_c, SSL_d, SSL_f, SSL_g, SSL_dp};
static const uint8_t pui8SSL_6[] = {SSL_a, SSL_c, SSL_d, SSL_e, SSL_f, SSL_g, SSL_dp};
static const uint8_t pui8SSL_7[] = {SSL_a, SSL_b, SSL_c, SSL_dp};
static const uint8_t pui8SSL_8[] = {SSL_a, SSL_b, SSL_c, SSL_d, SSL_e, SSL_f, SSL_g, SSL_dp};
static const uint8_t pui8SSL_9[] = {SSL_a, SSL_b, SSL_c, SSL_d, SSL_f, SSL_g, SSL_dp};
static const uint8_t pui8SSL_A[] = {SSL_a, SSL_b, SSL_c, SSL_e, SSL_f, SSL_g, SSL_dp};
static const uint8_t pui8SSL_b[] = {SSL_c, SSL_d, SSL_e, SSL_f, SSL_g, SSL_dp};
static const uint8_t pui8SSL_C[] = {SSL_a, SSL_d, SSL_e, SSL_f, SSL_dp};
static const uint8_t pui8SSL_d[] = {SSL_b, SSL_c, SSL_d, SSL_e, SSL_g, SSL_dp};
static const uint8_t pui8SSL_E[] = {SSL_a, SSL_d, SSL_e, SSL_f, SSL_g, SSL_dp};
static const uint8_t pui8SSL_F[] = {SSL_a, SSL_e, SSL_f, SSL_g, SSL_dp};
static const uint8_t pui8SSL_dp[]= {SSL_dp};
static const tInputEncode g_ps7SegLedFontEncode[CHARACTER_NUMBER] = {
{0, 6, pui8SSL_0}, // 0
{1, 2, pui8SSL_1}, // 1
{2, 5, pui8SSL_2}, // 2
{3, 5, pui8SSL_3}, // 3
{4, 4, pui8SSL_4}, // 4
{5, 5, pui8SSL_5}, // 5
{6, 6, pui8SSL_6}, // 6
{7, 3, pui8SSL_7}, // 7
{8, 7, pui8SSL_8}, // 8
{9, 6, pui8SSL_9}, // 9
{10, 6, pui8SSL_A}, // A
{11, 5, pui8SSL_b}, // b
{12, 4, pui8SSL_C}, // C
{13, 5, pui8SSL_d}, // d
{14, 5, pui8SSL_E}, // E
{15, 4, pui8SSL_F}, // F
{16, 1, pui8SSL_dp}, // The 7-segment led display only a '.'
};
static t38Decoder g_ps38Decoder[NUMBER_38DECODER_TO_7SEG_LED_MAP];
/*-----------------------------------------------------------------------------------------------*/
static void Drv7SegLed(t38Decoder* ps38Decoder, uint8_t ui8LedField);
/* Initial the 38-decoder */
t38Decoder* Drv38DecoderInit(uint8_t ui8Size)
{
uint8_t idx;
for (idx = 0; idx < NUMBER_38DECODER_TO_7SEG_LED_MAP && idx < ui8Size; ++idx)
{
g_ps38Decoder[idx].psInputEncode = (tInputEncode *)g_ps7SegLedFontEncode;
g_ps38Decoder[idx].pfnDecode = Drv7SegLed;
}
return g_ps38Decoder;
}
/*-----------------------------------------------------------------------------------------------*/
void DrvSevenSegLedOpen(void *pvDriver, uint8_t ui8DriverIdx)
{
t38Decoder *ps38Decoder = &((t38Decoder *)pvDriver)[ui8DriverIdx];
Drv38DecoderOpen(ps38Decoder);
}
/*-----------------------------------------------------------------------------------------------*/
void DrvSevenSegLedClose(void *pvDriver, uint8_t ui8DriverIdx)
{
t38Decoder *ps38Decoder = &((t38Decoder *)pvDriver)[ui8DriverIdx];
Drv38DecoderClose(ps38Decoder);
}
/*-----------------------------------------------------------------------------------------------*/
/* ui8Number range: 0 ~ (CHARACTER_NUMBER - 1) */
void DrvOneSevenSegLedUpdate(void* pvDriver, uint8_t ui87SegLedIndex,
uint8_t ui8Number, bool bShowDecimalPoint)
{
t38Decoder *ps38Decoder = &((t38Decoder *)pvDriver)[ui87SegLedIndex];
tInputEncode *psEncode = &ps38Decoder->psInputEncode[ui8Number % CHARACTER_NUMBER];
uint8_t size = psEncode->ui8Size;
uint8_t idx;
if (bShowDecimalPoint)
{
size += 1; // Display the decimal point
}
for (idx = 0; idx < size; ++idx)
{
ps38Decoder->pfnDecode(ps38Decoder, psEncode->pui8Encode[idx]);
}
// Eliminates the strong display of the last light up LED segment
DECODER_PIN_LOW(ps38Decoder->e3.sPort, ps38Decoder->e3.sPin);
}
/*-----------------------------------------------------------------------------------------------*/
static void Drv7SegLed(t38Decoder* ps38Decoder, uint8_t ui8LedField)
{
bool bEnable38Decoder = true;
// Eliminates Blanking
DECODER_PIN_LOW(ps38Decoder->e3.sPort, ps38Decoder->e3.sPin);
switch (ui8LedField)
{
case SSL_off:
bEnable38Decoder = false;
break;
case SSL_dp:
DECODER_PIN_LOW(ps38Decoder->a2.sPort, ps38Decoder->a2.sPin);
DECODER_PIN_LOW(ps38Decoder->a1.sPort, ps38Decoder->a1.sPin);
DECODER_PIN_LOW(ps38Decoder->a0.sPort, ps38Decoder->a0.sPin);
break;
case SSL_b:
DECODER_PIN_LOW(ps38Decoder->a2.sPort, ps38Decoder->a2.sPin);
DECODER_PIN_LOW(ps38Decoder->a1.sPort, ps38Decoder->a1.sPin);
DECODER_PIN_HIGH(ps38Decoder->a0.sPort, ps38Decoder->a0.sPin);
break;
case SSL_c:
DECODER_PIN_LOW(ps38Decoder->a2.sPort, ps38Decoder->a2.sPin);
DECODER_PIN_HIGH(ps38Decoder->a1.sPort, ps38Decoder->a1.sPin);
DECODER_PIN_LOW(ps38Decoder->a0.sPort, ps38Decoder->a0.sPin);
break;
case SSL_a:
DECODER_PIN_LOW(ps38Decoder->a2.sPort, ps38Decoder->a2.sPin);
DECODER_PIN_HIGH(ps38Decoder->a1.sPort, ps38Decoder->a1.sPin);
DECODER_PIN_HIGH(ps38Decoder->a0.sPort, ps38Decoder->a0.sPin);
break;
case SSL_f:
DECODER_PIN_HIGH(ps38Decoder->a2.sPort, ps38Decoder->a2.sPin);
DECODER_PIN_LOW(ps38Decoder->a1.sPort, ps38Decoder->a1.sPin);
DECODER_PIN_LOW(ps38Decoder->a0.sPort, ps38Decoder->a0.sPin);
break;
case SSL_d:
DECODER_PIN_HIGH(ps38Decoder->a2.sPort, ps38Decoder->a2.sPin);
DECODER_PIN_LOW(ps38Decoder->a1.sPort, ps38Decoder->a1.sPin);
DECODER_PIN_HIGH(ps38Decoder->a0.sPort, ps38Decoder->a0.sPin);
break;
case SSL_g:
DECODER_PIN_HIGH(ps38Decoder->a2.sPort, ps38Decoder->a2.sPin);
DECODER_PIN_HIGH(ps38Decoder->a1.sPort, ps38Decoder->a1.sPin);
DECODER_PIN_LOW(ps38Decoder->a0.sPort, ps38Decoder->a0.sPin);
break;
case SSL_e:
DECODER_PIN_HIGH(ps38Decoder->a2.sPort, ps38Decoder->a2.sPin);
DECODER_PIN_HIGH(ps38Decoder->a1.sPort, ps38Decoder->a1.sPin);
DECODER_PIN_HIGH(ps38Decoder->a0.sPort, ps38Decoder->a0.sPin);
break;
default:
// Whether use the previous input value
break;
}
if (bEnable38Decoder)
{
DECODER_PIN_HIGH(ps38Decoder->e3.sPort, ps38Decoder->e3.sPin);
DRV_ONE_7SEG_LED_DELAY_1MS();
}
}
/*-----------------------------------------------------------------------------------------------*/
| 2.0625 | 2 |
2024-11-18T22:09:58.906132+00:00
| 2023-08-12T19:08:59 |
d967e5c8f2db969939ce1904c20e0a29bc1ec961
|
{
"blob_id": "d967e5c8f2db969939ce1904c20e0a29bc1ec961",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-12T19:08:59",
"content_id": "a8ebbfec79626d708b64518dff4fdce83d5e8d06",
"detected_licenses": [
"MIT"
],
"directory_id": "8beeb98c38daf21f093e8f4c6dc244351d553a3e",
"extension": "c",
"filename": "test_set_value.c",
"fork_events_count": 1009,
"gha_created_at": "2010-12-04T22:17:02",
"gha_event_created_at": "2023-09-14T03:54:40",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 1139119,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4224,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/test_set_value.c",
"provenance": "stackv2-0106.json.gz:47348",
"repo_name": "json-c/json-c",
"revision_date": "2023-08-12T19:08:59",
"revision_id": "502522a93d0a111835094e4c62dbb41b64f2aca4",
"snapshot_id": "dbbc54fa6e0efbf2a7d969ed25115394a660d104",
"src_encoding": "UTF-8",
"star_events_count": 2607,
"url": "https://raw.githubusercontent.com/json-c/json-c/502522a93d0a111835094e4c62dbb41b64f2aca4/tests/test_set_value.c",
"visit_date": "2023-08-15T00:46:41.684553"
}
|
stackv2
|
#ifdef NDEBUG
#undef NDEBUG
#endif
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "json.h"
int main(int argc, char **argv)
{
json_object *tmp = json_object_new_int(123);
assert(json_object_get_int(tmp) == 123);
json_object_set_int(tmp, 321);
assert(json_object_get_int(tmp) == 321);
printf("INT PASSED\n");
json_object_set_int64(tmp, (int64_t)321321321);
assert(json_object_get_int64(tmp) == 321321321);
json_object_put(tmp);
printf("INT64 PASSED\n");
tmp = json_object_new_uint64(123);
assert(json_object_get_boolean(tmp) == 1);
assert(json_object_get_int(tmp) == 123);
assert(json_object_get_int64(tmp) == 123);
assert(json_object_get_uint64(tmp) == 123);
assert(json_object_get_double(tmp) == 123.000000);
json_object_set_uint64(tmp, (uint64_t)321321321);
assert(json_object_get_uint64(tmp) == 321321321);
json_object_set_uint64(tmp, 9223372036854775808U);
assert(json_object_get_int(tmp) == INT32_MAX);
assert(json_object_get_uint64(tmp) == 9223372036854775808U);
json_object_put(tmp);
printf("UINT64 PASSED\n");
tmp = json_object_new_boolean(1);
assert(json_object_get_boolean(tmp) == 1);
json_object_set_boolean(tmp, 0);
assert(json_object_get_boolean(tmp) == 0);
json_object_set_boolean(tmp, 1);
assert(json_object_get_boolean(tmp) == 1);
json_object_put(tmp);
printf("BOOL PASSED\n");
tmp = json_object_new_double(12.34);
assert(json_object_get_double(tmp) == 12.34);
json_object_set_double(tmp, 34.56);
assert(json_object_get_double(tmp) == 34.56);
json_object_set_double(tmp, 6435.34);
assert(json_object_get_double(tmp) == 6435.34);
json_object_set_double(tmp, 2e21);
assert(json_object_get_int(tmp) == INT32_MAX);
assert(json_object_get_int64(tmp) == INT64_MAX);
assert(json_object_get_uint64(tmp) == UINT64_MAX);
json_object_set_double(tmp, -2e21);
assert(json_object_get_int(tmp) == INT32_MIN);
assert(json_object_get_int64(tmp) == INT64_MIN);
assert(json_object_get_uint64(tmp) == 0);
json_object_put(tmp);
printf("DOUBLE PASSED\n");
#define SHORT "SHORT"
#define MID "A MID STRING"
// 12345678901234567890123456789012....
#define HUGE "A string longer than 32 chars as to check non local buf codepath"
tmp = json_object_new_string(MID);
assert(strcmp(json_object_get_string(tmp), MID) == 0);
assert(strcmp(json_object_to_json_string(tmp), "\"" MID "\"") == 0);
json_object_set_string(tmp, SHORT);
assert(strcmp(json_object_get_string(tmp), SHORT) == 0);
assert(strcmp(json_object_to_json_string(tmp), "\"" SHORT "\"") == 0);
json_object_set_string(tmp, HUGE);
assert(strcmp(json_object_get_string(tmp), HUGE) == 0);
assert(strcmp(json_object_to_json_string(tmp), "\"" HUGE "\"") == 0);
json_object_set_string(tmp, SHORT);
assert(strcmp(json_object_get_string(tmp), SHORT) == 0);
assert(strcmp(json_object_to_json_string(tmp), "\"" SHORT "\"") == 0);
// Set an empty string a couple times to try to trigger
// a case that used to leak memory.
json_object_set_string(tmp, "");
json_object_set_string(tmp, HUGE);
json_object_set_string(tmp, "");
json_object_set_string(tmp, HUGE);
json_object_put(tmp);
printf("STRING PASSED\n");
#define STR "STR"
#define DOUBLE "123.123"
#define DOUBLE_E "12E+3"
#define DOUBLE_STR "123.123STR"
#define DOUBLE_OVER "1.8E+308"
#define DOUBLE_OVER_NEGATIVE "-1.8E+308"
tmp = json_object_new_string(STR);
assert(json_object_get_double(tmp) == 0.0);
json_object_set_string(tmp, DOUBLE);
assert(json_object_get_double(tmp) == 123.123000);
json_object_set_string(tmp, DOUBLE_E);
assert(json_object_get_double(tmp) == 12000.000000);
json_object_set_string(tmp, DOUBLE_STR);
assert(json_object_get_double(tmp) == 0.0);
json_object_set_string(tmp, DOUBLE_OVER);
assert(json_object_get_double(tmp) == 0.0);
json_object_set_string(tmp, DOUBLE_OVER_NEGATIVE);
assert(json_object_get_double(tmp) == 0.0);
json_object_put(tmp);
printf("STRINGTODOUBLE PASSED\n");
tmp = json_tokener_parse("1.234");
json_object_set_double(tmp, 12.3);
const char *serialized = json_object_to_json_string(tmp);
fprintf(stderr, "%s\n", serialized);
assert(strncmp(serialized, "12.3", 4) == 0);
json_object_put(tmp);
printf("PARSE AND SET PASSED\n");
printf("PASSED\n");
return 0;
}
| 2.453125 | 2 |
2024-11-18T22:09:59.180885+00:00
| 2021-09-09T16:06:05 |
f95a30b21391079153ae48c98c6c4899b033a9c0
|
{
"blob_id": "f95a30b21391079153ae48c98c6c4899b033a9c0",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-09T16:06:05",
"content_id": "9db13f55d6085f5b8534947c6112f14c97eb7d5f",
"detected_licenses": [
"MIT"
],
"directory_id": "ca23690dac2c73054fe068a727028879c9396529",
"extension": "c",
"filename": "bainari.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 351738757,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7666,
"license": "MIT",
"license_type": "permissive",
"path": "/src/bainari.c",
"provenance": "stackv2-0106.json.gz:47865",
"repo_name": "aidencuneo/Bainari",
"revision_date": "2021-09-09T16:06:05",
"revision_id": "41a9e1b28e1c8e01a9b77b1cd1fe8386c161cd6d",
"snapshot_id": "f5749972a4118a15019595bd76718422483b0bed",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aidencuneo/Bainari/41a9e1b28e1c8e01a9b77b1cd1fe8386c161cd6d/src/bainari.c",
"visit_date": "2023-08-05T07:45:31.836127"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "bainari.h"
#include "stack.c"
#include "varlist.c"
#include "var.c"
char * current_file;
char * buffer = 0;
// Current index in the script
int fileIndex = 0;
// FILE * file_descriptor;
struct stack * stack;
// struct varlist * varlist;
int ptr0 = 0;
int ptr1 = 0;
int ptr2 = 0;
// Arg pointer sign (default: +)
// (Used to enable subtraction from ptr1)
int argSign = 1;
// CLI Options
int minify = 0;
int verbose = 0;
void error(char * text, char * buffer, int pos)
{
// int MAXLINE = 128;
printf("\nProgram execution terminated:\n\n");
if (buffer == NULL || pos < 0)
{
printf("(At %s)\n", current_file);
}
else
{
char * linepreview = malloc(5 + 1);
linepreview[0] = buffer[pos - 2];
linepreview[1] = buffer[pos - 1];
linepreview[2] = buffer[pos];
linepreview[3] = buffer[pos + 1];
linepreview[4] = buffer[pos + 2];
linepreview[5] = 0;
printf("At %s : Pos %d\n\n", current_file, pos);
printf("> {{ %s }}\n\n", linepreview);
free(linepreview);
}
printf("Error: %s\n\n", text);
quit(1);
}
char * minify_code(char * code)
{
int len = strlen(code);
char * min = malloc(len + 1);
min[0] = 0;
int ind = 0;
int comment = 0;
for (int i = 0; i < len; i++)
{
if (code[i] == '#')
comment = 1;
else if (code[i] == '\n')
comment = 0;
if (comment)
continue;
if (code[i] == '0' || code[i] == '1')
min[ind++] = code[i];
}
min[ind] = 0;
return min;
}
void quit(int code)
{
free(stack->items);
free(stack);
// free(varlist->names);
// free(varlist->values);
// free(varlist);
free(buffer);
exit(code);
}
void run_instruction()
{
// instPtr tells this function which pointer should be used as the opcode
int opcode = ptr0;
int arg = ptr1;
// opcode is now the operation code to perform, and arg is the argument
// that will be used with the operation
if (verbose)
printf("OPCODE: %d\n", opcode);
// (0) Set arg pointer to 0
if (opcode == 0)
ptr1 = 0;
// (1) Do nothing (not required anymore)
// (2) Push arg to the stack
else if (opcode == 2)
push(stack, arg);
// (3) Set the arg pointer to the next stack item (after popping)
else if (opcode == 3)
ptr1 = pop(stack);
// (4) Set the arg pointer to the first stack item (after popping)
else if (opcode == 4)
ptr1 = popBottom(stack);
// (5) Go back arg letters if the next stack item is not zero
else if (opcode == 5)
fileIndex -= arg * !!peek(stack);
// (6) Go forward arg letters if the next stack item is not zero
else if (opcode == 6)
fileIndex += arg * !!peek(stack);
// (6) Kill the program with arg as the exit code
// else if (opcode == 6)
// quit(arg);
// (7) Print the integer value of arg
else if (opcode == 7)
printf("%d", arg);
// (8) Print arg as a character
else if (opcode == 8)
printf("%c", arg);
// (9) Add arg to ptr2 (ptr2 += arg)
else if (opcode == 9)
ptr2 += arg;
// (10) Subtract the next stack item from arg (arg -= peek(stack))
else if (opcode == 10)
ptr1 -= peek(stack);
// (11) Multiply the next stack item with arg (arg *= peek(stack))
else if (opcode == 11)
ptr1 *= peek(stack);
// (12) Divide arg into the next stack item (arg /= peek(stack))
else if (opcode == 12)
ptr1 /= peek(stack);
// (13) Flip arg sign (+ to - and vice versa)
else if (opcode == 13)
argSign = -argSign;
// (13) Swap ptr2 and arg
// else if (opcode == 14)
// {
// int temp = ptr2;
// ptr2 = arg;
// if (instPtr)
// ptr0 = temp;
// else
// ptr1 = temp;
// }
}
int main(int argc, char ** argv)
{
char ** args = malloc(argc * sizeof(char *));
int newargc = 0;
for (int i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version"))
{
printf("Char %s\n", VERSION);
free(args);
return 0;
}
if (!strcmp(argv[i], "-m") || !strcmp(argv[i], "--minify"))
minify = 1;
if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--verbose"))
verbose = 1;
else
{
args[newargc] = argv[i];
newargc++;
}
}
if (!newargc)
return 0;
current_file = args[0];
long length;
FILE * f = fopen(current_file, "rb");
if (!f)
{
printf("File at path '%s' does not exist or is not accessible\n", current_file);
return 1;
}
fseek(f, 0, SEEK_END);
length = ftell(f);
fseek(f, 0, SEEK_SET);
buffer = malloc(length);
if (buffer)
fread(buffer, 1, length, f);
fclose(f);
if (!buffer)
return 0;
// Minify the whole program before running it
char * minified = minify_code(buffer);
free(buffer);
// Buffer now contains minified code
buffer = minified;
length = strlen(buffer);
if (minify)
{
printf("%s\n", buffer);
free(buffer);
return 0;
}
free(args);
// Interpreter vars
stack = newStack(512); // Block size is 512
// (Pointers are also global but are not defined here)
// (fileIndex is global)
for (fileIndex = 0; fileIndex < length; fileIndex++)
{
char ch = buffer[fileIndex];
if (verbose && (ch == '0' || ch == '1'))
{
printf("[%c] ptr0: %d, ptr1: %d, [", ch, ptr0, ptr1);
for (int a = 0; a < stack->top + 1; a++)
printf("%d,", stack->items[a]);
if (stack->top + 1)
printf("\b");
printf("]\n");
}
if (ch == '0')
{
// Temporary variable for shorter code
int i = fileIndex;
// If 0000 was found
if (i > 2 && buffer[i] + buffer[i - 1] + buffer[i - 2] + buffer[i - 3] == '0' * 4)
{
// Cancel if the character before this 0000 group is also a 0
if (i > 3 && buffer[i - 4] == '0')
{
++ptr0;
continue;
}
// Take away 3 from ptr0 to cancel what happens due to 0000
// executing as three ptr0 additions
ptr0 -= 3;
run_instruction();
// Reset ptr0 to 0
ptr0 = 0;
continue;
}
// Otherwise, handle instruction normally and set lastInst to 0
++ptr0;
}
else if (ch == '1')
{
// 111 was found
// if (secondLastInst == 1 && lastInst == 1)
// {
// // Take away 2 from ptr1 to counter what happens due to 111
// // executing as two ptr1 additions
// ptr1 -= 2;
// run_instruction(1);
// // Reset ptr1 to 0
// ptr1 = 0;
// secondLastInst = lastInst;
// lastInst = -1;
// continue;
// }
// Handle instruction normally and set lastInst to 1
// Since ptr1 is the arg pointer, add the arg sign to ptr1
ptr1 += argSign;
}
}
quit(0);
return 0;
}
| 3.046875 | 3 |
2024-11-18T22:09:59.381871+00:00
| 2021-05-30T15:36:04 |
71fdb1ef64a204a66027ce5fb08a3d1a0162e52a
|
{
"blob_id": "71fdb1ef64a204a66027ce5fb08a3d1a0162e52a",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-30T15:36:04",
"content_id": "163bf9d385ff5f4f5ff6d7ec7b939da399c86334",
"detected_licenses": [
"MIT"
],
"directory_id": "a803f6a8aaa3cdb509f49862087d7e5a3173ef2f",
"extension": "h",
"filename": "engine.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 210855663,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2263,
"license": "MIT",
"license_type": "permissive",
"path": "/src/engine.h",
"provenance": "stackv2-0106.json.gz:48123",
"repo_name": "ronaldosvieira/narset",
"revision_date": "2021-05-30T15:36:04",
"revision_id": "e26dca76a6bbb6cb561c6fc15176b23781e911f7",
"snapshot_id": "99402d0e7b2d860760eb801def9888bf18d21734",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ronaldosvieira/narset/e26dca76a6bbb6cb561c6fc15176b23781e911f7/src/engine.h",
"visit_date": "2023-05-09T13:44:15.476331"
}
|
stackv2
|
#ifndef NARSET_ENGINE_H
#define NARSET_ENGINE_H
#define FALSE 0
#define TRUE 1
#define NONE -1
#define UNKNOWN -99
typedef int Bool;
#define PASS 0
#define PICK 1
#define SUMMON 2
#define USE 3
#define ATTACK 4
typedef int ActionType;
typedef struct Action {
ActionType type;
int origin, target;
} Action;
#define CREATURE 0
#define GREEN_ITEM 1
#define RED_ITEM 2
#define BLUE_ITEM 3
typedef int CardType;
#define OUTSIDE (-1)
#define P0_HAND 0
#define P0_BOARD 8
#define P1_BOARD 14
#define P1_HAND 20
#define LEFT_LANE 0
#define RIGHT_LANE 3
typedef int Location;
#define BREAKTHROUGH 0
#define CHARGE 1
#define DRAIN 2
#define GUARD 3
#define LETHAL 4
#define WARD 5
typedef unsigned char Keyword;
typedef struct Card {
int id, instance_id;
CardType type;
int cost, attack, defense, player_hp, enemy_hp, card_draw, lane;
unsigned char keywords;
Location location;
Bool can_attack;
} Card;
typedef struct Player {
int id;
int health, base_mana, bonus_mana, mana, next_rune, bonus_draw;
int deck_size, hand_size, left_lane_size, right_lane_size;
} Player;
# define MAX_CARDS_HAND 8
# define MAX_CARDS_LANE 3
# define MAX_CARDS_BOARD 6
# define CARDS_IN_STATE ((MAX_CARDS_HAND + MAX_CARDS_BOARD) * 2)
# define CARDS_IN_DECK 30
#define SUMMON_START_INDEX 1
#define USE_START_INDEX 17
#define ATTACK_START_INDEX 73
typedef struct State {
int round;
Player *current_player, *opposing_player;
Player players[2];
Card cards[CARDS_IN_STATE];
Card decks[2][CARDS_IN_DECK];
Card *player_hand, *opp_hand;
Card *player_board, *opp_board;
Bool valid_actions[97];
int winner;
} State;
/* Card functions */
Bool has_keyword(Card card, Keyword keyword);
void add_keyword(Card* card, Keyword keyword);
void remove_keyword(Card* card, Keyword keyword);
int damage_creature(Card* creature, int amount);
/* Player functions */
void init_player(Player* player, int id);
int damage_player(Player* player, int amount);
/* State functions */
State* new_state();
int calculate_valid_actions(State* state);
void act_on_state(State* state, int action_index);
State* copy_state(State* from, State* to);
/* Util functions */
Action decode_action(int action);
#endif //NARSET_ENGINE_H
| 2.0625 | 2 |
2024-11-18T22:09:59.728779+00:00
| 2023-08-10T19:48:51 |
dc09e167317cea3f8680e5f365833f7bf8d0bd61
|
{
"blob_id": "dc09e167317cea3f8680e5f365833f7bf8d0bd61",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-10T19:48:51",
"content_id": "1523e0bec6f9df595cb1889e6dfb272c48999698",
"detected_licenses": [
"MIT"
],
"directory_id": "bc1361593eb147f7f823ae3272f1810b6d13c350",
"extension": "c",
"filename": "hb_log_console.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 211671347,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 962,
"license": "MIT",
"license_type": "permissive",
"path": "/src/hb_log_console/hb_log_console.c",
"provenance": "stackv2-0106.json.gz:48638",
"repo_name": "irov/hummingbird",
"revision_date": "2023-08-10T19:48:51",
"revision_id": "77e0550b70a73dc02d56bef5b94d355bd5b84df8",
"snapshot_id": "9473f8647c5937249bd64da13deb396d28b28468",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/irov/hummingbird/77e0550b70a73dc02d56bef5b94d355bd5b84df8/src/hb_log_console/hb_log_console.c",
"visit_date": "2023-08-21T12:50:27.117846"
}
|
stackv2
|
#include "hb_log_console.h"
#include <stdio.h>
//////////////////////////////////////////////////////////////////////////
static void __hb_log_observer( const char * _category, hb_log_level_t _level, const char * _file, uint32_t _line, const char * _message, void * _ud )
{
HB_UNUSED( _ud );
const char * ls = hb_log_level_string[_level];
printf( "%s [%s:%u] %s: %s\n", ls, _file, _line, _category, _message );
}
//////////////////////////////////////////////////////////////////////////
hb_result_t hb_log_console_initialize()
{
if( hb_log_add_observer( HB_NULLPTR, HB_LOG_ALL, &__hb_log_observer, HB_NULLPTR ) == HB_FAILURE )
{
return HB_FAILURE;
}
return HB_SUCCESSFUL;
}
//////////////////////////////////////////////////////////////////////////
void hb_log_console_finalize()
{
hb_log_remove_observer( &__hb_log_observer, HB_NULLPTR );
}
//////////////////////////////////////////////////////////////////////////
| 2.0625 | 2 |
2024-11-18T22:10:00.532444+00:00
| 2021-03-17T02:56:52 |
861339533a0852983d50559ffda47836be636888
|
{
"blob_id": "861339533a0852983d50559ffda47836be636888",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-17T02:56:52",
"content_id": "41cb23ba3311d3ec1c1839abdbde48feb4248531",
"detected_licenses": [
"MIT"
],
"directory_id": "91a471cb831df97d200574d5016ad24b0b84a8ca",
"extension": "c",
"filename": "strstr.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 336133285,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1786,
"license": "MIT",
"license_type": "permissive",
"path": "/libjr/missing/strstr.c",
"provenance": "stackv2-0106.json.gz:48766",
"repo_name": "frankjas/srcjr",
"revision_date": "2021-03-17T02:56:52",
"revision_id": "4c0da568b899f120abfbe6e17c3a8277946c6d09",
"snapshot_id": "fe3a3a4f0d0c70167ed427514851c4e21cafe5c4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/frankjas/srcjr/4c0da568b899f120abfbe6e17c3a8277946c6d09/libjr/missing/strstr.c",
"visit_date": "2023-03-14T15:43:39.668774"
}
|
stackv2
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <string.h>
#include <ctype.h>
/*
* This routine conforms to the ANSI standard
* description for 'strstr(string,pattern)'
* used for finding a substring pattern in
* a larger string. We provide the source because
* some C environments are not provided with all
* of the ANSI specified routines.
*/
#ifdef missing_strstr
char *strstr(string,pattern) /* position of pattern in string */
const char *string ;
const char *pattern ;
{
jr_int patlen = strlen( pattern ) ;
jr_int match = 0 ;
char *strptr = (char *) string ;
if (*pattern == '\0') return((char *) string) ;
if (*string == '\0') return(0) ;
while((strptr = (char *) strchr(strptr,*pattern)) != 0) {
if(strncmp(strptr,pattern,patlen) == 0) {
match = 1 ;
break ;
}
strptr++ ;
}
return( match ? strptr : 0 ) ;
}
#else
static void NotCalled () /* define this so ranlib doesn't complain */
{
NotCalled (); /* use it so the compiler doesn't complain */
}
#endif
#ifdef missing_strcasestr
static char *strcasechr(
const char * string,
int search_char)
{
for (; *string; string++) {
if (tolower( *string) == tolower( search_char)) {
return (char *) string;
}
}
if (search_char == 0) {
return (char *) string;
}
return 0;
}
char *strcasestr(string,pattern) /* position of pattern in string */
const char *string ;
const char *pattern ;
{
jr_int patlen = strlen( pattern ) ;
jr_int match = 0 ;
char *strptr = (char *) string ;
if (*pattern == '\0') return((char *) string) ;
if (*string == '\0') return(0) ;
while((strptr = (char *) strcasechr(strptr,*pattern)) != 0) {
if(strncasecmp(strptr,pattern,patlen) == 0) {
match = 1 ;
break ;
}
strptr++ ;
}
return( match ? strptr : 0 ) ;
}
#endif
| 2.765625 | 3 |
2024-11-18T22:10:00.635238+00:00
| 2016-07-04T12:31:53 |
f84afab207709ac03fbf82823cb2d0f7b1595013
|
{
"blob_id": "f84afab207709ac03fbf82823cb2d0f7b1595013",
"branch_name": "refs/heads/master",
"committer_date": "2016-07-04T12:31:53",
"content_id": "a84bfd380a0b6ee4526101ddf574883735d347c5",
"detected_licenses": [
"MIT"
],
"directory_id": "66b6774a4cd205e14280e159b32193d4865011ac",
"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": 1848,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/arithmetic/src/main.c",
"provenance": "stackv2-0106.json.gz:48895",
"repo_name": "shammellee/6502",
"revision_date": "2016-07-04T12:31:53",
"revision_id": "41937cc2331c5af4a55a18ec91f6573344a5df5b",
"snapshot_id": "65289488caf9e15b2e3d199af39588d477f88032",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/shammellee/6502/41937cc2331c5af4a55a18ec91f6573344a5df5b/tests/arithmetic/src/main.c",
"visit_date": "2020-03-19T00:41:01.224864"
}
|
stackv2
|
/**
* The MIT License (MIT)
* Copyright (c) 2016 Chaabane Jalal
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include "spi/cpu/cpu_6502.h"
#include "constants.h"
#include "test_adc.h"
static spi_program_config_t prg_16k() {
spi_program_config_t cfg;
cfg.load_addr = 0xC000;
cfg.prg_size = 16 * 1024;
cfg.reset_vector_offset = 0xFFFC;
cfg.stack_addr = 0x100;
return cfg;
}
int main(int ac, char **av) {
spi_byte_t memory[MEM_SIZE];
spi_cpu_t cpu;
const spi_program_config_t cfg = prg_16k();
bzero(memory, MEM_SIZE);
spi_cpu_init(&cpu, 20, MHZ);
spi_dump_memory(memory, MEM_SIZE, 0xFFFC, 0xFFFF);
spi_cpu_reset(&cpu, memory, &cfg);
spi_run_test_adc(&cpu, memory);
return 0;
}
| 2 | 2 |
2024-11-18T22:10:05.100914+00:00
| 2021-08-29T02:04:17 |
07be0a239e5311aa018c499d56a4dc2718d158cf
|
{
"blob_id": "07be0a239e5311aa018c499d56a4dc2718d158cf",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-29T02:04:17",
"content_id": "c184a7a32fc1c0cbe8a413b90f5dd9cf497bb963",
"detected_licenses": [
"MIT"
],
"directory_id": "218939403a4bd9dcbab6a777306fd5c9910a9efa",
"extension": "c",
"filename": "plurality.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 400929706,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2711,
"license": "MIT",
"license_type": "permissive",
"path": "/pset3/plurality/plurality.c",
"provenance": "stackv2-0106.json.gz:49024",
"repo_name": "Danilo-Xaxa/desafios_c",
"revision_date": "2021-08-29T02:04:17",
"revision_id": "a0c1a20963ddc111bbb901fdda1e03bc85a8c744",
"snapshot_id": "5fa82e70481184b478df5fe0914977873ee033cb",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Danilo-Xaxa/desafios_c/a0c1a20963ddc111bbb901fdda1e03bc85a8c744/pset3/plurality/plurality.c",
"visit_date": "2023-07-17T20:14:35.175099"
}
|
stackv2
|
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Max number of candidates
#define MAX 9
// Candidates have name and vote count
typedef struct
{
string name;
int votes;
}
candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates
int candidate_count;
// My own variables (in portuguese)
int maior = 0;
string vencedor;
bool mais_vencedores = false;
string outros_vencedores[MAX];
int cont_outros_vencedores = 0;
// Function prototypes
bool vote(string name);
void print_winner(void);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: plurality [candidate ...]\n");
return 1;
}
// Populate array of candidates
candidate_count = argc - 1;
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %i\n", MAX);
return 2;
}
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
}
int voter_count = get_int("Number of voters: ");
// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
// Check for invalid vote
if (!vote(name))
{
printf("Invalid vote.\n");
}
}
// Display winner of election
print_winner();
}
// Update vote totals given a new vote
bool vote(string name)
{
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(candidates[i].name, name) == 0)
{
candidates[i].votes += 1;
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
// criando a lista com todas a qtd de votos de todos os candidatos
int lista_votos[candidate_count];
for (int i = 0; i < candidate_count; i++)
{
lista_votos[i] = candidates[i].votes;
}
for (int i = 0; i < candidate_count; i++)
{
if (lista_votos[i] > maior) // pegando a maior qtd de votos e o nome do vencedor
{
maior = lista_votos[i];
vencedor = candidates[i].name;
}
else if (lista_votos[i] == maior) // pegando os outros vencedores
{
mais_vencedores = true;
outros_vencedores[cont_outros_vencedores] = candidates[i].name;
cont_outros_vencedores++;
}
}
printf("%s\n", vencedor); // printando o vencedor
if (mais_vencedores)
{
for (int i = 0; i < cont_outros_vencedores; i++)
{
printf("%s\n", outros_vencedores[i]); // printando os outros vencedores
}
}
return;
}
| 3.34375 | 3 |
2024-11-18T22:10:05.215326+00:00
| 2021-11-28T13:05:46 |
dcfa0e78ac4521372a9d1e97b0c9de03aebda0fe
|
{
"blob_id": "dcfa0e78ac4521372a9d1e97b0c9de03aebda0fe",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-28T13:05:46",
"content_id": "ec11c3a5a749c4a94e60af0b848e05bd6ce5f775",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "9368f1bc30ef17e1ed058f71d31d6e377e2a9cb8",
"extension": "c",
"filename": "info.c",
"fork_events_count": 1,
"gha_created_at": "2014-11-16T02:51:08",
"gha_event_created_at": "2021-11-28T13:05:47",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 26701637,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2086,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/test/info.c",
"provenance": "stackv2-0106.json.gz:49152",
"repo_name": "Terminus-IMRC/mailbox",
"revision_date": "2021-11-28T13:05:46",
"revision_id": "035c2a00ed8ce0f9262a689ed401970f130c4771",
"snapshot_id": "b605d8f6840d0753a5d04ace5584d7fe8deb2c14",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/Terminus-IMRC/mailbox/035c2a00ed8ce0f9262a689ed401970f130c4771/test/info.c",
"visit_date": "2021-12-14T09:00:26.187340"
}
|
stackv2
|
/*
* Copyright (c) 2018 Idein Inc. ( http://idein.jp/ )
* All rights reserved.
*
* This software is licensed under a Modified (3-Clause) BSD License.
* You should have received a copy of this license along with this
* software. If not, contact the copyright holder above.
*/
#include "mailbox.h"
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <time.h>
int main(void)
{
int mbfd;
int err;
mbfd = mailbox_open();
if (mbfd == -1)
return 1;
{
uint32_t rev;
time_t t;
char s[256];
err = mailbox_get_firmware_revision(mbfd, &rev);
if (err)
return err;
t = (time_t) rev;
strftime(s, sizeof(s), "%b %e %Y %T", gmtime(&t));
printf("Firmware revision: %s\n", s);
}
{
uint32_t model;
err = mailbox_get_board_model(mbfd, &model);
if (err)
return err;
printf("Board model: 0x%08" PRIx32 "\n", model);
}
{
uint32_t rev;
err = mailbox_get_board_revision(mbfd, &rev);
if (err)
return err;
printf("Board revision: 0x%08" PRIx32 "\n", rev);
}
{
uint64_t mac;
err = mailbox_get_board_mac_address(mbfd, &mac);
if (err)
return err;
printf("Board MAC address: %012" PRIx64 "\n", mac);
}
{
uint64_t serial;
err = mailbox_get_board_serial(mbfd, &serial);
if (err)
return err;
printf("Board serial: 0x%" PRIx64 "\n", serial);
}
{
uint32_t base, size;
err = mailbox_get_arm_memory(mbfd, &base, &size);
if (err)
return err;
printf("ARM memory: 0x%08" PRIx32 " bytes at 0x%08" PRIx32 "\n",
size, base);
}
{
uint32_t base, size;
err = mailbox_get_vc_memory(mbfd, &base, &size);
if (err)
return err;
printf("VC memory: 0x%08" PRIx32 " bytes at 0x%08" PRIx32 "\n",
size, base);
}
err = mailbox_close(mbfd);
return err;
}
| 2.53125 | 3 |
2024-11-18T22:10:05.390693+00:00
| 2014-10-24T14:18:47 |
3c97029fd755c6539d4723e46b0dfd950a060f62
|
{
"blob_id": "3c97029fd755c6539d4723e46b0dfd950a060f62",
"branch_name": "refs/heads/master",
"committer_date": "2014-10-24T14:18:47",
"content_id": "0d73ad5b3c187044306051292097d5dd2d907735",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "830d19615851513ca8b563e2653e8a0d3a1d4074",
"extension": "h",
"filename": "list.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": 1188,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/drivers/virtio/include/linux/list.h",
"provenance": "stackv2-0106.json.gz:49410",
"repo_name": "objectkuan/osv-dde",
"revision_date": "2014-10-24T14:18:47",
"revision_id": "295ade6050f3860b7863323b078473e0d11bf323",
"snapshot_id": "da950b2a321aaa125c8877a6c63bf4edc9c0ccc3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/objectkuan/osv-dde/295ade6050f3860b7863323b078473e0d11bf323/drivers/virtio/include/linux/list.h",
"visit_date": "2021-01-01T05:47:28.018482"
}
|
stackv2
|
#ifndef __LINUX_LIST_H__
#define __LINUX_LIST_H__
/*4*/ #include <linux/types.h>
/*5*/ #include <linux/stddef.h>
/*7*/ #include <linux/const.h>
/*19*/ #define LIST_HEAD_INIT(name) { &(name), &(name) }
/*21*/ #define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name)
/*28*/ void INIT_LIST_HEAD(struct list_head * a);
/*63*/ void list_add(struct list_head * a, struct list_head * b);
/*77*/ void list_add_tail(struct list_head * a, struct list_head * b);
/*109*/ void list_del(struct list_head * a);
/*189*/ int list_empty(const struct list_head * a);
/*350*/ #define list_entry(ptr,type,member) container_of(ptr, type, member)
/*361*/ #define list_first_entry(ptr,type,member) list_entry((ptr)->next, type, member)
/*418*/ #define list_for_each_entry(pos,head,member) for (pos = list_entry((head)->next, typeof(*pos), member); &pos->member != (head); pos = list_entry(pos->member.next, typeof(*pos), member))
/*492*/ #define list_for_each_entry_safe(pos,n,head,member) for (pos = list_entry((head)->next, typeof(*pos), member), n = list_entry(pos->member.next, typeof(*pos), member); &pos->member != (head); pos = n, n = list_entry(n->member.next, typeof(*n), member))
#endif
| 2.015625 | 2 |
2024-11-18T22:10:05.465163+00:00
| 2019-05-13T13:40:29 |
2d22b7ea4851d46be7920b9d555229958b97b928
|
{
"blob_id": "2d22b7ea4851d46be7920b9d555229958b97b928",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-13T13:40:29",
"content_id": "7cc6962141ac2458039b76ae1d23407b044f578b",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "2818e84c898daa580ce32b99a1d2bd295b2481de",
"extension": "h",
"filename": "gatt_api.h",
"fork_events_count": 1,
"gha_created_at": "2020-06-02T07:54:18",
"gha_event_created_at": "2020-06-02T07:54:19",
"gha_language": null,
"gha_license_id": null,
"github_id": 268736789,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8868,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/stack/ble/gatt/gatt_api.h",
"provenance": "stackv2-0106.json.gz:49540",
"repo_name": "silan-wireless/FR801x-SDK",
"revision_date": "2019-05-13T13:40:29",
"revision_id": "073b08fe21bb8423d7037641fcdd72421e96a596",
"snapshot_id": "6017bc2b04d4349a746c60165bc1e13eaed38725",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/silan-wireless/FR801x-SDK/073b08fe21bb8423d7037641fcdd72421e96a596/stack/ble/gatt/gatt_api.h",
"visit_date": "2022-01-26T05:44:35.196994"
}
|
stackv2
|
/**
* Copyright (c) 2019, Tsingtao Freqchip
*
* All rights reserved.
*
*
*/
#ifndef GATT_API_H
#define GATT_API_H
/*
* INCLUDES (包含头文件)
*/
/*
* MACROS (宏定义)
*/
/*
* CONSTANTS (常量定义)
*/
#define UUID_SIZE_2 2 //!< 2 bytes UUID, usually SIG assigned UUID. 2字节的UUID, 通常是SIG指定.
#define UUID_SIZE_16 16 //!< 16 bytes UUID, usually assigned by users. 16字节的UUID, 通常是由用户自定义.
/** @defgroup GATT_PROP_BITMAPS_DEFINES GATT Attribute Access Permissions Bit Fields
* @{
*/
#define GATT_PROP_READ 0x0001 //!< Attribute is Readable
#define GATT_PROP_WRITE 0x0002 //!< Attribute is Writable
#define GATT_PROP_AUTHEN_READ 0x0004 //!< Read requires Authentication
#define GATT_PROP_AUTHEN_WRITE 0x0008 //!< Write requires Authentication
#define GATT_PROP_AUTHOR_READ 0x0010 //!< Read requires Authorization
#define GATT_PROP_AUTHOR_WRITE 0x0020 //!< Write requires Authorization
#define GATT_PROP_ENCRYPT_READ 0x0040 //!< Read requires Encryption
#define GATT_PROP_ENCRYPT_WRITE 0x0080 //!< Write requires Encryption
#define GATT_PROP_NOTIFICATION 0x0100 //!< Attribute is able to send notification
#define GATT_PROP_INDICATION 0x0200 //!< Attribute is able to send indication
/** @} End GATT_PERMIT_BITMAPS_DEFINES */
/*
* TYPEDEFS (类型定义)
*/
/*********************************************************************
* @fn gatt_read_handler
*
* @brief User application handles read request in this callback.
* 应用层在这个回调函数里面处理读的请求。
*
* @param p_read - the pointer to read buffer. NOTE: It's just a pointer from lower layer, please create the buffer in application layer.
* 指向读缓冲区的指针。 请注意这只是一个指针,请在应用程序中分配缓冲区. 为输出函数, 因此为指针的指针.
* len - the pointer to the length of read buffer. Application to assign it.
* 读缓冲区的长度,用户应用程序去给它赋值.
* att_idx - offset of the attribute value.
* Attribute的偏移量.
*
* @return 读请求的长度.
*/
typedef uint16_t (*gatt_read_handler)(uint8_t **p_read, uint16_t *len, uint16_t att_idx);
/*********************************************************************
* @fn gatt_write_handler
*
* @brief User application handles write request in this callback.
* 应用层在这个回调函数里面处理写的请求。
*
* @param write_buf - the buffer for write
* 写操作的数据.
*
* len - the length of write buffer.
* 写缓冲区的长度.
* att_idx - offset of the attribute value.
* Attribute的偏移量.
*
* @return 写请求的长度.
*/
typedef uint16_t (*gatt_write_handler)(uint8_t *write_buf, uint16_t len, uint16_t att_idx);
/**
* GATT UUID format.
*/
typedef struct
{
uint8_t size; //!< Length of UUID (2 or 16 bytes UUIDs: UUID_SIZE_2 or UUID_SIZE_16). UUID长度(2 或者 16字节长度UUID).
uint8_t *p_uuid; //!< Pointer to uuid, could be 2 or 16 bytes array. 指向UUID的指针, 可以是2字节的, 也可以是16字节的数组.
}gatt_uuid_t;
/**
* BLE attribute define format.
*/
typedef struct
{
gatt_uuid_t uuid;
uint16_t prop;
uint16_t max_size;
uint8_t *p_data;
}gatt_attribute_t;
/**
* BLE service define format.
*/
typedef struct
{
gatt_attribute_t *p_att_tb; //!< Service's attributes table to add to system attribute database. 本服务的特征值的表格数组, 用于添加到系统的特征值数据库中.
uint8_t att_nb; //!< Service's attributes number. 本服务的特征值的表格数组的特征值个数, 这里包括所有的特征值, value, descriptor, CCC等等等等, 不是单单用于数据传输那几个value值.
uint16_t svc_id; //!< Service ID among all services in current system. 每个服务都会在系统里被分配一个特定的身份识别ID, 我们在svc_id中记录,这只是系统内部的, 注意这个SIG要求定义的全宇宙唯一UUID不同.
gatt_read_handler read_handler; //!< Read request callback function. 读请求回调函数指针.
gatt_write_handler write_handler; //!< Write request callback function. 写请求回调函数指针.
} gatt_service_t;
/**
* BLE notification format.
*/
typedef struct
{
uint16_t svc_id; //!< Service ID among all services in current system. 每个服务都会在系统里被分配一个特定的身份识别ID, 我们在svc_id中记录,这只是系统内部的, 注意这个SIG要求定义的全宇宙唯一UUID不同.
uint8_t att_idx; //!< Attribute id number in its service attribute table. 需要发送notification的特征值在它service的特征值表格中的位置,这可以从预定义特征值表格数组中轻松复制得到.
} gatt_ntf_t;
/**
* BLE indication format.
*/
typedef struct
{
uint16_t svc_id; //!< Service ID among all services in current system. 每个服务都会在系统里被分配一个特定的身份识别ID, 我们在svc_id中记录,这只是系统内部的, 注意这个SIG要求定义的全宇宙唯一UUID不同.
uint8_t att_idx; //!< Attribute id number in its service attribute table. 需要发送indication的特征值在它service的特征值表格中的位置,这可以从预定义特征值表格数组中轻松复制得到.
} gatt_ind_t;
/*
* GLOBAL VARIABLES (全局变量)
*/
/*
* LOCAL VARIABLES (本地变量)
*/
/*
* LOCAL FUNCTIONS (本地函数)
*/
/*
* EXTERN FUNCTIONS (外部函数)
*/
/*
* PUBLIC FUNCTIONS (全局函数)
*/
/** @function group ble peripheral device APIs (ble外设相关的API)
* @{
*/
/*********************************************************************
* @fn gatt_add_service
*
* @brief Addding a services & characteristics into gatt database.
* 添加一个服务和各个特征值到gatt的数据库里面去.
*
* @param service - service data to be added.
* 需要添加的服务的相关信息.
*
* @return None.
*/
void gatt_add_service(gatt_service_t *p_service);
/*********************************************************************
* @fn gatt_notification
*
* @brief Sending notification.
* 发送notification.
*
* @param ntf_att - in which service and which attribute the notification will be sent
* This parameter contains servcie ID and attribute ID
* to indicate exact which attribute will be used to send notification.
* 指明哪一个服务的哪一个特征值用来发送notification, 用初始化已经确定好的服务ID和特征值ID.
* p_data - notification data to be sent.
* 发送的内容.
* data_len - length of notification data.
* 发送内容的长度.
*
* @return None.
*/
void gatt_notification(gatt_ntf_t ntf_att, uint8_t *p_data, uint8_t data_len);
/*********************************************************************
* @fn gatt_indication
*
* @brief Sending indication.
* 发送indication.
*
* @param ind_att - in which service and which attribute the indication will be sent
* This parameter contains servcie ID and attribute ID
* to indicate exact which attribute will be used to send indication.
* 指明哪一个服务的哪一个特征值用来发送indication, 用初始化已经确定好的服务ID和特征值ID.
* p_data - indication data to be sent.
* 发送的内容.
* data_len - length of indication data.
* 发送内容的长度.
*
* @return None.
*/
void gatt_indication(gatt_ind_t ind_att, uint8_t *p_data, uint8_t data_len);
/*********************************************************************
* @fn gatt_indication
*
* @brief Sending indication.
* 发送indication.
*
* @param ind_att - in which service and which attribute the indication will be sent
* This parameter contains servcie ID and attribute ID
* to indicate exact which attribute will be used to send indication.
* 指明哪一个服务的哪一个特征值用来发送indication, 用初始化已经确定好的服务ID和特征值ID.
* p_data - indication data to be sent.
* 发送的内容.
* data_len - length of indication data.
* 发送内容的长度.
*
* @return None.
*/
void gatt_indication(gatt_ind_t ind_att, uint8_t *p_data, uint8_t data_len);
#endif // end of #ifndef GATT_API_H
| 2.125 | 2 |
2024-11-18T22:10:05.557622+00:00
| 2016-02-02T19:04:37 |
07b008d0d647f0d6f14f2ac040dcad433a8c56c7
|
{
"blob_id": "07b008d0d647f0d6f14f2ac040dcad433a8c56c7",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-02T19:04:37",
"content_id": "31f39e13e7f4217965685694154aa4225d27fed5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d24fc9607170f56e0a0757692fd075a02b7abc98",
"extension": "c",
"filename": "Ese2-TDE25022008.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": 1562,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/PreparazionePrimaProva/Ese2-TDE25022008.c",
"provenance": "stackv2-0106.json.gz:49671",
"repo_name": "annalisa-corradi/InformaticaA",
"revision_date": "2016-02-02T19:04:37",
"revision_id": "9c5f28a00ae80767c654ab7be0476c04aaac2b93",
"snapshot_id": "1e019a2ba2f6e95ca2c53c61dce198cd21189ab2",
"src_encoding": "WINDOWS-1252",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/annalisa-corradi/InformaticaA/9c5f28a00ae80767c654ab7be0476c04aaac2b93/PreparazionePrimaProva/Ese2-TDE25022008.c",
"visit_date": "2020-08-07T06:56:26.964102"
}
|
stackv2
|
/*
Si implementi una funzione che riceve in input una matrice NxM di float.
Definito “picco” un numero circondato in tutte le otto posizioni intorno solo da
numeri inferiori alla sua metà, la funzione conta il numero di “picchi” della matrice
(attenzione a gestire correttamente gli elementi ai bordi della matrice).
*/
#include <stdio.h>
const int N=5,M=3;
int f(float m[N][M]) {
int i,j,k,t,cont,quanti=0;
//esploro la matrice
for(i=0; i < N;i++) {
for (j = 0; j < M; j++) {
//cont=0;
//// valuto i valori intorno alla posizione i,j
//for(k=i-1; k <= i+1;k++) {
// for(t=j-1; t <= j+1;t++) {
// // sono fuori dalla matrice
// if(k < 0 || k >= N || t < 0 || t >= M) {
// cont++;
// }
// // condizione da verificare
// else if(condPicco(m[i][j], m[k][t]))
// cont++;
// }
//}
//tutti gli elementi verificano la condizione
if (fun2(i, j, m) == 1)
quanti++;
}
}
return quanti;
}
int fun2(int i, int j, float m[N][M]) {
int cont = 0;
// valuto i valori intorno alla posizione i,j
for (int k = i - 1; k <= i + 1; k++) {
for (int t = j - 1; t <= j + 1; t++) {
// sono fuori dalla matrice
if (k < 0 || k >= N || t < 0 || t >= M) {
cont++;
}
// condizione da verificare
else if (condPicco(m[i][j], m[k][t]))
cont++;
}
}
if (count == 8) return 1;
else
return 0;
}
int condPicco(int centro, int intorno){
return intorno*2<centro ? 1 : 0 ;
}
int condPozzo(int centro, int intorno){
return intorno>centro*2 ? 1 : 0 ;
}
| 3.75 | 4 |
2024-11-18T22:10:05.737934+00:00
| 2017-05-17T17:17:49 |
1d0cc467e65ae8e54f0a4e0843a042008ef626a8
|
{
"blob_id": "1d0cc467e65ae8e54f0a4e0843a042008ef626a8",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-17T17:18:18",
"content_id": "405b63b3c63add0789ac5a53a174932b5e8c4187",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "d45be73bf62b67b212a442866ad5371d10138046",
"extension": "c",
"filename": "release.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 46060804,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2313,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/tesla/test/Integration/release.c",
"provenance": "stackv2-0106.json.gz:49799",
"repo_name": "cadets/tesla",
"revision_date": "2017-05-17T17:17:49",
"revision_id": "f1e7c71899febc075a8c354c971431a593820737",
"snapshot_id": "3bdc2c1339124ec281ee007a13dcf5e9586ad522",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/cadets/tesla/f1e7c71899febc075a8c354c971431a593820737/tesla/test/Integration/release.c",
"visit_date": "2021-01-17T10:22:04.022291"
}
|
stackv2
|
//! @file call.c Tests basic caller and callee instrumentation.
/*
* Commands for llvm-lit:
* RUN: tesla analyse %s -o %t.tesla -- %cflags -D TESLA
* RUN: clang -S -emit-llvm %cflags %s -o %t.ll
* RUN: tesla instrument -S -tesla-manifest %t.tesla %t.ll -o %t.instr.ll
* RUN: clang %ldflags %t.instr.ll -o %t
* RUN: %t | tee %t.out
* RUN: %filecheck -input-file %t.out %s
*/
#include <errno.h>
#include <stddef.h>
#include <tesla-macros.h>
/*
* A few declarations of things that look a bit like real code:
*/
struct object {
int refcount;
};
struct credential {};
int get_object(int index, struct object **o);
int example_syscall(struct credential *cred, int index, int op);
/*
* Some functions we can reference in assertions:
*/
static void hold(struct object *o) { o->refcount += 1; }
static void release(struct object *o) { o->refcount -= 1; }
int
perform_operation(int op, struct object *o)
{
TESLA_WITHIN(example_syscall, eventually(call(release(o))));
return 0;
}
int
example_syscall(struct credential *cred, int index, int op)
{
/*
* System call entry is the inital bound of the automaton:
* CHECK: new [[INST0:[0-9]+]]: [[INIT:[0-9]+:0x0]]
*/
struct object *o;
int error = get_object(index, &o);
if (error != 0)
return (error);
/*
* perform_operation() contains the NOW event:
* CHECK: clone [[INST0]]:[[INIT]] -> [[INST1:[0-9]+]]:[[NOW:[0-9]+:0x1]]
*/
perform_operation(op, o);
/*
* CHECK: update [[INST1]]: [[NOW]]->[[REL:[0-9]+:0x1]]
*/
release(o);
/*
* Finally, leaving example_syscall() finalises the automaton:
* CHECK: update [[INST0]]: [[INIT]]->[[DONE:[0-9]+:0x0]]
* CHECK: pass '[[NAME:.*]]': [[INST0]]
* CHECK: update [[INST1]]: [[REL]]->[[DONE]]
* CHECK: pass '[[NAME:.*]]': [[INST1]]
* CHECK: tesla_class_reset [[NAME]]
*/
return 0;
}
int
main(int argc, char *argv[]) {
struct credential cred;
return example_syscall(&cred, 0, 0);
}
int
get_object(int index, struct object **o)
{
static struct object objects[] = {
{ .refcount = 0 },
{ .refcount = 0 },
{ .refcount = 0 },
{ .refcount = 0 }
};
static const size_t MAX = sizeof(objects) / sizeof(struct object);
if ((index < 0) || (index >= MAX))
return (EINVAL);
struct object *obj = objects + index;
hold(obj);
*o = obj;
return (0);
}
| 2.546875 | 3 |
2024-11-18T22:10:06.082678+00:00
| 2018-05-16T17:07:31 |
4ca2d6be77be3b1abcd4ed4a0ba3617dd22e5179
|
{
"blob_id": "4ca2d6be77be3b1abcd4ed4a0ba3617dd22e5179",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-16T17:07:31",
"content_id": "e95b9e993b4df2ad2fcc3606c9e41ef4e2a9736e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0c563b21858deda06c7cb8bf6a803a72ac633b38",
"extension": "c",
"filename": "vector_new_test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 73178927,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1560,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tests/vector_new_test.c",
"provenance": "stackv2-0106.json.gz:50189",
"repo_name": "etrobert/libft",
"revision_date": "2018-05-16T17:07:31",
"revision_id": "3dbd3972db57b8960ff79495d0b2b52bb40e355c",
"snapshot_id": "fe9272c8c42b90f124211ebadf766e9dc688457a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/etrobert/libft/3dbd3972db57b8960ff79495d0b2b52bb40e355c/tests/vector_new_test.c",
"visit_date": "2021-03-27T15:01:35.083182"
}
|
stackv2
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: etrobert <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/02 14:59:56 by etrobert #+# #+# */
/* Updated: 2016/12/19 19:25:10 by etrobert ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "ft_vector.h"
int main(int argc, char **argv)
{
t_vector *vec;
int i;
int n;
n = 45;
vec = ft_vector_new_size(sizeof(int), 0);
printf("capcity is %d\n", ft_vector_capacity(vec));
i = 0;
while (i < n)
{
ft_vector_push_back(vec);
*(int *)ft_vector_back(vec) = i;
// printf("adding %d: capcity is %d\n", i, ft_vector_capacity(vec));
i++;
}
i = n - 1;
while (i >= 0)
{
printf("%d\n", *(int *)ft_vector_at(vec, i));
i--;
}
printf("Back is : %d\n", *(int *)ft_vector_back(vec));
printf("front is : %d\n", *(int *)ft_vector_front(vec));
return (0);
}
| 2.984375 | 3 |
2024-11-18T22:10:06.180700+00:00
| 2019-02-11T19:53:01 |
9d9f14fe9762f17d13466716cd591ba31d4f8e6d
|
{
"blob_id": "9d9f14fe9762f17d13466716cd591ba31d4f8e6d",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-11T19:53:01",
"content_id": "4e194b5df62f6f451442c25f4df3f4c1a460ec40",
"detected_licenses": [
"MIT"
],
"directory_id": "cd649144fcba3a701b4ac3a01f58af749a55bffa",
"extension": "c",
"filename": "main_mm.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 141081829,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 708,
"license": "MIT",
"license_type": "permissive",
"path": "/17 Spring/4061 Intro to Operating Systems/project3/main_mm.c",
"provenance": "stackv2-0106.json.gz:50319",
"repo_name": "oway13/Schoolwork",
"revision_date": "2019-02-11T19:53:01",
"revision_id": "294f407c288ef532f8f187a6ee0bd9fd0e7559ab",
"snapshot_id": "d3aca4c566a1b1a152b2e40418d8229f91403d3f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/oway13/Schoolwork/294f407c288ef532f8f187a6ee0bd9fd0e7559ab/17 Spring/4061 Intro to Operating Systems/project3/main_mm.c",
"visit_date": "2020-03-23T04:24:44.147826"
}
|
stackv2
|
/* CSCI4061 S2017 Assignment 3
* login: kormi001
* date: 04/12/17
* name: Vy Le, Wyatt Kormick, Jon Huhn
* id: lexxx600, kormi001, huhnx025
*/
#include "mm.h"
void main() {
mm_t mm;
if (mm_init(&mm, NUM_CHUNKS, CHUNK_SIZE) < 0) {
perror("Could not initialize memory");
exit(-1);
}
struct timeval time_s, time_e;
/* start malloc timer */
gettimeofday(&time_s, NULL);
void *temp;
for (int i = 0; i < NUM_CHUNKS; i++) {
temp = mm_get(&mm);
}
for (int i = 0; i < NUM_CHUNKS; i++) {
temp = (char *)mm.buf + CHUNK_SIZE * i;
mm_put(&mm, temp);
}
gettimeofday(&time_e, NULL);
fprintf(stderr, "Time taken = %f msec\n", comp_time(time_s, time_e) / 1000.0);
}
| 2.640625 | 3 |
2024-11-18T22:10:06.248575+00:00
| 2021-04-14T13:45:45 |
5238ebf80cd8aa97b0e676e13b374abb15ce5cb9
|
{
"blob_id": "5238ebf80cd8aa97b0e676e13b374abb15ce5cb9",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-14T13:45:45",
"content_id": "40ed93991829b87eb6e2093086fac6cb35724105",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "bec07134a0cb52d70f30bfd2bd3d773484897e90",
"extension": "h",
"filename": "hashtable_sensors.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 401700881,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1281,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/CanMonitor/implementation/tables/hashtable_sensors.h",
"provenance": "stackv2-0106.json.gz:50447",
"repo_name": "JacoboFanjul/can-monitor",
"revision_date": "2021-04-14T13:45:45",
"revision_id": "9566b5727938f54c838e05bc261796f7392c195f",
"snapshot_id": "609b2402d97ff8151139a84e581aee6e9175c094",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JacoboFanjul/can-monitor/9566b5727938f54c838e05bc261796f7392c195f/src/CanMonitor/implementation/tables/hashtable_sensors.h",
"visit_date": "2023-07-20T01:20:10.100990"
}
|
stackv2
|
#ifndef _HASHTABLE_SENSORS_H_
#define _HASHTABLE_SENSORS_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../sensor.h"
/*
* @key: The key string of a pair
* The key is unique in the HashTable
*
* @value: The value corresponding to a key
* A value is not unique. It can correspond to several keys
*
* @next: A pointer to the next node of the List
*/
typedef struct ListSensors
{
char *key;
sensor *sensor;
struct ListSensors *next;
} ListSensors;
/*
* @size: The size of the array
*
* @array: An array of size @size
* Each cell of this array is a pointer to the first node of a linked list,
* because we want our HashTable to use a Chaining collision handling
*/
typedef struct HashTableSensors
{
unsigned int size;
ListSensors **array;
} HashTableSensors;
// Sensors Table
HashTableSensors * hts_create(unsigned int size);
int hts_put(HashTableSensors *hashtable_sensors, const char *key, sensor *value);
void node_handler_sensors(HashTableSensors *hashtable_sensors, ListSensors *node);
sensor * hts_get(HashTableSensors *hashtable_sensors, const char *key);
sensor * hts_delete(HashTableSensors *hashtable_sensors, const char *key);
void hts_free(HashTableSensors *hashtable_sensors);
#endif
| 2.5625 | 3 |
2024-11-18T22:36:55.431720+00:00
| 2022-05-03T06:20:18 |
c52beb2c6ff39a7bc3d7e8bf9a9d36656979d265
|
{
"blob_id": "c52beb2c6ff39a7bc3d7e8bf9a9d36656979d265",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-03T06:20:18",
"content_id": "e6f5781f0e77546dfe1aae6d8420397aede18881",
"detected_licenses": [
"MIT"
],
"directory_id": "49131570ce0a38fd620bb3cc8c05e6ed9574f37f",
"extension": "c",
"filename": "IOMngr.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 206841944,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2165,
"license": "MIT",
"license_type": "permissive",
"path": "/CS442/Assignment1/IOMngr.c",
"provenance": "stackv2-0107.json.gz:82715",
"repo_name": "BookerLoL/UWLCourses",
"revision_date": "2022-05-03T06:20:18",
"revision_id": "e9ba7a3ae1949de30e1987a0e15934ba4aaf6b2e",
"snapshot_id": "739983376fb944ee7946236558628befc9c7f945",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BookerLoL/UWLCourses/e9ba7a3ae1949de30e1987a0e15934ba4aaf6b2e/CS442/Assignment1/IOMngr.c",
"visit_date": "2022-05-17T03:57:51.019315"
}
|
stackv2
|
/*
* IOMngr.c
*
* Created on: Sep 21, 2019
* Author: Ethan
*/
#include "IOMngr.h"
#include <stdlib.h>
#include <stdio.h>
#define MAXLINE 1024
FILE *src;
FILE *listing;
char buffer[MAXLINE];
int currentLine = 0;
int currentColumn = 0;
int called = 0;
int offset = 0;
int OpenFiles(const char *ASourceName, const char *AListingName) {
if (!(src = fopen(ASourceName, "r"))) {
return 0;
}
if (AListingName && !(listing = fopen(AListingName, "w"))) {
return 0;
}
return 1;
}
void CloseFiles() {
if (src) {
fclose(src);
}
if (listing) {
fclose(listing);
}
}
int calcOffSet() {
int i = currentLine;
int count = 1;
while (i != 0) {
i /= 10;
count++;
}
return count;
}
char GetSourceChar() {
if (currentLine == 0 || buffer[currentColumn] == '\0') {
if (fgets(buffer, sizeof buffer, src) == NULL) {
return EOF;
}
currentLine++;
if (listing) {
if (currentLine == 1 || called == 0) {
fprintf(listing, "%d. %s", currentLine, buffer);
} else {
fprintf(listing, "\n%d. %s", currentLine, buffer);
}
}
offset = calcOffSet();
currentColumn = 0;
called = 0;
}
return buffer[currentColumn++];
}
void WriteIndicator(int AColumn) {
// Does not handle white spaces or tabs
int realColumn = AColumn + offset;
if (called == 0) {
if (listing) {
if (feof(src)) {
fprintf(listing, "\n%*s", realColumn, "^");
} else {
fprintf(listing, "%*s", realColumn, "^");
}
} else {
printf("\n%d. %s", currentLine, buffer);
if (feof(src)) { // last line doesn't print a new line, must add a new line
printf("\n%*s", realColumn, "^");
} else {
printf("%*s", realColumn, "^");
}
}
called = 1;
} else {
if (listing) {
fprintf(listing, "\n%*s", realColumn, "^");
} else {
printf("\n%*s", realColumn, "^");
}
}
}
void WriteMessage(const char *AMessage) {
if (listing) {
fprintf(listing, "\n%s", AMessage);
} else {
printf("\n%s", AMessage);
}
}
int GetCurrentLine() {
return currentLine;
}
int GetCurrentColumn() {
return currentColumn + 1;
}
| 2.921875 | 3 |
2024-11-18T22:36:55.653236+00:00
| 2013-06-27T21:11:09 |
d0f87dc3d039aeb850e89c25b4a2a3bbde3a9af0
|
{
"blob_id": "d0f87dc3d039aeb850e89c25b4a2a3bbde3a9af0",
"branch_name": "refs/heads/master",
"committer_date": "2013-06-27T21:11:09",
"content_id": "ee9677d515c207844169bffaa54a040d44345fb7",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "e1e44e108aabe4de84988b2bbb3366cc9ed531eb",
"extension": "c",
"filename": "tests-nodoubles.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2500056,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4362,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/test/tests-nodoubles.c",
"provenance": "stackv2-0107.json.gz:82974",
"repo_name": "robbesol/xprintf",
"revision_date": "2013-06-27T21:11:09",
"revision_id": "1094508f6e2f1c2c4b11457b2c998aaf1a7a8681",
"snapshot_id": "5bc9c95e56b953ac13ff12a094ff6bdc9190ce87",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/robbesol/xprintf/1094508f6e2f1c2c4b11457b2c998aaf1a7a8681/test/tests-nodoubles.c",
"visit_date": "2021-01-13T02:19:18.813092"
}
|
stackv2
|
/*
* Copyright (c) 2007-2011 Markus van Dijk
* All rights reserved.
*
* This file is part of the xprintf project.
* The xprintf project is open source software and distributed
* under the terms of the Simplified BSD License:
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <math.h>
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <inttypes.h>
#include "test-runner.h"
#include "test-rig.h"
void test_nodoubles(struct test_printf_info *tpi) {
startTests(tpi, __func__);
TEST_SAME("%.8f", M_PI);
TEST_SAME("%.0f", M_PI);
TEST_SAME("%1.f", M_PI);
TEST_SAME("%3.f", M_PI);
TEST_SAME("%0.0f", 0.32);
TEST_SAME("%.6f", 5.55555);
TEST_SAME("%.5f", 5.55555);
TEST_SAME("%.4f", 5.55555);
TEST_SAME("%.0f", 5.55555);
// %f, negative
TEST_SAME("%f", -M_PI);
TEST_SAME("%.8f", -M_PI);
TEST_SAME("%.0f", -M_PI);
TEST_SAME("%1.f", -M_PI);
TEST_SAME("%3.f", -M_PI);
TEST_SAME("%0.0f", 0.32);
TEST_SAME("%.6f", -5.55555);
TEST_SAME("%.5f", -5.55555);
TEST_SAME("%.4f", -5.55555);
TEST_SAME("%.0f", -5.55555);
/* %f, flags */
TEST_SAME("%+f", -M_PI);
TEST_SAME("% f", -M_PI);
TEST_SAME("% 10f", -M_PI);
TEST_SAME("%#.0f", -M_PI);
TEST_SAME("%05.2f", -M_PI);
TEST_SAME("%06.2f", -M_PI);
// leading zero in frac
TEST_SAME("%06.3f", 3.02134);
TEST_SAME("%06.3f", -3.02134);
TEST_SAME("%07.3f", -3.02134);
TEST_SAME("vrot %07.3f blerk", -3.02134);
TEST("vrot %07.3f blerk 11", "vrot %07.3f blerk %d", -3.02134, 11);
TEST("10 vrot %07.3f blerk", "%d vrot %07.3f blerk", 10, -3.02134);
TEST_SAME("vrot %07.3f blerk %f aap", -3.02134, -5.555);
TEST("x 10 vrot %07.3f blerk %f aap 011",
"x %-4d vrot %07.3f blerk %f aap %03d", 10, -3.02134, -5.555, 11);
// /* %e, basic formatting */
// /* for %e we can't expect to reproduce exact strings and lengths, since SUS
// * only guarantees that the exponent shall always contain at least two
// * digits. On Windows, it seems to be at least three digits long.
// * Therefore, we compare the test_results of parsing the expected test_result and the
// * actual test_result.
// */
// TEST (buf, g_snprintf (buf, 128, "%e", M_PI) >= 12 && same_value (buf, "3.141593e+00"));
// TEST (buf, g_snprintf (buf, 128, "%.8e", M_PI) >= 14 && same_value (buf, "3.14159265e+00"));
// TEST (buf, g_snprintf (buf, 128, "%.0e", M_PI) >= 5 && same_value (buf, "3e+00"));
// TEST (buf, g_snprintf (buf, 128, "%.1e", 0.0) >= 7 && same_value (buf, "0.0e+00"));
// TEST (buf, g_snprintf (buf, 128, "%.1e", 0.00001) >= 7 && same_value (buf, "1.0e-05"));
// TEST (buf, g_snprintf (buf, 128, "%.1e", 10000.0) >= 7 && same_value (buf, "1.0e+04"));
// /* %e, flags */
// TEST (buf, g_snprintf (buf, 128, "%+e", M_PI) >= 13 && same_value (buf, "+3.141593e+00"));
// TEST (buf, g_snprintf (buf, 128, "% e", M_PI) >= 13 && same_value (buf, " 3.141593e+00"));
// TEST (buf, g_snprintf (buf, 128, "%#.0e", M_PI) >= 6 && same_value (buf, "3.e+00"));
// TEST (buf, g_snprintf (buf, 128, "%09.2e", M_PI) >= 9 && same_value (buf, "03.14e+00"));
endTests(tpi);
}
| 2.078125 | 2 |
2024-11-18T22:36:55.713503+00:00
| 2021-07-02T19:05:50 |
267ec9a7e836c5cf5bf8f820c9c2e980255eedc7
|
{
"blob_id": "267ec9a7e836c5cf5bf8f820c9c2e980255eedc7",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-02T19:05:50",
"content_id": "280a7c3cf2688f89509004031d54541d29d6b1a0",
"detected_licenses": [
"Zlib"
],
"directory_id": "61e7fbfa3b61d87a314da80ccbbb631041a0437e",
"extension": "c",
"filename": "hashtable.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 381158221,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5887,
"license": "Zlib",
"license_type": "permissive",
"path": "/macelf/hashtable.c",
"provenance": "stackv2-0107.json.gz:83102",
"repo_name": "icculus/mojoelf",
"revision_date": "2021-07-02T19:05:50",
"revision_id": "ef31c30c9186e05cf3f3964923f3350e7ddc79bc",
"snapshot_id": "2045bcfb7d8b1ecfd1f3f4070d7b79943151e896",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/icculus/mojoelf/ef31c30c9186e05cf3f3964923f3350e7ddc79bc/macelf/hashtable.c",
"visit_date": "2023-05-31T16:20:14.064681"
}
|
stackv2
|
/**
* MojoELF; load ELF binaries from a memory buffer.
*
* Please see the file LICENSE.txt in the source's root directory.
*
* This file written by Ryan C. Gordon.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "hashtable.h"
typedef struct HashItem
{
const void *key;
const void *value;
struct HashItem *next;
} HashItem;
struct HashTable
{
HashItem **table;
uint32_t table_len;
void *data;
HashTable_HashFn hash;
HashTable_KeyMatchFn keymatch;
HashTable_NukeFn nuke;
};
static inline uint32_t calc_hash(const HashTable *table, const void *key)
{
return table->hash(key, table->data) & (table->table_len-1);
} // calc_hash
int hash_find(const HashTable *table, const void *key, const void **_value)
{
HashItem *i;
void *data = table->data;
const uint32_t hash = calc_hash(table, key);
HashItem *prev = NULL;
for (i = table->table[hash]; i != NULL; i = i->next)
{
if (table->keymatch(key, i->key, data))
{
if (_value != NULL)
*_value = i->value;
// Matched! Move to the front of list for faster lookup next time.
if (prev != NULL)
{
assert(prev->next == i);
prev->next = i->next;
i->next = table->table[hash];
table->table[hash] = i;
} // if
return 1;
} // if
prev = i;
} // for
return 0;
} // hash_find
int hash_iter(const HashTable *table, const void *key,
const void **_value, void **iter)
{
HashItem *item = *iter;
if (item == NULL)
item = table->table[calc_hash(table, key)];
else
item = item->next;
while (item != NULL)
{
if (table->keymatch(key, item->key, table->data))
{
*_value = item->value;
*iter = item;
return 1;
} // if
item = item->next;
} // while
// no more matches.
*_value = NULL;
*iter = NULL;
return 0;
} // hash_iter
int hash_iter_keys(const HashTable *table, const void **_key, void **iter)
{
HashItem *item = *iter;
int idx = 0;
if (item != NULL)
{
const HashItem *orig = item;
item = item->next;
if (item == NULL)
idx = calc_hash(table, orig->key) + 1;
} // if
while (!item && (idx < table->table_len))
item = table->table[idx++]; // skip empty buckets...
if (item == NULL) // no more matches?
{
*_key = NULL;
*iter = NULL;
return 0;
} // if
*_key = item->key;
*iter = item;
return 1;
} // hash_iter_keys
int hash_insert(HashTable *table, const void *key, const void *value)
{
HashItem *item = NULL;
const uint32_t hash = calc_hash(table, key);
if (hash_find(table, key, NULL))
return 0;
// !!! FIXME: grow and rehash table if it gets too saturated.
item = (HashItem *) malloc(sizeof (HashItem));
if (item == NULL)
return -1;
item->key = key;
item->value = value;
item->next = table->table[hash];
table->table[hash] = item;
return 1;
} // hash_insert
HashTable *hash_create(void *data, const HashTable_HashFn hashfn,
const HashTable_KeyMatchFn keymatchfn,
const HashTable_NukeFn nukefn)
{
const uint32_t initial_table_size = 0xFFFF;
const uint32_t alloc_len = sizeof (HashItem *) * initial_table_size;
HashTable *table = (HashTable *) malloc(sizeof (HashTable));
if (table == NULL)
return NULL;
memset(table, '\0', sizeof (HashTable));
table->table = (HashItem **) malloc(alloc_len);
if (table->table == NULL)
{
free(table);
return NULL;
} // if
memset(table->table, '\0', alloc_len);
table->table_len = initial_table_size;
table->data = data;
table->hash = hashfn;
table->keymatch = keymatchfn;
table->nuke = nukefn;
return table;
} // hash_create
void hash_destroy(HashTable *table)
{
uint32_t i;
void *data = table->data;
for (i = 0; i < table->table_len; i++)
{
HashItem *item = table->table[i];
while (item != NULL)
{
HashItem *next = item->next;
table->nuke(item->key, item->value, data);
free(item);
item = next;
} // while
} // for
free(table->table);
free(table);
} // hash_destroy
int hash_remove(HashTable *table, const void *key)
{
HashItem *item = NULL;
HashItem *prev = NULL;
void *data = table->data;
const uint32_t hash = calc_hash(table, key);
for (item = table->table[hash]; item != NULL; item = item->next)
{
if (table->keymatch(key, item->key, data))
{
if (prev != NULL)
prev->next = item->next;
else
table->table[hash] = item->next;
table->nuke(item->key, item->value, data);
free(item);
return 1;
} // if
prev = item;
} // for
return 0;
} // hash_remove
// this is djb's xor hashing function.
static inline uint32_t hash_string_djbxor(const char *str, size_t len)
{
register uint32_t hash = 5381;
while (len--)
hash = ((hash << 5) + hash) ^ *(str++);
return hash;
} // hash_string_djbxor
static inline uint32_t hash_string(const char *str, size_t len)
{
return hash_string_djbxor(str, len);
} // hash_string
uint32_t hash_hash_string(const void *sym, void *data)
{
(void) data;
return hash_string((const char*) sym, strlen((const char *) sym));
} // hash_hash_string
int hash_keymatch_string(const void *a, const void *b, void *data)
{
(void) data;
return (strcmp((const char *) a, (const char *) b) == 0);
} // hash_keymatch_string
// end of hashtable.c ...
| 2.921875 | 3 |
2024-11-18T22:36:55.772497+00:00
| 2018-03-21T18:10:52 |
d81f458ca7bdf30b64cf0cebcae21ec80a887ba4
|
{
"blob_id": "d81f458ca7bdf30b64cf0cebcae21ec80a887ba4",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-21T18:10:52",
"content_id": "9cb0d03feadb5e126af09bae18ebaedc450c1abb",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "46432330271da3c50f2e816679fb82b2ebc84444",
"extension": "c",
"filename": "stream_recv.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 123943273,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 17768,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/ucp/stream/stream_recv.c",
"provenance": "stackv2-0107.json.gz:83231",
"repo_name": "lemonrock/ucx-patches",
"revision_date": "2018-03-21T18:10:52",
"revision_id": "e20898d1c139225068d7354dbdf094444d642de4",
"snapshot_id": "2d41f92363bf6c5a377db560620a34fa706013dd",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/lemonrock/ucx-patches/e20898d1c139225068d7354dbdf094444d642de4/src/ucp/stream/stream_recv.c",
"visit_date": "2021-04-26T23:11:30.899646"
}
|
stackv2
|
/**
* Copyright (C) Mellanox Technologies Ltd. 2001-2017. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#include <ucp/core/ucp_ep.h>
#include <ucp/core/ucp_worker.h>
#include <ucp/core/ucp_context.h>
#include <ucp/core/ucp_request.h>
#include <ucp/core/ucp_request.inl>
#include <ucp/stream/stream.h>
#include <ucs/datastruct/mpool.inl>
#include <ucs/profile/profile.h>
#include <ucp/tag/eager.h> /* TODO: remove ucp_eager_sync_hdr_t usage */
/* @verbatim
* Data layout within Stream AM
* |---------------------------------------------------------------------------------------------------------------------------|
* | ucp_recv_desc_t | \ / | ucp_stream_am_data_t | payload |
* |-----------------------------------------------------------------| \ / |----------------------|-------------------------|
* | stream_queue | length | payload_offset | flags | \/ | am_header | |
* | tag_list (not used) | | | | /\ | rdesc | |
* |---------------------|----------------|----------------|---------| / \ |----------------------|-------------------------|
* | 4 * sizeof(ptr) | 32 bits | 32 bits | 16 bits | / \ | 64 bits | up to TL AM buffer size |
* |---------------------------------------------------------------------------------------------------------------------------|
* @endverbatim
*
* stream_queue is an entry link in the "unexpected" queue per endpoint
* length is an actual size of 'payload'
* payload_offset is a distance between 'ucp_recv_desc_t *' and 'payload *'
* X is an optional empty space which is a result of partial
* handled payload in case when 'length' greater than user's
* buffer size passed to @ref ucp_stream_recv_nb
* am_header is an active message header, not actual after ucp_recv_desc_t
* initialization and setup of offsets
* rdesc pointer to 'ucp_recv_desc_t *', it's needed to get access to
* 'ucp_recv_desc_t *' inside @ref ucp_stream_release_data after
* the buffer was returned to user by
* @ref ucp_stream_recv_data_nb as a pointer to 'paylod'
*/
#define ucp_stream_rdesc_payload(_rdesc) \
(UCS_PTR_BYTE_OFFSET((_rdesc), (_rdesc)->payload_offset))
#define ucp_stream_rdesc_am_data(_rdesc) \
((ucp_stream_am_data_t *) \
UCS_PTR_BYTE_OFFSET(ucp_stream_rdesc_payload(_rdesc), \
-sizeof(ucp_stream_am_data_t)))
#define ucp_stream_rdesc_from_data(_data) \
((ucp_stream_am_data_t *)_data - 1)->rdesc
static UCS_F_ALWAYS_INLINE ucp_recv_desc_t *
ucp_stream_rdesc_dequeue(ucp_ep_ext_stream_t *ep_stream)
{
ucp_recv_desc_t *rdesc = ucs_queue_pull_elem_non_empty(&ep_stream->match_q,
ucp_recv_desc_t,
stream_queue);
ucs_assert(ep_stream->flags & UCP_EP_STREAM_FLAG_HAS_DATA);
if (ucs_unlikely(ucs_queue_is_empty(&ep_stream->match_q))) {
ep_stream->flags &= ~UCP_EP_STREAM_FLAG_HAS_DATA;
if (ucp_stream_ep_is_queued(ep_stream)) {
ucp_stream_ep_dequeue(ep_stream);
}
}
return rdesc;
}
static UCS_F_ALWAYS_INLINE ucp_recv_desc_t *
ucp_stream_rdesc_get(ucp_ep_ext_stream_t *ep_stream)
{
ucp_recv_desc_t *rdesc = ucs_queue_head_elem_non_empty(&ep_stream->match_q,
ucp_recv_desc_t,
stream_queue);
ucs_assert(ep_stream->flags & UCP_EP_STREAM_FLAG_HAS_DATA);
ucs_trace_data("ep %p, rdesc %p with %u stream bytes",
ep_stream->ucp_ep, rdesc, rdesc->length);
return rdesc;
}
UCS_PROFILE_FUNC(ucs_status_ptr_t, ucp_stream_recv_data_nb,
(ep, length), ucp_ep_h ep, size_t *length)
{
ucp_recv_desc_t *rdesc;
ucp_stream_am_data_t *am_data;
UCP_THREAD_CS_ENTER_CONDITIONAL(&ep->worker->mt_lock);
if (ucs_unlikely(!(ep->ext.stream->flags & UCP_EP_STREAM_FLAG_HAS_DATA))) {
UCP_THREAD_CS_EXIT_CONDITIONAL(&ep->worker->mt_lock);
return UCS_STATUS_PTR(UCS_OK);
}
rdesc = ucp_stream_rdesc_dequeue(ep->ext.stream);
UCP_THREAD_CS_EXIT_CONDITIONAL(&ep->worker->mt_lock);
*length = rdesc->length;
am_data = ucp_stream_rdesc_am_data(rdesc);
am_data->rdesc = rdesc;
return am_data + 1;
}
static UCS_F_ALWAYS_INLINE void
ucp_stream_rdesc_release(ucp_recv_desc_t *rdesc)
{
if (ucs_unlikely(rdesc->flags & UCP_RECV_DESC_FLAG_UCT_DESC)) {
uct_iface_release_desc(UCS_PTR_BYTE_OFFSET(rdesc,
-sizeof(ucp_eager_sync_hdr_t)));
} else {
ucs_mpool_put_inline(rdesc);
}
}
static UCS_F_ALWAYS_INLINE void
ucp_stream_rdesc_dequeue_and_release(ucp_recv_desc_t *rdesc,
ucp_ep_ext_stream_t *ep)
{
ucs_assert(ep->flags & UCP_EP_STREAM_FLAG_HAS_DATA);
ucs_assert(rdesc == ucs_queue_head_elem_non_empty(&ep->match_q,
ucp_recv_desc_t,
stream_queue));
ucp_stream_rdesc_dequeue(ep);
ucp_stream_rdesc_release(rdesc);
}
UCS_PROFILE_FUNC_VOID(ucp_stream_data_release, (ep, data),
ucp_ep_h ep, void *data)
{
ucp_recv_desc_t *rdesc = ucp_stream_rdesc_from_data(data);
UCP_THREAD_CS_ENTER_CONDITIONAL(&ep->worker->mt_lock);
ucp_stream_rdesc_release(rdesc);
UCP_THREAD_CS_EXIT_CONDITIONAL(&ep->worker->mt_lock);
}
static UCS_F_ALWAYS_INLINE ssize_t
ucp_stream_rdata_unpack(const void *rdata, size_t length, ucp_request_t *dst_req)
{
size_t valid_len;
int last;
ucs_status_t status;
/* Truncated error is not actual for stream, need to adjust */
valid_len = dst_req->recv.length - dst_req->recv.stream.offset;
if (valid_len <= length) {
last = (valid_len == length);
} else {
valid_len = length;
last = !(dst_req->flags & UCP_REQUEST_FLAG_STREAM_RECV_WAITALL);
}
status = ucp_request_recv_data_unpack(dst_req, rdata, valid_len,
dst_req->recv.stream.offset, last);
if (ucs_likely(status == UCS_OK)) {
dst_req->recv.stream.offset += valid_len;
ucs_trace_data("unpacked %zd bytes of stream data %p",
valid_len, rdata);
return valid_len;
}
ucs_assert(status != UCS_ERR_MESSAGE_TRUNCATED);
return status;
}
static UCS_F_ALWAYS_INLINE ucs_status_t
ucp_stream_rdesc_advance(ucp_recv_desc_t *rdesc, ssize_t offset,
ucp_ep_ext_stream_t *ep)
{
ucs_assert(offset <= rdesc->length);
if (ucs_unlikely(offset < 0)) {
return offset;
} else if (ucs_likely(offset == rdesc->length)) {
ucp_stream_rdesc_dequeue_and_release(rdesc, ep);
} else {
rdesc->length -= offset;
rdesc->payload_offset += offset;
}
return UCS_OK;
}
static UCS_F_ALWAYS_INLINE ucs_status_t
ucp_stream_process_rdesc_inplace(ucp_recv_desc_t *rdesc, ucp_datatype_t dt,
void *buffer, size_t count, size_t length,
ucp_ep_ext_stream_t *ep_stream)
{
ucs_status_t status;
ssize_t unpacked;
status = ucp_dt_unpack_only(ep_stream->ucp_ep->worker, buffer, count, dt,
UCT_MD_MEM_TYPE_HOST, ucp_stream_rdesc_payload(rdesc),
length, 0);
unpacked = ucs_likely(status == UCS_OK) ? length : status;
return ucp_stream_rdesc_advance(rdesc, unpacked, ep_stream);
}
static UCS_F_ALWAYS_INLINE ucs_status_t
ucp_stream_process_rdesc(ucp_recv_desc_t *rdesc, ucp_ep_ext_stream_t *ep_stream,
ucp_request_t *req)
{
ssize_t unpacked;
unpacked = ucp_stream_rdata_unpack(ucp_stream_rdesc_payload(rdesc),
rdesc->length, req);
ucs_assert(req->recv.stream.offset <= req->recv.length);
return ucp_stream_rdesc_advance(rdesc, unpacked, ep_stream);
}
static UCS_F_ALWAYS_INLINE void
ucp_stream_recv_request_init(ucp_request_t *req, void *buffer, size_t count,
size_t length, ucp_datatype_t datatype,
ucp_stream_recv_callback_t cb,
uint16_t request_flags)
{
req->flags = UCP_REQUEST_FLAG_CALLBACK | request_flags;
#if ENABLE_ASSERT
req->flags |= UCP_REQUEST_FLAG_STREAM_RECV;
req->status = UCS_OK; /* for ucp_request_recv_data_unpack() */
#endif
req->recv.stream.cb = cb;
req->recv.stream.length = 0;
req->recv.stream.offset = 0;
ucp_dt_recv_state_init(&req->recv.state, buffer, datatype, count);
req->recv.buffer = buffer;
req->recv.datatype = datatype;
req->recv.length = ucs_likely(!UCP_DT_IS_GENERIC(datatype)) ? length :
ucp_dt_length(datatype, count, NULL, &req->recv.state);
req->recv.mem_type = UCT_MD_MEM_TYPE_HOST;
}
static UCS_F_ALWAYS_INLINE int
ucp_stream_recv_nb_is_inplace(ucp_ep_ext_stream_t *ep, size_t dt_length)
{
return (ep->flags & UCP_EP_STREAM_FLAG_HAS_DATA) &&
(ucp_stream_rdesc_get(ep)->length >= dt_length);
}
UCS_PROFILE_FUNC(ucs_status_ptr_t, ucp_stream_recv_nb,
(ep, buffer, count, datatype, cb, length, flags),
ucp_ep_h ep, void *buffer, size_t count,
ucp_datatype_t datatype, ucp_stream_recv_callback_t cb,
size_t *length, unsigned flags)
{
ucs_status_t status = UCS_OK;
ucp_ep_ext_stream_t *ep_stream = ep->ext.stream;
size_t dt_length;
ucp_request_t *req;
ucp_recv_desc_t *rdesc;
UCP_THREAD_CS_ENTER_CONDITIONAL(&ep->worker->mt_lock);
if (ucs_likely(!UCP_DT_IS_GENERIC(datatype))) {
dt_length = ucp_dt_length(datatype, count, buffer, NULL);
if (ucs_likely(ucp_stream_recv_nb_is_inplace(ep_stream, dt_length))) {
status = ucp_stream_process_rdesc_inplace(ucp_stream_rdesc_get(ep_stream),
datatype, buffer, count,
dt_length, ep_stream);
*length = dt_length;
goto out_status;
}
} else {
dt_length = 0; /* Suppress warnings of paranoid compilers */
}
req = ucp_request_get(ep->worker);
if (ucs_unlikely(req == NULL)) {
status = UCS_ERR_NO_MEMORY;
goto out_status;
}
ucp_stream_recv_request_init(req, buffer, count, dt_length, datatype, cb,
(flags & UCP_STREAM_RECV_FLAG_WAITALL) ?
UCP_REQUEST_FLAG_STREAM_RECV_WAITALL : 0);
/* OK, lets obtain all arrived data which matches the recv size */
while ((req->recv.stream.offset < req->recv.length) &&
(ep_stream->flags & UCP_EP_STREAM_FLAG_HAS_DATA)) {
rdesc = ucp_stream_rdesc_get(ep_stream);
status = ucp_stream_process_rdesc(rdesc, ep_stream, req);
if (ucs_unlikely(status != UCS_OK)) {
goto out_put_request;
}
/*
* NOTE: generic datatype can be completed with any amount of data to
* avoid extra logic in ucp_stream_process_rdesc, exception is
* WAITALL flag
*/
if (ucs_unlikely(UCP_DT_IS_GENERIC(req->recv.datatype)) &&
!(req->flags & UCP_REQUEST_FLAG_STREAM_RECV_WAITALL)) {
break;
}
}
ucs_assert(req->recv.stream.offset <= req->recv.length);
if (ucp_request_can_complete_stream_recv(req)) {
*length = req->recv.stream.offset;
} else {
ucs_assert(!(ep_stream->flags & UCP_EP_STREAM_FLAG_HAS_DATA));
ucs_queue_push(&ep_stream->match_q, &req->recv.queue);
req += 1;
goto out;
}
out_put_request:
ucp_request_put(req);
out_status:
req = UCS_STATUS_PTR(status);
out:
UCP_THREAD_CS_EXIT_CONDITIONAL(&ep->worker->mt_lock);
return req;
}
static UCS_F_ALWAYS_INLINE ucs_status_t
ucp_stream_am_data_process(ucp_worker_t *worker, ucp_ep_ext_stream_t *ep,
ucp_stream_am_data_t *am_data, size_t length,
unsigned am_flags)
{
ucp_recv_desc_t rdesc_tmp;
void *payload;
ucp_recv_desc_t *rdesc;
ucp_request_t *req;
ssize_t unpacked;
rdesc_tmp.length = length;
rdesc_tmp.payload_offset = sizeof(*am_data); /* add sizeof(*rdesc) only if
am_data wont be handled in
place */
/* First, process expected requests */
if (!(ep->flags & UCP_EP_STREAM_FLAG_HAS_DATA)) {
while (!ucs_queue_is_empty(&ep->match_q)) {
req = ucs_queue_head_elem_non_empty(&ep->match_q, ucp_request_t,
recv.queue);
payload = UCS_PTR_BYTE_OFFSET(am_data, rdesc_tmp.payload_offset);
unpacked = ucp_stream_rdata_unpack(payload, rdesc_tmp.length, req);
if (ucs_unlikely(unpacked < 0)) {
ucs_fatal("failed to unpack from am_data %p with offset %u to request %p",
am_data, rdesc_tmp.payload_offset, req);
} else if (unpacked == rdesc_tmp.length) {
if (ucp_request_can_complete_stream_recv(req)) {
ucp_request_complete_stream_recv(req, ep, UCS_OK);
}
return UCS_OK;
}
ucp_stream_rdesc_advance(&rdesc_tmp, unpacked, ep);
/* This request is full, try next one */
ucs_assert(ucp_request_can_complete_stream_recv(req));
ucp_request_complete_stream_recv(req, ep, UCS_OK);
}
}
ucs_assert(rdesc_tmp.length > 0);
/* Now, enqueue the rest of data */
if (ucs_likely(!(am_flags & UCT_CB_PARAM_FLAG_DESC))) {
rdesc = (ucp_recv_desc_t*)ucs_mpool_get_inline(&worker->am_mp);
ucs_assertv_always(rdesc != NULL,
"ucp recv descriptor is not allocated");
rdesc->length = rdesc_tmp.length;
/* reset offset to improve locality */
rdesc->payload_offset = sizeof(*rdesc) + sizeof(*am_data);
rdesc->flags = 0;
memcpy(ucp_stream_rdesc_payload(rdesc),
UCS_PTR_BYTE_OFFSET(am_data, rdesc_tmp.payload_offset),
rdesc_tmp.length);
} else {
/* slowpath */
rdesc = (ucp_recv_desc_t *)am_data - 1;
rdesc->length = rdesc_tmp.length;
rdesc->payload_offset = rdesc_tmp.payload_offset + sizeof(*rdesc);
rdesc->flags = UCP_RECV_DESC_FLAG_UCT_DESC;
}
ep->flags |= UCP_EP_STREAM_FLAG_HAS_DATA;
ucs_queue_push(&ep->match_q, &rdesc->stream_queue);
return UCS_INPROGRESS;
}
static UCS_F_ALWAYS_INLINE ucs_status_t
ucp_stream_am_handler(void *am_arg, void *am_data, size_t am_length,
unsigned am_flags)
{
ucp_worker_h worker = am_arg;
ucp_stream_am_data_t *data = am_data;
ucp_ep_ext_stream_t *ep_stream;
ucp_ep_h ep;
ucs_status_t status;
ucs_assert(am_length >= sizeof(ucp_stream_am_hdr_t));
ep = ucp_worker_ep_find(worker, data->hdr.sender_uuid);
if (ucs_unlikely(ep == NULL)) {
ucs_trace_data("ep not found for uuid %"PRIx64, data->hdr.sender_uuid);
/* drop the data */
return UCS_OK;
}
ep_stream = ep->ext.stream;
if (ucs_unlikely(!(ep_stream->flags & UCP_EP_STREAM_FLAG_VALID))) {
ucs_trace_data("stream ep with uuid %"PRIx64" is invalid",
data->hdr.sender_uuid);
/* drop the data */
return UCS_OK;
}
status = ucp_stream_am_data_process(worker, ep_stream, data,
am_length - sizeof(data->hdr),
am_flags);
if (status == UCS_OK) {
/* rdesc was processed in place */
return UCS_OK;
}
ucs_assert(status == UCS_INPROGRESS);
if (!ucp_stream_ep_is_queued(ep_stream)) {
ucp_stream_ep_enqueue(ep_stream, worker);
}
return (am_flags & UCT_CB_PARAM_FLAG_DESC) ? UCS_INPROGRESS : UCS_OK;
}
static void ucp_stream_am_dump(ucp_worker_h worker, uct_am_trace_type_t type,
uint8_t id, const void *data, size_t length,
char *buffer, size_t max)
{
const ucp_stream_am_hdr_t *hdr = data;
size_t hdr_len = sizeof(*hdr);
char *p;
snprintf(buffer, max, "STREAM ep uuid %"PRIx64, hdr->sender_uuid);
p = buffer + strlen(buffer);
ucp_dump_payload(worker->context, p, buffer + max - p, data + hdr_len,
length - hdr_len);
}
UCP_DEFINE_AM(UCP_FEATURE_STREAM, UCP_AM_ID_STREAM_DATA,
ucp_stream_am_handler, ucp_stream_am_dump,
UCT_CB_FLAG_SYNC);
UCP_DEFINE_AM_PROXY(UCP_AM_ID_STREAM_DATA);
| 2.046875 | 2 |
2024-11-18T22:36:56.438866+00:00
| 2023-07-24T16:37:33 |
d05235ceeec18e68c89b5e1a4e96e9a738d56dd5
|
{
"blob_id": "d05235ceeec18e68c89b5e1a4e96e9a738d56dd5",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-24T16:37:33",
"content_id": "0805aceb669b902bc90358d3cd0f633a370fe566",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "e19509bd2548f173aa492d7498812afa28fcfbb5",
"extension": "c",
"filename": "auto-attenuator.c",
"fork_events_count": 28,
"gha_created_at": "2015-05-23T12:32:52",
"gha_event_created_at": "2022-07-19T15:09:24",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 36122394,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2773,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/afilter/auto-attenuator.c",
"provenance": "stackv2-0107.json.gz:83750",
"repo_name": "stsaz/fmedia",
"revision_date": "2023-07-24T16:37:33",
"revision_id": "6f6d05fde4a6eba2f1fa0d9e194cd2b405258c3e",
"snapshot_id": "ef28a25e88ef50411014cfc7faef8813a67cf486",
"src_encoding": "UTF-8",
"star_events_count": 194,
"url": "https://raw.githubusercontent.com/stsaz/fmedia/6f6d05fde4a6eba2f1fa0d9e194cd2b405258c3e/src/afilter/auto-attenuator.c",
"visit_date": "2023-08-19T20:30:03.512098"
}
|
stackv2
|
/** fmedia: auto attenuator
2020, Simon Zolin */
#include <fmedia.h>
extern const fmed_core *core;
#define dbglog1(trk, ...) fmed_dbglog(core, trk, "auto-attenuator", __VA_ARGS__)
struct aa_ctx {
uint state;
ffpcmex orig_convfmt;
double track_gain;
double track_ceiling;
double ceiling;
int user_gain_int;
double user_gain;
};
static void* aa_open(fmed_filt *d)
{
if (d->audio.auto_attenuate_ceiling == 0.0)
return FMED_FILT_SKIP;
struct aa_ctx *aa = ffmem_new(struct aa_ctx);
aa->track_gain = 1.0;
aa->ceiling = ffpcm_db2gain(d->audio.auto_attenuate_ceiling);
aa->track_ceiling = aa->ceiling;
aa->user_gain = 1.0;
return aa;
}
static void aa_close(void *ctx)
{
struct aa_ctx *aa = ctx;
ffmem_free(aa);
}
static int aa_process(void *ctx, fmed_filt *d)
{
struct aa_ctx *aa = ctx;
if (d->flags & FMED_FSTOP) {
return FMED_RDONE;
}
switch (aa->state) {
case 0:
aa->orig_convfmt = d->audio.convfmt;
d->audio.convfmt.format = FFPCM_FLOAT;
aa->state = 1;
return FMED_RDATA;
case 1:
aa->state = 2;
if (!(aa->orig_convfmt.format == FFPCM_FLOAT
&& aa->orig_convfmt.ileaved)) {
dbglog1(d->trk, "requesting audio conversion");
d->audio.convfmt.format = FFPCM_FLOAT;
d->audio.convfmt.ileaved = 1;
}
return FMED_RMORE;
case 2:
if (!(d->audio.convfmt.format == FFPCM_FLOAT
&& d->audio.convfmt.ileaved)) {
dbglog1(d->trk, "unsupported format");
return FMED_RERR;
}
aa->state = 3;
}
float *f = (void*)d->data_in.ptr;
ffsize nsamples = d->data_in.len / sizeof(float);
if (nsamples == 0 && !(d->flags & FMED_FLAST))
return FMED_RMORE;
if (aa->user_gain_int != d->audio.gain) {
aa->user_gain_int = d->audio.gain;
aa->user_gain = ffpcm_db2gain((double)d->audio.gain / 100);
dbglog1(d->trk, "ceiling:%.2f aa-gain:%.2f user-gain:%.2f final-gain:%.2f"
, aa->track_ceiling, aa->track_gain, aa->user_gain, aa->user_gain * aa->track_gain);
}
double gain = aa->user_gain * aa->track_gain;
uint ich = 0;
double sum = 0.0;
for (ffsize i = 0; i != nsamples; i++) {
sum += ffint_abs((double)f[i]);
if (++ich == d->audio.convfmt.channels) {
ich = 0;
if (sum > aa->track_ceiling) {
aa->track_ceiling = sum;
sum /= d->audio.convfmt.channels;
if (sum > 1.0)
sum = 1.0;
aa->track_gain = 1.0 - (sum - aa->ceiling);
gain = aa->user_gain * aa->track_gain;
dbglog1(d->trk, "ceiling:%.2f aa-gain:%.2f user-gain:%.2f final-gain:%.2f"
, aa->track_ceiling, aa->track_gain, aa->user_gain, gain);
}
sum = 0.0;
}
if (gain != 1.0)
f[i] = f[i] * gain;
}
d->data_out = d->data_in;
d->data_in.len = 0;
return (d->flags & FMED_FLAST) ? FMED_RDONE : FMED_RDATA;
}
const fmed_filter fmed_auto_attenuator = {
aa_open, aa_process, aa_close
};
| 2.5625 | 3 |
2024-11-18T22:36:57.251277+00:00
| 2021-11-25T22:27:12 |
70b51e221efa94245440ee2b2b98a637c325c63c
|
{
"blob_id": "70b51e221efa94245440ee2b2b98a637c325c63c",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-25T22:27:12",
"content_id": "0994803df057e635a96d90beab8dc29dffdfe650",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "bade93cbfc1f25160dfbe9493bfa83f853326475",
"extension": "c",
"filename": "sys6.c",
"fork_events_count": 6,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 214182273,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15843,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/mwc/romana/relic/b/STREAMS/coh.386/sys6.c",
"provenance": "stackv2-0107.json.gz:84650",
"repo_name": "gspu/Coherent",
"revision_date": "2021-11-25T22:27:12",
"revision_id": "299bea1bb52a4dcc42a06eabd5b476fce77013ef",
"snapshot_id": "c8a9b956b1126ffc34df3c874554ee2eb7194299",
"src_encoding": "UTF-8",
"star_events_count": 26,
"url": "https://raw.githubusercontent.com/gspu/Coherent/299bea1bb52a4dcc42a06eabd5b476fce77013ef/mwc/romana/relic/b/STREAMS/coh.386/sys6.c",
"visit_date": "2021-12-01T17:49:53.618512"
}
|
stackv2
|
/* $Header: /src386/STREAMS/coh.386/RCS/sys6.c,v 2.1 93/08/09 13:36:55 bin Exp Locker: bin $ */
/*
* POSIX.1-oriented system calls for Coherent.
*
* Conventions: as elsewhere, system call handlers have the same name as the
* user would use but prefixed by a 'u'. Internal data interfaces have the
* same name as a user function if they have the same signature, which is a
* good thing for testing, and can save on redundant prototypes. Wherever
* possible, we use such function-call interfaces rather than get involved in
* the disgusting mess that is the U area or process-table mechanisms.
*/
/*
* $Log: sys6.c,v $
* Revision 2.1 93/08/09 13:36:55 bin
* Kernel 82 changes
*
* Revision 2.2 93/07/26 14:55:33 nigel
* Nigel's R80
*
*/
#include <common/ccompat.h>
#include <sys/signal.h>
#include <unistd.h>
/*
*-STATUS:
* POSIX.1
*
*-NAME:
* sigaction () Detailed signal management
*
*-SYNOPSIS:
* #include <signal.h>
*
* int sigaction (int sig, const struct sigaction * act,
* struct sigaction * oact);
*
*-DESCRIPTION:
* sigaction () allows the calling process to examine and/or specify the
* action to be taken on delivery of a specific signal.
*
* "sig" specifies the signal and can be assigned any of the signals
* specified in signal(5) except SIGKILL and SIGSTOP.
*
* If the argument "arg" is not NULL, it points to a structure specifying
* the new action to be taken when delivering "sig". If the argument
* "oact" is not NULL, it points to a structure where the action
* previously associated with "sig" is to be stored on return from
* sigaction ().
*
* The "sigaction" structure includes the following members:
* void (* sa_handler) ();
* sigset_t sa_mask;
* int sa_flags;
*
* "sa_handler" specifies the disposition of the signal and may take any
* of the values specified in signal (5).
*
* "sa_mask" specifies a set of signals to be blocked while the signal
* handler is active. On entry to the signal handler, that set of signals
* is added to the set of signals already being blocked when the signal
* is delivered. In addition, the signal that caused the handler to be
* executed will also be blocked, unless the SA_NODEFER flag has been
* specified. SIGSTOP and SIGKILL cannot be blocked (the system silently
* enforces this restriction).
*
* "sa_flags" specifies a set of flags used to modify the behaviour of
* the signal. It is formed by a logical OR of any of the following
* values (only SA_CLDSTOP is available to System V, Release 3
* applications):
*
* SA_NOCLDSTOP If set and "sig" equals SIGCHLD, "sig" will not be
* sent to the calling process when its child processes
* stop or continue.
*
* SA_NOCLDWAIT If set and "sig" equals SIGCHLD, the system will not
* create zombie processes when children of the calling
* process exit. If the calling process subsequently
* issues a wait (), it blocks until all of the calling
* process's child processes terminate, and then returns
* a value of -1 with "errno" set to ECHILD.
*
* SA_ONSTACK If set and the signal is caught and an alternate
* signal stack has been declared with sigaltstack (),
* the signal is delivered to the calling process on that
* stack. Otherwise, the signal is delivered on the
* same stack as the main program.
*
* SA_RESETHAND If set and the signal is caught, the disposition of
* the signal is reset to SIG_DFL, and the signal will
* not be blocked on entry to the signal handler (SIGILL,
* SIGTRAP, and SIGPWR cannot be automatically reset when
* delivered; the system silently enforces this
* restriction).
*
* SA_NODEFER If set and the signal is caught, the signal will not
* be automatically blocked by the kernel while it is
* being caught.
*
* SA_RESTART If set and the signal is caught, a system call that
* is interrupted by the execution of this signal's
* handler is transparently restarted by the system.
* Otherwise, the system call returns an EINTR error.
*
* SA_SIGINFO If cleared and the signal is caught, "sig" is passed
* as the only argument to the signal-catching function.
* If set and the signal is caught, pending signals of
* type "sig" are reliably queued to the calling process
* and two additional arguments are passed to the signal-
* catching function. If the second argument is not equal
* to NULL, it points to a "siginfo_t" structure
* containing the reason why the signal was generated;
* the third argument points to a "ucontext_t" structure
* containing the receiving process's context when the
* signal was delivered.
*
* sigaction () fails if any of the following is true:
*
* EINVAL The value of the "sig" argument is not a valid signal
* number or is equal to SIGKILL or SIGSTOP.
*
* EFAULT "act" or "oact" points outside the process's allocated
* address space.
*
*-DIAGNOSTICS:
* On success, sigaction () returns zero. On failure, it returns -1 and
* sets "errno" to indicate the error.
*/
#if __USE_PROTO__
int usigaction (int sig, __CONST__ struct sigaction * act,
struct sigaction * oact)
#else
int
usigaction (sig, act, oact)
int sig;
__CONST__ struct sigaction
* act;
struct sigaction * oact;
#endif
{
struct sigaction temp;
/*
* Once we validate the user pointers, we *must* take a local copy of
* either the previous signal setting or the data pointed to by "act"
* so that the caller is free to use the same pointer for both input
* and output arguments. Naturally, we must totally validate the new
* data before storing anything back to the user, irrespective of how
* convenient it might be to let a lower layer deal with this.
*/
return -1;
}
/*
*-STATUS:
* POSIX.1
*
*-NAME:
* sigpending () Examine signals that are blocked and pending
*
*-SYNOPSIS:
* #include <signal.h>
*
* int sigpending (sigset_t * set);
*
*-DESCRIPTION:
* The sigpending () function retrieves those signals that have been sent
* to the calling process but are being blocked from delivery by the
* calling process's signal mask. The signals are stored in the space
* pointed to by the argument "set".
*
* sigpending () fails if any of the following are true:
*
* EFAULT The "set" argument points outside the process's
* allocated address space.
*
*-DIAGNOSTICS:
* On success, sigpending () returns zero. On failure, it returns -1 and
* sets "errno" to indicate the error.
*/
#if __USE_PROTO__
int usigpending (o_sigset_t * set)
#else
int
usigpending (set)
o_sigset_t * set;
#endif
{
return -1;
}
/*
*-STATUS:
* POSIX.1
*
*-NAME:
* sigprocmask () Change or examine signal mask
*
*-SYNOPSIS:
* #include <signal.h>
*
* int sigprocmask (int how, const sigset_t * set, sigset_t * oset);
*
*-DESCRIPTION:
* The sigprocmask () function is used to examine and/or change the
* calling process's signal mask. If the value of "how" is SIG_BLOCK, the
* set pointed to by the argument "set" is added to the current signal
* mask. If "how" is SIG_UNBLOCK, the set pointed to by the argument
* "set" is removed from the current signal mask. If "how" is
* SIG_SETMASK, the current signal mask is replaced by the set pointed
* to by the argument "set". If the argument "oset" is not NULL, the
* previous mask is stored in the space pointed to by "oset". If the
* value of the argument "set" is NULL, the value "how" is not
* significant and the process's signal mask is unchanged; thus, the call
* can be used to enquire about currently blocked signals.
*
* If there are any pending unblocked signals after the call to
* sigprocmask (), at least one of those signals will be delivered before
* the call to sigprocmask () returns.
*
* It is not possible to block those signals that cannot be ignored [see
* sigaction ()]; this restriction is silently imposed by the system.
*
* If sigprocmask () fails, the process's signal mask is not changed.
*
* sigprocmask () fails if any of the following are true:
*
* EINVAL The value of the "how" argument is not equal to one of
* the defined values.
*
* EFAULT The value of "set" or "oset" points outside the
* process's allocated address space.
*
*-DIAGNOSTICS:
* On success, sigprocmask () returns zero. On failure, it returns -1 and
* sets "errno" to indicate the error.
*/
#if __USE_PROTO__
int usigprocmask (int how, __CONST__ o_sigset_t * set, o_sigset_t * oset)
#else
int
usigprocmask (how, set, oset)
int how;
__CONST__ o_sigset_t
* set;
o_sigset_t * oset;
#endif
{
o_sigset_t tmp;
/*
* Once we validate the user pointers, we *must* either take a local
* copy of the previous signal mask or the data pointed at by "set" so
* that the user is free to use the same pointer for both input and
* output arguments.
*/
return -1;
}
/*
*-STATUS:
* POSIX.1
*
*-NAME:
* fpathconf ()
* pathconf () get configurable pathname variables
*
*-SYNOPSIS:
* #include <unistd.h>
*
* long fpathconf (int fildes, int name);
* long pathconf (const char * path, int name);
*
*-DESCRIPTION:
* The functions fpathconf () and pathconf () return the current value of
* a configurable limit or option associated with a file or directory.
* The "path" argument points to the pathname of a file or directory;
* "fildes" is an open file descriptor; and "name" is the symbolic
* constant (defined in <unistd.h>) representing the configurable system
* limit or option to be returned.
*
* The values returned by pathconf () or fpathconf () depend on the type
* of file specified by "path" or "fildes". The following table contains
* the symbolic constants supported by pathconf () and fpathconf ()
* along with the POSIX defined return value. The return value is based
* on the type of file specified by "path" or "fildes".
*
* _PC_LINK_MAX The maximum value of a file's link count. If "path" or
* "fildes" refers to a directory, the value returned
* applies to the directory itself.
*
* _PC_MAX_CANON The number of bytes in a terminal canonical input
* queue. The behaviour is undefined if "path" or
* "fildes" does not refer to a terminal file.
*
* _PC_MAX_INPUT The number of bytes for which space will be available
* in a terminal input queue. The behaviour is undefined
* "path" or "fildes" does not refer to a terminal file.
*
* _PC_NAME_MAX The number of bytes in a filename. The behaviour is
* undefined if "path" or "fildes" does not refer to a
* directory. The value returned applies to the filenames
* within the directory.
*
* _PC_PATH_MAX The number of bytes in a pathname. The behaviour is
* undefined if "path" or "fildes" does not refer to a
* directory. The value returned is the maximum length of
* a relative pathname when the specified directory is
* the working directory.
*
* _PC_PIPE_BUF The number of bytes that can be written atomically
* when writing to a pipe. If "path" or "files" refers to
* a pipe or FIFO, the value returned applies to the FIFO
* itself. If "path" or "fildes" refers to a directory,
* the value returned applies to any FIFOs that exist or
* can be created within the directory. If "path" or
* "fildes" refer to any other type of file, the
* behaviour is undefined.
*
* _PC_CHOWN_RESTRICTED The use of the chown () function is restricted
* to a process with appropriate priveleges, and to
* changing the group ID of a file only to the effective
* group ID of the process or to one of its supplementary
* group IDs. If "path" or "fildes" refers to a
* directory, the value returned applies to any files,
* other than directories, that exist or can be created
* within the directory.
*
* _PC_NO_TRUNC Pathname components longer than NAME_MAX generate an
* error. The behaviour is undefined if "path" or
* "fildes" does not refer to a directory. The value
* returned applies to the filenames within the
* directory.
* _PC_VDISABLE Terminal special characters can be disabled using this
* character value, if it is defined. The behaviour is
* undefined if "path" or "filedes" does not refer to a
* terminal file.
*
* The value of the configurable system limit or option specified by
* "name" does not change during the lifetime of the calling process.
*
* fpathconf () fails if the following is true:
*
* EBADF "fildes" is not a valid file descriptor.
*
* pathconf () fails if any of the following are true:
*
* EACCES Search permission is denied for a component of the
* path prefix.
*
* ELOOP Too many symbolic links are encountered while
* translating "path".
*
* EMULTIHOP Components of "path" require hopping to multiple
* remote machines and the file system type does not
* allow it.
*
* ENAMETOOLONG The length of a pathname component exceeds PATH_MAX,
* or a pathname component is longer than NAME_MAX while
* _POSIX_NO_TRUNC is in effect.
*
* ENOENT "path" is needed for the command specified and the
* named file does not exist or if the "path" argument
* points to an empty string.
*
* ENOLINK "path" points to a remote machine and the link to that
* machine is no longer active.
*
* ENOTDIR A component of the path prefix is not a directory.
*
* Both fpathconf () and pathconf () fail if the following is true:
*
* EINVAL if "name" is an invalid value.
*
*-DIAGNOSTICS:
* If fpathconf () or pathconf () is invoked with an invalid symbolic
* constant or the symbolic constant corresponds to a configurable system
* limit or option not supported on the system, a value of -1 is returned
* to the invoking process. If the function fails because the
* configurable system limit or option corresponding to "name" is not
* supported on the system the value of "errno" is not changed.
*/
#if __USE_PROTO__
int ufpathconf (int fildes, int name)
#else
int
ufpathconf (fildes, name)
int fildes;
int name;
#endif
{
return -1;
}
#if __USE_PROTO__
int upathconf (__CONST__ char * path, int name)
#else
int
upathconf (path, name)
__CONST__ char * path;
int name;
#endif
{
return -1;
}
/*
*-STATUS:
* POSIX.1
*
*-NAME:
* sysconf () get configurable system variables
*
*-SYNOPSIS:
* #include <unistd.h>
*
* long sysconf (int name);
*
*-DESCRIPTION:
* The sysconf () function provides a method for the application to
* determine the current value of a configurable system limit or option.
*
* The "name" argument represents the system variable to be queried. The
* following table lists the minimal set of system variables from
* <limits.h> and <unistd.h> that can be returned by sysconf (), and the
* symbolic constants that are the corresponding values used for "name":
*
* NAME: RETURN VALUE:
* _SC_ARG_MAX ARG_MAX
* _SC_CHILD_MAX CHILD_MAX
* _SC_CLK_TCK CLK_TCK
* _SC_NGROUPS_MAX NGROUPS_MAX
* _SC_OPEN_MAX OPEN_MAX
* _SC_PASS_MAX PASS_MAX
* _SC_PAGESIZE PAGESIZE
* _SC_JOB_CONTROL _POSIX_JOB_CONTROL
* _SC_SAVED_IDS _POSIX_SAVED_IDS
* _SC_VERSION _POSIX_VERSION
* _SC_XOPEN_VERSION _XOPEN_VERSION
* _SC_LOGNAME_MAX LOGNAME_MAX
*
* The value of CLK_TCK may be variable and it should not be assumed that
* CLK_TCK is a compile-time constant. The value of CLK_TCK is the same
* as the value of sysconf (_SC_CLK_TCK).
*
*-DIAGNOSTICS:
* If "name" is an invalid value, sysconf () will return -1 and set
* "errno" to indicate the error. If sysconf () fails due to a value of
* "name" that is not defined on the system, the function will returne
* a value of -1 without changing the value of "errno".
*
*-NOTES:
* A call to setrlimit () may cause the value of OPEN_MAX to change on
* System V, Release 4-compatible systems.
*/
#if __USE_PROTO__
long usysconf (int name)
#else
long
usysconf (name)
int name;
#endif
{
return -1;
}
| 2.421875 | 2 |
2024-11-18T22:36:57.439574+00:00
| 2019-07-10T15:29:01 |
469fa66da8a648e0e6a600a90481655f40b7f1ce
|
{
"blob_id": "469fa66da8a648e0e6a600a90481655f40b7f1ce",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-10T15:29:01",
"content_id": "219ac994b9903a8188f2ae73c1c205c2bc65478a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "607b15b7de974e0d64eb7faf386d9fae875fc294",
"extension": "h",
"filename": "SocketOpts.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": 3488,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/SocketOpts.h",
"provenance": "stackv2-0107.json.gz:84908",
"repo_name": "yycccccccc/Cyclone",
"revision_date": "2019-07-10T15:29:01",
"revision_id": "666e7de6679d8867ef2cabfb4f96d55653bf43f1",
"snapshot_id": "ad22bb543237a99562db369a15e21a320472ac20",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yycccccccc/Cyclone/666e7de6679d8867ef2cabfb4f96d55653bf43f1/src/SocketOpts.h",
"visit_date": "2020-06-19T06:08:35.728526"
}
|
stackv2
|
/**********************************************************
* Author : RaKiRaKiRa
* Email : 763600693@qq.com
* Create time : 2019-07-09 23:54
* Last modified : 2019-07-10 21:18
* Filename : SocketOpts.h
* Description :
**********************************************************/
#ifndef SOCKETOPTS_H
#define SOCKETOPTS_H
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <endian.h>
//网路字节序与主机字节序相互转换,be指big-endian,网络序是大端的
inline uint16_t hostToNetwork16(uint16_t host)
{
return htobe16(host);
}
inline uint16_t networkToHost16(uint16_t network)
{
return be16toh(network);
}
inline uint32_t hostToNetwork32(uint32_t host)
{
return htobe32(host);
}
inline uint32_t networkToHost32(uint32_t network)
{
return be32toh(network);
}
inline uint64_t hostToNetwork64(uint64_t host)
{
return htobe64(host);
}
inline uint64_t networkToHost64(uint64_t network)
{
return be64toh(network);
}
/*
* struct in_addr{ in_addr_t s_addr; };
* struct sockaddr_in{
* uint8_t sin_len;
* sa_family_t sin_family; //AF_INET
* in_port_t sin_port; //16bit TCP或UDP端口号
* struct in_addr sin_addr; //32bit IPv4地址
* char sin_zero[8];
* };
*
* struct sockaddr{
* uint8_t sa_len;
* as_family_t sa_family;
* char sa_data[14];
* };
*/
typedef sockaddr SA;
const SA* sockaddr_cast(const sockaddr_in *addr)
{
return static_cast<const SA*>(static_cast<const void*>(addr));
}
SA* sockaddr_cast(sockaddr_in *addr)
{
return static_cast<SA*>(static_cast<void*>(addr));
}
//×××××××××××××××对socket通信api进行封装,增加报错×××××××××××××
//创建一个非阻塞socketFd
int createNonblockingSockfd();
int Connect(int sockfd, const struct sockaddr* addr);
void Bind(int sockfd, const struct sockaddr* addr);
void Listen(int sockfd);
int Accept(int sockfd, sockaddr* addr);
//仅关闭WR,用于优雅关闭,不用close保证接收数据的完整性
//TCP 是全双工,shutdownWrite() 关闭了“写”方向的连接,保留了“读”方向,这称为half-close。
//如果直接 close(socket_fd),那么 socket_fd 就不能读或写了。
//用 shutdown的效果是,如果对方已经发送了数据,这些数据还“在路上”,那么不会漏收这些数据。
//这种关闭连接的方式对对方也有要求,
//对方read() 到 0 字节之后会主动关闭连接(无论 shutdownWrite() 还是 close())
//完整的流程是:我们发完了数据,于是 shutdownWrite,发送 TCP FIN 分节,对方会读到 0 字节,
//然后对方通常会关闭连接,这样 muduo 会读到 0 字节,然后 muduo 关闭连接。
void ShutdownWrite(int sockfd);
void Close(int sockfd);
//×××××××××××××××对socket设置和部分api进行封装××××××××××××××××××××
//设置非阻塞
void setNonblock(int sockfd, bool on);
void setReusePort(int sockfd, bool on);
void setReuseAddr(int sockfd, bool on);
//开关Nagle
void setNodelay(int sockfd, bool on);
//开关Tcp默认心跳
void setKeepAlive(int sockfd, bool on);
//将addr中的ip:port 输出给buf
void toIpPort(char* buf, size_t size, const struct sockaddr_in *addr);
//将ip port 传给addr
void fromIpPort(const char* ip, uint16_t port, struct sockaddr_in *addr);
int getSocketError(int sockfd);
#endif
| 2.5 | 2 |
2024-11-18T22:36:58.059126+00:00
| 2021-07-13T17:46:13 |
cf5046b5e12d6292ab6aa9f8a87c37f5b6068101
|
{
"blob_id": "cf5046b5e12d6292ab6aa9f8a87c37f5b6068101",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-13T17:46:13",
"content_id": "5081cb7e5fd8b5ba16d1e222a0cc144616368448",
"detected_licenses": [
"MIT"
],
"directory_id": "871dd1de7378f22f69c7009e44c7ac7e88f5d8ea",
"extension": "h",
"filename": "device.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 382926494,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 893,
"license": "MIT",
"license_type": "permissive",
"path": "/src/loader/inc/device.h",
"provenance": "stackv2-0107.json.gz:85553",
"repo_name": "marvinborner/SegelBoot",
"revision_date": "2021-07-13T17:46:13",
"revision_id": "c9b5256eb58fd4dce5b027c1a2aadaaf2638c33b",
"snapshot_id": "a0c0f0402785ebbb5d257836de4e75ec8677590d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/marvinborner/SegelBoot/c9b5256eb58fd4dce5b027c1a2aadaaf2638c33b/src/loader/inc/device.h",
"visit_date": "2023-06-22T08:15:31.256410"
}
|
stackv2
|
// MIT License, Copyright (c) 2021 Marvin Borner
#ifndef DEVICE_H
#define DEVICE_H
#include <def.h>
#include <disk.h>
enum device_type {
DEVICE_NONE,
DEVICE_DISK,
DEVICE_FB,
};
struct dev {
u8 id;
enum device_type type;
char name[16];
s32 (*read)(void *, u32, u32, struct dev *);
s32 (*write)(const void *, u32, u32, struct dev *);
union {
struct {
struct fs fs;
} disk;
// TODO: Other (framebuffer?)
} p; // Prototype union
u32 data; // Optional (device-specific) data/information
};
struct dev *device_get_by_id(u8 id);
struct dev *device_get_by_name(const char *name, u32 len);
void device_foreach(enum device_type type, u8 (*cb)(struct dev *)); // cb=1 => break
u8 device_register(enum device_type type, char *name, u32 data,
s32 (*read)(void *, u32, u32, struct dev *),
s32 (*write)(const void *, u32, u32, struct dev *));
void device_print(void);
#endif
| 2.140625 | 2 |
2024-11-18T22:36:58.578146+00:00
| 2019-10-25T21:16:52 |
6093c4615d2e9c3ea8d130af79b3cf64f3f8a739
|
{
"blob_id": "6093c4615d2e9c3ea8d130af79b3cf64f3f8a739",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-25T21:16:52",
"content_id": "6a4184e7b5a33087d85d9a3d1407606b463d4ace",
"detected_licenses": [
"Unlicense"
],
"directory_id": "1ce93e537f089bb76db6ae3f0d77917f95de7e5f",
"extension": "h",
"filename": "gigs.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 217615060,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 988,
"license": "Unlicense",
"license_type": "permissive",
"path": "/gigs.h",
"provenance": "stackv2-0107.json.gz:85814",
"repo_name": "axifist/DIY-Midi-Controller",
"revision_date": "2019-10-25T21:16:52",
"revision_id": "ccc682afca941c9d73d2efe3c45c33f60146cbfe",
"snapshot_id": "7137b3f5e6b3b15b14b328bd20a232da76384e62",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/axifist/DIY-Midi-Controller/ccc682afca941c9d73d2efe3c45c33f60146cbfe/gigs.h",
"visit_date": "2020-08-28T05:57:19.672242"
}
|
stackv2
|
const unsigned char numberOfGigs = 3;
const unsigned char maximumNumberOfSongsInGigs = 12;
const unsigned char numberOfGigInfos = 1; //1. number of songs
const unsigned char gigs[numberOfGigs] = {0, 1, 2}; //for the menu
const unsigned char sizeOfGigNames = 15;
const char nameOfGig[numberOfGigs][sizeOfGigNames] = { //Here the gigs get names
"Gig 1 01.02.03",
"Gig 2 04.05.06",
"Gig 3 07.08.09",
};
const unsigned char gigSongs[numberOfGigs][maximumNumberOfSongsInGigs] = { //and here they are configured. Which songs will be played at which gig?
//Gig 1
{1, 2},
//Gig 2
{2, 1},
//Gig 3
{1, 2},
};
const unsigned char gigInfos[numberOfGigs] = { //For the Arduino to know when we reach the last song of the setlist, I need to tell it how many songs there are on this list. Could also be done with sizeof or something. TODO: see if sizeof is a good alternative to this. gigInfos is only called twice in songs_functions.h
//Gig 1
2,
//Gig 2
2,
//Gig 3
2,
};
| 2.578125 | 3 |
2024-11-18T22:36:58.933868+00:00
| 2018-02-14T12:13:42 |
ade9e7e8436d9edf486873030670ff24736398d1
|
{
"blob_id": "ade9e7e8436d9edf486873030670ff24736398d1",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-14T12:13:42",
"content_id": "171e9fceabccfbf6db07aa591a82c36692e1b768",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "341f700a1726371ff648508dc6d9df7433b2b90d",
"extension": "c",
"filename": "idt.c",
"fork_events_count": 0,
"gha_created_at": "2018-02-11T15:23:54",
"gha_event_created_at": "2018-02-11T15:23:54",
"gha_language": null,
"gha_license_id": null,
"github_id": 121136648,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2674,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/idt.c",
"provenance": "stackv2-0107.json.gz:86330",
"repo_name": "bauen1/svmbios",
"revision_date": "2018-02-14T12:13:42",
"revision_id": "2e1ae0fc6666970317e5cc2ee5c4a5851ecb3fbd",
"snapshot_id": "23b1c4d63d13520c43928a41de83af8e09178ed1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/bauen1/svmbios/2e1ae0fc6666970317e5cc2ee5c4a5851ecb3fbd/src/idt.c",
"visit_date": "2021-05-01T06:05:39.020663"
}
|
stackv2
|
#include <stdint.h>
#include <idt.h>
#include <idt_load.h>
#include <isrs.h>
static idt_entry_t idt[256];
static struct {
uint16_t limit __attribute__((packed));
uint32_t base __attribute__((packed));
} __attribute__((packed)) lidt_ptr;
void idt_set_gate(uint8_t i, void *isr, uint16_t selector, uint8_t flags) {
uint32_t offset = (uint32_t)isr;
idt[i].offset_low = (uint16_t)(offset & 0xFFFF);
idt[i].selector = selector;
idt[i].zero = 0;
idt[i].type_attr = flags;
idt[i].offset_high = (uint16_t)((offset >> 16) & 0xFFFF);
}
void idt_install() {
lidt_ptr.limit = sizeof(idt) - 1;
lidt_ptr.base = (uint32_t)&idt;
idt_load((uintptr_t)&lidt_ptr);
for (int i = 0; i < 256; i++) {
idt_set_gate(i, 0, 0, 0);
}
// Exceptions
idt_set_gate( 0, _isr0, 0x08, 0x8E);
idt_set_gate( 1, _isr1, 0x08, 0x8E);
idt_set_gate( 2, _isr2, 0x08, 0x8E);
idt_set_gate( 3, _isr3, 0x08, 0x8E);
idt_set_gate( 4, _isr4, 0x08, 0x8E);
idt_set_gate( 5, _isr5, 0x08, 0x8E);
idt_set_gate( 6, _isr6, 0x08, 0x8E);
idt_set_gate( 7, _isr7, 0x08, 0x8E);
idt_set_gate( 8, _isr8, 0x08, 0x8E);
idt_set_gate( 9, _isr9, 0x08, 0x8E);
idt_set_gate( 10, _isr10, 0x08, 0x8E);
idt_set_gate( 11, _isr11, 0x08, 0x8E);
idt_set_gate( 12, _isr12, 0x08, 0x8E);
idt_set_gate( 13, _isr13, 0x08, 0x8E);
idt_set_gate( 14, _isr14, 0x08, 0x8E);
idt_set_gate( 15, _isr15, 0x08, 0x8E);
idt_set_gate( 16, _isr16, 0x08, 0x8E);
idt_set_gate( 17, _isr17, 0x08, 0x8E);
idt_set_gate( 18, _isr18, 0x08, 0x8E);
idt_set_gate( 19, _isr19, 0x08, 0x8E);
idt_set_gate( 20, _isr20, 0x08, 0x8E);
idt_set_gate( 21, _isr21, 0x08, 0x8E);
idt_set_gate( 22, _isr22, 0x08, 0x8E);
idt_set_gate( 23, _isr23, 0x08, 0x8E);
idt_set_gate( 24, _isr24, 0x08, 0x8E);
idt_set_gate( 25, _isr25, 0x08, 0x8E);
idt_set_gate( 26, _isr26, 0x08, 0x8E);
idt_set_gate( 27, _isr27, 0x08, 0x8E);
idt_set_gate( 28, _isr28, 0x08, 0x8E);
idt_set_gate( 29, _isr29, 0x08, 0x8E);
idt_set_gate( 30, _isr30, 0x08, 0x8E);
idt_set_gate( 31, _isr31, 0x08, 0x8E);
// IRQs
idt_set_gate( 32, _isr32, 0x08, 0x8E);
idt_set_gate( 33, _isr33, 0x08, 0x8E);
idt_set_gate( 34, _isr34, 0x08, 0x8E);
idt_set_gate( 35, _isr35, 0x08, 0x8E);
idt_set_gate( 36, _isr36, 0x08, 0x8E);
idt_set_gate( 37, _isr37, 0x08, 0x8E);
idt_set_gate( 38, _isr38, 0x08, 0x8E);
idt_set_gate( 39, _isr39, 0x08, 0x8E);
idt_set_gate( 40, _isr40, 0x08, 0x8E);
idt_set_gate( 41, _isr41, 0x08, 0x8E);
idt_set_gate( 42, _isr42, 0x08, 0x8E);
idt_set_gate( 43, _isr43, 0x08, 0x8E);
idt_set_gate( 44, _isr44, 0x08, 0x8E);
idt_set_gate( 45, _isr45, 0x08, 0x8E);
idt_set_gate( 46, _isr46, 0x08, 0x8E);
idt_set_gate( 47, _isr47, 0x08, 0x8E);
}
| 2.265625 | 2 |
2024-11-18T22:36:59.063377+00:00
| 2021-02-04T11:37:07 |
5f2cd4663d5dd55d5f50a4ca03aa4e8d5a9f243b
|
{
"blob_id": "5f2cd4663d5dd55d5f50a4ca03aa4e8d5a9f243b",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-04T11:37:07",
"content_id": "95b7d1ecd525d67797af70761b73fdbb298f9b70",
"detected_licenses": [
"Zlib"
],
"directory_id": "766b796599d58038b32d7c1cbb2d8d026849269b",
"extension": "c",
"filename": "markers.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 329448715,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4671,
"license": "Zlib",
"license_type": "permissive",
"path": "/deps/draw_tools/examples/markers.c",
"provenance": "stackv2-0107.json.gz:86587",
"repo_name": "JulienCalbert/Numerical-Geometry",
"revision_date": "2021-02-04T11:37:07",
"revision_id": "b7646911556b7981fd5ebddc7f72d35fb586fa13",
"snapshot_id": "124feb52e02810b68d7611890268dd7b73196487",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JulienCalbert/Numerical-Geometry/b7646911556b7981fd5ebddc7f72d35fb586fa13/deps/draw_tools/examples/markers.c",
"visit_date": "2023-02-26T19:59:39.689961"
}
|
stackv2
|
/*************************************************************************
* Animation example program using Draw_tools, a wrapper around OpenGL and
* GLFW (www.glfw.org) to draw simple 2D graphics.
*------------------------------------------------------------------------
* Copyright (c) 2019-2020 Célestin Marot <marotcelestin@gmail.com>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*************************************************************************/
#include "draw_tools.h"
#include <math.h>
// Maybe there will be more marker types available in the future.
// At the moment, markers value wraps around at 25
// We cannot have more than 100 markers without chaning the way the
// string is created (putting %7.3f and lengthen the string)
#define DT_NMARKERS 25
int main(int argc, char *argv[])
{
/* Actually, this is not an example at all, you shouldn't draw the
* same f**king point 250 time, each time with a different draw
* call.
*
* This is more of a tool. When you launch this program, you will
* be able to see which marker value correspond to which shape
* and choose the shape that fits your need accordingly.
*
* REMINDER: DO NOT MAKE THAT MANY DRAW CALL IN YOUR CODE !!!!
*/
window_t* window = window_new(0,0, argv[0]);
window_set_color(window, (GLfloat[4]){1.0f, 0.8f, 0.5f, 1.0f});
const GLfloat pointWidth = 1.0f/DT_NMARKERS;
points_t* points = points_new((float[2][2]){{0.0f, 0.0f}, {1.0f, 0.0f}}, 2,
GL_STATIC_DRAW);
points_set_outline_color(points, (float[4]){0.3f, 0.3f, 0.3f, 1.0f});
points_set_outline_width(points, pointWidth*0.2f);
points_set_width(points, pointWidth);
text_t* marker_text;
{
/* first, we will generate all the text values */
// we will have 6 charater per number (2digit, one dot, 3 digit)
// then 2 space, for each marker.
// then we have 10 \n at the end of each line
char string[9*(DT_NMARKERS*8 + 9)+1];
int cur = 0;
for(int j=0; j<9; j++) {
for(int i=0; i<DT_NMARKERS; i++) {
sprintf(string+cur, " %6.3f ", i+j*0.12493f);
cur += 8;
}
// replace the 2 trailing space with 4 '\n'
sprintf(string+cur-1, "\n\n\n\n\n\n\n\n\n\n");
cur+= 9;
}
marker_text = text_new((unsigned char *) string,
GL_STATIC_DRAW);
text_set_fontsize(marker_text, pointWidth*0.5f);
text_set_pos(marker_text, (GLfloat[2]){-1.0f, 1.0f-pointWidth});
}
while(!window_should_close(window)){
double wtime = window_get_time(window);
// we change the color over time
points_set_color(points, (GLfloat[4]) {
sin(0.11*wtime)*0.5+0.5,
sin(0.7*wtime)*0.5+0.4,
sin(0.67*wtime)*0.5+0.6,
1});
points_set_outline_width(points, pointWidth*0.2f);
points_set_width(points, pointWidth);
// we modify wtime to go only between 0 and 1
double fract02 = modf(0.2*wtime, &wtime);
wtime = fabs(2*fract02-1.0);
for(int i=0; i<DT_NMARKERS; i++) {
GLfloat pos[2] = {pointWidth-1.0f+2.0f*pointWidth*i,
1.0f-2.5f*pointWidth};
for(int j=0; j<9; j++) {
points_set_pos(points, pos);
points_set_marker(points, i+j*0.12493f);
points_draw(window, points, 0, 1);
pos[1] -= 5.0f*pointWidth;
}
points_set_pos(points, pos);
points_set_marker(points, i+wtime);
points_draw(window, points, 0, 1);
}
text_draw(window, marker_text);
points_set_pos(points, (GLfloat[2]){-0.5, 1.0f - 9*5.0f*pointWidth});
points_set_width(points, pointWidth*0.5f);
points_set_outline_width(points, pointWidth*(0.5f*0.2f));
lines_draw(window, points, 0, 2);
window_update(window);
}
printf("Ended correctly");
points_delete(points);
text_delete(marker_text);
window_delete(window);
return EXIT_SUCCESS;
}
| 2.53125 | 3 |
2024-11-18T22:36:59.282110+00:00
| 2015-12-16T10:12:06 |
1246f1bd3d92cc4738476077307f858e19b5ec46
|
{
"blob_id": "1246f1bd3d92cc4738476077307f858e19b5ec46",
"branch_name": "refs/heads/master",
"committer_date": "2015-12-16T10:12:06",
"content_id": "a5fc8f43e6682d3be61524f57af2d24517ee4e35",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "ed68a1ac51764885be1d6cebeaaccc5f1b0f81bd",
"extension": "c",
"filename": "symbol.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 47487655,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1257,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/symbol.c",
"provenance": "stackv2-0107.json.gz:86846",
"repo_name": "a12e/matcc",
"revision_date": "2015-12-16T10:12:06",
"revision_id": "4b074e848be8f570d47d2d69a5a37f5025e2c845",
"snapshot_id": "f81eb8c980c28dc792f79b7e8385830555400995",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/a12e/matcc/4b074e848be8f570d47d2d69a5a37f5025e2c845/src/symbol.c",
"visit_date": "2021-01-10T14:41:41.469448"
}
|
stackv2
|
#include "symbol.h"
#include "utility.h"
unsigned int temps_count = 0;
unsigned int constants_count = 0;
const char *SYMBOL_TYPE_STR[] = {
"int", "float", "string", "matrix"
};
struct symbol *symbol_new(char *name, enum symbol_type type) {
struct symbol *s = safe_malloc(sizeof(struct symbol));
s->name = safe_strdup(name);
s->type = type;
s->constant = false;
s->size = 4;
return s;
}
struct symbol *symbol_new_user(char *name, enum symbol_type type) {
char user_variable_name[32];
snprintf(user_variable_name, 32, "_%s", name);
return symbol_new(user_variable_name, type);
}
struct symbol *symbol_new_temp(enum symbol_type type) {
char temp_name[32];
snprintf(temp_name, 32, "tmp%d", temps_count++);
return symbol_new(temp_name, type);
}
struct symbol *symbol_new_const(enum symbol_type type, union symbol_initial_value value) {
char constant_name[32];
snprintf(constant_name, 32, "cst%d", constants_count++);
struct symbol *s = symbol_new(constant_name, type);
s->initial_value = value;
s->constant = true;
return s;
}
void symbol_delete(struct symbol *s) {
safe_free(s->name);
if(s->type == STRING) safe_free(s->initial_value.stringval);
safe_free(s);
}
| 2.609375 | 3 |
2024-11-18T22:36:59.435745+00:00
| 2018-07-27T12:46:58 |
6a95598a4b505090a5e731bfe3f479f275a6b74c
|
{
"blob_id": "6a95598a4b505090a5e731bfe3f479f275a6b74c",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-27T12:46:58",
"content_id": "484d25464b1cdbf1f45f7f37b02771b95764ef6c",
"detected_licenses": [
"Apache-2.0",
"BSD-2-Clause"
],
"directory_id": "fb5d048562a851f3debe44899e7ad41af7e54a6d",
"extension": "h",
"filename": "pqueue.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 123906685,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3655,
"license": "Apache-2.0,BSD-2-Clause",
"license_type": "permissive",
"path": "/libhilti/3rdparty/libpqueue/src/pqueue.h",
"provenance": "stackv2-0107.json.gz:87103",
"repo_name": "jjchromik/hilti-104-total",
"revision_date": "2018-07-27T12:46:58",
"revision_id": "0f9e0cb7114acc157211af24f8254e4b23bd78a5",
"snapshot_id": "1503b60544bf03cc5ec43a9e530981ffffdcfa01",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jjchromik/hilti-104-total/0f9e0cb7114acc157211af24f8254e4b23bd78a5/libhilti/3rdparty/libpqueue/src/pqueue.h",
"visit_date": "2021-09-19T11:39:55.088380"
}
|
stackv2
|
/*
* Copyright 2010 Volkan Yazıcı <volkan.yazici@gmail.com>
* Copyright 2006-2010 The Apache Software 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.
*/
/**
* @file pqueue.h
* @brief Priority Queue function declarations
*
* @{
*/
#ifndef PRIORITY_QUEUE_H
#define PRIORITY_QUEUE_H
#include "../../../memory_.h"
#include "../../../timer.h"
/** priority data type */
typedef hlt_time priority_queue_pri_t;
/** the priority queue handle */
typedef struct priority_queue_t
{
size_t size;
size_t avail;
size_t step;
void **d;
} priority_queue_t;
/**
* initialize the queue
*
* @param n the initial estimate of the number of queue items for which memory
* should be preallocated
* @param pri the callback function to run to assign a score to a element
* @param get the callback function to get the current element's position
* @param set the callback function to set the current element's position
*
* @Return the handle or NULL for insufficent memory
*/
priority_queue_t *
priority_queue_init(size_t n);
/**
* free all memory used by the queue
* @param q the queue
*/
void priority_queue_free(priority_queue_t *q);
/**
* return the size of the queue.
* @param q the queue
*/
size_t priority_queue_size(priority_queue_t *q);
/**
* insert an item into the queue.
* @param q the queue
* @param d the item
* @return 0 on success
*/
int priority_queue_insert(priority_queue_t *q, void *d);
/**
* move an existing entry to a different priority
* @param q the queue
* @param old the old priority
* @param d the entry
*/
void
priority_queue_change_priority(priority_queue_t *q,
priority_queue_pri_t new_pri,
void *d);
/**
* pop the highest-ranking item from the queue.
* @param p the queue
* @param d where to copy the entry to
* @return NULL on error, otherwise the entry
*/
void *priority_queue_pop(priority_queue_t *q);
/**
* remove an item from the queue.
* @param p the queue
* @param d the entry
* @return 0 on success
*/
int priority_queue_remove(priority_queue_t *q, void *d);
/**
* access highest-ranking item without removing it.
* @param q the queue
* @param d the entry
* @return NULL on error, otherwise the entry
*/
void *priority_queue_peek(priority_queue_t *q);
#if 0
/**
* print the queue
* @internal
* DEBUG function only
* @param q the queue
* @param out the output handle
* @param the callback function to print the entry
*/
void
priority_queue_print(priority_queue_t *q,
FILE *out,
priority_queue_print_entry_f print);
/**
* dump the queue and it's internal structure
* @internal
* debug function only
* @param q the queue
* @param out the output handle
* @param the callback function to print the entry
*/
void
pqueueu_dump(priority_queue_t *q,
FILE *out,
priority_queue_print_entry_f print);
#endif
/**
* checks that the pq is in the right order, etc
* @internal
* debug function only
* @param q the queue
*/
int priority_queue_is_valid(priority_queue_t *q);
#endif /* PRIORITY_QUEUE_H */
/** @} */
| 2.375 | 2 |
2024-11-18T22:36:59.615805+00:00
| 2021-08-18T02:38:08 |
ab1d3f9d3860f21d606fcede5381c3e5eded9382
|
{
"blob_id": "ab1d3f9d3860f21d606fcede5381c3e5eded9382",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-18T02:38:08",
"content_id": "6cd51bbd30db2d3e72bebf508760854a05285b1c",
"detected_licenses": [
"Apache-2.0",
"curl"
],
"directory_id": "11ddbb17eebddb29a4dbd2e89cf1e403a4e5942d",
"extension": "c",
"filename": "test_networking_v1beta1_ingress_status.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": 2316,
"license": "Apache-2.0,curl",
"license_type": "permissive",
"path": "/kubernetes/unit-test/test_networking_v1beta1_ingress_status.c",
"provenance": "stackv2-0107.json.gz:87363",
"repo_name": "duokuiwang/c",
"revision_date": "2021-08-18T02:38:08",
"revision_id": "3cb0df06851a369e9b7062cb533ecf6b766e4130",
"snapshot_id": "86494f7ace5992f9402e4374e22eb5f6f67de984",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/duokuiwang/c/3cb0df06851a369e9b7062cb533ecf6b766e4130/kubernetes/unit-test/test_networking_v1beta1_ingress_status.c",
"visit_date": "2023-07-09T10:23:06.946203"
}
|
stackv2
|
#ifndef networking_v1beta1_ingress_status_TEST
#define networking_v1beta1_ingress_status_TEST
// the following is to include only the main from the first c file
#ifndef TEST_MAIN
#define TEST_MAIN
#define networking_v1beta1_ingress_status_MAIN
#endif // TEST_MAIN
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "../external/cJSON.h"
#include "../model/networking_v1beta1_ingress_status.h"
networking_v1beta1_ingress_status_t* instantiate_networking_v1beta1_ingress_status(int include_optional);
#include "test_v1_load_balancer_status.c"
networking_v1beta1_ingress_status_t* instantiate_networking_v1beta1_ingress_status(int include_optional) {
networking_v1beta1_ingress_status_t* networking_v1beta1_ingress_status = NULL;
if (include_optional) {
networking_v1beta1_ingress_status = networking_v1beta1_ingress_status_create(
// false, not to have infinite recursion
instantiate_v1_load_balancer_status(0)
);
} else {
networking_v1beta1_ingress_status = networking_v1beta1_ingress_status_create(
NULL
);
}
return networking_v1beta1_ingress_status;
}
#ifdef networking_v1beta1_ingress_status_MAIN
void test_networking_v1beta1_ingress_status(int include_optional) {
networking_v1beta1_ingress_status_t* networking_v1beta1_ingress_status_1 = instantiate_networking_v1beta1_ingress_status(include_optional);
cJSON* jsonnetworking_v1beta1_ingress_status_1 = networking_v1beta1_ingress_status_convertToJSON(networking_v1beta1_ingress_status_1);
printf("networking_v1beta1_ingress_status :\n%s\n", cJSON_Print(jsonnetworking_v1beta1_ingress_status_1));
networking_v1beta1_ingress_status_t* networking_v1beta1_ingress_status_2 = networking_v1beta1_ingress_status_parseFromJSON(jsonnetworking_v1beta1_ingress_status_1);
cJSON* jsonnetworking_v1beta1_ingress_status_2 = networking_v1beta1_ingress_status_convertToJSON(networking_v1beta1_ingress_status_2);
printf("repeating networking_v1beta1_ingress_status:\n%s\n", cJSON_Print(jsonnetworking_v1beta1_ingress_status_2));
}
int main() {
test_networking_v1beta1_ingress_status(1);
test_networking_v1beta1_ingress_status(0);
printf("Hello world \n");
return 0;
}
#endif // networking_v1beta1_ingress_status_MAIN
#endif // networking_v1beta1_ingress_status_TEST
| 2.578125 | 3 |
2024-11-18T22:37:00.972075+00:00
| 2015-08-12T20:20:37 |
734092f725f66c477df34ba6803f79410edc3676
|
{
"blob_id": "734092f725f66c477df34ba6803f79410edc3676",
"branch_name": "refs/heads/master",
"committer_date": "2015-08-12T20:20:37",
"content_id": "77dcf10d6ea0ae7a11b244c9839192c52610b6e9",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "86f026381e488b879214d22f28b68fb6eb23cd6d",
"extension": "c",
"filename": "pnbin.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 33747410,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3492,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/pdb/pnbin.c",
"provenance": "stackv2-0107.json.gz:88264",
"repo_name": "sabrown256/pactnew",
"revision_date": "2015-08-12T20:20:37",
"revision_id": "c5952f6edb5e41fbd91ed91cc3f0038cc59505a0",
"snapshot_id": "1490a4a46fe71d3bf3ad15fb449b8f7f3869135b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/sabrown256/pactnew/c5952f6edb5e41fbd91ed91cc3f0038cc59505a0/pdb/pnbin.c",
"visit_date": "2016-09-06T13:37:35.294245"
}
|
stackv2
|
/*
* PNBIN.C - binary IO for PDBNet
*
*/
#include "cpyright.h"
#include "pdb_int.h"
#include "scope_proc.h"
#include "scope_dp.h"
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* PN_RECV_FORMATS - receive binary formats from the given PROCESS */
int PN_recv_formats(PROCESS *pp)
{int ok;
long nc, nr;
char s[MAX_BFSZ+2];
char *ps;
PDBfile *file;
if (pp != NULL)
{ok = SC_ERR_TRAP();
if (ok != 0)
return(FALSE);
file = pp->vif;
SC_block(pp);
SC_set_attr(pp, SC_LINE, TRUE);
if (SC_status(pp) == SC_RUNNING)
{for (nc = 0; nc < MAX_BFSZ; nc = strlen(s))
{nr = MAX_BFSZ - nc;
ps = s + nc;
SC_gets(ps, nr, pp);
if (strcmp(ps, "END FORMATS\n") == 0)
break;};}
else
SC_error(-1, "PROCESS NOT RUNNING %d %d - PN_RECV_FORMATS",
pp->status, pp->reason);
(*file->rd_prim_types)(file, s);
SC_unblock(pp);
SC_ERR_UNTRAP();};
return(TRUE);}
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* PN_SEND_FORMATS - send binary formats to the parent PROCESS connected
* - to standard in and out
*/
int PN_send_formats(void)
{int rv;
char *_PD_tbuffer;
PDBfile *pf;
PROCESS *tty;
FILE *fp;
fp = stdout;
SC_fflush_safe(fp);
SC_setbuf(fp, NULL);
tty = SC_get_terminal_process();
if (tty == NULL)
return(FALSE);
pf = (PDBfile *) tty->vif;
if (pf == NULL)
rv = FALSE;
else
{(*pf->wr_prim_types)(fp, pf->chart);
_PD_tbuffer = _PD_get_tbuffer();
io_write(_PD_tbuffer, 1, strlen(_PD_tbuffer), fp);
io_flush(fp);
CFREE(_PD_tbuffer);
PRINT(fp, "END FORMATS\n");
rv = TRUE;};
return(rv);}
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* _PN_BIN_READ - do binary read from a PROCESS */
int _PN_bin_read(void *ptr, const char *type, size_t ni, PROCESS *pp)
{int nir;
syment *ep;
PDBfile *file;
PD_smp_state *pa;
pa = _PD_get_state(-1);
file = pp->vif;
switch (SETJMP(pa->read_err))
{case ABORT : return(FALSE);
case ERR_FREE : return(TRUE);
default : memset(PD_gs.err, 0, MAXLINE);
break;};
ep = _PD_mk_syment(type, ni, 0L, NULL, NULL);
nir = _PD_sys_read(file, ep, type, ptr);
_PD_rl_syment(ep);
return(nir);}
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* _PN_BIN_WRITE - do binary write to a PROCESS */
int _PN_bin_write(void *ptr, const char *type, size_t ni, PROCESS *pp)
{int niw;
char *name;
PDBfile *file;
PD_smp_state *pa;
name = "/net-var";
pa = _PD_get_state(-1);
file = pp->vif;
switch (SETJMP(pa->write_err))
{case ABORT :
return(FALSE);
case ERR_FREE :
return(TRUE);
default :
memset(PD_gs.err, 0, MAXLINE);
break;};
niw = _PD_sys_write(file, name, ptr, ni, type, type);
return(niw);}
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
| 2.140625 | 2 |
2024-11-18T22:37:01.283136+00:00
| 2022-03-20T17:53:25 |
d73f433f0a088d95bed4fa5215c29580691174c0
|
{
"blob_id": "d73f433f0a088d95bed4fa5215c29580691174c0",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-20T17:53:25",
"content_id": "b36bdd39ab771e684573543e8758316e4b4faddb",
"detected_licenses": [
"MIT"
],
"directory_id": "15fbb35cb68bd707f6a1eee9485e2ee37fc52876",
"extension": "c",
"filename": "cs_port.c",
"fork_events_count": 23,
"gha_created_at": "2016-09-19T19:00:32",
"gha_event_created_at": "2023-07-06T21:24:19",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 68636610,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 340,
"license": "MIT",
"license_type": "permissive",
"path": "/master-firmware/src/base/cs_port.c",
"provenance": "stackv2-0107.json.gz:88910",
"repo_name": "cvra/robot-software",
"revision_date": "2022-03-20T17:53:25",
"revision_id": "dcbfa7a99c452145e53142c182ae909079a63962",
"snapshot_id": "f922ec80a5d24f6d7904c1586a9d5f5aa7c1b4bf",
"src_encoding": "UTF-8",
"star_events_count": 42,
"url": "https://raw.githubusercontent.com/cvra/robot-software/dcbfa7a99c452145e53142c182ae909079a63962/master-firmware/src/base/cs_port.c",
"visit_date": "2023-07-20T09:58:30.975456"
}
|
stackv2
|
#include "cs_port.h"
void cs_pid_set_out_divider(void* _pid, float divider)
{
cs_pid_t* pid = (cs_pid_t*)_pid;
pid->divider = divider;
}
int32_t cs_pid_process(void* _pid, int32_t error)
{
cs_pid_t* pid = (cs_pid_t*)_pid;
float cmd = pid_process(&(pid->pid), (float)error / pid->divider);
return cmd * pid->divider;
}
| 2.375 | 2 |
2024-11-18T22:37:01.984832+00:00
| 2021-12-06T11:37:59 |
217d5f78d88ac832244f0e2113a0ddf35df3285b
|
{
"blob_id": "217d5f78d88ac832244f0e2113a0ddf35df3285b",
"branch_name": "refs/heads/master",
"committer_date": "2021-12-06T11:37:59",
"content_id": "cea16bdc8ced787ea8fe44feb8d3520a4e346a97",
"detected_licenses": [
"MIT"
],
"directory_id": "55368cb4c9d5fec97deaec8db38e9956c9e98435",
"extension": "c",
"filename": "ft_min_d.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 185663154,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1705,
"license": "MIT",
"license_type": "permissive",
"path": "/Math/ft_min_d.c",
"provenance": "stackv2-0107.json.gz:89038",
"repo_name": "akharrou/42-Project-Libft",
"revision_date": "2021-12-06T11:37:59",
"revision_id": "14a50e8706c8816d470625db4e7b027c956d89dd",
"snapshot_id": "4714abc378f891f6ff9c2c554f0417ca25b4e67c",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/akharrou/42-Project-Libft/14a50e8706c8816d470625db4e7b027c956d89dd/Math/ft_min_d.c",
"visit_date": "2021-12-14T17:18:39.662735"
}
|
stackv2
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_min_d.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akharrou <akharrou@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/16 22:22:32 by akharrou #+# #+# */
/* Updated: 2019/03/16 22:33:19 by akharrou ### ########.fr */
/* */
/* ************************************************************************** */
/*
** NAME
** ft_min_d -- get the minimum value of a vector.
**
** SYNOPSIS
** #include "math_42.h"
**
** double
** ft_min_d(double *vector, unsigned int size);
**
** PARAMETERS
**
** double *vector Vector containing numbers (of type double).
**
** unsigned int size Size of the vector.
**
** DESCRIPTION
** Iterates through the vector finds the minimum value of the vector
** and returns it.
**
** RETURN VALUES
** Returns the minimum value found in the vector.
*/
double ft_min_d(double *vector, unsigned int size)
{
unsigned int i;
double min;
if (vector && size > 0)
{
min = vector[0];
i = 0;
while (size > ++i)
min = (vector[i] < min) ? vector[i] : min;
return (min);
}
return (0);
}
| 3.125 | 3 |
2024-11-18T22:37:02.500129+00:00
| 2019-10-20T15:39:40 |
2969e56af1f0bdcdf1f2e85b5eed57e05143ce9e
|
{
"blob_id": "2969e56af1f0bdcdf1f2e85b5eed57e05143ce9e",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-20T15:39:40",
"content_id": "0d78975fe9e754bd1395bfc94a25c3612b06b41d",
"detected_licenses": [
"MIT"
],
"directory_id": "4ad1363d6d8f64a105acf76232389df57daa2304",
"extension": "c",
"filename": "mh_tabu_search.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 212425552,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15686,
"license": "MIT",
"license_type": "permissive",
"path": "/trajectory_based_mh/tabu_search/tabu_search/mh_tabu_search.c",
"provenance": "stackv2-0107.json.gz:89556",
"repo_name": "javierprtvel/metaheuristics",
"revision_date": "2019-10-20T15:39:40",
"revision_id": "7bc05b5c5c2c0f01eed9cfe76f6baf1351e463cc",
"snapshot_id": "98e86f285e1b4d72758f17058d098d356c52d9dd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/javierprtvel/metaheuristics/7bc05b5c5c2c0f01eed9cfe76f6baf1351e463cc/trajectory_based_mh/tabu_search/tabu_search/mh_tabu_search.c",
"visit_date": "2020-08-05T06:12:04.467447"
}
|
stackv2
|
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "tabu_list.h"
#include "tsp.h"
#define ITE_REINITIALIZATION 100
#define ITE_STOP 10000
typedef unsigned char** PERMUTATIONS; // binary flag matrix that marks generated permutations (lower triangular)
PERMUTATIONS p;
tabu_list lt = NULL;
SOLUTION current_solution = NULL, s_prime = NULL, best_neighbour = NULL;
int next_neighbour_i = 0, next_neighbour_j = 0;
unsigned int city = -1;
unsigned char any_neighbours_left = (unsigned char) 0;
unsigned int neighbour_fitness = -1, best_neighbour_fitness = -1;
INSERTION insertion_prime, best_neighbour_insertion;
unsigned int reset_count = 0;
void initialize_permutations() {
int i = 0, j = 0;
p = (unsigned char **)calloc(n_cities - 2, sizeof(unsigned char*));
for(; i < n_cities - 2; i++) {
p[i] = (unsigned char *)calloc(i + 1, sizeof(unsigned char));
for(j = 0; j < i + 1; j++) {
p[i][j] = (unsigned char) 0;
}
}
}
void reset_permutations() {
int i = 0, j = 0;
for(; i < n_cities - 2; i++) {
for(j = 0; j < i + 1; j++) {
p[i][j] = (unsigned char) 0;
}
}
}
void free_permutations() {
if(p != NULL) {
int i = 0;
for(; i < n_cities - 2; i++) {
if(p[i] != NULL) {
free(p[i]);
p[i] = NULL;
}
}
free(p);
p = NULL;
}
}
/******TABU SEARCH******/
void generate_initial_solution() {
int i = 0, j = 0;
for(; i < n_cities - 1; i++) {
solution[i] = 1 + floor(drand48() * (n_cities - 1));
for(j = 0; j < i; j++) {
if(solution[i] == solution[j]) {
int repeated = 0;
do {
repeated = 0;
solution[i] = solution[i] % (n_cities - 1) + 1;
for(j = 0; j < i; j++) {
if(solution[i] == solution[j]) {
repeated = 1;
break;
}
}
} while(repeated);
break;
}
}
}
}
int aspiration_criteria_compliance(SOLUTION s) {
if(fitness(s) < fitness(solution)) {
return 1;
}
else {
return 0;
}
}
void insertion(int city_index, int insertion_index) {
int i, j;
unsigned int insertion_value;
insertion_value = current_solution[city_index];
if(insertion_index < city_index) {
for(i = 0; i < insertion_index; i++) {
s_prime[i] = current_solution[i];
}
s_prime[insertion_index] = insertion_value;
for(i = insertion_index, j = insertion_index + 1; i < city_index; i++, j++) {
s_prime[j] = current_solution[i];
}
for(i = city_index + 1; i < n_cities - 1; i++) {
s_prime[i] = current_solution[i];
}
}
else if(insertion_index > city_index) {
for(i = 0; i < city_index; i++) {
s_prime[i] = current_solution[i];
}
for(i = city_index + 1, j = city_index; i <= insertion_index; i++, j++) {
s_prime[j] = current_solution[i];
}
s_prime[insertion_index] = insertion_value;
for(i = insertion_index + 1; i < n_cities - 1; i++) {
s_prime[i] = current_solution[i];
}
}
neighbour_fitness = fitness(s_prime);
}
void generate_neighbour() {
int i = 0, j = 0;
// assign new neighbour to s_prime
insertion(insertion_prime.city_index, insertion_prime.insertion_index);
if(aspiration_criteria_compliance(s_prime) || !is_tabu(lt, insertion_prime)) {
neighbour_fitness = fitness(s_prime);
}
else {
neighbour_fitness = 0;
}
p[i][j] = (unsigned char) 1;
next_neighbour_j = (j + 1) % (i + 1);
next_neighbour_i = (next_neighbour_j == 0)? i + 1 : i;
}
unsigned int tabu_search() {
unsigned int solution_fitness = 0;
unsigned int city_index = -1;
unsigned int insertion_index = -1, best_insertion_index = -1;
p = NULL;
initialize_permutations();
any_neighbours_left = (unsigned char) 1;
lt = NULL;
create_tabu_list(<, n_cities);
current_solution = (unsigned int *)calloc(n_cities - 1, sizeof(unsigned int));
s_prime = (unsigned int *)calloc(n_cities - 1, sizeof(unsigned int));
best_neighbour = (unsigned int *)calloc(n_cities - 1, sizeof(unsigned int));
neighbour_fitness = -1;
best_neighbour_fitness = -1;
reset_count = 0;
if(p != NULL && lt != NULL && current_solution != NULL && best_neighbour != NULL && s_prime != NULL) {
int i = 0, j = 1, ite_without_improvement = 0, ite_solution = 0;
srand48((unsigned)time(NULL));
generate_initial_solution();
solution_fitness = fitness(solution);
printf("INITIAL WALK\n");
printf("\tWALK:");
for(i = 0; i < n_cities - 1; i++) {
printf(" %u", solution[i]);
}
printf(" \n");
printf("\tFITNESS (km): %u\n", solution_fitness);
for(i = 0; i < n_cities - 1; i++) {
current_solution[i] = solution[i]; // first current solution: initial solution
}
do {
printf("\nITERATION: %d\n", j);
city_index = floor(drand48() * (n_cities - 1));
insertion_prime.city_index = city_index;
city = current_solution[city_index];
printf("\tCITY INDEX: %d\n", city_index);
printf("\tCITY: %u\n", city);
// initially, best neighbour is the first one
neighbour_fitness = 0;
insertion_index = (city_index + 1) % (n_cities - 1);
insertion_prime.insertion_index = insertion_index;
generate_neighbour();
best_neighbour_fitness = neighbour_fitness;
best_insertion_index = insertion_index;
insertion_prime.insertion_index = best_insertion_index;
memcpy(&best_neighbour_insertion, &insertion_prime, sizeof(INSERTION));
insertion_index = (insertion_index + 1) % (n_cities - 1);
// search best, non-tabu neighbour
do {
generate_neighbour();
if(neighbour_fitness != 0 && (neighbour_fitness < best_neighbour_fitness || (neighbour_fitness == best_neighbour_fitness && insertion_index < best_insertion_index))) {
for(i = 0; i < n_cities - 1; i++) {
best_neighbour[i] = s_prime[i];
}
best_neighbour_fitness = neighbour_fitness;
memcpy(&best_neighbour_insertion, &insertion_prime, sizeof(INSERTION));
}
insertion_index = (insertion_index + 1) % (n_cities - 1);
insertion_prime.insertion_index = insertion_index;
} while(insertion_index != city_index);
printf("\tINSERTION: (%u, %u)\n", best_neighbour_insertion.city_index, best_neighbour_insertion.insertion_index);
// assign best to current solution and add insertion to tabu list
printf("\tWALK:");
for(i = 0; i < n_cities - 1; i++) {
current_solution[i] = best_neighbour[i];
printf(" %u", current_solution[i]);
}
printf(" \n");
printf("\tFITNESS (km): %u\n", fitness(current_solution));
insert_tabu(lt, best_neighbour_insertion);
if(best_neighbour_fitness < solution_fitness) { // best neighbour is global optimum
for(i = 0; i < n_cities - 1; i++) {
solution[i] = best_neighbour[i];
}
solution_fitness = fitness(solution);
ite_solution = j;
ite_without_improvement = 0;
}
else { // best neighbour does not improve current optimal solution
ite_without_improvement++;
}
printf("\tITERATIONS WITHOUT IMPROVEMENT: %d\n", ite_without_improvement);
print_tabu_list(lt);
if(ite_without_improvement == ITE_REINITIALIZATION) {
// reinitialization
for(i = 0; i < n_cities - 1; i++) {
current_solution[i] = solution[i];
}
empty_tabu_list(lt);
ite_without_improvement = 0;
reset_count++;
printf("\n***************\nREINITIALIZATION: %u\n***************\n", reset_count);
}
any_neighbours_left = (unsigned char) 1;
next_neighbour_i = 0;
next_neighbour_j = 0;
j++;
} while(j <= ITE_STOP);
printf("\n\nBEST SOLUTION: \n");
printf("\tWALK:");
for(i = 0; i < n_cities - 1; i++) {
printf(" %u", solution[i]);
}
printf(" \n");
printf("\tFITNESS (km): %u\n", solution_fitness);
printf("\tITERATION: %d\n", ite_solution);
}
if(best_neighbour != NULL) {
free(best_neighbour);
best_neighbour = NULL;
}
if(s_prime != NULL) {
free(s_prime);
s_prime = NULL;
}
if(current_solution != NULL) {
free(current_solution);
current_solution = NULL;
}
free_tabu_list(<);
free_permutations();
return solution_fitness;
}
/******TABU SEARCH FROM FILE******/
FILE *random_file = NULL;
void generate_initial_solution_file() {
int i = 0, j = 0;
double r = 0.0;
for(; i < n_cities - 1; i++) {
fscanf(random_file, "%lf\r\n", &r);
solution[i] = 1 + floor(r * (n_cities - 1));
for(j = 0; j < i; j++) {
if(solution[i] == solution[j]) {
int repeated = 0;
do {
repeated = 0;
solution[i] = solution[i] % (n_cities - 1) + 1;
for(j = 0; j < i; j++) {
if(solution[i] == solution[j]) {
repeated = 1;
break;
}
}
} while(repeated);
break;
}
}
}
}
unsigned int tabu_search_file(char* trace) {
unsigned int solution_fitness = 0;
random_file = fopen(trace, "r");
if(random_file != NULL) {
p = NULL;
initialize_permutations();
any_neighbours_left = (unsigned char) 1;
lt = NULL;
create_tabu_list(<, n_cities);
current_solution = (unsigned int *)calloc(n_cities - 1, sizeof(unsigned int));
s_prime = (unsigned int *)calloc(n_cities - 1, sizeof(unsigned int));
best_neighbour = (unsigned int *)calloc(n_cities - 1, sizeof(unsigned int));
neighbour_fitness = -1;
best_neighbour_fitness = -1;
reset_count = 0;
if(p != NULL && lt != NULL && current_solution != NULL && best_neighbour != NULL && s_prime != NULL) {
int i = 0, j = 1, ite_without_improvement = 0, ite_solution = 0;
srand48((unsigned)time(NULL));
generate_initial_solution_file();
fclose(random_file);
random_file = NULL;
solution_fitness = fitness(solution);
printf("INITIAL WALK\n");
printf("\tWALK:");
for(i = 0; i < n_cities - 1; i++) {
printf(" %u", solution[i]);
}
printf(" \n");
printf("\tFITNESS (km): %u\n", solution_fitness);
for(i = 0; i < n_cities - 1; i++) {
current_solution[i] = solution[i]; // first current solution: initial solution
}
do {
printf("\nITERATION: %d\n", j);
// initially, best neighbour is the first one
neighbour_fitness = 0;
do {
generate_neighbour();
} while(neighbour_fitness == 0);
for(i = 0; i < n_cities - 1; i++) {
best_neighbour[i] = s_prime[i];
}
best_neighbour_fitness = neighbour_fitness;
memcpy(&best_neighbour_insertion, &insertion, sizeof(PERMUTATION));
// search best, non-tabu neighbour
do {
generate_neighbour();
if(neighbour_fitness != 0 && neighbour_fitness < best_neighbour_fitness) {
for(i = 0; i < n_cities - 1; i++) {
best_neighbour[i] = s_prime[i];
}
best_neighbour_fitness = neighbour_fitness;
memcpy(&best_neighbour_insertion, &insertion, sizeof(PERMUTATION));
}
} while(any_neighbours_left);
printf("\tPERMUTATION: (%u, %u)\n", best_neighbour_insertion.city_index, best_neighbour_insertion.insertion_index);
// assign best to current solution and add insertion to tabu list
printf("\tWALK:");
for(i = 0; i < n_cities - 1; i++) {
current_solution[i] = best_neighbour[i];
printf(" %u", current_solution[i]);
}
printf(" \n");
printf("\tFITNESS (km): %u\n", fitness(current_solution));
insert_tabu(lt, best_neighbour_insertion);
if(best_neighbour_fitness < solution_fitness) { // best neighbour is global optimum
for(i = 0; i < n_cities - 1; i++) {
solution[i] = best_neighbour[i];
}
solution_fitness = fitness(solution);
ite_solution = j;
ite_without_improvement = 0;
}
else { // best neighbour does not improve current optimal
ite_without_improvement++;
}
printf("\tITERATIONS WITHOUT IMPROVEMENT: %d\n", ite_without_improvement);
print_tabu_list(lt);
if(ite_without_improvement == ITE_REINITIALIZATION) {
// reinitialization
for(i = 0; i < n_cities - 1; i++) {
current_solution[i] = solution[i];
}
empty_tabu_list(lt);
ite_without_improvement = 0;
reset_count++;
printf("\n***************\nREINITIALIZATION: %u\n***************\n", reset_count);
}
reset_permutations();
any_neighbours_left = (unsigned char) 1;
next_neighbour_i = 0;
next_neighbour_j = 0;
j++;
} while(j <= ITE_STOP);
printf("\n\nBEST SOLUTION: \n");
printf("\tWALK:");
for(i = 0; i < n_cities - 1; i++) {
printf(" %u", solution[i]);
}
printf(" \n");
printf("\tFITNESS (km): %u\n", solution_fitness);
printf("\tITERATION: %d\n", ite_solution);
}
if(best_neighbour != NULL) {
free(best_neighbour);
best_neighbour = NULL;
}
if(s_prime != NULL) {
free(s_prime);
s_prime = NULL;
}
if(current_solution != NULL) {
free(current_solution);
current_solution = NULL;
}
free_tabu_list(<);
free_permutations();
}
return solution_fitness;
}
| 2.375 | 2 |
2024-11-18T22:37:03.447663+00:00
| 2017-09-01T09:17:45 |
cee0d2700d860757044324a16c059be47ee1cf28
|
{
"blob_id": "cee0d2700d860757044324a16c059be47ee1cf28",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-01T09:17:45",
"content_id": "326fb55806b767865498f66afe17b08b05787c11",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a23e7d66be17ea87501290d1d3ec2768cb9addee",
"extension": "h",
"filename": "parse_log_sense.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 101404550,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4285,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/libscsicmd/include/parse_log_sense.h",
"provenance": "stackv2-0107.json.gz:90074",
"repo_name": "baruch/disksurvey1",
"revision_date": "2017-09-01T09:17:45",
"revision_id": "b68836547cbb37a00dc5a6a87e03a5228e75b285",
"snapshot_id": "a6c27c2eb43e845ee1d2227011cd88f6fe8386b1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/baruch/disksurvey1/b68836547cbb37a00dc5a6a87e03a5228e75b285/libscsicmd/include/parse_log_sense.h",
"visit_date": "2021-01-20T04:58:46.402341"
}
|
stackv2
|
/* Copyright 2015 Baruch Even
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef LIBSCSICMD_LOG_SENSE_H
#define LIBSCSICMD_LOG_SENSE_H
#include "scsicmd_utils.h"
#include <stdint.h>
#include <stdbool.h>
/* Log Sense Header decode */
#define LOG_SENSE_MIN_LEN 4
static inline uint8_t log_sense_page_code(uint8_t *data)
{
return data[0] & 0x3F;
}
static inline bool log_sense_subpage_format(uint8_t *data)
{
return data[0] & 0x40;
}
static inline bool log_sense_data_saved(uint8_t *data)
{
return data[0] & 0x80;
}
static inline uint8_t log_sense_subpage_code(uint8_t *data)
{
return data[1];
}
static inline unsigned log_sense_data_len(uint8_t *data)
{
return get_uint16(data, 2);
}
static inline uint8_t *log_sense_data(uint8_t *data)
{
return data + LOG_SENSE_MIN_LEN;
}
static inline uint8_t *log_sense_data_end(uint8_t *data, unsigned data_len)
{
return data + safe_len(data, data_len, log_sense_data(data), log_sense_data_len(data));
}
static inline bool log_sense_is_valid(uint8_t *data, unsigned data_len)
{
if (data_len < LOG_SENSE_MIN_LEN)
return false;
if (!log_sense_subpage_format(data) && log_sense_subpage_code(data) != 0)
return false;
if (log_sense_data_len(data) + LOG_SENSE_MIN_LEN < data_len)
return false;
return true;
}
/* Log Sense Parameter decode */
#define LOG_SENSE_MIN_PARAM_LEN 4
#define LOG_PARAM_FLAG_DU 0x80
#define LOG_PARAM_FLAG_TSD 0x20
#define LOG_PARAM_FLAG_ETC 0x10
#define LOG_PARAM_FLAG_TMC_MASK 0x0C
#define LOG_PARAM_FLAG_FMT_MASK 0x03
#define LOG_PARAM_TMC_EVERY_UPDATE 0
#define LOG_PARAM_TMC_EQUAL 1
#define LOG_PARAM_TMC_NOT_EQUAL 2
#define LOG_PARAM_TMC_GREATER 3
#define LOG_PARAM_FMT_COUNTER_STOP 0
#define LOG_PARAM_FMT_ASCII 1
#define LOG_PARAM_FMT_COUNTER_ROLLOVER 2
#define LOG_PARAM_FMT_BINARY 2
static inline uint16_t log_sense_param_code(uint8_t *param)
{
return get_uint16(param, 0);
}
inline static uint8_t log_sense_param_flags(uint8_t *param)
{
return param[2];
}
inline static uint8_t log_sense_param_tmc(uint8_t *param)
{
return (log_sense_param_flags(param) & LOG_PARAM_FLAG_TMC_MASK) >> 2;
}
inline static uint8_t log_sense_param_fmt(uint8_t *param)
{
return log_sense_param_flags(param) & LOG_PARAM_FLAG_FMT_MASK;
}
static inline unsigned log_sense_param_len(uint8_t *param)
{
return param[3];
}
static inline uint8_t *log_sense_param_data(uint8_t *param)
{
return param + LOG_SENSE_MIN_PARAM_LEN;
}
static inline bool log_sense_param_is_valid(uint8_t *data, unsigned data_len, uint8_t *param)
{
if (param < data)
return false;
const unsigned param_offset = param - data;
if (param_offset > data_len)
return false;
if (param_offset + LOG_SENSE_MIN_PARAM_LEN > data_len)
return false;
if (param_offset + LOG_SENSE_MIN_PARAM_LEN + log_sense_param_len(param) > data_len)
return false;
return true;
}
#define for_all_log_sense_params(data, data_len, param) \
for (param = log_sense_data(data); \
log_sense_param_is_valid(data, data_len, param); \
param = param + LOG_SENSE_MIN_PARAM_LEN + log_sense_param_len(param))
#define for_all_log_sense_pg_0_supported_pages(data, data_len, supported_page) \
uint8_t *__tmp; \
for (__tmp = log_sense_data(data), supported_page = __tmp[0]; __tmp < log_sense_data_end(data, data_len); __tmp++, supported_page = __tmp[0])
#define for_all_log_sense_pg_0_supported_subpages(data, data_len, supported_page, supported_subpage) \
uint8_t *__tmp; \
for (__tmp = log_sense_data(data), supported_page = __tmp[0], supported_subpage = __tmp[1]; __tmp + 1 < log_sense_data_end(data, data_len); __tmp+=2, supported_page = __tmp[0], supported_subpage = __tmp[1])
bool log_sense_page_informational_exceptions(uint8_t *page, unsigned page_len, uint8_t *asc, uint8_t *ascq, uint8_t *temperature);
#endif
| 2.046875 | 2 |
2024-11-18T22:37:03.544599+00:00
| 2023-06-30T13:45:10 |
fb672682943f77662b72f180ba956343a49c8773
|
{
"blob_id": "fb672682943f77662b72f180ba956343a49c8773",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-30T13:45:10",
"content_id": "5e8e7f2fb3365f75efb38ffdef53a1ae298cdc2e",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "06c702ac49cac44d1956a45a5f84a82f5e173a64",
"extension": "c",
"filename": "rss.c",
"fork_events_count": 0,
"gha_created_at": "2012-11-21T17:24:32",
"gha_event_created_at": "2013-03-20T12:48:13",
"gha_language": "C",
"gha_license_id": null,
"github_id": 6799848,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8890,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/rss.c",
"provenance": "stackv2-0107.json.gz:90203",
"repo_name": "koue/rssroll",
"revision_date": "2023-06-30T13:45:10",
"revision_id": "4eabc8e2d796b8841a08d0e2e8b2770b4c0d80f9",
"snapshot_id": "8189c1c1d8eef428f3c97fa5bc47f73622cb546d",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/koue/rssroll/4eabc8e2d796b8841a08d0e2e8b2770b4c0d80f9/src/rss.c",
"visit_date": "2023-07-26T02:35:18.230627"
}
|
stackv2
|
/*
* Copyright (c) 2018-2023 Nikola Kolev <koue@chaosophia.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "rss.h"
#include "xml.h"
static struct feed *
feed_create(void)
{
struct pool *pool = pool_create(1024);
struct feed *feed = pool_alloc(pool, sizeof(struct feed));
/* Make sure cleared out */
memset(feed, 0, sizeof(struct feed));
/* Common */
feed->pool = pool;
feed->version = 0;
feed->title = NULL;
feed->url = NULL;
feed->desc = NULL;
feed->doc = NULL;
time_t date = 0;
return (feed);
}
static void
feed_free(struct feed *feed)
{
pool_free(feed->pool);
}
static void
rss_sanity_check(struct feed *rss)
{
struct item *item;
int count = 0;
TAILQ_FOREACH(item, &rss->items_list, entry) {
printf("title: %s\nurl: %s\ndate: %ld\ndesc: %s\n\n",
item->title, item->url, (long)item->date, item->desc);
count++;
}
printf("%d entries\n", count);
}
int
rss_close(struct feed *rss)
{
dmsg(1, "%s: start", __func__);
feed_free(rss);
dmsg(1, "%s: end", __func__);
return (0);
}
static void
rss_channel(struct feed *rss, xmlNode *pnode)
{
struct pool *pool = rss->pool;
xmlDoc *doc = rss->doc;
dmsg(1, "%s: start", __func__);
while (pnode) {
dmsg(1, "%s: pnode->name: %s", __func__, (char *) pnode->name);
if (xml_isnode(pnode, "title", 0)) {
rss->title = xml_get_content(pool, pnode);
} else if (xml_isnode(pnode, "description", 0)) {
rss->desc = xml_get_content(pool, pnode);
} else {
xml_isnode_date(pnode, &rss->date);
}
pnode = pnode->next;
}
dmsg(1, "%s: end", __func__);
}
static int
rss_entry(struct feed *rss, xmlNode *pnode)
{
struct item *current;
struct pool *pool = rss->pool;
xmlDoc *doc = rss->doc;
char *p = NULL, *link = NULL, *guid = NULL;
dmsg(1, "%s: start", __func__);
if ((current = item_create(pool)) == NULL) {
goto fail;
}
while (pnode) {
while (pnode && xmlIsBlankNode(pnode))
pnode = pnode->next;
if (pnode == NULL)
break;
dmsg(1, "%s: pnode->name: %s", __func__, (char *)pnode->name);
if (xml_isnode(pnode, "title", 0)) {
current->title = xml_get_content(pool, pnode);
} else if (xml_isnode(pnode, "link", 0)) {
// atom
if ((p = xml_get_value(pool, pnode, "rel")) != NULL) {
if (strcmp(p, "alternate") == 0) {
link = xml_get_value(pool, pnode, "href");
}
// rss
} else {
link = xml_get_content(pool, pnode);
}
} else if (xml_isnode(pnode, "guid", 0)) {
guid = xml_get_content(pool, pnode);
} else if (xml_isnode(pnode, "description", 0)) {
current->desc = xml_get_content(pool, pnode);
} else if (xml_isnode(pnode, "content", 0)) {
current->desc = xml_get_content(pool, pnode);
} else {
xml_isnode_date(pnode, ¤t->date);
}
pnode = pnode->next;
}
// some feeds use the guid tag for the link
if (link) {
if ((current->url = pool_strdup(pool, link)) == NULL) {
goto fail;
}
} else {
if ((current->url = pool_strdup(pool, guid)) == NULL) {
goto fail;
}
}
/* add items in reverse order, the first is the newest one */
TAILQ_INSERT_HEAD(&rss->items_list, current, entry);
dmsg(1, "%s: end", __func__);
return (0);
fail:
feed_free(rss);
exit(1);
}
static void
rss_head(struct feed *rss, xmlNode *node)
{
struct pool *pool = rss->pool;
xmlDoc *doc = rss->doc;
dmsg(1, "%s: start", __func__);
TAILQ_INIT(&rss->items_list);
while (node) {
while (node && xmlIsBlankNode(node))
node = node->next;
if (node == NULL)
break;
dmsg(1, "%s: node->name: %s", __func__, (char *)node->name);
if (xml_isnode(node, "title", 0)) {
rss->title = xml_get_content(pool, node);
} else if (xml_isnode(node, "description", 0)) {
rss->desc = xml_get_content(pool, node);
} else if (xml_isnode(node, "channel", 0) && (rss->version == RSS_V1_0)) {
rss_channel(rss, node->xmlChildrenNode);
} else if (xml_isnode(node, "item", 0) || xml_isnode(node, "entry", 0)) {
if (rss_entry(rss, node->xmlChildrenNode) == -1) {
xmlFreeDoc(doc);
rss_close(rss);
fprintf(stderr, "%s: %s\n", __func__, strerror(errno));
exit(1);
}
} else {
xml_isnode_date(node, &rss->date);
}
node = node->next;
}
dmsg(1, "%s: end", __func__);
}
static int
rss_version_atom(struct pool *pool, xmlNode *node)
{
int version = ATOM_V0_1; //default
char *p = NULL;
if ((p = xml_get_value(pool, node, "version")) == NULL)
goto done;
else if (strcmp(p, "0.3") == 0)
version = ATOM_V0_3;
else if (strcmp(p, "0.2") == 0)
version = ATOM_V0_2;
done:
return (version);
}
static int
rss_version_rss(struct pool *pool, xmlNode *node)
{
int version = -1;
char *p = NULL;
if ((p = xml_get_value(pool, node, "version")) == NULL)
goto done;
else if (strcmp(p, "0.91") == 0)
version = RSS_V0_91;
else if (strcmp(p, "0.92") == 0)
version = RSS_V0_92;
else if (strcmp(p, "0.93") == 0)
version = RSS_V0_93;
else if (strcmp(p, "0.94") == 0)
version = RSS_V0_94;
else if ((strcmp(p, "2") == 0) || (strcmp(p, "2.0") == 0) ||
(strcmp(p, "2.00") == 0))
version = RSS_V2_0;
done:
return (version);
}
static int
rss_demux(struct feed *rss, xmlNode *node)
{
struct pool *pool = rss->pool;
int version = -1;
dmsg(1, "%s: start", __func__);
if ((char *)node->name == NULL)
goto done;
else if (xml_isnode(node, "html", 0)) // not xml
goto done;
else if (xml_isnode(node, "feed", 0)) {
version = rss_version_atom(pool, node);
} else if (xml_isnode(node, "rss", 0)) {
version = rss_version_rss(pool, node);
} else if (xml_isnode(node, "rdf", 0) || xml_isnode(node, "RDF", 0)) {
version = RSS_V1_0;
}
done:
dmsg(1, "%s: end", __func__);
return (version);
}
struct feed *
rss_parse(const char *xmlstream, int isfile)
{
struct feed *rss;
xmlNode *node;
xmlDoc *doc;
dmsg(1, "%s: start", __func__);
if ((rss = feed_create()) == NULL)
return (NULL);
doc = rss->doc;
if (isfile)
doc = xmlParseFile(xmlstream);
else
doc = xmlParseDoc((const xmlChar *)xmlstream);
if (doc == NULL) {
fprintf(stderr, "%s: cannot read stream\n", __func__);
goto fail;
}
if ((node = xmlDocGetRootElement(doc)) == NULL) {
fprintf (stderr, "%s: empty document\n", __func__);
goto faildoc;
}
if ((rss->version = rss_demux(rss, node)) == -1) {
fprintf (stderr, "%s: unknown document\n", __func__);
goto faildoc;
}
node = node->xmlChildrenNode;
while (node && xmlIsBlankNode(node))
node = node->next;
if (node == NULL) {
fprintf(stderr, "%s: bad document\n", __func__);
goto faildoc;
} else if (rss->version < ATOM_V0_1) {
if (xml_isnode(node, "channel", 0) == 0) {
fprintf (stderr, "%s: bad document: channel missing\n", __func__);
goto faildoc;
} else if (rss->version != RSS_V1_0) // document is RSS
node = node->xmlChildrenNode;
}
rss_head(rss, node);
if (debug > 1) {
rss_sanity_check(rss);
fflush(stdout);
}
dmsg(1, "%s: end", __func__);
xmlFreeDoc(doc);
return (rss);
faildoc:
xmlFreeDoc(doc);
fail:
feed_free(rss);
return (NULL);
}
/* debug message out */
void
dmsg(int verbose, const char *fmt, ...)
{
if (debug > verbose) {
va_list ap;
time_t t = time(NULL);
struct tm *tm = gmtime(&t);
fprintf(stdout, "%4.4d.%2.2d.%2.2d %2.2d:%2.2d:%2.2d ",
tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour,
tm->tm_min, tm->tm_sec);
va_start(ap, fmt);
vfprintf(stdout, fmt, ap);
va_end(ap);
fprintf(stdout, "\n");
fflush(stdout);
}
}
| 2 | 2 |
2024-11-18T22:37:03.976593+00:00
| 2023-08-31T02:16:24 |
231b505940f841537db5b171a5368418cb1ef2c9
|
{
"blob_id": "231b505940f841537db5b171a5368418cb1ef2c9",
"branch_name": "refs/heads/vlm_master",
"committer_date": "2023-08-31T02:16:24",
"content_id": "fda63c3389d3f33b8970a91be6425c43c698be1a",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "853f3da12f4c0c5b4c5584e71537e4a81458bcce",
"extension": "c",
"filename": "check-25.-fwide-types.c",
"fork_events_count": 72,
"gha_created_at": "2016-12-22T20:44:21",
"gha_event_created_at": "2023-09-01T00:25:27",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 77174670,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5998,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/tests/tests-c-compiler/check-src/check-25.-fwide-types.c",
"provenance": "stackv2-0107.json.gz:90590",
"repo_name": "mouse07410/asn1c",
"revision_date": "2023-08-31T02:16:24",
"revision_id": "208d9edd4f14feec25a21788c0a515cf4ae8b0cb",
"snapshot_id": "b85071e689d9352ac46ade60992c3ba9a9ed16f5",
"src_encoding": "UTF-8",
"star_events_count": 71,
"url": "https://raw.githubusercontent.com/mouse07410/asn1c/208d9edd4f14feec25a21788c0a515cf4ae8b0cb/tests/tests-c-compiler/check-src/check-25.-fwide-types.c",
"visit_date": "2023-08-31T14:52:00.747113"
}
|
stackv2
|
#undef NDEBUG
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <assert.h>
#include <T.h>
uint8_t buf1[] = {
32 | 16, /* [UNIVERSAL 16], constructed */
128, /* L */
/* a INTEGER */
2, /* [UNIVERSAL 2] */
2, /* L */
150,
70,
/* b [2] IMPLICIT BOOLEAN */
128 | 2, /* [2] */
1, /* L */
0xff,
/* c NULL */
5, /* [UNIVERSAL 5] */
0, /* L */
/* d ENUMERATED */
10, /* [UNIVERSAL 10] */
1, /* L */
222,
/* e OCTET STRING */
4, /* [UNIVERSAL 4] */
3, /* L */
'x',
'y',
'z',
/*
* X.690 specifies that inner structures must be tagged by
* stripping off the outer tag for each subsequent level.
*/
/* f [5] IMPLICIT VisibleString */
128 | 32 | 5, /* [5], constructed */
128, /* L indefinite */
26, /* [UNIVERSAL 26] (VisibleString), primitive */
2,
'l',
'o',
32 | 26, /* [UNIVERSAL 26], recursively constructed */
128,
4, /* [UNIVERSAL 4] (OCTET STRING), primitive */
1,
'v',
4, /* [UNIVERSAL 4], primitive */
2,
'e',
'_',
0,
0,
26, /* [UNIVERSAL 26], primitive */
2,
'i',
't',
0,
0,
/* g BIT STRING */
3, /* [UNIVERSAL 3], primitive */
3, /* L */
2, /* Skip 2 bits */
147,
150, /* => 148 */
/* h [7] BIT STRING */
128 | 32 | 7, /* [7], constructed */
128, /* L indefinite */
3, /* [UNIVERSAL 3], primitive */
3, /* L */
0, /* Skip 0 bits */
140,
141,
3, /* [UNIVERSAL 3], primitive */
2, /* L */
1, /* Skip 1 bit */
143, /* => 142 */
0, /* End of h */
0,
0, /* End of the whole structure */
0,
/* Three bytes of planned leftover */
111, 222, 223
};
static void
check(int is_ok, uint8_t *buf, size_t size, size_t consumed) {
T_t t, *tp;
asn_dec_rval_t rval;
tp = memset(&t, 0, sizeof(t));
fprintf(stderr, "Buf %p (%zd)\n", buf, size);
rval = ber_decode(0, &asn_DEF_T, (void **)&tp, buf, size);
fprintf(stderr, "Returned code %d, consumed %zd, expected %zd\n",
(int)rval.code, rval.consumed, consumed);
if(is_ok) {
assert(rval.code == RC_OK);
assert(rval.consumed == consumed);
assert(strcmp((char *)t.e->buf, "xyz") == 0);
assert(strcmp((char *)t.f->buf, "love_it") == 0);
assert(t.g->size == 2);
assert(t.g->bits_unused == 2);
fprintf(stderr, "%d %d\n", t.g->buf[0], t.g->buf[1]);
assert(t.g->buf[0] == 147);
assert(t.g->buf[1] != 150);
assert(t.g->buf[1] == 148);
assert(t.h->size == 3);
assert(t.h->bits_unused == 1);
assert(t.h->buf[0] == 140);
assert(t.h->buf[1] == 141);
assert(t.h->buf[2] == 142);
} else {
if(rval.code == RC_OK) {
assert(t.a.size != 2
|| !t.d
|| t.d->size != 1
|| !t.e
|| t.e->size != 3
|| !t.f
|| t.f->size != 7
|| !t.g
|| t.g->size != 2
|| !t.h
|| t.h->size != 3
);
}
fprintf(stderr, "%zd %zd\n", rval.consumed, consumed);
assert(rval.consumed <= consumed);
}
ASN_STRUCT_RESET(asn_DEF_T, &t);
}
static void
try_corrupt(uint8_t *buf, size_t size, int allow_consume) {
uint8_t tmp[size];
fprintf(stderr, "\nCorrupting...\n");
for(int i = 0; i < 1000; i++) {
int loc;
memcpy(tmp, buf, size);
/* Corrupt random _non-value_ location. */
do { loc = random() % size; } while(
loc == 44 /* bit skips */
|| loc == 51 /* bit skips */
|| loc == 56 /* bit skips */
|| tmp[loc] >= 70);
do { tmp[loc] = buf[loc] ^ random(); } while(
(tmp[loc] == buf[loc])
|| (buf[loc] == 0 && tmp[loc] == 0x80));
fprintf(stderr, "\nTry %d: corrupting byte %d (%d->%d)\n",
i, loc, buf[loc], tmp[loc]);
check(0, tmp, size, allow_consume);
}
}
static void
partial_read(uint8_t *buf, size_t size) {
T_t t, *tp;
asn_dec_rval_t rval;
uint8_t tbuf1[size];
uint8_t tbuf2[size];
uint8_t tbuf3[size];
fprintf(stderr, "\nPartial read sequence...\n");
/*
* Divide the space (size) into three blocks in various combinations:
* |<----->i1<----->i2<----->|
* ^ buf ^ buf+size
* Try to read block by block.
*/
for(size_t i1 = 0; i1 < size; i1++) {
for(size_t i2 = i1; i2 < size; i2++) {
uint8_t *chunk1 = buf;
size_t size1 = i1;
uint8_t *chunk2 = buf + size1;
size_t size2 = i2 - i1;
uint8_t *chunk3 = buf + size1 + size2;
size_t size3 = size - size1 - size2;
fprintf(stderr, "\n%d:{%d, %d, %d}...\n",
(int)size, (int)size1, (int)size2, (int)size3);
memset(tbuf1, 0, size);
memset(tbuf2, 0, size);
memset(tbuf3, 0, size);
memcpy(tbuf1, chunk1, size1);
memcpy(tbuf2, chunk2, size2);
memcpy(tbuf3, chunk3, size3);
tp = memset(&t, 0, sizeof(t));
fprintf(stderr, "=> Chunk 1 (%d):\n", (int)size1);
rval = ber_decode(0, &asn_DEF_T, (void **)&tp,
tbuf1, size1);
assert(rval.code == RC_WMORE);
assert(rval.consumed <= size1);
if(rval.consumed < size1) {
int leftover = size1 - rval.consumed;
memcpy(tbuf2, tbuf1 + rval.consumed, leftover);
memcpy(tbuf2 + leftover, chunk2, size2);
size2 += leftover;
}
fprintf(stderr, "=> Chunk 2 (%d):\n", (int)size2);
rval = ber_decode(0, &asn_DEF_T, (void **)&tp,
tbuf2, size2);
assert(rval.code == RC_WMORE);
assert(rval.consumed <= size2);
if(rval.consumed < size2) {
int leftover = size2 - rval.consumed;
memcpy(tbuf3, tbuf2 + rval.consumed, leftover);
memcpy(tbuf3 + leftover, chunk3, size3);
size3 += leftover;
}
fprintf(stderr, "=> Chunk 3 (%d):\n", (int)size3);
rval = ber_decode(0, &asn_DEF_T, (void **)&tp,
tbuf3, size3);
assert(rval.code == RC_OK);
assert(rval.consumed == size3);
ASN_STRUCT_RESET(asn_DEF_T, &t);
}
}
}
int
main(int ac, char **av) {
(void)ac; /* Unused argument */
(void)av; /* Unused argument */
/* Check that the full buffer may be decoded normally */
check(1, buf1, sizeof(buf1), sizeof(buf1) - 3);
/* Check that some types of buffer corruptions will lead to failure */
try_corrupt(buf1, sizeof(buf1) - 3, sizeof(buf1) - 3);
/* Split the buffer in parts and check decoder restartability */
partial_read(buf1, sizeof(buf1) - 3);
return 0;
}
| 2.40625 | 2 |
2024-11-18T22:37:04.103135+00:00
| 2021-11-15T13:05:54 |
70b5758595eb9b4f91417f09dd3a18ae69bc5094
|
{
"blob_id": "70b5758595eb9b4f91417f09dd3a18ae69bc5094",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-15T13:05:54",
"content_id": "c5a382606676c766d1a3fcbc45e0caccb0a796ec",
"detected_licenses": [
"MIT"
],
"directory_id": "05ba9ec550487bdf81a2d5057e225f9bf4413849",
"extension": "h",
"filename": "ppu.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 122260939,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1881,
"license": "MIT",
"license_type": "permissive",
"path": "/src/include/enias/ppu.h",
"provenance": "stackv2-0107.json.gz:90846",
"repo_name": "piot/enias",
"revision_date": "2021-11-15T13:05:54",
"revision_id": "ef818c838b4471566f4874a9da06368fb0fed937",
"snapshot_id": "67d23033222ed161dc5bf8096b953882b762802b",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/piot/enias/ef818c838b4471566f4874a9da06368fb0fed937/src/include/enias/ppu.h",
"visit_date": "2021-11-30T15:49:36.909349"
}
|
stackv2
|
/*
MIT License
Copyright (c) 2017 Peter Bjorklund
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef enias_ppu_h
#define enias_ppu_h
#include <stdint.h>
#define ENIAS_PPU_SCREEN_WIDTH (256)
#define ENIAS_PPU_SCREEN_HEIGHT (224)
#pragma pack(1)
typedef struct enias_sprite_info {
uint8_t x;
uint8_t y;
uint8_t tile;
uint8_t flags;
} enias_sprite_info;
typedef struct enias_palette_info {
uint8_t r;
uint8_t g;
uint8_t b;
} enias_palette_info;
typedef struct enias_name_table_info {
uint8_t tile_index;
} enias_name_table_info;
#pragma pack()
typedef struct enias_ppu {
const enias_name_table_info* name_table;
const enias_palette_info* palette;
const enias_sprite_info* sprites;
const uint8_t* chars;
uint8_t scroll_x;
uint8_t scroll_y;
} enias_ppu;
void enias_ppu_setup(enias_ppu* ppu, const uint8_t* memory);
void enias_ppu_render(enias_ppu* ppu, uint32_t* pixels);
#endif
| 2.125 | 2 |
2024-11-18T22:37:04.376424+00:00
| 2017-11-12T08:30:36 |
c7d9904ffe149ecf48d1f55660a0d6e7fcecd28d
|
{
"blob_id": "c7d9904ffe149ecf48d1f55660a0d6e7fcecd28d",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-12T08:30:36",
"content_id": "9dbae8f6c07b71f2e6b5cd376cf9314abe03b9e8",
"detected_licenses": [
"MIT"
],
"directory_id": "b63e6515339cfda389a9e33381abf1ad6aa39d95",
"extension": "h",
"filename": "tth_arch_nios2.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87392032,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1799,
"license": "MIT",
"license_type": "permissive",
"path": "/software/olive_rubic_bsp/TINYTH/inc/priv/tth_arch_nios2.h",
"provenance": "stackv2-0107.json.gz:90975",
"repo_name": "kimushu/olive-piccolo",
"revision_date": "2017-11-12T08:30:36",
"revision_id": "f1198cc0721b259d81557817cc7e0ef66edb7b52",
"snapshot_id": "b5e16af78540a67fb8b91f9e3ed8da94a6987be8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kimushu/olive-piccolo/f1198cc0721b259d81557817cc7e0ef66edb7b52/software/olive_rubic_bsp/TINYTH/inc/priv/tth_arch_nios2.h",
"visit_date": "2021-01-19T04:44:41.277622"
}
|
stackv2
|
#ifndef __PRIV_TTH_ARCH_NIOS2_H__
#define __PRIV_TTH_ARCH_NIOS2_H__
#include <stdint.h>
#include <system.h>
#if defined(SMALL_C_LIB) && (TTHREAD_THREAD_SAFE_NEWLIB != 0)
# error "Small C library is not thread-safe. Turn off 'hal.enable_small_c_library' to use thread-safe environment."
#endif
#if defined(SMALL_C_LIB)
# define TTHREAD_MALLOC_LOCK 1
#endif
#if defined(ALT_EXCEPTION_STACK)
# error "TinyThreads does not support separate exception stack. Turn off 'hal.linker.enable_exception_stack'"
#endif
#if defined(ALT_INTERRUPT_STACK)
# error "TinyThreads does not support separate interrupt stack. Turn off 'hal.linker.enable_interrupt_stack'"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* Prototype for inline functions */
static inline void tth_crash(void) __attribute__((always_inline));
static inline int tth_cs_begin(void) __attribute__((always_inline));
static inline void tth_cs_end(int status) __attribute__((always_inline));
static inline void tth_cs_exec_switch(void) __attribute__((always_inline));
/* Crash system */
static inline void tth_crash(void)
{
__builtin_wrctl(0, 0);
for (;;)
{
__asm__("break");
}
}
/*
* Begin critical section
*/
static inline int tth_cs_begin(void)
{
int status;
status = __builtin_rdctl(0); /* status */
__builtin_wrctl(0, status & ~(1u << 0));
return status;
}
/*
* End critical section
*/
static inline void tth_cs_end(int status)
{
__builtin_wrctl(0, status);
}
/*
* Execute thread switching
*/
static inline void tth_cs_exec_switch(void)
{
/*
* Issue "trap <imm5>" instruction
* 24 means 24th alphabet "T" -- the first letter of TinyThreads.
*/
__asm__ volatile("trap 24");
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* __PRIV_TTH_ARCH_NIOS2_H__ */
/* vim: set et sts=2 sw=2: */
| 2.25 | 2 |
2024-11-18T22:37:09.022295+00:00
| 2021-03-05T20:21:39 |
6f358ddc65a42695c73ed701fa5ffc2971185e66
|
{
"blob_id": "6f358ddc65a42695c73ed701fa5ffc2971185e66",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-05T20:21:39",
"content_id": "e6548f60b47f5017ec1369fcf79d1b258acc2db1",
"detected_licenses": [
"MIT"
],
"directory_id": "3a0f9f87d807e9aa33b87568b0829edd92da4ef3",
"extension": "c",
"filename": "emain.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 343282601,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2856,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/epiphany-examples/labs/hardware_loops/src/emain.c",
"provenance": "stackv2-0107.json.gz:91232",
"repo_name": "Patuxent62/parallella-base-fs-gen",
"revision_date": "2021-03-05T20:21:39",
"revision_id": "67f85909185ad633433f95007b5a6a4c4aab096c",
"snapshot_id": "eb3c13ba41e3f4f76ab32a159e40ae7ee529a52f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Patuxent62/parallella-base-fs-gen/67f85909185ad633433f95007b5a6a4c4aab096c/examples/epiphany-examples/labs/hardware_loops/src/emain.c",
"visit_date": "2023-03-18T16:38:44.763305"
}
|
stackv2
|
/*
emain.c
Copyright (C) 2012 Adapteva, Inc.
Contributed by Xin Mao <maoxin99@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program, see the file COPYING. If not, see
<http://www.gnu.org/licenses/>.
*/
// This is the device side of the Hardware Barrier example project.
// The host may load this program to any eCore. When launched, the
// core do a simple matrix multiplication. The calculation is performed
// with three different versions: compiled by complier with level 3
// optimization, with hardware_loop, without hardware_loop. A
// success/error message is sent to the host according to the result.
//
// Aug-2013, XM.
#include <stdio.h>
#include <stdlib.h>
#include <e_lib.h>
#define N 1024
#define ctype E_CTIMER_CLK
int A[N], B[N];
void init_array();
int comloop();
int hwloop(int);
int sfloop(int);
int main(void) {
int *result;
unsigned *time;
unsigned *flag;
unsigned time_s, time_e;
unsigned ctimer;
init_array();
result = (unsigned *)0x8f801000;
time = (unsigned *)0x8f802000;
flag = (unsigned *)0x8f803000;
result[0] = 0;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = 0x0;
e_ctimer_stop(E_CTIMER_0);
//test the comloop
e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX);
time_s = e_ctimer_start(E_CTIMER_0, ctype);
result[0] = comloop();
time_e = e_ctimer_stop(E_CTIMER_0);
time[0] = time_s - time_e;
//test the hwloop
e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX);
time_s = e_ctimer_start(E_CTIMER_0, ctype);
result[1] = hwloop(1024);
time_e = e_ctimer_stop(E_CTIMER_0);
time[1] = time_s - time_e;
//time_s = e_ctimer_start(E_CTIMER_0, ctype);
//hwloop(2048);
//time_e = e_ctimer_stop(E_CTIMER_0);
//time[1] = (time_e - time_s) - time[1];
//test the sfloop
e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX);
time_s = e_ctimer_start(E_CTIMER_0, ctype);
result[2] = sfloop(1024);
time_e = e_ctimer_stop(E_CTIMER_0);
time[2] = time_s - time_e;
//time_s = e_ctimer_start(E_CTIMER_0, ctype);
//sfloop(2048);
//time_e = e_ctimer_stop(E_CTIMER_0);
//time[2] = (time_e - time_s) - time[2];
//
*flag = 1;
return EXIT_SUCCESS;
}
void init_array() {
int _i;
for(_i=0;_i<N;_i++)
{
A[_i] = _i;
B[_i] = _i;
}
return;
}
int comloop() {
int _i, sum;
sum = 0;
for(_i=0;_i<1024;_i++)
{
sum += A[_i]*B[_i];
}
return sum;
}
| 2.34375 | 2 |
2024-11-18T22:37:09.152117+00:00
| 2021-06-29T16:35:44 |
9af5d283429675651c6aae3edd438277c7c56b4b
|
{
"blob_id": "9af5d283429675651c6aae3edd438277c7c56b4b",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-29T16:35:44",
"content_id": "d9bbc7bc3be6d006dc0e244eeba02c552c334809",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fc7d5b988d885bd3a5ca89296a04aa900e23c497",
"extension": "c",
"filename": "mbed_critical_section_api.c",
"fork_events_count": 1,
"gha_created_at": "2021-01-29T07:28:32",
"gha_event_created_at": "2021-03-16T16:32:16",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 334069714,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1773,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Programming/mbed-os-example-sockets/mbed-os/hal/source/mbed_critical_section_api.c",
"provenance": "stackv2-0107.json.gz:91361",
"repo_name": "AlbinMartinsson/master_thesis",
"revision_date": "2021-06-29T16:35:44",
"revision_id": "495d0e53dd00c11adbe8114845264b65f14b8163",
"snapshot_id": "52746f035bc24e302530aabde3cbd88ea6c95b77",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/AlbinMartinsson/master_thesis/495d0e53dd00c11adbe8114845264b65f14b8163/Programming/mbed-os-example-sockets/mbed-os/hal/source/mbed_critical_section_api.c",
"visit_date": "2023-06-04T09:31:45.174612"
}
|
stackv2
|
/* mbed Microcontroller Library
* Copyright (c) 2017 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 "cmsis.h"
#include "hal/critical_section_api.h"
#include "platform/mbed_assert.h"
#include "platform/mbed_toolchain.h"
#include <stdbool.h>
static bool critical_interrupts_enabled = false;
static bool state_saved = false;
static bool are_interrupts_enabled(void)
{
#if defined(__CORTEX_A9)
return ((__get_CPSR() & 0x80) == 0);
#else
return ((__get_PRIMASK() & 0x1) == 0);
#endif
}
MBED_WEAK void hal_critical_section_enter(void)
{
const bool interrupt_state = are_interrupts_enabled();
__disable_irq();
if (state_saved == true) {
return;
}
critical_interrupts_enabled = interrupt_state;
state_saved = true;
}
MBED_WEAK void hal_critical_section_exit(void)
{
// Interrupts must be disabled on invoking an exit from a critical section
MBED_ASSERT(!are_interrupts_enabled());
state_saved = false;
// Restore the IRQs to their state prior to entering the critical section
if (critical_interrupts_enabled == true) {
__enable_irq();
}
}
MBED_WEAK bool hal_in_critical_section(void)
{
return (state_saved == true);
}
| 2.046875 | 2 |
2024-11-18T22:37:09.513762+00:00
| 2023-08-18T12:54:06 |
f8a4d530e976bf7f0c2657f2bc06687ee8055dfb
|
{
"blob_id": "f8a4d530e976bf7f0c2657f2bc06687ee8055dfb",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-18T12:54:06",
"content_id": "e3641fe4f29ac0184a432699997ba8d4395ab48b",
"detected_licenses": [
"MIT"
],
"directory_id": "22446075c2e71ef96b4a4777fe966714ac96b405",
"extension": "c",
"filename": "main.c",
"fork_events_count": 68,
"gha_created_at": "2020-09-30T10:18:15",
"gha_event_created_at": "2023-09-08T12:56:11",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 299882138,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2998,
"license": "MIT",
"license_type": "permissive",
"path": "/clicks/altitude6/example/main.c",
"provenance": "stackv2-0107.json.gz:91619",
"repo_name": "MikroElektronika/mikrosdk_click_v2",
"revision_date": "2023-08-18T12:54:06",
"revision_id": "49ab937390bef126beb7b703d5345fa8cd6e3555",
"snapshot_id": "2cc2987869649a304763b0f9d27c920d42a11c16",
"src_encoding": "UTF-8",
"star_events_count": 77,
"url": "https://raw.githubusercontent.com/MikroElektronika/mikrosdk_click_v2/49ab937390bef126beb7b703d5345fa8cd6e3555/clicks/altitude6/example/main.c",
"visit_date": "2023-08-21T22:15:09.036635"
}
|
stackv2
|
/*!
* @file main.c
* @brief Altitude6 Click example
*
* # Description
* This library contains API for Altitude 6 Click driver.
* The demo application reads and calculate
* temperature, pressure and altitude data.
*
* The demo application is composed of two sections :
*
* ## Application Init
* Initializes I2C or SPI driver and log UART.
* After driver initialization the app set
* driver interface setup and default settings.
*
* ## Application Task
* This is an example that demonstrates the use of the Altitude 6 Click board™.
* In this example, display the Altitude ( m ),
* Pressure ( mBar ) and Temperature ( degree Celsius ) data.
* Results are being sent to the Usart Terminal where you can track their changes.
*
* @author Nenad Filipovic
*
*/
#include "board.h"
#include "log.h"
#include "altitude6.h"
static altitude6_t altitude6;
static log_t logger;
void application_init ( void )
{
log_cfg_t log_cfg; /**< Logger config object. */
altitude6_cfg_t altitude6_cfg; /**< Click config object. */
/**
* Logger initialization.
* Default baud rate: 115200
* Default log level: LOG_LEVEL_DEBUG
* @note If USB_UART_RX and USB_UART_TX
* are defined as HAL_PIN_NC, you will
* need to define them manually for log to work.
* See @b LOG_MAP_USB_UART macro definition for detailed explanation.
*/
LOG_MAP_USB_UART( log_cfg );
log_init( &logger, &log_cfg );
log_info( &logger, " Application Init " );
// Click initialization.
altitude6_cfg_setup( &altitude6_cfg );
altitude6_drv_interface_selection( &altitude6_cfg, ALTITUDE6_DRV_SEL_I2C );
ALTITUDE6_MAP_MIKROBUS( altitude6_cfg, MIKROBUS_1 );
err_t init_flag = altitude6_init( &altitude6, &altitude6_cfg );
if ( ( I2C_MASTER_ERROR == init_flag ) || ( SPI_MASTER_ERROR == init_flag ) )
{
log_error( &logger, " Communication init." );
for ( ; ; );
}
if ( ALTITUDE6_ERROR == altitude6_default_cfg ( &altitude6 ) )
{
log_error( &logger, " Default configuration." );
for ( ; ; );
}
log_info( &logger, " Application Task " );
log_printf( &logger, "----------------------------\r\n" );
Delay_ms( 100 );
}
void application_task ( void )
{
static float temperature;
static float pressure;
static float altitude;
if ( altitude6_get_data( &altitude6, &temperature, &pressure, &altitude ) == ALTITUDE6_OK )
{
log_printf( &logger, " Altitude : %.2f m \r\n", altitude );
log_printf( &logger, " Pressure : %.2f mbar \r\n", pressure );
log_printf( &logger, " Temperature : %.2f C \r\n", temperature );
log_printf( &logger, "----------------------------\r\n" );
}
Delay_ms( 1000 );
}
void main ( void )
{
application_init( );
for ( ; ; )
{
application_task( );
}
}
// ------------------------------------------------------------------------ END
| 2.703125 | 3 |
2024-11-18T22:37:10.137750+00:00
| 2018-11-12T14:15:53 |
5b49a342ab7e31da4b9db9898b812a5ff1b0730f
|
{
"blob_id": "5b49a342ab7e31da4b9db9898b812a5ff1b0730f",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-12T14:15:53",
"content_id": "166e0115be9c7815c1e63d410780faa952a974af",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "96e3811013dfa98d91e0b4090e4e4c32ee4427e4",
"extension": "h",
"filename": "stack.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 41586700,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2561,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Calculator/stack.h",
"provenance": "stackv2-0107.json.gz:91748",
"repo_name": "vincentlauvlwj/Calculator",
"revision_date": "2018-11-12T14:15:53",
"revision_id": "575c0d51183b6564f620c0dfd2a5ddeaba936cb9",
"snapshot_id": "de2483e62491745c7a3534916611bde6d462999c",
"src_encoding": "GB18030",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/vincentlauvlwj/Calculator/575c0d51183b6564f620c0dfd2a5ddeaba936cb9/Calculator/stack.h",
"visit_date": "2021-05-16T02:26:39.813457"
}
|
stackv2
|
/*
* 此头文件使用宏定义实现栈的简单功能,一定程度上弥补了C语言没有泛型的缺陷
* 使用者应当十分谨慎地使用,在调用对应的操作"函数"时明确操作对象和操作的数据类型
*
* 作者:李宇涛
*/
#ifndef STACK_H
#define STACK_H
#include<stdlib.h>
#define MAX_STACK_SIZE 100 //默认初始化的栈容量
#define INCREMENT_SIZE 10 //栈容量的扩充增量
typedef struct tagSTACK{
void *base; //栈底指针
void *top; //栈顶指针
int size; //栈容量
} STACK;
/*
* 栈的初始化
* 参数:
* type: 栈内数据的数据类型
* stack: 等待初始化的栈
* 返回值:
* 无
*/
#define InitStack(type, stack) \
{ \
stack.top = stack.base = malloc (sizeof(type) * MAX_STACK_SIZE); \
stack.size = MAX_STACK_SIZE; \
}
/*
* 栈的销毁
* 参数:
* type: 栈内数据的数据类型
* stack: 等待销毁的栈
* 返回值:
* 无
*/
#define DestroyStack(type, stack) \
{ \
free((type*)stack.base); \
}
/*
* 数据压栈
* 参数:
* type: 栈内数据的数据类型
* stack: 等待操作的栈
* elem: 等待进栈的数据元素
* 返回值:
* 无
*/
#define PushStack(type, stack, elem)\
{ \
type *in = (type*)stack.top; \
if((type*)stack.top - (type*)stack.base >= stack.size){\
stack.base = realloc ( stack.base, sizeof(type) * (stack.size + INCREMENT_SIZE) );\
stack.top = (type*)stack.base + stack.size; \
stack.size += INCREMENT_SIZE; \
} \
*in = elem; \
stack.top = (type*)stack.top + 1; \
}
/*
* 数据弹栈
* 参数:
* type: 栈内数据的数据类型
* stack: 等待操作的栈
* elem: 接收弹栈的数据元素
* 返回值:
* 无
*/
#define PopStack(type, stack, elem) \
{ \
stack.top = (type*)stack.top - 1; \
elem = *((type*)stack.top); \
}
/*
* 获取栈顶元素
* type: 栈内数据的数据类型
* stack: 等待操作的栈
* elem: 接收栈顶的数据元素
* 返回值:
* 无
*/
#define GetStackTop(type, stack, elem) \
{ \
elem = *((type*)stack.top - 1); \
}
/*
* 判断操作栈为空
* 参数:
* stack: 等待操作的栈
* 返回值:
* 若栈为空,返回1; 若栈不为空,返回0.
*/
#define StackEmpty(stack) (stack.top == stack.base)
/*
* 清空栈
* 参数:
* stack: 等待操作的栈
* 返回值:
* 无
*/
#define ClearStack(stack) (stack.top = stack.base)
#endif
| 3.203125 | 3 |
2024-11-18T22:37:10.857426+00:00
| 2021-06-28T20:03:07 |
f6225a4fdb928a4ea1bc47ccb8a66dd5c9ad6f21
|
{
"blob_id": "f6225a4fdb928a4ea1bc47ccb8a66dd5c9ad6f21",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-28T20:03:07",
"content_id": "97d48658018a4fb02c81700a84a5192fc50b307c",
"detected_licenses": [
"MIT"
],
"directory_id": "e821bf51bb244191243179888a1082067ae5c0f7",
"extension": "c",
"filename": "testing.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 380612825,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1963,
"license": "MIT",
"license_type": "permissive",
"path": "/2_Simple Kernel Module/testing.c",
"provenance": "stackv2-0107.json.gz:92005",
"repo_name": "an36/Linux-Char-Dev-Driver",
"revision_date": "2021-06-28T20:03:07",
"revision_id": "3aadc75d8d9ff67f277a82f1b9d8b26617cd200a",
"snapshot_id": "cd19b312302a413938e339a1efe7939146253e09",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/an36/Linux-Char-Dev-Driver/3aadc75d8d9ff67f277a82f1b9d8b26617cd200a/2_Simple Kernel Module/testing.c",
"visit_date": "2023-06-07T09:55:54.823827"
}
|
stackv2
|
/*
* Abdullah Almarzouq (an36@pdx.edu)
* 4/22/20
*
* testing: opens, reads and writes to "/sys/module/HW2_2/parameters/exam"
* module parameter to view and modify the value of
* "exam" in HW2_2 module. The value of syscall_val will be
* changed too because syscall_val=exam.
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(){
int size;
char *val;
/*opening the kernel module parameter (called exam)*/
int fd = open("/sys/module/HW2_2/parameters/exam", O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO );
/*if open failed*/
if(fd<0){
perror("ERROR: ");
exit(1);
}
val = (char*)malloc(10*sizeof(char));
/*reading parameter value*/
size = read(fd,val,10);
val[size-1]='\0';
/*if reading fails*/
if(size<0){
perror("ERROR: ");
free(val);
close(fd);
exit(1);
}
/*print read value*/
printf("parameter exam: %s\n",val);
/*close the parameter file*/
if(close(fd)<0){
perror("ERROR: ");
free(val);
exit(1);
}
/*open parameter file again*/
fd = open("/sys/module/HW2_2/parameters/exam", O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO );
/*if open fails*/
if((fd)<0){
perror("ERROR: ");
free(val);
close(fd);
exit(1);
}
/*modify parameter exam*/
size = write(fd,"36",2);
/*if writing fails*/
if(size<0){
perror("ERROR: ");
free(val);
close(fd);
exit(1);
}
char *newval = (char*)malloc(10*sizeof(char));
lseek(fd,0,SEEK_SET);
/*reading new value of parameter exam*/
size = read(fd,newval,10);
newval[size-1]='\0';
/*if reading fails*/
if(size<0){
perror("ERROR: ");
free(val);
free(newval);
close(fd);
exit(1);
}
/*print new value*/
printf("new value of parameter exam: %s\n",newval);
if(close(fd)<0){
perror("ERROR: ");
free(val);
free(newval);
exit(1);
}
printf("file closed\n");
free(val);
free(newval);
return 0;
}
| 3.09375 | 3 |
2024-11-18T22:37:10.970592+00:00
| 2017-11-14T05:23:53 |
3ef02f83020baebf3ac4cc224b72da55a22ec90c
|
{
"blob_id": "3ef02f83020baebf3ac4cc224b72da55a22ec90c",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-14T05:23:53",
"content_id": "ce1b1106a35b54ef5c1dc23b39770ea7b958ce65",
"detected_licenses": [
"MIT"
],
"directory_id": "b2e1b748535fe6c37435ea98796a8d4b7246cf63",
"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": 47225204,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4920,
"license": "MIT",
"license_type": "permissive",
"path": "/src/io.c",
"provenance": "stackv2-0107.json.gz:92135",
"repo_name": "blin00/os",
"revision_date": "2017-11-14T05:23:53",
"revision_id": "60d231fb9a3b7ad747387ca3b265c170eed240a1",
"snapshot_id": "009ac6dcad4acee8066777edd35ed2d2100b012c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/blin00/os/60d231fb9a3b7ad747387ca3b265c170eed240a1/src/io.c",
"visit_date": "2021-05-04T11:04:39.850574"
}
|
stackv2
|
#include <stdint.h>
#include <stdarg.h>
#include <stddef.h>
#include "io.h"
#include "util.h"
#include "string.h"
static size_t WIDTH;
static size_t HEIGHT;
static volatile uint16_t* fb = (uint16_t*) 0xb8000;
static size_t row;
static size_t col;
static uint16_t port;
static char num_to_hex_lower[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
static char num_to_hex_upper[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
static void set_cursor(size_t loc);
static void update_cursor(void);
static void _putc(size_t loc, char c);
static void set_cursor(size_t loc) {
outb(port, 14);
outb(port + 1, (uint8_t) (loc >> 8)); // high byte
outb(port, 15);
outb(port + 1, (uint8_t) loc); // low byte
}
static void update_cursor(void) {
set_cursor(row * WIDTH + col);
}
static void _putc(size_t loc, char c) {
uint16_t value = (0x07 << 8) | c;
fb[loc] = value;
}
void fb_write(const char* buf, size_t count) {
for (size_t i = 0; i < count; i++) {
char c = buf[i];
if (c == '\n') {
row++;
col = 0;
} else if (c == 8) {
if (row || col) {
if (col) col--;
else {
col = WIDTH - 1;
row--;
}
}
_putc(row * WIDTH + col, ' ');
} else if (c == '\t') {
fb_write(" ", 4 - col % 4);
} else {
_putc(row * WIDTH + col, c);
if (++col >= WIDTH) {
row++;
col = 0;
}
}
if (row >= HEIGHT) {
row = HEIGHT - 1;
fb_scroll(WIDTH);
}
}
update_cursor();
}
void putc(char c) {
fb_write(&c, 1);
}
void puts(const char* str) {
fb_write(str, strlen(str));
putc('\n');
}
void putu(uint32_t num) {
if (num == 0) putc('0');
else {
if (num >= 10) putu(num / 10);
putc('0' + num % 10);
}
}
void putlu(uint64_t num) {
if (num == 0) putc('0');
else {
if (num >= 10) putlu(num / 10);
putc('0' + num % 10);
}
}
void putbytes(void* ptr, size_t num) {
uint8_t* buf = (uint8_t*) ptr;
for (size_t i = 0; i < num; i++) {
putc(num_to_hex_lower[(buf[i] >> 4) & 0xf]);
putc(num_to_hex_lower[buf[i] & 0xf]);
}
}
void printf(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
size_t idx = 0;
while (1) {
if (fmt[idx] == '%' || !fmt[idx]) {
// print buffered stuff
fb_write(fmt, idx);
if (!fmt[idx]) break;
fmt += idx;
idx = 0;
size_t length = 4; // # of bytes in the integer
char type;
look_at_type:
type = (++fmt)[idx];
if (!type) break;
else if (type == 'l') {
length <<= 1;
goto look_at_type;
} else if (type == 'h') {
length >>= 1;
goto look_at_type;
} else if (type == 'x' || type == 'X') {
char* table = (type == 'x') ? num_to_hex_lower : num_to_hex_upper;
if (length > 4) {
uint64_t num = va_arg(args, uint64_t);
for (int i = length * 2 - 1; i >= 0; i--) {
putc(table[(num >> (i * 4)) & 0xf]);
}
} else {
uint32_t num = va_arg(args, uint32_t);
for (int i = length * 2 - 1; i >= 0; i--) {
putc(table[(num >> (i * 4)) & 0xf]);
}
}
} else if (type == 'u') {
if (length > 4) {
putlu(va_arg(args, uint64_t));
} else {
putu(va_arg(args, uint32_t));
}
} else if (type == 's') {
const char* str = va_arg(args, const char*);
fb_write(str, strlen(str));
} else if (type == 'c') {
putc((char) va_arg(args, int)); // apparently %c takes int and turns it into char
} else if (type == '%') {
putc('%');
} else {
// ignore invalid format stuff
}
fmt++;
} else idx++;
}
va_end(args);
}
void fb_init(size_t width, size_t height) {
port = *(uint16_t*) 0x0463;
WIDTH = width;
HEIGHT = height;
fb_clear();
}
void fb_clear(void) {
for (size_t i = 0; i < WIDTH * HEIGHT; i++) _putc(i, ' ');
row = col = 0;
set_cursor(0);
}
void fb_scroll(size_t amt) {
size_t i;
size_t debug = 0;
for (i = 0; i < WIDTH * HEIGHT - amt; i++, debug++) {
fb[i] = fb[i + amt];
}
for(; i < WIDTH * HEIGHT; i++) {
_putc(i, ' ');
}
}
| 2.921875 | 3 |
2024-11-18T22:37:11.102584+00:00
| 2016-04-17T00:04:33 |
2e54a49022e1cabdeaae024eedb0f4f823ff7dae
|
{
"blob_id": "2e54a49022e1cabdeaae024eedb0f4f823ff7dae",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-17T00:04:33",
"content_id": "71464df8ba5412d6e8b57bfae96d9181fdf2a67b",
"detected_licenses": [
"MIT"
],
"directory_id": "dfd9f8e93c4689527420deed2dfbba2130b60a73",
"extension": "c",
"filename": "option.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 50609191,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1856,
"license": "MIT",
"license_type": "permissive",
"path": "/Lab2Foxhall_tfoxhal1/option.c",
"provenance": "stackv2-0107.json.gz:92392",
"repo_name": "hallfox/os-school",
"revision_date": "2016-04-17T00:04:33",
"revision_id": "ed248cb5dbff671dceec57d29978115de70f0b6d",
"snapshot_id": "fcf9398fed35aea99cd9fd04edff575f032aeecc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hallfox/os-school/ed248cb5dbff671dceec57d29978115de70f0b6d/Lab2Foxhall_tfoxhal1/option.c",
"visit_date": "2021-01-12T12:04:16.882350"
}
|
stackv2
|
#include "option.h"
#include "debug.h"
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
// Option impl
Option *Option_new(int argc, char **argv) {
char flag;
unsigned int t;
bool s_flag = false;
bool p_flag = false;
// Initialize new Option struct using argv and getopts
Option *option = malloc(sizeof(Option));
// Setting defaults
option->levels = 1;
option->children = 1;
option->sleep_time = 1;
option->pause_mode = false;
while ((flag = getopt(argc, argv, "uN:M:ps:")) != -1) {
switch (flag) {
case 'u':
case '?':
// Just kick out and let main print usage
goto die;
case 'N':
// Max of 4
t = (unsigned int) strtol(optarg, NULL, 10);
if (t == 0) t = 1; // shhhhh
if (t > OPT_LEVELS_MAX) {
log_err("Maximum number of levels is %d", OPT_LEVELS_MAX);
goto die;
}
option->levels = t;
break;
case 'M':
// Max of 3
t = (unsigned int) strtol(optarg, NULL, 10);
if (t > OPT_CHILDREN_MAX) {
log_err("Maximum number of children is %d", OPT_CHILDREN_MAX);
goto die;
}
option->children = t;
break;
case 'p':
if (s_flag) {
log_err("-p flag cannot be specified with -s\n");
goto die;
}
option->pause_mode = true;
p_flag = true;
break;
case 's':
if (p_flag) {
log_err("-p flag cannot be specified with -s\n");
goto die;
}
t = (unsigned int) strtol(optarg, NULL, 10);
option->sleep_time = t;
s_flag = true;
break;
default:
// Just kick out and let main print usage
goto die;
}
}
return option;
die:
Option_del(option);
return NULL;
}
void Option_del(Option *option) {
// Close any open files
free(option);
option = NULL;
}
| 2.734375 | 3 |
2024-11-18T22:37:11.468896+00:00
| 2018-09-02T18:57:15 |
d2a9e4d24085783ba79dd46d90f423209450da44
|
{
"blob_id": "d2a9e4d24085783ba79dd46d90f423209450da44",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-02T18:57:15",
"content_id": "53bc1e5d2e212b5747c0585fa245d4746f096af4",
"detected_licenses": [
"MIT"
],
"directory_id": "857bfe927c9e17bc816949e047ab4b0ddc4ee2a1",
"extension": "c",
"filename": "normal.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 147109778,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 37926,
"license": "MIT",
"license_type": "permissive",
"path": "/normal.c",
"provenance": "stackv2-0107.json.gz:92783",
"repo_name": "FSUcilab/Compartmental_model_astrocytes",
"revision_date": "2018-09-02T18:57:15",
"revision_id": "b97139eea2570594269b08cf6033f135c42fdc94",
"snapshot_id": "95dd7c9464fa86aab603effc6f2aa62376f5dce3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/FSUcilab/Compartmental_model_astrocytes/b97139eea2570594269b08cf6033f135c42fdc94/normal.c",
"visit_date": "2020-03-27T21:00:48.251142"
}
|
stackv2
|
# include <complex.h>
# include <stdlib.h>
# include <stdio.h>
# include <time.h>
# include <math.h>
# include "normal.h"
/******************************************************************************/
int i4_normal_ab ( float a, float b, int *seed )
/******************************************************************************/
/*
Purpose:
I4_NORMAL_AB returns a scaled pseudonormal I4.
Discussion:
The normal probability distribution function (PDF) is sampled,
with mean A and standard deviation B.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
02 July 2006
Author:
John Burkardt
Parameters:
Input, float A, the mean of the PDF.
Input, float B, the standard deviation of the PDF.
Input/output, int *SEED, a seed for the random number generator.
Output, int I4_NORMAL_AB, a sample of the normal PDF.
*/
{
int value;
float value_float;
value_float = a + b * r4_normal_01 ( seed );
value = ( int ) ( value_float );
return value;
}
/******************************************************************************/
long long int i8_normal_ab ( double a, double b, long long int *seed )
/******************************************************************************/
/*
Purpose:
I8_NORMAL_AB returns a scaled pseudonormal I8.
Discussion:
The normal probability distribution function (PDF) is sampled,
with mean A and standard deviation B.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
02 July 2006
Author:
John Burkardt
Parameters:
Input, double A, the mean of the PDF.
Input, double B, the standard deviation of the PDF.
Input/output, long long int *SEED, a seed for the random number generator.
Output, long long int I8_NORMAL_AB, a sample of the normal PDF.
*/
{
int seed_int;
double value_double;
long long int value_long_int;
seed_int = ( int ) *seed;
value_double = a + b * r8_normal_01 ( &seed_int );
if ( value_double < 0.0 )
{
value_long_int = ( long long int ) ( value_double - 0.5 );
}
else
{
value_long_int = ( long long int ) ( value_double + 0.5 );
}
*seed = ( long long int ) seed_int;
return value_long_int;
}
/******************************************************************************/
float r4_normal_01 ( int *seed )
/******************************************************************************/
/*
Purpose:
R4_NORMAL_01 returns a unit pseudonormal R4.
Discussion:
The standard normal probability distribution function (PDF) has
mean 0 and standard deviation 1.
The Box-Muller method is used, which is efficient, but
generates two values at a time.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
05 June 2013
Author:
John Burkardt
Parameters:
Input/output, int *SEED, a seed for the random number generator.
Output, float R4_NORMAL_01, a normally distributed random value.
*/
{
float r1;
float r2;
const double r4_pi = 3.141592653589793;
float x;
r1 = r4_uniform_01 ( seed );
r2 = r4_uniform_01 ( seed );
x = sqrt ( - 2.0 * log ( r1 ) ) * cos ( 2.0 * r4_pi * r2 );
return x;
}
/******************************************************************************/
float r4_normal_ab ( float a, float b, int *seed )
/******************************************************************************/
/*
Purpose:
R4_NORMAL_AB returns a scaled pseudonormal R4.
Discussion:
The normal probability distribution function (PDF) is sampled,
with mean A and standard deviation B.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
29 June 2006
Author:
John Burkardt
Parameters:
Input, float A, the mean of the PDF.
Input, float B, the standard deviation of the PDF.
Input/output, int *SEED, a seed for the random number generator.
Output, float R4_NORMAL_AB, a sample of the normal PDF.
*/
{
float value;
value = a + b * r4_normal_01 ( seed );
return value;
}
/******************************************************************************/
float r4_uniform_01 ( int *seed )
/******************************************************************************/
/*
Purpose:
R4_UNIFORM_01 returns a unit pseudorandom R4.
Discussion:
This routine implements the recursion
seed = 16807 * seed mod ( 2^31 - 1 )
r4_uniform_01 = seed / ( 2^31 - 1 )
The integer arithmetic never requires more than 32 bits,
including a sign bit.
If the initial seed is 12345, then the first three computations are
Input Output R4_UNIFORM_01
SEED SEED
12345 207482415 0.096616
207482415 1790989824 0.833995
1790989824 2035175616 0.947702
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
16 November 2004
Author:
John Burkardt
Reference:
Paul Bratley, Bennett Fox, Linus Schrage,
A Guide to Simulation,
Springer Verlag, pages 201-202, 1983.
Pierre L'Ecuyer,
Random Number Generation,
in Handbook of Simulation
edited by Jerry Banks,
Wiley Interscience, page 95, 1998.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, pages 362-376, 1986.
Peter Lewis, Allen Goodman, James Miller,
A Pseudo-Random Number Generator for the System/360,
IBM Systems Journal,
Volume 8, pages 136-143, 1969.
Parameters:
Input/output, int *SEED, the "seed" value. Normally, this
value should not be 0. On output, SEED has been updated.
Output, float R4_UNIFORM_01, a new pseudorandom variate, strictly between
0 and 1.
*/
{
const int i4_huge = 2147483647;
int k;
float r;
k = *seed / 127773;
*seed = 16807 * ( *seed - k * 127773 ) - k * 2836;
if ( *seed < 0 )
{
*seed = *seed + i4_huge;
}
/*
Although SEED can be represented exactly as a 32 bit integer,
it generally cannot be represented exactly as a 32 bit real number!
*/
r = ( float ) ( *seed ) * 4.656612875E-10;
return r;
}
/******************************************************************************/
void r4mat_print ( int m, int n, float a[], char *title )
/******************************************************************************/
/*
Purpose:
R4MAT_PRINT prints an R4MAT.
Discussion:
An R4MAT is a doubly dimensioned array of R4 values, stored as a vector
in column-major order.
Entry A(I,J) is stored as A[I+J*M]
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 March 2015
Author:
John Burkardt
Parameters:
Input, int M, the number of rows in A.
Input, int N, the number of columns in A.
Input, float A[M*N], the M by N matrix.
Input, char *TITLE, a title.
*/
{
r4mat_print_some ( m, n, a, 1, 1, m, n, title );
return;
}
/******************************************************************************/
void r4mat_print_some ( int m, int n, float a[], int ilo, int jlo, int ihi,
int jhi, char *title )
/******************************************************************************/
/*
Purpose:
R4MAT_PRINT_SOME prints some of an R4MAT.
Discussion:
An R4MAT is a doubly dimensioned array of R4 values, stored as a vector
in column-major order.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 March 2015
Author:
John Burkardt
Parameters:
Input, int M, the number of rows of the matrix.
M must be positive.
Input, int N, the number of columns of the matrix.
N must be positive.
Input, float A[M*N], the matrix.
Input, int ILO, JLO, IHI, JHI, designate the first row and
column, and the last row and column to be printed.
Input, char *TITLE, a title.
*/
{
# define INCX 5
int i;
int i2hi;
int i2lo;
int j;
int j2hi;
int j2lo;
fprintf ( stdout, "\n" );
fprintf ( stdout, "%s\n", title );
if ( m <= 0 || n <= 0 )
{
fprintf ( stdout, "\n" );
fprintf ( stdout, " (None)\n" );
return;
}
/*
Print the columns of the matrix, in strips of 5.
*/
for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
{
j2hi = j2lo + INCX - 1;
if ( n < j2hi )
{
j2hi = n;
}
if ( jhi < j2hi )
{
j2hi = jhi;
}
fprintf ( stdout, "\n" );
/*
For each column J in the current range...
Write the header.
*/
fprintf ( stdout, " Col: ");
for ( j = j2lo; j <= j2hi; j++ )
{
fprintf ( stdout, " %7d ", j - 1 );
}
fprintf ( stdout, "\n" );
fprintf ( stdout, " Row\n" );
fprintf ( stdout, "\n" );
/*
Determine the range of the rows in this strip.
*/
if ( 1 < ilo )
{
i2lo = ilo;
}
else
{
i2lo = 1;
}
if ( m < ihi )
{
i2hi = m;
}
else
{
i2hi = ihi;
}
for ( i = i2lo; i <= i2hi; i++ )
{
/*
Print out (up to) 5 entries in row I, that lie in the current strip.
*/
fprintf ( stdout, "%5d:", i - 1 );
for ( j = j2lo; j <= j2hi; j++ )
{
fprintf ( stdout, " %14g", a[i-1+(j-1)*m] );
}
fprintf ( stdout, "\n" );
}
}
return;
# undef INCX
}
/******************************************************************************/
void r4vec_print ( int n, float a[], char *title )
/******************************************************************************/
/*
Purpose:
R4VEC_PRINT prints an R4VEC.
Discussion:
An R4VEC is a vector of R4's.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 March 2015
Author:
John Burkardt
Parameters:
Input, int N, the number of components of the vector.
Input, float A[N], the vector to be printed.
Input, char *TITLE, a title.
*/
{
int i;
fprintf ( stdout, "\n" );
fprintf ( stdout, "%s\n", title );
fprintf ( stdout, "\n" );
for ( i = 0; i < n; i++ )
{
fprintf ( stdout, " %8d: %14g\n", i, a[i] );
}
return;
}
/******************************************************************************/
float *r4vec_uniform_01_new ( int n, int *seed )
/******************************************************************************/
/*
Purpose:
R4VEC_UNIFORM_01_NEW returns a unit pseudorandom R4VEC.
Discussion:
This routine implements the recursion
seed = 16807 * seed mod ( 2^31 - 1 )
unif = seed / ( 2^31 - 1 )
The integer arithmetic never requires more than 32 bits,
including a sign bit.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 March 2015
Author:
John Burkardt
Reference:
Paul Bratley, Bennett Fox, Linus Schrage,
A Guide to Simulation,
Springer Verlag, pages 201-202, 1983.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, pages 362-376, 1986.
Peter Lewis, Allen Goodman, James Miller,
A Pseudo-Random Number Generator for the System/360,
IBM Systems Journal,
Volume 8, pages 136-143, 1969.
Parameters:
Input, int N, the number of entries in the vector.
Input/output, int *SEED, a seed for the random number generator.
Output, float R4VEC_UNIFORM_01_NEW[N], the vector of pseudorandom values.
*/
{
int i;
const int i4_huge = 2147483647;
int k;
float *r;
r = ( float * ) malloc ( n * sizeof ( float ) );
for ( i = 0; i < n; i++ )
{
k = *seed / 127773;
*seed = 16807 * ( *seed - k * 127773 ) - k * 2836;
if ( *seed < 0 )
{
*seed = *seed + i4_huge;
}
r[i] = ( float ) ( *seed ) * 4.656612875E-10;
}
return r;
}
/******************************************************************************/
double r8_normal_01 ( int *seed )
/******************************************************************************/
/*
Purpose:
R8_NORMAL_01 returns a unit pseudonormal R8.
Discussion:
The standard normal probability distribution function (PDF) has
mean 0 and standard deviation 1.
Because this routine uses the Box Muller method, it requires pairs
of uniform random values to generate a pair of normal random values.
This means that on every other call, the code can use the second
value that it calculated.
However, if the user has changed the SEED value between calls,
the routine automatically resets itself and discards the saved data.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
06 August 2013
Author:
John Burkardt
Parameters:
Input/output, int *SEED, a seed for the random number generator.
Output, double R8_NORMAL_01, a normally distributed random value.
*/
{
double r1;
double r2;
const double r8_pi = 3.141592653589793;
double x;
r1 = r8_uniform_01 ( seed );
r2 = r8_uniform_01 ( seed );
x = sqrt ( - 2.0 * log ( r1 ) ) * cos ( 2.0 * r8_pi * r2 );
return x;
}
/******************************************************************************/
double r8_normal_ab ( double a, double b, int *seed )
/******************************************************************************/
/*
Purpose:
R8_NORMAL_AB returns a scaled pseudonormal R8.
Discussion:
The normal probability distribution function (PDF) is sampled,
with mean A and standard deviation B.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
21 November 2004
Author:
John Burkardt
Parameters:
Input, double A, the mean of the PDF.
Input, double B, the standard deviation of the PDF.
Input/output, int *SEED, a seed for the random number generator.
Output, double R8_NORMAL_AB, a sample of the normal PDF.
*/
{
double value;
value = a + b * r8_normal_01 ( seed );
return value;
}
/******************************************************************************/
double r8_uniform_01 ( int *seed )
/******************************************************************************/
/*
Purpose:
R8_UNIFORM_01 returns a unit pseudorandom R8.
Discussion:
This routine implements the recursion
seed = 16807 * seed mod ( 2^31 - 1 )
r8_uniform_01 = seed / ( 2^31 - 1 )
The integer arithmetic never requires more than 32 bits,
including a sign bit.
If the initial seed is 12345, then the first three computations are
Input Output R8_UNIFORM_01
SEED SEED
12345 207482415 0.096616
207482415 1790989824 0.833995
1790989824 2035175616 0.947702
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
11 August 2004
Author:
John Burkardt
Reference:
Paul Bratley, Bennett Fox, Linus Schrage,
A Guide to Simulation,
Springer Verlag, pages 201-202, 1983.
Pierre L'Ecuyer,
Random Number Generation,
in Handbook of Simulation
edited by Jerry Banks,
Wiley Interscience, page 95, 1998.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, pages 362-376, 1986.
Peter Lewis, Allen Goodman, James Miller,
A Pseudo-Random Number Generator for the System/360,
IBM Systems Journal,
Volume 8, pages 136-143, 1969.
Parameters:
Input/output, int *SEED, the "seed" value. Normally, this
value should not be 0. On output, SEED has been updated.
Output, double R8_UNIFORM_01, a new pseudorandom variate, strictly between
0 and 1.
*/
{
const int i4_huge = 2147483647;
int k;
double r;
k = *seed / 127773;
*seed = 16807 * ( *seed - k * 127773 ) - k * 2836;
if ( *seed < 0 )
{
*seed = *seed + i4_huge;
}
/*
Although SEED can be represented exactly as a 32 bit integer,
it generally cannot be represented exactly as a 32 bit real number!
*/
r = ( double ) ( *seed ) * 4.656612875E-10;
return r;
}
/******************************************************************************/
void r8mat_normal_01 ( int m, int n, int *seed, double r[] )
/******************************************************************************/
/*
Purpose:
R8MAT_NORMAL_01 returns a unit pseudonormal R8MAT.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 October 2005
Author:
John Burkardt
Reference:
Paul Bratley, Bennett Fox, Linus Schrage,
A Guide to Simulation,
Springer Verlag, pages 201-202, 1983.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, pages 362-376, 1986.
Peter Lewis, Allen Goodman, James Miller,
A Pseudo-Random Number Generator for the System/360,
IBM Systems Journal,
Volume 8, pages 136-143, 1969.
Parameters:
Input, int M, N, the number of rows and columns in the array.
Input/output, int *SEED, the "seed" value, which should NOT be 0.
On output, SEED has been updated.
Output, double R[M*N], the array of pseudonormal values.
*/
{
r8vec_normal_01 ( m * n, seed, r );
return;
}
/******************************************************************************/
double *r8mat_normal_01_new ( int m, int n, int *seed )
/******************************************************************************/
/*
Purpose:
R8MAT_NORMAL_01_NEW returns a unit pseudonormal R8MAT.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 October 2005
Author:
John Burkardt
Reference:
Paul Bratley, Bennett Fox, Linus Schrage,
A Guide to Simulation,
Springer Verlag, pages 201-202, 1983.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, pages 362-376, 1986.
Peter Lewis, Allen Goodman, James Miller,
A Pseudo-Random Number Generator for the System/360,
IBM Systems Journal,
Volume 8, pages 136-143, 1969.
Parameters:
Input, int M, N, the number of rows and columns in the array.
Input/output, int *SEED, the "seed" value, which should NOT be 0.
On output, SEED has been updated.
Output, double R8MAT_NORMAL_01_NEW[M*N], the array of pseudonormal values.
*/
{
double *r;
r = r8vec_normal_01_new ( m * n, seed );
return r;
}
/******************************************************************************/
void r8mat_normal_ab ( int m, int n, double a, double b, int *seed, double r[] )
/******************************************************************************/
/*
Purpose:
R8MAT_NORMAL_AB returns a scaled pseudonormal R8MAT.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 October 2005
Author:
John Burkardt
Reference:
Paul Bratley, Bennett Fox, Linus Schrage,
A Guide to Simulation,
Springer Verlag, pages 201-202, 1983.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, pages 362-376, 1986.
Peter Lewis, Allen Goodman, James Miller,
A Pseudo-Random Number Generator for the System/360,
IBM Systems Journal,
Volume 8, pages 136-143, 1969.
Parameters:
Input, int M, N, the number of rows and columns in the array.
Input, double A, B, the mean and standard deviation.
Input/output, int *SEED, the "seed" value, which should NOT be 0.
On output, SEED has been updated.
Output, double R[M*N], the array of pseudonormal values.
*/
{
r8vec_normal_ab ( m * n, a, b, seed, r );
return;
}
/******************************************************************************/
double *r8mat_normal_ab_new ( int m, int n, double a, double b, int *seed )
/******************************************************************************/
/*
Purpose:
R8MAT_NORMAL_AB_NEW returns a scaled pseudonormal R8MAT.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 October 2005
Author:
John Burkardt
Reference:
Paul Bratley, Bennett Fox, Linus Schrage,
A Guide to Simulation,
Springer Verlag, pages 201-202, 1983.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, pages 362-376, 1986.
Peter Lewis, Allen Goodman, James Miller,
A Pseudo-Random Number Generator for the System/360,
IBM Systems Journal,
Volume 8, pages 136-143, 1969.
Parameters:
Input, int M, N, the number of rows and columns in the array.
Input, double A, B, the mean and standard deviation.
Input/output, int *SEED, the "seed" value, which should NOT be 0.
On output, SEED has been updated.
Output, double R8MAT_NORMAL_AB_NEW[M*N], the array of pseudonormal values.
*/
{
double *r;
r = r8vec_normal_ab_new ( m * n, a, b, seed );
return r;
}
/******************************************************************************/
void r8mat_print ( int m, int n, double a[], char *title )
/******************************************************************************/
/*
Purpose:
R8MAT_PRINT prints an R8MAT.
Discussion:
An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
in column-major order.
Entry A(I,J) is stored as A[I+J*M]
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
28 May 2008
Author:
John Burkardt
Parameters:
Input, int M, the number of rows in A.
Input, int N, the number of columns in A.
Input, double A[M*N], the M by N matrix.
Input, char *TITLE, a title.
*/
{
r8mat_print_some ( m, n, a, 1, 1, m, n, title );
return;
}
/******************************************************************************/
void r8mat_print_some ( int m, int n, double a[], int ilo, int jlo, int ihi,
int jhi, char *title )
/******************************************************************************/
/*
Purpose:
R8MAT_PRINT_SOME prints some of an R8MAT.
Discussion:
An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
in column-major order.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
26 June 2013
Author:
John Burkardt
Parameters:
Input, int M, the number of rows of the matrix.
M must be positive.
Input, int N, the number of columns of the matrix.
N must be positive.
Input, double A[M*N], the matrix.
Input, int ILO, JLO, IHI, JHI, designate the first row and
column, and the last row and column to be printed.
Input, char *TITLE, a title.
*/
{
# define INCX 5
int i;
int i2hi;
int i2lo;
int j;
int j2hi;
int j2lo;
fprintf ( stdout, "\n" );
fprintf ( stdout, "%s\n", title );
if ( m <= 0 || n <= 0 )
{
fprintf ( stdout, "\n" );
fprintf ( stdout, " (None)\n" );
return;
}
/*
Print the columns of the matrix, in strips of 5.
*/
for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
{
j2hi = j2lo + INCX - 1;
if ( n < j2hi )
{
j2hi = n;
}
if ( jhi < j2hi )
{
j2hi = jhi;
}
fprintf ( stdout, "\n" );
/*
For each column J in the current range...
Write the header.
*/
fprintf ( stdout, " Col: ");
for ( j = j2lo; j <= j2hi; j++ )
{
fprintf ( stdout, " %7d ", j - 1 );
}
fprintf ( stdout, "\n" );
fprintf ( stdout, " Row\n" );
fprintf ( stdout, "\n" );
/*
Determine the range of the rows in this strip.
*/
if ( 1 < ilo )
{
i2lo = ilo;
}
else
{
i2lo = 1;
}
if ( m < ihi )
{
i2hi = m;
}
else
{
i2hi = ihi;
}
for ( i = i2lo; i <= i2hi; i++ )
{
/*
Print out (up to) 5 entries in row I, that lie in the current strip.
*/
fprintf ( stdout, "%5d:", i - 1 );
for ( j = j2lo; j <= j2hi; j++ )
{
fprintf ( stdout, " %14g", a[i-1+(j-1)*m] );
}
fprintf ( stdout, "\n" );
}
}
return;
# undef INCX
}
/******************************************************************************/
void r8vec_normal_01 ( int n, int *seed, double x[] )
/******************************************************************************/
/*
Purpose:
R8VEC_NORMAL_01 returns a unit pseudonormal R8VEC.
Discussion:
The standard normal probability distribution function (PDF) has
mean 0 and standard deviation 1.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
06 August 2013
Author:
John Burkardt
Parameters:
Input, int N, the number of values desired.
Input/output, int *SEED, a seed for the random number generator.
Output, double X[N], a sample of the standard normal PDF.
Local parameters:
Local, double R[N+1], is used to store some uniform random values.
Its dimension is N+1, but really it is only needed to be the
smallest even number greater than or equal to N.
Local, int X_LO, X_HI, records the range of entries of
X that we need to compute.
*/
{
int i;
int m;
double *r;
const double r8_pi = 3.141592653589793;
int x_hi;
int x_lo;
/*
Record the range of X we need to fill in.
*/
x_lo = 1;
x_hi = n;
/*
If we need just one new value, do that here to avoid null arrays.
*/
if ( x_hi - x_lo + 1 == 1 )
{
r = r8vec_uniform_01_new ( 2, seed );
x[x_hi-1] = sqrt ( - 2.0 * log ( r[0] ) ) * cos ( 2.0 * r8_pi * r[1] );
free ( r );
}
/*
If we require an even number of values, that's easy.
*/
else if ( ( x_hi - x_lo + 1 ) % 2 == 0 )
{
m = ( x_hi - x_lo + 1 ) / 2;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2*m-2; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( - 2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
free ( r );
}
/*
If we require an odd number of values, we generate an even number,
and handle the last pair specially, storing one in X(N), and
saving the other for later.
*/
else
{
x_hi = x_hi - 1;
m = ( x_hi - x_lo + 1 ) / 2 + 1;
r = r8vec_uniform_01_new ( 2 * m, seed );
for ( i = 0; i <= 2 * m - 4; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( - 2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
i = 2*m - 2;
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
free ( r );
}
return;
}
/******************************************************************************/
double *r8vec_normal_01_new ( int n, int *seed )
/******************************************************************************/
/*
Purpose:
R8VEC_NORMAL_01_NEW returns a unit pseudonormal R8VEC.
Discussion:
The standard normal probability distribution function (PDF) has
mean 0 and standard deviation 1.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
06 August 2013
Author:
John Burkardt
Parameters:
Input, int N, the number of values desired.
Input/output, int *SEED, a seed for the random number generator.
Output, double R8VEC_NORMAL_01_NEW[N], a sample of the standard normal PDF.
Local parameters:
Local, double R[N+1], is used to store some uniform random values.
Its dimension is N+1, but really it is only needed to be the
smallest even number greater than or equal to N.
Local, int X_LO, X_HI, records the range of entries of
X that we need to compute.
*/
{
int i;
int m;
double *r;
const double r8_pi = 3.141592653589793;
double *x;
int x_hi;
int x_lo;
x = ( double * ) malloc ( n * sizeof ( double ) );
/*
Record the range of X we need to fill in.
*/
x_lo = 1;
x_hi = n;
/*
If we need just one new value, do that here to avoid null arrays.
*/
if ( x_hi - x_lo + 1 == 1 )
{
r = r8vec_uniform_01_new ( 2, seed );
x[x_hi-1] = sqrt ( - 2.0 * log ( r[0] ) ) * cos ( 2.0 * r8_pi * r[1] );
free ( r );
}
/*
If we require an even number of values, that's easy.
*/
else if ( ( x_hi - x_lo + 1 ) % 2 == 0 )
{
m = ( x_hi - x_lo + 1 ) / 2;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2*m-2; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( - 2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
free ( r );
}
/*
If we require an odd number of values, we generate an even number,
and handle the last pair specially, storing one in X(N), and
saving the other for later.
*/
else
{
x_hi = x_hi - 1;
m = ( x_hi - x_lo + 1 ) / 2 + 1;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2*m-4; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( - 2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
i = 2 * m - 2;
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
free ( r );
}
return x;
}
/******************************************************************************/
void r8vec_normal_ab ( int n, double b, double c, int *seed, double x[] )
/******************************************************************************/
/*
Purpose:
R8VEC_NORMAL_AB returns a scaled pseudonormal R8VEC.
Discussion:
The scaled normal probability distribution function (PDF) has
mean A and standard deviation B.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
06 August 2013
Author:
John Burkardt
Parameters:
Input, int N, the number of values desired.
Input, double B, C, the mean and standard deviation.
Input/output, int *SEED, a seed for the random number generator.
Output, double X[N], a sample of the standard normal PDF.
Local parameters:
Local, double R[N+1], is used to store some uniform random values.
Its dimension is N+1, but really it is only needed to be the
smallest even number greater than or equal to N.
Local, int X_LO, X_HI, records the range of entries of
X that we need to compute.
*/
{
int i;
int m;
double *r;
const double r8_pi = 3.141592653589793;
int x_hi;
int x_lo;
/*
Record the range of X we need to fill in.
*/
x_lo = 1;
x_hi = n;
/*
If we need just one new value, do that here to avoid null arrays.
*/
if ( x_hi - x_lo + 1 == 1 )
{
r = r8vec_uniform_01_new ( 2, seed );
x[x_hi-1] = sqrt ( - 2.0 * log ( r[0] ) ) * cos ( 2.0 * r8_pi * r[1] );
free ( r );
}
/*
If we require an even number of values, that's easy.
*/
else if ( ( x_hi - x_lo + 1 ) % 2 == 0 )
{
m = ( x_hi - x_lo + 1 ) / 2;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2*m-2; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( - 2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
free ( r );
}
/*
If we require an odd number of values, we generate an even number,
and handle the last pair specially, storing one in X(N), and
saving the other for later.
*/
else
{
x_hi = x_hi - 1;
m = ( x_hi - x_lo + 1 ) / 2 + 1;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2*m-4; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( - 2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
i = 2 * m - 2;
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
free ( r );
}
for ( i = 0; i < n; i++ )
{
x[i] = b + c * x[i];
}
return;
}
/******************************************************************************/
double *r8vec_normal_ab_new ( int n, double b, double c, int *seed )
/******************************************************************************/
/*
Purpose:
R8VEC_NORMAL_AB_NEW returns a scaled pseudonormal R8VEC.
Discussion:
The scaled normal probability distribution function (PDF) has
mean A and standard deviation B.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
06 August 2013
Author:
John Burkardt
Parameters:
Input, int N, the number of values desired.
Input, double B, C, the mean and standard deviation.
Input/output, int *SEED, a seed for the random number generator.
Output, double R8VEC_NORMAL_AB_NEW[N], a sample of the standard normal PDF.
Local parameters:
Local, double R[N+1], is used to store some uniform random values.
Its dimension is N+1, but really it is only needed to be the
smallest even number greater than or equal to N.
Local, int X_LO, X_HI, records the range of entries of
X that we need to compute.
*/
{
int i;
int m;
double *r;
const double r8_pi = 3.141592653589793;
double *x;
int x_hi;
int x_lo;
x = ( double * ) malloc ( n * sizeof ( double ) );
/*
Record the range of X we need to fill in.
*/
x_lo = 1;
x_hi = n;
/*
If we need just one new value, do that here to avoid null arrays.
*/
if ( x_hi - x_lo + 1 == 1 )
{
r = r8vec_uniform_01_new ( 2, seed );
x[x_hi-1] = sqrt ( - 2.0 * log ( r[0] ) ) * cos ( 2.0 * r8_pi * r[1] );
free ( r );
}
/*
If we require an even number of values, that's easy.
*/
else if ( ( x_hi - x_lo + 1 ) % 2 == 0 )
{
m = ( x_hi - x_lo + 1 ) / 2;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2*m-2; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( - 2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
free ( r );
}
/*
If we require an odd number of values, we generate an even number,
and handle the last pair specially, storing one in X(N).
*/
else
{
x_hi = x_hi - 1;
m = ( x_hi - x_lo + 1 ) / 2 + 1;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2*m-4; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( - 2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
i = 2*m - 2;
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
free ( r );
}
for ( i = 0; i < n; i++ )
{
x[i] = b + c * x[i];
}
return x;
}
/******************************************************************************/
void r8vec_print ( int n, double a[], char *title )
/******************************************************************************/
/*
Purpose:
R8VEC_PRINT prints an R8VEC.
Discussion:
An R8VEC is a vector of R8's.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
08 April 2009
Author:
John Burkardt
Parameters:
Input, int N, the number of components of the vector.
Input, double A[N], the vector to be printed.
Input, char *TITLE, a title.
*/
{
int i;
fprintf ( stdout, "\n" );
fprintf ( stdout, "%s\n", title );
fprintf ( stdout, "\n" );
for ( i = 0; i < n; i++ )
{
fprintf ( stdout, " %8d: %14g\n", i, a[i] );
}
return;
}
/******************************************************************************/
double *r8vec_uniform_01_new ( int n, int *seed )
/******************************************************************************/
/*
Purpose:
R8VEC_UNIFORM_01_NEW returns a unit pseudorandom R8VEC.
Discussion:
This routine implements the recursion
seed = 16807 * seed mod ( 2^31 - 1 )
unif = seed / ( 2^31 - 1 )
The integer arithmetic never requires more than 32 bits,
including a sign bit.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
19 August 2004
Author:
John Burkardt
Reference:
Paul Bratley, Bennett Fox, Linus Schrage,
A Guide to Simulation,
Springer Verlag, pages 201-202, 1983.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, pages 362-376, 1986.
Peter Lewis, Allen Goodman, James Miller,
A Pseudo-Random Number Generator for the System/360,
IBM Systems Journal,
Volume 8, pages 136-143, 1969.
Parameters:
Input, int N, the number of entries in the vector.
Input/output, int *SEED, a seed for the random number generator.
Output, double R8VEC_UNIFORM_01_NEW[N], the vector of pseudorandom values.
*/
{
int i;
const int i4_huge = 2147483647;
int k;
double *r;
r = ( double * ) malloc ( n * sizeof ( double ) );
for ( i = 0; i < n; i++ )
{
k = *seed / 127773;
*seed = 16807 * ( *seed - k * 127773 ) - k * 2836;
if ( *seed < 0 )
{
*seed = *seed + i4_huge;
}
r[i] = ( double ) ( *seed ) * 4.656612875E-10;
}
return r;
}
/******************************************************************************/
| 2.875 | 3 |
2024-11-18T22:37:11.525885+00:00
| 2015-10-28T20:04:08 |
33728da058594dc3985b6b7063765daf3967e6ff
|
{
"blob_id": "33728da058594dc3985b6b7063765daf3967e6ff",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-28T20:04:08",
"content_id": "4344a016ea65d9925524b6f0d7c1c8a7c03afeba",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "bd75801199e2d2c848347824a6db67e4fe970e5e",
"extension": "h",
"filename": "cx_vertex_data.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 15833314,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3557,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/earthnews/source/engine/graphics/cx_vertex_data.h",
"provenance": "stackv2-0107.json.gz:92913",
"repo_name": "uonyx/now360",
"revision_date": "2015-10-28T20:04:08",
"revision_id": "09f8925b2660f71fe5b478bf2e14fc9ca0f38494",
"snapshot_id": "03a1c90f9958569e9e441068cb7df44506d04b27",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/uonyx/now360/09f8925b2660f71fe5b478bf2e14fc9ca0f38494/earthnews/source/engine/graphics/cx_vertex_data.h",
"visit_date": "2021-01-20T09:12:39.860485"
}
|
stackv2
|
//
// cx_vertex_data.h
//
// Copyright (c) 2012 Ubaka Onyechi. All rights reserved.
//
#ifndef CX_VERTEX_DATA_H
#define CX_VERTEX_DATA_H
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "../system/cx_system.h"
#include "../system/cx_vector4.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
#define CX_VERTEX_DATA_AOS 1 // array of structs
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
#if !CX_VERTEX_DATA_AOS
#define CX_VERTEX_POSITION_SIZE 3
#define CX_VERTEX_NORMAL_SIZE 3
#define CX_VERTEX_TANGENT_SIZE 3
#define CX_VERTEX_TEXCOORD_SIZE 2
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef enum cx_vertex_format
{
CX_VERTEX_FORMAT_INVALID,
CX_VERTEX_FORMAT_P, // position
CX_VERTEX_FORMAT_PN, // position, normal
CX_VERTEX_FORMAT_PT, // position, texcoord
CX_VERTEX_FORMAT_PTN, // position, texcoord, normal
CX_VERTEX_FORMAT_PTNTB, // position, texcoord, normal, tangent, bitangent
NUM_VERTEX_FORMATS
} cx_vertex_format;
#if CX_VERTEX_DATA_AOS
typedef struct cx_vertex
{
cx_vec4 position;
cx_vec4 normal;
cx_vec4 tangent;
cx_vec4 bitangent;
cx_vec2 texCoord;
} cx_vertex;
struct cx_vertex_data_aos
{
cx_vertex *vertices;
cxu16 *indices;
cxi32 numVertices;
cxi32 numIndices;
cxi32 numTriangles;
cx_vertex_format format;
};
typedef struct cx_vertex_data_aos cx_vertex_data;
#else
struct cx_vertex_data_soa
{
cxf32 *positions;
cxf32 *texCoords;
cxf32 *normals;
cxf32 *tangents;
cxf32 *bitangents;
cxu16 *indices;
cxi32 numVertices;
cxi32 numIndices;
cxi32 numTriangles;
cx_vertex_format format;
};
typedef struct cx_vertex_data_soa cx_vertex_data;
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
cx_vertex_data *cx_vertex_data_create_sphere (cxf32 radius, cxu16 slices, cx_vertex_format format);
void cx_vertex_data_destroy (cx_vertex_data *vertexData);
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif
| 2.25 | 2 |
2024-11-18T22:37:11.789848+00:00
| 2016-08-19T15:04:28 |
e396c0c65556aa2221a242b6afa70991625982a8
|
{
"blob_id": "e396c0c65556aa2221a242b6afa70991625982a8",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-19T15:04:28",
"content_id": "5bf386239a2b0b9cce1792cb799262b04d1f093b",
"detected_licenses": [
"MIT"
],
"directory_id": "48a1969a04d3b87e1bbb89c1755eaf2b92d2ad3d",
"extension": "h",
"filename": "physical_allocator.h",
"fork_events_count": 0,
"gha_created_at": "2016-08-07T22:34:50",
"gha_event_created_at": "2016-08-07T22:34:50",
"gha_language": null,
"gha_license_id": null,
"github_id": 65157036,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 717,
"license": "MIT",
"license_type": "permissive",
"path": "/include/truth/physical_allocator.h",
"provenance": "stackv2-0107.json.gz:93171",
"repo_name": "awensaunders/kernel-of-truth",
"revision_date": "2016-08-19T15:04:28",
"revision_id": "bf4bf9cd0a8753c089e401beff9b32cbe958eb4f",
"snapshot_id": "c2278d26d8681de785d78d6858f29f4ba00cb575",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/awensaunders/kernel-of-truth/bf4bf9cd0a8753c089e401beff9b32cbe958eb4f/include/truth/physical_allocator.h",
"visit_date": "2020-12-26T03:55:33.048430"
}
|
stackv2
|
#pragma once
#include <truth/types.h>
// Build the page frame bitmap.
void physical_allocator_init(size_t phys_memory_size);
/* Free a physical page @frame */
void free_frame(page_frame_t frame);
/* Allocate a page frame.
* @return a new page frame marked as used.
*/
page_frame_t alloc_frame();
/* Mark a single page @frame as used. */
void use_frame(page_frame_t frame);
/* Check if a physical address @frame is free.
* @return true if it's free, false otherwise
*/
bool is_free_frame(page_frame_t frame);
/* Mark a range of physical addresses as in use.
* Starts including the @begin page, and goes up to but does not include the
* @end page.
*/
void use_range(page_frame_t begin, page_frame_t end);
| 2.53125 | 3 |
2024-11-18T22:37:12.320550+00:00
| 2023-03-03T10:38:11 |
fec53a757b9fc50837e44f12f081995a4d4bca12
|
{
"blob_id": "fec53a757b9fc50837e44f12f081995a4d4bca12",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-03T10:38:11",
"content_id": "2b04103ff67e8102bf48c8c577cd53974489c0fe",
"detected_licenses": [
"MIT"
],
"directory_id": "10d6ae9a652a2a3b80b66ea72b34633af510c3c5",
"extension": "c",
"filename": "one-wire.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 186288884,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1271,
"license": "MIT",
"license_type": "permissive",
"path": "/src/embedded/radio-base/sender/one-wire.c",
"provenance": "stackv2-0107.json.gz:93429",
"repo_name": "cidermole/yaca",
"revision_date": "2023-03-03T10:38:11",
"revision_id": "041af4c7e0827842938e68fc8d5ffc962574d2bd",
"snapshot_id": "b4e372db6fc7c126ca76d7f85d5462b2a1b8d8d3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cidermole/yaca/041af4c7e0827842938e68fc8d5ffc962574d2bd/src/embedded/radio-base/sender/one-wire.c",
"visit_date": "2023-03-08T18:41:27.944725"
}
|
stackv2
|
#include "one-wire.h"
#include <avr/io.h>
#include <util/delay.h>
#include <inttypes.h>
void ow_write(uint8_t b) {
uint8_t i;
for(i = 0; i < 8; i++) {
if(b & 1) {
// write 1
set_bit(OW_DDR, OW_BIT); // OW bit = output -> pull low
_delay_us(2);
clear_bit(OW_DDR, OW_BIT);
_delay_us(80);
} else {
// write 0
set_bit(OW_DDR, OW_BIT); // OW bit = output -> pull low
_delay_us(80);
clear_bit(OW_DDR, OW_BIT);
_delay_us(2);
}
b >>= 1;
}
}
uint8_t ow_read() {
uint8_t buf = 0;
uint8_t i;
for(i = 0; i < 8; i++) {
buf >>= 1;
set_bit(OW_DDR, OW_BIT); // OW bit = output -> pull low
_delay_us(2);
clear_bit(OW_DDR, OW_BIT);
_delay_us(12);
if(bit_is_set(OW_PIN, OW_BIT))
buf |= 0x80;
_delay_us(80 - 14);
}
return buf;
}
void ow_pull() {
set_bit(OW_PORT, OW_BIT);
set_bit(OW_DDR, OW_BIT);
}
void ow_release() {
clear_bit(OW_DDR, OW_BIT);
clear_bit(OW_PORT, OW_BIT);
}
uint8_t ow_check() {
// reset pulse: low for min. 480 us, max. 960 us
set_bit(OW_DDR, OW_BIT); // OW bit = output -> pull low
_delay_us(600);
clear_bit(OW_DDR, OW_BIT);
_delay_us(600);
return 1; // FIXME we should check if DS18S20 is there (presence pulse, datasheet page 13)
}
| 2.625 | 3 |
2024-11-18T22:37:12.717751+00:00
| 2020-12-16T01:23:53 |
ba2acd964563b35b2496c1caa0110cd7bb07bfe0
|
{
"blob_id": "ba2acd964563b35b2496c1caa0110cd7bb07bfe0",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-16T01:23:53",
"content_id": "d6be9de8d4307a4a78fd7106707bd20ea0f8f657",
"detected_licenses": [
"MIT"
],
"directory_id": "1f59e983476ccad5a39b7b00b0fc0eb2fab63d8c",
"extension": "c",
"filename": "example.c",
"fork_events_count": 6,
"gha_created_at": "2014-05-22T19:51:11",
"gha_event_created_at": "2020-09-23T23:27:04",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 20074732,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1076,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/builder/example.c",
"provenance": "stackv2-0107.json.gz:94079",
"repo_name": "ohler55/ojc",
"revision_date": "2020-12-16T01:23:53",
"revision_id": "08f6420b34135a5017c1eefe142541b77748fd8f",
"snapshot_id": "d2ae70ff728e58b25cb0afb6a6611b4f9f66a346",
"src_encoding": "UTF-8",
"star_events_count": 28,
"url": "https://raw.githubusercontent.com/ohler55/ojc/08f6420b34135a5017c1eefe142541b77748fd8f/examples/builder/example.c",
"visit_date": "2021-01-17T13:48:57.921292"
}
|
stackv2
|
// Copyright (c) 2020 by Peter Ohler, ALL RIGHTS RESERVED
#include <stdio.h>
#include "oj/oj.h"
// This example demonstrates the use of the ojBuilder to construct a JSON
// document as well as writing the document to a file as indented JSON.
int
main(int argc, char **argv) {
struct _ojBuilder b = OJ_BUILDER_INIT;
oj_build_object(&b, NULL);
oj_build_double(&b, "num", 12.34e567L);
oj_build_array(&b, "list");
oj_build_bool(&b, NULL, true);
oj_build_bool(&b, NULL, false);
oj_build_pop(&b);
oj_build_pop(&b);
if (OJ_OK != b.err.code) {
printf("Build error: %s at %d:%d\n", b.err.msg, b.err.line, b.err.col);
return 1;
}
char buf[256];
struct _ojErr err = OJ_ERR_INIT;
oj_fill(&err, b.top, 2, buf, sizeof(buf));
printf("Built %s\n", buf);
// Once written, the file should look like the output displayed by printf.
oj_fwrite(&err, b.top, 2, "out.json");
if (OJ_OK != err.code) {
printf("Build error: %s at %d:%d\n", err.msg, err.line, err.col);
return 1;
}
oj_cleanup();
return 0;
}
| 2.890625 | 3 |
2024-11-18T22:37:12.798704+00:00
| 2021-06-29T16:30:54 |
648669fe450ee436b38c00cfaadaa2ac8aea306c
|
{
"blob_id": "648669fe450ee436b38c00cfaadaa2ac8aea306c",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-29T16:30:54",
"content_id": "5c35d76425c00ceeb4d6d01ddb2bbd94bdeca26d",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "e68fa846c71ffd3d40868e63197eb0947aea061b",
"extension": "c",
"filename": "server.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4225,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/examples/autobahn/server.c",
"provenance": "stackv2-0107.json.gz:94208",
"repo_name": "cwerner77/wic",
"revision_date": "2021-06-29T16:30:54",
"revision_id": "54d124005c25ca376aa4e85c45f87b6c3bb95797",
"snapshot_id": "f646e96a3b2571c4423996f75e2ed39a84caaf85",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cwerner77/wic/54d124005c25ca376aa4e85c45f87b6c3bb95797/examples/autobahn/server.c",
"visit_date": "2023-06-06T13:39:20.218495"
}
|
stackv2
|
/* Copyright (c) 2020 Cameron Harper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* */
#include "wic.h"
#include "transport.h"
#include "log.h"
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <poll.h>
#include <errno.h>
static void on_close(struct wic_inst *inst, uint16_t code, const char *reason, uint16_t size);
static void on_text(struct wic_inst *inst, bool fin, const char *data, uint16_t size);
static void on_binary(struct wic_inst *inst, bool fin, const void *data, uint16_t size);
static void on_open(struct wic_inst *inst);
static void do_write(struct wic_inst *inst, const void *data, size_t size);
static uint32_t do_random(struct wic_inst *inst);
int main(int argc, char **argv)
{
static struct wic_inst inst;
static uint8_t tx[UINT16_MAX+10UL];
static uint8_t rx[UINT16_MAX];
srand(time(NULL));
int server = -1;
int client = -1;
struct wic_init_arg arg = {0};
arg.rx = rx;
arg.rx_max = sizeof(rx);
arg.tx = tx;
arg.tx_max = sizeof(tx);
arg.on_open = on_open;
arg.on_close = on_close;
arg.on_text = on_text;
arg.on_binary = on_binary;
arg.write = do_write;
arg.rand = do_random;
arg.role = WIC_ROLE_SERVER;
struct sockaddr_in serv_addr;
struct sockaddr_in client_addr;
socklen_t client_len;
server = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if(server < 0){
ERROR("socket()")
exit(EXIT_FAILURE);
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(9002);
if(bind(server, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0){
ERROR("bind()")
exit(EXIT_FAILURE);
}
for(;;){
listen(server, 2);
client = accept(server, (struct sockaddr *)&client_addr, &client_len);
if(client < 0){
ERROR("accept()")
break;
}
arg.app = &client;
if(!wic_init(&inst, &arg)){
ERROR("wic_init()")
transport_close(&client);
break;
}
while(transport_recv(client, &inst));
wic_close(&inst);
}
transport_close(&server);
LOG("exiting...")
exit(EXIT_SUCCESS);
}
static void on_close(struct wic_inst *inst, uint16_t code, const char *reason, uint16_t size)
{
transport_close((int *)wic_get_app(inst));
}
static void on_text(struct wic_inst *inst, bool fin, const char *data, uint16_t size)
{
wic_send_text(inst, fin, data, size);
}
static void on_binary(struct wic_inst *inst, bool fin, const void *data, uint16_t size)
{
wic_send_binary(inst, fin, data, size);
}
static void on_open(struct wic_inst *inst)
{
wic_start(inst);
}
static void do_write(struct wic_inst *inst, const void *data, size_t size)
{
if(!transport_write(*(int *)wic_get_app(inst), data, size)){
ERROR("transport_write()")
wic_close(inst);
}
}
static uint32_t do_random(struct wic_inst *inst)
{
return rand();
}
| 2.28125 | 2 |
2024-11-18T22:37:14.002277+00:00
| 2014-06-09T15:33:32 |
f6fa69c9a126af4a800d57966491ac59f0f96fee
|
{
"blob_id": "f6fa69c9a126af4a800d57966491ac59f0f96fee",
"branch_name": "refs/heads/master",
"committer_date": "2014-06-09T15:33:32",
"content_id": "08e5c7ecc719b2a6fe535090bcef7078e45533b0",
"detected_licenses": [
"MIT"
],
"directory_id": "28a2664f7f2cfd74733e00572104330ebf0f386d",
"extension": "c",
"filename": "console.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6449,
"license": "MIT",
"license_type": "permissive",
"path": "/madcos/src/kernel/console.c",
"provenance": "stackv2-0107.json.gz:95244",
"repo_name": "n3on/madOS",
"revision_date": "2014-06-09T15:33:32",
"revision_id": "768310898b922b76245f42e38582944c3a901863",
"snapshot_id": "2d2adbb65f0b4c48c709427656e1d61ea3b880d7",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/n3on/madOS/768310898b922b76245f42e38582944c3a901863/madcos/src/kernel/console.c",
"visit_date": "2016-09-16T04:35:36.570700"
}
|
stackv2
|
/****************************************
(c)2008-2009 by MADCrew all rights reserved
Marcel S., Dmitrij M.
****************************************/
/**
*\file console.c
*\brief Implementiert die Kernelkonsole
*
*/
#include <system\console.h>
struct Console console;
//initialisiere konsole, belege mit standartwertten
void initConsole()
{
//videobuffer adresse
console.video = (unsigned short*)0xB8000;
console.numX = 80; //breite in zeichen
console.numY = 25; //höhe in zeichen
console.fgColor = CL_WHITE; //schriftvordergrund
console.bgColor = CL_BLACK; //schrifthintergrund
console.clColor = CL_BLACK; //konsolenhintergrund
console.cursor_x = 0; //cursorposiition
console.cursor_y = 0;
console.tabWidth = 4; //breite von dem tab zeichen
console.blink = 0; //status ob text blinkt
}
//ausgabe von einem zeichen
void kputchar(char c)
{
//newline
if(c=='\n')
{
//gehe eine zeile nach unten
setCursor(0, ++console.cursor_y);
}
//tabulator
else if(c=='\t')
{
//verschiebe x cursor position um tabbreite
setCursor(console.cursor_x+console.tabWidth, console.cursor_y);
}
//zeichen löschen
else if(c=='\b')
{
//nicht anfang der zeile
if(console.cursor_x>0)
{
//zeichen löschen und x cursor position verringern
setCursor(--console.cursor_x, console.cursor_y);
kputchar(' ');
setCursor(--console.cursor_x, console.cursor_y);
}
//anfang der zeile
else
{
//zeichen löschen und y position verringen, um in die obere zeile zu kommen
setCursor(console.numX, --console.cursor_y);
kputchar(' ');
setCursor(console.numX, --console.cursor_y);
}
}
//alle andere zeichen einfach in den textbuffer ausgeben
else
{
//fülle textbuffer mit zeichen und parametern
console.video[console.cursor_x+console.cursor_y*console.numX] = \
c |(console.fgColor<<8) | (console.bgColor<<12);
//verschiebe richtig den cursor
updateCursor();
}
}
//string ausgeben
void kprint(char *str)
{
int i;
//jedes zeichen einzeln ausgeben
for(i=0; str[i]; i++)
{
kputchar(str[i]);
}
}
//konsolenbildschirm löschen
void clearScreen()
{
//textbuffer mit leerzeichen füllen und entsprechende farbe als parameter setzen
int numChars = console.numX*console.numY;
int i;
for(i=0; i<numChars; i++)
{
console.video[i] = '\0' | (console.clColor<<12);
}
//cursorposition ist wieder oben links(startposition)
setCursor(0,0);
}
//konsolenhintergrundfarbe setzen
void setClearColor(enum TEXT_COLOR color)
{
console.clColor = color;
console.bgColor = color;
}
//text hintergrundfarbe setzen
void setBgColor(enum TEXT_COLOR color)
{
console.bgColor = color;
}
enum TEXT_COLOR getBgColor()
{
return console.bgColor;
}
//text vordergrundfarbe setzen
void setFgColor(enum TEXT_COLOR color)
{
console.fgColor = color;
}
//schrift blinkt oder nicht?
void setBlink(int blinker)
{
if(blinker)
console.blink = 1;
else
console.blink = 0;
}
enum TEXT_COLOR getFgColor()
{
return console.fgColor;
}
//cursorposition setzen
void setCursor(int x, int y)
{
if((x<=console.numX) && (x>=0))
console.cursor_x=x;
else if((x>console.numX) && (x>=0))
{
console.cursor_x=0;
++y;
}
else if(x<0)
{
console.cursor_x=console.numX-1;
--console.cursor_y;
}
console.cursor_y=y;
if(y>=console.numY)
{
console.cursor_y=console.numY-3;
scrollDown();
}
//hardware cursor aktualisieren
updateHrdCursor();
}
//nach unten scrollen, wenn konsole zu voll ist
void scrollDown()
{
int i;
//konsolenspeicher um eine zeile nach oben verschieben und die untere zeile löschen
memcpyw(console.video, console.video+console.numX*3, console.numX*(console.numY-3));
memsetw(console.video+(console.numX*(console.numY-3)),
' ' |(console.clColor<<8) | (console.clColor<<12),
console.numX*3);
}
//cursor aktualisieren
void updateCursor()
{
setCursor(++console.cursor_x, console.cursor_y);
}
//hardware cursor aktualisieren
void updateHrdCursor()
{
unsigned int cursorIndex;
cursorIndex = (console.cursor_x)+console.cursor_y*console.numX;
//vga ports für cursor
outb(0x3D4, 0xE);
outb(0x3D5, cursorIndex>>8);
outb(0x3D4, 0xF);
outb(0x3D5, cursorIndex);
cursorIndex = 0;
}
//starte befehl ein/ausgabe für die konsole
void startConsole()
{
//solange kein abbruch, befehl einlesen und verarbeiten
int runConsole = 1;
while(runConsole)
{
char command[256] = {'\0'};
kprint("\nsympos > ");
_kbGetStr(command);
if(processCommand(command)!=0)
runConsole = 0;
/*unsigned char key = _kbGetChar();
if(key<255)
kputchar(key);*/
//zu schnelle bearbeitung verhindern
timerSleep(50);
}
}
//befehl bearbeiten
int processCommand(char* command)
{
//speicher für das angegebene befehl
//char com[256]={'\0'};
char com[2][256]={'\0','\0'};
//leerzeichen am anfang und ende löschen
trim(command, command);
//befehl - argument trennen(leerzeichen ist trennzeichen)
tokanize(command, com, ' ');
//debug ausgaben
/*kprint("\n");
kprint(com[0]);
kprint("\n");
kprint(com[1]);
kprint("\n");
kprint(command);
kprint('\n');*/
//textfarbe setzen
setFgColor(CL_LIGHT_GRAY);
//befehle abarbeiten
if(!strcmp(com[0], "help"))
{
kprint("\n\n =Sympos, Symplatonix Operating System\n");
kprint(" =(c)2008-2009 Symplatonix Software\n\n");
setFgColor(CL_RED);
kprint(" ==Befehle:\n");
setFgColor(CL_LIGHT_GRAY);
kprint(" ==help - Befehlsuerbersicht\n");
kprint(" ==shutdown - Computer herunterfahren\n");
kprint(" ==reboot - Computer neustarten\n");
kprint(" ==cls - Bildschirm loeschen\n");
kprint(" ==int interruptNummer - interrupt ausloesen\n\n");
}
else if(!strcmp(com[0], "shutdown"))
{
kprint("\n\nDer Computer wird heruntergefahren!\n\n");
return 1;
}
else if(!strcmp(com[0], "reboot"))
{
kprint("\n\nDer Computer wird neugestarted!\n\n");
reboot();
}
else if(!strcmp(com[0], "cls"))
{
clearScreen();
}
else if(!strcmp(com[0], "int"))
{
unsigned char intNum = atoi(com[1]);
unsigned char intN = 10;
//asm("int %0;"::"g" (intN));
}
//für interne testzwecke
else if(!strcmp(com[0], "test"))
{
floppy_init();
}
else
{
kprint("\n\nBefehl [");
setFgColor(CL_RED);
kprint(com[0]);
setFgColor(CL_LIGHT_GRAY);
kprint("] nicht gefunden!...\n");
}
command[0]='\0';
setFgColor(CL_WHITE);
return 0;
}
| 2.828125 | 3 |
2024-11-18T22:37:14.095481+00:00
| 2020-09-01T07:12:55 |
583a06b42440dc3c2e313417d8388d837bc465fe
|
{
"blob_id": "583a06b42440dc3c2e313417d8388d837bc465fe",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-01T07:12:55",
"content_id": "2f7706a73ee9c970e3f81fde87b9849db7488aa3",
"detected_licenses": [
"Unlicense"
],
"directory_id": "0e007b1afb6ce6d5522a7471fef740439f56011d",
"extension": "c",
"filename": "select.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 90471406,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1911,
"license": "Unlicense",
"license_type": "permissive",
"path": "/base-usage/systemcall/select.c",
"provenance": "stackv2-0107.json.gz:95372",
"repo_name": "sczzq/symmetrical-spoon",
"revision_date": "2020-09-01T07:12:55",
"revision_id": "aa0c27bb40a482789c7c6a7088307320a007b49b",
"snapshot_id": "9ab7813c5238bb43a1c4e60244781f05bc422470",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sczzq/symmetrical-spoon/aa0c27bb40a482789c7c6a7088307320a007b49b/base-usage/systemcall/select.c",
"visit_date": "2021-06-03T21:00:45.448102"
}
|
stackv2
|
/*************************************************************************
> File Name: select.c
> Author: ziqiang
> Mail: ziqiang_free@163.com
> Created Time: Wed 24 May 2017 03:51:28 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdbool.h>
#include "socket.h"
#undef max
#define max(a, b) ((a) > (b) ? (a) : (b))
bool empty(int* fds, fd_set* rfds, int n)
{
for(int i=0; i<n; i++){
// if has one fd in set, then the set is not empty.
if(FD_ISSET(fds[i], rfds))
return false;
}
// here, all of the fds is not in set, then set is empty.
return true;
}
/*
* issue:
* if fd_num equlas 1, then select() returns until timeout, and return value is -1,
* if fd_num greater then 1, then select() return immidiately, and the last socket file desctiptor is not in set using FD_ISSET() to check.
*
*/
int
main(void)
{
fd_set rfds;
FD_ZERO(&rfds);
int nfds = 1;
int fd_num = 10*1000;
int fds[10*1000];
for(int i=0; i<fd_num; i++){
int fd = getsocket(AF_INET, SOCK_STREAM);
if(fd < 0){
fd_num = i;
break;
}
fds[i] = fd;
FD_SET(fd, &rfds);
nfds = max(nfds, fd);
}
printf("true=%d, false=%d\n", true, false);
for(int i=0; i<fd_num; i++){
printf("fd=%d is %d\n", fds[i], FD_ISSET(fds[i], &rfds));
}
while(!empty(fds, &rfds, fd_num)){
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
int retval = select(nfds, &rfds, NULL, NULL, &tv);
if(retval == -1)
perror("select()");
else if(retval){
printf("data is available now.\n");
for(int i=0; i<fd_num; i++){
// printf("fd=%d is %d\n", fds[i], FD_ISSET(fds[i], &rfds));
}
}
else
printf("No data within five seconds.\n");
break;
}
for(int i=0; i<fd_num; i++){
if(fds[i] > 2)
close(fds[i]);
}
exit(EXIT_SUCCESS);
}
| 2.953125 | 3 |
2024-11-18T22:37:14.271742+00:00
| 2020-09-16T15:09:55 |
69879fe99a0c6db6c2c824916412b1383c09f2b1
|
{
"blob_id": "69879fe99a0c6db6c2c824916412b1383c09f2b1",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-16T15:10:20",
"content_id": "77a89c9ccba5abaa74239cb67fcbd49f8c707ff4",
"detected_licenses": [
"MIT"
],
"directory_id": "53e3c7acf8d2feb7dbf566338460bac9d6cd531d",
"extension": "c",
"filename": "read_lastwallpaper.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 58122683,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3457,
"license": "MIT",
"license_type": "permissive",
"path": "/read_lastwallpaper.c",
"provenance": "stackv2-0107.json.gz:95628",
"repo_name": "hboetes/fbsetbg",
"revision_date": "2020-09-16T15:09:55",
"revision_id": "cadee0b4903ec19b665d6bf0e516a9cd6a598888",
"snapshot_id": "835424e2be1e7e042f4eabb1f37404fd9e85958e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/hboetes/fbsetbg/cadee0b4903ec19b665d6bf0e516a9cd6a598888/read_lastwallpaper.c",
"visit_date": "2021-03-08T19:36:30.298659"
}
|
stackv2
|
/*
* Copyright (c) 2004 - 2016 Han Boetes <hboetes@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "fbsetbg.h"
/*
* This function reads arguments of the last remembered session for reuse for
* fbsetbg -l
*/
int
read_lastwallpaper(char *option, char *wallpaper)
{
char *lstwllpprarray;
char *tempstring;
char *display, *t1, *t2;
FILE *fp;
uint i;
int found = FALSE, ret;
tempstring = malloc(MAXPATHLEN);
if (tempstring == NULL)
err(1, "out of memory");
lstwllpprarray = malloc(MAXPATHLEN);
if (lstwllpprarray == NULL)
err(1, "out of memory");
/* Copy the pointers for freeing (because of strsep */
t1 = tempstring;
t2 = lstwllpprarray;
if ((display = getenv("DISPLAY")) == NULL)
errx(1, "the DISPLAY environment variable isn't set");
if ((fp = fopen(lastwallpaper, "r")) == NULL)
/* Most likely ~/.lastwallpaper doesn't exist */
err(1, "%s", lastwallpaper);
for (i = 0; i < MAXLLW; i++)
{
if (fgets(lstwllpprarray, MAXPATHLEN, fp) == NULL)
break;
ret = snprintf(tempstring, MAXPATHLEN, "|%s\n", display);
if (ret < 0 || ret >= MAXPATHLEN)
{
if (fclose(fp) != 0)
err(1, "%s", lastwallpaper);
errx(1, "error while trying to read %s", lastwallpaper);
}
if (strstr(lstwllpprarray, tempstring))
{
(void)strncpy(option, strsep(&lstwllpprarray, "|"), MAXPATHLEN - 1);
option[MAXPATHLEN - 1] = '\0';
(void)strncpy(wallpaper, strsep(&lstwllpprarray, "|"), MAXPATHLEN - 1);
wallpaper[MAXPATHLEN - 1] = '\0';
found = TRUE;
break;
}
}
if (fclose(fp) != 0)
err(1, "%s", lastwallpaper);
free(t1);
free(t2);
if (found == TRUE)
return(TRUE);
else
errx(1, "no wallpaper recorded for display %s", display);
}
| 2.09375 | 2 |
2024-11-18T22:37:14.333712+00:00
| 2018-02-13T20:18:19 |
4047eb04e8993dff127cf5bb2e3205695c4f5273
|
{
"blob_id": "4047eb04e8993dff127cf5bb2e3205695c4f5273",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-13T20:18:19",
"content_id": "eee4e3f73451ba175ca692125ae2d7b944e90328",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "c9225166490e448c0b18845c90de4c53fdba5725",
"extension": "c",
"filename": "pref.time.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": 10662,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/cmd/bin/pref.time.c",
"provenance": "stackv2-0107.json.gz:95758",
"repo_name": "jdefrancesco/newsys",
"revision_date": "2018-02-13T20:18:19",
"revision_id": "314956b8ca463b8d7cc9b30de2be2d4247adf432",
"snapshot_id": "98961c1f93a2dab230c24d386301626858aaf099",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jdefrancesco/newsys/314956b8ca463b8d7cc9b30de2be2d4247adf432/cmd/bin/pref.time.c",
"visit_date": "2023-03-17T03:57:04.187930"
}
|
stackv2
|
/* Copyright (c) 2017, Piotr Durlej
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <wingui_cgadget.h>
#include <wingui_msgbox.h>
#include <wingui_color.h>
#include <wingui_form.h>
#include <wingui.h>
#include <sys/signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <newtask.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <time.h>
#include <err.h>
#define HWCLOCK "/sbin/hwclock"
#define WEEK_START 1
struct gadget *tod;
struct gadget *cal;
struct form *form;
int time_chg;
int on_close(struct form *f)
{
exit(0);
}
#define CAL_FONT WIN_FONT_DEFAULT
#define get_cal_data(g) ((struct cal_data *)((g)->p_data))
static void cal_focus(struct gadget *g);
static void cal_remove(struct gadget *g);
static void cal_redraw_day(struct gadget *g, int wd, time_t t);
static void cal_redraw(struct gadget *g, int wd);
static void cal_ptr_down(struct gadget *g, int x, int y, int button);
static void cal_key_down(struct gadget *g, unsigned ch, unsigned shift);
struct gadget * cal_creat(struct form *f, int x, int y);
void cal_on_change(struct gadget *g, void (*proc)(struct gadget *g));
void cal_set_time(struct gadget *g, time_t t);
time_t cal_get_time(struct gadget *g);
static char *cal_mstr[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec" };
static char *cal_dstr[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
struct cal_data
{
void (*on_change)(struct gadget *g);
time_t time;
int cell_w;
int cell_h;
};
static void cal_focus(struct gadget *g)
{
win_paint();
gadget_clip(g, 0, 0, g->rect.w, g->rect.h, 0, 0);
cal_redraw_day(g, g->form->wd, get_cal_data(g)->time);
win_end_paint();
}
static void cal_remove(struct gadget *g)
{
free(get_cal_data(g));
}
static void cal_redraw_day(struct gadget *g, int wd, time_t t)
{
struct cal_data *cd = get_cal_data(g);
struct tm *tm = localtime(&t);
win_color s_bg;
win_color s_fg;
win_color bg;
win_color fg;
char str[4];
int cell_i;
int w, h;
int x, y;
if (form_get_focus(g->form) == g)
{
s_bg = wc_get(WC_SEL_BG);
s_fg = wc_get(WC_SEL_FG);
}
else
{
s_bg = wc_get(WC_NFSEL_BG);
s_fg = wc_get(WC_NFSEL_FG);
}
bg = wc_get(WC_BG);
fg = wc_get(WC_FG);
cell_i = (42 + tm->tm_wday - (tm->tm_mday - 1) - WEEK_START) % 7;
cell_i += tm->tm_mday - 1;
x = (cell_i % 7) * cd->cell_w;
y = (cell_i / 7) * cd->cell_h;
y += cd->cell_h * 2;
sprintf(str, "%i ", (int)tm->tm_mday);
win_text_size(CAL_FONT, &w, &h, str);
if (t == cd->time)
{
win_rect(wd, s_bg, x, y, cd->cell_w, cd->cell_h);
win_btext(wd, s_bg, s_fg, x + cd->cell_w - w, y, str);
return;
}
win_rect(wd, bg, x, y, cd->cell_w, cd->cell_h);
win_btext(wd, bg, fg, x + cd->cell_w - w, y, str);
}
static void cal_redraw(struct gadget *g, int wd)
{
struct cal_data *cd = get_cal_data(g);
struct tm *tm = localtime(&cd->time);
time_t t = cd->time;
win_color h_bg;
win_color h_fg;
win_color bg;
win_color fg;
char str[64];
int mon;
int i;
h_bg = wc_get(WC_TITLE_BG);
h_fg = wc_get(WC_TITLE_FG);
bg = wc_get(WC_BG);
fg = wc_get(WC_FG);
win_set_font(wd, CAL_FONT);
win_paint();
win_rect(wd, h_bg, 0, 0, g->rect.w, cd->cell_h);
win_rect(wd, bg, 0, cd->cell_h, g->rect.w, g->rect.h - cd->cell_h);
sprintf(str, "%s %i", cal_mstr[tm->tm_mon], (int)tm->tm_year + 1900);
win_text(wd, h_fg, 1, 0, str);
for (i = 0; i < 7; i++)
{
const char *dstr = cal_dstr[(i + WEEK_START) % 7];
int w, h;
int x;
win_text_size(CAL_FONT, &w, &h, dstr);
x = i * cd->cell_w;
x += (cd->cell_w - w) / 2;
win_text(wd, fg, x + 1, cd->cell_h, dstr);
win_text(wd, fg, x, cd->cell_h, dstr);
}
win_hline(wd, fg, 0, cd->cell_h * 2 - 1, g->rect.w);
t -= (tm->tm_mday - 1) * 60 * 60 * 24;
tm = localtime(&t);
mon = tm->tm_mon;
do
{
cal_redraw_day(g, wd, t);
t += 60 * 60 * 24;
tm = localtime(&t);
} while (tm && tm->tm_mon == mon);
win_end_paint();
}
static void cal_ptr_down(struct gadget *g, int x, int y, int button)
{
struct cal_data *cd = get_cal_data(g);
struct tm *tm;
int cell_i;
time_t t;
cell_i = x / cd->cell_w + (y / cd->cell_h) * 7 - 14;
if (cell_i < 0)
return;
tm = localtime(&cd->time);
t = cd->time;
t -= (tm->tm_mday - 1) * 60 * 60 * 24;
t += cell_i * 60 * 60 * 24;
t -= (42 + tm->tm_wday - (tm->tm_mday - 1) - WEEK_START) % 7 * 60 * 60 * 24;
cal_set_time(g, t);
}
static const int __libc_monthlen[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static void cal_key_down(struct gadget *g, unsigned ch, unsigned shift)
{
struct cal_data *cd = get_cal_data(g);
struct tm *tm;
time_t t;
switch (ch)
{
case WIN_KEY_HOME:
cal_set_time(g, time(NULL));
break;
case WIN_KEY_LEFT:
cal_set_time(g, cd->time - 60 * 60 * 24);
break;
case WIN_KEY_RIGHT:
cal_set_time(g, cd->time + 60 * 60 * 24);
break;
case WIN_KEY_UP:
cal_set_time(g, cd->time - 60 * 60 * 24 * 7);
break;
case WIN_KEY_DOWN:
cal_set_time(g, cd->time + 60 * 60 * 24 * 7);
break;
case WIN_KEY_PGUP:
tm = localtime(&cd->time);
if (shift & WIN_SHIFT_CTRL)
tm->tm_year -= 100;
else if (shift & WIN_SHIFT_SHIFT)
tm->tm_year--;
else if (!tm->tm_mon)
{
tm->tm_year--;
tm->tm_mon = 11;
}
else
tm->tm_mon--;
cltime(tm);
t = mktime(tm);
if (t != -1 || tm->tm_year == 69)
cal_set_time(g, mktime(tm));
break;
case WIN_KEY_PGDN:
tm = localtime(&cd->time);
if (shift & WIN_SHIFT_CTRL)
tm->tm_year += 100;
else if (shift & WIN_SHIFT_SHIFT)
tm->tm_year++;
else if (tm->tm_mon == 11)
{
tm->tm_year++;
tm->tm_mon = 0;
}
else
tm->tm_mon++;
cltime(tm);
t = mktime(tm);
if (t != -1 || tm->tm_year == 69)
cal_set_time(g, mktime(tm));
break;
}
}
struct gadget *cal_creat(struct form *f, int x, int y)
{
struct cal_data *cd;
struct gadget *g;
int w, h;
cd = malloc(sizeof *cd);
if (!cd)
return NULL;
cd->on_change = NULL;
cd->time = time(NULL);
win_text_size(CAL_FONT, &cd->cell_w, &cd->cell_h, " 13 ");
w = cd->cell_w * 7;
h = cd->cell_h * 8;
g = gadget_creat(f, x, y, w, h);
if (!g)
{
free(cd);
return NULL;
}
g->p_data = cd;
gadget_set_want_focus(g, 1);
gadget_set_focus_cb(g, cal_focus);
gadget_set_remove_cb(g, cal_remove);
gadget_set_redraw_cb(g, cal_redraw);
gadget_set_ptr_down_cb(g, cal_ptr_down);
gadget_set_key_down_cb(g, cal_key_down);
return g;
}
void cal_on_change(struct gadget *g, void (*proc)(struct gadget *g))
{
struct cal_data *cd = get_cal_data(g);
cd->on_change = proc;
}
void cal_set_time(struct gadget *g, time_t t)
{
struct cal_data *cd = get_cal_data(g);
struct tm *tm;
struct tm otm;
time_t ot;
if (cd->time == t)
return;
ot = cd->time;
tm = localtime(&ot);
if (!tm)
return;
otm = *tm;
tm = localtime(&t);
if (!tm)
return;
cd->time = t;
if (cd->on_change)
cd->on_change(g);
if (otm.tm_mon != tm->tm_mon || otm.tm_year != tm->tm_year)
gadget_redraw(g);
else
{
win_paint();
gadget_clip(g, 0, 0, g->rect.w, g->rect.h, 0, 0);
cal_redraw_day(g, g->form->wd, ot);
cal_redraw_day(g, g->form->wd, t);
win_end_paint();
}
}
time_t cal_get_time(struct gadget *g)
{
return get_cal_data(g)->time;
}
static void sig_alrm(int nr)
{
struct tm *tm;
time_t t;
char str[16];
if (form_get_focus(form) != tod && !time_chg)
{
t = time(NULL);
tm = localtime(&t);
sprintf(str, "%i:%02i:%02i", (int)tm->tm_hour, (int)tm->tm_min, (int)tm->tm_sec);
input_set_text(tod, str);
time_chg = 0;
}
win_signal(SIGALRM, sig_alrm);
alarm(1);
}
static void tod_on_chg(struct gadget *g)
{
time_chg = 1;
}
static int update_hw(void)
{
pid_t pid;
int st;
pid = _newtaskl(HWCLOCK, HWCLOCK, "w", NULL);
if (pid < 0)
return -1;
while (wait(&st) != pid);
if (WEXITSTATUS(st))
{
errno = WEXITSTATUS(st);
return -1;
}
if (WTERMSIG(st))
{
errno = EINTR;
return -1;
}
return 0;
}
static void set_time(void)
{
struct tm tm;
time_t t;
char *p;
t = cal_get_time(cal);
tm = *localtime(&t);
tm.tm_hour = strtoul(tod->text, &p, 10);
if (*p != ':')
goto fail;
tm.tm_min = strtoul(p + 1, &p, 10);
if (*p != ':')
goto fail;
tm.tm_sec = strtoul(p + 1, &p, 10);
if (*p)
goto fail;
t = mktime(&tm);
if (stime(&t))
{
msgbox_perror(form, "Error", "Cannot set time", errno);
return;
}
if (msgbox_ask(form, "Save", "Software clock has been updated.\n\n"
"Do you want to write the time to the\n"
"hardware clock?") == MSGBOX_YES &&
update_hw())
msgbox_perror(form, "Error", "Cannot set hardware clock", errno);
exit(0);
fail:
msgbox(form, "Error", "Invalid time specification.");
}
int main()
{
struct win_rect cfr;
struct gadget *cancel;
struct gadget *ok;
struct gadget *cf;
if (win_attach())
err(255, NULL);
form = form_load("/lib/forms/pref.time.frm");
form_on_close(form, on_close);
cancel = gadget_find(form, "cancel");
ok = gadget_find(form, "ok");
cf = gadget_find(form, "calframe");
tod = gadget_find(form, "input");
input_on_change(tod, tod_on_chg);
gadget_get_rect(cf, &cfr);
gadget_remove(cf);
if (geteuid())
{
button_set_text(ok, "Close");
gadget_remove(cancel);
}
cal = cal_creat(form, cfr.x, cfr.y);
gadget_focus(cal);
win_signal(SIGALRM, sig_alrm);
raise(SIGALRM);
if (form_wait(form) == 1 && !geteuid())
set_time();
return 0;
}
| 2.046875 | 2 |
2024-11-18T22:37:14.418290+00:00
| 2017-08-30T07:36:30 |
f9c2558822f5c8a2e2e95eeab92bab24d6535789
|
{
"blob_id": "f9c2558822f5c8a2e2e95eeab92bab24d6535789",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-30T07:36:30",
"content_id": "b9c6ec3fef29f2744660ff8d8558ea926c99e95f",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "f9183ee2638ea9246398864001e7e71cc6f9a4da",
"extension": "c",
"filename": "dom.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": 18330,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/json/dom.c",
"provenance": "stackv2-0107.json.gz:95887",
"repo_name": "skyformat99/Jsong",
"revision_date": "2017-08-30T07:36:30",
"revision_id": "be68a219d95a48c6b0d0a9e7c9930b8a9e16aeed",
"snapshot_id": "149f200e90f51e79a2809da9bb0ba4777bad9515",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skyformat99/Jsong/be68a219d95a48c6b0d0a9e7c9930b8a9e16aeed/json/dom.c",
"visit_date": "2021-01-21T13:26:31.698396"
}
|
stackv2
|
// =============================================================================
// <dom.c>
//
// Copyright Kristian Garnét.
// -----------------------------------------------------------------------------
#include <quantum/build.h>
#include <quantum/core.h>
#include <quantum/integer.h>
// -----------------------------------------------------------------------------
#define MEM_POOL_STATIC
#include "api/macros.h"
#include "api/dom.h"
#include "utils/misc.h"
// -----------------------------------------------------------------------------
// DOM tree traversal
// -----------------------------------------------------------------------------
// Compare key strings for equality if only length is known
#define json_key_cmp_name(a_kv, a_str, a_len) do\
{ \
bool pack = a_kv->ukey.tag & json_str_pack; \
json_ukey_t ukey = {.ptr = json_unpack (void*, a_kv->ukey)};\
\
if (unlikely (json_key_len (ukey.ikey) == a_len))\
{ \
const u8* buf; \
\
if (likely (pack)) buf = ukey.ikey->buf; \
else buf = ukey.key->buf; \
\
if (unlikely (json_str_equal (buf, a_str, a_len))) return (json_kv_t*)a_kv;\
} \
} while (0)
// -----------------------------------------------------------------------------
// Compare key strings for equality if hash is known
#define json_key_cmp_hash(a_kv, a_str, a_hash) do\
{ \
bool pack = a_kv->ukey.tag & json_str_pack; \
json_ukey_t ukey = {.ptr = json_unpack (void*, a_kv->ukey)};\
\
if (unlikely (ukey.ikey->hash == a_hash)) \
{ \
const u8* buf; \
\
if (likely (pack)) buf = ukey.ikey->buf; \
else buf = ukey.key->buf; \
\
if (unlikely (json_str_equal (buf, a_str, len))) return (json_kv_t*)a_kv;\
} \
} while (0)
// -----------------------------------------------------------------------------
// Lookup object property by name
inline json_kv_t* json_kv_find (const json_kv_t* kv, const u8* str, uint len)
{
while (kv != null)
{
json_key_cmp_name (kv, str, len);
kv = kv->next;
}
return null;
}
// -----------------------------------------------------------------------------
// Lookup object property by name in reverse order (backwards)
inline json_kv_t* json_kv_rfind (const json_kv_t* kv, const u8* str, uint len)
{
json_kv_t* prev;
if (unlikely (kv == null)) return null;
while (true)
{
json_key_cmp_name (kv, str, len);
prev = json_unbox (json_kv_t*, kv->box);
// Previous property value cannot be a property.
//
// If pointers are the same, then it means we have reached
// the beginning of an upper object and `prev->box.ptr` is
// actually the `obj->first` field of an upper object,
// and `prev` itself is an object.
if (unlikely (prev->box.ptr == kv)) return null;
kv = prev;
}
}
// -----------------------------------------------------------------------------
#if JSON(HASH_KEYS)
// -----------------------------------------------------------------------------
// Same as above, except do the lookup using the provided key hash value
inline json_kv_t* json_kv_find_hash (const json_kv_t* kv, const u8* str, uint hash)
{
uint len = json_hash_len (hash);
while (kv != null)
{
json_key_cmp_hash (kv, str, hash);
kv = kv->next;
}
return null;
}
// -----------------------------------------------------------------------------
// Same as above, but backwards
inline json_kv_t* json_kv_rfind_hash (const json_kv_t* kv, const u8* str, uint hash)
{
json_kv_t* prev;
if (unlikely (kv == null)) return null;
uint len = json_hash_len (hash);
while (true)
{
json_key_cmp_hash (kv, str, hash);
prev = json_unbox (json_kv_t*, kv->box);
if (unlikely (prev->box.ptr == kv)) return null;
kv = prev;
}
}
// -----------------------------------------------------------------------------
#endif // JSON(HASH_KEYS)
// -----------------------------------------------------------------------------
#undef json_key_cmp_name
#undef json_key_cmp_hash
// -----------------------------------------------------------------------------
// RFC 6901 JSON Pointer implementation
// -----------------------------------------------------------------------------
// Parse the JSON Pointer string. It cannot be null-terminated,
// so its length must be provided explicitly by the caller.
uint json_parse_pointer (const u8* str, uint len, u8* buf, json_key_t* keys, uint max)
{
if (unlikely (len == 0)) return 0;
uint num = 0;
const u8* s = str;
const u8* e = str + len;
const u8* p = buf;
u8* b = buf;
register uint c = *s++;
// URI-style syntax handling
if (unlikely (c == '#'))
{
// Empty location (root element)
if (unlikely (s == e)) return 0;
// Next character must begin the pointer element
if (unlikely ((c = *s++) != '/')) return UINT_MAX;
while (s != e)
{
c = *s++;
// JSON Pointer character sequence parsing template
#define json_parse_pointer_seq(u)\
/* Next pointer element start */ \
if (unlikely (c == '/')) \
{ \
if (unlikely (num == max)) return UINT_MAX;\
\
keys[num].buf = (u8*)p; \
keys[num].hash = json_hash_key (p, (size_t)(b - p));\
num++; \
\
*b++ = '\0'; \
p = b; \
\
continue; \
} \
/* Pointer escape sequence */ \
if (unlikely (c == '~')) \
{ \
if (unlikely (s == e)) return UINT_MAX;\
\
c = *s++; \
\
if (unlikely ((c | 1u) != '1')) return UINT_MAX;\
\
c = (c == '0') ? '~' : '/'; \
} \
/* URI percent-encoded sequence */\
else if (u && (c == '%')) \
{ \
if (unlikely ((size_t)(e - s) < 2u)) return UINT_MAX;\
\
uint xh = chr_xdig_to_int (s[0]);\
uint xl = chr_xdig_to_int (s[1]);\
\
if (unlikely ((xh | xl) > 0xFu)) return UINT_MAX;\
\
c = (xh << 4) | xl;\
s += 2;\
} \
\
*b++ = c
// Parse and handle URI percent-encoded sequences
json_parse_pointer_seq (true);
}
}
// Default pointer syntax
else
{
if (unlikely (c != '/')) return UINT_MAX;
while (s != e)
{
c = *s++;
// Parse without URI percent-encoded sequences recognition
json_parse_pointer_seq (false);
}
}
// Handle the last pointer element
if (unlikely (num == max)) return UINT_MAX;
*b = '\0';
keys[num].buf = (u8*)p;
keys[num].hash = json_hash_key (p, (size_t)(b - p));
return num + 1u;
#undef json_parse_pointer_seq
}
// -----------------------------------------------------------------------------
// Query the DOM tree using the parsed JSON Pointer
json_node_t json_pointer (json_node_t node, const json_key_t* keys, uint num)
{
// Number of elements to traverse
const json_key_t* end = keys + num;
// Get the collection type from the element node
json_coll_type_t coll = node.tag & json_coll_type;
// Get the element itself
json_elmnt_t* elmnt = json_unbox (json_elmnt_t*, node);
while (keys < end)
{
// Get the element value.
// It must be an object or an array.
json_type_t type = json_get_type (elmnt);
// Lookup the property by hash if it's an object
if (likely (type == json_val_obj))
{
#if JSON(HASH_KEYS)
elmnt = (json_elmnt_t*)json_kv_find_hash (elmnt->val.obj->first
, keys->buf, keys->hash);
#else
elmnt = (json_elmnt_t*)json_kv_find (elmnt->val.obj->first
, keys->buf, keys->hash);
#endif
if (unlikely (elmnt == null)) return json_node_null;
coll = json_coll_obj;
}
// Lookup the array item by its index
else if (likely (type == json_val_arr))
{
int_parse_t parse;
uint idx = int_uint_parse (keys->buf, json_key_len (keys), &parse);
if (unlikely (parse.err != int_parse_ok))
{
// `-` reference (next item after the last array element)
// is not handled
return json_node_null;
}
elmnt = (json_elmnt_t*)json_arr_get (elmnt->val.arr, idx);
if (unlikely (elmnt == null)) return json_node_null;
coll = json_coll_arr;
}
// The element node value is neither an object nor an array.
// There is nothing left to look up.
else return json_node_null;
keys++;
}
// Pack whatever element node we have reached and return it
node.ptr = elmnt;
node.tag |= coll;
return node;
}
// -----------------------------------------------------------------------------
// Query the DOM tree using the simple JSON Query syntax.
// JSON Query doesn't require any pre-parsing to use it.
json_node_t json_query (json_node_t node, const u8* str, uint len)
{
if (unlikely (len == 0)) return node;
json_coll_type_t coll = node.tag & json_coll_type;
json_elmnt_t* elmnt = json_unbox (json_elmnt_t*, node);
const u8* s = str;
const u8* e = str + len;
register uint c = *s++;
if (unlikely (c != '/')) return json_node_null;
const u8* p = s;
// Get the key strings and query the DOM on the fly
while (s != e)
{
if (unlikely (*s++ == '/'))
{
#define json_query_elmnt()\
json_type_t type = json_get_type (elmnt);\
\
if (likely (type == json_val_obj))\
{ \
elmnt = (json_elmnt_t*)json_kv_find (elmnt->val.obj->first\
, p, (size_t)(s - p)); \
\
if (unlikely (elmnt == null)) return json_node_null;\
\
coll = json_coll_obj; \
} \
else if (likely (type == json_val_arr))\
{ \
elmnt = (json_elmnt_t*)json_arr_get (elmnt->val.arr\
, int_uint_from_str (p, (size_t)(s - p)));\
\
if (unlikely (elmnt == null)) return json_node_null;\
\
coll = json_coll_arr; \
} \
else return json_node_null
json_query_elmnt();
p = s;
}
}
// Query the last key
json_query_elmnt();
node.ptr = elmnt;
node.tag |= coll;
return node;
}
// -----------------------------------------------------------------------------
// Factory
// -----------------------------------------------------------------------------
#if (MEM_POOL_ALIGNMENT == 0) && (INTPTR_BIT <= 64)
#define MEM_POOL_ALIGNMENT 8u
#endif
#include <quantum/memory/pool.c>
// -----------------------------------------------------------------------------
mem_pool_t* json_pool_create (void)
{
return mem_pool_create (JSON_POOL_SIZE, JSON_POOL_MAX, sizeof (json_kv_t));
}
void json_pool_destroy (mem_pool_t* pool)
{
mem_pool_destroy (pool);
}
// -----------------------------------------------------------------------------
json_elmnt_t* json_new_root (mem_pool_t* pool)
{
json_elmnt_t* elmnt = mem_pool_alloc (pool, sizeof (json_elmnt_t));
if (unlikely (elmnt == null)) return null;
elmnt->box.ptr = null;
elmnt->val.ptr = null;
return elmnt;
}
// -----------------------------------------------------------------------------
json_obj_t* json_new_obj (mem_pool_t* pool)
{
json_obj_t* obj = mem_pool_alloc (pool, sizeof (json_obj_t*));
if (unlikely (obj == null)) return null;
obj->first = null;
return obj;
}
// -----------------------------------------------------------------------------
json_arr_t* json_new_arr (mem_pool_t* pool)
{
json_arr_t* arr = mem_pool_alloc (pool, sizeof (json_arr_t*));
if (unlikely (arr == null)) return null;
arr->items = (json_item_t*)(arr + 1);
arr->size = 0;
arr->num = 0;
return arr;
}
// -----------------------------------------------------------------------------
json_kv_t* json_new_kv (mem_pool_t* pool)
{
json_kv_t* kv = mem_pool_alloc (pool, sizeof (json_kv_t));
if (unlikely (kv == null)) return null;
kv->val.ptr = null;
return kv;
}
// -----------------------------------------------------------------------------
json_key_t* json_new_key (const u8* str, uint len, mem_pool_t* pool)
{
json_key_t* key = mem_pool_alloc (pool, sizeof (json_key_t));
if (unlikely (key == null)) return null;
key->buf = (u8*)str;
key->hash = json_hash_key (str, len);
return key;
}
json_ikey_t* json_new_ikey (const u8* str, uint len, mem_pool_t* pool)
{
json_ikey_t* ikey = mem_pool_alloc (pool, sizeof (json_ikey_t) + len);
if (unlikely (ikey == null)) return null;
ikey->hash = json_hash_key (str, len);
json_str_copy (ikey->buf, str, len);
return ikey;
}
// -----------------------------------------------------------------------------
json_str_t* json_new_str (const u8* buf, uint len, mem_pool_t* pool)
{
json_str_t* str = mem_pool_alloc (pool, sizeof (json_str_t));
if (unlikely (str == null)) return null;
str->buf = (u8*)buf;
str->len = len;
return str;
}
json_istr_t* json_new_istr (const u8* buf, uint len, mem_pool_t* pool)
{
json_istr_t* str = mem_pool_alloc (pool, sizeof (json_istr_t) + len);
if (unlikely (str == null)) return null;
str->len = len;
str_copy (str->buf, buf, len);
return str;
}
// -----------------------------------------------------------------------------
json_num_str_t* json_new_num_str (const u8* buf, uint len, mem_pool_t* pool)
{
json_num_str_t* str = mem_pool_alloc (pool, sizeof (json_num_str_t));
if (unlikely (str == null)) return null;
obj_zero (str);
str->meta.len_number = len;
str->buf = (u8*)buf;
return str;
}
json_num_istr_t* json_new_num_istr (const u8* buf, uint len, mem_pool_t* pool)
{
json_num_istr_t* str = mem_pool_alloc (pool, sizeof (json_num_istr_t) + len);
if (unlikely (str == null)) return null;
str->meta.len_number = len;
str_copy (str->buf, buf, len);
return str;
}
// -----------------------------------------------------------------------------
json_num_big_t* json_new_num_big (mem_pool_t* pool)
{
json_num_big_t* big = mem_pool_alloc (pool, sizeof (json_num_big_t));
if (unlikely (big == null)) return null;
obj_zero (big);
return big;
}
// -----------------------------------------------------------------------------
// DOM tree manipulation
// -----------------------------------------------------------------------------
// Array manipulation
// -----------------------------------------------------------------------------
json_item_t* json_arr_set (json_arr_t* arr, uint idx, mem_pool_t* pool)
{
uint num = arr->num;
if (likely (idx < num)) return arr->items + idx;
uint size = arr->size;
uint isz = (idx + 1u) - num;
if (likely (idx < size))
{
arr->num = idx + 1u;
json_arr_init (arr, num, isz);
return arr->items + idx;
}
uint nsz = (idx + 1u) + (size >> 1);
json_item_t* items = mem_pool_realloc (pool, arr->items
, arr_size (items, size), arr_size (items, nsz));
if (unlikely (items == null)) return null;
arr->items = items;
arr->size = nsz;
arr->num = idx + 1u;
json_arr_init (arr, num, isz);
return items + idx;
}
// -----------------------------------------------------------------------------
json_item_t* json_arr_add (json_arr_t* arr, uint num, mem_pool_t* pool)
{
uint size = arr->size;
uint n = arr->num;
if (likely ((n + num) <= size))
{
arr->num = n + num;
json_arr_init (arr, n, num);
return arr->items + n;
}
uint nsz = (n + num) + (size >> 1);
json_item_t* items = mem_pool_realloc (pool, arr->items
, arr_size (items, size), arr_size (items, nsz));
if (unlikely (items == null)) return null;
arr->items = items;
arr->size = nsz;
arr->num = n + num;
json_arr_init (arr, n, num);
return items + n;
}
// -----------------------------------------------------------------------------
bool json_arr_resize (json_arr_t* arr, uint num, bool soft, mem_pool_t* pool)
{
uint n = arr->num;
// Shrunk
if (unlikely (num < n))
{
if (unlikely (!soft))
{
json_item_t* items = mem_pool_realloc (pool, arr->items
, arr_size (items, arr->size), arr_size (items, num));
if (unlikely (items == null)) return false;
arr->items = items;
}
arr->num = num;
return true;
}
// Grow
else if (likely (num > n))
{
uint size = arr->size;
if (likely (num <= size))
{
arr->num = num;
json_arr_init (arr, n, num - n);
return true;
}
json_item_t* items = mem_pool_realloc (pool, arr->items
, arr_size (items, size), arr_size (items, num));
if (unlikely (items == null)) return false;
arr->items = items;
arr->size = num;
arr->num = num;
json_arr_init (arr, n, num - n);
}
return true;
}
// -----------------------------------------------------------------------------
void json_arr_remove (json_arr_t* arr, uint idx, uint num, bool soft)
{
uint n = arr->num;
if (likely ((idx + num) >= n))
{
arr->num = (idx < n) ? idx : n;
return;
}
if (likely (soft))
{
json_arr_init (arr, idx, num);
}
else
{
arr->num -= num;
mem_move (arr->items + idx, arr->items + idx + num
, arr_size (arr->items, n - (idx + num)));
}
}
| 2.359375 | 2 |
2024-11-18T22:37:14.661134+00:00
| 2020-09-01T07:41:06 |
f490e57dff6cd58ff08d94028b8c1756f8475484
|
{
"blob_id": "f490e57dff6cd58ff08d94028b8c1756f8475484",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-01T07:41:06",
"content_id": "613c531541dc80a8706347cb1966a71e43a72c58",
"detected_licenses": [
"MIT"
],
"directory_id": "0b5440b3d2f37a13c63bbf20d199b8e7f70e20d8",
"extension": "c",
"filename": "bigint.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 291088161,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12630,
"license": "MIT",
"license_type": "permissive",
"path": "/bigint.c",
"provenance": "stackv2-0107.json.gz:96272",
"repo_name": "gonzus/bigint",
"revision_date": "2020-09-01T07:41:06",
"revision_id": "752a7889b262701d248bbf66b414add78dfed151",
"snapshot_id": "9a9e4eafb7972b21f16d2d3d95bd97527a3e410f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gonzus/bigint/752a7889b262701d248bbf66b414add78dfed151/bigint.c",
"visit_date": "2022-12-13T03:52:30.545404"
}
|
stackv2
|
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "bigint.h"
#define DEBUG 0
#define SHOW 0
#if BIGINT_LIMB_BITS == 32
#define BIGINT_LIMB_BASE (((bigint_larger_t)UINT32_MAX)+1)
#define BIGINT_LIMB_FMT PRIu32
#define BIGINT_LARGER_FMT PRIu64
#endif
#if BIGINT_LIMB_BITS == 16
#define BIGINT_LIMB_BASE (((bigint_larger_t)UINT16_MAX)+1)
#define BIGINT_LIMB_FMT PRIu16
#define BIGINT_LARGER_FMT PRIu32
#endif
#if BIGINT_LIMB_BITS == 8
#define BIGINT_LIMB_BASE (((bigint_larger_t)UINT8_MAX)+1)
#define BIGINT_LIMB_FMT PRIu8
#define BIGINT_LARGER_FMT PRIu16
#endif
#if 0
// set an arbitrary base, to prove it works with weird sizes
// NOTE: this has a HUGE negative impact in performance!!!
#ifdef BIGINT_LIMB_BASE
#undef BIGINT_LIMB_BASE
#endif
#define BIGINT_LIMB_BASE ((bigint_larger_t)10)
#endif
#define SET_DIGIT(b, p, value, base) \
do { \
if (b->cap <= p) { enlarge(b, p); } \
b->lmb[p] = value % base; \
value /= base; \
} while (0)
static void enlarge(bigint* b, size_t p);
static void bigint_ass_base(bigint* b, unsigned long long value, bigint_larger_t base);
static void bigint_add_base(const bigint* b, const bigint* n, bigint* t, bigint_larger_t base);
static void bigint_sub_base(const bigint* l, const bigint* r, bigint* a, bigint_larger_t base);
static void bigint_mul_base(const bigint* b, const bigint* n, bigint* t, bigint_larger_t base);
#if defined(SHOW) && SHOW > 0
static void show(const char* msg, const bigint* b) {
if (msg && msg[0] != '\0') {
printf("%s | ", msg);
}
printf("size %u [", b->pos);
for (int first = 1, j = b->pos - 1; j >= 0; first = 0, --j) {
printf("%s%"BIGINT_LIMB_FMT, first ? "" : ":", b->lmb[j]);
}
printf("]\n");
fflush(stdout);
(void) msg;
(void) b;
}
#endif
bigint* bigint_create(void) {
bigint* b = (bigint*) malloc(sizeof(bigint));
memset(b, 0, sizeof(bigint));
#if defined(DEBUG) && (DEBUG > 0)
printf("CREATE %p\n", b);
#endif
return b;
}
bigint* bigint_clone(bigint* o) {
bigint* b = bigint_create();
b->neg = o->neg;
b->pos = o->pos;
b->cap = o->cap;
b->lmb = realloc(0, b->cap * sizeof(bigint_limb_t));
for (uint64_t j = 0; j < o->pos; ++j) {
b->lmb[j] = o->lmb[j];
}
memset(b->lmb + b->pos, 0, (b->cap - b->pos) * sizeof(bigint_limb_t));
return b;
}
void bigint_destroy(bigint* b) {
#if defined(DEBUG) && (DEBUG > 0)
printf("DESTROY %p\n", b);
#endif
if (b->lmb) {
free((void*) b->lmb);
b->lmb = 0;
}
free((void*) b);
b = 0;
}
bigint* bigint_clear(bigint* b) {
memset(b->lmb, 0, b->pos * sizeof(bigint_limb_t));
b->neg = 0;
b->pos = 0;
#if defined(DEBUG) && (DEBUG > 0)
printf("CLEAR %p\n", b);
#endif
return b;
}
int bigint_is_zero(const bigint* b) {
return b->pos == 0 || (b->pos == 1 && b->lmb[0] == 0);
}
int bigint_is_one(const bigint* b) {
return b->pos == 1 && b->lmb[0] == 1 && !b->neg;
}
static int bigint_cmp_abs(const bigint* a, const bigint* b) {
if (a->pos > b->pos) {
// a has more digits than b
return +1;
}
if (a->pos < b->pos) {
// a has fewer digits than b
return -1;
}
// a and b have the same amount of digits
for (int j = a->pos - 1; j >= 0; --j) {
if (a->lmb[j] > b->lmb[j]) {
// a's digit > b's digit
return +1;
}
if (a->lmb[j] < b->lmb[j]) {
// a's digit < b's digit
return -1;
}
}
// they are the same!
return 0;
}
int bigint_compare(const bigint* a, const bigint* b) {
if (!a->neg && b->neg) {
// a > 0 and b < 0
return +1;
}
if (a->neg && !b->neg) {
// a < 0 and b > 0
return -1;
}
// a and b have the same sign
int cmp = bigint_cmp_abs(a, b);
return a->neg ? -cmp : +cmp;
}
bigint* bigint_assign_integer(bigint* b, long long value) {
#if defined(DEBUG) && (DEBUG > 0)
printf("Assigning integer [%lld]\n", value);
#endif
uint8_t n = 0;
unsigned long long v = 0;
if (value >= 0) {
v = value;
} else {
v = -value;
n = 1;
}
bigint_ass_base(b, v, BIGINT_LIMB_BASE);
b->neg = n;
return b;
}
bigint* bigint_assign_string(bigint* b, const char* value) {
enum {
STATE_INIT,
STATE_DIGIT,
};
#if defined(DEBUG) && (DEBUG > 0)
printf("Assigning string [%s]\n", value);
#endif
int state = STATE_INIT;
int neg = 0;
bigint_clear(b);
bigint* m = bigint_create();
bigint_assign_integer(m, 10);
bigint* d = bigint_create();
bigint* t = bigint_create();
uint32_t l = strlen(value);
for (uint32_t j = 0; j < l; ++j) {
uint8_t digit = UINT8_MAX;
if (isspace(value[j])) {
if (state == STATE_INIT) {
continue;
} else {
break;
}
} else if (value[j] == '+') {
if (state == STATE_INIT) {
state = STATE_DIGIT;
continue;
} else {
break;
}
} else if (value[j] == '-') {
if (state == STATE_INIT) {
state = STATE_DIGIT;
neg = 1;
continue;
} else {
break;
}
} else if (isdigit(value[j])) {
if (state == STATE_INIT || state == STATE_DIGIT) {
state = STATE_DIGIT;
digit = value[j] - '0';
} else {
break;
}
}
assert(digit != UINT8_MAX); // could not read a valid digit
bigint_assign_integer(d, digit);
// show("DIGIT", d);
bigint_mul_base(b, m, t, BIGINT_LIMB_BASE);
// show("AFTER MUL", t);
bigint_add_base(t, d, b, BIGINT_LIMB_BASE);
// show("AFTER ADD", b);
}
assert(state == STATE_DIGIT); // could not read any digit
b->neg = neg;
bigint_destroy(t);
bigint_destroy(d);
bigint_destroy(m);
return b;
}
bigint* bigint_assign_bigint(bigint* b, const bigint* n) {
#if defined(DEBUG) && (DEBUG > 0)
bigint_print("Assigning bigint ", n, stdout, 1);
#endif
bigint_clear(b);
b->neg = n->neg;
while (b->pos < n->pos) {
bigint_limb_t t = n->lmb[b->pos];
SET_DIGIT(b, b->pos, t, BIGINT_LIMB_BASE);
++b->pos;
}
return b;
}
char* bigint_format(const bigint* b, char* buf) {
// show("Formatting", b);
bigint* c = bigint_create();
bigint* m = bigint_create();
bigint_ass_base(m, BIGINT_LIMB_BASE, 10);
// show("USING BASE", m);
bigint* d = bigint_create();
bigint* t = bigint_create();
for (int j = b->pos - 1; j >= 0; --j) {
bigint_assign_integer(d, b->lmb[j]);
// show("DIGIT", d);
bigint_mul_base(c, m, t, 10);
// show("AFTER MUL", c);
bigint_add_base(t, d, c, 10);
// show("AFTER ADD", c);
}
bigint_destroy(t);
bigint_destroy(d);
bigint_destroy(m);
int p = 0;
int e = 1;
if (b->neg) {
buf[p++] = '-';
}
for (int j = c->pos - 1; j >= 0; --j) {
buf[p++] = c->lmb[j] + '0';
e = 0;
}
if (e) {
buf[p++] = '0';
e = 0;
}
buf[p] = '\0';
bigint_destroy(c);
// printf("FORMATTED [%s]\n", buf);
return buf;
}
void bigint_print(const char* msg, const bigint* b, FILE* stream, int newline) {
// TODO: change this to use a buffer
char buf[1000];
bigint_format(b, buf);
if (msg && msg[0]) {
fprintf(stream, "%s", msg);
}
fprintf(stream, "%s", buf);
if (newline) {
fputc('\n', stream);
}
}
bigint* bigint_add(const bigint* l, const bigint* r, bigint* a) {
if (l->neg != r->neg) {
int cmp = bigint_cmp_abs(l, r);
if (cmp == 0) {
bigint_clear(a);
} else if (cmp > 0) {
bigint_sub_base(l, r, a, BIGINT_LIMB_BASE);
a->neg = l->neg;
} else {
bigint_sub_base(r, l, a, BIGINT_LIMB_BASE);
a->neg = r->neg;
}
} else {
bigint_add_base(l, r, a, BIGINT_LIMB_BASE);
a->neg = l->neg;
}
return a;
}
bigint* bigint_sub(const bigint* l, const bigint* r, bigint* a) {
if (l->neg != r->neg) {
bigint_add_base(l, r, a, BIGINT_LIMB_BASE);
a->neg = l->neg;
} else {
int cmp = bigint_cmp_abs(l, r);
if (cmp == 0) {
bigint_clear(a);
} else if (cmp > 0) {
bigint_sub_base(l, r, a, BIGINT_LIMB_BASE);
a->neg = l->neg;
} else {
bigint_sub_base(r, l, a, BIGINT_LIMB_BASE);
a->neg = !r->neg;
}
}
return a;
}
bigint* bigint_mul(const bigint* l, const bigint* r, bigint* a) {
uint8_t s = l->neg == r->neg ? 0 : 1;
bigint_mul_base(l, r, a, BIGINT_LIMB_BASE);
a->neg = s;
return a;
}
bigint_limb_t bigint_mod_integer(bigint* b, bigint_limb_t value) {
assert(!b->neg); // must be positive for now
bigint_larger_t mod = 0;
for (int j = b->pos - 1; j >= 0; --j) {
mod = (mod * BIGINT_LIMB_BASE + b->lmb[j]) % value;
}
return mod;
}
void bigint_factorial(bigint_limb_t n, bigint* b) {
bigint_ass_base(b, 1, BIGINT_LIMB_BASE);
if (n <= 1) {
return;
}
bigint* d = bigint_create();
bigint* t = bigint_clone(b);
bigint* l = b;
bigint* r = t;
for (bigint_limb_t x = 2; x <= n; ++x) {
bigint_ass_base(d, x, BIGINT_LIMB_BASE);
bigint_mul_base(l, d, r, BIGINT_LIMB_BASE);
bigint* z = l;
l = r;
r = z;
}
if (l != b) {
bigint_assign_bigint(b, t);
}
bigint_destroy(t);
bigint_destroy(d);
}
static void enlarge(bigint* b, size_t p) {
if (b->cap > p) {
return;
}
size_t size = b->cap ? 2*b->cap : 1;
while (size <= p) {
size *= 2;
}
#if defined(DEBUG) && (DEBUG > 0)
printf("GROW %p %u -> %zu\n", b, b->cap, size);
#endif
bigint_limb_t* limb = realloc(b->lmb, size * sizeof(bigint_limb_t));
memset(limb + b->cap, 0, (size - b->cap) * sizeof(bigint_limb_t));
b->lmb = limb;
b->cap = size;
}
static void bigint_ass_base(bigint* b, unsigned long long value, bigint_larger_t base) {
bigint_clear(b);
while (value > 0) {
SET_DIGIT(b, b->pos, value, base);
++b->pos;
}
}
static void bigint_add_base(const bigint* l, const bigint* r, bigint* a, bigint_larger_t base) {
bigint_clear(a);
bigint_larger_t overflow = 0;
uint64_t p = 0;
while (p < l->pos || p < r->pos) {
if (p < l->pos) {
overflow += l->lmb[p];
}
if (p < r->pos) {
overflow += r->lmb[p];
}
SET_DIGIT(a, p, overflow, base);
++p;
}
while (overflow) {
SET_DIGIT(a, p, overflow, base);
++p;
}
if (a->pos < p) {
a->pos = p;
}
}
static void bigint_sub_base(const bigint* l, const bigint* r, bigint* a, bigint_larger_t base) {
assert(l->pos > r->pos || (l->pos == r->pos && l->lmb[l->pos-1] >= r->lmb[r->pos-1]));
bigint_clear(a);
bigint_larger_t borrow = 0;
bigint_larger_t tally = 0;
uint64_t p = 0;
uint64_t t = 0;
while (p < l->pos) {
tally = borrow;
if (p < r->pos) {
tally += r->lmb[p];
}
borrow = 0;
if (tally <= l->lmb[p]) {
tally = l->lmb[p] - tally;
} else {
tally = l->lmb[p] + base - tally;
borrow = 1;
}
if (tally > 0) {
t = p;
}
SET_DIGIT(a, p, tally, base);
++p;
}
while (tally) {
if (tally > 0) {
t = p;
}
SET_DIGIT(a, p, tally, base);
++p;
}
a->pos = t+1;
}
static void bigint_mul_base(const bigint* l, const bigint* r, bigint* a, bigint_larger_t base) {
// show("MUL l", l);
// show("MUL r", r);
bigint_clear(a);
enlarge(a, l->pos + r->pos);
for (uint64_t p = 0; p < l->pos; ++p) {
bigint_larger_t total = 0;
uint64_t q;
for (q = 0; q < r->pos; ++q) {
total += (bigint_larger_t) a->lmb[p+q] + (bigint_larger_t) l->lmb[p] * (bigint_larger_t) r->lmb[q];
SET_DIGIT(a, p+q, total, base);
}
for (; total; ++q) {
SET_DIGIT(a, p+q, total, base);
}
if (a->pos < p+q) {
a->pos = p+q;
}
}
}
| 2.609375 | 3 |
2024-11-18T22:37:15.762691+00:00
| 2016-02-22T07:08:59 |
90880a216876bb75c895e99de4fe5965240e1d0b
|
{
"blob_id": "90880a216876bb75c895e99de4fe5965240e1d0b",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-22T07:09:05",
"content_id": "a905edc62f6d4d072690ad41f99b6e8f7b0546f9",
"detected_licenses": [
"MIT"
],
"directory_id": "8396198ddcc8f758d9ab78fe4fac68f4e6c3877e",
"extension": "c",
"filename": "node.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 50845243,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 947,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/node.c",
"provenance": "stackv2-0107.json.gz:96403",
"repo_name": "jagreene/haptiphone",
"revision_date": "2016-02-22T07:08:59",
"revision_id": "c8a7c6c2b4f085afbc9766df5dd236e90ed29ae8",
"snapshot_id": "1b498bcc908ffc0b289dd78f39bb639be140cdf2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jagreene/haptiphone/c8a7c6c2b4f085afbc9766df5dd236e90ed29ae8/lib/node.c",
"visit_date": "2021-01-10T10:31:06.561909"
}
|
stackv2
|
#include "node.h"
#include <stdlib.h>
node* new_node(uint8_t val, node* next){
node* new = (node*)malloc(sizeof(node));
new->val = val;
new->next = next;
new->isTerminal = false;
return new;
};
node* init_list(int length){
//make terminal node
node* tail = (node*)malloc(sizeof(node));
tail->val = 0;
tail->isTerminal = true;
node* head = tail;
//make the rest
int i = 0;
for(i=0; i<length-1; i++){
head = new_node(0, head);
}
return head;
};
node* add_node(uint8_t val, node* head){
head = new_node(val, head);
node* curr = head;
int count = 0
while (!curr->next->isTerminal){
curr = curr->next;
}
curr->isTerminal = true;
free(curr->next);
return head;
};
node* get_avg_diff(node* head){
int16_t total = 0;
int count = 0;
node* curr = head;
while (!curr->isTerminal){
count++;
total += curr->next->val - curr->val;
curr = curr->next;
}
return total/count;
}
| 3.53125 | 4 |
2024-11-18T22:37:17.006339+00:00
| 2016-01-20T09:05:11 |
6ead02b24ad22d5326c5e4c5f168cae9727e5fd8
|
{
"blob_id": "6ead02b24ad22d5326c5e4c5f168cae9727e5fd8",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-20T09:05:11",
"content_id": "4f9b247194151288a19fa748a5b23c24277cfeb3",
"detected_licenses": [
"MIT"
],
"directory_id": "5b0234980ba850b446c5b9a372adc07ee80e2faa",
"extension": "c",
"filename": "main_mod.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": 8045,
"license": "MIT",
"license_type": "permissive",
"path": "/mod/main_mod.c",
"provenance": "stackv2-0107.json.gz:96660",
"repo_name": "VictorTagayun/UniSP-firmware",
"revision_date": "2016-01-20T09:05:11",
"revision_id": "9be7e3a9c309e9c1a2440da228e2819e820e1af6",
"snapshot_id": "23e1553bcb31427a2d8dda558f8aa71f9daa7de4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/VictorTagayun/UniSP-firmware/9be7e3a9c309e9c1a2440da228e2819e820e1af6/mod/main_mod.c",
"visit_date": "2020-05-22T00:21:50.710332"
}
|
stackv2
|
/**
* @file main_mod.c
* @brief
* @author raiden00
* @date 2015-10-08
**/
/********************************************************************
* project: UniSP
* chip: STM32F334X8
* compiler: arm-none-eabi-gcc
*
********************************************************************/
#ifdef OUT_MODULE_MAIN_
#warning "Compile main_mod.c"
/*
+===================================================================+
| includes
+===================================================================+
*/
#include "mod/main_mod.h"
/*
+=============================================================================+
| local functions' declarations
+=============================================================================+
*/
static void system_init(void);
static void NVIC_init(void);
/*
+===================================================================+
| global variables
+===================================================================+
*/
volatile struct Button_buffer gButton_buff; //!< global button_buff
volatile struct UI_slave_status gUi_stat; //!< ui status @TODO wywalic do ui
int main(void){
system_init(); //!< system initialize, hal, etc
smps_struct_init(&gSmps_stat, &gSmps_sets, &gSmps_adc_val); //!<
ui_struct_init(&gUi_stat); //!<
smps_disable(&gSmps_stat); //!<
smps_settings_struct_reset(&gSmps_sets); //!<
// smps_inrush_protection_off(); //!< obsolete
// smps_const_current_mode(); //!< @TODO
// smps_const_voltage_mode(); //!< @TODO
/////// temporary sets for debug purpose
/// ustalic jakies defaultowe limity na init i walnac w smps_init
smps_write_overload_current(&gSmps_sets, SMPS_PRIM_CURRENT_MAX_F32 * SMPS_OVERLOAD_COEFF_F32); // for hardware limit
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 35.0);
smps_init(gSmps_sets, &gSmps_stat, &gSmps_pid_reg);
smps_enable(&gSmps_stat);
smps_start(gSmps_sets, &gSmps_stat, &gSmps_pid_reg);
smps_set_fan_duty(0.9);
uint8_t uc_state = 1;
/// Ui CODE \/
/* SPI1->CR2 |= SPI_CR2_RXNEIE; //!< Rx buffer not empty interrupt enable */
/* SPI_enable(SPI1); */
while(1){
if(gButton_buff.button0){
switch(uc_state){
case 1:
// smps_bridge_pwm_set_duty(0.1); //!<
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 40.0);
LED3_ODR &=~ LED3;
break;
case 2:
// smps_bridge_pwm_set_duty(0.2); //!<
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 50.0);
break;
case 3:
// smps_bridge_pwm_set_duty(0.3); //!<
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 60.0);
break;
case 4:
// smps_bridge_pwm_set_duty(0.4); //!<
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 70.0);
break;
case 5:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 80.0);
break;
case 6:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 90.0);
break;
case 7:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 100.0);
break;
case 8:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 110.0);
break;
case 9:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 112.0);
break;
case 10:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 115.0);
break;
case 11:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 117.0);
break;
case 12:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 120.0);
break;
case 13:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 125.0);
break;
case 14:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 130.0);
break;
case 15:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 135.0);
break;
case 16:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 140.0);
break;
case 17:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 145.0);
break;
default:
smps_set_out_voltage(&gSmps_sets, &gSmps_stat, 150.0);
uc_state = 0;
LED3_ODR |= LED3;
break;
}
uc_state+=1;
reset_button_buff(&gButton_buff, 255);
}
if(gSmps_stat.overcurrent){
smps_overload_routine(gSmps_sets, &gSmps_stat, &gSmps_pid_reg);
}
smps_temp_regulator(gSmps_adc_val); //!< temperature control
#define _TODO 1
#ifndef _TODO
if(gUi_stat.ui_call){
//if ui_call send ACK
/* SPI_sendString(SPI1, UI_ACK); */
/* SPI_enable(SPI1); */
//stop edm and smps actions
smps_stop(&gSmps_stat, &gSmps_pid_reg);
while(gUi_stat.ui_call){
ui_cmd_buffer = ui_readCommand(ui_cmd_buffer); //!< read cmd from UI inerface as str
ui_handler(&ui_cmd_temp, ui_cmd_buffer); //!<
}
//after ui call - enable RXNEIE
/* SPI1->CR2 |= SPI_CR2_RXNEIE;//Rx buffer not empty interrupt enable */
/* SPI_enable(SPI1); */
}
/* if(gSmps_stat.enable){ */
/* smps_assert(); */
/* smps_init_and_loop(); */
/* } */
#endif
}
while(1);
}//end of main()
/*
+===================================================================+
| local functions
+===================================================================+
*/
/**
* @brief
* @details
**/
static void NVIC_init(void){
NVIC_SetPriorityGrouping(NVIC_PRIORITY_GROUP);
}
/**
* @brief System initialization.
* @details Call some functions.
**/
static void system_init(void){
pll_start(CRYSTAL, FREQUENCY);//!<
fpu_enable();
NVIC_init();
// systick_init(8000000ul); //!<
gpio_init();
gpio_pin_cfg_init();
hrtim_init(); //!<
timer6_wait_ms_init();
timer3_pwm_fan_init();
timer7_debouncing_init();
timer17_debug_time_ns_init();
// SPI1_init();
dma_init(); //!<
dac1_init(); //!<
// dac2_init(); //!<
comp2_init(); //!< -DAC1_CH2, +PA7, SMPS overload protection
// comp4_init(); //!<
// comp6_init(); //!<
adc1_init(); //!<
// adc2_init(); //!<
}
/**
* @brief
* @details
**/
inline void smps_overload_routine(const struct SMPS_settings smps_sets,
volatile struct SMPS_status* smps_stat,
volatile struct SMPS_PID_reg* smps_pid_reg){
smps_overload_reset(smps_stat);
timer6_wait_ms(400); //!< wait @TODO: define in config
smps_start(smps_sets, smps_stat, smps_pid_reg); //!< re-enable converter
timer6_wait_ms(200); //!< wait @TODO: define in config
if(smps_stat->overcurrent){ //!< if overcurrent still exist
SMPS_OVERLOAD_LED_ON; //!<
DISABLE_ALL_PWR_OUT;
while(1); //!< hard reset needed. Check what is wrong.
}
}
/**
* @brief
* @details
**/
void disable_all_pwr_out(volatile struct SMPS_status* smps_stat,
volatile struct SMPS_PID_reg* smps_pid_reg){
smps_stop(smps_stat, smps_pid_reg);
smps_disable(smps_stat);
}
/*******************************************************************
* END OF FILE
********************************************************************/
#endif /* OUT_MODULE_MAIN_ */
| 2.015625 | 2 |
2024-11-18T22:37:17.129989+00:00
| 2021-08-02T08:13:19 |
8ebcaff548480967f49714fe09794ea30c547e56
|
{
"blob_id": "8ebcaff548480967f49714fe09794ea30c547e56",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-02T08:13:19",
"content_id": "214a290472ab7ee998769d61df95694a3239e059",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "fd81afd43333803faafef56258ea3682bfebf6ae",
"extension": "c",
"filename": "dsec_ta_ih_privkey.c",
"fork_events_count": 0,
"gha_created_at": "2021-08-02T06:38:56",
"gha_event_created_at": "2021-08-02T08:16:18",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 391840688,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13339,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/trusted_application/src/dsec_ta_ih_privkey.c",
"provenance": "stackv2-0107.json.gz:96790",
"repo_name": "xuezhilei40308/libddssec",
"revision_date": "2021-08-02T08:13:19",
"revision_id": "fcab496edc560e63024a20a6dbce181521cd718a",
"snapshot_id": "f112028668c3de942d36b61d31770695fc1cd133",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xuezhilei40308/libddssec/fcab496edc560e63024a20a6dbce181521cd718a/trusted_application/src/dsec_ta_ih_privkey.c",
"visit_date": "2023-06-25T08:33:29.635491"
}
|
stackv2
|
/*
* DDS Security library
* Copyright (c) 2019, Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <dsec_ta_digest.h>
#include <dsec_ta_ih_privkey.h>
#include <dsec_ta_ih.h>
#include <dsec_ta_manage_object.h>
#include <dsec_errno.h>
#include <dsec_macros.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/entropy.h>
/*
* Callback function to generate random numbers for mbedTLS using TEE function.
*/
static int optee_ctr_drbg_random(void* p_rng,
unsigned char* output,
size_t output_len)
{
int result = 0;
/*
* Unused pseudo random generator context as we use TEE_GenerateRandom for
* the generation.
*/
DSEC_UNUSED(p_rng);
if (output == NULL) {
result = 1;
}
TEE_GenerateRandom(output, output_len);
return result;
}
/*
* This function checks the given inputs to make sure they are valid and can be
* used as inputs for privkey_sign(...)
*/
static TEE_Result privkey_sign_check_input(
const unsigned char* input,
size_t input_size,
const unsigned char* signature,
size_t signature_size)
{
TEE_Result result = 0;
const mbedtls_ecp_curve_info* curve_info = NULL;
if ((input != NULL) &&
(input_size != 0) &&
(signature != NULL) &&
(signature_size != 0)) {
curve_info =
mbedtls_ecp_curve_info_from_grp_id(MBEDTLS_ECP_DP_SECP256R1);
if (curve_info != NULL) {
unsigned int bitlength = curve_info->bit_size;
size_t max_signature_size = 2 * (bitlength / 8) + 9;
/*
* Make sure that the output buffer for the signature is big
* enough to contain the actual signature produced
*/
if (max_signature_size <= signature_size) {
result = TEE_SUCCESS;
} else {
EMSG("Signature buffer is too small.\n");
result = TEE_ERROR_SHORT_BUFFER;
}
} else {
EMSG("Could not retrieve information about ECP.\n");
result = TEE_ERROR_BAD_FORMAT;
}
} else {
EMSG("Input parameters are invalid (NULL or 0).\n");
result = TEE_ERROR_BAD_PARAMETERS;
}
return result;
}
/*
* Sign a given buffer using the private key.
* Note: This function is not making any checks on its input and assumes that
* all its arguments are valid. This function should be called after
* privkey_sign_check_input(...) and after making sure mbedtls_ecp_keypair*
* is not NULL.
*/
static TEE_Result privkey_sign(const mbedtls_ecp_keypair* ecp_privkey,
const unsigned char* input,
size_t input_size,
unsigned char* signature,
size_t* signature_size)
{
TEE_Result result = 0;
int result_mbedtls = 0;
mbedtls_ecdsa_context ecdsa_privkey;
/* Contains the SHA256 of the incoming buffer to be signed */
uint8_t data_sha256[DSEC_TA_SHA256_SIZE] = {0};
size_t output_signature_size = 0;
mbedtls_ecdsa_init(&ecdsa_privkey);
result_mbedtls = mbedtls_ecdsa_from_keypair(&ecdsa_privkey, ecp_privkey);
if (result_mbedtls == 0) {
int32_t result_sha256 = 0;
/* Generate a SHA256 of the message */
result_sha256 = dsec_ta_digest_sha256(data_sha256, input, input_size);
if (result_sha256 == DSEC_SUCCESS) {
result_mbedtls =
mbedtls_ecdsa_write_signature(&ecdsa_privkey,
MBEDTLS_MD_SHA256,
data_sha256,
DSEC_TA_SHA256_SIZE,
signature,
&output_signature_size,
optee_ctr_drbg_random,
NULL /* p_rng */);
if (result_mbedtls == 0) {
result = TEE_SUCCESS;
*signature_size = output_signature_size;
} else {
EMSG("Could not generate signature: 0x%x.\n", result_mbedtls);
result = TEE_ERROR_SECURITY;
}
} else {
EMSG("Could not generate sha256 for signature: %d.\n",
result_sha256);
result = TEE_ERROR_SECURITY;
}
mbedtls_ecdsa_free(&ecdsa_privkey);
} else {
EMSG("Could not extract private key: 0x%x.\n", result_mbedtls);
result = TEE_ERROR_BAD_FORMAT;
}
if (result != TEE_SUCCESS) {
*signature_size = 0;
}
return result;
}
/*
* Fill the mbedtls_pk_context with the given buffer and apply the password if
* any is specified. The private key is then checked against the public key
* stored in the certificate stored in the Identity Handle specified.
* Note: This function is not making any checks on its input and assumes that
* the given parameters are valid.
*/
static TEE_Result privkey_load_and_verify(struct identity_handle_t* ih,
const void* object_buffer,
size_t object_size,
const unsigned char* password,
size_t password_size)
{
TEE_Result result = 0;
int result_mbedtls = 0;
const mbedtls_x509_crt* cert = &(ih->cert_handle.cert);
mbedtls_pk_context* privkey = &(ih->privkey_handle.privkey);
ih->privkey_handle.initialized = false;
mbedtls_pk_init(privkey);
result_mbedtls = mbedtls_pk_parse_key(privkey,
object_buffer,
object_size,
password,
password_size);
if (result_mbedtls == 0) {
result_mbedtls = mbedtls_pk_check_pair(&(cert->pk), privkey);
if (result_mbedtls == 0) {
result = TEE_SUCCESS;
ih->privkey_handle.initialized = true;
} else {
EMSG("Check between public and private key failed 0x%x\n",
result_mbedtls);
result = TEE_ERROR_SECURITY;
mbedtls_pk_init(privkey);
}
} else {
EMSG("Could not parse private key 0x%x\n", result_mbedtls);
result = TEE_ERROR_BAD_FORMAT;
}
return result;
}
TEE_Result dsec_ta_ih_privkey_load(uint32_t parameters_type,
const TEE_Param parameters[3])
{
TEE_Result result = 0;
int32_t index_ih = 0;
struct identity_handle_t* ih = NULL;
uint32_t filename_size = 0;
void* object_buffer = NULL;
size_t object_size = 0;
const unsigned char* password = NULL;
size_t password_size = 0;
const uint32_t expected_types = TEE_PARAM_TYPES(TEE_PARAM_TYPE_VALUE_INPUT,
TEE_PARAM_TYPE_MEMREF_INPUT,
TEE_PARAM_TYPE_MEMREF_INPUT,
TEE_PARAM_TYPE_NONE);
if (parameters_type == expected_types) {
index_ih = (int32_t)parameters[0].value.a;
ih = dsec_ta_get_identity_handle(index_ih);
if (ih != NULL) {
if (ih->cert_handle.initialized &&
!ih->privkey_handle.initialized) {
password = parameters[2].memref.buffer;
password_size = parameters[2].memref.size;
filename_size = (uint32_t)parameters[1].memref.size;
if (filename_size < DSEC_MAX_NAME_LENGTH) {
result = dsec_ta_load_builtin(&object_buffer,
&object_size,
parameters[1].memref.buffer);
if (result == TEE_SUCCESS) {
result = privkey_load_and_verify(ih,
object_buffer,
object_size,
password,
password_size);
dsec_ta_unload_object_memory();
} else {
EMSG("Could not load the object.\n");
/* Return the value from the function that failed */
}
} else {
EMSG("Filename buffer is too big.\n");
result = TEE_ERROR_EXCESS_DATA;
}
} else {
EMSG("Identity handle element are not valid.\n");
result = TEE_ERROR_NO_DATA;
}
} else {
EMSG("Identity handle index is not valid %d.\n", index_ih);
result = TEE_ERROR_BAD_PARAMETERS;
}
} else {
EMSG("Bad parameters types: 0x%x.\n", parameters_type);
result = TEE_ERROR_BAD_PARAMETERS;
}
return result;
}
TEE_Result dsec_ta_ih_privkey_free(struct privkey_handle_t* privkey_handle)
{
TEE_Result result = 0;
if (privkey_handle != NULL) {
if (privkey_handle->initialized) {
mbedtls_pk_free(&(privkey_handle->privkey));
privkey_handle->initialized = false;
result = TEE_SUCCESS;
} else {
EMSG("Given element has no private key initialized.\n");
result = TEE_ERROR_NO_DATA;
}
} else {
EMSG("Pointer to structure privkey_handle is NULL.\n");
result = TEE_ERROR_BAD_PARAMETERS;
}
return result;
}
TEE_Result dsec_ta_ih_privkey_unload(uint32_t parameters_type,
const TEE_Param parameters[1])
{
TEE_Result result = 0;
int32_t index_ih = 0;
struct identity_handle_t* ih = NULL;
const uint32_t expected_types = TEE_PARAM_TYPES(TEE_PARAM_TYPE_VALUE_INPUT,
TEE_PARAM_TYPE_NONE,
TEE_PARAM_TYPE_NONE,
TEE_PARAM_TYPE_NONE);
if (parameters_type == expected_types) {
index_ih = (int32_t)parameters[0].value.a;
ih = dsec_ta_get_identity_handle(index_ih);
if (ih != NULL) {
result = dsec_ta_ih_privkey_free(&(ih->privkey_handle));
} else {
EMSG("Identity handle is invalid.\n");
result = TEE_ERROR_BAD_PARAMETERS;
}
} else {
EMSG("Bad parameters types: 0x%x\n", parameters_type);
result = TEE_ERROR_BAD_PARAMETERS;
}
return result;
}
TEE_Result dsec_ta_ih_privkey_sign(uint32_t parameters_type,
TEE_Param parameters[3])
{
TEE_Result result = 0;
uint32_t index_lih = 0;
struct identity_handle_t* lih = NULL;
const unsigned char* input = NULL;
size_t input_size = 0;
unsigned char* signature = NULL;
size_t signature_size = 0;
const uint32_t expected_types =
TEE_PARAM_TYPES(TEE_PARAM_TYPE_MEMREF_OUTPUT,
TEE_PARAM_TYPE_VALUE_INPUT,
TEE_PARAM_TYPE_MEMREF_INPUT,
TEE_PARAM_TYPE_NONE);
if (parameters_type == expected_types) {
index_lih = (int32_t)parameters[1].value.a;
lih = dsec_ta_get_identity_handle(index_lih);
if (lih != NULL) {
if (lih->privkey_handle.initialized) {
signature = parameters[0].memref.buffer;
signature_size = parameters[0].memref.size;
input = parameters[2].memref.buffer;
input_size = parameters[2].memref.size;
result = privkey_sign_check_input(input,
input_size,
signature,
signature_size);
if (result == TEE_SUCCESS) {
result = privkey_sign(lih->privkey_handle.privkey.pk_ctx,
input,
input_size,
signature,
&signature_size);
if (result == TEE_SUCCESS) {
parameters[0].memref.size = signature_size;
} else {
parameters[0].memref.size = 0;
}
/* Return result given by the subfunction*/
}
} else {
EMSG("Identity Handle does not contain a private key.\n");
result = TEE_ERROR_NO_DATA;
}
} else {
EMSG("Identity Handle is invalid.\n");
result = TEE_ERROR_BAD_PARAMETERS;
}
} else {
EMSG("Bad parameters types: 0x%x\n", parameters_type);
result = TEE_ERROR_BAD_PARAMETERS;
}
return result;
}
| 2.53125 | 3 |
2024-11-18T22:37:17.524757+00:00
| 2018-06-27T20:18:16 |
9b543b461d80b4a454c8fa2fb6abb01cf32e6ef7
|
{
"blob_id": "9b543b461d80b4a454c8fa2fb6abb01cf32e6ef7",
"branch_name": "refs/heads/main",
"committer_date": "2018-06-27T20:18:16",
"content_id": "bb8164a7395bc50ef124458602933dd7c8a3553e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3dc15ce99dac2c88c45beb20f1a670051f164dba",
"extension": "c",
"filename": "common.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 134432858,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 496,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/common.c",
"provenance": "stackv2-0107.json.gz:97177",
"repo_name": "zupzup/call-u-later",
"revision_date": "2018-06-27T20:18:16",
"revision_id": "3e8e2ebdc311edfed869dd93a94fe817e3c5f090",
"snapshot_id": "ef2421b7435427385edf848881f071219ddeda53",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zupzup/call-u-later/3e8e2ebdc311edfed869dd93a94fe817e3c5f090/common.c",
"visit_date": "2021-06-02T14:00:41.843792"
}
|
stackv2
|
#include "common.h"
#include <stdlib.h>
void remove_spaces(char *str) {
char *temp = str;
char *tmp = str;
while (*temp != '\0') {
*tmp = *temp++;
if (!isspace(*tmp)) tmp++;
}
*tmp = '\0';
}
char *method_to_text(enum METHOD m) {
if (m == GET) return "GET";
if (m == POST) return "POST";
if (m == PUT) return "PUT";
if (m == DELETE) return "DELETE";
if (m == OPTIONS) return "OPTIONS";
if (m == HEAD) return "HEAD";
return NULL;
}
| 2.359375 | 2 |
2024-11-18T22:37:17.959307+00:00
| 2017-05-13T02:14:27 |
6a532e1891a0c2c81233eeb41d617ddf309ce9ba
|
{
"blob_id": "6a532e1891a0c2c81233eeb41d617ddf309ce9ba",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-13T02:14:27",
"content_id": "c8326893d9daa4b0bbc3190010820f5b892c5867",
"detected_licenses": [
"MIT"
],
"directory_id": "ab82f7f4e58c4c083ddca1742e502456e2b821b1",
"extension": "c",
"filename": "lld.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 80882128,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 434,
"license": "MIT",
"license_type": "permissive",
"path": "/cpu/ops/lld.c",
"provenance": "stackv2-0107.json.gz:97436",
"repo_name": "georgemorgan/ns4",
"revision_date": "2017-05-13T02:14:27",
"revision_id": "c981a1d124b957a4a60fae2a441bf9d3e4a4ad34",
"snapshot_id": "c78f1e337de5db0fd9f51342c5a9429a9ff9be21",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/georgemorgan/ns4/c981a1d124b957a4a60fae2a441bf9d3e4a4ad34/cpu/ops/lld.c",
"visit_date": "2021-01-19T10:11:38.004031"
}
|
stackv2
|
/* lld.c - Load Linked Doubleword */
#include <vr4300i.h>
/*
LLD rt, offset( base )
load a doubleword from memory for an atomic read-modify-write.
*/
#define OPCODE 0x34
void ns4_vr4300i_lld(struct _vr4300i *vr) {
uint32_t base = (vr -> op >> 0x15) & 0x1f;
uint32_t rt = (vr -> op >> 0x10) & 0x1f;
uint32_t offset = (vr -> op >> 0x0) & 0xffff;
/* no imp */;
ns4_debug("lld 0x%x, %s, 0x%x", base, regstrs[rt], offset);
}
| 2.296875 | 2 |
2024-11-18T22:37:18.017387+00:00
| 2021-01-12T21:34:47 |
f1d31c41159e5dd83d268023a962ed9feb9ddac6
|
{
"blob_id": "f1d31c41159e5dd83d268023a962ed9feb9ddac6",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-12T21:34:47",
"content_id": "5c331c8b331ea0e254761916522268431d905393",
"detected_licenses": [
"MIT"
],
"directory_id": "ddeea3042153fc00f12288535ae3d3fc477e97a9",
"extension": "c",
"filename": "renderer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 329118317,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8328,
"license": "MIT",
"license_type": "permissive",
"path": "/src/renderer.c",
"provenance": "stackv2-0107.json.gz:97565",
"repo_name": "rolandbernard/pathtrace",
"revision_date": "2021-01-12T21:34:47",
"revision_id": "63d876d185da2373b45a5bd86818e49be974b4b2",
"snapshot_id": "c7831deb7a534b569af088061877811d5bdcbe71",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rolandbernard/pathtrace/63d876d185da2373b45a5bd86818e49be974b4b2/src/renderer.c",
"visit_date": "2023-02-13T13:04:19.511955"
}
|
stackv2
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include "vec.h"
#include "renderer.h"
#include "intersection.h"
void initRenderer(Renderer* renderer, int width, int height, float hview, float vview) {
renderer->width = width;
renderer->height = height;
renderer->horizontal_view = hview;
renderer->vertical_view = vview;
renderer->position = createVec3(0, 0, 0);
renderer->direction = createVec3(0, 0, -1);
renderer->up = createVec3(0, 1, 0);
renderer->void_color = createVec3(0, 0, 0);
renderer->pixel_samples = 128;
renderer->depth = 100;
renderer->specular_depth_cost = 20;
renderer->diffuse_depth_cost = 30;
renderer->transmition_depth_cost = 5;
renderer->buffer = (Color*)malloc(sizeof(Color) * width * height);
}
void freeRenderer(Renderer* renderer) {
free(renderer->buffer);
}
#include <assert.h>
static Color computeRadiance(Ray* ray, Scene* scene, Renderer* renderer, int depth) {
if (depth <= 0) {
return renderer->void_color;
} else {
Intersection intersection = {
.dist = INFINITY, // Maximum distance
};
if (testRayBvhIntersection(ray, scene->bvh, &intersection)) {
Vec3 vert0 = scene->vertecies[scene->vertex_indices[intersection.triangle_id][0]];
Vec3 vert1 = scene->vertecies[scene->vertex_indices[intersection.triangle_id][1]];
Vec3 vert2 = scene->vertecies[scene->vertex_indices[intersection.triangle_id][2]];
Vec3 vert = addVec3(
scaleVec3(vert0, 1 - intersection.u - intersection.v),
addVec3(
scaleVec3(vert1, intersection.u),
scaleVec3(vert2, intersection.v)
)
);
Vec3 norm0 = scene->normals[scene->normal_indices[intersection.triangle_id][0]];
Vec3 norm1 = scene->normals[scene->normal_indices[intersection.triangle_id][1]];
Vec3 norm2 = scene->normals[scene->normal_indices[intersection.triangle_id][2]];
Vec3 normal = addVec3(
scaleVec3(norm0, 1 - intersection.u - intersection.v),
addVec3(
scaleVec3(norm1, intersection.u),
scaleVec3(norm2, intersection.v)
)
);
bool outside = true;
if (dotVec3(normal, ray->direction) > 0) {
outside = false;
normal = scaleVec3(normal, -1);
}
int object_id = scene->object_ids[intersection.triangle_id];
MaterialProperties* material = &scene->objects[object_id].material;
Color c = material->emission_color;
if (depth - renderer->diffuse_depth_cost > 0) {
if (!isVec3Null(material->diffuse_color)) {
Ray new_ray = createRay(vert, randomVec3InDirection(normal, 1, 1));
Color color = computeRadiance(&new_ray, scene, renderer, depth - renderer->diffuse_depth_cost);
Color diffuse_color = mulVec3(color, material->diffuse_color);
c = addVec3(c, diffuse_color);
}
}
if (material->specular_sharpness != 0) {
if (material->transmitability > 0.0 && !isVec3Null(material->transmition_color)) {
float n1 = outside ? 1.0 : material->index_of_refraction;
float n2 = outside ? material->index_of_refraction : 1.0;
float cosO = -dotVec3(ray->direction, normal);
float r0 = (n1 - n2) / (n1 + n2);
r0 *= r0;
float refl = r0 + (1 - r0) * powf(1 - cosO, 5);
if (refl * (float)RAND_MAX > rand()) {
if (depth - renderer->specular_depth_cost > 0) {
Vec3 reflection = subVec3(ray->direction, scaleVec3(normal, 2 * dotVec3(ray->direction, normal)));
Vec3 direction = randomVec3InDirection(reflection, 1, material->specular_sharpness);
Ray new_ray = createRay(vert, direction);
Color color = computeRadiance(&new_ray, scene, renderer, depth - renderer->specular_depth_cost);
Color reflection_color = mulVec3(color, material->specular_color);
c = addVec3(c, reflection_color);
}
} else {
if (depth - renderer->transmition_depth_cost > 0) {
float angle = acosf(cosO);
float sinO = sinf(angle);
Vec3 transmition = addVec3(scaleVec3(ray->direction, n1 / n2), scaleVec3(normal, (cosO * n1 / n2 - sqrtf(1 - sinO * sinO))));
Vec3 direction = randomVec3InDirection(transmition, 1, material->specular_sharpness);
Ray new_ray = createRay(vert, direction);
Color color = computeRadiance(&new_ray, scene, renderer, depth - renderer->transmition_depth_cost);
Color reflection_color = scaleVec3(color, material->transmitability);
reflection_color = mulVec3(reflection_color, material->transmition_color);
c = addVec3(c, reflection_color);
}
}
} else if (depth - renderer->specular_depth_cost > 0) {
if (!isVec3Null(material->specular_color)) {
Vec3 reflection = subVec3(ray->direction, scaleVec3(normal, 2 * dotVec3(ray->direction, normal)));
Vec3 direction = randomVec3InDirection(reflection, 1, material->specular_sharpness);
Ray new_ray = createRay(vert, direction);
Color color = computeRadiance(&new_ray, scene, renderer, depth - renderer->specular_depth_cost);
Color specular_color = mulVec3(color, material->specular_color);
c = addVec3(c, specular_color);
}
}
}
return c;
} else {
return renderer->void_color;
}
}
}
void renderScene(Renderer* renderer, Scene* scene) {
Vec3 right = normalizeVec3(crossVec3(renderer->direction, renderer->up));
Vec3 down = normalizeVec3(crossVec3(renderer->direction, right));
Vec3 forward = normalizeVec3(renderer->direction);
float horizontal_scale = tanf(renderer->horizontal_view);
float vertical_scale = tanf(renderer->vertical_view);
#pragma omp parallel for schedule(dynamic, 1)
for (int y = 0; y < renderer->height; y++) {
for (int x = 0; x < renderer->width; x++) {
float scale_x = (x / (float)renderer->width - 0.5) * horizontal_scale;
float scale_y = (y / (float)renderer->height - 0.5) * vertical_scale;
Vec3 direction = normalizeVec3(addVec3(forward, addVec3(scaleVec3(right, scale_x), scaleVec3(down, scale_y))));
Color pixel_color = createVec3(0, 0, 0);
for (int s = 0; s < renderer->pixel_samples; s++) {
Vec3 actual_direction = randomVec3InDirection(direction, 1e-5, 100);
Ray ray = createRay(renderer->position, actual_direction);
Color color = computeRadiance(&ray, scene, renderer, renderer->depth);
pixel_color = addVec3(pixel_color, color);
}
pixel_color = scaleVec3(pixel_color, 1.0 / renderer->pixel_samples);
Color* pixel = renderer->buffer + (y * renderer->width + x);
*pixel = addVec3(*pixel, pixel_color);
}
}
}
void scaleBuffer(Renderer* renderer, float scale) {
for (int i = 0; i < renderer->height; i++) {
for (int j = 0; j < renderer->width; j++) {
Color* pixel = renderer->buffer + (i * renderer->width + j);
*pixel = scaleVec3(*pixel, scale);
}
}
}
void clearBuffer(Renderer* renderer) {
for (int i = 0; i < renderer->height; i++) {
for (int j = 0; j < renderer->width; j++) {
renderer->buffer[i * renderer->width + j] = createVec3(0, 0, 0);
}
}
}
| 2.203125 | 2 |
2024-11-18T22:37:18.150572+00:00
| 2023-08-30T23:07:48 |
7e44d094f432010e0c12165951208aa2367a7264
|
{
"blob_id": "7e44d094f432010e0c12165951208aa2367a7264",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-30T23:07:48",
"content_id": "4cfa661d882e5d0ede965417364455ece898bb24",
"detected_licenses": [
"PostgreSQL"
],
"directory_id": "8a51a96f61699f0318315ccc89cef39f6866f2b5",
"extension": "h",
"filename": "supportnodes.h",
"fork_events_count": 4807,
"gha_created_at": "2010-09-21T11:35:45",
"gha_event_created_at": "2023-09-09T13:59:15",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 927442,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16029,
"license": "PostgreSQL",
"license_type": "permissive",
"path": "/src/include/nodes/supportnodes.h",
"provenance": "stackv2-0107.json.gz:97696",
"repo_name": "postgres/postgres",
"revision_date": "2023-08-30T23:07:48",
"revision_id": "b5934bfd6071fed3a38cea0cfaa93afda63d9c0c",
"snapshot_id": "979febf2b41c00090d1256228f768f33e7ef3b6f",
"src_encoding": "UTF-8",
"star_events_count": 13691,
"url": "https://raw.githubusercontent.com/postgres/postgres/b5934bfd6071fed3a38cea0cfaa93afda63d9c0c/src/include/nodes/supportnodes.h",
"visit_date": "2023-08-31T00:10:01.373472"
}
|
stackv2
|
/*-------------------------------------------------------------------------
*
* supportnodes.h
* Definitions for planner support functions.
*
* This file defines the API for "planner support functions", which
* are SQL functions (normally written in C) that can be attached to
* another "target" function to give the system additional knowledge
* about the target function. All the current capabilities have to do
* with planning queries that use the target function, though it is
* possible that future extensions will add functionality to be invoked
* by the parser or executor.
*
* A support function must have the SQL signature
* supportfn(internal) returns internal
* The argument is a pointer to one of the Node types defined in this file.
* The result is usually also a Node pointer, though its type depends on
* which capability is being invoked. In all cases, a NULL pointer result
* (that's PG_RETURN_POINTER(NULL), not PG_RETURN_NULL()) indicates that
* the support function cannot do anything useful for the given request.
* Support functions must return a NULL pointer, not fail, if they do not
* recognize the request node type or cannot handle the given case; this
* allows for future extensions of the set of request cases.
*
*
* Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/include/nodes/supportnodes.h
*
*-------------------------------------------------------------------------
*/
#ifndef SUPPORTNODES_H
#define SUPPORTNODES_H
#include "nodes/plannodes.h"
struct PlannerInfo; /* avoid including pathnodes.h here */
struct IndexOptInfo;
struct SpecialJoinInfo;
struct WindowClause;
/*
* The Simplify request allows the support function to perform plan-time
* simplification of a call to its target function. For example, a varchar
* length coercion that does not decrease the allowed length of its argument
* could be replaced by a RelabelType node, or "x + 0" could be replaced by
* "x". This is invoked during the planner's constant-folding pass, so the
* function's arguments can be presumed already simplified.
*
* The planner's PlannerInfo "root" is typically not needed, but can be
* consulted if it's necessary to obtain info about Vars present in
* the given node tree. Beware that root could be NULL in some usages.
*
* "fcall" will be a FuncExpr invoking the support function's target
* function. (This is true even if the original parsetree node was an
* operator call; a FuncExpr is synthesized for this purpose.)
*
* The result should be a semantically-equivalent transformed node tree,
* or NULL if no simplification could be performed. Do *not* return or
* modify *fcall, as it isn't really a separately allocated Node. But
* it's okay to use fcall->args, or parts of it, in the result tree.
*/
typedef struct SupportRequestSimplify
{
NodeTag type;
struct PlannerInfo *root; /* Planner's infrastructure */
FuncExpr *fcall; /* Function call to be simplified */
} SupportRequestSimplify;
/*
* The Selectivity request allows the support function to provide a
* selectivity estimate for a function appearing at top level of a WHERE
* clause (so it applies only to functions returning boolean).
*
* The input arguments are the same as are supplied to operator restriction
* and join estimators, except that we unify those two APIs into just one
* request type. See clause_selectivity() for the details.
*
* If an estimate can be made, store it into the "selectivity" field and
* return the address of the SupportRequestSelectivity node; the estimate
* must be between 0 and 1 inclusive. Return NULL if no estimate can be
* made (in which case the planner will fall back to a default estimate,
* traditionally 1/3).
*
* If the target function is being used as the implementation of an operator,
* the support function will not be used for this purpose; the operator's
* restriction or join estimator is consulted instead.
*/
typedef struct SupportRequestSelectivity
{
NodeTag type;
/* Input fields: */
struct PlannerInfo *root; /* Planner's infrastructure */
Oid funcid; /* function we are inquiring about */
List *args; /* pre-simplified arguments to function */
Oid inputcollid; /* function's input collation */
bool is_join; /* is this a join or restriction case? */
int varRelid; /* if restriction, RTI of target relation */
JoinType jointype; /* if join, outer join type */
struct SpecialJoinInfo *sjinfo; /* if outer join, info about join */
/* Output fields: */
Selectivity selectivity; /* returned selectivity estimate */
} SupportRequestSelectivity;
/*
* The Cost request allows the support function to provide an execution
* cost estimate for its target function. The cost estimate can include
* both a one-time (query startup) component and a per-execution component.
* The estimate should *not* include the costs of evaluating the target
* function's arguments, only the target function itself.
*
* The "node" argument is normally the parse node that is invoking the
* target function. This is a FuncExpr in the simplest case, but it could
* also be an OpExpr, DistinctExpr, NullIfExpr, or WindowFunc, or possibly
* other cases in future. NULL is passed if the function cannot presume
* its arguments to be equivalent to what the calling node presents as
* arguments; that happens for, e.g., aggregate support functions and
* per-column comparison operators used by RowExprs.
*
* If an estimate can be made, store it into the cost fields and return the
* address of the SupportRequestCost node. Return NULL if no estimate can be
* made, in which case the planner will rely on the target function's procost
* field. (Note: while procost is automatically scaled by cpu_operator_cost,
* this is not the case for the outputs of the Cost request; the support
* function must scale its results appropriately on its own.)
*/
typedef struct SupportRequestCost
{
NodeTag type;
/* Input fields: */
struct PlannerInfo *root; /* Planner's infrastructure (could be NULL) */
Oid funcid; /* function we are inquiring about */
Node *node; /* parse node invoking function, or NULL */
/* Output fields: */
Cost startup; /* one-time cost */
Cost per_tuple; /* per-evaluation cost */
} SupportRequestCost;
/*
* The Rows request allows the support function to provide an output rowcount
* estimate for its target function (so it applies only to set-returning
* functions).
*
* The "node" argument is the parse node that is invoking the target function;
* currently this will always be a FuncExpr or OpExpr.
*
* If an estimate can be made, store it into the rows field and return the
* address of the SupportRequestRows node. Return NULL if no estimate can be
* made, in which case the planner will rely on the target function's prorows
* field.
*/
typedef struct SupportRequestRows
{
NodeTag type;
/* Input fields: */
struct PlannerInfo *root; /* Planner's infrastructure (could be NULL) */
Oid funcid; /* function we are inquiring about */
Node *node; /* parse node invoking function */
/* Output fields: */
double rows; /* number of rows expected to be returned */
} SupportRequestRows;
/*
* The IndexCondition request allows the support function to generate
* a directly-indexable condition based on a target function call that is
* not itself indexable. The target function call must appear at the top
* level of WHERE or JOIN/ON, so this applies only to functions returning
* boolean.
*
* The "node" argument is the parse node that is invoking the target function;
* currently this will always be a FuncExpr or OpExpr. The call is made
* only if at least one function argument matches an index column's variable
* or expression. "indexarg" identifies the matching argument (it's the
* argument's zero-based index in the node's args list).
*
* If the transformation is possible, return a List of directly-indexable
* condition expressions, else return NULL. (A List is used because it's
* sometimes useful to generate more than one indexable condition, such as
* when a LIKE with constant prefix gives rise to both >= and < conditions.)
*
* "Directly indexable" means that the condition must be directly executable
* by the index machinery. Typically this means that it is a binary OpExpr
* with the index column value on the left, a pseudo-constant on the right,
* and an operator that is in the index column's operator family. Other
* possibilities include RowCompareExpr, ScalarArrayOpExpr, and NullTest,
* depending on the index type; but those seem less likely to be useful for
* derived index conditions. "Pseudo-constant" means that the right-hand
* expression must not contain any volatile functions, nor any Vars of the
* table the index is for; use is_pseudo_constant_for_index() to check this.
* (Note: if the passed "node" is an OpExpr, the core planner already verified
* that the non-indexkey operand is pseudo-constant; but when the "node"
* is a FuncExpr, it does not check, since it doesn't know which of the
* function's arguments you might need to use in an index comparison value.)
*
* In many cases, an index condition can be generated but it is weaker than
* the function condition itself; for example, a LIKE with a constant prefix
* can produce an index range check based on the prefix, but we still need
* to execute the LIKE operator to verify the rest of the pattern. We say
* that such an index condition is "lossy". When returning an index condition,
* you should set the "lossy" request field to true if the condition is lossy,
* or false if it is an exact equivalent of the function's result. The core
* code will initialize that field to true, which is the common case.
*
* It is important to verify that the index operator family is the correct
* one for the condition you want to generate. Core support functions tend
* to use the known OID of a built-in opfamily for this, but extensions need
* to work harder, since their OIDs aren't fixed. A possibly workable
* answer for an index on an extension datatype is to verify the index AM's
* OID instead, and then assume that there's only one relevant opclass for
* your datatype so the opfamily must be the right one. Generating OpExpr
* nodes may also require knowing extension datatype OIDs (often you can
* find these out by applying exprType() to a function argument) and
* operator OIDs (which you can look up using get_opfamily_member).
*/
typedef struct SupportRequestIndexCondition
{
NodeTag type;
/* Input fields: */
struct PlannerInfo *root; /* Planner's infrastructure */
Oid funcid; /* function we are inquiring about */
Node *node; /* parse node invoking function */
int indexarg; /* index of function arg matching indexcol */
struct IndexOptInfo *index; /* planner's info about target index */
int indexcol; /* index of target index column (0-based) */
Oid opfamily; /* index column's operator family */
Oid indexcollation; /* index column's collation */
/* Output fields: */
bool lossy; /* set to false if index condition is an exact
* equivalent of the function call */
} SupportRequestIndexCondition;
/* ----------
* To support more efficient query execution of any monotonically increasing
* and/or monotonically decreasing window functions, we support calling the
* window function's prosupport function passing along this struct whenever
* the planner sees an OpExpr qual directly reference a window function in a
* subquery. When the planner encounters this, we populate this struct and
* pass it along to the window function's prosupport function so that it can
* evaluate if the given WindowFunc is;
*
* a) monotonically increasing, or
* b) monotonically decreasing, or
* c) both monotonically increasing and decreasing, or
* d) none of the above.
*
* A function that is monotonically increasing can never return a value that
* is lower than a value returned in a "previous call". A monotonically
* decreasing function can never return a value higher than a value returned
* in a previous call. A function that is both must return the same value
* each time.
*
* We define "previous call" to mean a previous call to the same WindowFunc
* struct in the same window partition.
*
* row_number() is an example of a monotonically increasing function. The
* return value will be reset back to 1 in each new partition. An example of
* a monotonically increasing and decreasing function is COUNT(*) OVER ().
* Since there is no ORDER BY clause in this example, all rows in the
* partition are peers and all rows within the partition will be within the
* frame bound. Likewise for COUNT(*) OVER(ORDER BY a ROWS BETWEEN UNBOUNDED
* PRECEDING AND UNBOUNDED FOLLOWING).
*
* COUNT(*) OVER (ORDER BY a ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
* is an example of a monotonically decreasing function.
*
* Implementations must only concern themselves with the given WindowFunc
* being monotonic in a single partition.
*
* Inputs:
* 'window_func' is the pointer to the window function being called.
*
* 'window_clause' pointer to the WindowClause data. Support functions can
* use this to check frame bounds, etc.
*
* Outputs:
* 'monotonic' the resulting MonotonicFunction value for the given input
* window function and window clause.
* ----------
*/
typedef struct SupportRequestWFuncMonotonic
{
NodeTag type;
/* Input fields: */
WindowFunc *window_func; /* Pointer to the window function data */
struct WindowClause *window_clause; /* Pointer to the window clause data */
/* Output fields: */
MonotonicFunction monotonic;
} SupportRequestWFuncMonotonic;
/*
* Some WindowFunc behavior might not be affected by certain variations in
* the WindowClause's frameOptions. For example, row_number() is coded in
* such a way that the frame options don't change the returned row number.
* nodeWindowAgg.c will have less work to do if the ROWS option is used
* instead of the RANGE option as no check needs to be done for peer rows.
* Since RANGE is included in the default frame options, window functions
* such as row_number() might want to change that to ROW.
*
* Here we allow a WindowFunc's support function to determine which, if
* anything, can be changed about the WindowClause which the WindowFunc
* belongs to. Currently only the frameOptions can be modified. However,
* we may want to allow more optimizations in the future.
*
* The support function is responsible for ensuring the optimized version of
* the frameOptions doesn't affect the result of the window function. The
* planner is responsible for only changing the frame options when all
* WindowFuncs using this particular WindowClause agree on what the optimized
* version of the frameOptions are. If a particular WindowFunc being used
* does not have a support function then the planner will not make any changes
* to the WindowClause's frameOptions.
*
* 'window_func' and 'window_clause' are set by the planner before calling the
* support function so that the support function has these fields available.
* These may be required in order to determine which optimizations are
* possible.
*
* 'frameOptions' is set by the planner to WindowClause.frameOptions. The
* support function must only adjust this if optimizations are possible for
* the given WindowFunc.
*/
typedef struct SupportRequestOptimizeWindowClause
{
NodeTag type;
/* Input fields: */
WindowFunc *window_func; /* Pointer to the window function data */
struct WindowClause *window_clause; /* Pointer to the window clause data */
/* Input/Output fields: */
int frameOptions; /* New frameOptions, or left untouched if no
* optimizations are possible. */
} SupportRequestOptimizeWindowClause;
#endif /* SUPPORTNODES_H */
| 2.015625 | 2 |
2024-11-18T22:37:18.311324+00:00
| 2018-09-24T14:32:23 |
8001a06741126d34d3fb55e478d665e4b4a59f7f
|
{
"blob_id": "8001a06741126d34d3fb55e478d665e4b4a59f7f",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-24T14:32:23",
"content_id": "c43b39092ec7a1225f7cc678b0e8235ef86aec21",
"detected_licenses": [
"MIT"
],
"directory_id": "5c7b38c896bad76c8b1f113a8c59860a0aa5f16a",
"extension": "h",
"filename": "strtrm.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 146443435,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 454,
"license": "MIT",
"license_type": "permissive",
"path": "/include/strtrm.h",
"provenance": "stackv2-0107.json.gz:97955",
"repo_name": "Chris-1101/boxecho",
"revision_date": "2018-09-24T14:32:23",
"revision_id": "a6ebe34a4dacae557e6b3d96db82cc74cceff973",
"snapshot_id": "9be2c2217e57970e9b4d9e8b0a4a4b30049de40a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Chris-1101/boxecho/a6ebe34a4dacae557e6b3d96db82cc74cceff973/include/strtrm.h",
"visit_date": "2020-03-27T10:45:46.712925"
}
|
stackv2
|
#ifndef TRIMCHAR_H
#define TRIMCHAR_H
char *strtrm(char *str, const char chr);
wchar_t *wcstrm(wchar_t *str, const wchar_t chr);
/* Trim Character From String
* --------------------------
* Trims the character specified in [chr]
* from the beginning and end of [str].
*
* Returns a pointer to a null-terminated substring of the
* original. Must be able to write to the original string.
* --------------------------
*/
#endif
| 2.046875 | 2 |
2024-11-18T22:37:18.643481+00:00
| 2020-06-16T12:44:30 |
9cb5d6cd70382e774e12a68d6a9416850d278013
|
{
"blob_id": "9cb5d6cd70382e774e12a68d6a9416850d278013",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-16T12:44:30",
"content_id": "2e9d6ba6d5ba91ea11c1c0336b7c2b1d4ad9b9db",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "642e256e68c6df2660cbc9e541d076dba6bae586",
"extension": "c",
"filename": "728-1_pav-6-2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 272171969,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4642,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/728-1_pav-6-2.c",
"provenance": "stackv2-0107.json.gz:98212",
"repo_name": "prmn9362/timp-728-1_pav",
"revision_date": "2020-06-16T12:44:30",
"revision_id": "06d5e734d41ad959d2f11e652fbedfe8e24cf9b7",
"snapshot_id": "9f21d1cc563efd36a93660bfd083f3110ef2d3d1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/prmn9362/timp-728-1_pav/06d5e734d41ad959d2f11e652fbedfe8e24cf9b7/728-1_pav-6-2.c",
"visit_date": "2022-10-23T09:29:16.458141"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct uzel
{
int data;
struct uzel *leviy;
struct uzel *praviy;
struct uzel *roditel;
} uzel;
typedef struct tree
{
struct uzel *golova;
} tree;
void init(tree *t)
{
t -> golova = NULL;
}
typedef struct Stack {
size_t size;
size_t max;
uzel **data;
} Stack;
Stack* add_Stack() {
Stack *tmp = (Stack*) malloc(sizeof(Stack));
tmp -> max = 7;
tmp -> size = 0;
tmp -> data = (uzel**) malloc(tmp->max * sizeof(uzel*));
return tmp;
}
void freee(Stack **s)
{
free((*s) -> data);
free(*s);
*s = NULL;
}
uzel *find(uzel *n, int value)
{
if(n == NULL)
{
return NULL;
}
if(value == n -> data)
{
return n;
}
if (value < n -> data)
{
return find(n -> leviy, value);
}
else
{
return find(n -> praviy, value);
}
}
uzel *add_Uzel(int value)
{
uzel *root = (uzel *)malloc(sizeof(uzel));
root -> data = value;
root -> leviy = root -> praviy = root -> roditel = NULL;
return root;
}
int insert(uzel *n, uzel *root)
{
while (n != NULL)
{
if (root->data > n->data)
{
if (n->praviy == NULL)
{
root->roditel = n;
n->praviy = root;
return 0;
}
else
{
n = n->praviy;
}
}
else
{
if (root->data < n->data)
{
if (n->leviy == NULL)
{
root->roditel = n;
n->leviy = root;
return 0;
}
else
{
n = n->leviy;
}
}
else
{
if (root->data == n->data)
{
return 1;
}
}
}
}
}
uzel *min(uzel* n)
{
uzel *current = n;
while (current && current->leviy != NULL)
current = current->leviy;
return current;
}
uzel *max(uzel *n)
{
uzel *current = n;
while (current && current->praviy != NULL)
current = current->praviy;
return current;
}
uzel* delete(uzel* root, int value)
{
if(root == NULL)
{
return root;
}
if (value < root -> data)
{
root -> leviy = delete(root -> leviy, value);
}
else if (value > root -> data)
{
root -> praviy = delete(root -> praviy, value);
}
else
{
if (root -> leviy == NULL)
{
uzel *temp = root -> praviy;
free(root);
return temp;
}
else if (root -> praviy == NULL)
{
uzel *temp = root -> leviy;
free(root);
return temp;
}
uzel* temp = min(root -> praviy);
root -> data = temp -> data;
root -> praviy = delete(root -> praviy, temp -> data);
}
return root;
}
int remove_min(uzel *n)
{
int min_n = min(n) -> data;
delete(n, min_n);
return min_n;
}
uzel *rotate_left(uzel *n){
uzel* n_leviy = n -> praviy;
n -> praviy = n_leviy -> leviy;
n_leviy -> leviy = n;
return n_leviy;
}
uzel *rotate_right(uzel *n){
uzel* n_praviy = n -> leviy;
n -> leviy = n_praviy -> praviy;
n_praviy -> praviy = n;
return n_praviy;
}
void push(Stack *s, uzel *temp)
{
if (s -> size >= s -> max)
{
s -> max *= 2;
s -> data = (uzel**) realloc(s -> data, s -> max * sizeof(uzel*));
}
s -> data[s -> size++] = temp;
}
uzel* pop(Stack *s)
{
if (s -> size == 0)
{
exit(7);
}
s -> size--;
return s -> data[s -> size];
}
uzel* peek(Stack *s)
{
return s -> data[s -> size-1];
}
void print(uzel *root) {
Stack *s = add_Stack();
while (s -> size != 0 || root != NULL)
{
if (root != NULL)
{
printf("%d ", root -> data);
if (root -> praviy != NULL)
{
push(s, root -> praviy);
}
root = root -> leviy;
}
else
{
root = pop(s);
}
}
freee(&s);
}
int main()
{
int a;
tree *temp = malloc(sizeof(tree));
init(temp);
uzel *root1 = temp->golova;
scanf("%d", &a);
root1 = add_Uzel(a);
for(int i=0; i<6; i++)
{
scanf("%d", &a);
if(find(root1, a) == NULL)
{
insert(root1, add_Uzel(a));
}
}
print(root1);
return 0;
}
| 3.234375 | 3 |
2024-11-18T22:37:18.877306+00:00
| 2018-06-21T14:22:29 |
93108075c946261fab5872999da19865946f7252
|
{
"blob_id": "93108075c946261fab5872999da19865946f7252",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-21T14:22:29",
"content_id": "4ac8be0d0e3f102a5ff837a2cfaace6e449499e1",
"detected_licenses": [
"MIT"
],
"directory_id": "c2fa77235aed272ed290b5970ac10fe0d0ed88e8",
"extension": "h",
"filename": "Iterator.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 133674242,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 765,
"license": "MIT",
"license_type": "permissive",
"path": "/include/bolib/data/Iterator.h",
"provenance": "stackv2-0107.json.gz:98469",
"repo_name": "boldowa/bolib2",
"revision_date": "2018-06-21T14:22:29",
"revision_id": "1671662b7e009882abdad94a68d86e5229bc22b0",
"snapshot_id": "5359dc60e997f60ca0b613550894a56e01802295",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/boldowa/bolib2/1671662b7e009882abdad94a68d86e5229bc22b0/include/bolib/data/Iterator.h",
"visit_date": "2020-03-17T14:30:00.575372"
}
|
stackv2
|
/**
* @file Iterator.h
*/
#ifndef ITERATOR_H
#define ITERATOR_H
#include "bolib/btypes.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* public accessor
*/
typedef struct _Iterator Iterator;
typedef struct _Iterator_protected Iterator_protected;
typedef struct _Iterator_private Iterator_private;
struct _Iterator {
Iterator* (*prev)(Iterator*);
Iterator* (*next)(Iterator*);
void* (*data)(Iterator*);
bool (*insert)(Iterator*, void*);
void (*remove)(Iterator*, bool);
Iterator_protected* pro;
};
/**
* Constructor
*/
Iterator* new_Iterator_impl(void*);
#define new_Iterator(a) new_Iterator_impl(a)
/**
* Destractor
*/
void delete_Iterator_impl(Iterator**);
#define delete_Iterator(a) delete_Iterator_impl(a)
#ifdef __cplusplus
}
#endif
#endif
| 2.234375 | 2 |
2024-11-18T22:37:19.543918+00:00
| 2014-12-25T18:27:08 |
15e45ce3b8a51e353ab842e44fe41cbc0dfe5c1a
|
{
"blob_id": "15e45ce3b8a51e353ab842e44fe41cbc0dfe5c1a",
"branch_name": "refs/heads/master",
"committer_date": "2014-12-25T18:27:08",
"content_id": "00762d382009cfba742e71624d3ab06d9add0439",
"detected_licenses": [
"MIT"
],
"directory_id": "ebc648049d56273c4790b5aaddfc35e245a65335",
"extension": "h",
"filename": "array_list.h",
"fork_events_count": 0,
"gha_created_at": "2013-12-09T21:06:21",
"gha_event_created_at": "2014-12-25T18:27:08",
"gha_language": "C",
"gha_license_id": null,
"github_id": 15059056,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1108,
"license": "MIT",
"license_type": "permissive",
"path": "/src/array_list.h",
"provenance": "stackv2-0107.json.gz:98861",
"repo_name": "ibawt/ev",
"revision_date": "2014-12-25T18:27:08",
"revision_id": "0dbbfc90d6c8e31a0b20c7ab924e392dc42aaef6",
"snapshot_id": "37aa09ef9f93884f75675bda227ac99a6a4bf74d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ibawt/ev/0dbbfc90d6c8e31a0b20c7ab924e392dc42aaef6/src/array_list.h",
"visit_date": "2020-04-09T07:56:44.287687"
}
|
stackv2
|
#ifndef EV_ARRAY_LIST_H_
#define EV_ARRAY_LIST_H_
#include "evil.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Shitty array list for size < a pointer
* TODO:
* - allow for value types (like ev_vec2)
* - benchmark
*/
typedef struct {
size_t len;
size_t top;
void **buff;
} ev_arraylist;
#define ev_arraylist_len(_p) (_p)->top
ev_err_t ev_arraylist_init(ev_arraylist *al, size_t initial);
#define ev_arraylist_destroy(_p) ev_free((_p)->buff)
ev_err_t ev_arraylist_push_ex(ev_arraylist *al, void *d);
#define ev_arraylist_push(_p, _d) do { if((_p)->top >= (_p)->len) { \
ev_arraylist_push_ex((_p),(_d)); \
} else { (_p)->buff[(_p)->top++] = (_d); } } while(0)
#define ev_arraylist_pop(_p) ( (_p)->top ? (_p)->buff[(_p)->top-- - 1] : NULL )
void ev_arraylist_insert(ev_arraylist *al, size_t index, void *d);
void ev_arraylist_remove(ev_arraylist *al, size_t index);
#define ev_arraylist_clear(_p) (_p)->top = 0
ev_err_t ev_arraylist_reserve(ev_arraylist *al, size_t amt);
#ifdef __cplusplus
}
#endif
#endif
| 2.4375 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.