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-18T21:06:33.401544+00:00 | 2012-03-30T23:01:23 | 114a49336aa263979e39a7800af65a19fef7324e | {
"blob_id": "114a49336aa263979e39a7800af65a19fef7324e",
"branch_name": "refs/heads/master",
"committer_date": "2012-03-30T23:01:23",
"content_id": "9e503a05b4ed8f1cb799b2a27993db1786ae76de",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "614ec0df6a8d84bf059ba7731954ff4b71e512f7",
"extension": "c",
"filename": "play.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": 940,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/play.c",
"provenance": "stackv2-0128.json.gz:77275",
"repo_name": "shroukkhan/wavplay",
"revision_date": "2012-03-30T23:01:23",
"revision_id": "2941ee0485f1556a86ea46f25684e88d5b7978cf",
"snapshot_id": "980c74dbae12ff677dc277a90c6a494cbe9d4b93",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/shroukkhan/wavplay/2941ee0485f1556a86ea46f25684e88d5b7978cf/play.c",
"visit_date": "2020-12-25T05:46:52.607987"
} | stackv2 | /*
* A sample program using wavplay. It can play multiple PCM files;
* if the filename is `-', it reads a file from the standard input.
* Press Ctrl-\ to drop the current playing file.
*/
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include "wavplay.h"
#ifdef SIGQUIT
static void drop(int sig) {
if (sig == SIGQUIT)
snd_drop();
}
#endif
int main(int argc, char *argv[]) {
char *prog = argv[0];
if (argc < 2) {
printf("Usage: %s [FILE|-]...\n", prog);
return 1;
}
if (snd_init() < 0) {
fprintf(stderr, "%s: Failed to open device `"
DEV_NAME "'\n", prog);
return 1;
}
#ifdef SIGQUIT
signal(SIGQUIT, drop);
#endif
int i = 1;
while (1) {
const char *fn = argv[i++];
if (!strcmp(fn, "-"))
fn = NULL;
if (fn ? wav_play(fn) : wav_send(stdin))
fprintf(stderr, "%s: Skipping file `%s'\n",
prog, fn ? fn : "STDIN");
if (i < argc) sleep(1);
else break;
}
snd_end();
return 0;
}
| 2.84375 | 3 |
2024-11-18T21:06:33.525205+00:00 | 2020-06-05T19:38:52 | 1e82adef2b8f10ffeccb267dfcd3c73613009260 | {
"blob_id": "1e82adef2b8f10ffeccb267dfcd3c73613009260",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-05T19:38:52",
"content_id": "59ffe2a58fd62b92f26c6247aca1eb382eb8c8ea",
"detected_licenses": [
"MIT"
],
"directory_id": "fdc313abdc5644cfcfb4cfb36f1b69e9082ae248",
"extension": "c",
"filename": "second.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": 514,
"license": "MIT",
"license_type": "permissive",
"path": "/Assignment 1 - Basics of fork()/second.c",
"provenance": "stackv2-0128.json.gz:77535",
"repo_name": "r-Iyer/Operating-System-Lab-Assignments",
"revision_date": "2020-06-05T19:38:52",
"revision_id": "75e3a3150db76ff58a7ca8e84f9cdf9237d02c22",
"snapshot_id": "f30fb1e3f37767cff01c02fbf6b5e99a2699d4da",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/r-Iyer/Operating-System-Lab-Assignments/75e3a3150db76ff58a7ca8e84f9cdf9237d02c22/Assignment 1 - Basics of fork()/second.c",
"visit_date": "2022-09-22T06:42:43.278550"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
// make two process which run same program after this instruction
int n=argc-1,index=0,num;
int nums[n];
// int i,j;
long int fact;
for(int i=0;i<n;i++)
nums[i]=atoi(argv[i+1]);
pid_t pid;
while(index<n && fork()==0) {
fact=1;
num=nums[index++];
for(int j=1;j<=num;j++)
fact*=j;
printf("%ld\n",fact);
}
}
| 2.78125 | 3 |
2024-11-18T21:06:33.700834+00:00 | 2019-12-12T12:32:21 | 00dac6c7c743bf071961a11088746004a2ee1929 | {
"blob_id": "00dac6c7c743bf071961a11088746004a2ee1929",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-12T12:32:21",
"content_id": "7f3e5982b1c5db559331a3c35d896b90c193d06c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4e5a8a96a69b563b102a60c54b3a40a1da887cc2",
"extension": "c",
"filename": "HelloWorld2.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 117062632,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 95,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/testdata/util/folder01/HelloWorld2.c",
"provenance": "stackv2-0128.json.gz:77796",
"repo_name": "KernelHaven/IncrementalAnalysesInfrastructure",
"revision_date": "2019-12-12T12:32:21",
"revision_id": "447c2d707114a41683f8a324ce587de869c154b8",
"snapshot_id": "18961430af2249d580821042d887035d3e40edb8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/KernelHaven/IncrementalAnalysesInfrastructure/447c2d707114a41683f8a324ce587de869c154b8/testdata/util/folder01/HelloWorld2.c",
"visit_date": "2021-06-08T08:57:43.615589"
} | stackv2 | #include<stdio.h>
int main() {
printf("Hello World - this is the 2nd World \n");
return 0;
} | 2.078125 | 2 |
2024-11-18T21:06:33.936111+00:00 | 2020-12-11T02:58:47 | e046d4270d6c62b706161b74018f733f83a271eb | {
"blob_id": "e046d4270d6c62b706161b74018f733f83a271eb",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-11T02:58:47",
"content_id": "7a17bf48afcd4d212e102b2a3fc08a72cc36ffbb",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c301f3cc6af2ee0a5be9bc9afc337eee9e8c255b",
"extension": "c",
"filename": "util.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 320379851,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 596,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/util.c",
"provenance": "stackv2-0128.json.gz:78184",
"repo_name": "Bader-Research/CUDARMAT",
"revision_date": "2020-12-11T02:58:47",
"revision_id": "dee24df21cb71e814d7f1e5bcc34a9289a7dea3f",
"snapshot_id": "5a4ceaa24846ae1d7fcc69fd091ff3399f39872b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Bader-Research/CUDARMAT/dee24df21cb71e814d7f1e5bcc34a9289a7dea3f/util.c",
"visit_date": "2023-02-12T03:13:58.784695"
} | stackv2 | #include <sys/time.h>
#include <stdio.h>
#include "util.h"
struct timeval tv;
double firsttic = 0;
double lasttic = 0;
void tic_reset() {
gettimeofday(&tv, NULL);
firsttic = (double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec;
lasttic = firsttic;
}
double tic_total() {
gettimeofday(&tv, NULL);
lasttic = (double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec;
return lasttic - firsttic;
}
double tic_sincelast() {
gettimeofday(&tv, NULL);
double rtnval = ((double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec) - lasttic;
lasttic = (double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec;
return rtnval;
}
| 2.390625 | 2 |
2024-11-18T21:06:34.853894+00:00 | 2021-05-11T08:50:06 | 44ac2decbacfbc3ad0ba47941897ab6bc3ea9354 | {
"blob_id": "44ac2decbacfbc3ad0ba47941897ab6bc3ea9354",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-11T08:50:06",
"content_id": "a2bf7bf2e3e3c360ac3992dee9aa73618396b317",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "e57ccc18f8cacec8ff47b4d4c81c200b63977ec0",
"extension": "c",
"filename": "tlock_queue.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 257070254,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3696,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/tlock_queue.c",
"provenance": "stackv2-0128.json.gz:78964",
"repo_name": "00xc/tlock-queue",
"revision_date": "2021-05-11T08:50:06",
"revision_id": "2ba98a953e65e7db07134ed842e625ae4dec8f29",
"snapshot_id": "81ac1ed3d6e6d567ed9c2d3572d8e0f1535c65c8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/00xc/tlock-queue/2ba98a953e65e7db07134ed842e625ae4dec8f29/src/tlock_queue.c",
"visit_date": "2023-04-21T22:26:51.501934"
} | stackv2 | #include <stdlib.h>
#include <string.h>
#ifndef __STDC_NO_THREADS__
#include "tlock_queue.h"
/* Helper function to allocate and initialize a queue node */
#ifdef __GNUC__
__attribute__ ((malloc))
#endif
inline static _tlock_node_t* _tlock_node_init(void* value) {
_tlock_node_t* node;
if ( (node = malloc(sizeof(_tlock_node_t))) == NULL ) {
return NULL;
}
node->value = value;
node->next = NULL;
return node;
}
/* Helper function to free a queue node */
inline static void _tlock_node_free(_tlock_node_t* node) {
free(node);
}
/* Allocates and initializes queue */
#ifdef __GNUC__
__attribute__ ((malloc))
#endif
tlock_queue_t* tlock_init() {
tlock_queue_t* queue;
_tlock_node_t* dummy;
/* Allocate queue */
if ( (queue = malloc(sizeof(tlock_queue_t))) == NULL )
return NULL;
/* Allocate mutexes */
if ( (queue->first_mutex = malloc(sizeof(mtx_t))) == NULL ) {
free(queue);
return NULL;
}
if ( (queue->last_mutex = malloc(sizeof(mtx_t))) == NULL ) {
free(queue->first_mutex);
free(queue);
return NULL;
}
/* Initialize mutexes */
if (mtx_init(queue->first_mutex, mtx_plain) != thrd_success || mtx_init(queue->last_mutex, mtx_plain) != thrd_success) {
tlock_free(queue);
return NULL;
}
/* Allocate dummy node */
if ( (dummy = _tlock_node_init(NULL)) == NULL ) {
tlock_free(queue);
return NULL;
}
/* Initialize ends of queue */
queue->first = queue->last = dummy;
return queue;
}
/* Frees queue resources. Assumes the queue is depleted */
void tlock_free(tlock_queue_t* queue) {
if (queue == NULL) {
return;
}
/* Free the dummy node */
if (queue->first != NULL) {
free(queue->first);
}
/* Destroy and free mutexes */
if (queue->first_mutex != NULL ){
mtx_destroy(queue->first_mutex);
free(queue->first_mutex);
}
if (queue->last_mutex != NULL) {
mtx_destroy(queue->last_mutex);
free(queue->last_mutex);
}
free(queue);
}
/* Push at the end of the queue */
#ifdef __GNUC__
__attribute__ ((warn_unused_result))
#endif
int tlock_push(tlock_queue_t* restrict queue, void* restrict new_element) {
_tlock_node_t* node;
/* Prepare new node */
if ( (node = _tlock_node_init(new_element)) == NULL ) {
return TLOCK_ERROR;
}
/* Add to queue with lock */
mtx_lock(queue->last_mutex);
queue->last->next = node;
queue->last = node;
mtx_unlock(queue->last_mutex);
return TLOCK_OK;
}
/* Pop from beginning of queue */
void* tlock_pop(tlock_queue_t* queue) {
_tlock_node_t* node; /* Node to be removed */
_tlock_node_t* new_header; /* Node that will become the first in the queue */
void* return_value; /* Data to be retrieved */
mtx_lock(queue->first_mutex);
node = queue->first;
new_header = queue->first->next;
/* Queue is empty */
if (new_header == NULL) {
mtx_unlock(queue->first_mutex);
return NULL;
}
/* Queue not empty: retrieve data and rewire */
return_value = new_header->value;
queue->first = new_header;
mtx_unlock(queue->first_mutex);
/* Free removed node and return */
_tlock_node_free(node);
return return_value;
}
/*
* Retrieves the minimum number of elements in the queue at the time of function call. The number
* can be bigger if threads are pushing to the queue concurrently.
*/
size_t tlock_min_size(const tlock_queue_t* queue) {
register size_t counter = 0;
_tlock_node_t* node;
mtx_lock(queue->first_mutex);
/* Get first element if queue is not empty */
if ( (node = queue->first->next) != NULL ) {
++counter;
}
/* Count the rest of elements */
while (node != NULL && node->next != NULL) {
++counter;
node = node->next;
}
mtx_unlock(queue->first_mutex);
return counter;
}
#else
#pragma message ( "No C11 thread support" )
#endif
| 3.234375 | 3 |
2024-11-18T21:06:35.160929+00:00 | 2017-05-05T06:05:45 | 9b92691b81a451a3f5f12f332a1d9a84938823e2 | {
"blob_id": "9b92691b81a451a3f5f12f332a1d9a84938823e2",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-05T06:05:45",
"content_id": "693df44a58e15ea9c47f55a83ebeeb1644cd8c28",
"detected_licenses": [
"MIT"
],
"directory_id": "d9fd7fcdb680897eadc32e16bca59bbdf1de903d",
"extension": "c",
"filename": "app.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87692406,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10693,
"license": "MIT",
"license_type": "permissive",
"path": "/applications/app.c",
"provenance": "stackv2-0128.json.gz:79096",
"repo_name": "ToSeven/environment_monitor",
"revision_date": "2017-05-05T06:05:45",
"revision_id": "8f597273b1a0d4565b8c5e85a71845cb0e28afce",
"snapshot_id": "001831eacc3aaecdb866d8a512b7ea8228b225f1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ToSeven/environment_monitor/8f597273b1a0d4565b8c5e85a71845cb0e28afce/applications/app.c",
"visit_date": "2021-01-19T08:52:41.249007"
} | stackv2 | /**
* @Author: ToSeven
* @Date: 2017-04-06T20:52:47+08:00
* @Email: byone.heng@gmail.com
* @Last modified by: ToSeven
* @Last modified time: 2017-04-22T15:17:21+08:00
* @License: MIT
*/
#include "app.h"
#include "bsp_common.h"
#include "bluenrg_sdk_api.h"
#include "juma_sensor.h"
#include "oled.h"
#include "bmp.h"
#include "stm32f4xx.h"
#include <stdlib.h>
#define UPDATE_INTERVAL 100
static void read_temperature(void* arg);
static void read_humidity(void* arg);
static void read_pressure(void* arg);
static void read_magenetometer(void* arg);
static void read_accelerometer(void* arg);
static void read_gyroscopic(void* arg);
static void led_on(void* arg);
static void led_off(void* arg);
static void Show_WarnValue();
static void Monitor_Gas();
static void Monitor_People();
static void Show_Facility();
const char* board_name = "ToSeven";
static uint8_t running;
static uint8_t sendflag;
static uint16_t warnTemper;
static uint16_t rawTemper;
static uint16_t warnHumid;
static uint16_t rawHumid;
static uint32_t warnPress;
static uint32_t rawPress;
static uint8_t show_flag;
uint8_t gas_flag;
uint8_t infrared_flag;
uint8_t facility_flag;
void jsensor_app_set_sensors(void)
{
jsensor_app_set_sensor(JSENSOR_TYPE_HUMITY_TEMP);
jsensor_app_set_sensor(JSENSOR_TYPE_PRESSURE);
jsensor_app_set_sensor(JSENSOR_TYPE_MOTION_6AXIS);
jsensor_app_set_sensor(JSENSOR_TYPE_MAGNET);
}
void on_ready(void)
{
uint8_t tx_power_level = 7;
uint16_t adv_interval = 100;
uint8_t bdAddr[6];
char name[32];
running = 0;
BSP_LED_On(LED0);
HCI_get_bdAddr(bdAddr);
sprintf(name, "%s %01x%01x", board_name, bdAddr[0], bdAddr[1]);
/*Config Adv Parameter And Ready to Adv*/
ble_set_adv_param(name, bdAddr, tx_power_level, adv_interval);
ble_device_start_advertising();
OLED_Clear();
OLED_DrawBMP(0,0,127,7,BMP2);
OLED_Content_clear();
OLED_ShowString(45,2,"MEMU");
OLED_ShowString(45,4,"SETS");
OLED_ShowString(41,6,"ABOUT");
}
static void Show_WarnValue()
{
if(show_flag==2)
{
OLED_Content_clear();
OLED_ShowString(0,2,"WarnTemper:");
OLED_ShowNum(88,2,warnTemper,2,16);
OLED_ShowString(0,4,"WarnHumid:");
OLED_ShowNum(80,4,warnHumid,2,16);
OLED_ShowString(0,6,"warnPress:");
OLED_ShowNum(80,6,warnPress,2,16);
}
run_after_delay(read_temperature,NULL,50);
}
static void Monitor_Gas()
{
if(show_flag==1)
{
OLED_Line_clear(1);
OLED_ShowString(0,2,"Monitor Gas:");
OLED_ShowNum(96,2,gas_flag,1,16);
gas_flag=0;
}
run_after_delay(Monitor_People,NULL,50);
}
static void Monitor_People()
{
if(show_flag==1)
{
OLED_Line_clear(2);
OLED_ShowString(0,4,"Monitor Peo:");
OLED_ShowNum(96,4,infrared_flag,1,16);
infrared_flag=0;
}
run_after_delay(Show_Facility,NULL,50);
}
static void Show_Facility()
{
if(show_flag==1)
{
OLED_Line_clear(3);
OLED_ShowString(0,6,"Facility On:");
OLED_ShowNum(96,6,facility_flag,1,16);
}
run_after_delay(Show_WarnValue,NULL,50);
}
static void read_temperature(void* arg)
{
int16_t humidity;
int16_t temperature;
JSensor_HUM_TEMP_Typedef tdef;
int16_t copy_temperature=0;
if (!running) return;
tdef.humidity = &humidity;
tdef.temperature = &temperature;
if (JSENSOR_OK == jsensor_app_read_sensor(JSENSOR_TYPE_HUMITY_TEMP, (void *)&tdef)&&sendflag==0) {
ble_device_send(0x00, 2, (uint8_t *)&temperature);
}
uint8_t *temp_temperature=(uint8_t *)&temperature;
copy_temperature|=temp_temperature[0];
copy_temperature<<=8;
rawTemper=copy_temperature/100;
// printf("\n\r-tempe:%x \r\n",copy_temperature);
if(show_flag==0)
{
OLED_Line_clear(1);
OLED_ShowString(0,2,"TEM:");
short integer=copy_temperature/100;
short decimals=copy_temperature-integer*100;
if(integer==0)
{
OLED_ShowChar(32,2,'0');
OLED_ShowChar(40,2,'0');
}else
OLED_ShowNum(32,2,integer,2,16);
OLED_ShowChar(48,2,'.');
if(decimals==0)
{
OLED_ShowChar(56,2,'0');
OLED_ShowChar(64,2,'0');
} else
OLED_ShowNum(56,2,decimals,2,16);
OLED_ShowString(72,2,"'C");
}
run_after_delay(read_humidity, NULL, UPDATE_INTERVAL);
}
static void read_humidity(void* arg)
{
int16_t humidity;
int16_t temperature;
int16_t copy_humidity=0;
JSensor_HUM_TEMP_Typedef tdef;
if (!running) return;
tdef.humidity = &humidity;
tdef.temperature = &temperature;
if (JSENSOR_OK == jsensor_app_read_sensor(JSENSOR_TYPE_HUMITY_TEMP, (void *)&tdef)&&sendflag==0) {
ble_device_send(0x01, 2, (uint8_t *)&humidity);
}
uint8_t *temp_humidity=(uint8_t *)&humidity;
copy_humidity|=temp_humidity[0];
copy_humidity<<=8;
copy_humidity|=(temp_humidity[1]&0x00ff);
rawHumid=copy_humidity/100;
// printf("\n\r-humidity:%x \r\n",copy_humidity);
if(show_flag==0)
{
OLED_Line_clear(2);
OLED_ShowString(0,4,"HUM:");
short integer=copy_humidity/100;
short decimals=copy_humidity-integer*100;
if(integer==0)
{
OLED_ShowChar(32,4,'0');
OLED_ShowChar(40,4,'0');
}else
OLED_ShowNum(32,4,integer,2,16);
OLED_ShowChar(48,4,'.');
if(decimals==0)
{
OLED_ShowChar(56,4,'0');
OLED_ShowChar(64,4,'0');
}else
OLED_ShowNum(56,4,decimals,2,16);
OLED_ShowString(72,4,"RH");
}
run_after_delay(read_pressure, NULL, UPDATE_INTERVAL);
}
static void read_pressure(void* arg)
{
JSensor_Press_Typedef tdef;
int32_t pressure;
int32_t copy_pressure=0;
if (!running) return;
tdef.pressure = &pressure;
if (JSENSOR_OK == jsensor_app_read_sensor(JSENSOR_TYPE_PRESSURE, (void *)&tdef)&&sendflag==0) {
ble_device_send(0x02, 3, (uint8_t *)&pressure);
}
uint8_t *temp_pressure=(uint8_t *)&pressure;
copy_pressure|=temp_pressure[0];
copy_pressure<<=8;
copy_pressure|=(temp_pressure[1]&0x00ff);
copy_pressure<<=8;
copy_pressure|=(temp_pressure[2]&0x0000ff);
rawPress=copy_pressure/100000;
// printf("\n\r press:%x\r\n",copy_pressure);
if(show_flag==0)
{
OLED_Line_clear(3);
OLED_ShowString(0,6,"PRE:");
short integer=copy_pressure/100000;
short decimals=(copy_pressure-integer*100000)/1000;
if(integer==0)
{
OLED_ShowChar(32,6,'0');
OLED_ShowChar(40,6,'0');
}else
OLED_ShowNum(32,6,integer,2,16);
OLED_ShowChar(48,6,'.');
if(decimals==0)
{
OLED_ShowChar(56,6,'0');
OLED_ShowChar(64,6,'0');
} else
OLED_ShowNum(56,6,decimals,2,16);
OLED_ShowString(72,6,"Pa");
}
run_after_delay(Monitor_Gas, NULL, UPDATE_INTERVAL);
}
static void read_magenetometer(void* arg)
{
JSensor_MAG_Typedef tdef;
int8_t MAG[6];
if (!running) return;
tdef.MAG = MAG;
if(JSENSOR_OK == jsensor_app_read_sensor(JSENSOR_TYPE_MAGNET, (void *)&tdef)) {
// ble_device_send(0x03, 6, (uint8_t*)MAG);
// printf("%x,%x,%x,%x,%x,%x\n\r", MAG[0],MAG[1],MAG[2],MAG[3],MAG[4],MAG[5]);
}
run_after_delay(read_accelerometer, NULL, UPDATE_INTERVAL);
}
static void read_accelerometer(void* arg)
{
JSensor_AXIS_Typedef tdef;
int8_t ACC[6], GRO[6];
if (!running) return;
tdef.ACC = ACC;
tdef.GRO = GRO;
if (JSENSOR_OK == jsensor_app_read_sensor(JSENSOR_TYPE_MOTION_6AXIS, (void *)&tdef)) {
// ble_device_send(0x04, 6, (uint8_t*)ACC);
}
run_after_delay(read_gyroscopic, NULL, UPDATE_INTERVAL);
}
static void read_gyroscopic(void* arg)
{
JSensor_AXIS_Typedef tdef;
int8_t ACC[6], GRO[6];
if (!running) return;
tdef.ACC = ACC;
tdef.GRO = GRO;
if (JSENSOR_OK == jsensor_app_read_sensor(JSENSOR_TYPE_MOTION_6AXIS, (void *)&tdef)) {
// ble_device_send(0x05, 6, (uint8_t*)GRO);
}
run_after_delay(read_temperature, NULL, UPDATE_INTERVAL);
}
/* Device On Message receive data from ble */
void ble_device_on_message(uint8_t type, uint16_t length, uint8_t* value)
{
switch (type) {
case 0x00:
sendflag=*value;
break;
case 0x01:
warnTemper=*value;
break;
case 0x02:
warnHumid=*value;
break;
case 0x03:
warnPress=*value;
break;
case 0x04:
if(*value>0)
{
Bsp_Facility_On();
facility_flag=1;
}
else{
Bsp_Facility_Off();
facility_flag=0;
}
break;
case 0x05:
show_flag=*value;
break;
}
}
/* Device on connect */
void ble_device_on_connect(void)
{
running = 1;
run_after_delay(led_off, NULL, 150);
run_after_delay(read_temperature,NULL,100);
}
static void led_on(void* arg)
{
BSP_LED_On(LED0);
run_after_delay(led_off, NULL, 100);
}
static void led_off(void* arg)
{
if (!running) return;
BSP_LED_Off(LED0);
run_after_delay(led_on, NULL, 150);
}
/* Device on disconnect */
void ble_device_on_disconnect(uint8_t reason)
{
running = 0;
/* Make the device connectable again. */
ble_device_start_advertising();
}
void loop()
{
if(Bsp_Gas_GetStatus()==0)
HAL_Delay(10);
if(Bsp_Gas_GetStatus()==0)
{
Buzzer_On();
gas_flag=1;
HAL_Delay(1000);
Buzzer_Off();
}
if(Bsp_People_GetStatus()==1)
{
Buzzer_On();
infrared_flag=1;
HAL_Delay(1000);
Buzzer_Off();
}
if(rawTemper<warnTemper)
{
Buzzer_On();
HAL_Delay(1000);
Buzzer_Off();
}
if(rawHumid<warnHumid)
{
Buzzer_On();
HAL_Delay(1000);
Buzzer_Off();
}
if(rawPress<warnPress)
{
Buzzer_On();
HAL_Delay(1000);
Buzzer_Off();
}
}
| 2.15625 | 2 |
2024-11-18T21:06:35.251890+00:00 | 2023-08-28T12:45:01 | 0ce4f18423916aad886feda8a022f447261fc01c | {
"blob_id": "0ce4f18423916aad886feda8a022f447261fc01c",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-28T13:28:42",
"content_id": "b80db467c45c41c175706af3757cb366c21e163f",
"detected_licenses": [
"MIT"
],
"directory_id": "a091d500abbda0a3e36898b23075744c5a36433d",
"extension": "c",
"filename": "sampler.c",
"fork_events_count": 1,
"gha_created_at": "2016-06-11T12:23:16",
"gha_event_created_at": "2022-12-14T16:43:36",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 60905873,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1603,
"license": "MIT",
"license_type": "permissive",
"path": "/opengl/src/sampler.c",
"provenance": "stackv2-0128.json.gz:79225",
"repo_name": "FabianHahn/shoveler",
"revision_date": "2023-08-28T12:45:01",
"revision_id": "2f602fe2edc4bb99f74e570115fc733ecc80503c",
"snapshot_id": "e996a50dd9d9e40442bd5e562fdbc45b1760b06c",
"src_encoding": "UTF-8",
"star_events_count": 34,
"url": "https://raw.githubusercontent.com/FabianHahn/shoveler/2f602fe2edc4bb99f74e570115fc733ecc80503c/opengl/src/sampler.c",
"visit_date": "2023-08-31T00:52:54.630367"
} | stackv2 | #include "shoveler/sampler.h"
#include <stdlib.h> // malloc, free
#include "shoveler/opengl.h"
ShovelerSampler* shovelerSamplerCreate(bool interpolate, bool useMipmaps, bool clamp) {
ShovelerSampler* sampler = malloc(sizeof(ShovelerSampler));
glGenSamplers(1, &sampler->sampler);
if (interpolate) {
if (useMipmaps) {
glSamplerParameteri(sampler->sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
} else {
glSamplerParameteri(sampler->sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
glSamplerParameteri(sampler->sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else {
if (useMipmaps) {
glSamplerParameteri(sampler->sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
} else {
glSamplerParameteri(sampler->sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
glSamplerParameteri(sampler->sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
shovelerOpenGLCheckSuccess();
if (clamp) {
glSamplerParameteri(sampler->sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glSamplerParameteri(sampler->sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
} else {
glSamplerParameteri(sampler->sampler, GL_TEXTURE_WRAP_S, GL_REPEAT);
glSamplerParameteri(sampler->sampler, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
shovelerOpenGLCheckSuccess();
return sampler;
}
bool shovelerSamplerUse(ShovelerSampler* sampler, GLuint unitIndex) {
glBindSampler(unitIndex, sampler->sampler);
return shovelerOpenGLCheckSuccess();
}
void shovelerSamplerFree(ShovelerSampler* sampler) {
glDeleteSamplers(1, &sampler->sampler);
free(sampler);
}
| 2.40625 | 2 |
2024-11-18T21:06:35.538863+00:00 | 2017-06-08T13:20:31 | bae863fd2fe6bc1d996e20ad82c322181b1b3bc4 | {
"blob_id": "bae863fd2fe6bc1d996e20ad82c322181b1b3bc4",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-08T13:20:31",
"content_id": "6abc4cf6e83c52c8e3beaba0fd86865f3d6c6da7",
"detected_licenses": [
"MIT"
],
"directory_id": "3f9b4126045b66a46737ee6039355106246ed83c",
"extension": "c",
"filename": "bootloader.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 60821942,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3897,
"license": "MIT",
"license_type": "permissive",
"path": "/bootloader.c",
"provenance": "stackv2-0128.json.gz:79611",
"repo_name": "xobs/joyboot",
"revision_date": "2017-06-08T13:20:31",
"revision_id": "ab80271fa494750363b38a3d4d7035b71e434aa4",
"snapshot_id": "7e914ab71d40b0f2698010a72b2b2b5d7b044eef",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/xobs/joyboot/ab80271fa494750363b38a3d4d7035b71e434aa4/bootloader.c",
"visit_date": "2020-05-22T08:14:25.849703"
} | stackv2 | #include <stdint.h>
#include "kl17.h"
#include "core_cm0plus.h"
#include "palawan.h"
#include "palawan_bl.h"
#include "radio.h"
enum bootloader_reason bootloader_reason;
int updateRx(void);
int updateTx(void);
static __attribute__((section(".appvectors"))) uint32_t appVectors[64];
static int test_boot_token(void)
{
/*
* If we find a valid boot token in RAM, the application is asking us explicitly
* to enter DFU mode. This is used to implement the DFU_DETACH command when the app
* is running.
*/
return boot_token.magic == 0x74624346;
}
static int button_held_down(void)
{
int before;
int after;
/* Set PTB12 as a GPIO input, slow slew rate */
PORTB->PCR[12] = (1 << 8) | (1 << 2);
/* Set it as an input */
FGPIOB->PDDR &= ~(1 << 12);
/* If the pin isn't held down, don't enter the bootloader */
before = !(FGPIOB->PDIR & (1 << 12));
if (!before)
return 0;
/* Sample the pin before, then wait about 500ms and sample again */
{
int i;
for (i = 0; i < 500000; i++)
{
int j;
for (j = 0; j < 77; j++)
{
asm("");
}
}
}
after = !(FGPIOB->PDIR & (1 << 12));
if (!after)
return 0;
return 1;
}
static int should_enter_bootloader(void)
{
extern uint32_t __ram_start__;
extern uint32_t __ram_end__;
extern uint32_t __app_start__;
extern uint32_t __app_end__;
/* Reset the boot token if we've just been powered up for the first time */
if (RCM->SRS0 & RCM_SRS0_POR)
{
boot_token.magic = 0;
boot_token.boot_count = 0;
}
/* If the special magic number is present, enter the bootloader */
if (test_boot_token())
{
bootloader_reason = BOOT_TOKEN_PRESENT;
return 1;
}
/* If the user is holding the button down */
if (button_held_down())
{
bootloader_reason = BUTTON_HELD_DOWN;
return 1;
}
/* If we've failed to boot many times, enter the bootloader */
if (boot_token.boot_count > 3)
{
bootloader_reason = BOOT_FAILED_TOO_MANY_TIMES;
return 1;
}
/* Otherwise, if the application appears valid (i.e. stack is in a sane
* place, and the program counter is in flash,) boot to it */
if (((appVectors[0] >= (uint32_t)&__ram_start__) && (appVectors[0] <= (uint32_t)&__ram_end__)) && ((appVectors[1] >= (uint32_t)&__app_start__) && (appVectors[1] <= (uint32_t)&__app_end__)))
{
bootloader_reason = NOT_ENTERING_BOOTLOADER;
return 0;
}
/* If there is no valid program, enter the bootloader */
bootloader_reason = NO_PROGRAM_PRESENT;
return 1;
}
__attribute__((noreturn)) static void boot_app(void)
{
// Relocate IVT to application flash
__disable_irq();
SCB->VTOR = (uint32_t)&appVectors[0];
// Switch the clock mode from FEE back to FEI
if (palawanModel() == palawan_rx) {
MCG->C1 = /* Clear the IREFS bit to switch to the external reference. */
MCG_C1_CLKS_FLLPLL | /* Use FLL for system clock, MCGCLKOUT. */
MCG_C1_IRCLKEN | /* Enable the internal reference clock. */
MCG_C1_IREFS; /* Use the internal reference clock. */
MCG->C6 = 0; /* PLLS=0: Select FLL as MCG source, not PLL */
}
// Refresh watchdog right before launching app
watchdog_refresh();
// Clear the boot token, so we don't repeatedly enter DFU mode.
boot_token.magic = 0;
boot_token.boot_count++;
asm volatile(
"mov lr, %0 \n\t"
"mov sp, %1 \n\t"
"bx %2 \n\t"
:
: "r"(0xFFFFFFFF),
"r"(appVectors[0]),
"r"(appVectors[1]));
while (1)
;
}
__attribute__((noreturn)) void bootloader_main(void)
{
if (should_enter_bootloader())
{
boot_token.magic = 0;
boot_token.boot_count = 0;
spiInit();
radioInit();
if (palawanModel() == palawan_rx)
/* Start USB */
updateRx();
else if (palawanModel() == palawan_tx)
updateTx();
}
boot_app();
}
| 2.15625 | 2 |
2024-11-18T21:06:35.989884+00:00 | 2014-05-18T15:42:54 | 1a506983be633aba65dba7ecc94381ffcc8dc5c8 | {
"blob_id": "1a506983be633aba65dba7ecc94381ffcc8dc5c8",
"branch_name": "refs/heads/master",
"committer_date": "2014-05-18T15:42:58",
"content_id": "9604006a1bc36b8fbb4f6651d78effd4e06845fc",
"detected_licenses": [
"MIT"
],
"directory_id": "2193a3d5c821b01ec6485b5fd04dc9b5d4ea318e",
"extension": "c",
"filename": "symspace.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 19913985,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12936,
"license": "MIT",
"license_type": "permissive",
"path": "/symspace.c",
"provenance": "stackv2-0128.json.gz:80126",
"repo_name": "OS2World/DEV-FORTRAN-UTIL-ftnchek",
"revision_date": "2014-05-18T15:42:54",
"revision_id": "6a0369cb369312d7f4cfc96c6ce27a28e28acfd5",
"snapshot_id": "00dfde1972899cfc390724fbda4a96f7721a781a",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/OS2World/DEV-FORTRAN-UTIL-ftnchek/6a0369cb369312d7f4cfc96c6ce27a28e28acfd5/symspace.c",
"visit_date": "2020-05-20T13:37:13.913840"
} | stackv2 | /* $Id: symspace.c,v 1.6 2001/11/03 00:55:37 moniot Rel $
Routines to allocate various symbol table-related items.
Copyright (c) 2001 by Robert K. Moniot.
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.
Acknowledgement: the above permission notice is what is known
as the "MIT License."
*/
#include <stdio.h>
#include <string.h>
#include "ftnchek.h"
#include "symtab.h"
#include "symspace.h"
#include "symutils.h"
PROTO(PRIVATE TokenListHeader * new_tokhead,( void ));
PRIVATE StrSpace *
curr_loc_strspace; /* Ptr to current local string space struct */
PRIVATE StrSpace *
curr_srctextspace; /* Ptr to current token string space struct */
PRIVATE ParamInfoSpace *
curr_paraminfospace; /* Ptr to current param info space struct */
PRIVATE TokHeadSpace *
curr_tokheadspace; /* Ptr to current TokHeadSpace struct */
PRIVATE TokenSpace *
curr_tokspace; /* Ptr to current TokenSpace struct */
PRIVATE PtrSpace *
curr_ptrspace; /* Ptr to current PtrSpace struct */
void
init_globals(VOID) /* Clears the global symbol table */
{
glob_symtab_top = 0; /* Neither of these stmts is really needed. */
glob_strings_used = 0;
/* local strings are now permanently stored */
curr_loc_strspace = &lstrspace;
loc_str_top = 0;
extra_locstrspace = 0;
}/*init_globals*/
void
init_symtab(VOID) /* Clears the local symbol table */
{
int i,h;
/* Define factor equal to ratio of time to clear hashtable
entry by looking up in symbol table to time to clear it
directly. This factor is used to choose the method
of clearing out the hashtab.
*/
#ifndef HINITFACTOR
#define HINITFACTOR 20
#endif
/* Clear the hash table of local symbol refs */
if( loc_symtab_top < HASHSZ/HINITFACTOR ) {
/* few local symbols: look them up in symtab */
for(i=0; i<loc_symtab_top; i++) {
h=hash_lookup(loc_symtab[i].name);
hashtab[h].loc_symtab = NULL;
hashtab[h].com_loc_symtab = NULL;
}
}
else {
/* many local symbols: skip lookup, sweep hashtable */
for(h=0;h<HASHSZ;h++) {
hashtab[h].loc_symtab = NULL;
hashtab[h].com_loc_symtab = NULL;
}
}
loc_symtab_top = 0; /* Clear local symtab */
curr_srctextspace = &srctextspace;
srctextspace_top = 0; /* Reset storage area for token text */
extra_srctextspace = 0;
curr_tokspace = &tokspace;
token_space_top = 0; /* Reset storage for tokens in lists & trees */
extra_tokspace = 0;
curr_paraminfospace = ¶minfospace;
param_info_space_top = 0;/* Reset storage for parameter info structs */
extra_paraminfospace = 0;
curr_tokheadspace = &tokheadspace;
token_head_space_top = 0;/* Reset storage for tokenlist headers */
extra_tokheadspace = 0;
curr_ptrspace = &ptrspace;
ptrspace_top = 0; /* Reset storage for array dim textvecs */
extra_ptrspace = 0;
parameter_count = 0;
/* Restores implicit typing to default values.
Note: 27 is '$', 28 is '_' which are default REAL */
{
int c;
for( c=0; c<=('Z'-'A'+2); c++ ) {
implicit_type[c] = type_REAL;
implicit_size[c] = size_DEFAULT;
implicit_len_text[c] = NULL;
}
for( c='I'-'A'; c <= 'N'-'A'; c++ )
implicit_type[c] = type_INTEGER;
}
init_labtable(); /* Clear out label table */
}/*init_symtab*/
TokenListHeader * /* Initializes a tokenlist header */
#if HAVE_STDC
make_TL_head(Token *t)
#else /* K&R style */
make_TL_head(t)
Token *t;
#endif /* HAVE_STDC */
{
TokenListHeader *TH_ptr;
TH_ptr = new_tokhead();
TH_ptr->line_num = t->line_num;
TH_ptr->top_line_num = (current_filename == top_filename?
t->line_num: top_file_line_num);
TH_ptr->filename = current_filename;
/* Clear all the flags */
TH_ptr->external_decl = FALSE;
TH_ptr->actual_arg = FALSE;
TH_ptr->tokenlist = NULL;
TH_ptr->next = NULL;
return TH_ptr;
}
PRIVATE TokenListHeader *
new_tokhead(VOID)
{
if(token_head_space_top == TOKHEADSPACESZ) {
if(curr_tokheadspace->next == (TokHeadSpace *)NULL) {
TokHeadSpace *new_tokheadspace;
if( (new_tokheadspace = (TokHeadSpace *)malloc(sizeof(TokHeadSpace)))
== (TokHeadSpace *)NULL) {
oops_message(OOPS_FATAL,line_num,NO_COL_NUM,
"Cannot alloc space for token list header");
return (TokenListHeader *)NULL; /*NOTREACHED*/
}
else {
new_tokheadspace->next = (TokHeadSpace *)NULL;
curr_tokheadspace->next = new_tokheadspace;
}
}
curr_tokheadspace = curr_tokheadspace->next;
extra_tokheadspace += TOKHEADSPACESZ;
token_head_space_top = 0;
}
return curr_tokheadspace->tokheadspace + token_head_space_top++;
}
/* this routine allocates room in global stringspace
(top down) for string s, and copies it there. */
char *
#if HAVE_STDC
new_global_string(char *s)
#else /* K&R style */
new_global_string(s)
char *s;
#endif /* HAVE_STDC */
{
static unsigned long glob_str_bot = 0;
static char *glob_strspace;
unsigned count = strlen(s) + 1;/* no. of chars needed including final nul */
glob_strings_used += count; /* keep track for -resource */
if(glob_str_bot < count) {
unsigned long numalloc = (count > STRSPACESZ? count: STRSPACESZ);
glob_strspace = (char *)calloc(numalloc,sizeof(char));
if(glob_strspace == (char *)NULL) {
oops_message(OOPS_FATAL,line_num,NO_COL_NUM,
"Cannot alloc space for global strings");
return (char *)NULL; /*NOTREACHED*/
}
glob_str_bot = numalloc;
}
glob_str_bot -= count; /*pre-decrement*/
return strcpy(glob_strspace+glob_str_bot,s);
}/*new_global_string*/
/* Allocate space for string s in local string space
(bottom up), and copy it there. */
char *
#if HAVE_STDC
new_local_string(char *s)
#else /* K&R style */
new_local_string(s)
char *s;
#endif /* HAVE_STDC */
{
int count = strlen(s) + 1; /* No. of chars needed including final nul */
int orig_top = loc_str_top;
loc_str_top += count;
if(loc_str_top > STRSPACESZ) {
StrSpace *new_loc_strspace;
new_loc_strspace = (StrSpace *)malloc(sizeof(StrSpace));
if(new_loc_strspace == (StrSpace *)NULL) {
oops_message(OOPS_FATAL,line_num,NO_COL_NUM,
"Cannot alloc space for local strings");
return (char *)NULL; /*NOTREACHED*/
}
else {
new_loc_strspace->next = (StrSpace *)NULL;
curr_loc_strspace->next = new_loc_strspace;
}
curr_loc_strspace = curr_loc_strspace->next;
extra_locstrspace += orig_top; /* Remember amount used so far */
orig_top = 0;
loc_str_top = count;
}
return strcpy(curr_loc_strspace->strspace+orig_top,s);
}/* new_local_string */
ParamInfo *
new_param_info(VOID) /* Allocates space for parameter info field */
{
if(param_info_space_top == PARAMINFOSPACESZ) {
if(curr_paraminfospace->next == (ParamInfoSpace *)NULL) {
ParamInfoSpace *new_paraminfospace;
if( (new_paraminfospace = (ParamInfoSpace *)malloc(sizeof(ParamInfoSpace)))
== (ParamInfoSpace *)NULL) {
oops_message(OOPS_FATAL,line_num,NO_COL_NUM,
"Cannot alloc space for parameter info");
return (ParamInfo *)NULL; /*NOTREACHED*/
}
else {
new_paraminfospace->next = (ParamInfoSpace *)NULL;
curr_paraminfospace->next = new_paraminfospace;
}
}
curr_paraminfospace = curr_paraminfospace->next;
extra_paraminfospace += PARAMINFOSPACESZ;
param_info_space_top = 0;
}
return curr_paraminfospace->paraminfospace + param_info_space_top++;
}
void
#if HAVE_STDC
free_textvec(char **p) /*ARGSUSED0*/
#else /* K&R style */
free_textvec(p) /*ARGSUSED0*/
char **p;
#endif /* HAVE_STDC */
{
/* No action necessary since all the space is freed in
a lump at end of processing module */
}
char **
#if HAVE_STDC
new_textvec(int n) /* Allocates space for array of n char ptrs */
#else /* K&R style */
new_textvec(n) /* Allocates space for array of n char ptrs */
int n;
#endif /* HAVE_STDC */
{
int orig_top = ptrspace_top;
ptrspace_top += n;
if( ptrspace_top > PTRSPACESZ) {
if(curr_ptrspace->next == (PtrSpace *)NULL) {
PtrSpace *new_ptrspace;
if( (new_ptrspace = (PtrSpace *)malloc(sizeof(PtrSpace)))
== (PtrSpace *)NULL) {
oops_message(OOPS_FATAL,line_num,NO_COL_NUM,
"Cannot alloc space for pointers to text");
return (char **)NULL; /*NOTREACHED*/
}
else {
new_ptrspace->next = (PtrSpace *)NULL;
curr_ptrspace->next = new_ptrspace;
}
}
curr_ptrspace = curr_ptrspace->next;
extra_ptrspace += orig_top;
orig_top = 0;
ptrspace_top = n;
}
return curr_ptrspace->ptrspace + orig_top;
}
/* Routine to allocate space for
a string containing source text
of a token. */
char *
#if HAVE_STDC
new_src_text_alloc(int size)
/* length counting nul */
#else /* K&R style */
new_src_text_alloc(size)
int size; /* length counting nul */
#endif /* HAVE_STDC */
{
int orig_top = srctextspace_top;
srctextspace_top += size;
if(srctextspace_top > STRSPACESZ) {
StrSpace *new_srctextspace;
new_srctextspace = (StrSpace *)malloc(sizeof(StrSpace));
if(new_srctextspace == (StrSpace *)NULL) {
oops_message(OOPS_FATAL,line_num,col_num,
"Cannot alloc space for token text");
return (char *)NULL; /*NOTREACHED*/
}
else {
new_srctextspace->next = (StrSpace *)NULL;
curr_srctextspace->next = new_srctextspace;
}
curr_srctextspace = curr_srctextspace->next;
extra_srctextspace += orig_top; /* Remember amount used so far */
orig_top = 0;
srctextspace_top = size;
}
return curr_srctextspace->strspace + orig_top;
}
/* Tokens that are 1 char long have their
src_text stored in this array, indexed
by their codes. Avoids duplication of
strings, wasting space.
*/
PRIVATE char onechar_text[2*(MAX_CHAR_CODE+1)];
/* Routine to get space for string
containing source text of token
and copy it to there.
*/
char *
#if HAVE_STDC
new_src_text(const char *s, int len)
/* string (final nul not needed) */
/* length not counting nul */
#else /* K&R style */
new_src_text(s,len)
char *s; /* string (final nul not needed) */
int len; /* length not counting nul */
#endif /* HAVE_STDC */
{
int i;
char *new_s;
/* If it is a single char, it goes
into the special array. Otherwise
allocate space for it. */
if(len <= 1)
new_s = &onechar_text[s[0]*2];
else
new_s = new_src_text_alloc(len+1);
for(i=0; i<len; i++) /* copy string to new space */
new_s[i] = s[i];
new_s[i] = '\0';
return new_s;
}
/* Copy expr token src text into local stringspace. */
#define MAXTREETEXT (20*72+1) /* Enough space for any f77 expression. */
PRIVATE char tree_text_space[MAXTREETEXT];
char *
#if HAVE_STDC
new_tree_text(Token *t)
#else /* K&R style */
new_tree_text(t)
Token *t;
#endif /* HAVE_STDC */
{
(void) cp_tree_src_text(tree_text_space, t, MAXTREETEXT-1);
return new_local_string(tree_text_space);
}
Token *
new_token(VOID) /* Returns pointer to space for a token */
{
if(token_space_top == TOKENSPACESZ) {
/* When token space is used up, go to the next. If none, then
allocate a new one. The memory is never deallocated, since
it will likely be needed again later. So token space structs
are linked into a list. */
if(curr_tokspace->next == (TokenSpace *)NULL) {
TokenSpace *new_tokspace;
if( (new_tokspace = (TokenSpace *)malloc(sizeof(TokenSpace)))
== (TokenSpace *)NULL) {
oops_message(OOPS_FATAL,line_num,NO_COL_NUM,
"Cannot alloc space for tokens");
return (Token *)NULL; /*NOTREACHED*/
}
else {
new_tokspace->next = (TokenSpace *)NULL;
curr_tokspace->next = new_tokspace;
}
}
curr_tokspace = curr_tokspace->next;
extra_tokspace += TOKENSPACESZ; /* Keep track of how much for -resource */
token_space_top = 0;
}
return curr_tokspace->tokenspace + token_space_top++;
}
| 2.046875 | 2 |
2024-11-18T21:06:36.762607+00:00 | 2023-08-31T05:50:29 | bea6e6688fd80dd1464c95e9728e09b4fb4a3bed | {
"blob_id": "bea6e6688fd80dd1464c95e9728e09b4fb4a3bed",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T05:50:29",
"content_id": "36600b25aa1d1bb857d3c4dfbcadd7401bba7964",
"detected_licenses": [
"MIT"
],
"directory_id": "79d343002bb63a44f8ab0dbac0c9f4ec54078c3a",
"extension": "h",
"filename": "prfchiintrin.h",
"fork_events_count": 2399,
"gha_created_at": "2015-08-06T00:51:28",
"gha_event_created_at": "2023-09-14T21:09:50",
"gha_language": "Zig",
"gha_license_id": "MIT",
"github_id": 40276274,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2073,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/include/prfchiintrin.h",
"provenance": "stackv2-0128.json.gz:80257",
"repo_name": "ziglang/zig",
"revision_date": "2023-08-31T05:50:29",
"revision_id": "f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c",
"snapshot_id": "4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5",
"src_encoding": "UTF-8",
"star_events_count": 25560,
"url": "https://raw.githubusercontent.com/ziglang/zig/f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c/lib/include/prfchiintrin.h",
"visit_date": "2023-08-31T13:16:45.980913"
} | stackv2 | /*===---- prfchiintrin.h - PREFETCHI intrinsic -----------------------------===
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===-----------------------------------------------------------------------===
*/
#ifndef __PRFCHIINTRIN_H
#define __PRFCHIINTRIN_H
#ifdef __x86_64__
/* Define the default attributes for the functions in this file. */
#define __DEFAULT_FN_ATTRS \
__attribute__((__always_inline__, __nodebug__, __target__("prefetchi")))
/// Loads an instruction sequence containing the specified memory address into
/// all level cache.
///
/// Note that the effect of this intrinsic is dependent on the processor
/// implementation.
///
/// \headerfile <x86intrin.h>
///
/// This intrinsic corresponds to the \c PREFETCHIT0 instruction.
///
/// \param __P
/// A pointer specifying the memory address to be prefetched.
static __inline__ void __DEFAULT_FN_ATTRS
_m_prefetchit0(volatile const void *__P) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-qual"
__builtin_ia32_prefetchi((const void *)__P, 3 /* _MM_HINT_T0 */);
#pragma clang diagnostic pop
}
/// Loads an instruction sequence containing the specified memory address into
/// all but the first-level cache.
///
/// Note that the effect of this intrinsic is dependent on the processor
/// implementation.
///
/// \headerfile <x86intrin.h>
///
/// This intrinsic corresponds to the \c PREFETCHIT1 instruction.
///
/// \param __P
/// A pointer specifying the memory address to be prefetched.
static __inline__ void __DEFAULT_FN_ATTRS
_m_prefetchit1(volatile const void *__P) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-qual"
__builtin_ia32_prefetchi((const void *)__P, 2 /* _MM_HINT_T1 */);
#pragma clang diagnostic pop
}
#endif /* __x86_64__ */
#undef __DEFAULT_FN_ATTRS
#endif /* __PRFCHWINTRIN_H */
| 2.046875 | 2 |
2024-11-18T21:06:37.466306+00:00 | 2019-03-06T14:35:06 | 417fc7bad60c07152d80cb41a9af8e59739b81e0 | {
"blob_id": "417fc7bad60c07152d80cb41a9af8e59739b81e0",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-06T14:35:06",
"content_id": "672f7a8bafe8074e0d3bebd831061ed2c053b7ca",
"detected_licenses": [
"MIT"
],
"directory_id": "97c2a634d660310cae25db65900ba9cab0748923",
"extension": "h",
"filename": "vector.h",
"fork_events_count": 0,
"gha_created_at": "2018-03-06T16:43:31",
"gha_event_created_at": "2018-05-18T13:13:51",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 124108256,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 391,
"license": "MIT",
"license_type": "permissive",
"path": "/L2/S1/type_abstrait/TP2/vector.h",
"provenance": "stackv2-0128.json.gz:80775",
"repo_name": "ZeCroque/study-uppa",
"revision_date": "2019-03-06T14:35:06",
"revision_id": "94b902eaeb6ffe78a28a2bab3581ce017f51bc92",
"snapshot_id": "7a100db6efc30650fa1cbb0915837331b06fa98f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ZeCroque/study-uppa/94b902eaeb6ffe78a28a2bab3581ce017f51bc92/L2/S1/type_abstrait/TP2/vector.h",
"visit_date": "2021-04-26T22:32:00.275041"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
typedef int Elt;
typedef struct cellule
{
Elt elem;
int pos;
struct cellule* suivant;
} Cellule;
typedef Cellule* Vector;
int taille(Vector v);
Vector vide();
void inserer(Vector* v, int pos, Elt element);
Vector modifier(Vector v, int pos, Elt element);
Vector supprimer(Vector* v, int pos);
Elt ieme(Vector v, int pos);
int estVide(Vector v);
| 2.484375 | 2 |
2024-11-18T21:06:37.762466+00:00 | 2021-01-09T15:26:52 | 06fb08dc380f8353c02ad496997cfd7564ea3d8e | {
"blob_id": "06fb08dc380f8353c02ad496997cfd7564ea3d8e",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-09T15:26:52",
"content_id": "41e3b2514672bb24932cd310701897e69942d24c",
"detected_licenses": [
"MIT"
],
"directory_id": "b2bcccd7556c74e56297b5df3a99c503ef667b1f",
"extension": "c",
"filename": "Curso Exercício 26.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 302115820,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 241,
"license": "MIT",
"license_type": "permissive",
"path": "/Programas do Curso da Udemy/Curso Exercício 26.c",
"provenance": "stackv2-0128.json.gz:81165",
"repo_name": "carvalhopedro22/Programas-em-C-cursos-e-geral",
"revision_date": "2021-01-09T15:26:52",
"revision_id": "5c8c74101113ea9b9d05fabc113adf774b4a5d35",
"snapshot_id": "f5bee52c288f052a6e6d9e493b8141fc00130ed3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/carvalhopedro22/Programas-em-C-cursos-e-geral/5c8c74101113ea9b9d05fabc113adf774b4a5d35/Programas do Curso da Udemy/Curso Exercício 26.c",
"visit_date": "2023-02-15T07:54:02.639722"
} | stackv2 | #include <stdio.h>
int main(void) {
int numero, soma = 0;
for(int i = 0; i < 10; i ++){
printf("Digite um numero \n");
scanf("%d",&numero);
soma = soma + numero;
}
printf("A soma dos valores é %d \n",soma);
return 0;
} | 3.5 | 4 |
2024-11-18T21:06:37.818805+00:00 | 2020-06-29T20:19:57 | c473468faa892b1d9269aa548f78002d2824b4ad | {
"blob_id": "c473468faa892b1d9269aa548f78002d2824b4ad",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-29T20:19:57",
"content_id": "fa094d6f403751701139ff7651545599a3ae9d7b",
"detected_licenses": [
"MIT"
],
"directory_id": "1e5468c77999214a0496990576d6240e9b1839e4",
"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": 1079,
"license": "MIT",
"license_type": "permissive",
"path": "/fw/chaac/apps/blinky_usb/src/main.c",
"provenance": "stackv2-0128.json.gz:81295",
"repo_name": "nullvoid121/chaac",
"revision_date": "2020-06-29T20:19:57",
"revision_id": "a2e9d51c4bd75330f9a2defa154870d3f52f701c",
"snapshot_id": "e6299cf0998d9ea89c4aa1e44154ed695153cb68",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nullvoid121/chaac/a2e9d51c4bd75330f9a2defa154870d3f52f701c/fw/chaac/apps/blinky_usb/src/main.c",
"visit_date": "2022-11-07T08:53:42.656555"
} | stackv2 | #include <assert.h>
#include <string.h>
#include "sysinit/sysinit.h"
#include "os/os.h"
#include "console/console.h"
#include "bsp/bsp.h"
#include "hal/hal_gpio.h"
#define BLINK_TASK_PRI (99)
#define BLINK_STACK_SIZE (1024)
struct os_task blink_task;
os_stack_t blink_task_stack[BLINK_STACK_SIZE];
void blink_task_fn(void *arg) {
uint8_t count = 0;
hal_gpio_init_out(LED1_PIN, 0);
hal_gpio_init_out(LED2_PIN, 0);
while(1) {
os_time_delay(OS_TICKS_PER_SEC/4);
if (count & 1) {
hal_gpio_toggle(LED1_PIN);
}
if (count & 2) {
hal_gpio_toggle(LED2_PIN);
}
console_printf("%d\n", count);
count++;
}
}
int
main(int argc, char **argv)
{
sysinit();
os_task_init(
&blink_task,
"blink_task",
blink_task_fn,
NULL,
BLINK_TASK_PRI,
OS_WAIT_FOREVER,
blink_task_stack,
BLINK_STACK_SIZE);
while(1) {
os_eventq_run(os_eventq_dflt_get());
}
assert(0);
return 0;
}
| 2.40625 | 2 |
2024-11-18T21:06:37.955507+00:00 | 2023-08-07T20:50:54 | 171fea839d84bc749f7c145635b3e5fbf7f6cb41 | {
"blob_id": "171fea839d84bc749f7c145635b3e5fbf7f6cb41",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-07T20:50:54",
"content_id": "f3aa5088e7522c2c848fab3e558a3939b84a6376",
"detected_licenses": [
"MIT"
],
"directory_id": "d8c8f4148940cd9c93bb0692af8c5004f47af05e",
"extension": "c",
"filename": "XmpEntry-A.c",
"fork_events_count": 14,
"gha_created_at": "2023-06-11T06:54:24",
"gha_event_created_at": "2023-06-28T15:55:29",
"gha_language": "C",
"gha_license_id": null,
"github_id": 652124068,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4940,
"license": "MIT",
"license_type": "permissive",
"path": "/xUSL/XMP/Ver-A/XmpEntry-A.c",
"provenance": "stackv2-0128.json.gz:81551",
"repo_name": "openSIL/openSIL",
"revision_date": "2023-08-07T20:50:54",
"revision_id": "0f39fbc2454af9a67fc84a88093bcd2f2c8dd887",
"snapshot_id": "92213cc94dd4c6d6c43fedeaedd96537001e182f",
"src_encoding": "UTF-8",
"star_events_count": 233,
"url": "https://raw.githubusercontent.com/openSIL/openSIL/0f39fbc2454af9a67fc84a88093bcd2f2c8dd887/xUSL/XMP/Ver-A/XmpEntry-A.c",
"visit_date": "2023-08-19T11:48:14.911453"
} | stackv2 | /* Copyright 2021-2023 Advanced Micro Devices, Inc. All rights reserved. */
// SPDX-License-Identifier: MIT
/**
* @file
* This file contains the Example (Xmp) IPclass init code.
* > > > > EXAMPLE FILE < < < <
* This file is an EXAMPLE to the module owner for which to pattern
* their actual init procedures.
*
* This file holds the revision specific data and procedures for
* the IP revision 'A'. These are used by the IpBlkFxxMxx.c files
* for declaring the IP entry routines for the SoC.
*
* This file is NOT Host visible - meaning it is not included or
* referenced from Host code.
*/
#include <SilCommon.h>
#include <XmpRevA-api.h>
#include <XmpClass.h>
#include <XmpIp2Ip.h>
#include <XmpCommon.h>
#include <XmpCmn2Rev.h>
/* prototype for forward references */
/*********** Section for the IP Block List table functions *************/
extern XmpDataRevA DefaultsRevA;
/**
* @brief Set the Input Block(s) for the device
* @details This function is called by the openSIL core so that the IP can
* establish the memory resident data block(s) it needs to operate.
*
* @param none
* @return SIL_STATUS
*/
SIL_STATUS
XmpSetInputBlockRevATp1 ( void )
{
SIL_STATUS Status = SilPass;
XUSL_TRACEPOINT (SIL_TRACE_ENTRY, "\n");
// Body of XMP Init routines
// Call the common routine, passing pointer to the RevA specific data
Status = XmpCmnSetInputBlk ( (uint8_t *)&DefaultsRevA, sizeof(DefaultsRevA) );
XUSL_TRACEPOINT (SIL_TRACE_EXIT, "\n");
return Status;
};
/* Note the TP2 and TP3 version of SetInputBlock are no-ops */
/**----------------------------------------------------------------------
* @brief Primary TP1 Initialize for the Example (XMP) device
* @details This function initializes the XMP silicon block.
*
* This is an IP private function, not visible to the Host
*
* In this example, the 'initializeIp' routine is specific to each IP revision.
* There is one entry point routine per revision and it is these revision
* specific routines that are listed in the SoC IP Block list file(s).
*
* @param none
* @return SIL_STATUS
* @retval SilPass - everything is OK
* @retval SilAbort - Something went wrong
*/
SIL_STATUS
XmpInitializeRevATp1 ( void )
{
XMPCLASS_INPUT_BLK *LclInpBlk; // Local var to hold pointer to input blk
SIL_STATUS Status = SilPass;
XUSL_TRACEPOINT (SIL_TRACE_ENTRY, "\n");
LclInpBlk = (XMPCLASS_INPUT_BLK *)SilFindStructure( SilId_XmpClass, 0); //Instance 0
XUSL_TRACEPOINT (SIL_TRACE_INFO, "openSIL XMP found blk at: 0x%x \n", LclInpBlk);
if (LclInpBlk == NULL) {
// Coult not find the IP input block
return SilNotFound;
}
/**********************************
* Body of XMP Init routines
* This is where the IP code is located.
* Use Common routines where ever possible.
**********************************/
// File with actions your IP needs to perform for early Si initialization
/* For this example, the IP will use a common routine to perform the bulk of
* the IP Si init, but will also use a IP Rev specific call to perform
* some Rev A special actions at a certain point in the init sequence.
*/
// Here is the call to the common routine...
Status = XmpCmnFcnSiInit(LclInpBlk);
XUSL_TRACEPOINT (SIL_TRACE_EXIT, "\n");
return Status;
}
/** ----------------------------------------------------------------------
* @brief Secondary TP2 Initialize for the Example (XMP) device
* @details This function initializes the XMP silicon block after the
* PCIe enumeration has xompleted.
*/
SIL_STATUS
XmpInitializeRevATp2 ( void )
{
// Fill with actions your IP needs after PCIe enumeration is completed
return SilPass;
}
/** ----------------------------------------------------------------------
* @brief Terciary TP3 Initialize for the Example (XMP) device
* @details This function initializes the XMP silicon block just before
* the hand-off to the OS.
*/
SIL_STATUS
XmpInitializeRevATp3 ( void )
{
// File with actions your IP needs just before hand-off to the OS
return SilPass;
}
extern XMP_XFER_TABLE XmpCommon2RevAXfer;
extern const XMP_IP2IP_PUBLISHED_FCNS XmpPublicApiRevA;
/**----------------------------------------------------------------------
* @brief Set the APIs for the device
* @details Initialize internal and external APIs for XMP RevA. The external
* API is the Ip2IpApi and the internal is the Common-2-Rev transfer table.
*
* @retval SilPass API initialized successfully
* @retval SilInvalidParameter Id class is invalid
*
*/
SIL_STATUS
XmpInitApiRevA ( void )
{
SIL_STATUS Status;
// Initialize Common to Rev specific transfer table first
Status = SilInitCommon2RevXferTable (SilId_XmpClass, &XmpCommon2RevAXfer);
if (Status != SilPass) {
return Status;
}
// Initialize the openSIL IP-2-IP API
return SilInitIp2IpApi (SilId_XmpClass, (void *)((uintptr_t)&XmpPublicApiRevA));
}
| 2.09375 | 2 |
2024-11-18T21:06:38.125485+00:00 | 2016-08-22T20:40:25 | 8bbcd68cc94e5743355becfa4604ef1c51c6bb00 | {
"blob_id": "8bbcd68cc94e5743355becfa4604ef1c51c6bb00",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-22T20:40:25",
"content_id": "153fb239c9072dc74e0a750d4a3c3fafc3cc3227",
"detected_licenses": [
"MIT"
],
"directory_id": "a4650acfdea4a68d7770700cc955d5ef56d3212f",
"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": 46450288,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 520,
"license": "MIT",
"license_type": "permissive",
"path": "/SoftUni/C Programming/C Data Types-Homework/07-Exchange Variable Values/main.c",
"provenance": "stackv2-0128.json.gz:81809",
"repo_name": "NikolovV/C-Language",
"revision_date": "2016-08-22T20:40:25",
"revision_id": "7e5c4ea26a985dc0807c708abda2cb890377765d",
"snapshot_id": "f901956a6088a4175005bf50d712ab13af5cebfc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NikolovV/C-Language/7e5c4ea26a985dc0807c708abda2cb890377765d/SoftUni/C Programming/C Data Types-Homework/07-Exchange Variable Values/main.c",
"visit_date": "2021-01-10T15:03:09.013636"
} | stackv2 | /*
Declare two integer variables a and b and assign them with 5 and 10
and after that exchange their values by using some programming logic.
Print the variable values before and after the exchange.
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
int a = 5, b = 10;
printf("Now a = %d and b = %d\n", a, b);
printf("Exchanging....\n");
a = a + b;
b = a - b;
a = a - b;
printf("After the exchange a = %d b = %d\n", a, b);
return (EXIT_SUCCESS);
}
| 4.3125 | 4 |
2024-11-18T21:06:39.364780+00:00 | 2021-04-26T23:54:47 | 8da91d5f998bf47607aeffca0759e4fcc3ab06bd | {
"blob_id": "8da91d5f998bf47607aeffca0759e4fcc3ab06bd",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-26T23:54:47",
"content_id": "c165462219fedca01150265dbd5feac8ab6b9337",
"detected_licenses": [
"MIT"
],
"directory_id": "4e0377c4ee0608852d12fc0cbece0e4dd2a6c41b",
"extension": "c",
"filename": "test_spawn.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 206223033,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 610,
"license": "MIT",
"license_type": "permissive",
"path": "/lecture7/test_spawn.c",
"provenance": "stackv2-0128.json.gz:82200",
"repo_name": "csatuic/vscode-lectures",
"revision_date": "2021-04-26T23:54:47",
"revision_id": "0e4a22c58a535484919c0557af47adabdd0e2a30",
"snapshot_id": "0b88fb0adb7974ef70fc092251ff33334a02fa8d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/csatuic/vscode-lectures/0e4a22c58a535484919c0557af47adabdd0e2a30/lecture7/test_spawn.c",
"visit_date": "2023-04-16T00:20:56.289780"
} | stackv2 | #include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
// external symbol that always points to the list of enviornment variables
extern char **environ;
int main(int argc, char **argv) {
char *args[2] = {"/bin/true", 0};
int child_status;
int result;
int iterations = atoi(argv[1]);
for (int i = 0; i < iterations; i++) {
malloc(4096);
}
for (int j = 0; j < 100; j++) {
if (0 != posix_spawn(&result, args[0], NULL, NULL, args, environ)) {
perror("spawn failed");
exit(1);
}
wait(&child_status);
}
} | 2.15625 | 2 |
2024-11-18T21:06:39.464779+00:00 | 2019-05-15T17:32:16 | 477445e358d2c0881f8116434ee9317bbb032b1c | {
"blob_id": "477445e358d2c0881f8116434ee9317bbb032b1c",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-15T17:32:16",
"content_id": "ff176f720891fac6ca87ca1df8deac8610c4aa16",
"detected_licenses": [
"MIT",
"ISC"
],
"directory_id": "64527c06106bd0a0d6a35cc231af8979a926930d",
"extension": "c",
"filename": "analysing_code_test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 163555621,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 20652,
"license": "MIT,ISC",
"license_type": "permissive",
"path": "/tests/analysing_code_test/analysing_code_test.c",
"provenance": "stackv2-0128.json.gz:82331",
"repo_name": "X-CASH-official/XCASH_proof_of_stake_consensus_node",
"revision_date": "2019-05-15T17:32:16",
"revision_id": "ca9c9ae81b2573264237f9fbc767399afb8caabc",
"snapshot_id": "5b8f9a3cda7fb25ed01fb7aaad7cb77142c51b66",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/X-CASH-official/XCASH_proof_of_stake_consensus_node/ca9c9ae81b2573264237f9fbc767399afb8caabc/tests/analysing_code_test/analysing_code_test.c",
"visit_date": "2020-04-14T01:14:34.161146"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "define_macro_functions.h"
#include "define_macros.h"
#include "structures.h"
#include "string_functions.h"
#include "variables_test.h"
#include "analysing_code_test.h"
/*
-----------------------------------------------------------------------------------------------------------
Functions
-----------------------------------------------------------------------------------------------------------
*/
/*
-----------------------------------------------------------------------------------------------------------
Name: analysing_code_test
Description: Test all of the code in the program for the following
All return or exit statements reset all the variables allocated on the heap before they exit the function
All define statments are then undefined at the end of the function
No unsafe string functions are ran in the code
Uninitialized variables are initialized before their code is run
Return: The number of passed analysing_code test
-----------------------------------------------------------------------------------------------------------
*/
int analysing_code_test()
{
// structures
struct uninitialized_variable_data {
char* data[100];
size_t count;
};
struct analysing_code_test_files {
char* data[100];
size_t count;
};
// Variables
char* data = (char*)calloc(BUFFER_SIZE,sizeof(char));
char* data1 = (char*)calloc(BUFFER_SIZE,sizeof(char));
char* data2 = (char*)calloc(BUFFER_SIZE,sizeof(char));
char* data3 = (char*)calloc(BUFFER_SIZE,sizeof(char));
char* data4 = (char*)calloc(BUFFER_SIZE,sizeof(char));
char* data5 = (char*)calloc(BUFFER_SIZE,sizeof(char));
struct uninitialized_variable_data uninitialized_variable_data;
struct analysing_code_test_files analysing_code_test_files;
FILE* file;
size_t analysing_code_test_files_count = 0;
size_t count = 0;
size_t counter = 0;
size_t pointer_reset_all_count = 0;
size_t pointer_reset_all_counter = 0;
size_t define_count = 0;
size_t undefine_count = 0;
size_t uninitialized_variable_counter = 0;
size_t data_count = 0;
size_t data_counter = 0;
size_t return_count = 0;
size_t return_count_total = 0;
size_t string_count = 0;
size_t line_count = 1;
// define macros
#define pointer_reset_all \
free(data); \
data = NULL; \
free(data1); \
data1 = NULL; \
free(data2); \
data2 = NULL; \
free(data3); \
data3 = NULL; \
free(data4); \
data4 = NULL; \
free(data5); \
data5 = NULL;
// check if the memory needed was allocated on the heap successfully
if (data == NULL || data1 == NULL || data2 == NULL || data3 == NULL || data4 == NULL || data5 == NULL)
{
if (data != NULL)
{
pointer_reset(data);
}
if (data1 != NULL)
{
pointer_reset(data1);
}
if (data2 != NULL)
{
pointer_reset(data2);
}
if (data3 != NULL)
{
pointer_reset(data3);
}
if (data4 != NULL)
{
pointer_reset(data4);
}
if (data5 != NULL)
{
pointer_reset(data5);
}
color_print("Could not allocate the memory needed on the heap","red");
exit(0);
}
// reset the variables
memset(data_test,0,strnlen(data_test,BUFFER_SIZE));
count_test = 0;
// initialize the arrays
for (data_count = 0; data_count < 100; data_count++)
{
uninitialized_variable_data.data[data_count] = (char*)calloc(BUFFER_SIZE,sizeof(char));
// check if the memory needed was allocated on the heap successfully
if (uninitialized_variable_data.data[data_count] == NULL)
{
color_print("Could not allocate the memory needed on the heap","red");
exit(0);
}
}
uninitialized_variable_data.count = 0;
for (data_count = 0; data_count < 100; data_count++)
{
analysing_code_test_files.data[data_count] = (char*)calloc(BUFFER_SIZE,sizeof(char));
// check if the memory needed was allocated on the heap successfully
if (analysing_code_test_files.data[data_count] == NULL)
{
color_print("Could not allocate the memory needed on the heap","red");
exit(0);
}
}
memcpy(analysing_code_test_files.data[0],"xcash_proof_of_stake_website_server_test.c",strnlen("xcash_proof_of_stake_website_server_test.c",BUFFER_SIZE));
analysing_code_test_files.count = 1;
data_count = 0;
// run the test
// read the file
for (analysing_code_test_files_count = 0; analysing_code_test_files_count < analysing_code_test_files.count; analysing_code_test_files_count++)
{
memset(data_test,0,strnlen(data_test,BUFFER_SIZE));
line_count = 1;
// check if the file exist
file = fopen(analysing_code_test_files.data[analysing_code_test_files_count],"r");
if (file != NULL)
{
while(fgets(data_test,BUFFER_SIZE,file) != NULL)
{
// check for the function name
if (strstr(data_test,"Name: ") != NULL && strstr(data_test,"\"Name: \"") == NULL)
{
// save the function name
string_replace(data_test, "Name: ", "");
memset(result_test,0,strnlen(result_test,BUFFER_SIZE));
memcpy(result_test,data_test,strnlen(data_test,BUFFER_SIZE));
// reset the counters
count = 0;
counter = 0;
pointer_reset_all_count = 0;
pointer_reset_all_counter = 0;
define_count = 0;
undefine_count = 0;
uninitialized_variable_counter = 0;
data_count = 0;
data_counter = 0;
return_count = 0;
return_count_total = 0;
string_count = 0;
memset(data,0,strnlen(data,BUFFER_SIZE));
// initialize the arrays
for (count = 0; count < 100; count++)
{
uninitialized_variable_data.data[count] = (char*)calloc(BUFFER_SIZE,sizeof(char));
// check if the memory needed was allocated on the heap successfully
if (uninitialized_variable_data.data[count] == NULL)
{
color_print("Could not allocate the memory needed on the heap","red");
exit(0);
}
}
uninitialized_variable_data.count = 0;
count = 0;
printf("Analysing function %s",data_test);
}
// check if the pointer_reset_all has the same amount of resets as malloc or calloc
if ((strstr(data_test,"malloc") != NULL || strstr(data_test,"calloc") != NULL) && (strstr(data_test,".") == NULL))
{
count++;
}
if (strstr(data_test,"#define pointer_reset_all") != NULL)
{
pointer_reset_all_counter = 1;
}
if (pointer_reset_all_counter == 1 && strstr(data_test,"free") != NULL)
{
pointer_reset_all_count++;
}
if (pointer_reset_all_counter == 1 && strncmp(data_test,"\n",BUFFER_SIZE) == 0)
{
pointer_reset_all_counter = 0;
if (count != pointer_reset_all_count)
{
printf("\033[1;31mpointer_reset_all does not contain enough resets\033[0m\n");
}
else
{
printf("\033[1;32mpointer_reset_all does contain enough resets\033[0m\n");
count_test++;
}
}
// check if each return, exit, _exit statement has a pointer_reset_all or all of the pointer_resets
if ((strstr(data_test,"return") != NULL || strstr(data_test,"exit(0);") != NULL || strstr(data_test,"_exit(0);") != NULL) && strstr(data_test,"//") == NULL)
{
// the previous 5 lines should contain either a pointer_reset_all or the same amount of pointer_reset as calloc or malloc
if (((strstr(data1,"pointer_reset_all") != NULL || strstr(data2,"pointer_reset_all") != NULL || strstr(data3,"pointer_reset_all") != NULL || strstr(data4,"pointer_reset_all") != NULL || strstr(data5,"pointer_reset_all") != NULL) && (strstr(data1,"return") == NULL && strstr(data2,"return") == NULL && strstr(data3,"return") == NULL && strstr(data4,"return") == NULL && strstr(data5,"return") == NULL) && (strstr(data1,"exit(0);") == NULL && strstr(data2,"exit(0);") == NULL && strstr(data3,"exit(0);") == NULL && strstr(data4,"exit(0);") == NULL && strstr(data5,"exit(0);") == NULL) && (strstr(data1,"_exit(0);") == NULL && strstr(data2,"_exit(0);") == NULL && strstr(data3,"_exit(0);") == NULL && strstr(data4,"_exit(0);") == NULL && strstr(data5,"_exit(0);") == NULL)) || ((strstr(data1,"}") != NULL || strstr(data2,"}") != NULL || strstr(data3,"}") != NULL || strstr(data4,"}") != NULL || strstr(data5,"}") != NULL)))
{
return_count++;
}
else
{
if (((strstr(data1,"pointer_reset(") != NULL) && (strstr(data1,"return") == NULL && strstr(data2,"return") == NULL && strstr(data3,"return") == NULL && strstr(data4,"return") == NULL && strstr(data5,"return") == NULL) && (strstr(data1,"exit(0);") == NULL && strstr(data2,"exit(0);") == NULL && strstr(data3,"exit(0);") == NULL && strstr(data4,"exit(0);") == NULL && strstr(data5,"exit(0);") == NULL) && (strstr(data1,"_exit(0);") == NULL && strstr(data2,"_exit(0);") == NULL && strstr(data3,"_exit(0);") == NULL && strstr(data4,"_exit(0);") == NULL && strstr(data5,"_exit(0);") == NULL)) || ((strstr(data1,"}") != NULL || strstr(data2,"}") != NULL || strstr(data3,"}") != NULL || strstr(data4,"}") != NULL || strstr(data5,"}") != NULL)))
{
counter++;
}
if (((strstr(data2,"pointer_reset(") != NULL) && (strstr(data1,"return") == NULL && strstr(data2,"return") == NULL && strstr(data3,"return") == NULL && strstr(data4,"return") == NULL && strstr(data5,"return") == NULL) && (strstr(data1,"exit(0);") == NULL && strstr(data2,"exit(0);") == NULL && strstr(data3,"exit(0);") == NULL && strstr(data4,"exit(0);") == NULL && strstr(data5,"exit(0);") == NULL) && (strstr(data1,"_exit(0);") == NULL && strstr(data2,"_exit(0);") == NULL && strstr(data3,"_exit(0);") == NULL && strstr(data4,"_exit(0);") == NULL && strstr(data5,"_exit(0);") == NULL)) || ((strstr(data1,"}") != NULL || strstr(data2,"}") != NULL || strstr(data3,"}") != NULL || strstr(data4,"}") != NULL || strstr(data5,"}") != NULL)))
{
counter++;
}
if (((strstr(data3,"pointer_reset(") != NULL) && (strstr(data1,"return") == NULL && strstr(data2,"return") == NULL && strstr(data3,"return") == NULL && strstr(data4,"return") == NULL && strstr(data5,"return") == NULL) && (strstr(data1,"exit(0);") == NULL && strstr(data2,"exit(0);") == NULL && strstr(data3,"exit(0);") == NULL && strstr(data4,"exit(0);") == NULL && strstr(data5,"exit(0);") == NULL) && (strstr(data1,"_exit(0);") == NULL && strstr(data2,"_exit(0);") == NULL && strstr(data3,"_exit(0);") == NULL && strstr(data4,"_exit(0);") == NULL && strstr(data5,"_exit(0);") == NULL)) || ((strstr(data1,"}") != NULL || strstr(data2,"}") != NULL || strstr(data3,"}") != NULL || strstr(data4,"}") != NULL || strstr(data5,"}") != NULL)))
{
counter++;
}
if (((strstr(data4,"pointer_reset(") != NULL) && (strstr(data1,"return") == NULL && strstr(data2,"return") == NULL && strstr(data3,"return") == NULL && strstr(data4,"return") == NULL && strstr(data5,"return") == NULL) && (strstr(data1,"exit(0);") == NULL && strstr(data2,"exit(0);") == NULL && strstr(data3,"exit(0);") == NULL && strstr(data4,"exit(0);") == NULL && strstr(data5,"exit(0);") == NULL) && (strstr(data1,"_exit(0);") == NULL && strstr(data2,"_exit(0);") == NULL && strstr(data3,"_exit(0);") == NULL && strstr(data4,"_exit(0);") == NULL && strstr(data5,"_exit(0);") == NULL)) || ((strstr(data1,"}") != NULL || strstr(data2,"}") != NULL || strstr(data3,"}") != NULL || strstr(data4,"}") != NULL || strstr(data5,"}") != NULL)))
{
counter++;
}
if (((strstr(data5,"pointer_reset(") != NULL) && (strstr(data1,"return") == NULL && strstr(data2,"return") == NULL && strstr(data3,"return") == NULL && strstr(data4,"return") == NULL && strstr(data5,"return") == NULL) && (strstr(data1,"exit(0);") == NULL && strstr(data2,"exit(0);") == NULL && strstr(data3,"exit(0);") == NULL && strstr(data4,"exit(0);") == NULL && strstr(data5,"exit(0);") == NULL) && (strstr(data1,"_exit(0);") == NULL && strstr(data2,"_exit(0);") == NULL && strstr(data3,"_exit(0);") == NULL && strstr(data4,"_exit(0);") == NULL && strstr(data5,"_exit(0);") == NULL)) || ((strstr(data1,"}") != NULL || strstr(data2,"}") != NULL || strstr(data3,"}") != NULL || strstr(data4,"}") != NULL || strstr(data5,"}") != NULL)))
{
counter++;
}
if (counter == count)
{
return_count++;
}
else if (counter != count)
{
printf("\033[1;31mreturn statement has not reset all variables allocated on the heap at line %zu \033[0m\n",line_count);
}
counter = 0;
}
return_count_total++;
}
// check if each define statment in the function is undef at the end of the function
if (strstr(data_test,"#define") != NULL)
{
define_count++;
}
if (strstr(data_test,"#undef") != NULL)
{
undefine_count++;
}
if (memcmp(data_test,"}",1) == 0)
{
if (define_count != undefine_count)
{
printf("\033[1;31mAll define statments are not undefined at the end of the function\033[0m\n");
}
else
{
printf("\033[1;32mAll define statments are undefined at the end of the function\033[0m\n");
count_test++;
}
// check if any variables have been uninitialized and have ran in the code
for (data_count = 0; data_count < uninitialized_variable_data.count; data_count++)
{
if (memcmp(uninitialized_variable_data.data[data_count],"0",1) != 0)
{
printf("\033[1;31mVariable %s is run in code and not initialized\033[0m\n",uninitialized_variable_data.data[data_count]);
}
else
{
data_counter++;
}
}
if (data_counter == uninitialized_variable_data.count)
{
printf("\033[1;32mAll variables are initialized before they are ran in the code\033[0m\n");
count_test++;
}
// check if any return or exit statements have not reset all variables allocated on the heap
if (return_count == return_count_total)
{
printf("\033[1;32mAll return or exit statements have reset all variables allocated on the heap\033[0m\n");
count_test++;
}
// check if no unsafe string functions are ran in the code
if (string_count == 0)
{
printf("\033[1;32mNo unsafe string functions are ran in the code\033[0m\n");
count_test++;
}
// reset the arrays
for (count = 0; count < 100; count++)
{
pointer_reset(uninitialized_variable_data.data[count]);
}
uninitialized_variable_data.count = 0;
count = 0;
}
// check for unsafe functions
if ((strstr(data_test,"strcmp") != NULL || strstr(data_test,"strcpy") != NULL || strstr(data_test,"strcat") != NULL || strstr(data_test,"sprintf") != NULL || strstr(data_test,"strlen") != NULL) && (strstr(data_test,"\"strcmp\"") == NULL && strstr(data_test,"\"strcpy\"") == NULL && strstr(data_test,"\"strcat\"") == NULL && strstr(data_test,"\"sprintf\"") == NULL && strstr(data_test,"\"strlen\"") == NULL))
{
printf("\033[1;31mUnsafe string function at line %zu \033[0m\n",line_count);
string_count++;
}
// check to see if variables that are uninitialized are initialized before their code is run
if (strstr(data_test,"// Variables") != NULL && strstr(data_test,"\"// Variables\"") == NULL)
{
uninitialized_variable_counter = 1;
}
else if (uninitialized_variable_counter == 1 && (strstr(data_test,"=") == NULL && strstr(data_test,"malloc") == NULL && strstr(data_test,"calloc") == NULL && strstr(data_test,"struct") == NULL) && strncmp(data_test,"\n",BUFFER_SIZE) != 0)
{
string_replace(data_test,"(char*)malloc(BUFFER_SIZE)","");
string_replace(data_test,"(char*)calloc(BUFFER_SIZE,sizeof(char))","");
string_replace(data_test,"=","");
string_replace(data_test,"[BUFFER_SIZE]","");
string_replace(data_test,"FILE*","");
string_replace(data_test,"char*","");
string_replace(data_test,"char","");
string_replace(data_test,"int","");
string_replace(data_test,"size_t","");
string_replace(data_test," ","");
string_replace(data_test,"\n","");
string_replace(data_test,";","");
memcpy(uninitialized_variable_data.data[uninitialized_variable_data.count],data_test,strnlen(data_test,BUFFER_SIZE));
uninitialized_variable_data.count++;
}
if (uninitialized_variable_counter == 1 && strncmp(data_test,"\n",BUFFER_SIZE) == 0)
{
uninitialized_variable_counter = 0;
}
if (uninitialized_variable_counter == 0 && (strstr(data_test,"=") != NULL || strstr(data_test,"memset") != NULL || strstr(data_test,"fopen") != NULL))
{
// check for each variable in the uninitialized_variable_data
for (data_count = 0; data_count < uninitialized_variable_data.count; data_count++)
{
// if its is match and is being initialized then remove it from the struct
if (strstr(data_test,uninitialized_variable_data.data[data_count]) != NULL)
{
// check if the variable is being initialized
memset(data,0,strnlen(data,BUFFER_SIZE));
memcpy(data,"memset(",7);
memcpy(data+7,uninitialized_variable_data.data[data_count],strnlen(uninitialized_variable_data.data[data_count],BUFFER_SIZE));
if (strstr(data_test,data) != NULL)
{
memset(uninitialized_variable_data.data[data_count],0,strnlen(uninitialized_variable_data.data[data_count],BUFFER_SIZE));
memcpy(uninitialized_variable_data.data[data_count],"0",1);
}
memset(data,0,strnlen(data,BUFFER_SIZE));
memcpy(data,"memset(&",8);
memcpy(data+8,uninitialized_variable_data.data[data_count],strnlen(uninitialized_variable_data.data[data_count],BUFFER_SIZE));
if (strstr(data_test,data) != NULL)
{
memset(uninitialized_variable_data.data[data_count],0,strnlen(uninitialized_variable_data.data[data_count],BUFFER_SIZE));
memcpy(uninitialized_variable_data.data[data_count],"0",1);
}
memset(data,0,strnlen(data,BUFFER_SIZE));
memcpy(data,"pointer_reset(",14);
memcpy(data+14,uninitialized_variable_data.data[data_count],strnlen(uninitialized_variable_data.data[data_count],BUFFER_SIZE));
if (strstr(data_test,data) != NULL)
{
memset(uninitialized_variable_data.data[data_count],0,strnlen(uninitialized_variable_data.data[data_count],BUFFER_SIZE));
memcpy(uninitialized_variable_data.data[data_count],"0",1);
}
memset(data,0,strnlen(data,BUFFER_SIZE));
memcpy(data,uninitialized_variable_data.data[data_count],strnlen(uninitialized_variable_data.data[data_count],BUFFER_SIZE));
memcpy(data+strnlen(uninitialized_variable_data.data[data_count],BUFFER_SIZE)," = ",3);
if (strstr(data_test,data) != NULL)
{
memset(uninitialized_variable_data.data[data_count],0,strnlen(uninitialized_variable_data.data[data_count],BUFFER_SIZE));
memcpy(uninitialized_variable_data.data[data_count],"0",1);
}
if (strstr(data_test,"fopen") != NULL)
{
memset(uninitialized_variable_data.data[data_count],0,strnlen(uninitialized_variable_data.data[data_count],BUFFER_SIZE));
memcpy(uninitialized_variable_data.data[data_count],"0",1);
}
}
}
}
// save the previous 5 lines of the file
memcpy(data5,data4,strnlen(data4,BUFFER_SIZE));
memcpy(data4,data3,strnlen(data3,BUFFER_SIZE));
memcpy(data3,data2,strnlen(data2,BUFFER_SIZE));
memcpy(data2,data1,strnlen(data1,BUFFER_SIZE));
memcpy(data1,data_test,strnlen(data_test,BUFFER_SIZE));
// reset the varaible
memset(data_test,0,strnlen(data_test,BUFFER_SIZE));
line_count++;
}
}
}
pointer_reset_all;
return count_test;
#undef pointer_reset_all
} | 2.90625 | 3 |
2024-11-18T21:06:39.540550+00:00 | 2021-10-01T17:19:19 | 9053f091a7760f9f292b1f089ffe57707d3a7441 | {
"blob_id": "9053f091a7760f9f292b1f089ffe57707d3a7441",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-01T17:19:19",
"content_id": "319e435bb8c2670589c560741b380bca2af4b6ca",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "502fa024064f0b45535331156b542d5540a556fa",
"extension": "c",
"filename": "buf.c",
"fork_events_count": 14,
"gha_created_at": "2013-11-30T21:43:00",
"gha_event_created_at": "2023-09-11T20:54:17",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 14828870,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1448,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/nmsg/buf.c",
"provenance": "stackv2-0128.json.gz:82459",
"repo_name": "farsightsec/nmsg",
"revision_date": "2021-10-01T17:19:19",
"revision_id": "42d284551c0f8da9c02ba06b5a551ba575243c7f",
"snapshot_id": "e9aac68ebe82c1f5f90d8626a89af23bedf513d3",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/farsightsec/nmsg/42d284551c0f8da9c02ba06b5a551ba575243c7f/nmsg/buf.c",
"visit_date": "2023-08-31T14:39:16.245311"
} | stackv2 | /*
* Copyright (c) 2008, 2012 by Farsight Security, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Import. */
#include "private.h"
/* Internal functions. */
struct nmsg_buf *
_nmsg_buf_new(size_t sz) {
struct nmsg_buf *buf;
buf = calloc(1, sizeof(*buf));
if (buf == NULL)
return (NULL);
buf->data = calloc(1, sz);
if (buf->data == NULL) {
free(buf);
return (NULL);
}
return (buf);
}
ssize_t
_nmsg_buf_used(struct nmsg_buf *buf) {
assert(buf->pos >= buf->data);
return (buf->pos - buf->data);
}
ssize_t
_nmsg_buf_avail(struct nmsg_buf *buf) {
assert(buf->pos <= buf->end);
return (buf->end - buf->pos);
}
void
_nmsg_buf_destroy(struct nmsg_buf **buf) {
if (*buf != NULL) {
if (_nmsg_global_autoclose == true)
close((*buf)->fd);
if ((*buf)->data != NULL)
free((*buf)->data);
free(*buf);
*buf = NULL;
}
}
void
_nmsg_buf_reset(struct nmsg_buf *buf) {
buf->end = buf->pos = buf->data;
}
| 2 | 2 |
2024-11-18T21:06:39.636062+00:00 | 2023-02-22T20:20:35 | 5cf955cae3ddbf7d78cbd322e20db70c78c0999b | {
"blob_id": "5cf955cae3ddbf7d78cbd322e20db70c78c0999b",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-22T20:20:35",
"content_id": "bb36cfcf46a1e66c19d2065ee160e8cc5e5b620e",
"detected_licenses": [
"MIT"
],
"directory_id": "c8f7773f80acf75345af37c67f0d925cf0234118",
"extension": "c",
"filename": "cal.c",
"fork_events_count": 35,
"gha_created_at": "2015-07-13T18:21:31",
"gha_event_created_at": "2023-05-19T07:27:16",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 39029490,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5099,
"license": "MIT",
"license_type": "permissive",
"path": "/src/cal.c",
"provenance": "stackv2-0128.json.gz:82590",
"repo_name": "uglyDwarf/linuxtrack",
"revision_date": "2023-02-22T20:20:35",
"revision_id": "fe9b98b51f6ee6521d38bd1f7edf84839227e588",
"snapshot_id": "14a8854b826d57fa28ca276ec6ba5c54a1ddaa31",
"src_encoding": "UTF-8",
"star_events_count": 156,
"url": "https://raw.githubusercontent.com/uglyDwarf/linuxtrack/fe9b98b51f6ee6521d38bd1f7edf84839227e588/src/cal.c",
"visit_date": "2023-05-25T02:05:04.332165"
} | stackv2 | /*************************************************************
****************** CAMERA ABSTRACTION LAYER *****************
*************************************************************/
#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
#include "cal.h"
#include "utils.h"
#include "dyn_load.h"
static dev_interface iface = {
.device_run = NULL,
.device_shutdown = NULL,
.device_suspend = NULL,
.device_wakeup = NULL
};
static lib_fun_def_t functions[] = {
{"ltr_int_rl_run", (void*) &iface.device_run},
{"ltr_int_rl_shutdown", (void*) &iface.device_shutdown},
{"ltr_int_rl_suspend", (void*) &iface.device_suspend},
{"ltr_int_rl_wakeup", (void*) &iface.device_wakeup},
{NULL, NULL}
};
static void *libhandle = NULL;
static enum ltr_request_t request = RUN;
static linuxtrack_state_type ltr_int_cal_device_state = STOPPED;
static bool new_request_received = false;
/************************/
/* function definitions */
/************************/
int ltr_int_cal_run(struct camera_control_block *ccb, frame_callback_fun cbk)
{
char *libname = NULL;
assert(ccb != NULL);
ltr_int_cal_set_state(INITIALIZING);
switch (ccb->device.category) {
case tir:
libname = "libtir";
break;
case tir4_camera:
libname = "libtir4";
break;
case webcam:
libname = "libwc";
break;
case mac_webcam:
libname = "libmacwc";
break;
case webcam_ft:
libname = "libft";
break;
case mac_webcam_ft:
libname = "libmacwc";
break;
case wiimote:
libname = "libmacwii";
break;
case joystick:
libname = "libjoy";
break;
case mac_ps3eye:
libname = "libp3e";
break;
case mac_ps3eye_ft:
libname = "libp3eft";
break;
default:
assert(0);
break;
}
ltr_int_log_message("Loading library '%s'\n", libname);
if((libhandle = ltr_int_load_library(libname, functions)) == NULL){
return -1;
}
assert(iface.device_run != NULL);
if(request != PAUSE){
ltr_int_change_state(RUN);
}
ltr_int_log_message("Running!\n");
int res = (iface.device_run)(ccb, cbk);
//Runloop blocks until shutdown is called
ltr_int_unload_library(libhandle, functions);
return res;
}
int ltr_int_cal_shutdown()
{
ltr_int_change_state(SHUTDOWN);
if(iface.device_shutdown == NULL){
ltr_int_log_message("Calling shutdown without initializing first!\n");
return -1;
}
ltr_int_log_message("Closing!\n");
int res = (iface.device_shutdown)();
return res;
}
int ltr_int_cal_suspend()
{
ltr_int_change_state(PAUSE);
if(iface.device_suspend == NULL){
ltr_int_log_message("Calling suspend without initializing first!\n");
return -1;
}
ltr_int_log_message("Suspending!\n");
return (iface.device_suspend)();
}
int ltr_int_cal_wakeup()
{
ltr_int_change_state(RUN);
if(iface.device_wakeup == NULL){
ltr_int_log_message("Calling wake-up without initializing first!\n");
return -1;
}
ltr_int_log_message("Waking!\n");
return (iface.device_wakeup)();
}
linuxtrack_state_type ltr_int_cal_get_state()
{
return ltr_int_cal_device_state;
}
static ltr_status_update_callback_t ltr_status_changed_cbk = NULL;
static void *ltr_status_changed_cbk_param = NULL;
static char *state_desc[] = {"OK", "INITIALIZING", "RUNNING", "PAUSED", "STOPPED"};
void ltr_int_cal_set_state(linuxtrack_state_type new_state)
{
char *msg;
if(new_state < 0){
msg = "ERROR";
}else{
msg = state_desc[new_state];
}
ltr_int_log_message("Changing state to %s!\n", msg);
ltr_int_cal_device_state = new_state;
if(ltr_status_changed_cbk != NULL){
ltr_status_changed_cbk(ltr_status_changed_cbk_param);
}
}
void ltr_int_change_state(enum ltr_request_t new_req)
{
request = new_req;
new_request_received = true;
}
bool ltr_int_got_new_request()
{
return new_request_received;
}
void ltr_int_set_status_change_cbk(ltr_status_update_callback_t status_change_cbk, void *param)
{
ltr_status_changed_cbk = status_change_cbk;
ltr_status_changed_cbk_param = param;
}
enum ltr_request_t ltr_int_get_state_request()
{
enum ltr_request_t res = request;
request = CONTINUE;
new_request_received = false;
return res;
}
void ltr_int_frame_free(struct camera_control_block *ccb,
struct frame_type *f)
{
assert(ccb != NULL);
assert(f->bloblist.blobs != NULL);
free(f->bloblist.blobs);
f->bloblist.blobs = NULL;
}
static void blob_print(struct blob_type b)
{
printf("x: %f\ty: %f\tscore: %d\n", b.x,b.y,b.score);
}
static void bloblist_print(struct bloblist_type bl)
{
unsigned int i;
printf("-- start blob --\n");
for (i=0;i<bl.num_blobs;i++) {
blob_print((bl.blobs)[i]);
}
printf("-- end blob --\n");
}
void ltr_int_frame_print(struct frame_type f)
{
printf("-- start frame --\n");
printf("num blobs: %d\n", f.bloblist.num_blobs);
bloblist_print(f.bloblist);
/* FIXME: print something for pixels? */
printf("-- end frame --\n");
}
| 2.125 | 2 |
2024-11-18T21:06:39.756593+00:00 | 2021-02-03T05:25:24 | 61d919a08dc20ffe218b7f8d6612d46ebdb9d38f | {
"blob_id": "61d919a08dc20ffe218b7f8d6612d46ebdb9d38f",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-03T05:25:24",
"content_id": "15b7fd3d8316b3ea1c33e757515a3c5c4b9b3005",
"detected_licenses": [
"MIT"
],
"directory_id": "691c2624e22896a1d20a7358adf443f0d43e50c0",
"extension": "c",
"filename": "minHeap.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 334534222,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3420,
"license": "MIT",
"license_type": "permissive",
"path": "/minHeap.c",
"provenance": "stackv2-0128.json.gz:82718",
"repo_name": "Sun694/CUDA-Jaccard-Score",
"revision_date": "2021-02-03T05:25:24",
"revision_id": "822b1ac442e444a2f03f1b5477bc573a1c15b2fd",
"snapshot_id": "dfeafe3344fa2a2ab37a136c65ebc551c54243fd",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Sun694/CUDA-Jaccard-Score/822b1ac442e444a2f03f1b5477bc573a1c15b2fd/minHeap.c",
"visit_date": "2023-02-25T04:32:02.598849"
} | stackv2 | /*
File: minHeap.c
Desc: Program showing various operations on a binary min heap
Modified by me, original implementation by Robin Thomas at
https://github.com/robin-thomas/min-heap/blob/master/minHeap.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#define LCHILD(x) 2 * x + 1
#define RCHILD(x) 2 * x + 2
#define PARENT(x) (x - 1) / 2
typedef struct node {
float data;
int idx;
} node;
typedef struct minHeap {
int size;
int maxSize;
node *elem;
} minHeap;
/*
Function to initialize the min heap with size = 0, maxsize = maxSize
*/
struct minHeap * initMinHeap(int maxSize) {
struct minHeap *hp;
hp = (struct minHeap*) malloc(sizeof(struct minHeap));
hp->size = 0;
hp->maxSize = maxSize;
hp->elem = (node*)malloc(sizeof(node) * maxSize);
return hp;
}
/*
Function to swap data within two nodes of the min heap using pointers
*/
void swap(node *n1, node *n2) {
node temp = *n1;
*n1 = *n2;
*n2 = temp;
}
/*
Heapify function is used to make sure that the heap property is never violated
In case of deletion of a node, or creating a min heap from an array, heap property
may be violated. In such cases, heapify function can be called to make sure that
heap property is never violated
*/
void heapify(minHeap *hp, int i) {
int smallest = (LCHILD(i) < hp->size && hp->elem[LCHILD(i)].data < hp->elem[i].data) ? LCHILD(i) : i;
if (RCHILD(i) < hp->size && hp->elem[RCHILD(i)].data < hp->elem[smallest].data) {
smallest = RCHILD(i);
}
if (smallest != i) {
swap(&(hp->elem[i]), &(hp->elem[smallest]));
heapify(hp, smallest);
}
}
/*
Function to insert a node into the min heap
*/
void insertNode(minHeap *hp, float data, int idx) {
assert(hp->size < hp->maxSize);
node nd;
nd.data = data;
nd.idx = idx;
int i = (hp->size)++;
while (i && nd.data < hp->elem[PARENT(i)].data) {
hp->elem[i] = hp->elem[PARENT(i)];
i = PARENT(i);
}
hp->elem[i] = nd;
}
/*
Function to delete a node from the min heap
It shall remove the root node, and place the last node in its place
and then call heapify function to make sure that the heap property
is never violated
*/
void deleteNode(minHeap *hp) {
if (hp->size) {
// printf("Deleting node %d\n\n", hp->elem[0].data) ;
hp->elem[0] = hp->elem[--(hp->size)];
heapify(hp, 0);
}
else {
printf("\nMin Heap is empty!\n");
free(hp->elem);
}
}
/*
Function to get maximum node from a min heap
The maximum node shall always be one of the leaf nodes. So we shall recursively
move through both left and right child, until we find their maximum nodes, and
compare which is larger. It shall be done recursively until we get the maximum
node
*/
int getMaxNode(minHeap *hp, int i) {
if (LCHILD(i) >= hp->size) {
return hp->elem[i].data;
}
int l = getMaxNode(hp, LCHILD(i));
int r = getMaxNode(hp, RCHILD(i));
if (l >= r) {
return l;
}
else {
return r;
}
}
float getMinNode(minHeap *hp) {
return hp->elem[0].data;
}
/*
Function to clear the memory allocated for the min heap
*/
void deleteMinHeap(minHeap *hp) {
free(hp->elem);
}
/*
Function to display all the nodes in the min heap by doing a preorder traversal
*/
void preorderTraversal(minHeap *hp, int i) {
printf("%f ", hp->elem[i].data);
printf("%d ", hp->elem[i].idx);
if (LCHILD(i) < hp->size) {
preorderTraversal(hp, LCHILD(i));
}
if (RCHILD(i) < hp->size) {
preorderTraversal(hp, RCHILD(i));
}
}
| 3.9375 | 4 |
2024-11-18T21:06:40.162015+00:00 | 2021-01-22T16:03:03 | 31752e2d399b18b0a685fc62489b860e9e76ab01 | {
"blob_id": "31752e2d399b18b0a685fc62489b860e9e76ab01",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-22T16:03:03",
"content_id": "1d26dc54a088eb51b0d0a38c87bbd2e4f61a113a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7a54d0de2b28ce889a60af6fda3ae7959e2a16bd",
"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": 10048,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Project/main.c",
"provenance": "stackv2-0128.json.gz:82976",
"repo_name": "carvalho28/Trabalho-de-Labs-de-Programa-o",
"revision_date": "2021-01-22T16:03:03",
"revision_id": "9a889cd775d095c5c45734c4f5b25d5ca68fe631",
"snapshot_id": "67763e6dc0bce15c60f7119947c27eac080d28a9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/carvalho28/Trabalho-de-Labs-de-Programa-o/9a889cd775d095c5c45734c4f5b25d5ca68fe631/Project/main.c",
"visit_date": "2023-02-21T18:05:36.302937"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "part1.h"
#include "part2.h"
/**
* @file main.c
* @brief This file contains the main function, adtional features and menus of the program.
* @version 1.00
* @authors <c>Team 13</c><ul><li>Diogo Carvalho Nº 45716 </li> <li>Eduardo Mendes Nº 45916 </li> <li>Francisco Casais Nº 45465 </li> <li>Guilherme Barata Nº 45779</li> <li>João Marques Nº 45722</li> </ul>
* @copyright Copyright 2021 <c>Team 13</c>. All rights reserved. \n This project is released under the Apache License 2.0.
*/
/**
* N is the number of rows of the matrix.
*/
#define N 18
/**
* M is the number of columns of the matrix.
*/
#define M 1
/**
* @brief Function that clears the input buffer. Useful for clearing "\n" from the buffer after using the scanf function.
*/
void cleanInputBuffer(void)
{
while (getchar() != '\n')
;
}
/**
* @brief This function shows the user the main menu of the program.
* @param vet[N][M] it is the vector created by the user.
*/
int mainMenu(int vet[N][M])
{
int i, j, resposta = -1;
printf("\e[1;1H\e[2J");
printf("\nVector:\n[");
for (i = 0; i < N; i++)
{
for (j = 0; j < M; j++)
{
if (i != N - 1)
{
printf("%3d, ", vet[i][j]);
}
else
{
printf("%3d ", vet[i][j]);
}
}
}
printf("]\n\n");
printf("Main Menu\n\n");
printf("1. Sort Vector by Ascending Order\n");
printf("2. Median of Given Vector\n");
printf("3. Multiply All Vector Elements by 3\n");
printf("4. Create Matrix with Vector and Quadruples\n");
printf("5. Natural Base Logarithm of All Vector Elements\n");
printf("6. Value of Elements in Positions Multiple of Three\n");
printf("7. Help\n");
printf("8. Additional Options\n");
printf("\n9. Create New Vector\n");
printf("0. Exit\n");
do
{
if (scanf("%d", &resposta) != 1 || resposta < 0 || resposta > 9)
{
printf("\nInvalid input. Please try again!\n");
}
cleanInputBuffer();
} while (resposta < 0 || resposta > 9);
printf("\n");
return resposta;
}
/**
* @brief Extra options menu that returns the option number the user has chosen.
* @param vet[N][M] it is the vector created by the user.
*/
int extraMenu(int vet[N][M])
{
int i, j, resposta = -1;
printf("\e[1;1H\e[2J");
printf("\nVector:\n[");
for (i = 0; i < N; i++)
{
for (j = 0; j < M; j++)
{
if (i != N - 1)
{
printf("%3d, ", vet[i][j]);
}
else
{
printf("%3d ", vet[i][j]);
}
}
}
printf("]\n\n");
printf("Additional Options\n\n");
printf("1. Mix Half of the Vector with Half of a New One\n");
printf("2. Prime Factorization of the Vector's Odd Numbers\n");
printf("3. Multiply the First Vector by a New One (Create 18x18 Matrix)\n");
printf("4. Previous Option's 18x18 Matrix Transposition\n");
printf("\n0. Exit\n");
do
{
if (scanf("%d", &resposta) != 1 || resposta < 0 || resposta > 4)
{
printf("\nInvalid input. Please try again!\n");
}
cleanInputBuffer();
} while (resposta < 0 || resposta > 4);
printf("\n");
return resposta;
}
/**
* @brief This Function copies the vector given by the user to an auxiliary vector.
* @param vetInicial it is the initional vector wich was asked to the user;
* @param vetAuxiliar it is the aditional vector created by the user.
*/
void createAuxVec(int vetInicial[N][M], int vetAuxiliar[N][M])
{
int i, j;
for (i = 0; i < N; i++)
{
for (j = 0; j < M; j++)
{
vetAuxiliar[i][j] = vetInicial[i][j];
}
}
}
/**
* @brief Realization of extra features depending on the user's option.
* @param vet[N][M] it`s the vector created by the user.
*/
void extraOptions(int vet[N][M])
{
int vetAux[N][M] = {}, vet18x18[N][N] = {};
int i, j, resposta = -1, flag = 0;
do
{
createAuxVec(vet, vetAux);
resposta = extraMenu(vetAux);
switch (resposta)
{
case 1:
mixHalfVectors(vetAux);
printf("\nPress 'Enter' to continue.\n");
cleanInputBuffer();
break;
case 2:
OddPrimeFactoring(vetAux);
printf("\nPress 'Enter' to continue.\n");
cleanInputBuffer();
break;
case 3:
matrix18x18(vetAux, vet18x18);
printf("\nThe 18x18 matrix which isthe product of the two vectors is:\n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
printf("%4d ", vet18x18[i][j]);
}
printf("\n");
}
flag++;
printf("\nPress 'Enter' to continue.\n");
cleanInputBuffer();
break;
case 4:
if (flag == 0)
{
printf("A 18x18 matrix does not exist.\nSelect option '3' to create a 18x18 matrix.\n");
}
else
{
transpose18x18(vet18x18);
}
printf("\nPress 'Enter' to continue.\n");
cleanInputBuffer();
break;
case 0:
resposta = 0;
break;
default:
printf("Invalid input. Please try again!\n");
break;
}
} while (resposta != 0); // menu loop condition
}
/**
* @brief This is the main function os this program.
* @param argc it is the quantity of arguments;
* @param argv it is a pointer for the arguments, which are strings.
*/
int main(int argc, char **argv)
{
if (argc > 2)
{
printf("Incorrect number of arguments.\n");
exit(1);
}
else if (argc == 2)
{
if (strcmp(argv[1], "--help") == 0)
{
printHelp();
printf("Press 'Enter' to continue.\n");
cleanInputBuffer();
exit(1);
}
else
{
printf("Invalid argument.\n");
exit(1);
}
}
else
{
int vet[N][M] = {}, vetAux[N][M] = {};
int i, resposta_menu;
printf("\e[1;1H\e[2J");
printf("Welcome to B1nV3ctor!\n");
printf("This program will ask the user to insert a vector and then present some statistics or operations using it.\n");
printf("Press 'Enter' to continue.\n");
cleanInputBuffer();
printf("\nInsert 18 integers between 6 and 28:\n");
do
{
for (i = 0; i < N; i++)
{
do
{
printf("Position no. %d: ", i + 1); // Verify if input is between 6 and 28
if (scanf("%d", &vet[i][0]) != 1 || vet[i][0] <= 6 || vet[i][0] >= 28)
{
printf("\nInvalid input. Please try again!\n");
}
printf("\n");
cleanInputBuffer();
} while (vet[i][0] <= 6 || vet[i][0] >= 28);
}
do
{
createAuxVec(vet, vetAux);
resposta_menu = mainMenu(vetAux);
switch (resposta_menu)
{
case 1:
ascendingOrder(vetAux);
printf("The vector's elements in ascending order are as follows:\n");
for (i = 0; i < N; ++i)
{
printf("%d ", vetAux[i][M - 1]);
}
printf("\n\nPress 'Enter' to continue.\n");
cleanInputBuffer();
break;
case 2:
elementsMedian(vetAux);
printf("\nPress 'Enter' to continue.\n");
cleanInputBuffer();
break;
case 3:
multiplyBy3(vetAux);
printf("\nPress 'Enter' to continue.\n");
cleanInputBuffer();
break;
case 4:
matrix2x18Quadruples(vetAux);
printf("\nPress 'Enter' to continue.\n");
cleanInputBuffer();
break;
case 5:
elementsLogarithm(vetAux);
printf("\nPress 'Enter' to continue.\n");
cleanInputBuffer();
break;
case 6:
mult3PositionsValues(vetAux);
printf("\nPress 'Enter' to continue.\n");
cleanInputBuffer();
break;
case 7:
printHelp();
printf("\nPress 'Enter' to continue.\n");
cleanInputBuffer();
break;
case 8:
extraOptions(vetAux);
break;
case 9:
resposta_menu = 9;
break;
case 0:
resposta_menu = 0;
break;
default:
printf("Invalid input. Please try again!\n");
break;
}
} while (resposta_menu != 0 && resposta_menu != 9); // menu loop condition
} while (resposta_menu == 9);
}
return 0;
}
| 3.375 | 3 |
2024-11-18T21:06:40.296944+00:00 | 2023-06-02T13:13:27 | 380144ba8505064bdf395d3146f7992e7daea99b | {
"blob_id": "380144ba8505064bdf395d3146f7992e7daea99b",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-02T13:13:27",
"content_id": "2edd98a15de5d8088798e626e757a551b7b671d0",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "5a04950c7280843e8c0e52ef023dc2e82103624b",
"extension": "c",
"filename": "audioPlayer.c",
"fork_events_count": 6,
"gha_created_at": "2014-08-21T15:04:21",
"gha_event_created_at": "2020-02-18T17:22:10",
"gha_language": "HTML",
"gha_license_id": "CC0-1.0",
"github_id": 23191607,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7633,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/soft/reflex/audioPlayer.c",
"provenance": "stackv2-0128.json.gz:83104",
"repo_name": "janvitek/janvitek.github.io",
"revision_date": "2023-06-02T13:13:27",
"revision_id": "6924b06751d42df65690f3ac392ba173e4daf1e4",
"snapshot_id": "966ae807f0dd501791faf4ac0c322798ff90de1c",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/janvitek/janvitek.github.io/6924b06751d42df65690f3ac392ba173e4daf1e4/soft/reflex/audioPlayer.c",
"visit_date": "2023-06-10T10:04:33.644056"
} | stackv2 | #include <signal.h>
#include <time.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <complex.h>
#include "posix_time.h"
#include <linux/soundcard.h>
#define NANOS_PER_SEC (1000LL*1000*1000)
#define MICROS_PER_SEC (1000LL*1000)
#define NANOS_PER_MICRO 1000LL
#define SOUND_DEV "/dev/dsp"
#define PERIOD_NANOS 45000LL
#define ITERATIONS 1000000
long long deadlineMissOverTime[ITERATIONS];
int iteration = 0;
int fd;
long long expectedCmplTimeNanos;
int errWrites = 0;
int misses = 0;
timer_t timer_h;
static struct timespec ts_start, ts_stop;
static struct timespec write_start[ITERATIONS], write_stop[ITERATIONS];
int buff;
long long calcCeil(long long x, long long y) {
return (x + y - 1) / y;
}
void logDeadlineMiss(long long diff) {
misses++;
deadlineMissOverTime[iteration] = diff;
}
void timer_intr(int sig, siginfo_t *extra, void *cruft) {
// start timer first time
if (ts_start.tv_nsec == 0) {
clock_gettime(CLOCK_REALTIME, &ts_start);
}
// write byte to file
clock_gettime(CLOCK_REALTIME, &write_start[iteration]);
if (write(fd, &buff, 1) != 1) {
errWrites++;
}
clock_gettime(CLOCK_REALTIME, &write_stop[iteration]);
// check for missing deadline
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
long long nowNanos = (now.tv_sec * NANOS_PER_SEC + now.tv_nsec);
if (iteration > 0) {
//printf("Diff: %lld\n", llabs(nowNanos - expectedCmplTimeNanos));
if (nowNanos > expectedCmplTimeNanos) {
logDeadlineMiss(nowNanos - expectedCmplTimeNanos);
}
}
iteration++;
if (iteration == ITERATIONS) {
//printf("expt: %lld\n", (expectedCmplTimeNanos - nowNanos));
clock_gettime(CLOCK_REALTIME, &ts_stop);
// disable timer
struct itimerspec tmr_setting;
tmr_setting.it_value.tv_sec = 0;
tmr_setting.it_value.tv_nsec = 0;
tmr_setting.it_interval.tv_sec = 0;
tmr_setting.it_interval.tv_nsec = 0;
if ( timer_settime(timer_h,0,&tmr_setting,NULL) < 0 ) {
perror("settimer -- disable");
}
}
// calculate next deadline
expectedCmplTimeNanos = ((calcCeil(nowNanos, PERIOD_NANOS) + 1) * PERIOD_NANOS);
}
int openDevice() {
int fd = open(SOUND_DEV, O_WRONLY | O_NONBLOCK);
if (fd < 0) {
perror("Couldn't open device");
return -1;
}
/* Set up the soundcard */
printf("SOUND_PCM_WRITE_BITS %d\n", SOUND_PCM_WRITE_BITS);
printf("SOUND_PCM_WRITE_CHANNELS %d\n", SOUND_PCM_WRITE_CHANNELS);
printf("SOUND_PCM_WRITE_RATE %d\n", SOUND_PCM_WRITE_RATE);
printf("SNDCTL_DSP_GETBLKSIZE %d\n", SNDCTL_DSP_GETBLKSIZE);
int arg = 16;
int result = ioctl(fd, SOUND_PCM_WRITE_BITS, &arg);
if (result == -1) {
return -1;
}
if (arg != 16) {
return -1;
}
arg = 1;
result = ioctl(fd, SOUND_PCM_WRITE_CHANNELS, &arg);
if (result == -1) {
return -1;
}
if (arg != 1) {
return -1;
}
arg = 22050;
result = ioctl(fd, SOUND_PCM_WRITE_RATE, &arg);
if (result == -1) {
return -1;
}
arg = 0;
/* Display blksize */
ioctl(fd, SNDCTL_DSP_GETBLKSIZE, &arg);
fprintf(stderr, "blksize: %d\n", arg);
sleep(2);
return fd;
}
void doTest()
{
struct sigaction sa;
struct sigevent sig_spec;
sigset_t allsigs;
struct itimerspec tmr_setting;
buff = 1;
/* setup signal to respond to timer */
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = timer_intr;
if ( sigaction(SIGRTMIN, &sa, NULL) < 0 )
perror("sigaction");
sig_spec.sigev_notify = SIGEV_SIGNAL;
sig_spec.sigev_signo = SIGRTMIN;
/* create timer, which uses the REALTIME clock */
if (timer_create(CLOCK_REALTIME,&sig_spec,&timer_h) < 0 )
perror("timer create");
/* set the initial expiration and frequency of timer */
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
long long nowNanos = (now.tv_sec * NANOS_PER_SEC) + now.tv_nsec;
long long initTime = (long long) ((nowNanos / PERIOD_NANOS) * PERIOD_NANOS + (PERIOD_NANOS * 1000));
tmr_setting.it_value.tv_sec = (initTime - nowNanos) / NANOS_PER_SEC;
tmr_setting.it_value.tv_nsec = (initTime - nowNanos) % NANOS_PER_SEC;
tmr_setting.it_interval.tv_sec = 0L;
tmr_setting.it_interval.tv_nsec = 45000L;
if ( timer_settime(timer_h,0,&tmr_setting,NULL) < 0 ) {
perror("settimer");
}
/* wait for signals */
sigemptyset(&allsigs);
while (iteration < ITERATIONS) {
sigsuspend(&allsigs);
}
}
void dumpWriteTimeHistogram() {
int HISTOSIZE = 1500;
int MAX_GRADE = 10;
int histogram[HISTOSIZE];
int extremes_ = 0;
int i;
for (i = 0; i < HISTOSIZE; i++) {
histogram[i] = 0;
}
for (i = 0; i < ITERATIONS; i++) {
long long startTime = write_start[i].tv_sec * NANOS_PER_SEC + write_start[i].tv_nsec;
long long endTime = write_stop[i].tv_sec * NANOS_PER_SEC + write_stop[i].tv_nsec;
int timeInMicros = (int) calcCeil((endTime - startTime), NANOS_PER_MICRO);
if (timeInMicros >= HISTOSIZE) {
extremes_++;
}
else {
histogram[timeInMicros]++;
}
}
printf("\n");
printf("Write Time Histogram\n");
for (i = 1; i < HISTOSIZE; i++) {
printf("%d %d\n", i, histogram[i]);
//for (int j = 0; j < (histogram[i] / (HISTOSIZE / MAX_GRADE)); j++) {
// System.out.print("*");
//}
}
printf("[extremes] = %d\n", extremes_);
}
void dumpWriteTimesOverTime() {
printf("\n");
printf("Write Time Over Time\n");
int i;
for (i = 0; i < ITERATIONS; i++) {
long long startTime = write_start[i].tv_sec * NANOS_PER_SEC + write_start[i].tv_nsec;
long long endTime = write_stop[i].tv_sec * NANOS_PER_SEC + write_stop[i].tv_nsec;
int timeInMicros = (int) calcCeil((endTime - startTime), NANOS_PER_MICRO);
printf("%d %d\n", i, timeInMicros);
}
}
void dumpMissedDeadlineHistogram() {
int HISTOSIZE = 150;
int MAX_GRADE = 10;
int histogram[HISTOSIZE];
int extremes_ = 0;
int i;
for (i = 0; i < HISTOSIZE; i++) {
histogram[i] = 0;
}
for (i = 1; i < ITERATIONS; i++) {
int missInMicros = (int) calcCeil(deadlineMissOverTime[i], NANOS_PER_MICRO);
if (missInMicros >= HISTOSIZE) {
extremes_++;
}
else {
histogram[missInMicros]++;
}
}
printf("\n");
printf("Missed Deadline Histogram\n");
for (i = 1; i < HISTOSIZE; i++) {
printf("%d %d\n", i, histogram[i]);
//for (int j = 0; j < (histogram[i] / (HISTOSIZE / MAX_GRADE)); j++) {
// System.out.print("*");
//}
}
printf("[extremes] = %d\n", extremes_);
}
void dumpDeadlineMissesOverTime() {
printf("\n");
printf("Deadline misses in microseconds over time\n");
int i;
for ( i = 0; i < ITERATIONS; i++) {
printf("%d %lld\n", i, calcCeil(deadlineMissOverTime[i], NANOS_PER_MICRO));
}
}
void dumpStatistics() {
long long startTime = ts_start.tv_sec * NANOS_PER_SEC + ts_start.tv_nsec;
long long endTime = ts_stop.tv_sec * NANOS_PER_SEC + ts_stop.tv_nsec;
printf("Missed deadlines: %lld\n", (((endTime - startTime) / PERIOD_NANOS) - ITERATIONS));
printf("Missed deadlines: %d and bad writes %d\n", misses, errWrites);
}
int main(int argc, char *argv[]) {
if (openDevice() == -1)
exit(-1);
doTest();
dumpWriteTimesOverTime();
/*
dumpWriteTimeHistogram();
printf("------------------------------\n");
dumpMissedDeadlineHistogram();
printf("------------------------------\n");
dumpDeadlineMissesOverTime();
printf("------------------------------\n");
dumpStatistics();
*/
}
| 2.265625 | 2 |
2024-11-18T21:06:40.790555+00:00 | 2020-03-18T11:27:26 | 49f7218e5d10479bb80a59fdcd88b69025732068 | {
"blob_id": "49f7218e5d10479bb80a59fdcd88b69025732068",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-18T11:27:26",
"content_id": "d364d737161a7fc3c4e96efa15e4a27dbe32f1ac",
"detected_licenses": [
"MIT"
],
"directory_id": "e79f2b7d29f43ea1945e9f4a7d5d38fd52dabd2a",
"extension": "h",
"filename": "shadow.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 92254598,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2615,
"license": "MIT",
"license_type": "permissive",
"path": "/common/shadow.h",
"provenance": "stackv2-0128.json.gz:83363",
"repo_name": "yang-han/EnjoyYourRoad",
"revision_date": "2020-03-18T11:27:26",
"revision_id": "c2a5926717ac1fbf6eaae8f89f451a601c5b1186",
"snapshot_id": "7c25fa32d8a0535bee48e130a7d0a3e485fea558",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/yang-han/EnjoyYourRoad/c2a5926717ac1fbf6eaae8f89f451a601c5b1186/common/shadow.h",
"visit_date": "2022-04-14T16:52:49.311995"
} | stackv2 |
/*
GLuint depthProgramID = LoadShaders( "/Users/mr.wang/2017term/Computer Graphics/Project/EnjoyYourRoad/depth.vs", "/Users/mr.wang/2017term/Computer Graphics/Project/EnjoyYourRoad/depth.fs" );
int windowWidth;
int windowHeight;
glfwGetFramebufferSize(window, &windowWidth, &windowHeight);
GLuint depthMapFBO;
GLuint depthMap;
shadowFBO(depthMapFBO, depthMap);
while(){
glfwPollEvents();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
//--------------render depth of scene to the texture-------------
glm::vec3 lightPos = glm::vec3(-4.0f, 35.0f, -0.0f);
glm::mat4 lightSpaceMatrix = getlightSpaceMatrix(lightPos);
glUseProgram(depthProgramID);
glUniformMatrix4fv(glGetUniformLocation(depthProgramID, "lightSpaceMatrix"), 1, GL_FALSE, &lightSpaceMatrix[0][0]);
// Clear the screen
glViewport(0, 0, 2048, 2048);
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glClear(GL_DEPTH_BUFFER_BIT);
//set model
...
//render as usual (only model matrix)
...
glBindFramebuffer(GL_FRAMEBUFFER, 0);
//--------------------------------------------------------
// reset viewport
glViewport(0, 0, windowWidth, windowHeight);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// render as usual (all matrix)
...
---------------------------how to use new shader----------------
glUniformMatrix4fv(glGetUniformLocation(programID, "P"), 1, GL_FALSE, &ProjectionMatrix[0][0]);
glUniformMatrix4fv(glGetUniformLocation(programID, "M"), 1, GL_FALSE, &SceneModelMatrix[0][0]);
//or...
glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]);
glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z);
glUniformMatrix4fv(glGetUniformLocation(programID, "lightSpaceMatrix"), 1, GL_FALSE, &lightSpaceMatrix[0][0]);
//bind texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, Texture);
glUniform1i(TextureID, 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, depthMap);
glUniform1i(ShadowMapID, 1);
}
*/
#ifndef shadow_h
#define shadow_h
#include <GL/glew.h>
#include <glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
void shadowFBO(GLuint &depthMapFBO, GLuint &depthMap);
glm::mat4 getlightSpaceMatrix(glm::vec3 lightPos);
#endif //shadow_h | 2.078125 | 2 |
2024-11-18T21:06:41.094459+00:00 | 2021-05-03T14:49:04 | 85c5f32f794e21fb6c2e52866ea6b58464f7172b | {
"blob_id": "85c5f32f794e21fb6c2e52866ea6b58464f7172b",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-04T17:43:24",
"content_id": "9a4141087a3da26042771b4a944880455ce44feb",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "198495fe8749e53edfbedb36abb125de54df895e",
"extension": "h",
"filename": "syntaxdot.h",
"fork_events_count": 0,
"gha_created_at": "2020-10-10T07:27:37",
"gha_event_created_at": "2021-05-04T17:43:25",
"gha_language": "Rust",
"gha_license_id": "NOASSERTION",
"github_id": 302842273,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2891,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/include/syntaxdot.h",
"provenance": "stackv2-0128.json.gz:83749",
"repo_name": "tensordot/syntaxdot-ffi",
"revision_date": "2021-05-03T14:49:04",
"revision_id": "16ae9cf577f8c89d7216c878c167bd60acb884ba",
"snapshot_id": "cdc8cb5027a6b3cd2bc0d6cf8b7315c5affbd698",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tensordot/syntaxdot-ffi/16ae9cf577f8c89d7216c878c167bd60acb884ba/include/syntaxdot.h",
"visit_date": "2023-04-27T19:52:22.101311"
} | stackv2 | #ifndef SYNTAXDOT_H
#define SYNTAXDOT_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* <p>
* A syntaxdot error.
* </p>
* <p>
* If a function was unsuccessful, the <tt>code</tt> will be set to
* non-zero and NUL-terminated error message will be assigned to
* <tt>error</tt>. The caller is responsible for deallocating the
* message with <tt>syntaxdot_free_string</tt>.
* </p>
*/
typedef struct {
int code;
char *error;
} ExternError;
/**
* <p>
* A byte buffer.
* <p>
* <p>
* <tt>data</tt> contains a pointer to the buffer, <tt>len</tt> the
* buffer length. The caller is responsible for deallocating the
* buffer with <tt>syntaxdot_free_bytebuffer</tt>.
* </p>
*/
typedef struct {
int64_t len;
uint8_t *data;
} ByteBuffer;
/**
* Load a syntaxdot annotation model.
*
* This function, when successful, returns a handle for the loaded model.
*
* @param path The path to the model configuration
* @param err Pointer to an error value.
* @return The handle for the annotator.
*/
uint64_t syntaxdot_annotator_load(char const *config_path, ExternError *err);
/**
* Free a syntaxdot annotation model.
*
* @param handle The handle of the model to free.
* @param err Pointer to an error value.
*/
void syntaxdot_annotator_free(uint64_t handle, ExternError *err);
/**
* <p>
* Annotate sentences using a model.
* </p>
* <p>
* This function annotates a set of sentences using the model specified by
* <tt>handle</tt>. The sentences must be provided as serialized protobuf,
* <tt>sentences_data</tt> must be a pointer to protobuf data with the length
* <tt>sentences_data_length<tt>.
* </p>
*
* @param handle The handle of the model to annotate with.
* @param sentences_data Pointer to the protocol buffer data.
* @param sentences_data_len Length of the protocol buffer data.
* @param batch_size Model batch size.
* @param err Pointer to an error value.
* @return Buffer with the annotations serialized to protobuf.
*/
ByteBuffer syntaxdot_annotator_annotate(uint64_t handle, uint8_t *sentences_data,
int32_t sentences_data_len, size_t batch_size,
ExternError *err);
/**
* Set the number of Torch inter-op threads.
*/
void syntaxdot_set_num_intraop_threads(int32_t n_threads);
/**
* Set the number of Torch inter-op threads.
*/
void syntaxdot_set_num_intraop_threads(int32_t n_threads);
/**
* Get the syntaxdot version.
*
* The returned string must not be deallocated.
*/
char const *syntaxdot_version();
/**
* Free a <tt>ByteBuffer</tt>.
* @param buf The buffer to free.
*/
void syntaxdot_free_bytebuffer(ByteBuffer buf);
/**
* Free a string allocated through this library.
* @param s The string to free.
*/
void syntaxdot_free_string(char *s);
#ifdef __cplusplus
}
#endif
#endif //SYNTAXDOT_H
| 2.46875 | 2 |
2024-11-18T21:06:41.561991+00:00 | 2016-02-13T22:08:05 | 682ace3256be991e42da560d037aac2ff3d3d9a0 | {
"blob_id": "682ace3256be991e42da560d037aac2ff3d3d9a0",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-13T22:08:05",
"content_id": "b46ffa9bc71981e7e1c832c53ccef4ccdcdaedec",
"detected_licenses": [
"MIT"
],
"directory_id": "72026389b4c77983737fc3eda883c32b98f1294a",
"extension": "h",
"filename": "main.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 53087484,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1670,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main.h",
"provenance": "stackv2-0128.json.gz:84137",
"repo_name": "muflax-scholars/ergodox-firmware",
"revision_date": "2016-02-13T22:08:05",
"revision_id": "ea97f185dec308a07bfad5a306c279a123030e1d",
"snapshot_id": "f1e8b4023082fa885ed6db1a2fbb95ff528e1dd4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/muflax-scholars/ergodox-firmware/ea97f185dec308a07bfad5a306c279a123030e1d/src/main.h",
"visit_date": "2021-01-24T21:19:43.204998"
} | stackv2 | /* ----------------------------------------------------------------------------
* main() : functions and data that may be useful externally
* ----------------------------------------------------------------------------
* Copyright (c) 2012 Ben Blazak <benblazak.dev@gmail.com>
* Released under The MIT License (MIT) (see "license.md")
* Project located at <https://github.com/benblazak/ergodox-firmware>
* ------------------------------------------------------------------------- */
#ifndef MAIN_h
#define MAIN_h
#include <stdbool.h>
#include <stdint.h>
#include "./keyboard/layout.h"
#include "./keyboard/matrix.h"
// --------------------------------------------------------------------
typedef enum StickyState
{
eStickyNone,
eStickyOnceDown,
eStickyOnceUp,
eStickyLock
} StickyState;
extern bool (*main_kb_is_pressed)[KB_ROWS][KB_COLUMNS];
extern bool (*main_kb_was_pressed)[KB_ROWS][KB_COLUMNS];
extern uint8_t main_layers_pressed[KB_ROWS][KB_COLUMNS];
extern uint8_t main_arg_layer;
extern uint8_t main_arg_layer_offset;
extern uint8_t main_arg_row;
extern uint8_t main_arg_col;
extern bool main_arg_is_pressed;
extern bool main_arg_was_pressed;
extern bool main_arg_any_non_trans_key_pressed;
extern bool main_arg_trans_key_pressed;
// --------------------------------------------------------------------
void main_exec_key (void);
uint8_t main_layers_top_layer (void);
uint8_t main_layers_top_sticky (void);
uint8_t main_layers_sticky (uint8_t layer);
void main_layers_enable (uint8_t layer, uint8_t sticky);
void main_layers_disable (uint8_t layer);
void main_layers_disable_top (void);
#endif
| 2.015625 | 2 |
2024-11-18T21:06:41.652139+00:00 | 2020-01-09T20:55:29 | 8d4637ab86040400f7eadfe7f17ff20a1b8fce3a | {
"blob_id": "8d4637ab86040400f7eadfe7f17ff20a1b8fce3a",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-09T20:55:29",
"content_id": "cb0875c06aefd7871e64b48ddddf97d2c282aa82",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "3ff76234d69e6c48fc77a9cc01fdd5d9092bbe30",
"extension": "h",
"filename": "cbmc_utils.h",
"fork_events_count": 2,
"gha_created_at": "2017-02-28T15:59:47",
"gha_event_created_at": "2019-11-22T20:09:08",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 83451747,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3456,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/tests/cbmc/include/cbmc_proof/cbmc_utils.h",
"provenance": "stackv2-0128.json.gz:84267",
"repo_name": "danielsn/s2n",
"revision_date": "2020-01-09T20:55:29",
"revision_id": "d5d9bf7405bffeee06748157ad0e40b6a95e7dc9",
"snapshot_id": "0cd451a76f293562f05c9e8e12c33f00b4d80a63",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/danielsn/s2n/d5d9bf7405bffeee06748157ad0e40b6a95e7dc9/tests/cbmc/include/cbmc_proof/cbmc_utils.h",
"visit_date": "2021-01-21T10:38:27.264621"
} | stackv2 | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <cbmc_proof/nondet.h>
#include <cbmc_proof/proof_allocators.h>
#include <utils/s2n_blob.h>
#include <stddef.h>
#include <stdint.h>
#define IMPLIES(a, b) (!(a) || (b))
struct store_byte_from_buffer {
size_t index;
uint8_t byte;
};
/**
* Asserts whether all bytes from two arrays of same length match.
*/
void assert_bytes_match(const uint8_t *const a, const uint8_t *const b, const size_t len);
/**
* Asserts whether all bytes from an array are equal to c.
*/
void assert_all_bytes_are(const uint8_t *const a, const uint8_t c, const size_t len);
/**
* Asserts whether all bytes from an array are equal to 0.
*/
void assert_all_zeroes(const uint8_t *const a, const size_t len);
/**
* Asserts whether the byte in storage correspond to the byte in the same position in buffer.
*/
void assert_byte_from_buffer_matches(const uint8_t *const buffer, const struct store_byte_from_buffer *const b);
/**
* Asserts whether the byte in storage correspond to the byte in the same position in buffer.
*/
void assert_byte_from_blob_matches(const struct s2n_blob *blob, const struct store_byte_from_buffer *const b);
/**
* Nondeterministically selects a byte from array and stores it into a store_array_list_byte
* structure. Afterwards, one can prove using the assert_byte_from_buffer_matches function
* whether no byte in the array has changed.
*/
void save_byte_from_array(const uint8_t *const array, const size_t size, struct store_byte_from_buffer *const storage);
/**
* Nondeterministically selects a byte from blob and stores it into a store_array_list_byte
* structure. Afterwards, one can prove using the assert_byte_from_blob_matches function
* whether no byte in the blob has changed.
*/
void save_byte_from_blob(const struct s2n_blob *blob, struct store_byte_from_buffer * storage);
/**
* Standard stub function to compare two items.
*/
int nondet_compare(const void *const a, const void *const b);
/**
* Standard stub function to compare two items.
*/
int uninterpreted_compare(const void *const a, const void *const b);
/**
* Standard stub function to compare two items.
*/
bool nondet_equals(const void *const a, const void *const b);
/**
* Standard stub function to compare two items.
* Also enforces uninterpreted_hasher() to be equal for equal values.
*/
bool uninterpreted_equals(const void *const a, const void *const b);
/**
* uninterpreted_equals(), but with an extra assertion that a and b are both not null
*/
bool uninterpreted_equals_assert_inputs_nonnull(const void *const a, const void *const b);
/**
* Standard stub function to hash one item.
*/
uint64_t nondet_hasher(const void *a);
/**
* Standard stub function to hash one item.
*/
uint64_t uninterpreted_hasher(const void *a);
/**
* Standard stub function of a predicate
*/
bool uninterpreted_predicate_fn(uint8_t value);
| 2.234375 | 2 |
2024-11-18T21:06:41.833440+00:00 | 2019-05-14T17:44:39 | 9b5c6cac8d04e8ff7d2c09f4a4ac5ac0cc8c520f | {
"blob_id": "9b5c6cac8d04e8ff7d2c09f4a4ac5ac0cc8c520f",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-14T17:44:39",
"content_id": "31f180e190581b0d109c0fac2e0c672a07fc4ce6",
"detected_licenses": [
"MIT"
],
"directory_id": "05dd0ac039864daf89cefcc32adaff5993b30a18",
"extension": "c",
"filename": "interface_console.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 186670859,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8263,
"license": "MIT",
"license_type": "permissive",
"path": "/sources/interface_console.c",
"provenance": "stackv2-0128.json.gz:84655",
"repo_name": "ggabimoran/ProjetC",
"revision_date": "2019-05-14T17:44:39",
"revision_id": "bda1a335f5faf3f2784699f1176b69be1700de6f",
"snapshot_id": "a96c46e1231b31c86ab940c8d70ff00524b1be1a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ggabimoran/ProjetC/bda1a335f5faf3f2784699f1176b69be1700de6f/sources/interface_console.c",
"visit_date": "2020-05-23T06:59:47.120022"
} | stackv2 | #include "../headers/history.h"
#include "../headers/interface.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <linux/limits.h>
/* Colors and effects support */
#define RESET "\033[0m"
#define RED "\033[31m" /* Red */
#define BOLDRED "\033[1m\033[31m" /* Bold Red */
#define LIGHTYELLOW "\033[93m" /* Light Yellow */
#define LIGHTGREEN "\033[92m" /* Light Green */
#define BLINK "\033[5m" /* Blinking effect */
static bool hint;
void set_hint(bool boolean){
hint=boolean;
}
bool get_hint(){
return hint;
}
void set_fullscreen(bool set) {
if (set)
system("wmctrl -r ':ACTIVE:' -b add,fullscreen &> /dev/null");
else
system("wmctrl -r ':ACTIVE:' -b remove,fullscreen &> /dev/null");
}
/*@requires pboard not null
@assigns nothing
@ensures prints board, shows possible moves if hint set to true */
void print_board(Board* pboard)
{
int width = pboard->width;
int height = pboard->height;
int indexLines[8] = {-1,-1,-1,-1,-1,-1,-1,-1};
int i, j;
Move possible_moves=Move_create();
if (hint){
get_valid_moves(pboard,&possible_moves);
}
/* print header (y coordinates) */
printf("\t\t\t\t Points scored : %d \n\n",get_points_scored());
printf(" ");
for(i = 0 ; i < width ; i++) {
/* Header not displayed correctly if size > 99
* Accepted because a board should not be as big.
* A game on a board this big would be way too
* long anyway.
*/
if(i < 10)
printf(" %d ", i);
else {
printf(" %d", i);
}
}
printf("\n");
/* print x coordinates and board */
for(i = 0 ; i < height ; i++) {
/* print x coordinates */
if(i < 10)
printf("%d ", i);
else
printf("%d", i);
for(j = 0 ; j < width ; j++) {
/* print board line */
printf("[");
if(pboard->points[i][j]) {
if (Move_search(get_lines_history(),j,i,indexLines)) {
printf(LIGHTGREEN "x" RESET);
} else {
printf("\u2022");
}
}
else if (hint && Move_search(possible_moves,j,i,indexLines)){
printf(BLINK LIGHTYELLOW "*" RESET);
}
else {
printf(" ");
}
printf("]");
}
printf("\n");
}
}
Coord select_move(void)
{
int x,y;
printf("Type the point coordinates [x,y] (type x <space> y <enter>) :\n");
int succAffect = -1; /* number of successful affectations */
while(succAffect != 2) {
printf(":> ");
succAffect = scanf(" %d%d", &x, &y);
if (succAffect != 2) {
print_error(WRONG_INPUT_ERR);
}
empty_input_buffer();
}
Coord coord;
coord.x=x;
coord.y=y;
coord.previous=NULL;
return coord;
}
enum action select_action(void)
{
printf("\nSelect : Play move [p] / Cancel previous move [c] / Replay cancelled move [r]\n List valid moves [l] / Ask help [h] / Quit game [q]\n");
char c;
while (true) {
printf(":> ");
scanf(" %c",&c);
/*c = getchar();*/
while('\n'!=getchar()); /* only capture the first character */
c = tolower(c);
switch(c) {
case 'p':
return PLAY_MOVE;
break;
case 'c':
return CANCEL_MOVE;
break;
case 'r':
return REPLAY_MOVE;
break;
case 'l':
return LIST_MOVES;
break;
case 'h':
return ASK_HELP;
break;
case 'q':
return QUIT_GAME;
break;
default:
print_error(WRONG_INPUT_ERR);
break;
}
}
}
void print_help(void)
{
printf("------- HELP -------\n\n");
printf("> The goal is to add points on the board.\n");
printf("> A point can be added to the board if it creates a line of 5 points vertically, horizontally or diagonally.\n");
printf("> Two lines can't have more than one point in common.\n\n");
press_enter_to_continue();
}
/*@requires pmove not null
@assings pmove
@ensures asks player to chose amongst possible lines and frees all those not chosen*/
void select_line(Move* pmove){
int choice;
Move current=*pmove;
int i=0;
printf("List of possible moves :\n");
printf("1 : ");
printf("[%d,%d]",current->x,current->y);
current=current->previous;
i++;
while(!Move_isEmpty(current)){
if (i%5==0){
printf("\n");
printf("%d : ",(i/5)+1);
printf("[%d,%d]",current->x,current->y);
} else {
printf("->[%d,%d]",current->x,current->y);
}
current=current->previous;
i++;
}
printf("\nChoose your line.\n");
do{
scanf("%d",&choice);
}while(0 > choice || choice > (i/5));
i=0;
current=*pmove;
for (i=0;i<(choice-1)*5;i++){
Move_popM(¤t);
}
Move current2=current;
for (i=0;i<4;i++){
current2=current2->previous;
}
Move tmp=current2->previous;
current2->previous=NULL;
pMove_free(&tmp);
printf("You have chosen:\n");
Move_print(current);
*pmove=current;
}
bool confirm_quit_save(Board* pboard) {
char quit;
do {
printf("Do you really want to exit the game? (y/n)\n");
scanf(" %c", &quit);
if (quit != 'y' && quit != 'n')
printf("\nWrong input.\n");
} while (quit != 'y' && quit != 'n');
if(quit == 'y') {
char save;
do {
printf("Do you want to save the current board? (y/n)\n");
scanf(" %c", &save);
if (save != 'y' && save != 'n')
printf("\nWrong input.\n");
} while (save != 'y' && save != 'n');
if (save == 'y')
save_board(pboard);
return true;
}
else
return false;
}
char* ask_savefile_name(void){
char* fileName = (char*)malloc(sizeof(char)*MAX_INPUT);
printf("What name does the file should have ? :> ");
scanf(" %s", fileName);
return fileName;
}
void display_logo(void){
char resolved_path[PATH_MAX];
FILE * fp;
char * line = NULL;
size_t len = 0;
realpath("assets/logo", resolved_path);
fp = fopen(resolved_path, "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((getline(&line, &len, fp)) != -1) {
printf("%s", line);
}
fclose(fp);
if (line)
free(line);
press_enter_to_continue();
clear_screen();
}
void clear_screen(void){
system("clear");
}
void press_enter_to_continue(void){
printf("\n\n \t\t\t\t =================== Press enter to continue ===================\n");
while (true) {
char c=getchar();
if (c=='\n' || c==EOF)
break;
}
}
void print_error(Error err) {
switch (err) {
case WRONG_INPUT_ERR:
fprintf(stderr, RED "Wrong input.\n" RESET);
break;
case FILE_PTR_ERR:
fprintf(stderr, BOLDRED "File could not be opened.\n" RESET);
break;
case FILE_DIMENSION_ERR:
fprintf(stderr, BOLDRED "File error: board width must be equal for each line.\n" RESET);
break;
case FILE_UNKNOWN_CHAR_ERR:
fprintf(stderr, BOLDRED "File error: unknown character.\n" RESET);
break;
case POINT_ALREADY_EXIST_ERR:
fprintf(stderr, BOLDRED "This point already exists.\n" RESET);
break;
case INVALID_COORDINATES_ERR:
fprintf(stderr, BOLDRED "Coordinates are invalid.\n" RESET);
break;
case ALIGNMENT_ERR:
fprintf(stderr, BOLDRED "No valid alignment.\n" RESET);
break;
case CANCEL_ERR:
fprintf(stderr, BOLDRED "Cannot cancel: no move to cancel.\n" RESET);
break;
case REPLAY_ERR:
fprintf(stderr, BOLDRED "Cannot replay: no move has been cancelled.\n" RESET);
break;
default:
fprintf(stderr, RED "Undefined error (requires implementation)." RESET);
exit(EXIT_FAILURE);
break;
/* TODO: press_enter_to_continue() should be called be functions calling print_error */
}
}
void print_game_over(void) {
printf("No more point to be played: the game is over!\n");
}
void print_score(void) {
printf("Your final score is : %d\n", get_points_scored());
} | 2.859375 | 3 |
2024-11-18T21:06:42.489332+00:00 | 2017-10-14T07:43:17 | 5b4dfef502ae0d7d6c6e1c834d3cc1c65dc76414 | {
"blob_id": "5b4dfef502ae0d7d6c6e1c834d3cc1c65dc76414",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-14T07:43:17",
"content_id": "3230267c127ed8452bfea64a64e97576ac0c914f",
"detected_licenses": [
"MIT"
],
"directory_id": "d1873a8ac1d726ca1acc85c0117d127f94759297",
"extension": "c",
"filename": "ccurlmodule.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": 7759,
"license": "MIT",
"license_type": "permissive",
"path": "/src/ccurlmodule.c",
"provenance": "stackv2-0128.json.gz:84916",
"repo_name": "jmarcelino/pyota-ccurl",
"revision_date": "2017-10-14T07:43:17",
"revision_id": "f22965e40ee1fd61e2206684c8fad61128f38bf5",
"snapshot_id": "16cc36cdafc49e29cce50c191d923e8fdf4279af",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jmarcelino/pyota-ccurl/f22965e40ee1fd61e2206684c8fad61128f38bf5/src/ccurlmodule.c",
"visit_date": "2021-07-14T01:15:09.504227"
} | stackv2 | #include <Python.h>
#include <stdint.h>
#define HASH_LENGTH 243
#define NUMBER_OF_ROUNDS 81
#define STATE_LENGTH 3 * HASH_LENGTH
#if PY_MAJOR_VERSION >= 3
#define PYTRIT_CHECK PyLong_Check
#define PYTRIT_AS_LONG PyLong_AsLong
#define PYTRIT_FROM_LONG PyLong_FromLong
#define INITERROR return NULL
#else
#define PYTRIT_CHECK PyInt_Check
#define PYTRIT_AS_LONG PyInt_AsLong
#define PYTRIT_FROM_LONG PyInt_FromLong
#define INITERROR return
#endif
// For consistency with the Curl c library, each trit gets 64 bits.
// In future versions of the software, this will yield significant
// speedups because we can compute multiple hashes concurrently.
typedef int64_t trit_t;
// Copied from https://github.com/iotaledger/ccurl/blob/master/src/lib/Curl.c
#define __TRUTH_TABLE \
1, 0, -1, \
1, -1, 0, \
-1, 1, 0
static const trit_t TRUTH_TABLE[9] = {__TRUTH_TABLE};
typedef struct {
PyObject_HEAD
trit_t _state[STATE_LENGTH];
} Curl;
static PyObject*
Curl_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
Curl *self;
self = (Curl*)type->tp_alloc(type, 0);
if (self != NULL) {
memset(self->_state, 0, STATE_LENGTH * sizeof(trit_t));
}
return (PyObject*)self;
}
static void
_Curl_transform(Curl *self)
{
// Adapted from https://github.com/iotaledger/ccurl/blob/master/src/lib/Curl.c
trit_t scratchpad[STATE_LENGTH];
int round, scratchpadIndex=0, scratchpadIndexSave, stateIndex;
for (round = 0; round < NUMBER_OF_ROUNDS; round++) {
memcpy(scratchpad, self->_state, STATE_LENGTH * sizeof(trit_t));
for (stateIndex = 0; stateIndex < STATE_LENGTH; stateIndex++) {
scratchpadIndexSave = scratchpadIndex;
scratchpadIndex += (scratchpadIndex < 365 ? 364 : -365);
self->_state[stateIndex] = TRUTH_TABLE[scratchpad[scratchpadIndexSave ] + scratchpad[scratchpadIndex ] * 3 + 4];
}
}
}
static PyObject*
Curl_absorb(Curl *self, PyObject *args, PyObject *kwds)
{
PyObject *incoming, *incoming_item;
int i, incoming_count, offset=0;
trit_t incoming_value;
trit_t *trits;
static char *kwlist[] = {"trits", NULL};
// Extract and validate parameters.
// Based on https://github.com/alfredch/iotaPy-Extension/blob/master/iotaPy.c
if (! PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &incoming))
return NULL;
if (! PyList_Check(incoming)) {
PyErr_SetString(PyExc_TypeError, "`trits` argument must be a list.");
return NULL;
}
// Check for invalid values in ``incoming``.
incoming_count = PyList_Size(incoming);
trits = (trit_t*)malloc(incoming_count * sizeof(trit_t));
for (i=0; i < incoming_count; i++) {
incoming_item = PyList_GetItem(incoming, i);
if ((incoming_item == NULL) || ! PYTRIT_CHECK(incoming_item)) {
PyErr_Format(PyExc_ValueError, "`trits` argument contains non-numeric value at index %u.", i);
return NULL;
}
incoming_value = (trit_t)PYTRIT_AS_LONG(incoming_item);
if ((incoming_value < -1) || (incoming_value > 1)) {
PyErr_Format(PyExc_ValueError, "`trits` argument contains value outside range [-1, 1] at index %u.", i);
return NULL;
}
trits[i] = incoming_value;
}
// Copy values to state and transform.
// Adapted from https://github.com/iotaledger/ccurl/blob/master/src/lib/Curl.c
do {
memcpy(self->_state, trits+offset, (incoming_count < HASH_LENGTH ? incoming_count : HASH_LENGTH ) * sizeof(trit_t));
_Curl_transform(self);
offset += HASH_LENGTH;
} while ((incoming_count -= HASH_LENGTH) > 0);
free(trits);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject*
Curl_squeeze(Curl *self, PyObject *args, PyObject *kwds)
{
PyObject *incoming;
int i, incoming_count;
static char *kwlist[] = {"trits", NULL};
// Extract and validate parameters.
if (! PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &incoming))
return NULL;
if (! PyList_Check(incoming)) {
PyErr_SetString(PyExc_TypeError, "`trits` argument must be a list.");
return NULL;
}
// Ensure that ``incoming`` can hold at least 1 hash worth of trits.
for(incoming_count = PyList_Size(incoming); incoming_count < HASH_LENGTH; incoming_count++) {
PyList_Append(incoming, PYTRIT_FROM_LONG(0));
}
// Adapted from https://github.com/iotaledger/ccurl/blob/master/src/lib/Curl.c
// Note that squeeze only copies one hash.
// Can't use ``memcpy`` here because we have to convert ints into ``PyLongObject``.
// This isn't the slow part of Curl (that honor is reserved for ``_Curl_transform``),
// so it shouldn't be that big of a problem.
for (i=0; i < HASH_LENGTH; i++) {
PyList_SetItem(incoming, i, PYTRIT_FROM_LONG(self->_state[i]));
}
_Curl_transform(self);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject*
Curl_reset(Curl *self)
{
memset(self->_state, 0, STATE_LENGTH * sizeof(trit_t));
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef Curl_methods[] = {
{"absorb", (PyCFunction)Curl_absorb, METH_VARARGS|METH_KEYWORDS, "Absorb trits into the sponge."},
{"reset", (PyCFunction)Curl_reset, METH_NOARGS, "Resets internal state."},
{"squeeze", (PyCFunction)Curl_squeeze, METH_VARARGS|METH_KEYWORDS, "Squeeze trits from the sponge."},
{NULL} /* Sentinel */
};
static PyTypeObject ccurl_CurlType = {
PyVarObject_HEAD_INIT(NULL, 0)
"ccurl.Curl", /* tp_name */
sizeof(Curl), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"Curl", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Curl_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
Curl_new, /* tp_new */
};
#if PY_MAJOR_VERSION >= 3
static PyModuleDef ccurlmodule = {
PyModuleDef_HEAD_INIT,
"ccurl",
"C implementation of IOTA curl functionality.",
-1,
NULL, NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC
PyInit_ccurl(void)
#else
void
initccurl(void)
#endif
{
PyObject *hash_length;
#if PY_MAJOR_VERSION >= 3
PyObject *module = PyModule_Create(&ccurlmodule);
#else
PyObject *module = Py_InitModule("ccurl", Curl_methods);
#endif
if (module == NULL)
INITERROR;
ccurl_CurlType.tp_new = PyType_GenericNew;
if (PyType_Ready(&ccurl_CurlType) < 0)
INITERROR;
hash_length = Py_BuildValue("i", HASH_LENGTH);
if (hash_length == NULL)
INITERROR;
// Define module-level symbols, named for compatibility with
// pycurl module in PyOTA library.
Py_INCREF(&ccurl_CurlType);
PyModule_AddObject(module, "Curl", (PyObject*)&ccurl_CurlType);
Py_INCREF(hash_length);
PyModule_AddObject(module, "HASH_LENGTH", hash_length);
#if PY_MAJOR_VERSION >= 3
return module;
#endif
}
| 2.453125 | 2 |
2024-11-18T21:06:42.593121+00:00 | 2022-01-04T14:31:55 | 4b6d60672f95b6aaa10bb745f7cad6fbace2b1f4 | {
"blob_id": "4b6d60672f95b6aaa10bb745f7cad6fbace2b1f4",
"branch_name": "refs/heads/master",
"committer_date": "2022-01-04T14:31:55",
"content_id": "8bc11a2ab3521967897c4e14348acd360b39c654",
"detected_licenses": [
"TCL"
],
"directory_id": "0feb512cfe7c0c2ddab2ab99991f85403f3a68a9",
"extension": "c",
"filename": "schur.c",
"fork_events_count": 8,
"gha_created_at": "2014-03-25T08:29:19",
"gha_event_created_at": "2023-01-04T22:11:21",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 18093495,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4966,
"license": "TCL",
"license_type": "permissive",
"path": "/generic/schur.c",
"provenance": "stackv2-0128.json.gz:85044",
"repo_name": "auriocus/VecTcl",
"revision_date": "2022-01-04T14:31:55",
"revision_id": "8cce67a4f4d54bcb67b601af6569d13407943d4d",
"snapshot_id": "4cef9800ed9c065d2648b630e5d769aac0242625",
"src_encoding": "UTF-8",
"star_events_count": 28,
"url": "https://raw.githubusercontent.com/auriocus/VecTcl/8cce67a4f4d54bcb67b601af6569d13407943d4d/generic/schur.c",
"visit_date": "2023-01-12T21:09:10.019885"
} | stackv2 | #include "schur.h"
#include "clapack_cutdown.h"
#define MIN(X, Y) ((X)<(Y) ? X : Y)
#define MAX(X, Y) ((X)>(Y) ? X : Y)
static int doSchur(Tcl_Interp *interp, Tcl_Obj *matrix, Tcl_Obj **Z, Tcl_Obj **T) {
/* Compute Schur decomposition of a matrix.
* Return Schur vectors in Z and Schur form in T,
*/
/* Convert matrix to VecTcl object */
NumArrayInfo *info = NumArrayGetInfoFromObj(interp, matrix);
if (!info) { return TCL_ERROR; }
/* Check that it is a square matrix */
if (info->nDim != 2) {
/* Could be a scalar. In this case return the trivial
* decomposition */
if (ISSCALARINFO(info)) {
*T = Tcl_DuplicateObj(matrix);
*Z = Tcl_NewDoubleObj(1.0);
return TCL_OK;
}
Tcl_SetResult(interp, "Schur decomposition is only defined for square matrix", NULL);
return TCL_ERROR;
}
/* get matrix dimensions */
long int m = info->dims[0];
long int n = info->dims[1];
if (m != n) {
Tcl_SetResult(interp, "Schur decomposition is only defined for square matrix", NULL);
return TCL_ERROR;
}
char *jobvs = "V";
char *sort = "N";
if (info->type != NumArray_Complex128) {
/* Real-valued matrix, prepare for dgees */
/* create a column-major copy of matrix
* This also converts an integer matrix to double */
*T = NumArrayNewMatrixColMaj(NumArray_Float64, m, n);
NumArrayObjCopy(interp, matrix, *T);
*Z = NumArrayNewMatrixColMaj(NumArray_Float64, m, m);
/* Extract the raw pointers from the VecTcl objects */
double *Tptr = NumArrayGetPtrFromObj(interp, *T);
double *Zptr = NumArrayGetPtrFromObj(interp, *Z);
/* Space to store the eigenvalues */
doublereal *wr = ckalloc(sizeof(doublereal)*n);
doublereal *wi = ckalloc(sizeof(doublereal)*n);
/* setup workspace arrays */
integer lwork = 3*n;
doublereal* work=ckalloc(sizeof(doublereal)*lwork);
logical *bwork = NULL;
integer sdim=0;
/* Leading dimensions of T and Vr
* Don't compute left vectors. */
integer ldt = n;
integer ldz = n;
integer info;
/* Subroutine int dgees_(char *jobvs, char *sort, L_fp select,
* integer *n, doublereal *a, integer *lda, integer *sdim,
* doublereal *wr, doublereal *wi, doublereal *vs, integer *ldvs,
* doublereal *work, integer *lwork, logical *bwork, integer *info) */
/* call out to dgees */
int errcode=dgees_(interp, jobvs, sort, NULL,
&n, Tptr, &ldt, &sdim,
wr, wi, Zptr, &ldz,
work, &lwork, bwork, &info);
/* free workspace */
ckfree(work);
ckfree(wr); ckfree(wi);
if (errcode != TCL_OK) {
/* release temporary storage for result */
Tcl_DecrRefCount(*Z);
Tcl_DecrRefCount(*T);
if (errcode > 0) {
RESULTPRINTF(("DGEES failed to converge at eigenvector %d ", info));
}
return TCL_ERROR;
}
return TCL_OK;
} else {
/* Complex matrix, prepare for zgees */
/* create a column-major copy of matrix
* This also converts an integer matrix to double */
*T = NumArrayNewMatrixColMaj(NumArray_Complex128, m, n);
NumArrayObjCopy(interp, matrix, *T);
*Z = NumArrayNewMatrixColMaj(NumArray_Complex128, m, m);
/* Extract the raw pointers from the VecTcl objects */
doublecomplex *Tptr = NumArrayGetPtrFromObj(interp, *T);
doublecomplex *Zptr = NumArrayGetPtrFromObj(interp, *Z);
/* Space to store the eigenvalues */
doublecomplex *w = ckalloc(sizeof(doublecomplex)*n);
/* setup workspace arrays */
integer lwork = 2*n;
doublecomplex *work=ckalloc(sizeof(doublecomplex)*lwork);
doublereal *rwork=ckalloc(sizeof(doublereal)*n);
logical *bwork = NULL;
integer sdim=0;
/* Leading dimensions of T and Vr
* Don't compute left vectors. */
integer ldt = n;
integer ldz = n;
integer info;
/* Subroutine int zgees_(char *jobvs, char *sort, L_fp select,
* integer *n, doublecomplex *a, integer *lda, integer *sdim,
* doublecomplex *w, doublecomplex *vs, integer *ldvs,
* doublecomplex *work, integer *lwork, doublereal *rwork, logical *bwork, integer *info) */
/* call out to dgees */
int errcode=zgees_(interp, jobvs, sort, NULL,
&n, Tptr, &ldt, &sdim,
w, Zptr, &ldz,
work, &lwork, rwork, bwork, &info);
/* free workspace */
ckfree(work);
ckfree(rwork);
ckfree(w);
if (errcode != TCL_OK) {
/* release temporary storage for result */
Tcl_DecrRefCount(*Z);
Tcl_DecrRefCount(*T);
if (errcode > 0) {
RESULTPRINTF(("ZGEES failed to converge at eigenvector %d ", info));
}
return TCL_ERROR;
}
return TCL_OK;
}
}
int NumArraySchurCmd(ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) {
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "matrix");
return TCL_ERROR;
}
Tcl_Obj *matrix = objv[1];
Tcl_Obj *Z, *T;
if (doSchur(interp, matrix, &Z, &T) != TCL_OK) {
return TCL_ERROR;
}
/* return as list */
Tcl_Obj *result=Tcl_NewObj();
Tcl_ListObjAppendElement(interp, result, Z);
Tcl_ListObjAppendElement(interp, result, T);
Tcl_SetObjResult(interp, result);
return TCL_OK;
}
| 2.25 | 2 |
2024-11-18T21:06:42.681797+00:00 | 2016-02-22T05:20:02 | 804c7f3c4eb89bef2b901cd6952d8ffbcea548f6 | {
"blob_id": "804c7f3c4eb89bef2b901cd6952d8ffbcea548f6",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-22T05:20:02",
"content_id": "7cbc975c6d76f0d8b2d0fe3b99a3506a1fcd19d2",
"detected_licenses": [
"MIT"
],
"directory_id": "1530b85baa3552372f1358cc7b95d5647cbeaf0d",
"extension": "c",
"filename": "stable_marriage.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 52248947,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9799,
"license": "MIT",
"license_type": "permissive",
"path": "/stable_marriage.c",
"provenance": "stackv2-0128.json.gz:85174",
"repo_name": "solongoo/MPI_C_tutorial_examples",
"revision_date": "2016-02-22T05:20:02",
"revision_id": "809ad1810965efe89853c747cb92ac943b0e8fad",
"snapshot_id": "2a780dbc7fbd8779ca854d1651e3d525c6e10028",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/solongoo/MPI_C_tutorial_examples/809ad1810965efe89853c747cb92ac943b0e8fad/stable_marriage.c",
"visit_date": "2021-01-10T03:35:34.876718"
} | stackv2 | #include "time.h"
#include "mpi.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define COORD 0
typedef enum { false, true } bool;
int main(int argc, char* argv[]){
int numprocs; // the number of processes
int pid; // current process id
int N, count = 1, tag = 1, start = 1;
MPI_Status status; // status object
/*Initialization phase*/
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &pid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
N = numprocs / 2; // integer division rounds down
int menPartners[N];
int run = 1;
if(pid == COORD){
// coordinator
int menPartnerValues[N], bestPartnerVal, bestPartner;
int counter[N], stable = false;
int woman, womanID, manID;
int packet[2];
int start = 1;
/* Artificial Barrier: Used for printing ranks before matching */
for(int i = 1; i <= 2*N; i++){
MPI_Send(&start, count, MPI_INT, i, tag, MPI_COMM_WORLD);
MPI_Recv(&start, count, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
}
printf("\n\nCOORDINATOR: MATCHING STARTING\n\n");
for(int i = 1; i <= 2*N; i++)
MPI_Send(&start, count, MPI_INT, i, tag, MPI_COMM_WORLD);
while(true){
// receive reports from men }
for(int i = 1; i <= N; i++){
MPI_Recv(packet, 2, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
menPartners[i - 1] = packet[0];
menPartnerValues[i - 1] = packet[1];
}
printf("COORDINATOR: RUN %d complete - received reports from all men\n", run++);
//count men who thinks he is engaged to woman }
memset(counter, 0, N*sizeof(int));
for(int woman = 0; woman < N; woman++){
if(menPartners[woman] > -1){
counter[menPartners[woman]]++;
}
}
//Determine stability and find out if any men was dumped
stable = true;
for(int woman = 0; woman < N; woman ++){
if(counter[woman] != 1){
stable = false;
// find the best partner
bestPartnerVal = -1;
for(int manID = 0; manID < N; manID++){
// man thinks he is engaged to woman
if(menPartners[manID] == woman){
// woman thinks he is the best partner for her
if(menPartnerValues[manID] > bestPartnerVal){
bestPartner = manID;
bestPartnerVal = menPartnerValues[manID];
}
}
}
// Dump others
for(int manID = 0; manID < N; manID++){
if(menPartners[manID] == woman){
if( manID != bestPartner)
menPartners[manID] = -1;
}
}
}
}
//update men
for(int manID = 0; manID < N; manID++){
packet[0] = menPartners[manID];
packet[1] = stable;
//printf("COORDINATOR: Updating MAN %d with partner id : %d and stability : %d\n", manID + 1, menPartners[manID], stable);
MPI_Send(packet, 2, MPI_INT, manID + 1, tag, MPI_COMM_WORLD);
}
//if stable shut down women
if(stable == true){
/*Make sure all men are shut down*/
for(int manID = 0; manID < N; manID++){
MPI_Recv(&start, count, MPI_INT, manID + 1, tag, MPI_COMM_WORLD, &status);
}
/*
printf("\n\nCOORDINATOR: SYSTEM STABILIZED AFTER %d RUNS\n", run - 1);
for(int i = 0; i < N; i++)
printf("======= MAN %d is paired with WOMAN %d ========\n", i, menPartners[i]); */
printf("COORDINATOR: Men are shut down\n");
for(int woman = 1; woman <= N; woman++)
MPI_Send(&stable, count, MPI_INT, N + woman, tag, MPI_COMM_WORLD);
printf("COORDINATOR: Women are shut down\n");
break;
}
}
}
else if(pid >= 1 && pid <= N){
// Man
int womensRank[N], answer, stability, proposalCount = 0;
int partnerValue = -1; // woman's rank for the man
int partnerID = -1, engaged = false;
int packet[2];
srand(pid);
// rank women
for(int i = 0; i < N; i++)
womensRank[i] = i + 1;
//Shuffle
for(int i = 0 ; i < N ; i ++){
int temp = womensRank[i];
int ind = rand() % N;
womensRank[i] = womensRank[ind];
womensRank[ind] = temp;
}
MPI_Recv(&start, count, MPI_INT, COORD, tag, MPI_COMM_WORLD, &status);
printf("MAN %d: RANKING ", pid);
for(int i = 0; i < N; i++)
printf("%d ", womensRank[i]);
printf("\n");
MPI_Send(&start, count, MPI_INT, COORD, tag, MPI_COMM_WORLD);
MPI_Recv(&start, count, MPI_INT, COORD, tag, MPI_COMM_WORLD, &status);
while(true){
if(engaged == false && proposalCount < N){
// get the id of the highest ranked woman
int w, rank = -1;
for(int i = 0 ; i < N; i++){
if(womensRank[i] > rank){
w = i;
rank = womensRank[i];
}
}
// propose
printf("MAN %d: proposing WOMAN %d\n", pid, w + 1);
MPI_Send(&womensRank[w], count, MPI_INT, N + w + 1, tag, MPI_COMM_WORLD);
// woman responds with her rank of the man
MPI_Recv(&partnerValue, count, MPI_INT, N + w + 1, tag, MPI_COMM_WORLD, &status);
if(partnerValue != false){
engaged = true;
partnerID = w;
printf(">>> MAN %d: engaged to WOMAN %d\n", pid, partnerID + 1);
}
else{
// cannot propose this woman again
womensRank[w] = -1;
printf("___ MAN %d: rejected by WOMAN %d\n", pid, partnerID + 1);
}
proposalCount++;
}
//Report current match to the coordinator
packet[0] = partnerID;
packet[1] = partnerValue;
//printf("MAN %d: reporting to COORDINATOR my partner id : %d and partner Value : %d\n", pid, partnerID + 1, partnerValue);
MPI_Send(packet, 2, MPI_INT, COORD, tag, MPI_COMM_WORLD);
// update from coordinater
MPI_Recv(packet, 2, MPI_INT, COORD, tag, MPI_COMM_WORLD, &status);
int partnerIDstatus = packet[0];
stability = packet[1];
if(stability == true)
break;
if(partnerIDstatus == -1){
engaged = false;
womensRank[partnerID] = -1;
partnerID = -1;
partnerValue = -1;
}
else
partnerID = partnerIDstatus;
//printf("MAN %d: received from COORDINATOR partnerID : %d\n", pid, partnerID + 1);
}
//printf("---- MAN %d: DONE\n", pid);
MPI_Send(&start, count, MPI_INT, COORD, tag, MPI_COMM_WORLD);
}
else{
// woman
int mensRank[N],coordinatorID = 0,engaged = false;
int partnerID = -1, currentRank = -1, currentPartnerID = -1;
int newMenID, newRank, answer;
srand(pid);
// rank women
for(int i = 0; i < N; i++)
mensRank[i] = i + 1;
//Shuffle
for(int i = 0 ; i < N ; i ++){
int temp = mensRank[i];
int ind = rand() % N;
mensRank[i] = mensRank[ind];
mensRank[ind] = temp;
}
MPI_Recv(&start, count, MPI_INT, COORD, tag, MPI_COMM_WORLD, &status);
printf("WOMAN %d: RANKING ", pid - N);
for(int i = 0; i < N; i++)
printf("%d ", mensRank[i]);
printf("\n");
MPI_Send(&start, count, MPI_INT, COORD, tag, MPI_COMM_WORLD);
MPI_Recv(&start, count, MPI_INT, COORD, tag, MPI_COMM_WORLD, &status);
while(true){
// receive proposal
MPI_Recv(&newRank, count, MPI_INT, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, &status);
// coordinator signals end of program
newMenID = status.MPI_SOURCE;
if(newMenID == COORD)
break;
printf("??? WOMAN %d: received proposal from %d\n", pid - N , newMenID);
// if not engaged or finds better man, say yes to new man
if(engaged == false || (mensRank[newMenID - 1] > mensRank[partnerID])){
engaged = true;
partnerID = newMenID;
answer = mensRank[newMenID - 1];
printf(">>> WOMAN %d: accepting %d\n", pid - N, newMenID);
}
else{
answer = false;
printf("!!! WOMAN %d: rejecting %d\n", pid - N, newMenID);
}
MPI_Send(&answer, count, MPI_INT, newMenID, tag, MPI_COMM_WORLD);
}
//printf("---- WOMAN %d: DONE\n", pid);
}
if(pid == COORD){
printf("\n\nCOORDINATOR: SYSTEM STABILIZED AFTER %d RUNS\n", run - 1);
for(int i = 0; i < N; i++)
printf("======= MAN %d is paired with WOMAN %d ========\n", i, menPartners[i]);
}
MPI_Finalize();
return 0;
}
| 2.8125 | 3 |
2024-11-18T21:06:42.980932+00:00 | 2021-02-14T04:35:03 | 4d2178d5ba292dbfb777c0195de8b3acc6254124 | {
"blob_id": "4d2178d5ba292dbfb777c0195de8b3acc6254124",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-14T04:35:03",
"content_id": "9cb87915b4ff962406040765081fb5d963b2db91",
"detected_licenses": [
"MIT"
],
"directory_id": "83c6a192360144ebf82eb68b92fed7fa4d7cc9b3",
"extension": "h",
"filename": "zmath.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 333241435,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 920,
"license": "MIT",
"license_type": "permissive",
"path": "/source/zmath.h",
"provenance": "stackv2-0128.json.gz:85432",
"repo_name": "gek169/TinyGL_3DS",
"revision_date": "2021-02-14T04:35:03",
"revision_id": "bf1555d73f9588d8fde174917ba899dc315779a0",
"snapshot_id": "23b66bb554a640b6e2ae4f35f5e72ec3ae3a5c72",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/gek169/TinyGL_3DS/bf1555d73f9588d8fde174917ba899dc315779a0/source/zmath.h",
"visit_date": "2023-03-06T07:56:03.959031"
} | stackv2 | #ifndef __ZMATH__
#define __ZMATH__
/* Matrix & Vertex */
typedef struct {
float m[4][4];
} M4;
typedef struct {
float m[3][3];
} M3;
typedef struct {
float m[3][4];
} M34;
#define X v[0]
#define Y v[1]
#define Z v[2]
#define W v[3]
typedef struct {
float v[3];
} V3;
typedef struct {
float v[4];
} V4;
void gl_M4_Id(M4 *a);
int gl_M4_IsId(M4 *a);
void gl_M4_Move(M4 *a,M4 *b);
void gl_MoveV3(V3 *a,V3 *b);
void gl_MulM4V3(V3 *a,M4 *b,V3 *c);
void gl_MulM3V3(V3 *a,M4 *b,V3 *c);
void gl_M4_MulV4(V4 * a,M4 *b,V4 * c);
void gl_M4_InvOrtho(M4 *a,M4 b);
void gl_M4_Inv(M4 *a,M4 *b);
void gl_M4_Mul(M4 *c,M4 *a,M4 *b);
void gl_M4_MulLeft(M4 *c,M4 *a);
void gl_M4_Transpose(M4 *a,M4 *b);
void gl_M4_Rotate(M4 *c,float t,int u);
int gl_V3_Norm(V3 *a);
V3 gl_V3_New(float x,float y,float z);
V4 gl_V4_New(float x,float y,float z,float w);
int gl_Matrix_Inv(float *r,float *m,int n);
#endif
// __ZMATH__
| 2.078125 | 2 |
2024-11-18T21:06:43.125850+00:00 | 2015-12-02T18:36:01 | dbb7d7268adfbfb1056107330514fa500b24cac9 | {
"blob_id": "dbb7d7268adfbfb1056107330514fa500b24cac9",
"branch_name": "refs/heads/master",
"committer_date": "2015-12-02T18:36:01",
"content_id": "6507405971a70d7ed3998a778ab48d0f43d3b84a",
"detected_licenses": [
"MIT"
],
"directory_id": "b16c52e9470b3b62dbdf52d640b9603a6ac66f0d",
"extension": "c",
"filename": "2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 46982348,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7453,
"license": "MIT",
"license_type": "permissive",
"path": "/2.c",
"provenance": "stackv2-0128.json.gz:85691",
"repo_name": "marcteves/cs11-class-project",
"revision_date": "2015-12-02T18:36:01",
"revision_id": "e364cc957ac76667612126b00d725b8ff00b7f94",
"snapshot_id": "5a07a323336f73689a6b2971682a71dd491ed2dc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marcteves/cs11-class-project/e364cc957ac76667612126b00d725b8ff00b7f94/2.c",
"visit_date": "2021-01-10T07:53:39.638194"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
hcheckerx1=higher x value of the rightmost line segment
hcheckery1=corresponding y value of the higher x value of the rightmost line segment
lcheckerx1=lower x value of the rightmost line segment
lcheckery1=corresponding y value of the lower x value of the rightmost line segment
hcheckerx2=higher x value of the leftmost line segment
hcheckery2=corresponding y value of the higher x value of the leftmost line segment
lcheckerx2=lower x value of the leftmost line segment
lcheckery2=corresponding y value of the lower x value of the leftmost line segment
high=higher y value between hcheckery1 and lcheckery1
low=lower y value between hcheckery1 and lcheckery1
high1=higher value between hcheckery2 and lcheckery2
low1=lower value between hcheckery2 and lcheckery2
*/
void checker1(float x1, float y1, float x2, float y2, float *hcheckerx1, float *hcheckery1, float *lcheckerx1, float *lcheckery1){
if(x1>x2){
*hcheckerx1=x1;
*hcheckery1=y1;
*lcheckerx1=x2;
*lcheckery1=y2;
}
else{
*hcheckerx1=x2;
*hcheckery1=y2;
*lcheckerx1=x1;
*lcheckery1=y1;
}
}
void vchecker1(float x1, float y1, float x2, float y2, float *hcheckerx1, float *hcheckery1, float *lcheckerx1, float *lcheckery1){
if(y1>y2){
*hcheckerx1=x1;
*hcheckery1=y1;
*lcheckerx1=x2;
*lcheckery1=y2;
}
else{
*hcheckerx1=x2;
*hcheckery1=y2;
*lcheckerx1=x1;
*lcheckery1=y1;
}
}
void vchecker2(float x3, float y3, float x4, float y4, float *hcheckerx2, float *hcheckery2, float *lcheckerx2, float *lcheckery2){
if(y3>y4){
*hcheckerx2=x3;
*hcheckery2=y3;
*lcheckerx2=x4;
*lcheckery2=y4;
}
else{
*hcheckerx2=x4;
*hcheckery2=y4;
*lcheckerx2=x3;
*lcheckery2=y3;
}
}
void checker2(float x3, float y3, float x4, float y4, float *hcheckerx2, float *hcheckery2, float *lcheckerx2, float *lcheckery2){
if(x3>x4){
*hcheckerx2=x3;
*hcheckery2=y3;
*lcheckerx2=x4;
*lcheckery2=y4;
}
else{
*hcheckerx2=x4;
*hcheckery2=y4;
*lcheckerx2=x3;
*lcheckery2=y3;
}
}
void hline(float *hcheckerx1, float *hcheckery1, float *lcheckerx1, float *lcheckery1, float *hcheckerx2, float *hcheckery2, float *lcheckerx2, float *lcheckery2){
if(*hcheckerx2>*hcheckerx1){
float tempx1=*hcheckerx1, tempy1=*hcheckery1, tempx2=*lcheckerx1, tempy2=*lcheckery1;
*hcheckerx1=*hcheckerx2;
*hcheckerx2=tempx1;
*hcheckery1=*hcheckery2;
*hcheckery2=tempy1;
*lcheckerx1=*lcheckerx2;
*lcheckerx2=tempx2;
*lcheckery1=*lcheckery2;
*lcheckery2=tempy2;
}
}
void hvline(float *hcheckerx1, float *hcheckery1, float *lcheckerx1, float *lcheckery1, float *hcheckerx2, float *hcheckery2, float *lcheckerx2, float *lcheckery2){
if(*hcheckery2>*hcheckery1){
float tempx1=*hcheckerx1, tempy1=*hcheckery1, tempx2=*lcheckerx1, tempy2=*lcheckery1;
*hcheckerx1=*hcheckerx2;
*hcheckerx2=tempx1;
*hcheckery1=*hcheckery2;
*hcheckery2=tempy1;
*lcheckerx1=*lcheckerx2;
*lcheckerx2=tempx2;
*lcheckery1=*lcheckery2;
*lcheckery2=tempy2;
}
}
int main(){
float x1, x2, x3, x4, y1, y2, y3, y4, m1, m2, b1, b2, interx, intery, first, second;
float lcheckerx1, hcheckerx1, lcheckery1, hcheckery1;
float lcheckerx2, hcheckerx2, lcheckery2, hcheckery2;
char string[1000], temp[1000]="";
float x[8];
int k=0, i;
printf("Problem 2: Given 4 points ((x1,y1), (x2,y2), (x3,y3), (x4,y4)), \nthe program will determine the intersection of the line segments formed by \n(x1,y1), (x2,y2) and (x3,y3), (x4,y4).\n");
printf("Enter x1,y1,x2,y2,x3,y3,x4,y4: ");
fgets(string, 1000, stdin);
string[strlen(string)-1]='\0';
for(i=0; i<strlen(string); i++){
for(i; string[i]!=',' && i<strlen(string); i++){
strncat(temp, &string[i], 1);
}
x[k]=atof(temp);
k++;
memset(&temp[0], 0, sizeof(temp));
}
x1=x[0];
y1=x[1];
x2=x[2];
y2=x[3];
x3=x[4];
y3=x[5];
x4=x[6];
y4=x[7];
printf("The output is: ");
if((x2-x1)==0){
if((x4-x3)==0){
vchecker1(x1, y1, x2, y2, &hcheckerx1, &hcheckery1, &lcheckerx1, &lcheckery1);
vchecker2(x3, y3, x4, y4, &hcheckerx2, &hcheckery2, &lcheckerx2, &lcheckery2);
hvline(&hcheckerx1, &hcheckery1, &lcheckerx1, &lcheckery1, &hcheckerx2, &hcheckery2, &lcheckerx2, &lcheckery2);
if(hcheckerx1==hcheckerx2){
if(lcheckery1==hcheckery2){
printf("The lines will intersect at (%.3f, %.3f).\n", lcheckerx1, lcheckery1);
}
else if((lcheckery1>=lcheckery2)&&(lcheckery1<=hcheckery2)){
printf("The lines are coinciding.\n");
}
else{
printf("No intersection.\n");
}
}
else{
printf("No intersection.\n");
}
}
else{
vchecker1(x1, y1, x2, y2, &hcheckerx1, &hcheckery1, &lcheckerx1, &lcheckery1);
checker2(x3, y3, x4, y4, &hcheckerx2, &hcheckery2, &lcheckerx2, &lcheckery2);
float high, low;
if(hcheckery2<lcheckery2){
high1=lcheckery2, low1=hcheckery2;
}
else{
high1=hcheckery2, low1=lcheckery2;
}
m2=(y4-y3)/(x4-x3);
b2=(y3)-(m2*x3);
interx=hcheckerx1;
intery=(m2*(interx))+(b2);
if((intery>=lcheckery1 && intery<=hcheckery1) && (interx>=lcheckerx2 && interx<=hcheckerx2) && (intery<=high1 && intery>=low1)){
printf("The lines will intersect at (%.3f, %.3f).\n", interx, intery);
}
else{
printf("No intersection.\n");
}
}
}
else if((x4-x3)==0){
checker1(x1, y1, x2, y2, &hcheckerx1, &hcheckery1, &lcheckerx1, &lcheckery1);
vchecker2(x3, y3, x4, y4, &hcheckerx2, &hcheckery2, &lcheckerx2, &lcheckery2);
float high, low;
if(hcheckery1<lcheckery1){
high=lcheckery1, low=hcheckery1;
}
else{
high=hcheckery1, low=lcheckery1;
}
m1=(y2-y1)/(x2-x1);
b1=(y1)-(m1*x1);
interx=hcheckerx2;
intery=(m1*(interx))+(b1);
if((intery>=lcheckery2 && intery<=hcheckery2) && (interx>=lcheckerx1 && interx<=hcheckerx1) && (intery<=high && intery>=low)){
printf("The lines will intersect at (%.3f, %.3f).\n", interx, intery);
}
else{
printf("No intersection.\n");
}
}
else{
m1=(y2-y1)/(x2-x1);
m2=(y4-y3)/(x4-x3);
b1=(y1)-(m1*x1);
b2=(y3)-(m2*x3);
checker1(x1, y1, x2, y2, &hcheckerx1, &hcheckery1, &lcheckerx1, &lcheckery1);
checker2(x3, y3, x4, y4, &hcheckerx2, &hcheckery2, &lcheckerx2, &lcheckery2);
hline(&hcheckerx1, &hcheckery1, &lcheckerx1, &lcheckery1, &hcheckerx2, &hcheckery2, &lcheckerx2, &lcheckery2);
if(m1==m2){
if(b1==b2){
if((lcheckerx1==hcheckerx1) && (lcheckery1==hcheckery2)){
printf("The lines will intersect at (%.3f, %.3f).\n", lcheckerx1, lcheckery1);
}
else if((lcheckerx1>=lcheckerx2)&&(lcheckerx1<=hcheckerx2)){
printf("The lines are coinciding.\n");
}
else{
printf("No intersection.\n");
}
}
else{
printf("No intersection.\n");
}
}
else{
interx=(b2-b1)/(m1-m2);
intery=(m1*(interx))+(b1);
float high, low, high1, low1;
if(hcheckery1<lcheckery1){
high=lcheckery1, low=hcheckery1;
}
else{
high=hcheckery1, low=lcheckery1;
}
if(hcheckery2<lcheckery2){
high1=lcheckery2, low1=hcheckery2;
}
else{
high1=hcheckery2, low1=lcheckery2;
}
if(x1>x2){
first=x1;
second=x2;
}
else{
first=x2;
second=x1;
}
if(((interx<=hcheckerx1) && (interx>=lcheckerx1) && (interx<=hcheckerx2) && (interx>=lcheckerx2))
&& ((intery<=high) && (intery>=low) && (intery<=high1) && (intery>=low1))){
printf("The lines will intersect at (%.3f,%.3f).\n", interx, intery);
}
else{
printf("No intersection.\n");
}
}
}
} | 2.765625 | 3 |
2024-11-18T21:06:43.262351+00:00 | 2021-10-12T10:18:36 | f53da16be063ab87788c34d5570240a6880d4dd5 | {
"blob_id": "f53da16be063ab87788c34d5570240a6880d4dd5",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-12T10:18:36",
"content_id": "c8ee35c5c4aa7f2529c213c24d07e00f1e759e05",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3755cd56bdd0a7ad5ce7f8c5539b4d5a920ef512",
"extension": "h",
"filename": "List.h",
"fork_events_count": 0,
"gha_created_at": "2019-10-05T19:17:15",
"gha_event_created_at": "2021-10-12T10:11:10",
"gha_language": "C#",
"gha_license_id": "Apache-2.0",
"github_id": 213057600,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 759,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Semester3/тест3.3/3.1/3.1/List.h",
"provenance": "stackv2-0128.json.gz:85948",
"repo_name": "NikitaBabich26rus/SPbU-HomeWork",
"revision_date": "2021-10-12T10:18:36",
"revision_id": "f95dd0da5b7ba673bd58a2f0cc68887d7c9da1bf",
"snapshot_id": "3e314b4f90a937f31086e12fbe49684d0e53322d",
"src_encoding": "WINDOWS-1251",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/NikitaBabich26rus/SPbU-HomeWork/f95dd0da5b7ba673bd58a2f0cc68887d7c9da1bf/Semester3/тест3.3/3.1/3.1/List.h",
"visit_date": "2023-08-23T16:12:26.124582"
} | stackv2 | #pragma once
// Элемент списка
struct ListElement;
// Список
struct List;
// Создать список
List* createList();
// Проверка списка на пустоту
bool empty(List* head);
// Добавить элемент списка
void push(List* list, int value);
// Удалить элемент списка
void deleteElement(List* list, int value);
// Вывести список
void outputList(List* list);
// Проверить список на отсортированность
bool checkSort(List* list);
// Проверка списка на наличие в нем данного элемента
bool contains(List* list, int value);
// Удалить список
void deleteList(List* list);
| 2.28125 | 2 |
2024-11-18T21:06:43.337635+00:00 | 2021-11-02T20:12:32 | cc53e6e05c924723673f80a2418af150356b9a9a | {
"blob_id": "cc53e6e05c924723673f80a2418af150356b9a9a",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-02T20:12:32",
"content_id": "c118e140e397db9757b988a240ddd819207d08fb",
"detected_licenses": [
"MIT"
],
"directory_id": "070557b28a9640dd8a9e570c74025b122e7a92ed",
"extension": "h",
"filename": "compfuncs.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 423981557,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 960,
"license": "MIT",
"license_type": "permissive",
"path": "/save_version/include/compfuncs.h",
"provenance": "stackv2-0128.json.gz:86077",
"repo_name": "Raikils/OC_lab1",
"revision_date": "2021-11-02T20:12:32",
"revision_id": "5df20c5eb645961231bfb996e7b9702c6202c809",
"snapshot_id": "305c771388ea2cbb73cf67f60f765a3e586c4028",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Raikils/OC_lab1/5df20c5eb645961231bfb996e7b9702c6202c809/save_version/include/compfuncs.h",
"visit_date": "2023-08-26T14:19:42.244311"
} | stackv2 | #ifndef _OS_LAB1_COMPFUNCS_H
#define _OS_LAB1_COMPFUNCS_H
#include <stdbool.h>
#define TYPENAME_and bool
#define TYPENAME_or bool
#define TYPENAME_imul int
#define TYPENAME_fmul double
#define TYPENAME_imin unsigned int
#define TYPENAME_fmin double
#define TYPE(op) TYPENAME_ ## op
enum _compfunc_status {
COMPFUNC_SUCCESS = 0,
COMPFUNC_SOFT_FAIL,
COMPFUNC_HARD_FAIL,
COMPFUNC_STATUS_MAX
};
typedef enum _compfunc_status compfunc_status_t;
static char *_symbolic_status[] = { [COMPFUNC_SUCCESS] = "value",
[COMPFUNC_SOFT_FAIL] = "soft-fail",
[COMPFUNC_HARD_FAIL] = "hard-fail",
[COMPFUNC_STATUS_MAX] = "undefined" };
static inline char *symbolic_status(compfunc_status_t status)
{
return _symbolic_status[(long )(unsigned )status >= COMPFUNC_STATUS_MAX ? COMPFUNC_STATUS_MAX : status];
}
#define DECLARE_COMPFUNC(op, name) \
extern compfunc_status_t name ## _ ## op(int , TYPE(op) *)
#endif // _OS_LAB1_COMPFUNCS_H
| 2.046875 | 2 |
2024-11-18T21:06:43.607892+00:00 | 2023-08-13T07:00:15 | c572b20347ceced8cdca37e256122df1d8cff5a0 | {
"blob_id": "c572b20347ceced8cdca37e256122df1d8cff5a0",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-13T07:00:15",
"content_id": "08ef256287396be6ee563dbc889a52789f3bf170",
"detected_licenses": [
"MIT"
],
"directory_id": "2266eb133fc3121daf0aa7f4560626b46b94afe0",
"extension": "c",
"filename": "feicui2.c",
"fork_events_count": 49,
"gha_created_at": "2017-11-28T03:05:14",
"gha_event_created_at": "2023-02-01T03:42:14",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 112278568,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1911,
"license": "MIT",
"license_type": "permissive",
"path": "/d/shenfeng/feicui2.c",
"provenance": "stackv2-0128.json.gz:86334",
"repo_name": "oiuv/mud",
"revision_date": "2023-08-13T07:00:15",
"revision_id": "e9ff076724472256b9b4bd88c148d6bf71dc3c02",
"snapshot_id": "6fbabebc7b784279fdfae06d164f5aecaa44ad90",
"src_encoding": "UTF-8",
"star_events_count": 99,
"url": "https://raw.githubusercontent.com/oiuv/mud/e9ff076724472256b9b4bd88c148d6bf71dc3c02/d/shenfeng/feicui2.c",
"visit_date": "2023-08-18T20:18:37.848801"
} | stackv2 | #include <ansi.h>
inherit ROOM;
void create()
{
set("short", "翡翠池");
set("long", @LONG
这里是一个四周镶满翡翠的圆池,你身在池中,伸下手去
只觉清凉入骨,双手捧起水来但见池水澄净清澈,更无纤毫苔
泥,原来圆池四周都是翡翠,池水才映成绿色。洁白的玉峰映
在碧绿的池中,显得格外的明艳洁净,幽绝清绝。只见池边长
满了翠绿的青藤(rattan)。池底似乎有个洞(hole)。
LONG);
set("item_desc", ([
"rattan" : GRN "\n生长在翡翠池岸边的翠绿青藤,可以由它爬上岸去。\n" NOR,
"hole" : WHT "\n潜藏在池底的一个小洞,你似乎可以钻进去。\n" NOR,
]));
setup();
}
void init()
{
add_action("do_zuan", "zuan");
add_action("do_climb", "climb");
}
int do_zuan(string arg)
{
object me = this_player();
if (! arg || arg != "hole")
return notify_fail("你要钻什么?\n");
message("vision", HIC "只见" + me->name() + HIC "紧闭呼吸,一个猛子朝池底"
"的洞钻去。\n" NOR, environment(me), ({me}) );
write(HIC "\n你朝池底的洞钻去,哪知突然一道暗流冲来,把你扯入旋涡中。\n\n" NOR);
me->move(__DIR__"lake3");
message_vision(HIC "\n$N" HIC "被暗流从瀑布里抛了出来。\n\n" NOR, me);
return 1;
}
int do_climb(string arg)
{
object me = this_player();
if (! arg || arg != "rattan")
return notify_fail("你要爬什么?\n");
message("vision", HIC "只见" + me->name() + HIC "顺着青藤爬了上去。\n" NOR,
environment(me), ({me}));
me->move(__DIR__"feicui1");
message_vision(HIC "\n$N" HIC "顺着青藤水淋淋地爬了上来。\n\n" NOR, me);
return 1;
}
| 2.40625 | 2 |
2024-11-18T21:06:43.687631+00:00 | 2015-08-19T15:19:55 | 4d6e75b9927fd76d34a332917d46c37f4c5aed65 | {
"blob_id": "4d6e75b9927fd76d34a332917d46c37f4c5aed65",
"branch_name": "refs/heads/master",
"committer_date": "2015-08-19T15:19:55",
"content_id": "d3472ecc2208b9f3babdb89d5ccbf505be0b1eeb",
"detected_licenses": [
"MIT"
],
"directory_id": "f60ca7d81a87000688ce47969f67671c106d3e6a",
"extension": "c",
"filename": "jogodavelha.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 41041761,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 17871,
"license": "MIT",
"license_type": "permissive",
"path": "/jogodavelha.c",
"provenance": "stackv2-0128.json.gz:86463",
"repo_name": "RenanGaleno/jogodavelha",
"revision_date": "2015-08-19T15:19:55",
"revision_id": "544735e4d5bf77cce64b8155bac8477fd7c21194",
"snapshot_id": "b39d57c82685f3de96c8c5bcebfaf47fd148f215",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RenanGaleno/jogodavelha/544735e4d5bf77cce64b8155bac8477fd7c21194/jogodavelha.c",
"visit_date": "2021-01-19T17:06:44.320807"
} | stackv2 | #include <stdio.h>//Default
#include <stdlib.h>//Default
#include <string.h>//For treating strings
#include <locale.h>//For localized text
#include <time.h>//For time operations, used by delay function
#include <curses.h>//For advanced screen out
char *title = "Jogo da Velha";//Game title, as an string for easier use when printing on screen center
short int row,col;//Screen size
//Players names and scores
char player1[100];//Player1 name
short int player1Score = 0;//Player1 score
char player2[100];//Player2 name
short int player2Score = 0;//Player2 score
//Initialize game table
char game[3][3];//3 x 3 table
/* Auxiliar third party delay function - http://c-for-dummies.com/blog/?p=69 */
void delay(int milliseconds)
{
long pause;
clock_t now,then;
pause = milliseconds*(CLOCKS_PER_SEC/1000);
now = then = clock();
while( (now-then) < pause )
now = clock();
}
//Print centered function
void printCentered(int row, int totalcols, char *string2print){
move(row, 0);
clrtoeol();
mvprintw(row, (totalcols-strlen(string2print))/2,"%s\n", string2print);
}
//Splash with ASCII art
void splashScreen(){
curs_set(0);
mvprintw(3, 0, " # # # ");
mvprintw(4, 0, " # #### #### #### ##### ## # # ###### # # # ## ");
mvprintw(5, 0, " # # # # # # # # # # # # # # # # # # # ");
mvprintw(6, 0, " # # # # # # # # # # # # ##### # ###### # #");
mvprintw(7, 0, "# # # # # ### # # # # ###### # # # # # # ######");
mvprintw(8, 0, "# # # # # # # # # # # # # # # # # # # #");
mvprintw(9, 0, " ##### #### #### #### ##### # # # ###### ###### # # # #");
refresh();
delay(2000);
curs_set(1);
}
//Initialize game table
void initializeGameTable(){
game[0][0] = '1'; game[0][1] = '2'; game[0][2] = '3';
game[1][0] = '4'; game[1][1] = '5'; game[1][2] = '6';
game[2][0] = '7'; game[2][1] = '8'; game[2][2] = '9';
}
/* Function to show the header, including title and players names */
void refreshScores(){
//Check if players names was informed
if(strcmp(player1, "")){
//Print a divisor line
for(short int _clrscr_i = 0; _clrscr_i < col; _clrscr_i++){
mvprintw(2,_clrscr_i,"-");
}
//Print the player names
attron(COLOR_PAIR(2));//Set player 1 color
mvprintw(3, 0, "P1: %s, com X - %d vitórias", player1, player1Score);//Show player1 data
attron(COLOR_PAIR(3));//Set player 2 color
if(!strcmp(player2, "")){
mvprintw(3, col/2, "PC, com O - %d vitórias", player2Score);//Show PC data
}else{
mvprintw(3, col/2, "P2: %s, com O - %d vitórias", player2, player2Score);//Show player2 data
}
attron(COLOR_PAIR(1));//Set default color
//Break a line
printw("\n");
}
}
void showHeader(){
//Clear screen
wclear(stdscr);
//Declare i for counter
short int _clrscr_i;
//Print the first divisor line
for(_clrscr_i = 0; _clrscr_i < col; _clrscr_i++){
mvprintw(0,_clrscr_i,"-");
}
//Print the # above title
for(_clrscr_i = 0; _clrscr_i < ((col-strlen(title))/2)-1; _clrscr_i++){
mvprintw(1,_clrscr_i,"#");
}
//Print title in the center
mvprintw(1, (col-strlen(title))/2,"%s\n", title);
//Print the # after title
for(_clrscr_i = _clrscr_i + strlen(title) + 2; _clrscr_i < col; _clrscr_i++){
mvprintw(1, _clrscr_i, "#");
}
//Show scores
refreshScores();
//Print a divisor line
for(_clrscr_i = 0;_clrscr_i < col; _clrscr_i++){
printw("-");
}
}
//Request names from the players
bool requestedNames = 0;
void requestPlayerNames(){
if(!requestedNames){
//While the player1 name is empty, ask for it
while(!strcmp(player1,"")){
printw("Digite o nome do primeiro jogador: \n");
attron(COLOR_PAIR(2));
getstr(player1);
attron(COLOR_PAIR(1));
}
//While the player2 name is empty, ask for it
//while(!strcmp(player2,"")){
printw("Digite o nome do segundo jogador, ou deixe em branco e pressione enter para jogar contra o PC: \n");
attron(COLOR_PAIR(3));
getstr(player2);
attron(COLOR_PAIR(1));
//}
requestedNames = 1;
}
}
//Set color for use in refreshGame()
void setColorRefreshGame(char symbol){
if(symbol == 'X'){
attron(COLOR_PAIR(2));
} else if(symbol == 'O'){
attron(COLOR_PAIR(3));
}else{
attron(COLOR_PAIR(1));
}
}
//Refresh the game table
void refreshGame(){
//Here we'll check if it's from player 1, or 2, or none, and colour respectively, and then print X, O, or the numbers and table format
setColorRefreshGame(game[0][0]);
mvprintw(6, ((col-9)/2), "%c", game[0][0]);
attron(COLOR_PAIR(1));
mvprintw(6, ((col-9)/2)+1, " | ");
setColorRefreshGame(game[0][1]);
mvprintw(6, ((col-9)/2)+4, "%c", game[0][1]);
attron(COLOR_PAIR(1));
mvprintw(6, ((col-9)/2)+5, " | ");
setColorRefreshGame(game[0][2]);
mvprintw(6, ((col-9)/2)+8, "%c", game[0][2]);
attron(COLOR_PAIR(1));
mvprintw(7, (col-9)/2, "--+---+--\n");
setColorRefreshGame(game[1][0]);
mvprintw(8, ((col-9)/2), "%c", game[1][0]);
attron(COLOR_PAIR(1));
mvprintw(8, ((col-9)/2)+1, " | ");
setColorRefreshGame(game[1][1]);
mvprintw(8, ((col-9)/2)+4, "%c", game[1][1]);
attron(COLOR_PAIR(1));
mvprintw(8, ((col-9)/2)+5, " | ");
setColorRefreshGame(game[1][2]);
mvprintw(8, ((col-9)/2)+8, "%c", game[1][2]);
attron(COLOR_PAIR(1));
mvprintw(9, (col-9)/2, "--+---+--\n");
setColorRefreshGame(game[2][0]);
mvprintw(10, ((col-9)/2), "%c", game[2][0]);
attron(COLOR_PAIR(1));
mvprintw(10, ((col-9)/2)+1, " | ");
setColorRefreshGame(game[2][1]);
mvprintw(10, ((col-9)/2)+4, "%c", game[2][1]);
attron(COLOR_PAIR(1));
mvprintw(10, ((col-9)/2)+5, " | ");
setColorRefreshGame(game[2][2]);
mvprintw(10, ((col-9)/2)+8, "%c", game[2][2]);
attron(COLOR_PAIR(1));
//Break a line
printw("\n");
}
//Check if someone win the game
int checkWin(){
bool p1win = 0;
bool p2win = 0;
//Check X axis
for(short int i=0; i<3; i++){
if(game[i][0] == game[i][1] && game[i][1] == game[i][2] && game[i][2] == 'X')
p1win = 1;
if(game[i][0] == game[i][1] && game[i][1] == game[i][2] && game[i][2] == 'O')
p2win = 1;
}
//Check Y axis
for(short int i=0; i<3; i++){
if(game[0][i] == game[1][i] && game[1][i] == game[2][i] && game[2][i] == 'X')
p1win = 1;
if(game[0][i] == game[1][i] && game[1][i] == game[2][i] && game[2][i] == 'O')
p2win = 1;
}
//Check diagonal 1
if(game[0][0] == game[1][1] && game[1][1] == game[2][2] && game[2][2] == 'X')
p1win = 1;
if(game[0][0] == game[1][1] && game[1][1] == game[2][2] && game[2][2] == 'O')
p2win = 1;
//Check diagonal 2
if(game[0][2] == game[1][1] && game[1][1] == game[2][0] && game[2][0] == 'X')
p1win = 1;
if(game[0][2] == game[1][1] && game[1][1] == game[2][0] && game[2][0] == 'O')
p2win = 1;
//Check and return the winner, or 0 if the game is still running
if(p1win){
return 1;
}else if(p2win){
return 2;
}else{
return 0;
}
}
//Request player match
short int actualPlayer = 1;
void requestMatch(){
short int choosenNumberValid = 0;
char choosenNumber;
char playerSymbol;
while(!choosenNumberValid){
//Clear line 13
move(13,0);
clrtoeol();
//Ask user for the number
if(actualPlayer == 1){
attron(COLOR_PAIR(2));//Set player 1 color
mvprintw(13, 0, "%s", player1);//Print player name
attron(COLOR_PAIR(1));//Set default color
printw(", sua vez, escolha um número e pressione no teclado.");
playerSymbol = 'X';
}
//Ask user for the number
if(actualPlayer == 2 && !strcmp(player2, "")){
attron(COLOR_PAIR(3));
mvprintw(13, 0, "%s", player2);
attron(COLOR_PAIR(1));
printw(", sua vez, escolha um número e pressione no teclado.");
playerSymbol = 'O';
}
//Get and validate the number if it's user, or use a little IA if it's PC
if(actualPlayer == 1){
choosenNumber = getch();
}else{
if(strcmp(player2, "")){
choosenNumber = getch();
}else{
//Use A.I. to get a number to play
//Check if there is a place that we can win the game, or the player can win
if(((game[0][0] == 'X' && game[0][1] == 'X') || (game[0][0] == 'O' && game[0][1] == 'O')) && game[0][2] == '3'){
choosenNumber = '3';
}else if(((game[0][1] == 'X' && game[0][2] == 'X') || (game[0][1] == 'O' && game[0][2] == 'O')) && game[0][0] == '1'){
choosenNumber = '1';
}else if(((game[1][0] == 'X' && game[1][1] == 'X') || (game[1][0] == 'O' && game[1][1] == 'O')) && game[1][2] == '6'){
choosenNumber = '6';
}else if(((game[1][1] == 'X' && game[1][2] == 'X') || (game[1][1] == 'O' && game[1][2] == 'O')) && game[1][0] == '4'){
choosenNumber = '4';
}else if(((game[2][0] == 'X' && game[2][1] == 'X') || (game[2][0] == 'O' && game[2][1] == 'O')) && game[2][2] == '9'){
choosenNumber = '9';
}else if(((game[2][1] == 'X' && game[2][2] == 'X') || (game[2][1] == 'O' && game[2][2] == 'O')) && game[2][0] == '7'){
choosenNumber = '7';
}else if(((game[0][0] == 'X' && game[1][0] == 'X') || (game[0][0] == 'O' && game[1][0] == 'O')) && game[2][0] == '7'){
choosenNumber = '7';
}else if(((game[1][0] == 'X' && game[2][0] == 'X') || (game[1][0] == 'O' && game[2][0] == 'O')) && game[0][0] == '1'){
choosenNumber = '1';
}else if(((game[0][1] == 'X' && game[1][1] == 'X') || (game[0][1] == 'O' && game[1][1] == 'O')) && game[2][1] == '8'){
choosenNumber = '8';
}else if(((game[1][1] == 'X' && game[2][1] == 'X') || (game[1][1] == 'O' && game[2][1] == 'O')) && game[0][1] == '2'){
choosenNumber = '2';
}else if(((game[0][2] == 'X' && game[1][2] == 'X') || (game[0][2] == 'O' && game[1][2] == 'O')) && game[2][2] == '9'){
choosenNumber = '9';
}else if(((game[1][2] == 'X' && game[2][2] == 'X') || (game[1][2] == 'O' && game[2][2] == 'O')) && game[0][2] == '3'){
choosenNumber = '3';
}else if(((game[0][0] == 'X' && game[1][1] == 'X') || (game[0][0] == 'O' && game[1][1] == 'O')) && game[2][2] == '9'){
choosenNumber = '9';
}else if(((game[1][1] == 'X' && game[2][2] == 'X') || (game[1][1] == 'O' && game[2][2] == 'O')) && game[0][0] == '1'){
choosenNumber = '1';
}else if(((game[0][2] == 'X' && game[1][1] == 'X') || (game[0][2] == 'O' && game[1][1] == 'O')) && game[2][0] == '7'){
choosenNumber = '7';
}else if(((game[1][1] == 'X' && game[2][0] == 'X') || (game[1][1] == 'O' && game[2][0] == 'O')) && game[0][2] == '3'){
choosenNumber = '3';
}else{
//Check if there is some blank space between two filled
if(((game[0][0] == 'X' && game[0][2] == 'X') || (game[0][0] == 'O' && game[0][2] == 'O')) && game[0][1] == '2'){
choosenNumber = '2';
}else if(((game[1][0] == 'X' && game[1][2] == 'X') || (game[1][0] == 'O' && game[1][2] == 'O')) && game[1][1] == '5'){
choosenNumber = '5';
}else if(((game[2][0] == 'X' && game[2][2] == 'X') || (game[2][0] == 'O' && game[2][2] == 'O')) && game[2][1] == '8'){
choosenNumber = '8';
}else if(((game[0][0] == 'X' && game[2][0] == 'X') || (game[0][0] == 'O' && game[2][0] == 'O')) && game[1][0] == '4'){
choosenNumber = '4';
}else if(((game[0][1] == 'X' && game[2][1] == 'X') || (game[0][1] == 'O' && game[2][1] == 'O')) && game[1][1] == '5'){
choosenNumber = '5';
}else if(((game[0][2] == 'X' && game[2][2] == 'X') || (game[0][2] == 'O' && game[2][2] == 'O')) && game[1][2] == '6'){
choosenNumber = '6';
}else{
//If there's no blank spaces on centers...
//Select by priority
if(game[1][1] == '5'){
choosenNumber = '5';
}else if(game[0][0] == '1'){
choosenNumber = '1';
}else if(game[2][2] == '9'){
choosenNumber = '9';
}else if(game[0][2] == '3'){
choosenNumber = '3';
}else if(game[2][0] == '7'){
choosenNumber = '7';
}else if(game[0][1] == '2'){
choosenNumber = '2';
}else if(game[1][0] == '4'){
choosenNumber = '4';
}else if(game[1][2] == '6'){
choosenNumber = '6';
}else if(game[2][1] == '8'){
choosenNumber = '8';
}
}
}
mvprintw(0, 0, "PC: %c", choosenNumber);
refresh();
}
}
switch(choosenNumber){
case '1':
if(game[0][0] == choosenNumber)
choosenNumberValid = 1;
break;
case '2':
if(game[0][1] == choosenNumber)
choosenNumberValid = 1;
break;
case '3':
if(game[0][2] == choosenNumber)
choosenNumberValid = 1;
break;
case '4':
if(game[1][0] == choosenNumber)
choosenNumberValid = 1;
break;
case '5':
if(game[1][1] == choosenNumber)
choosenNumberValid = 1;
break;
case '6':
if(game[1][2] == choosenNumber)
choosenNumberValid = 1;
break;
case '7':
if(game[2][0] == choosenNumber)
choosenNumberValid = 1;
break;
case '8':
if(game[2][1] == choosenNumber)
choosenNumberValid = 1;
break;
case '9':
if(game[2][2] == choosenNumber)
choosenNumberValid = 1;
break;
default:
choosenNumberValid = 0;
break;
}
}
//Cast choosen number to int
choosenNumberValid = choosenNumber - '0';
//Fill the game table
if(choosenNumberValid < 4){
game[0][choosenNumberValid-1] = playerSymbol;
}
if(choosenNumberValid >= 4 && choosenNumberValid < 7){
game[1][choosenNumberValid-4] = playerSymbol;
}
if(choosenNumberValid >= 7){
game[2][choosenNumberValid-7] = playerSymbol;
}
//Go to next player
if (actualPlayer == 1){
actualPlayer = 2;
}else{
actualPlayer = 1;
}
}
int main(){
setlocale(LC_ALL, "ptb");//Set pt-br locale
initscr();//Initialize cursor mode
start_color();//Initialize color mode
getmaxyx(stdscr,row,col);//Get screen dimensions
attron(A_BOLD);
//Configure color pairs
init_pair(1, COLOR_WHITE, COLOR_BLACK);//Our default
init_pair(2, COLOR_BLUE, COLOR_BLACK);//For Player 1
init_pair(3, COLOR_RED, COLOR_BLACK);//For Player 2
//Set default color pair
wbkgd(stdscr, COLOR_PAIR(1));
//Refresh screen to apply
refresh();
//Splash screen
splashScreen();
//wclear(stdscr);
//Ready!
char playAgain = 's';//Answer to the play again question on the end
//Restart the game while play again answer is positive
while(playAgain == 's'){
initializeGameTable();//Initialize game table
showHeader();//Show header with only title
requestPlayerNames();//Request players for typing their names
showHeader();//Show header with the title and players names
refreshGame();//Show the game table
//Print a divisor line after a blank line
printw("\n");
for(short int i = 0; i < col; i++){
printw("-");
}
/* Here is the game, we'll request a match and refresh the game table while the game is not won or tied (tied is defined by number of matches) */
//Matches counter
int matchesCounter = 1;
//Disable cursor
curs_set(0);
//While the game is not won and matches counter is under/equal 9
while(checkWin() == 0 && matchesCounter <= 9){
//Request match
requestMatch();
//Refresh the game table
refreshGame();
//Increase matches counter
matchesCounter++;
}
//Clear line 13
move(13,0);
clrtoeol();
//Check who won, or if the game tied
if(checkWin() == 1){
//Player 1 won
//Increase score
player1Score++;
//Show congratulations on player color
attron(COLOR_PAIR(2));
mvprintw(13, 0, "Parabéns %s, você ganhou!\n", player1);
attron(COLOR_PAIR(1));
}
if(checkWin() == 2){
if(!strcmp(player2, "")){
//PC won
//Increase score
player2Score++;
//Show congratulations on player color
attron(COLOR_PAIR(3));
mvprintw(13, 0, "O PC ganhou!\n", player2);
attron(COLOR_PAIR(1));
}else{
//Player2 won
//Increase score
player2Score++;
//Show congratulations on player color
attron(COLOR_PAIR(3));
mvprintw(13, 0, "Parabéns %s, você ganhou!\n", player2);
attron(COLOR_PAIR(1));
}
}
if(checkWin() == 0){
//Game tied
mvprintw(13, 0, "Deu velha! O jogo terminou em empate.\n");
}
//Refresh scores
refreshScores();
//Reset play again var
playAgain = ' ';
//Enable cursor
curs_set(1);
//Validate play again answer
while(!(playAgain == 's' | playAgain == 'n')){
//Clear line 15, removing possible wrong answers from screen
move(15, 0);
clrtoeol();
//Ask user
printw("Desejam jogar novamente?[s/n] ");
playAgain = getch();
}
}
//Disable cursor
curs_set(0);
//Clear screen and show the header
showHeader();
//Print the thanks on center
mvprintw(6, (col-strlen("Obrigado por jogar!"))/2,"Obrigado por jogar!\n");
//Delay
refresh(); delay(600);
//Print the credits
mvprintw(9, 0, "Desenvolvido por:\n");
printw("Renan Galeno <renangaleno@gmail.com>\n");
printw("Marcos Antuanny <caramarcos@hotmail.com>\n");
printw("Victor Patrick <vp8_10@hotmail.com>\n");
printw("\n");
//Delay
refresh(); delay(600);
printw("Este trabalho está licenciado sob uma Licença Creative Commons Atribuição-CompartilhaIgual 4.0 Internacional.\nPara ver uma cópia desta licença, visite http://creativecommons.org/licenses/by-sa/4.0/.\n\n");
//Delay
refresh(); delay(1000);
//Print the press anything to exit message
printw("Pressione qualquer tecla para sair.");
getch();
//End curses mode
endwin();
//Return 0, as the program had no errors
return(0);
} | 3.015625 | 3 |
2024-11-18T21:06:43.766649+00:00 | 2017-02-13T19:57:43 | 202fbf035c84eccda32ef78132fc2a0782878b6b | {
"blob_id": "202fbf035c84eccda32ef78132fc2a0782878b6b",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-13T19:57:43",
"content_id": "d6a3fa078061f3700130f7a2f03589d5827892f2",
"detected_licenses": [
"MIT"
],
"directory_id": "46a6192544651d4683617113f42bd9fa693ee62d",
"extension": "c",
"filename": "fiber.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 81646550,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1223,
"license": "MIT",
"license_type": "permissive",
"path": "/src/fiber.c",
"provenance": "stackv2-0128.json.gz:86592",
"repo_name": "jorsanpe/toolgorithms",
"revision_date": "2017-02-13T19:57:43",
"revision_id": "95ce1763c9003855eb54286ea207279d21eb17ff",
"snapshot_id": "7f3940e45cc2f2935f4d78a5d06d7288f7eadbcc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jorsanpe/toolgorithms/95ce1763c9003855eb54286ea207279d21eb17ff/src/fiber.c",
"visit_date": "2021-01-22T05:16:26.541322"
} | stackv2 | /**
* fiber.c --
*
* Copyright (C) 2016 Jordi Sánchez, jorsanpe@gmail.com
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include <stdlib.h>
#include <ucontext.h>
#include <fiber.h>
struct fiber {
void *(*routine)(void *);
void *arg;
ucontext_t context;
ucontext_t parent_context;
unsigned char stack[SIGSTKSZ];
};
static void createContext(Fiber* self)
{
getcontext(&self->context);
self->context.uc_link = &self->parent_context;
self->context.uc_stack.ss_sp = self->stack;
self->context.uc_stack.ss_size = SIGSTKSZ;
makecontext(&self->context, (void (*)(void)) self->routine, 1, self->arg);
}
Fiber *Fiber_Create(void *(*routine)(void *), void *arg)
{
Fiber *self = malloc(sizeof(Fiber));
self->routine = routine;
self->arg = arg;
createContext(self);
return self;
}
void Fiber_Destroy(Fiber *self)
{
free(self);
}
void Fiber_Run(Fiber *self)
{
Fiber_Resume(self);
}
void Fiber_Yield(Fiber *self)
{
swapcontext(&self->context, &self->parent_context);
}
void Fiber_Resume(Fiber *self)
{
swapcontext(&self->parent_context, &self->context);
}
| 2.828125 | 3 |
2024-11-18T21:06:44.043677+00:00 | 2022-03-01T22:33:16 | 2d40567e0789a626bb5fd6fe15d7caf9a80d82e3 | {
"blob_id": "2d40567e0789a626bb5fd6fe15d7caf9a80d82e3",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-12T17:03:27",
"content_id": "41b347519c97289d82068ed77ceb855674f4e6f0",
"detected_licenses": [
"MIT"
],
"directory_id": "c7308b6f7534ec1d08d02ff7882020636f42a2cb",
"extension": "c",
"filename": "assign.c",
"fork_events_count": 10,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2223381,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 360,
"license": "MIT",
"license_type": "permissive",
"path": "/test/cases/old_func/assign.c",
"provenance": "stackv2-0128.json.gz:87108",
"repo_name": "bobrippling/ucc-c-compiler",
"revision_date": "2022-03-01T22:33:16",
"revision_id": "d0283673261bbd5d872057ee169378fdf349a6fa",
"snapshot_id": "0d8808a31bb8b0b6403d1e757b866753ac969e23",
"src_encoding": "UTF-8",
"star_events_count": 74,
"url": "https://raw.githubusercontent.com/bobrippling/ucc-c-compiler/d0283673261bbd5d872057ee169378fdf349a6fa/test/cases/old_func/assign.c",
"visit_date": "2023-06-21T22:25:07.825365"
} | stackv2 | // RUN: %check --only %s -Wno-omitted-param-types
f(a)
char *a;
{
return 0;
}
char *h(a)
char *a;
{
return a;
}
void test()
{
int (*ifp)(char *);
char *(*cpfp)(char *);
ifp = f; // CHECK: !/warn/
cpfp = h; // CHECK: !/warn/
cpfp = f; // CHECK: warning: mismatching types, assignment
ifp = h; // CHECK: warning: mismatching types, assignment
}
| 2.34375 | 2 |
2024-11-18T21:06:44.116579+00:00 | 2017-12-02T09:17:27 | c1be84e0eecc515519ffdedc5eaa70dd1b3d2e32 | {
"blob_id": "c1be84e0eecc515519ffdedc5eaa70dd1b3d2e32",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-02T09:17:27",
"content_id": "1383f76d7268016022b79970354364a4dc267c60",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "939ba8355bb1c97dc252a9c8e46103381df088bf",
"extension": "h",
"filename": "bmic_object.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 72469953,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3053,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/base/common/bmic_object.h",
"provenance": "stackv2-0128.json.gz:87240",
"repo_name": "orpiske/bmic",
"revision_date": "2017-12-02T09:17:27",
"revision_id": "8327d0eed18355824eac2341ff47de4c4cbd9074",
"snapshot_id": "e815d3809245d93a2f3bc9dd92de356e53f05823",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/orpiske/bmic/8327d0eed18355824eac2341ff47de4c4cbd9074/src/base/common/bmic_object.h",
"visit_date": "2021-01-12T12:22:37.330575"
} | stackv2 | /**
Copyright 2016 Otavio Rodolfo Piske
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 BMIC_OBJECT_H
#define BMIC_OBJECT_H
#include <assert.h>
#include <stdbool.h>
#include <common/gru_alloc.h>
#include <common/gru_status.h>
#include <log/gru_logger.h>
#include <collection/gru_list.h>
#include <collection/gru_tree.h>
#include "bmic_cap_value.h"
#include "bmic_debug.h"
#include "bmic_regex.h"
#define REG_SEARCH_NAME 1
#define REG_SEARCH_PATH 2
#ifdef __cplusplus
extern "C" {
#endif
typedef union bmic_value_t_ {
int64_t number;
char *str;
bool value;
double d;
} bmic_value_t;
typedef struct bmic_object_t_ {
char *name;
char *path;
/**
* A pointer to their position within the document tree
*/
gru_tree_node_t *self;
bmic_value_t data;
bmic_value_type_t type;
} bmic_object_t;
bmic_object_t *bmic_object_new(const char *name, gru_status_t *status);
bmic_object_t *bmic_object_new_root(gru_status_t *status);
void bmic_object_destroy(bmic_object_t **ptr);
bool bmic_object_set_name(bmic_object_t *obj, const char *name);
bool bmic_object_set_path(bmic_object_t *obj, const char *path, ...);
void bmic_object_set_string(bmic_object_t *obj, const char *value);
void bmic_object_set_integer(bmic_object_t *obj, int64_t value);
void bmic_object_set_boolean(bmic_object_t *obj, bool value);
void bmic_object_set_double(bmic_object_t *obj, double value);
void bmic_object_set_null(bmic_object_t *obj);
// Hierarchy manipulation
void bmic_object_add_list_element(
bmic_object_t *gru_restrict parent, bmic_object_t *gru_restrict element);
void bmic_object_add_object(
bmic_object_t *gru_restrict parent, bmic_object_t *gru_restrict child);
// Path searching
const bmic_object_t *bmic_object_find_by_name(
const bmic_object_t *parent, const char *name);
const bmic_object_t *bmic_object_find_by_path(
const bmic_object_t *parent, const char *path);
const bmic_object_t *bmic_object_find(
const bmic_object_t *parent, compare_function_t compare, void *data);
const bmic_object_t *bmic_object_find_child_by_name(
const bmic_object_t *parent, const char *name);
const bmic_object_t *bmic_object_find_regex(
const bmic_object_t *parent, const char *regex, int flags);
// Navigates within the object tree
void bmic_object_for_each(
const bmic_object_t *obj, tree_callback_fn callback, void *payload);
void bmic_object_for_each_child(
const bmic_object_t *obj, tree_callback_fn callback, void *payload);
// DEBUG
void bmic_object_print(const bmic_object_t *parent);
#ifdef __cplusplus
}
#endif
#endif /* BMIC_OBJECT_H */
| 2.1875 | 2 |
2024-11-18T21:06:44.178919+00:00 | 2022-07-20T14:38:45 | efde9656193e43384e14e29b8dd3df94eb852aea | {
"blob_id": "efde9656193e43384e14e29b8dd3df94eb852aea",
"branch_name": "refs/heads/main",
"committer_date": "2022-07-20T14:38:45",
"content_id": "d74ac7a24b3a5c299779e8cb2818039ca2505ac5",
"detected_licenses": [
"MIT"
],
"directory_id": "04e5b6df2ee3bcfb7005d8ec91aab8e380333ac4",
"extension": "h",
"filename": "CGPath.h",
"fork_events_count": 157,
"gha_created_at": "2018-09-15T22:29:07",
"gha_event_created_at": "2023-02-26T21:34:04",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 148944721,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 17118,
"license": "MIT",
"license_type": "permissive",
"path": "/Extensions/clib/iPhoneOS.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CGPath.h",
"provenance": "stackv2-0128.json.gz:87369",
"repo_name": "ColdGrub1384/Pyto",
"revision_date": "2022-07-20T14:38:45",
"revision_id": "7557485a733dd7e17ba0366b92794931bdb39975",
"snapshot_id": "64e2a593957fd640907f0e4698d430ea7754a73e",
"src_encoding": "UTF-8",
"star_events_count": 884,
"url": "https://raw.githubusercontent.com/ColdGrub1384/Pyto/7557485a733dd7e17ba0366b92794931bdb39975/Extensions/clib/iPhoneOS.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CGPath.h",
"visit_date": "2023-08-01T03:48:35.694832"
} | stackv2 | /* CoreGraphics - CGPath.h
Copyright (c) 2001-2011 Apple Inc.
All rights reserved. */
#ifndef CGPATH_H_
#define CGPATH_H_
#include <CoreFoundation/CFBase.h>
#include <CoreFoundation/CFAvailability.h>
#include <stdint.h>
typedef struct CF_BRIDGED_TYPE(id) CGPath *CGMutablePathRef;
typedef const struct CF_BRIDGED_TYPE(id) CGPath *CGPathRef;
#include <CoreGraphics/CGBase.h>
#include <CoreGraphics/CGAffineTransform.h>
#include <CoreFoundation/CFBase.h>
CF_IMPLICIT_BRIDGING_ENABLED
CF_ASSUME_NONNULL_BEGIN
/* Line join styles. */
typedef CF_ENUM(int32_t, CGLineJoin) {
kCGLineJoinMiter,
kCGLineJoinRound,
kCGLineJoinBevel
};
/* Line cap styles. */
typedef CF_ENUM(int32_t, CGLineCap) {
kCGLineCapButt,
kCGLineCapRound,
kCGLineCapSquare
};
/* Return the CFTypeID for CGPathRefs. */
CG_EXTERN CFTypeID CGPathGetTypeID(void)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Create a mutable path. */
CG_EXTERN CGMutablePathRef CGPathCreateMutable(void)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Create a copy of `path'. */
CG_EXTERN CGPathRef __nullable CGPathCreateCopy(CGPathRef cg_nullable path)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Create a copy of `path' transformed by `transform'. */
CG_EXTERN CGPathRef __nullable CGPathCreateCopyByTransformingPath(
CGPathRef cg_nullable path, const CGAffineTransform * __nullable transform)
CG_AVAILABLE_STARTING(10.7, 5.0);
/* Create a mutable copy of `path'. */
CG_EXTERN CGMutablePathRef __nullable CGPathCreateMutableCopy(
CGPathRef cg_nullable path)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Create a mutable copy of `path' transformed by `transform'. */
CG_EXTERN CGMutablePathRef __nullable CGPathCreateMutableCopyByTransformingPath(
CGPathRef cg_nullable path, const CGAffineTransform * __nullable transform)
CG_AVAILABLE_STARTING(10.7, 5.0);
/* Return a path representing a rectangle bounded by `rect'. The rectangle
forms a complete subpath of the path --- that is, it begins with a "move
to" and ends with a "close subpath" --- oriented in the clockwise
direction. If `transform' is non-NULL, then the lines representing the
rectangle will be transformed by `transform' before they are added to the
path. */
CG_EXTERN CGPathRef CGPathCreateWithRect(CGRect rect,
const CGAffineTransform * __nullable transform)
CG_AVAILABLE_STARTING(10.5, 4.0);
/* Return a path representing an ellipse bounded by `rect'. The ellipse is
approximated by a sequence of Bézier curves. The center of the ellipse is
the midpoint of `rect'. If `rect' is square, then the ellipse will be
circular with radius equal to one-half the width (equivalently, one-half
the height) of `rect'. If `rect' is rectangular, then the major- and
minor-axes will be the `width' and `height' of rect. The ellipse forms a
complete subpath of the path --- that is, it begins with a "move to" and
ends with a "close subpath" --- oriented in the clockwise direction. If
`transform' is non-NULL, then the constructed Bézier curves representing
the ellipse will be transformed by `transform' before they are added to
the path. */
CG_EXTERN CGPathRef CGPathCreateWithEllipseInRect(CGRect rect,
const CGAffineTransform * __nullable transform)
CG_AVAILABLE_STARTING(10.7, 5.0);
/* Return a path representing a rounded rectangle. The rounded rectangle
coincides with the edges of `rect'. Each corner is consists of
one-quarter of an ellipse with axes equal to `cornerWidth' and
`cornerHeight'. The rounded rectangle forms a complete subpath of the
path --- that is, it begins with a "move to" and ends with a "close
subpath" --- oriented in the clockwise direction. If `transform' is
non-NULL, then the path elements representing the rounded rectangle will
be transformed by `transform' before they are added to the path. */
CG_EXTERN CGPathRef CGPathCreateWithRoundedRect(CGRect rect,
CGFloat cornerWidth, CGFloat cornerHeight,
const CGAffineTransform * __nullable transform)
CG_AVAILABLE_STARTING(10.9, 7.0);
/* Add a rounded rectangle to `path'. The rounded rectangle coincides with
the edges of `rect'. Each corner is consists of one-quarter of an ellipse
with axes equal to `cornerWidth' and `cornerHeight'. The rounded
rectangle forms a complete subpath of the path --- that is, it begins
with a "move to" and ends with a "close subpath" --- oriented in the
clockwise direction. If `transform' is non-NULL, then the path elements
representing the rounded rectangle will be transformed by `transform'
before they are added to the path. */
CG_EXTERN void CGPathAddRoundedRect(CGMutablePathRef cg_nullable path,
const CGAffineTransform * __nullable transform, CGRect rect,
CGFloat cornerWidth, CGFloat cornerHeight)
CG_AVAILABLE_STARTING(10.9, 7.0);
/* Create a dashed path from `path'. The parameters `phase', `lengths', and
`count' have the same meaning as the corresponding parameters for
`CGContextSetLineDash'. If `transform' is non-NULL, then the elements of
the constructed path will be transformed by `transform' before they are
added to the path. */
CG_EXTERN CGPathRef __nullable CGPathCreateCopyByDashingPath(
CGPathRef cg_nullable path, const CGAffineTransform * __nullable transform,
CGFloat phase, const CGFloat * __nullable lengths, size_t count)
CG_AVAILABLE_STARTING(10.7, 5.0);
/* Create a stroked path from `path'. The parameters `lineWidth', `lineCap',
`lineJoin', and `miterLimit' have the same meaning as the corresponding
CGContext parameters. If `transform' is non-NULL, then the elements of
the constructed path will be transformed by `transform' before they are
added to the path. */
CG_EXTERN CGPathRef __nullable CGPathCreateCopyByStrokingPath(
CGPathRef cg_nullable path, const CGAffineTransform * __nullable transform,
CGFloat lineWidth, CGLineCap lineCap,
CGLineJoin lineJoin, CGFloat miterLimit)
CG_AVAILABLE_STARTING(10.7, 5.0);
/* Equivalent to `CFRetain(path)', except it doesn't crash (as CFRetain
does) if `path' is NULL. */
CG_EXTERN CGPathRef cg_nullable CGPathRetain(CGPathRef cg_nullable path)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Equivalent to `CFRelease(path)', except it doesn't crash (as CFRelease
does) if `path' is NULL. */
CG_EXTERN void CGPathRelease(CGPathRef cg_nullable path)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Return true if `path1' is equal to `path2'; false otherwise. */
CG_EXTERN bool CGPathEqualToPath(CGPathRef cg_nullable path1,
CGPathRef cg_nullable path2)
CG_AVAILABLE_STARTING(10.2, 2.0);
/*** Path construction functions. ***/
/* Move the current point to `(x, y)' in `path' and begin a new subpath. If
`m' is non-NULL, then transform `(x, y)' by `m' first. */
CG_EXTERN void CGPathMoveToPoint(CGMutablePathRef cg_nullable path,
const CGAffineTransform * __nullable m, CGFloat x, CGFloat y)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Append a straight line segment from the current point to `(x, y)' in
`path' and move the current point to `(x, y)'. If `m' is non-NULL, then
transform `(x, y)' by `m' first. */
CG_EXTERN void CGPathAddLineToPoint(CGMutablePathRef cg_nullable path,
const CGAffineTransform * __nullable m, CGFloat x, CGFloat y)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Append a quadratic curve from the current point to `(x, y)' with control
point `(cpx, cpy)' in `path' and move the current point to `(x, y)'. If
`m' is non-NULL, then transform all points by `m' first. */
CG_EXTERN void CGPathAddQuadCurveToPoint(CGMutablePathRef cg_nullable path,
const CGAffineTransform *__nullable m, CGFloat cpx, CGFloat cpy,
CGFloat x, CGFloat y)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Append a cubic Bézier curve from the current point to `(x,y)' with
control points `(cp1x, cp1y)' and `(cp2x, cp2y)' in `path' and move the
current point to `(x, y)'. If `m' is non-NULL, then transform all points
by `m' first. */
CG_EXTERN void CGPathAddCurveToPoint(CGMutablePathRef cg_nullable path,
const CGAffineTransform * __nullable m, CGFloat cp1x, CGFloat cp1y,
CGFloat cp2x, CGFloat cp2y, CGFloat x, CGFloat y)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Append a line from the current point to the starting point of the current
subpath of `path' and end the subpath. */
CG_EXTERN void CGPathCloseSubpath(CGMutablePathRef cg_nullable path)
CG_AVAILABLE_STARTING(10.2, 2.0);
/*** Path construction convenience functions. ***/
/* Add `rect' to `path'. If `m' is non-NULL, then first transform `rect' by
`m' before adding it to `path'. */
CG_EXTERN void CGPathAddRect(CGMutablePathRef cg_nullable path,
const CGAffineTransform * __nullable m, CGRect rect)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Add each rectangle specified by `rects', an array of `count' CGRects, to
`path'. If `m' is non-NULL, then first transform each rectangle by `m'
before adding it to `path'. */
CG_EXTERN void CGPathAddRects(CGMutablePathRef cg_nullable path,
const CGAffineTransform * __nullable m, const CGRect * __nullable rects,
size_t count)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Move to the first element of `points', an array of `count' CGPoints, and
append a line from each point to the next point in `points'. If `m' is
non-NULL, then first transform each point by `m'. */
CG_EXTERN void CGPathAddLines(CGMutablePathRef cg_nullable path,
const CGAffineTransform * __nullable m, const CGPoint * __nullable points,
size_t count)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Add an ellipse (an oval) inside `rect' to `path'. The ellipse is
approximated by a sequence of Bézier curves. The center of the ellipse is
the midpoint of `rect'. If `rect' is square, then the ellipse will be
circular with radius equal to one-half the width (equivalently, one-half
the height) of `rect'. If `rect' is rectangular, then the major- and
minor-axes will be the `width' and `height' of rect. The ellipse forms a
complete subpath of `path' --- that is, it begins with a "move to" and
ends with a "close subpath" --- oriented in the clockwise direction. If
`m' is non-NULL, then the constructed Bézier curves representing the
ellipse will be transformed by `m' before they are added to `path'. */
CG_EXTERN void CGPathAddEllipseInRect(CGMutablePathRef cg_nullable path,
const CGAffineTransform * __nullable m, CGRect rect)
CG_AVAILABLE_STARTING(10.4, 2.0);
/* Add an arc of a circle to `path', possibly preceded by a straight line
segment. The arc is approximated by a sequence of Bézier curves. The
center of the arc is `(x,y)'; `radius' is its radius. `startAngle' is the
angle to the first endpoint of the arc, measured counter-clockwise from
the positive x-axis. `startAngle + delta' is the angle to the second
endpoint of the arc. If `delta' is positive, then the arc is drawn
counter-clockwise; if negative, clockwise. `startAngle' and `delta' are
measured in radians. If `matrix' is non-NULL, then the constructed Bézier
curves representing the arc will be transformed by `matrix' before they
are added to the path. */
CG_EXTERN void CGPathAddRelativeArc(CGMutablePathRef cg_nullable path,
const CGAffineTransform * __nullable matrix, CGFloat x, CGFloat y,
CGFloat radius, CGFloat startAngle, CGFloat delta)
CG_AVAILABLE_STARTING(10.7, 5.0);
/* Add an arc of a circle to `path', possibly preceded by a straight line
segment. The arc is approximated by a sequence of Bézier curves. `(x, y)'
is the center of the arc; `radius' is its radius; `startAngle' is the
angle to the first endpoint of the arc; `endAngle' is the angle to the
second endpoint of the arc; and `clockwise' is true if the arc is to be
drawn clockwise, false otherwise. `startAngle' and `endAngle' are
measured in radians. If `m' is non-NULL, then the constructed Bézier
curves representing the arc will be transformed by `m' before they are
added to `path'.
Note that using values very near 2π can be problematic. For example,
setting `startAngle' to 0, `endAngle' to 2π, and `clockwise' to true will
draw nothing. (It's easy to see this by considering, instead of 0 and 2π,
the values ε and 2π - ε, where ε is very small.) Due to round-off error,
however, it's possible that passing the value `2 * M_PI' to approximate
2π will numerically equal to 2π + δ, for some small δ; this will cause a
full circle to be drawn.
If you want a full circle to be drawn clockwise, you should set
`startAngle' to 2π, `endAngle' to 0, and `clockwise' to true. This avoids
the instability problems discussed above. */
CG_EXTERN void CGPathAddArc(CGMutablePathRef cg_nullable path,
const CGAffineTransform * __nullable m,
CGFloat x, CGFloat y, CGFloat radius, CGFloat startAngle, CGFloat endAngle,
bool clockwise)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Add an arc of a circle to `path', possibly preceded by a straight line
segment. The arc is approximated by a sequence of Bézier curves. `radius'
is the radius of the arc. The resulting arc is tangent to the line from
the current point of `path' to `(x1, y1)', and the line from `(x1, y1)'
to `(x2, y2)'. If `m' is non-NULL, then the constructed Bézier curves
representing the arc will be transformed by `m' before they are added to
`path'. */
CG_EXTERN void CGPathAddArcToPoint(CGMutablePathRef cg_nullable path,
const CGAffineTransform * __nullable m, CGFloat x1, CGFloat y1,
CGFloat x2, CGFloat y2, CGFloat radius)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Add `path2' to `path1'. If `m' is non-NULL, then the points in `path2'
will be transformed by `m' before they are added to `path1'. */
CG_EXTERN void CGPathAddPath(CGMutablePathRef cg_nullable path1,
const CGAffineTransform * __nullable m, CGPathRef cg_nullable path2)
CG_AVAILABLE_STARTING(10.2, 2.0);
/*** Path information functions. ***/
/* Return true if `path' contains no elements, false otherwise. */
CG_EXTERN bool CGPathIsEmpty(CGPathRef cg_nullable path)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Return true if `path' represents a rectangle, false otherwise. */
CG_EXTERN bool CGPathIsRect(CGPathRef cg_nullable path, CGRect * __nullable rect)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Return the current point of the current subpath of `path'. If there is no
current point, then return CGPointZero. */
CG_EXTERN CGPoint CGPathGetCurrentPoint(CGPathRef cg_nullable path)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Return the bounding box of `path'. The bounding box is the smallest
rectangle completely enclosing all points in the path, including control
points for Bézier cubic and quadratic curves. If the path is empty, then
return `CGRectNull'. */
CG_EXTERN CGRect CGPathGetBoundingBox(CGPathRef cg_nullable path)
CG_AVAILABLE_STARTING(10.2, 2.0);
/* Return the path bounding box of `path'. The path bounding box is the
smallest rectangle completely enclosing all points in the path, *not*
including control points for Bézier cubic and quadratic curves. If the
path is empty, then return `CGRectNull'. */
CG_EXTERN CGRect CGPathGetPathBoundingBox(CGPathRef cg_nullable path)
CG_AVAILABLE_STARTING(10.6, 4.0);
/* Return true if `point' is contained in `path'; false otherwise. A point
is contained in a path if it is inside the painted region when the path
is filled; if `eoFill' is true, then the even-odd fill rule is used to
evaluate the painted region of the path, otherwise, the winding-number
fill rule is used. If `m' is non-NULL, then the point is transformed by
`m' before determining whether the path contains it. */
CG_EXTERN bool CGPathContainsPoint(CGPathRef cg_nullable path,
const CGAffineTransform * __nullable m, CGPoint point, bool eoFill)
CG_AVAILABLE_STARTING(10.4, 2.0);
/* The types of path elements returned by `CGPathApply'. */
typedef CF_ENUM(int32_t, CGPathElementType) {
kCGPathElementMoveToPoint,
kCGPathElementAddLineToPoint,
kCGPathElementAddQuadCurveToPoint,
kCGPathElementAddCurveToPoint,
kCGPathElementCloseSubpath
};
/* An element of a path returned by `CGPathApply'. */
struct CGPathElement {
CGPathElementType type;
CGPoint * points;
};
typedef struct CGPathElement CGPathElement;
/* The prototype for the function called by `CGPathApplyFunction'. */
typedef void (*CGPathApplierFunction)(void * __nullable info,
const CGPathElement * element);
/* For element of `path', call `function', passing it the path element and
`info'. */
CG_EXTERN void CGPathApply(CGPathRef cg_nullable path, void * __nullable info,
CGPathApplierFunction cg_nullable function)
CG_AVAILABLE_STARTING(10.2, 2.0);
typedef void (^CGPathApplyBlock)(const CGPathElement * element);
CG_EXTERN void CGPathApplyWithBlock(CGPathRef path, CGPathApplyBlock CF_NOESCAPE block)
CG_AVAILABLE_STARTING(10.13, 11.0);
CF_ASSUME_NONNULL_END
CF_IMPLICIT_BRIDGING_DISABLED
#endif /* CGPATH_H_ */
| 2.015625 | 2 |
2024-11-18T21:06:44.285358+00:00 | 2023-04-12T13:34:45 | 067271b8da89e5be6f74e2acae6106a080965fe9 | {
"blob_id": "067271b8da89e5be6f74e2acae6106a080965fe9",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-12T13:34:45",
"content_id": "2257ca920cc846099132ee190f239a301ea62c0a",
"detected_licenses": [
"MIT"
],
"directory_id": "510e0852976c9d75193d513a2bb3af6712af1384",
"extension": "c",
"filename": "relays.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 167187572,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 889,
"license": "MIT",
"license_type": "permissive",
"path": "/components/relay/relays.c",
"provenance": "stackv2-0128.json.gz:87497",
"repo_name": "charrea6/homething",
"revision_date": "2023-04-12T13:34:45",
"revision_id": "5a600ab5f56fd154727ca87d73a576117f79edd5",
"snapshot_id": "f4e901143782d004a74368b0b3f5eca16f7ac80f",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/charrea6/homething/5a600ab5f56fd154727ca87d73a576117f79edd5/components/relay/relays.c",
"visit_date": "2023-04-27T05:24:15.571359"
} | stackv2 | #include <stdlib.h>
#include <string.h>
#include "relay.h"
#include "sdkconfig.h"
#include "esp_log.h"
#include "iot.h"
struct RelayMapEntry {
const char *id;
Relay_t *relay;
struct RelayMapEntry *next;
};
static const char TAG[]="relays";
static struct RelayMapEntry *rootEntry = NULL;
void relayRegister(Relay_t *relay, const char *id)
{
struct RelayMapEntry *entry;
entry = calloc(1, sizeof(struct RelayMapEntry));
if (entry == NULL) {
ESP_LOGE(TAG, "Failed to allocate entry for %s", id);
return;
}
entry->id = id;
entry->relay = relay;
entry->next = rootEntry;
rootEntry = entry;
}
Relay_t *relayFind(const char *id)
{
struct RelayMapEntry *entry;
for (entry = rootEntry; entry; entry = entry->next) {
if (strcmp(id, entry->id) == 0) {
return entry->relay;
}
}
return NULL;
} | 2.421875 | 2 |
2024-11-18T21:06:44.400193+00:00 | 2011-08-22T20:11:58 | e25f64d055abab67ae4409ac28a4df3796955c20 | {
"blob_id": "e25f64d055abab67ae4409ac28a4df3796955c20",
"branch_name": "refs/heads/master",
"committer_date": "2011-08-22T20:11:58",
"content_id": "8389e0c6e24c30c2acc943fffd9f0da986cf918c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4560608c030221fd19e0d2ebe4aaffdee88f0ab2",
"extension": "c",
"filename": "eventid.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1557341,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10142,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/eventid.c",
"provenance": "stackv2-0128.json.gz:87628",
"repo_name": "github-ivan/eventid",
"revision_date": "2011-08-22T20:11:58",
"revision_id": "fc87ea9ed8c233a3c0a902da706e8ae790c31e07",
"snapshot_id": "dc40e902d6f97e18bf774b8c0f655bf90bf26c2c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/github-ivan/eventid/fc87ea9ed8c233a3c0a902da706e8ae790c31e07/eventid.c",
"visit_date": "2021-01-02T08:56:08.952663"
} | stackv2 | /*
* 2011.04.01 ivan <github-ivan@enfinity.hu>
*
* Unique id generator server inspired by
* twitter's snowflake.
*
* Id composed:
* 41 bit time (millisecond resulution)
* 10 bits worker id
* 13 bits counter
*
* 10 bits counter id (/<counter id>)
*
* Implementation based on Kuzuki Ohta's sample
*
*/
#define __STDC_LIMIT_MACROS
#define __STDC_FORMAT_MACROS /* Enable PRIu64 in <inttypes.h> */
#include <stdio.h>
#include <event.h>
#include <evhttp.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <sched.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <netdb.h>
#include <inttypes.h>
#define zepoch 1288834974657L
#define timeBits 41
#define workerIdBits 10
#define counterBits 12
#define numCounterId 128
#ifdef DEBUG
#define DPRINT(...) fprintf(__VA_ARGS__);
#else
#define DPRINT(...)
#endif
#ifndef DEFLOGFILE
#define DEFLOGFILE "/var/log/eventid.log"
#endif
#define RET(rv, ...) { fprintf(__VA_ARGS__); return (rv) ? rv : NULL; }
using namespace std;
namespace enfinity {
namespace eventid {
class HTTPServer {
public:
HTTPServer();
~HTTPServer() {}
int processParams(int argc, char** argv);
int daemonize();
int serv();
protected:
struct thread_arg {
struct event_base* eventBase;
int workerId;
};
struct counter_item {
uint64_t lastMillisec;
uint32_t counter;
};
const char* logFile;
struct sockaddr_in listenAddr;
int listenPort;
bool isDaemon;
int backlogSize;
static FILE* logfd;
uint64_t maxWorkerId, timestampLeftShift, maxCounter;
static uint64_t workerIdShift;
static int retVal, cpuCount, workerNo, workerOffset;
static __thread uint64_t workerId;
static __thread struct counter_item* counters;
static void* dispatch(void* arg);
static void genericHandler(struct evhttp_request *req, void *arg);
inline uint64_t getMillisec();
void processRequest(struct evhttp_request *request);
int bindSocket();
void usage();
};
int HTTPServer::retVal = 0;
FILE* HTTPServer::logfd = NULL;
int HTTPServer::cpuCount = 0;
int HTTPServer::workerNo = 0;
int HTTPServer::workerOffset = 0;
uint64_t HTTPServer::workerIdShift = 0;
__thread uint64_t HTTPServer::workerId = 0;
__thread struct HTTPServer::counter_item* HTTPServer::counters = NULL;
HTTPServer::HTTPServer() {
retVal = 0;
maxWorkerId = UINT64_MAX ^ (UINT64_MAX << workerIdBits);
maxCounter = UINT64_MAX ^ (UINT64_MAX << counterBits);
workerIdShift = counterBits;
timestampLeftShift = counterBits + workerIdBits;
cpuCount = sysconf(_SC_NPROCESSORS_ONLN);
workerNo = cpuCount;
isDaemon = false;
logfd = stderr;
listenPort = 3843;
backlogSize = -1;
logFile = DEFLOGFILE;
memset(&listenAddr, 0, sizeof(listenAddr));
listenAddr.sin_family = AF_INET;
listenAddr.sin_addr.s_addr = INADDR_ANY;
listenAddr.sin_port = htons(listenPort);
}
void HTTPServer::usage() {
fprintf(stdout, "Usage: eventid [-d] [-b <backlog_size>] [-t <thread no>] "
"[-l <remote address:port>] [-f <logfile path>]\n");
}
int HTTPServer::processParams(int argc, char* argv[]) {
int c, intval;
char* colonpos;
struct hostent* host;
if (argc == 1)
return 0;
while ((c = getopt (argc, argv, "d?l:b:f:t:")) != -1)
switch (c)
{
case 'd':
isDaemon = true;
break;
case 'f':
logFile = optarg;
break;
case 'b':
intval = atoi(optarg);
if (intval < 0) RET(-101, logfd, "Invalid backlog_size value: %d.\n", intval);
backlogSize = intval;
break;
case 't':
intval = atoi(optarg);
if (intval < 0)
RET(-102, logfd, "Invalid worker number value: %d, max value: %"PRIu64".\n",
intval, maxWorkerId);
workerNo = intval;
break;
case 'l':
colonpos = strrchr(optarg, 58);
if (colonpos != NULL) {
*colonpos = 0;
intval = atoi(colonpos + 1);
if ((intval < 1) || (intval > 65535))
RET(-103, logfd, "Invalid remote port value: %d.\n", intval);
listenPort = intval;
listenAddr.sin_port = htons(intval);
}
host = gethostbyname(optarg);
if (! host) RET(-104, logfd, "Invalid remote address.\n");
memcpy(&(listenAddr.sin_addr.s_addr), host->h_addr, sizeof(host->h_addr));
listenAddr.sin_family = host->h_addrtype;
break;
case '?':
usage();
return -100;
break;
default:
break;
}
return 0;
}
int HTTPServer::daemonize()
{
int pid;
int sid;
FILE* rv;
if (! isDaemon) return 0;
pid = fork();
if (pid < 0) RET(-201, logfd, "Can't fork.\n");
if (pid > 0) exit(EXIT_SUCCESS);
/* Change the file mode mask */
umask(0);
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) RET(-202, logfd, "Can't set new session id.\n");
if ((chdir("/")) < 0) RET(-4, logfd, "Can't chdir.\n");
close(STDIN_FILENO);
close(STDOUT_FILENO);
// TODO: implement better logging
rv = fopen(logFile, "w+");
if (rv == NULL) RET(-203, logfd, "Can't open logfile: %s,\n", logFile);
fclose(logfd);
logfd = rv;
return 0;
}
int HTTPServer::bindSocket() {
int rv;
int lfd;
lfd = socket(listenAddr.sin_family, SOCK_STREAM, 0);
if (lfd < 0) RET(-301, logfd, "Can't create socket.");
int one = 1;
rv = setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, (char*) &one, sizeof(int));
rv = bind(lfd, (struct sockaddr*) &listenAddr, sizeof(listenAddr));
if (rv < 0) RET(-302, logfd, "Can't bind socket.");
rv = listen(lfd, backlogSize);
if (rv < 0) RET(-303, logfd, "Can't listen on socket.");
int flags;
if ((flags = fcntl(lfd, F_GETFL, 0)) < 0 || fcntl(lfd, F_SETFL, flags | O_NONBLOCK) < 0)
RET(-304, logfd, "Can't set non-blocking on socket.");
return lfd;
}
int HTTPServer::serv() {
int rv;
int lfd = bindSocket();
if (lfd < 0) return lfd;
pthread_t ths[workerNo];
struct thread_arg threadArg[workerNo];
for (int i = 0; i < workerNo; i++) {
struct event_base *base = event_init();
if (base == NULL) RET(-401, logfd, "event_init() error.");
struct evhttp *httpd = evhttp_new(base);
if (httpd == NULL) RET(-402, logfd, "evhttp_new() error.");
rv = evhttp_accept_socket(httpd, lfd);
if (rv != 0) RET(-403, logfd, "evhttp_accept_socket() error (%d).", rv);
evhttp_set_gencb(httpd, HTTPServer::genericHandler, this);
threadArg[i].workerId = workerOffset + i;
threadArg[i].eventBase = base;
rv = pthread_create(&ths[i], NULL, HTTPServer::dispatch, &threadArg[i]);
if (rv != 0) RET(-404, logfd, "pthread_create() errori (%d).", rv);
}
for (int i = 0; i < workerNo; i++) {
pthread_join(ths[i], NULL);
}
return retVal;
}
void* HTTPServer::dispatch(void *arg) {
struct thread_arg *threadArg = (struct thread_arg*) arg;
workerId = threadArg->workerId << workerIdShift;
cpu_set_t mask;
if (HTTPServer::cpuCount) {
int cpu = threadArg->workerId % HTTPServer::cpuCount;
CPU_ZERO(&mask);
CPU_SET(cpu, &mask);
sched_setaffinity(0, sizeof(mask), &mask);
}
counters = (struct counter_item*) calloc(numCounterId,
sizeof(struct counter_item));
if (counters == NULL) {
retVal = -405;
RET(NULL, logfd, "Can't allocate memory for counters.");
}
event_base_dispatch((struct event_base*)threadArg->eventBase);
return NULL;
}
void HTTPServer::genericHandler(struct evhttp_request *req, void *arg) {
((HTTPServer*)arg)->processRequest(req);
}
uint64_t HTTPServer::getMillisec() {
struct timeval tv;
// TODO: return value should be checked
gettimeofday(&tv, NULL);
return (tv.tv_sec * 1000 - zepoch) + (tv.tv_usec / 1000);
}
void HTTPServer::processRequest(struct evhttp_request *req) {
uint64_t uniqueId;
uint64_t curMillisec;
struct timespec sleepTime, remainingTime;
struct counter_item* sCounter;
int rv, counterId;
const char* uri;
if (! counters) return;
uniqueId = 0;
counterId = 0;
uri = evhttp_request_uri(req);
if (uri[1]) {
int tCounterId = atoi(uri + 1);
if ((tCounterId > 0) && (tCounterId < numCounterId)) {
counterId = tCounterId;
}
}
sCounter = &(counters[counterId]);
curMillisec = getMillisec();
// time goes backward
if (sCounter->lastMillisec > curMillisec) {
fprintf(logfd, "%"PRIu64" - Time goes backward. Waiting for %"PRIu64" msec.\n"
"Last msec: %"PRIu64", cur msec: %"PRIu64", workerId: %"PRIu64", counter: %d\n",
curMillisec, (sCounter->lastMillisec - curMillisec),
sCounter->lastMillisec, curMillisec, workerId, sCounter->counter);
sleepTime.tv_sec = sCounter->lastMillisec / 1000;
sleepTime.tv_nsec = ((sCounter->lastMillisec % 1000) + 1) * 1000000;
while ((rv = nanosleep(&sleepTime, &remainingTime))) {
if (rv != EINTR) {
evhttp_send_reply(req, HTTP_SERVUNAVAIL, "Service unavaible", NULL);
retVal = -501;
fprintf(logfd, "nanosleep() error.");
}
sleepTime.tv_sec = remainingTime.tv_sec;
sleepTime.tv_nsec = remainingTime.tv_nsec;
}
}
if (sCounter->lastMillisec == curMillisec) {
sCounter->counter++;
if (sCounter->counter > maxCounter) {
do {
curMillisec = getMillisec();
} while (curMillisec <= sCounter->lastMillisec);
}
}
if (sCounter->lastMillisec < curMillisec) {
sCounter->counter = 0;
sCounter->lastMillisec = curMillisec;
}
uniqueId = (curMillisec << timestampLeftShift) |
workerId | sCounter->counter;
struct evbuffer *buf = evbuffer_new();
if (buf == NULL) {
evhttp_send_reply(req, HTTP_SERVUNAVAIL, "Service unavaible", NULL);
retVal = -502;
fprintf(logfd, "evbuffer_new() error.");
}
evbuffer_add_printf(buf, "%"PRIu64, uniqueId);
evhttp_send_reply(req, HTTP_OK, "OK", buf);
evbuffer_free(buf);
}
}} // namespace enfinity::eventid
int main(int argc, char** argv) {
int rv;
enfinity::eventid::HTTPServer eserver;
rv = eserver.processParams(argc, argv);
if (rv) {
if (rv == -100) return 0;
return rv;
}
rv = eserver.daemonize();
if (rv) return rv;
eserver.serv();
}
| 2.0625 | 2 |
2024-11-18T21:06:44.506932+00:00 | 2022-06-01T01:47:02 | 411fae2859a743acd5b797104f20f8f8ebba4ac4 | {
"blob_id": "411fae2859a743acd5b797104f20f8f8ebba4ac4",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-01T01:47:02",
"content_id": "26a617f8e0f0eba7cbcf411f65ee082d85c8313c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "554e0d92071d8ce0a1888e970edd77be59699c01",
"extension": "c",
"filename": "utf8.c",
"fork_events_count": 19,
"gha_created_at": "2013-08-17T04:50:04",
"gha_event_created_at": "2018-04-29T23:53:11",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 12173574,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 17485,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test/parser/utf8.c",
"provenance": "stackv2-0128.json.gz:87761",
"repo_name": "craigbarnes/lua-gumbo",
"revision_date": "2022-06-01T01:47:02",
"revision_id": "9f2defdcc2e0d660a9fb0dd29c6e11f8cac87d01",
"snapshot_id": "5e424186d2905f48a2058b80312f70421ca72a7d",
"src_encoding": "UTF-8",
"star_events_count": 135,
"url": "https://raw.githubusercontent.com/craigbarnes/lua-gumbo/9f2defdcc2e0d660a9fb0dd29c6e11f8cac87d01/test/parser/utf8.c",
"visit_date": "2022-06-24T01:01:51.124075"
} | stackv2 | // Copyright 2018 Craig Barnes.
// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "utf8.h"
#include "test.h"
#define SETUP() \
Utf8Iterator input_; \
BASE_SETUP();
#define TEARDOWN() \
BASE_TEARDOWN();
#define Advance(num_chars) do { \
for (size_t i = 0; i < num_chars; ++i) { \
utf8iterator_next(&input_); \
} \
} while (0)
#define ResetText(text) do { \
utf8iterator_init(&parser_, text, strlen(text), &input_); \
} while (0)
#define GetFirstError() \
(GumboError*)(parser_._output->errors.data[0])
#define GetNumErrors() \
parser_._output->errors.length
TEST(Utf8Test, EmptyString) {
SETUP();
ResetText("");
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, GetPosition_EmptyString) {
SETUP();
ResetText("");
GumboSourcePosition pos;
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(1, pos.line);
EXPECT_EQ(1, pos.column);
EXPECT_EQ(0, pos.offset);
TEARDOWN();
}
TEST(Utf8Test, Null) {
SETUP();
// Can't use ResetText, as the implicit strlen will choke on the null.
const char *text = "\0f";
utf8iterator_init(&parser_, text, 2, &input_);
EXPECT_EQ(0, utf8iterator_current(&input_));
EXPECT_EQ('\0', *utf8iterator_get_char_pointer(&input_));
utf8iterator_next(&input_);
EXPECT_EQ('f', utf8iterator_current(&input_));
EXPECT_EQ('f', *utf8iterator_get_char_pointer(&input_));
TEARDOWN();
}
TEST(Utf8Test, OneByteChar) {
SETUP();
ResetText("a");
EXPECT_EQ(0, GetNumErrors());
EXPECT_EQ('a', utf8iterator_current(&input_));
EXPECT_EQ('a', *utf8iterator_get_char_pointer(&input_));
GumboSourcePosition pos;
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(1, pos.line);
EXPECT_EQ(1, pos.column);
EXPECT_EQ(0, pos.offset);
utf8iterator_next(&input_);
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, ContinuationByte) {
SETUP();
ResetText("\x85");
EXPECT_EQ(1, GetNumErrors());
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
EXPECT_EQ('\x85', *utf8iterator_get_char_pointer(&input_));
GumboError* error = GetFirstError();
EXPECT_EQ(GUMBO_ERR_UTF8_INVALID, error->type);
EXPECT_EQ('\x85', *error->original_text);
EXPECT_EQ(0x85, error->v.codepoint);
utf8iterator_next(&input_);
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, MultipleContinuationBytes) {
SETUP();
ResetText("a\x85\xA0\xC2x\x9A");
EXPECT_EQ('a', utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ('x', utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(-1, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(4, GetNumErrors());
TEARDOWN();
}
TEST(Utf8Test, OverlongEncoding) {
SETUP();
// \xC0\x75 = 11000000 01110101.
ResetText("\xC0\x75");
ASSERT_EQ(1, GetNumErrors());
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
EXPECT_EQ('\xC0', *utf8iterator_get_char_pointer(&input_));
GumboError* error = GetFirstError();
EXPECT_EQ(GUMBO_ERR_UTF8_INVALID, error->type);
EXPECT_EQ(1, error->position.line);
EXPECT_EQ(1, error->position.column);
EXPECT_EQ(0, error->position.offset);
EXPECT_EQ('\xC0', *error->original_text);
EXPECT_EQ(0xC0, error->v.codepoint);
utf8iterator_next(&input_);
EXPECT_EQ(0x75, utf8iterator_current(&input_));
EXPECT_EQ('\x75', *utf8iterator_get_char_pointer(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, OverlongEncodingWithContinuationByte) {
SETUP();
// \xC0\x85 = 11000000 10000101.
ResetText("\xC0\x85");
ASSERT_EQ(1, GetNumErrors());
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
EXPECT_EQ('\xC0', *utf8iterator_get_char_pointer(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
GumboError* error = GetFirstError();
EXPECT_EQ(GUMBO_ERR_UTF8_INVALID, error->type);
EXPECT_EQ(1, error->position.line);
EXPECT_EQ(1, error->position.column);
EXPECT_EQ(0, error->position.offset);
EXPECT_EQ('\xC0', *error->original_text);
EXPECT_EQ(0xC0, error->v.codepoint);
utf8iterator_next(&input_);
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, TwoByteChar) {
SETUP();
// \xC3\xA5 = 11000011 10100101.
ResetText("\xC3\xA5o");
EXPECT_EQ(0, GetNumErrors());
// Codepoint = 000 11100101 = 0xE5.
EXPECT_EQ(0xE5, utf8iterator_current(&input_));
EXPECT_EQ('\xC3', *utf8iterator_get_char_pointer(&input_));
GumboSourcePosition pos;
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(1, pos.line);
EXPECT_EQ(1, pos.column);
EXPECT_EQ(0, pos.offset);
utf8iterator_next(&input_);
EXPECT_EQ('o', utf8iterator_current(&input_));
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(1, pos.line);
EXPECT_EQ(2, pos.column);
EXPECT_EQ(2, pos.offset);
TEARDOWN();
}
TEST(Utf8Test, TwoByteChar2) {
SETUP();
// \xC2\xA5 = 11000010 10100101.
ResetText("\xC2\xA5");
EXPECT_EQ(0, GetNumErrors());
// Codepoint = 000 10100101 = 0xA5.
EXPECT_EQ(0xA5, utf8iterator_current(&input_));
EXPECT_EQ('\xC2', *utf8iterator_get_char_pointer(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, ThreeByteChar) {
SETUP();
// \xE3\xA7\xA7 = 11100011 10100111 10100111
ResetText("\xE3\xA7\xA7\xB0");
EXPECT_EQ(0, GetNumErrors());
// Codepoint = 00111001 11100111 = 0x39E7
EXPECT_EQ(0x39E7, utf8iterator_current(&input_));
EXPECT_EQ('\xE3', *utf8iterator_get_char_pointer(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(1, GetNumErrors());
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
EXPECT_EQ('\xB0', *utf8iterator_get_char_pointer(&input_));
GumboSourcePosition pos;
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(1, pos.line);
EXPECT_EQ(2, pos.column);
EXPECT_EQ(3, pos.offset);
utf8iterator_next(&input_);
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, FourByteChar) {
SETUP();
// \xC3\x9A = 11000011 10011010
// \xF1\xA7\xA7\xA7 = 11110001 10100111 10100111 10100111
ResetText("\xC3\x9A\xF1\xA7\xA7\xA7");
// Codepoint = 000 11011010 = 0xDA.
EXPECT_EQ(0xDA, utf8iterator_current(&input_));
EXPECT_EQ('\xC3', *utf8iterator_get_char_pointer(&input_));
utf8iterator_next(&input_);
// Codepoint = 00110 01111001 11100111 = 0x679E7.
EXPECT_EQ(0x679E7, utf8iterator_current(&input_));
EXPECT_EQ('\xF1', *utf8iterator_get_char_pointer(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, FourByteCharWithoutContinuationChars) {
SETUP();
// \xF1\xA7\xA7\xA7 = 11110001 10100111 10100111 10100111
ResetText("\xF1\xA7\xA7-");
EXPECT_EQ(1, GetNumErrors());
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
EXPECT_EQ('\xF1', *utf8iterator_get_char_pointer(&input_));
utf8iterator_next(&input_);
EXPECT_EQ('-', utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, FiveByteCharIsError) {
SETUP();
ResetText("\xF6\xA7\xA7\xA7\xA7x");
EXPECT_EQ(1, GetNumErrors());
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
utf8iterator_next(&input_);
utf8iterator_next(&input_);
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ('x', utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, SixByteCharIsError) {
SETUP();
ResetText("\xF8\xA7\xA7\xA7\xA7\xA7x");
EXPECT_EQ(1, GetNumErrors());
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
utf8iterator_next(&input_);
utf8iterator_next(&input_);
utf8iterator_next(&input_);
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ('x', utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, SevenByteCharIsError) {
SETUP();
ResetText("\xFC\xA7\xA7\xA7\xA7\xA7\xA7x");
EXPECT_EQ(1, GetNumErrors());
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
utf8iterator_next(&input_);
utf8iterator_next(&input_);
utf8iterator_next(&input_);
utf8iterator_next(&input_);
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ('x', utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, xFFIsError) {
SETUP();
ResetText("\xFFx");
EXPECT_EQ(1, GetNumErrors());
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ('x', utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, InvalidControlCharIsNotReplaced) {
SETUP();
ResetText("\x1Bx");
EXPECT_EQ(1, GetNumErrors());
EXPECT_EQ(0x001B, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ('x', utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, TruncatedInput) {
SETUP();
ResetText("\xF1\xA7");
EXPECT_EQ(1, GetNumErrors());
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
GumboError* error = GetFirstError();
EXPECT_EQ(GUMBO_ERR_UTF8_TRUNCATED, error->type);
EXPECT_EQ(1, error->position.line);
EXPECT_EQ(1, error->position.column);
EXPECT_EQ(0, error->position.offset);
EXPECT_EQ('\xF1', *error->original_text);
EXPECT_EQ(0xF1A7, error->v.codepoint);
utf8iterator_next(&input_);
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, Html5SpecExample) {
SETUP();
// This example has since been removed from the spec, and the spec has been
// changed to reference the Unicode Standard 6.2, 5.22 "Best practices for
// U+FFFD substitution."
ResetText("\x41\x98\xBA\x42\xE2\x98\x43\xE2\x98\xBA\xE2\x98");
EXPECT_EQ('A', utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ('B', utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ('C', utf8iterator_current(&input_));
utf8iterator_next(&input_);
// \xE2\x98\xBA = 11100010 10011000 10111010
// Codepoint = 00100110 00111010 = 0x263A
EXPECT_EQ(0x263A, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(0xFFFD, utf8iterator_current(&input_));
utf8iterator_next(&input_);
TEARDOWN();
}
TEST(Utf8Test, MultipleEOFReads) {
SETUP();
ResetText("a");
Advance(2);
EXPECT_EQ(-1, utf8iterator_current(&input_));
utf8iterator_next(&input_);
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, AsciiOnly) {
SETUP();
ResetText("hello");
Advance(4);
EXPECT_EQ('o', utf8iterator_current(&input_));
EXPECT_EQ('o', *utf8iterator_get_char_pointer(&input_));
GumboSourcePosition pos;
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(1, pos.line);
EXPECT_EQ(5, pos.column);
EXPECT_EQ(4, pos.offset);
Advance(1);
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, NewlinePosition) {
SETUP();
ResetText("a\nnewline");
Advance(1);
// Newline itself should register as being at the end of a line.
GumboSourcePosition pos;
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(1, pos.line);
EXPECT_EQ(2, pos.column);
EXPECT_EQ(1, pos.offset);
// The next character should be at the next line.
Advance(1);
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(2, pos.line);
EXPECT_EQ(1, pos.column);
EXPECT_EQ(2, pos.offset);
TEARDOWN();
}
TEST(Utf8Test, TabPositionFreshTabstop) {
SETUP();
ResetText("a\n\ttab");
Advance(sizeof("a\n\t") - 1);
GumboSourcePosition pos;
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(2, pos.line);
EXPECT_EQ(8, pos.column);
EXPECT_EQ(3, pos.offset);
TEARDOWN();
}
TEST(Utf8Test, TabPositionMidTabstop) {
SETUP();
ResetText("a tab\tinline");
Advance(sizeof("a tab\t") - 1);
GumboSourcePosition pos;
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(1, pos.line);
EXPECT_EQ(8, pos.column);
EXPECT_EQ(6, pos.offset);
TEARDOWN();
}
TEST(Utf8Test, ConfigurableTabstop) {
SETUP();
options_.tab_stop = 4;
ResetText("a\n\ttab");
Advance(sizeof("a\n\t") - 1);
GumboSourcePosition pos;
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(2, pos.line);
EXPECT_EQ(4, pos.column);
EXPECT_EQ(3, pos.offset);
TEARDOWN();
}
TEST(Utf8Test, CRLF) {
SETUP();
ResetText("Windows\r\nlinefeeds");
Advance(sizeof("Windows") - 1);
EXPECT_EQ('\n', utf8iterator_current(&input_));
EXPECT_EQ('\n', *utf8iterator_get_char_pointer(&input_));
GumboSourcePosition pos;
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(1, pos.line);
// The carriage return should be ignore in column calculations, treating the
// CRLF combination as one character.
EXPECT_EQ(8, pos.column);
// However, it should not be ignored in computing offsets, which are often
// used by other tools to index into the original buffer. We don't expect
// other unicode-aware tools to have the same \r\n handling as HTML5.
EXPECT_EQ(8, pos.offset);
TEARDOWN();
}
TEST(Utf8Test, CarriageReturn) {
SETUP();
ResetText("Mac\rlinefeeds");
Advance(sizeof("Mac") - 1);
EXPECT_EQ('\n', utf8iterator_current(&input_));
// We don't change the original pointer, which is part of the const input
// buffer. original_text pointers will see a carriage return as original
// written.
EXPECT_EQ('\r', *utf8iterator_get_char_pointer(&input_));
GumboSourcePosition pos;
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(1, pos.line);
EXPECT_EQ(4, pos.column);
EXPECT_EQ(3, pos.offset);
Advance(1);
EXPECT_EQ('l', utf8iterator_current(&input_));
EXPECT_EQ('l', *utf8iterator_get_char_pointer(&input_));
utf8iterator_get_position(&input_, &pos);
EXPECT_EQ(2, pos.line);
EXPECT_EQ(1, pos.column);
EXPECT_EQ(4, pos.offset);
TEARDOWN();
}
TEST(Utf8Test, Matches) {
SETUP();
ResetText("\xC2\xA5goobar");
Advance(1);
EXPECT_TRUE(utf8iterator_maybe_consume_literal(&input_, "goo"));
EXPECT_EQ('b', utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, MatchesOverflow) {
SETUP();
ResetText("goo");
EXPECT_FALSE(utf8iterator_maybe_consume_literal(&input_, "goobar"));
EXPECT_EQ('g', utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, MatchesEof) {
SETUP();
ResetText("goo");
EXPECT_TRUE(utf8iterator_maybe_consume_literal(&input_, "goo"));
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, MatchesCaseSensitivity) {
SETUP();
ResetText("gooBAR");
EXPECT_FALSE(utf8iterator_maybe_consume_literal(&input_, "goobar"));
EXPECT_EQ('g', utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, MatchesCaseInsensitive) {
SETUP();
ResetText("gooBAR");
EXPECT_TRUE(utf8iterator_maybe_consume_literal_icase(&input_, "goobar"));
EXPECT_EQ(-1, utf8iterator_current(&input_));
TEARDOWN();
}
TEST(Utf8Test, MatchFollowedByNullByte) {
SETUP();
// Can't use ResetText, as the implicit strlen will choke on the null.
const char *text = "CDATA\0f";
utf8iterator_init(&parser_, text, 7, &input_);
EXPECT_TRUE(utf8iterator_maybe_consume_literal_icase(&input_, "cdata"));
EXPECT_EQ(0, utf8iterator_current(&input_));
EXPECT_EQ('\0', *utf8iterator_get_char_pointer(&input_));
utf8iterator_next(&input_);
EXPECT_EQ('f', utf8iterator_current(&input_));
EXPECT_EQ('f', *utf8iterator_get_char_pointer(&input_));
TEARDOWN();
}
TEST(Utf8Test, MarkReset) {
SETUP();
ResetText("this is a test");
Advance(5);
EXPECT_EQ('i', utf8iterator_current(&input_));
utf8iterator_mark(&input_);
Advance(3);
EXPECT_EQ('a', utf8iterator_current(&input_));
GumboError error;
utf8iterator_fill_error_at_mark(&input_, &error);
EXPECT_EQ('i', *error.original_text);
EXPECT_EQ(1, error.position.line);
EXPECT_EQ(6, error.position.column);
EXPECT_EQ(5, error.position.offset);
utf8iterator_reset(&input_);
EXPECT_EQ('i', utf8iterator_current(&input_));
EXPECT_EQ('i', *utf8iterator_get_char_pointer(&input_));
GumboSourcePosition position;
utf8iterator_get_position(&input_, &position);
EXPECT_EQ(1, error.position.line);
EXPECT_EQ(6, error.position.column);
EXPECT_EQ(5, error.position.offset);
TEARDOWN();
}
| 2.203125 | 2 |
2024-11-18T21:06:44.745994+00:00 | 2018-06-08T22:43:49 | 88a65027722452aab07adfff216010e53c665833 | {
"blob_id": "88a65027722452aab07adfff216010e53c665833",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-08T22:43:49",
"content_id": "1035b17a94cfc357be3d614cc18ee2800f74441f",
"detected_licenses": [
"MIT"
],
"directory_id": "cb3fe2aa64cb24d0ced9adea6242671c075992b8",
"extension": "c",
"filename": "system_init.c",
"fork_events_count": 2,
"gha_created_at": "2016-09-28T21:56:47",
"gha_event_created_at": "2017-06-03T16:18:12",
"gha_language": "C",
"gha_license_id": null,
"github_id": 69507029,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1132,
"license": "MIT",
"license_type": "permissive",
"path": "/kernel/platform/system_init.c",
"provenance": "stackv2-0128.json.gz:88153",
"repo_name": "goniz/gzOS",
"revision_date": "2018-06-08T22:43:49",
"revision_id": "176bfcdd06370d634a56df61b0cd7cf6c92ad9f8",
"snapshot_id": "2f5bad243d6a80d2e65df0804161efeceeae56a2",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/goniz/gzOS/176bfcdd06370d634a56df61b0cd7cf6c92ad9f8/kernel/platform/system_init.c",
"visit_date": "2021-01-11T17:04:48.961772"
} | stackv2 | #include <stdio.h>
#include <lib/kernel/proc/Scheduler.h>
#include <platform/pci/pci.h>
#include <platform/drivers.h>
#include "kprintf.h"
#include "clock.h"
static void initialize_stdio(void);
static void invoke_constructors(void);
extern int __init_array_start;
extern int __init_array_end;
extern int kernel_main(void *argument);
void system_init(int argc, const char **argv, const char **envp)
{
initialize_stdio();
invoke_constructors();
drivers_init();
platform_pci_driver_probe();
scheduler_run_main(kernel_main, NULL);
}
static void initialize_stdio(void)
{
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
}
static void invoke_constructors(void)
{
typedef void (*func_t)(void);
int* init_array = &__init_array_start;
int* init_array_end = &__init_array_end;
/*
* Call C++ constructors
*/
printf("\nInvoking C++ static constructors!\n");
while (init_array < init_array_end) {
func_t func = (func_t)(*init_array++);
printf("Invoking ctor at %p\r\n", func);
func();
}
}
| 2.375 | 2 |
2024-11-18T21:06:45.038879+00:00 | 2023-05-10T22:56:51 | b24f3d600b2de05daac051463ab44b73f0378b3b | {
"blob_id": "b24f3d600b2de05daac051463ab44b73f0378b3b",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-10T23:23:49",
"content_id": "dfcc6166930466bcc21e032579c0832f4dfdc6f7",
"detected_licenses": [
"ISC"
],
"directory_id": "96708ff23d9ab55862bd252dbb929c1dc29a7fec",
"extension": "c",
"filename": "scsniff.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 249073536,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3169,
"license": "ISC",
"license_type": "permissive",
"path": "/scsniff.c",
"provenance": "stackv2-0128.json.gz:88544",
"repo_name": "yarrick/scsniff",
"revision_date": "2023-05-10T22:56:51",
"revision_id": "9363dcd9944d348b1fc50e8c195c8c30ecbc0cc3",
"snapshot_id": "2ff43c101c8168f16b63f770ab5178d800429778",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/yarrick/scsniff/9363dcd9944d348b1fc50e8c195c8c30ecbc0cc3/scsniff.c",
"visit_date": "2023-05-27T19:30:29.601451"
} | stackv2 | #define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include "packet.h"
#include "serial.h"
#include "session.h"
static int reset_active(int fd) {
int reset = serial_reset_active(fd);
if (reset == -1) {
fprintf(stderr, "Connection lost\n");
exit(1);
}
return reset;
}
static struct timeval reset_time;
static void wait_reset(int fd) {
fprintf(stderr, "== Waiting for reset.. ");
fflush(stderr);
serial_wait_reset(fd);
fprintf(stderr, "Done\n");
}
static void usage(char *name) {
fprintf(stderr, "\nUsage: %s <device> [<baudrate>]\n", name);
exit(2);
}
static void handle_packet(struct packet *packet) {
struct timeval diff;
unsigned i;
timersub(&packet->time, &reset_time, &diff);
printf("+%ld.%06lds | ", diff.tv_sec, diff.tv_usec);
switch (packet->result) {
case NOISE: printf("NOISE??"); break;
case PACKET_TO_CARD: printf("CARD<<<"); break;
case PACKET_FROM_CARD: printf("CARD>>>"); break;
case PACKET_UNKNOWN: printf("CARD<?>"); break;
default: printf("ERROR!!"); break;
}
printf(" |");
for (i = 0; i < packet->data_length; i++) {
printf(" %02X", packet->data[i]);
}
printf("\n");
}
static void log_message(const char *message) {
fprintf(stderr, "== %s\n", message);
}
int main(int argc, char **argv) {
if (argc < 2) usage(argv[0]);
int fd = serial_open(argv[1]);
if(fd < 0) {
fprintf(stderr, "Opening %s ", argv[1]);
perror("failed");
usage(argv[0]);
}
int baudrate = 9600;
if (argc > 2) {
baudrate = atoi(argv[2]);
}
if (baudrate <= 0) {
fprintf(stderr, "Failed to parse baudrate '%s'\n", argv[2]);
usage(argv[0]);
}
fprintf(stderr, "== Opened %s\n", argv[1]);
struct session session;
session_init(&session, handle_packet, serial_configure, log_message,
fd, baudrate);
while (1) {
fprintf(stderr, "== Speed: %d baud\n", baudrate);
if (!reset_active(fd)) wait_reset(fd);
gettimeofday(&reset_time, NULL);
while (reset_active(fd)) {
// Eat noise while reset active.
unsigned char c;
read(fd, &c, 1);
}
int loops = 0;
int resets = 0;
while (1) {
unsigned char c;
if (read(fd, &c, 1) >0) {
loops = 0;
if (resets < 15) session_add_byte(&session, c);
}
if (reset_active(fd)) {
resets++;
if (resets > 50) {
fprintf(stderr, "\n========================="
"\n== Got warm reset or deactivate\n");
break;
}
} else {
resets = 0;
}
loops++;
if (loops > 3000000) {
fprintf(stderr, "\n=========================\n== Timeout!\n");
break;
}
}
session_reset(&session);
}
return 0;
}
| 2.65625 | 3 |
2024-11-18T21:06:45.903477+00:00 | 2023-08-30T14:32:34 | e70103b9c5917de0475714f403d67c60146890d3 | {
"blob_id": "e70103b9c5917de0475714f403d67c60146890d3",
"branch_name": "refs/heads/develop",
"committer_date": "2023-08-30T14:32:34",
"content_id": "882128329204a55635dab6f1afc4b1c0564cfbd0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "dca770e1b56cf36ef1922a4293298a3e8e155a26",
"extension": "c",
"filename": "ulp_adc_example_main.c",
"fork_events_count": 576,
"gha_created_at": "2016-10-21T23:00:55",
"gha_event_created_at": "2023-09-11T13:27:05",
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 71603115,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3397,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/examples/espidf-ulp-adc/main/ulp_adc_example_main.c",
"provenance": "stackv2-0128.json.gz:88673",
"repo_name": "platformio/platform-espressif32",
"revision_date": "2023-08-30T14:32:34",
"revision_id": "ceafaa7c176c18875538886b35e7291b2635f64a",
"snapshot_id": "45c60ae0973a62ca7c4bc17f22a95c569528a905",
"src_encoding": "UTF-8",
"star_events_count": 787,
"url": "https://raw.githubusercontent.com/platformio/platform-espressif32/ceafaa7c176c18875538886b35e7291b2635f64a/examples/espidf-ulp-adc/main/ulp_adc_example_main.c",
"visit_date": "2023-08-31T02:51:07.482741"
} | stackv2 | /* ULP Example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "esp_sleep.h"
#include "soc/rtc_cntl_reg.h"
#include "soc/sens_reg.h"
#include "driver/gpio.h"
#include "driver/rtc_io.h"
#include "ulp.h"
#include "ulp_main.h"
#include "esp_adc/adc_oneshot.h"
#include "ulp/example_config.h"
#include "ulp_adc.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
extern const uint8_t ulp_main_bin_start[] asm("_binary_ulp_main_bin_start");
extern const uint8_t ulp_main_bin_end[] asm("_binary_ulp_main_bin_end");
/* This function is called once after power-on reset, to load ULP program into
* RTC memory and configure the ADC.
*/
static void init_ulp_program(void);
/* This function is called every time before going into deep sleep.
* It starts the ULP program and resets measurement counter.
*/
static void start_ulp_program(void);
void app_main(void)
{
esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
if (cause != ESP_SLEEP_WAKEUP_ULP) {
printf("Not ULP wakeup\n");
init_ulp_program();
} else {
printf("Deep sleep wakeup\n");
printf("ULP did %"PRIu32" measurements since last reset\n", ulp_sample_counter & UINT16_MAX);
printf("Thresholds: low=%"PRIu32" high=%"PRIu32"\n", ulp_low_thr, ulp_high_thr);
ulp_last_result &= UINT16_MAX;
printf("Value=%"PRIu32" was %s threshold\n", ulp_last_result,
ulp_last_result < ulp_low_thr ? "below" : "above");
}
printf("Entering deep sleep\n\n");
start_ulp_program();
ESP_ERROR_CHECK( esp_sleep_enable_ulp_wakeup() );
#if !CONFIG_IDF_TARGET_ESP32
/* RTC peripheral power domain needs to be kept on to keep SAR ADC related configs during sleep */
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
#endif
esp_deep_sleep_start();
}
static void init_ulp_program(void)
{
esp_err_t err = ulp_load_binary(0, ulp_main_bin_start,
(ulp_main_bin_end - ulp_main_bin_start) / sizeof(uint32_t));
ESP_ERROR_CHECK(err);
ulp_adc_cfg_t cfg = {
.adc_n = EXAMPLE_ADC_UNIT,
.channel = EXAMPLE_ADC_CHANNEL,
.width = EXAMPLE_ADC_WIDTH,
.atten = EXAMPLE_ADC_ATTEN,
.ulp_mode = ADC_ULP_MODE_FSM,
};
ESP_ERROR_CHECK(ulp_adc_init(&cfg));
ulp_low_thr = EXAMPLE_ADC_LOW_TRESHOLD;
ulp_high_thr = EXAMPLE_ADC_HIGH_TRESHOLD;
/* Set ULP wake up period to 20ms */
ulp_set_wakeup_period(0, 20000);
#if CONFIG_IDF_TARGET_ESP32
/* Disconnect GPIO12 and GPIO15 to remove current drain through
* pullup/pulldown resistors on modules which have these (e.g. ESP32-WROVER)
* GPIO12 may be pulled high to select flash voltage.
*/
rtc_gpio_isolate(GPIO_NUM_12);
rtc_gpio_isolate(GPIO_NUM_15);
#endif // CONFIG_IDF_TARGET_ESP32
esp_deep_sleep_disable_rom_logging(); // suppress boot messages
}
static void start_ulp_program(void)
{
/* Reset sample counter */
ulp_sample_counter = 0;
/* Start the program */
esp_err_t err = ulp_run(&ulp_entry - RTC_SLOW_MEM);
ESP_ERROR_CHECK(err);
}
| 2.171875 | 2 |
2024-11-18T21:06:46.634569+00:00 | 2021-10-02T19:23:32 | 0f378905211fcca5f993ff18f14ee9b45cb2d672 | {
"blob_id": "0f378905211fcca5f993ff18f14ee9b45cb2d672",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-02T19:23:32",
"content_id": "3dc06ced66f8a58ae0bc0721cc10cb8969dc5afd",
"detected_licenses": [
"MIT"
],
"directory_id": "0e8d193b1aad75c1ef76c1ded5bda58d34984705",
"extension": "c",
"filename": "SPIRIT1_Util.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 412890552,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10639,
"license": "MIT",
"license_type": "permissive",
"path": "/components/spirit1/SPIRIT1_Util/Src/SPIRIT1_Util.c",
"provenance": "stackv2-0128.json.gz:89317",
"repo_name": "mcu/esp32-spirit1",
"revision_date": "2021-10-02T19:23:32",
"revision_id": "86773be90daeb387b1de4c6d74f5766be699f732",
"snapshot_id": "9cfefcfc2b5fa91dc4f85d8f1ba64f5de3ccf58b",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/mcu/esp32-spirit1/86773be90daeb387b1de4c6d74f5766be699f732/components/spirit1/SPIRIT1_Util/Src/SPIRIT1_Util.c",
"visit_date": "2023-08-31T00:11:02.149411"
} | stackv2 | /* Includes ------------------------------------------------------------------*/
#include "esp_log.h"
#include "SPIRIT1_Util.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "driver/gpio.h"
#include "spirit1_appli.h"
//#endif
/**
* @addtogroup ST_SPIRIT1
* @{
*/
/**
* @addtogroup SPIRIT1_Util
* @{
*/
/**
* @defgroup SPIRIT1_Util_Private_TypesDefinitions SPIRIT1_Util Private Types Definitions
* @{
*/
/**
* @}
*/
/**
* @defgroup SPIRIT1_Util_Private_Defines SPIRIT1_Util Private Defines
* @{
*/
/**
* @}
*/
/**
* @defgroup SPIRIT1_Util_Private_Macros SPIRIT1_Util Private Macros
* @{
*/
#define XTAL_FREQUENCY 50000000L
#define SPIRIT_VERSION SPIRIT_VERSION_3_0
#define RANGE_TYPE RANGE_EXT_NONE /*RANGE_EXT_SKYWORKS*/
/**
* @}
*/
/**
* @defgroup SPIRIT1_Util_Private_Variables SPIRIT1_Util Private Variables
* @{
*/
/**
* @brief A map that contains the SPIRIT version
*/
const SpiritVersionMap xSpiritVersionMap[] =
{
/* The Control Board frame handler functions */
{CUT_2_1v4, SPIRIT_VERSION_2_1},
{CUT_2_1v3, SPIRIT_VERSION_2_1},
{CUT_3_0, SPIRIT_VERSION_3_0},
};
static RangeExtType xRangeExtType = RANGE_EXT_NONE;
static uint8_t s_RfModuleBand = 0;
static uint8_t s_eeprom = 0;
static int32_t s_RfModuleOffset=0;
/**
* @}
*/
/**
* @defgroup SPIRIT1_Util_Private_FunctionPrototypes SPIRIT1_Util Private Function Prototypes
* @{
*/
/**
* @}
*/
/**
* @defgroup SPIRIT1_Util_Private_Functions SPIRIT1_Util Private Functions
* @{
*/
/**
* @brief Read the status register.
* @param None
* @retval Status
*/
void Spirit1InterfaceInit(void)
{
RadioGpioInit(RADIO_GPIO_SDN,RADIO_MODE_GPIO_OUT);
SpiritSpiInit();
/* Board management */
SpiritEnterShutdown();
SpiritExitShutdown();
SpiritManagementIdentificationRFBoard();
SpiritManagementRangeExtInit();
RadioGpioInit(RADIO_GPIO_3,RADIO_MODE_EXTI_IN);
}
void SpiritSetIntHandler(void (*handler)(void *), void *arg)
{
RadioGpioInterruptSetHandler(RADIO_GPIO_3, handler, arg);
}
#if defined(SPIRIT1_HAS_EEPROM)
/**
* @brief Read the status register.
* @param None
* @retval Status
*/
uint8_t EepromIdentification(void)
{
uint8_t status;
status = EepromSetSrwd();
status = EepromStatus();
if((status&0xF0) == EEPROM_STATUS_SRWD)
{
/*0xF0 mask [SRWD 0 0 0]*/
status = 1;
EepromResetSrwd();
}
else
status = 0;
return status;
}
#endif
/**
* @brief Identifies the SPIRIT1 Xtal frequency and version.
* @param None
* @retval Status
*/
void SpiritManagementIdentificationRFBoard(void)
{
do{
/* Delay for state transition */
vTaskDelay(pdMS_TO_TICKS(1));
/* Reads the MC_STATUS register */
SpiritRefreshStatus();
}while(g_xStatus.MC_STATE!=MC_STATE_READY);
SpiritRadioSetXtalFrequency(XTAL_FREQUENCY);
//SpiritGeneralSetSpiritVersion(SPIRIT_VERSION);
}
/**
* @brief Sets the SPIRIT frequency band
* @param uint8_t value: RF FREQUENCY
* @retval None
*/
void SpiritManagementSetBand(uint8_t value)
{
s_RfModuleBand = value;
}
/**
* @brief returns the SPIRIT frequency band
* @param None
* @retval uint8_t value: RF FREQUENCY
*/
uint8_t SpiritManagementGetBand(void)
{
return s_RfModuleBand;
}
/**
* @defgroup RANGE_EXT_MANAGEMENT_FUNCTIONS SDK SPIRIT Management Range Extender Functions
* @{
*/
void SpiritManagementRangeExtInit(void)
{
RangeExtType range_type = SpiritManagementGetRangeExtender();
if(range_type==RANGE_EXT_SKYWORKS_169) {
/* TCXO optimization power consumption */
SpiritGeneralSetExtRef(MODE_EXT_XIN);
uint8_t tmp = 0x01; SpiritSpiWriteRegisters(0xB6,1,&tmp);
/* CSD control */
SpiritGpioInit(&(SGpioInit){SPIRIT_GPIO_0, SPIRIT_GPIO_MODE_DIGITAL_OUTPUT_HP, SPIRIT_GPIO_DIG_OUT_TX_RX_MODE});
/* CTX/BYP control */
SpiritGpioInit(&(SGpioInit){SPIRIT_GPIO_1, SPIRIT_GPIO_MODE_DIGITAL_OUTPUT_HP, SPIRIT_GPIO_DIG_OUT_TX_STATE});
/* Vcont control */
SpiritGpioInit(&(SGpioInit){SPIRIT_GPIO_2, SPIRIT_GPIO_MODE_DIGITAL_OUTPUT_HP, SPIRIT_GPIO_DIG_OUT_RX_STATE});
}
else if(range_type==RANGE_EXT_SKYWORKS_868) {
/* CSD control */
SpiritGpioInit(&(SGpioInit){SPIRIT_GPIO_0, SPIRIT_GPIO_MODE_DIGITAL_OUTPUT_HP, SPIRIT_GPIO_DIG_OUT_TX_RX_MODE});
/* CTX/BYP control */
SpiritGpioInit(&(SGpioInit){SPIRIT_GPIO_1, SPIRIT_GPIO_MODE_DIGITAL_OUTPUT_HP, SPIRIT_GPIO_DIG_OUT_RX_STATE});
/* Vcont control */
SpiritGpioInit(&(SGpioInit){SPIRIT_GPIO_2, SPIRIT_GPIO_MODE_DIGITAL_OUTPUT_HP, SPIRIT_GPIO_DIG_OUT_TX_STATE});
}
}
/**
* @brief returns the spirit1 range extender type
* @param None
* @retval RangeExtType
*/
RangeExtType SpiritManagementGetRangeExtender(void)
{
return xRangeExtType;
}
/**
* @brief Sets the spirit1 range extender type
* @param RangeExtType
* @retval None
*/
void SpiritManagementSetRangeExtender(RangeExtType xRangeType)
{
xRangeExtType = xRangeType;
}
/**
* @brief this function returns the value to indicate that EEPROM is present or not
* @param None
* @retval uint8_t: 0 or 1
*/
uint8_t SdkEvalGetHasEeprom(void)
{
return s_eeprom;
}
/**
* @brief this function setc the value to indicate that EEPROM is present or not
* @param None
* @retval uint8_t: 0 or 1
*/
void SdkEvalSetHasEeprom(uint8_t eeprom)
{
s_eeprom = eeprom;
}
/**
* @brief this function intializes the spirit1 gpio irq for TX and Rx
* @param None
* @retval None
*/
void Spirit1GpioIrqInit(SGpioInit *pGpioIRQ)
{
/* Spirit IRQ config */
SpiritGpioInit(pGpioIRQ);
}
/**
* @brief this function used to receive RX packet
* @param None
* @retval None
*/
void Spirit1RadioInit(SRadioInit *pRadioInit)
{
/* Spirit Radio config */
SpiritRadioInit(pRadioInit);
}
/**
* @brief this function sets the radio power
* @param uint8_t cIndex, float fPowerdBm
* @retval None
*/
void Spirit1SetPower(uint8_t cIndex, float fPowerdBm)
{
/* Spirit Radio set power */
SpiritRadioSetPALeveldBm(cIndex,fPowerdBm);
SpiritRadioSetPALevelMaxIndex(cIndex);
}
/**
* @brief this function sets the packet configuration according to the protocol used
* @param None
* @retval None
*/
void Spirit1PacketConfig(void)
{
BasicProtocolInit();
}
/**
* @brief this function sets the payload length
* @param uint8_t length
* @retval None
*/
void Spirit1SetPayloadlength(uint8_t length)
{
/* payload length config */
SpiritPktBasicSetPayloadLength(length);
}
/**
* @brief this function sets the destination address
* @param uint8_t adress
* @retval None
*/
void Spirit1SetDestinationAddress(uint8_t address)
{
/* destination address */
SpiritPktBasicSetDestinationAddress(address);
}
/**
* @brief this function enables the Tx IRQ
* @param None
* @retval None
*/
void Spirit1EnableTxIrq(void)
{
/* Spirit IRQs enable */
SpiritIrq(TX_DATA_SENT, S_ENABLE);
}
/**
* @brief this function enables the Rx IRQ
* @param None
* @retval None
*/
void Spirit1EnableRxIrq(void)
{
/* Spirit IRQs enable */
SpiritIrq(RX_DATA_READY, S_ENABLE);
SpiritIrq(RX_DATA_DISC, S_ENABLE);
SpiritIrq(RX_TIMEOUT, S_ENABLE);
}
/**
* @brief this function disable IRQs
* @param None
* @retval None
*/
void Spirit1DisableIrq(void)
{
/* Spirit IRQs enable */
SpiritIrqDeInit(NULL);
}
/**
* @brief this function set the receive timeout period
* @param None
* @retval None
*/
void Spirit1SetRxTimeout(float cRxTimeOut)
{
if(cRxTimeOut == 0)
{
/* rx timeout config */
SET_INFINITE_RX_TIMEOUT();
SpiritTimerSetRxTimeoutStopCondition(ANY_ABOVE_THRESHOLD);
}
else
{
/* RX timeout config */
SpiritTimerSetRxTimeoutMs(cRxTimeOut);
Spirit1EnableSQI();
SpiritTimerSetRxTimeoutStopCondition(RSSI_AND_SQI_ABOVE_THRESHOLD);
}
}
/**
* @brief this function sets the RSSI threshold
* @param int dbmValue
* @retval None
*/
void Spirit1SetRssiTH(int dbmValue)
{
SpiritQiSetRssiThresholddBm(dbmValue);
}
/**
* @brief this function sets the RSSI threshold
* @param int dbmValue
* @retval None
*/
float Spirit1GetRssiTH(void)
{
float dbmValue=0;
dbmValue = SpiritQiGetRssidBm();
return dbmValue;
}
/**
* @brief this function enables SQI check
* @param None
* @retval None
*/
void Spirit1EnableSQI(void)
{
/* enable SQI check */
SpiritQiSetSqiThreshold(SQI_TH_0);
SpiritQiSqiCheck(S_ENABLE);
}
/**
* @brief this function starts the RX process
* @param None
* @retval None
*/
void Spirit1StartRx(void)
{
#if 1
if(g_xStatus.MC_STATE==MC_STATE_RX)
{
SpiritCmdStrobeSabort();
}
#endif
/* RX command */
SpiritCmdStrobeRx();
}
/**
* @brief this function receives the data
* @param None
* @retval None
*/
void Spirit1GetRxPacket(uint8_t *buffer, uint8_t *cRxData )
{
uint8_t noofbytes = 0;
/* when rx data ready read the number of received bytes */
*cRxData=SpiritLinearFifoReadNumElementsRxFifo();
noofbytes = *cRxData;
/* read the RX FIFO */
SpiritSpiReadLinearFifo(noofbytes, buffer);
SpiritCmdStrobeFlushRxFifo();
}
/**
* @brief this function starts the TX process
* @param None
* @retval None
*/
void Spirit1StartTx(uint8_t *buffer, uint8_t size )
{
if(g_xStatus.MC_STATE==MC_STATE_RX)
{
SpiritCmdStrobeSabort();
}
#ifdef CSMA_ENABLE
/* Enable CSMA */
SpiritRadioPersistenRx(S_DISABLE);
SpiritRadioCsBlanking(S_DISABLE);
SpiritCsmaInit(&xCsmaInit);
SpiritCsma(S_ENABLE);
SpiritQiSetRssiThresholddBm(CSMA_RSSI_THRESHOLD);
#endif
/* fit the TX FIFO */
SpiritCmdStrobeFlushTxFifo();
SpiritSpiWriteLinearFifo(size, buffer);
/* send the TX command */
SpiritCmdStrobeTx();
}
/**
* @brief this function clear the IRQ status
* @param None
* @retval None
*/
void Spirit1ClearIRQ(void)
{
SpiritIrqClearStatus();
}
void SpiritManagementSetOffset(int32_t value)
{
s_RfModuleOffset=value;
}
int32_t SpiritManagementGetOffset(void)
{
return s_RfModuleOffset;
}
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/
| 2.15625 | 2 |
2024-11-18T21:06:46.820626+00:00 | 2018-02-11T22:32:28 | 3ff202e53beb69167a608f7fa7cf5f80156ce3d2 | {
"blob_id": "3ff202e53beb69167a608f7fa7cf5f80156ce3d2",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-11T22:32:28",
"content_id": "8977d5a91d30f099ae779da40f9cfceb9cfbdbcc",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "886becb5df0db3dd417a958774dfad00744e74b7",
"extension": "c",
"filename": "table-generator-test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 93900813,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 981,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/tests/table-generator-test.c",
"provenance": "stackv2-0128.json.gz:89575",
"repo_name": "basbossink/mokarc-ch01-1.03",
"revision_date": "2018-02-11T22:32:28",
"revision_id": "553d081e2b80f8ae39752205128ce50f8174fbcf",
"snapshot_id": "06738e237e0d80db84c1c23e1d0df37c3a2c61f9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/basbossink/mokarc-ch01-1.03/553d081e2b80f8ae39752205128ce50f8174fbcf/tests/table-generator-test.c",
"visit_date": "2021-01-25T10:56:54.902903"
} | stackv2 | #include <math.h>
#include "../vendor/minunit/minunit.h"
#include "../src/table-generator.h"
static int output_call_count = 0;
double converter_stub(
double input) {
return input;
}
int call_counter(
char const * line) {
(void)line;
return output_call_count++;
}
char* test_table_generator(void) {
const double start = 0.0;
const double maximum = 10.0;
const double step = 1.0;
generate_table(
start,
maximum,
step,
"",
"",
converter_stub,
call_counter);
const int expected = 12;
char const *message_format = "(%s:%s) expected conversion of table genarator with start %f maximum %f step %f to call output function %d times but it was called %d times.";
mu_assert(
output_call_count == expected,
message_format,
__FILE__,
__func__,
start,
maximum,
step,
expected,
output_call_count);
return 0;
}
| 2.34375 | 2 |
2024-11-18T21:06:46.994508+00:00 | 2023-07-18T07:07:59 | a2ecdde9b88869f00656b532502bf2e1c9c778bf | {
"blob_id": "a2ecdde9b88869f00656b532502bf2e1c9c778bf",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-30T12:25:58",
"content_id": "50ce545a57309b28a3fa225a727d3089648e9771",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "a01baa2a29bc08c093a11144983133128bb2ffb1",
"extension": "c",
"filename": "shake.c",
"fork_events_count": 2,
"gha_created_at": "2022-02-20T13:23:12",
"gha_event_created_at": "2022-02-20T13:23:13",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 461494646,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2815,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/core/lib/libtomcrypt/shake.c",
"provenance": "stackv2-0128.json.gz:89834",
"repo_name": "gagachang/optee_os",
"revision_date": "2023-07-18T07:07:59",
"revision_id": "3db1b3e3179fb98fba226bae3b7d6d1f5723e8ac",
"snapshot_id": "e9166cb0a21117e4f5faff5ccdbc0ba429518122",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gagachang/optee_os/3db1b3e3179fb98fba226bae3b7d6d1f5723e8ac/core/lib/libtomcrypt/shake.c",
"visit_date": "2023-08-30T13:34:50.650048"
} | stackv2 | // SPDX-License-Identifier: BSD-2-Clause
/*
* Copyright (c) 2022, Linaro Limited
*/
#include <crypto/crypto.h>
#include <crypto/crypto_impl.h>
#include <stdlib.h>
#include <string.h>
#include <tomcrypt_private.h>
#include <utee_defines.h>
struct shake_ctx {
struct crypto_hash_ctx ctx;
struct sha3_state sha3;
};
static struct shake_ctx *to_shake_ctx(struct crypto_hash_ctx *ctx)
{
return container_of(ctx, struct shake_ctx, ctx);
}
static TEE_Result do_shake_init(struct crypto_hash_ctx *ctx, unsigned int num)
{
struct shake_ctx *c = to_shake_ctx(ctx);
if (sha3_shake_init((void *)&c->sha3, num) == CRYPT_OK)
return TEE_SUCCESS;
else
return TEE_ERROR_BAD_STATE;
}
static TEE_Result do_sha3_update(struct crypto_hash_ctx *ctx,
const uint8_t *data, size_t len)
{
struct shake_ctx *c = to_shake_ctx(ctx);
if (sha3_process((void *)&c->sha3, data, len) == CRYPT_OK)
return TEE_SUCCESS;
else
return TEE_ERROR_BAD_STATE;
}
static TEE_Result do_shake_final(struct crypto_hash_ctx *ctx,
uint8_t *digest, size_t len)
{
struct shake_ctx *c = to_shake_ctx(ctx);
if (sha3_shake_done((void *)&c->sha3, digest, len) == CRYPT_OK)
return TEE_SUCCESS;
else
return TEE_ERROR_BAD_STATE;
}
static TEE_Result do_shake_alloc_ctx(struct crypto_hash_ctx **ctx_ret,
const struct crypto_hash_ops *ops)
{
struct shake_ctx *ctx = calloc(1, sizeof(*ctx));
if (!ctx)
return TEE_ERROR_OUT_OF_MEMORY;
ctx->ctx.ops = ops;
*ctx_ret = &ctx->ctx;
return TEE_SUCCESS;
}
static void do_sha3_free_ctx(struct crypto_hash_ctx *ctx)
{
struct shake_ctx *c = to_shake_ctx(ctx);
free(c);
}
static void do_sha3_copy_state(struct crypto_hash_ctx *dst_ctx,
struct crypto_hash_ctx *src_ctx)
{
struct shake_ctx *dc = to_shake_ctx(dst_ctx);
struct shake_ctx *sc = to_shake_ctx(src_ctx);
assert(sc->ctx.ops == dc->ctx.ops);
dc->sha3 = sc->sha3;
}
#if defined(_CFG_CORE_LTC_SHAKE128)
static TEE_Result do_shake128_init(struct crypto_hash_ctx *ctx)
{
return do_shake_init(ctx, 128);
}
static const struct crypto_hash_ops shake128_ops = {
.init = do_shake128_init,
.update = do_sha3_update,
.final = do_shake_final,
.free_ctx = do_sha3_free_ctx,
.copy_state = do_sha3_copy_state,
};
TEE_Result crypto_shake128_alloc_ctx(struct crypto_hash_ctx **ctx)
{
return do_shake_alloc_ctx(ctx, &shake128_ops);
}
#endif
#if defined(_CFG_CORE_LTC_SHAKE256)
static TEE_Result do_shake256_init(struct crypto_hash_ctx *ctx)
{
return do_shake_init(ctx, 256);
}
static const struct crypto_hash_ops shake256_ops = {
.init = do_shake256_init,
.update = do_sha3_update,
.final = do_shake_final,
.free_ctx = do_sha3_free_ctx,
.copy_state = do_sha3_copy_state,
};
TEE_Result crypto_shake256_alloc_ctx(struct crypto_hash_ctx **ctx)
{
return do_shake_alloc_ctx(ctx, &shake256_ops);
}
#endif
| 2.390625 | 2 |
2024-11-18T21:06:47.538646+00:00 | 2020-04-01T20:05:02 | 2bf427522da98e3ce394fbb45a520d808b6e687a | {
"blob_id": "2bf427522da98e3ce394fbb45a520d808b6e687a",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-01T20:15:48",
"content_id": "d3085291f395ccb7eee48080205e7ffe8ac69491",
"detected_licenses": [
"MIT"
],
"directory_id": "2056375c5c30e253c758193e124adf528c3a4593",
"extension": "h",
"filename": "cogtypes.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 252275880,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2019,
"license": "MIT",
"license_type": "permissive",
"path": "/libcog/Core/cogtypes.h",
"provenance": "stackv2-0128.json.gz:90354",
"repo_name": "dcerjan/old-cog-engine",
"revision_date": "2020-04-01T20:05:02",
"revision_id": "e6aa34989af7ae359f2550f430dba567a0a1c313",
"snapshot_id": "451510cb9e6835291d83dfb4b02389630063e2e1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dcerjan/old-cog-engine/e6aa34989af7ae359f2550f430dba567a0a1c313/libcog/Core/cogtypes.h",
"visit_date": "2021-05-20T11:28:31.449493"
} | stackv2 | #ifndef _COG_TYPES_H_
#define _COG_TYPES_H_
#include <stdio.h>
#include <stdint.h>
#include "cogarray.h"
#include "coglist.h"
#include "coghash.h"
#include "cogmap.h"
//#ifndef __APPLE__
typedef enum Bool {
True = 1,
False = 0,
Yes = 1,
No = 0
} Bool;
//#endif
// some standard types as CogArrays
CogDefineArray(char);
CogDefineArray(short);
CogDefineArray(int);
CogDefineArray(long);
CogDefineArray(float);
CogDefineArray(double);
CogDefineList(char);
CogDefineList(short);
CogDefineList(int);
CogDefineList(long);
CogDefineList(float);
CogDefineList(double);
CogDefineHash(char);
CogDefineHash(short);
CogDefineHash(int);
CogDefineHash(long);
CogDefineHash(float);
CogDefineHash(double);
#define CogInherit(C) C super
/* Basic value types */
//typedef short short;
typedef unsigned short ushort;
//typedef int int;
typedef unsigned int uint;
typedef int32_t int32;
typedef uint32_t uint32;
typedef int64_t int64;
typedef uint64_t uint64;
//typedef char byte;
typedef unsigned char ubyte;
//typedef long long;
typedef unsigned long ulong;
//typedef float float;
//typedef double double;
/* builtin types inspection */
#define shortInspect(var) printf("%hd", var)
#define ushortInspect(var) printf("%hu", var)
#define intInspect(var) printf("%d", var)
#define uintInspect(var) printf("%u", var);
#define int32Inspect(var) printf("%d", var);
#define uint32Inspect(var) printf("%u", var);
#define int64Inspect(var) printf("%ld", var);
#define uint64Inspect(var) printf("%lu", var);
#define byteInspect(var) printf("%d", var);
#define charInspect(var) printf("%c", var);
#define ubyteInspect(var) printf("%hd", var;
#define longInspect(var) printf("%ld", var);
#define ulongInspect(var) printf("%lu", var);
#define floatInspect(var) printf("%f", var);
#define doubleInspect(var) printf("%g", var);
#endif | 2.421875 | 2 |
2024-11-18T21:06:48.185750+00:00 | 2012-06-06T07:01:48 | 0aac467eb3fd690a50a0f38c533c91ce7b2bd4ea | {
"blob_id": "0aac467eb3fd690a50a0f38c533c91ce7b2bd4ea",
"branch_name": "refs/heads/master",
"committer_date": "2012-06-06T07:01:48",
"content_id": "ec343130aa7c1e6217b3702684bd8c4570aa0bba",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7c1c3e28d9bbf96893f21ea61252b611b5165864",
"extension": "c",
"filename": "jninio.c",
"fork_events_count": 0,
"gha_created_at": "2020-06-23T01:21:12",
"gha_event_created_at": "2020-06-23T01:21:12",
"gha_language": null,
"gha_license_id": null,
"github_id": 274278683,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1742,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ch02/JniNio/jni/jninio.c",
"provenance": "stackv2-0128.json.gz:90615",
"repo_name": "sterling0x1/AndroidNDKbook",
"revision_date": "2012-06-06T07:01:48",
"revision_id": "fbfe74b9d5b88cd97457ccf44d9748b0ac43f61d",
"snapshot_id": "3c17a81fdc256b2f562135a047aeb47903fdf06e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/sterling0x1/AndroidNDKbook/fbfe74b9d5b88cd97457ccf44d9748b0ac43f61d/ch02/JniNio/jni/jninio.c",
"visit_date": "2021-05-27T08:42:14.915452"
} | stackv2 | #include <stdio.h>
#include <android/log.h>
#include "jninio.h"
#define EXPORT __attribute__((visibility("default")))
#define LOG_TAG ("jninio")
#define LOGD(... ) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
#define LOGE(... ) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
typedef struct _DataInfo {
int a;
short b;
char c;
} DataInfo;
jint
setByteBuffer( JNIEnv* env, jobject thiz, jobject buf)
{
DataInfo *dataInfo;
dataInfo = (*env)->GetDirectBufferAddress(env, buf);
LOGD("dataInfo->a=%d\n",dataInfo->a);
LOGD("dataInfo->b=%d\n",dataInfo->b);
LOGD("dataInfo->c=%d\n",dataInfo->c);
dataInfo->a += 10;
dataInfo->b += 10;
dataInfo->c += 10;
return 0;
}
int jniRegisterNativeMethods(JNIEnv* env, const char* className,
const JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
LOGD("Registering %s natives\n", className);
clazz = (*env)->FindClass(env, className);
if (clazz == NULL) {
LOGD("Native registration unable to find class '%s'\n", className);
return -1;
}
if ((*env)->RegisterNatives(env, clazz, gMethods, numMethods) < 0) {
LOGD("RegisterNatives failed for '%s'\n", className);
return -1;
}
return 0;
}
static JNINativeMethod sMethods[] = {
/* name, signature, funcPtr */
{"setByteBuffer", "(Ljava/nio/Buffer;)I", (void*)setByteBuffer},
};
EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -1;
if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_6) != JNI_OK) {
return result;
}
jniRegisterNativeMethods(env, "com/example/jninio/MainActivity", sMethods, NELEM(sMethods));
return JNI_VERSION_1_6;
}
| 2.296875 | 2 |
2024-11-18T21:06:48.928692+00:00 | 1994-06-29T21:19:38 | cef49ddc43eb70f76ab082167d5f94cbda90c540 | {
"blob_id": "cef49ddc43eb70f76ab082167d5f94cbda90c540",
"branch_name": "refs/heads/master",
"committer_date": "1994-06-29T21:19:38",
"content_id": "5b09ed675409ea55861c12ed8d823703f2a7f637",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "486b2ddfd48234374ffe3bff9e63d2aaf84fba0a",
"extension": "c",
"filename": "netread.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": 1095,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/kerberosIV/krb/netread.c",
"provenance": "stackv2-0128.json.gz:90745",
"repo_name": "salewski/freebsd-1.x-src",
"revision_date": "1994-06-29T21:19:38",
"revision_id": "d015541579467c971b38fbab5027b60fb6db5ec9",
"snapshot_id": "bc6fa3babb05b31d84a3d60c2ef51e297acbfb4c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/salewski/freebsd-1.x-src/d015541579467c971b38fbab5027b60fb6db5ec9/kerberosIV/krb/netread.c",
"visit_date": "2021-05-18T01:52:10.395572"
} | stackv2 | /*
* $Source: /a/cvs/386BSD/src/kerberosIV/krb/netread.c,v $
* $Author: wollman $
*
* Copyright 1987, 1988 by the Massachusetts Institute of Technology.
*
* For copying and distribution information, please see the file
* <mit-copyright.h>.
*/
#ifndef lint
static char rcsid_netread_c[] =
"$Header: /a/cvs/386BSD/src/kerberosIV/krb/netread.c,v 1.1 1994/02/25 01:14:23 wollman Exp $";
#endif lint
#include <mit-copyright.h>
/*
* krb_net_read() reads from the file descriptor "fd" to the buffer
* "buf", until either 1) "len" bytes have been read or 2) cannot
* read anymore from "fd". It returns the number of bytes read
* or a read() error. (The calling interface is identical to
* read(2).)
*
* XXX must not use non-blocking I/O
*/
int
krb_net_read(fd, buf, len)
int fd;
register char *buf;
register int len;
{
int cc, len2 = 0;
do {
cc = read(fd, buf, len);
if (cc < 0)
return(cc); /* errno is already set */
else if (cc == 0) {
return(len2);
} else {
buf += cc;
len2 += cc;
len -= cc;
}
} while (len > 0);
return(len2);
}
| 2.34375 | 2 |
2024-11-18T21:19:01.415204+00:00 | 2015-02-02T09:42:53 | 812adda2e4f45772768bd1a138965b4041817117 | {
"blob_id": "812adda2e4f45772768bd1a138965b4041817117",
"branch_name": "refs/heads/master",
"committer_date": "2015-02-02T09:42:53",
"content_id": "effc8125cfe7456091f1d1b73feafd91bba4341f",
"detected_licenses": [
"MIT"
],
"directory_id": "71e30ccae68f3ad369c671d2ca6bbdea22cf1c40",
"extension": "h",
"filename": "lexer.h",
"fork_events_count": 0,
"gha_created_at": "2015-01-17T22:24:52",
"gha_event_created_at": "2015-01-17T22:24:52",
"gha_language": null,
"gha_license_id": null,
"github_id": 29407835,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7977,
"license": "MIT",
"license_type": "permissive",
"path": "/includes/lexer.h",
"provenance": "stackv2-0128.json.gz:297017",
"repo_name": "haneefmubarak/ink",
"revision_date": "2015-02-02T09:42:53",
"revision_id": "34e8c8f8e0426a0894affef2b3ecf89c538e6053",
"snapshot_id": "d8a3706baa26cedb5865d02a8cae56f3149a9db2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/haneefmubarak/ink/34e8c8f8e0426a0894affef2b3ecf89c538e6053/includes/lexer.h",
"visit_date": "2021-01-17T21:15:17.911489"
} | stackv2 | #ifndef LEXER_H
#define LEXER_H
/**
* This is C code Linguist, come on...
*/
#include "util.h"
#include "vector.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ASCII_CHARACTER_THRESHOLD 128
/** types of token */
typedef enum {
END_OF_FILE, IDENTIFIER, NUMBER,
OPERATOR, SEPARATOR, ERRORNEOUS,
STRING, CHARACTER, UNKNOWN, SPECIAL_CHAR
} token_type;
/**
* Token properties:
* type - the token type
* content - the token content
* line_number - the line number of the token
* char_number - the number of the char of the token
*/
typedef struct {
int type;
char* content;
int line_number;
int char_number;
} token;
/** Lexer stuff */
typedef struct {
char* input; // input to lex
int pos; // position in the input
int current_char; // current character
int line_number; // current line number
size_t input_size; // sizeof lexer input
int char_number; // current character at line
int start_pos; // keeps track of positions without comments
bool running; // if lexer is running
vector *token_stream; // where the tokens are stored
} lexer;
/**
* Create an empty token
*
* @return allocate memory for token
*/
token *create_token(lexer *lexer);
/**
* Get the name of the given token
* as a string
*
* @param token token to find name of
* @return the name of the given token
*/
const char* get_token_name(token *token);
/**
* Deallocates memory for token
*
* @param token token to free
*/
void destroy_token(token *token);
/**
* Retrieves the line that a token is on
* @param lexer the lexer instance
* @param tok the token to get the context of
* @param colour_error_token whether or not to colour the errored token
* @return the context as a string
*/
char* get_token_context(vector *stream, token *tok, bool colour_error_token);
/**
* Retrieves the line that a token is on
* @param lexer the lexer instance
* @param line_num the number to get context of
* @return the context as a string
*/
char* get_line_number_context(vector *stream, int line_num);
/**
* Create an instance of the Lexer
*
* @param input the input to lex
* @return instance of Lexer
*/
lexer *create_lexer(char* input);
/**
* Simple substring, basically extracts the token from
* the lexers input from [start .. start + length]
*
* @param lexer instance of lexer
* @param start start of the input
* @param length of the input
* @return string cut from buffer
*/
char* extract_token(lexer *lexer, int start, int length);
/**
* Advance to the next character, consuming the
* current one.
*
* @param lexer instance of the lexer
*/
void consume_character(lexer *lexer);
/**
* Skips layout characters, such as spaces,
* and comments, which are denoted with the
* pound (#).
*
* @param lexer the lexer instance
*/
void skip_layout_and_comments(lexer *lexer);
/**
* Checks if current character is the given character
* otherwise throws an error
*
* @param lexer the lexer instance
*/
void expect_character(lexer *lexer, char c);
/**
* Recognize an identifier
*
* @param lexer the lexer instance
*/
void recognize_identifier_token(lexer *lexer);
/**
* Recognize an Integer
*
* @param lexer the lexer instance
*/
void recognize_number_token(lexer *lexer);
/**
* Recognize a String
*
* @param lexer the lexer instance
*/
void recognize_string_token(lexer *lexer);
/**
* Recognize a Character
*
* @param lexer the lexer instance
*/
void recognize_character_token(lexer *lexer);
/**
* Recognizes the given operator and pushes it
* @param lexer the lexer for access to the token stream
*/
void recognize_operator_token(lexer *lexer);
/**
* Recognizes the end of line token
* @param lexer the lexer for access to the token stream
*/
void recognize_end_of_line_token(lexer *lexer);
/**
* Recognizes a separator token and pushes it
* to the tree
* @param lexer the lexer for access to the token stream
*/
void recognize_separator_token(lexer *lexer);
/**
* Recognizes an errored token and pushes it to the
* tree
* @param lexer the lexer for access to the token stream
*/
void recognize_errorneous_token(lexer *lexer);
/**
* Pushes a token to the token tree, also captures the
* token content so you don't have to.
*
* @param lexer the lexer for access to the token tree
* @param type the type of token
*/
void push_token(lexer *lexer, int type);
/**
* Pushes a token with content to the token tree
* @param lexer the lexer for access to the token tree
* @param type the type of token to push
* @param content the content to push
*/
void push_token_c(lexer *lexer, int type, char *content);
/**
* Peek ahead in the character stream by
* the given amount
*
* @lexer instance of lexer
* @ahead amount to peek by
* @return the char we peeked at
*/
char peek_ahead(lexer *lexer, int ahead);
/**
* Process the next token in the token stream
*
* @param lexer the lexer instance
*/
void get_next_token(lexer *lexer);
/**
* Destroys the given lexer instance,
* freeing any memory
*
* @param lexer the lexer instance to destroy
*/
void destroy_lexer(lexer *lexer);
/**
* @return if the character given is the end of input
* @param ch the character to check
*/
static inline bool is_end_of_input(char ch) {
return ch == '\0';
}
/**
* @return if the character given is a layout character
* @param ch the character to check
*/
static inline bool is_layout(char ch) {
return !is_end_of_input(ch) && (ch) <= ' ';
}
/**
* @return if the character given is a comment closer
* @param ch the character to check
*/
static inline bool is_comment_closer(char ch) {
return ch == '\n';
}
/**
* @return if the character given is an uppercase letter
* @param ch the character to check
*/
static inline bool is_upper_letter(char ch) {
return 'A' <= ch && ch <= 'Z';
}
/**
* @return if the character given is a lower case letter
* @param ch the character to check
*/
static inline bool is_lower_letter(char ch) {
return 'a' <= ch && ch <= 'z';
}
/**
* @return if the character given is a letter a-z, A-Z
* @param ch the character to check
*/
static inline bool is_letter(char ch) {
return is_upper_letter(ch) || is_lower_letter(ch);
}
/**
* @return if the character given is a digit 0-9
* @param ch the character to check
*/
static inline bool is_digit(char ch) {
return '0' <= ch && ch <= '9';
}
/**
* @return if the character given is a letter or digit a-z, A-Z, 0-9
* @param ch the character to check
*/
static inline bool is_letter_or_digit(char ch) {
return is_letter(ch) || is_digit(ch);
}
/**
* @return if the character given is an underscore
* @param ch the character to check
*/
static inline bool is_underscore(char ch) {
return ch == '_';
}
/**
* @return if the character given is a quote, denoting a string
* @param ch the character to check
*/
static inline bool is_string(char ch) {
return ch == '"';
}
/**
* @return if the character given is a single quote, denoting a character
* @param ch the character to check
*/
static inline bool is_character(char ch) {
return ch == '\'';
}
/**
* @return if the character given is an operator
* @param ch the character to check
*/
static inline bool is_operator(char ch) {
return (strchr("+-*/=><!~?:|&%^\"'", ch) != 0);
}
/**
* @return if the character given is a separator
* @param ch the character to check
*/
static inline bool is_separator(char ch) {
return (strchr(" ;,.`@(){}[] ", ch) != 0);
}
/**
* @return if the character is a special character like the British symbol or alike
* @param ch character to check
*/
static inline bool is_special_char(char ch) {
return (int) ch >= ASCII_CHARACTER_THRESHOLD;
}
/**
* @return if the character is end of line to track line number
* @param ch character to check
*/
static inline bool is_end_of_line(char ch) {
return ch == '\n';
}
#endif // LEXER_H
| 2.640625 | 3 |
2024-11-18T21:19:01.489388+00:00 | 2021-10-25T19:22:50 | 49686cca3247b886f5d928af9de9589a6f4d7977 | {
"blob_id": "49686cca3247b886f5d928af9de9589a6f4d7977",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-25T19:22:50",
"content_id": "4a5f002326c7bb7c2e6ae54f86cf79e81018393d",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "18df702758fa034d30f7e3573e9a986a93b5ba88",
"extension": "h",
"filename": "cthread.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": 2865,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/app/smart_display_service/net/cthread.h",
"provenance": "stackv2-0128.json.gz:297145",
"repo_name": "qiaoweibiao/merged",
"revision_date": "2021-10-25T19:22:50",
"revision_id": "3b016b1330c2a148753d00c542aaa39e7f86e726",
"snapshot_id": "e8eedb87c73f12436fb26b8058ea295fc3e703c0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/qiaoweibiao/merged/3b016b1330c2a148753d00c542aaa39e7f86e726/app/smart_display_service/net/cthread.h",
"visit_date": "2023-08-25T01:53:59.791416"
} | stackv2 | #ifndef _CG_UTIL_CTHREAD_H_
#define _CG_UTIL_CTHREAD_H_
#include <net/typedef.h>
#include <net/ccond.h>
#include <pthread.h>
#include <signal.h>
#ifdef __cplusplus
extern "C" {
#endif
/****************************************
* Define
****************************************/
#define CG_THREAD_MIN_SLEEP 1000
/* ADD END Fabrice Fontaine Orange 24/04/2007 */
/****************************************
* Data Type
****************************************/
/**
* \brief The generic wrapper struct for CyberLinkC's threads.
*
* This wrapper has been created to enable 100% code
* compatibility between different platforms (Linux, Win32 etc..)
*/
typedef struct _CgThread {
BOOL headFlag;
struct _CgThread *prev;
struct _CgThread *next;
/** Indicates whether this thread is ready to run */
BOOL runnableFlag;
#if defined DEBUG
char friendlyName[32];
#endif
/** The POSIX thread handle */
pthread_t pThread;
int priority;
/** Thread's worker function */
void (*action)(struct _CgThread *);
/** Arbitrary data pointer */
void *userData;
} CgThread, CgThreadList;
/**
* Prototype for the threads' worker functions
*/
typedef void (*CG_THREAD_FUNC)(CgThread *);
/****************************************
* Function
****************************************/
/**
* Create a new thread
*/
CgThread *cg_thread_new();
/**
* Get a self reference to thread.
*/
CgThread *cg_thread_self();
/**
* Stop and destroy a thread.
*
* \param thread Thread to destroy
*/
BOOL cg_thread_delete(CgThread *thread);
/**
* Start a thread (must be created first with ch_thread_new())
*
* \param thread Thread to start
*/
BOOL cg_thread_start(CgThread *thread);
/**
* Stop a running thread.
*
* \param thread Thread to stop
*/
BOOL cg_thread_stop(CgThread *thread);
/**
* Stop the running thread and signal the given CGCond.
*/
BOOL cg_thread_stop_with_cond(CgThread *thread, CgCond *cond);
/**
* Restart a thread. Essentially calls cg_thread_stop() and cg_thread_start()
*
* \param thread Thread to restart
*/
BOOL cg_thread_restart(CgThread *thread);
/**
* Check if a thread has been started
*
* \param thread Thread to check
*/
BOOL cg_thread_isrunnable(CgThread *thread);
/**
* Set the thread's worker function.
*
* \param thread Thread struct
* \param actionFunc Function pointer to set as the worker function
*/
void cg_thread_setaction(CgThread *thread, CG_THREAD_FUNC actionFunc);
/**
* Set the user data pointer
*
* \param thread Thread struct
* \param data Pointer to user data
*/
void cg_thread_setuserdata(CgThread *thread, void *data);
int cg_thread_setname(CgThread *thread,const char *name);
/**
* Get the user data pointer
*
* \param thread Thread from which to get the pointer
*/
void *cg_thread_getuserdata(CgThread *thread);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
| 2.375 | 2 |
2024-11-18T21:19:02.241119+00:00 | 2021-05-17T05:32:15 | 4242e7a7cac9d1d1d8e3bc3752425cc36b900959 | {
"blob_id": "4242e7a7cac9d1d1d8e3bc3752425cc36b900959",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-17T05:32:15",
"content_id": "318c040302394fbf4b58788e299f75110208083f",
"detected_licenses": [
"MIT"
],
"directory_id": "8c778876499e99463d7daa4db286341a3113c317",
"extension": "c",
"filename": "huffman.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": 2751,
"license": "MIT",
"license_type": "permissive",
"path": "/Compression/Huffman/Static/huffman.c",
"provenance": "stackv2-0128.json.gz:297661",
"repo_name": "vstflugel/PiedPiper",
"revision_date": "2021-05-17T05:32:15",
"revision_id": "10b97ccc40245186f89e32729888d979cf5277aa",
"snapshot_id": "7ea630a279d501a432cb7f2a46ed8f3fecdefafd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vstflugel/PiedPiper/10b97ccc40245186f89e32729888d979cf5277aa/Compression/Huffman/Static/huffman.c",
"visit_date": "2023-05-03T11:33:34.915301"
} | stackv2 | #include "huffman.h"
long long int charFrequencies[256];
Code* codes[270];
Node* newNode(char _c, long long int _frequency, bool _isLeafNode)
{
Node* node = (Node*) malloc(sizeof(Node));
node -> c = _c;
node -> frequency = _frequency;
node -> isLeafNode = _isLeafNode;
node -> leftChild = NULL;
node -> rightChild = NULL;
return node;
}
bool isSmallerNode(Node* node1, Node* node2)
{
if ((node1 -> frequency) < (node2 -> frequency))
{
return true;
}
else
{
return false;
}
}
Code* newCode(char _c, char* _code)
{
Code* code = (Code*) malloc(sizeof(Code));
code -> c = _c;
code -> code = _code;
code->code = (char*)malloc(1 + strlen(_code));
sprintf(code->code, "%s", _code);
return code;
}
void formCodes(Node* node, char* code)
{
#include<stdio.h>
if(node == NULL)
return;
if(node -> isLeafNode == true)
{
Code* codeNode = newCode(node->c, code);
codes[((int)(codeNode->c) + 256) % 256] = codeNode;
return;
}
else
{
char zero[] = "0", one[] = "1";
char* rightChildCode = (char*)malloc(strlen(code) + 2);
char* leftChildCode = (char*)malloc(strlen(code) + 2);
sprintf(rightChildCode, "%s1", code);
sprintf(leftChildCode, "%s0", code);
formCodes(node->leftChild, leftChildCode);
free(leftChildCode);
formCodes(node->rightChild, rightChildCode);
free(rightChildCode);
}
return ;
}
codeSearchTreeNode* newCodeTreeNode(char chararcter, bool isValid)
{
codeSearchTreeNode* node = (codeSearchTreeNode*)malloc(sizeof(codeSearchTreeNode));
node->c = chararcter;
node->aValidCharacter = isValid;
node->leftChild = NULL;
node->rightChild = NULL;
return node;
}
void writeBitToOutputFile(int bit, FILE* file)
{
static int dataToBeWritten;
static int bitsInData;
dataToBeWritten = dataToBeWritten << 1;
bitsInData++;
if(bit == 1)
{
dataToBeWritten = dataToBeWritten | 1;
}
if(bitsInData == 8)
{
char data = (char)dataToBeWritten;
fwrite(&data, sizeof(char), 1, file);
dataToBeWritten = 0;
bitsInData = 0;
}
}
void writeCode(Code* sourceCode, FILE* file)
{
char codeLength = (char)strlen(sourceCode->code);
char character = sourceCode->c;
char *codeString = sourceCode->code;
fwrite(&character, sizeof(char), 1, file);
fwrite(&codeLength, sizeof(char), 1, file);
fwrite(codeString, sizeof(char), charToInt(codeLength), file);
}
void readCode(Code* destinationCode, FILE* file)
{
char character, codeLength;
char* codeString = NULL;
fread(&character, sizeof(char), 1, file);
fread(&codeLength, sizeof(char), 1, file);
codeString = (char*)malloc((1+codeLength)*sizeof(char));
fread(codeString, sizeof(char), charToInt(codeLength), file);
codeString[charToInt(codeLength)] = '\0';
destinationCode->c = character;
destinationCode->code = codeString;
} | 3.203125 | 3 |
2024-11-18T21:19:02.291267+00:00 | 2018-10-27T03:36:57 | 62a4912c872a67e1e4884a61c0af2a2a79982de1 | {
"blob_id": "62a4912c872a67e1e4884a61c0af2a2a79982de1",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-27T03:36:57",
"content_id": "21dc6a352fa5176c12edaa58e8f6dee3b2c16a97",
"detected_licenses": [
"MIT"
],
"directory_id": "25059cc98e17d6e9fab326349e349491daf1d5da",
"extension": "c",
"filename": "graph.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 154791551,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4045,
"license": "MIT",
"license_type": "permissive",
"path": "/graph.c",
"provenance": "stackv2-0128.json.gz:297792",
"repo_name": "kingJHome/AOEnet",
"revision_date": "2018-10-27T03:36:57",
"revision_id": "301318aa4e642684932ba8d699beddecc4b5ab63",
"snapshot_id": "025cc82c963e4f688510f6ee4904da8367a99d0b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/kingJHome/AOEnet/301318aa4e642684932ba8d699beddecc4b5ab63/graph.c",
"visit_date": "2020-04-02T21:13:29.213562"
} | stackv2 | #include "graph.h"
//获取字符串的字母
char** getContentLetters(char *content,int *nums){
char **letters = NULL;
char *temp = NULL;
int st = 0;
size_t clen = strlen(content);
for(size_t i = 0; i < clen; ++i){
if( content[i]==' ' ){
*nums += 1;
}
}
*nums += 1;
letters = (char**)malloc((*nums) * sizeof(char*));
if( letters ){
while( (temp = strsep(&content," \n")) != NULL ){
if( strlen(temp) ){
letters[st++] = temp;
}
}
}else{
*nums = 0;
}
return letters;
}
//获取key在vertices中的位置
int getVertexPos(ALGraph *g,char *key){
int pos = 0;
for(int i = 0; i < g->length; ++i){
if( strcmp(g->vertices[i].data, key) == 0 ){
pos = i;
break;
}
}
return pos;
}
//插入弧
void addArcToVertex(Vertex *vers,int st,int et,int weight){
Arc *temp = vers[st].firstarc,
*addNote = (Arc*)malloc(sizeof(Arc));
if( addNote ){
addNote->adjvex = et;
addNote->cost = weight;
addNote->nextarc = NULL;
//increace the out degree of the arc
vers[st].dOut += 1;
//增加弧头的入度
vers[et].dIn += 1;
if( !temp ){
vers[st].firstarc = addNote;
}else{
for( ; temp->nextarc; temp = temp->nextarc);
temp->nextarc = addNote;
}
}
}
//构建有向图
void CreateALGraph(ALGraph *g,char *contents){
int clen = 0;
char **letters = getContentLetters(contents, &clen);
if( letters && clen ){
g->vertices = (Vertex*)malloc(clen * sizeof(Vertex));
if( g->vertices ){
g->length = clen;
for(int i = 0; i < clen; ++i){
g->vertices[i].data = strdup(letters[i]);
g->vertices[i].dIn = g->vertices[i].dOut = 0;
g->vertices[i].firstarc = NULL;
}
}
}
}
//添加弧
void AddArcs(ALGraph *g,char *head,char *tail,int weight){
int headPos = getVertexPos(g, head),
tailPos = getVertexPos(g, tail);
addArcToVertex(g->vertices, headPos, tailPos, weight);
}
//topological sort
int TopologicalOrder(ALGraph g,Stack *t,Stack *s,int *ve){
int count = 0,j,k,
*inDegee = (int*)malloc(g.length * sizeof(int));
if( inDegee ){
for(int i = 0; i < g.length; ++i){
inDegee[i] = g.vertices[i].dIn;
if( !inDegee[i] ){
Push(t, i);
}
}
while( !StackEmpty(*t) ){
Pop(t, &j);
Push(s, j);
count++;
for(Arc *temp = g.vertices[j].firstarc; temp; temp = temp->nextarc){
k = temp->adjvex;
--inDegee[k];
if( !inDegee[k] ){
Push(t, k);
}
if( ve[j] + temp->cost > ve[k] ){
ve[k] = ve[j] + temp->cost;
}
}
}
}
if( count < g.length ){
return 0;
}else{
return 1;
}
}
void OppTopologicalOrder(ALGraph g,Stack *t,int *ve,int *vl){
int j,k;
for(int i = 0; i < g.length; ++i){
vl[i] = ve[i];
}
while( !StackEmpty(*t) ){
Pop(t, &j);
if( g.vertices[j].dIn ){
for(Arc *temp = g.vertices[j].firstarc; temp; temp = temp->nextarc){
k = temp->adjvex;
if(vl[k] - temp->cost > vl[j]){
vl[j] = vl[k] - temp->cost;
}
}
}
}
}
//find key path
int CriticalPath(ALGraph g){
int ve[g.length],vl[g.length];
Stack st = {NULL,0,0},tt = {NULL,0,0};
InitStack(&st, g.length);
InitStack(&tt, g.length);
for(int i = 0; i < g.length; ++i){
ve[i] = vl[i] = 0;
}
if( !TopologicalOrder(g,&st,&tt,ve) ){
return 0;
}
//calulation vl array
OppTopologicalOrder(g,&tt,ve,vl);
//output critical vertex
printf("critical path is:");
for(int i = 0; i < g.length; ++i){
if(ve[i] == vl[i]){
printf("%s ", g.vertices[i].data);
}
}
printf("\n");
return 1;
}
//visit graph
void outPutALGraph(ALGraph g){
for(int i = 0; i < g.length; ++i){
printf("%s(%d)", g.vertices[i].data, g.vertices[i].dIn);
Arc *temp = g.vertices[i].firstarc;
for( ; temp; temp = temp->nextarc){
printf("-->%d(%d)", temp->adjvex, temp->cost);
}
printf("\n");
}
}
//清除有向图
void clearALGraph(ALGraph *g){
for(int i = 0; i < g->length; ++i){
Arc *temp = g->vertices[i].firstarc;
while( temp ){
g->vertices[i].firstarc = temp->nextarc;
free(temp);
temp = g->vertices[i].firstarc;
}
}
free(g->vertices);
g->vertices = NULL;
g->length = 0;
} | 3 | 3 |
2024-11-18T21:19:02.405332+00:00 | 2020-07-13T10:25:31 | 1318044a8b0d42df8d31cd4a52472851cb33a51e | {
"blob_id": "1318044a8b0d42df8d31cd4a52472851cb33a51e",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-13T10:25:31",
"content_id": "5912020d9380301c95efd1b6fe8cd2ac80ee77e9",
"detected_licenses": [
"MIT"
],
"directory_id": "5ebbf44e2b6cf0e223184713f76d003b728f215f",
"extension": "c",
"filename": "game.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": 37516,
"license": "MIT",
"license_type": "permissive",
"path": "/game.c",
"provenance": "stackv2-0128.json.gz:297922",
"repo_name": "rafaeldschultz/Qwirkle",
"revision_date": "2020-07-13T10:25:31",
"revision_id": "69271e5c45bb4b2fcb7dc78e24c78b14bae34ebe",
"snapshot_id": "07b74dd95bb2ec917474f01d7b0a04031b06dfab",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rafaeldschultz/Qwirkle/69271e5c45bb4b2fcb7dc78e24c78b14bae34ebe/game.c",
"visit_date": "2022-11-15T10:30:02.041809"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "headers/infoBlock.h"
#include "headers/infoGame.h"
#include "headers/infoPlayer.h"
#include "headers/infoMove.h"
#include "headers/colors.h"
#include "headers/output.h"
#include "headers/buffer.h"
#include "headers/blocks.h"
#include "headers/board.h"
#include "headers/players.h"
#include "headers/pontuacao.h"
#include "headers/game.h"
/******************************************
* INICIALIZA OU DELETA ELEMENTOS DO JOGO *
******************************************/
/*
* Inicializa o Jogo
*/
void createGame(Game *g, Player **p){
createBoard(g);
createBag(g);
initializePlayers(g, p);
}
/*
* Deleta os Elementos do Jogo
*/
void deleteGame(Game *g, Player **p){
deleteBlocksControl(g);
deletePlayers(*g, *p);
eraseBoard(g);
}
/***********
* RODADAS *
***********/
/*
* Inicia o jogo e mantem a alternancia de jogadores durante as rodadas
*/
void gameRounds(Game *g, Player *p){
do{
cheatModeMenu(); //Verifica se o cheatMode deve ser ativado
char isCheatMode = fgetc(stdin);
cleanBufferEnter(); //limpa o buffer de entrada ate um enter
if(isCheatMode == 's' || isCheatMode == 'n') { //Se a resposta for dada minuscula (apenas as opcoes aceitas), transforma em maiuscula
isCheatMode -= 32;
}
if(isCheatMode == 'S' || isCheatMode == 'N'){ //Verifica se a opcao eh valida
short result = 0; //armazena se o resultado do jogo ja foi definido
int i = 0;
while(!result){ //Executa ate que o resultado do jogo seja definido
playerTurn(g, p, i, isCheatMode); //Executa a vez de um jogador
i = (++i) % (g->n_players); //Soma um ao contador de usuario e realiza o modulo com o numero de jogadores
if(g->bag.blocks_number == 0){ //se a quantidade de pecas na sacola for 0
result = verifyEndGame(g, p); //verifica se o jogo finalizou
}
}
break; //Quando finalizar o jogo, quebra o laco de repeticao
} else {
invalidOption(0); //indica opcao invalida
}
} while(1);
}
/*
* Realiza a vez de um jogador
*/
void playerTurn(Game *g, Player *players, short player_number, char isCheatMode){
short p_option = 0; //Define o tipo de jogada selecionada (1:'jogar'; 2:'trocar')
short line_turn = 0; //Indica o sentido da jogada (0: indefinido; 1: linha; 2: coluna)
int score = 0; //Armazena a pontuacao da jogada
Move firstMove; //Armazena as coordenadas do primeiro movimento feito pelo jogador na rodada
firstMove.col = -1;
firstMove.lin = -1;
do {
showBoard(g);
showPlayersTiles(*g, players);
//Imprime titulo
printf("───────────────────────────────────────────────────\n");
green(1);
printf("\tJOGADA DE @%s\n\n", players[player_number].name); //Indica o Jogador da vez
//Mostra a pontuacao do jogar
showScore(players[player_number]);
//Mostra os blocos do jogador
showOnePlayerTiles(players[player_number]); //Mostra os blocos do jogador da vez
//Mostra as opcoes
playerOptions(); //Mostra as opcoes para o jogador
do{
blue(1);
printf("Selecione: ");
reset();
//Recebe o comando
char command[40];
fgets(command, 40, stdin);
char *enter = strchr(command, '\n'); //Encontra o enter adicionado ao final pelo fgets
if(enter != NULL) *enter = '\0'; //Remove o enter se ele existir
//Encontra os comandos
char *cmd = strtok(command, " ");
char *peca = strtok(NULL, " ");
char *lin = strtok(NULL, " ");
char *col = strtok(NULL, " ");
if(cmd != NULL && (!strcmp(cmd, "jogar") || !strcmp(cmd, "j"))){ //Verifica se a opcao eh jogar
Block b;
if(peca != NULL && strlen(peca) == 2){ //Verifica se o bloco inserido eh valido
if(peca[0] >= 'a' && peca[0] <= 'f'){ //Verifica se a letra eh minuscula e converte para maiuscula
peca[0] -= 32;
}
if(peca[0] >= 'A' && peca[0] <= 'F' && peca[1] >= '1' && peca[1] <= '6'){ //verifica se o bloco apresenta numero/letra validos
b.letter = peca[0]; //Cria uma struct bloco com as informacoes passadas
b.number = (short) atoi(&peca[1]);
b.relation.vertical = 0;
b.relation.horizontal = 0;
Move m;
if((lin != NULL && isdigit(lin[0])) && ((col != NULL && isdigit(col[0])))){ //verifica se linha e coluna inseridos sao validos
m.lin = (short) atoi(lin);
m.col = (short) atoi(col);
if((m.col >= 0) && (m.lin >= 0) && (m.col <= g->max_col) && (m.lin <= g->max_lin)){ //Verifica se linha e coluna estao no intervalo permitido pelo tabuleiro
if(p_option == 0 || p_option == 1){ //Verifica se outro tipo de jogada nao foi executada antes
short m_status = 0; //Representa se a jogada foi realizada com sucesso
if(isCheatMode == 'S'){ //Verifica se o cheatMode esta ativado
m_status = useBlockCheatMode(g, &players[player_number], b, m, &firstMove, &line_turn); //verifica a jogada eh valida e faz o movimento se sim
} else {
m_status = useBlock(g, &players[player_number], b, m, &firstMove, &line_turn);
}
if(m_status){ //Verifica se a jogada foi executada com sucesso
p_option = 1;
if(line_turn != 0){
int score1 = 0;
if(line_turn == 1){
if(g->board[m.lin][m.col].relation.vertical != 0){ //Se existir ramificação da linha da jogada, verifica pontuacao
score1 = defineScoreUp(g, m) + defineScoreDown(g, m) - 1;
if(score1 == 6) score1 += 6; //Fez um Qwirkle
}
} else if(line_turn == 2) { //Se existir ramificação da linha da jogada, verifica pontuacao
if(g->board[m.lin][m.col].relation.horizontal != 0){
score1 = defineScoreLeft(g, m) + defineScoreRight(g, m) - 1;
if(score1 == 6) score1 += 6; //Fez um Qwirkle
}
}
score += score1;
}
break;
}
} else {
invalidOption(1);
}
} else {
invalidPosition();
}
} else {
invalidPosition();
}
} else {
invalidBlock(0);
}
} else {
invalidBlock(0);
}
}
else if(cmd != NULL && (!strcmp(cmd, "trocar") || !strcmp(cmd, "t"))){
Block b;
if(peca != NULL && strlen(peca) == 2){ //Verifica se o bloco inserido eh valido
if(peca[0] >= 'a' && peca[0] <= 'f'){ //Verifica se a letra eh minuscula e converte para maiuscula
peca[0] -= 32;
}
if(peca[0] >= 'A' && peca[0] <= 'F' && peca[1] >= '1' && peca[1] <= '6'){ //verifica se o bloco apresenta numero/letra validos
b.letter = peca[0]; //Cria uma struct bloco com as informacoes passadas
b.number = (short) atoi(&peca[1]);
b.relation.vertical = 0;
b.relation.horizontal = 0;
if(p_option == 0 || p_option == 2){ //verifica se o usuario ja fez uma jogada de outro tipo
short t_status = exchangeBlock(g, &players[player_number], b); //Troca a peca
if(t_status){ //Verifica se a peca foi trocada corretamente
p_option = 2;
break;
}
} else {
invalidOption(1);
}
} else {
invalidBlock(0);
}
} else {
invalidBlock(0);
}
} else if(cmd != NULL && (!strcmp(cmd, "passar") || !strcmp(cmd, "p"))) { //verifica se a opcao eh passar
if(g->bag.blocks_number > 0){ //verifica se existem pecas na sacola disponiveis
completeBlocksNumber(g, &players[player_number]); //se sim, completa com as pecas que faltam
}
if(firstMove.lin != -1 && firstMove.col != -1){
score += defineScoreFirstMove(g, firstMove); //Verifica pontuacao da peca inicial
//caso a peca inicial faca parte apenas de uma linha/coluna, subtrai um do valor do score (score eh calculado considerando que faz parte de uma linha e uma coluna)
if(!((g->board[firstMove.lin][firstMove.col].relation.horizontal != 0) && (g->board[firstMove.lin][firstMove.col].relation.vertical != 0))){
score--;
}
players[player_number].score += score; //soma o score da rodada ao do jogador
showScoreTurn(score, players[player_number]);
printf("───────────────────────────────────────────────────\n");
}
return;
} else {
invalidOption(0);
}
} while (1);
} while (1);
}
/********************
* OPCOES DE JOGADA *
********************/
/*
* Coloca uma peca no tabuleiro quando em cheatMode
*/
short useBlockCheatMode(Game *g, Player *p, Block b, Move m, Move *firstMove, short *lt){
short mov_status = verifyMoviment(g, b, m, firstMove, lt); //verifica a possibilidade de executar o movimento
//se possivel, ja executa
if(mov_status){ //Verifica se o movimento foi executado
removeBlockFromHand(p, b); //remove o bloco utilizado da mao do jogador
return 1;
}
return 0;
}
/*
* Coloca uma peca no tabuleiro quando em modo normal
*/
short useBlock(Game *g, Player *p, Block b, Move m, Move *firstMove, short *lt){
if(verifyPlayerHand(*p, b)){ //Verifica se o bloco existe na mao do jogador
short mov_suc = verifyMoviment(g, b, m, firstMove, lt); //verifica a possibilidade de executar o movimento
//se possivel, ja executa
if(mov_suc){ //Verifica se o movimento foi executado
removeBlockFromHand(p, b); //remove o bloco utilizado da mao do jogador
return 1;
}
} else {
invalidBlock(1);
}
return 0;
}
/*
* Troca um bloco do usuario
*/
short exchangeBlock(Game *g, Player *p, Block b){
if(g->bag.blocks_number > 0){ //Verifica se ainda ha pecas disponiveis no saco
if(verifyPlayerHand(*p, b)){ //verifica se o usuario possui a peca
changeBlock(g, p, b); //troca o bloco
return 1;
} else {
invalidBlock(1);
}
} else { //Senao houver mais pecas no saco, informa para o usuario
noMoreBlocksBag();
}
return 0;
}
/****************
* VERIFICACOES *
****************/
/*
* Verifica se um movimento eh possivel
* Armazena algumas verificacoes mais simples e trabalhosas
* Porta de entrada para outras funcoes de verificacao
*/
short verifyMoviment(Game *g, Block b, Move m, Move *firstMove, short *lt){
//0: indefinido; 1: letra; 2: numero
if(g->max_col == 0 && g->max_lin == 0){ //Primeira Rodada; Pode ser adicionado em qualquer local
firstMove->col = m.col; //altera as coordenadas de coluna do primeiro movimento
firstMove->lin = m.lin; //altera as coordenadas de linha do primeiro movimento
makeMoviment(g, b, m, firstMove);
return 1;
} else if(g->board[m.lin][m.col].letter != '\0'){ //Verifica se a posicao inserida para o movimento eh vazia
invalidMove();
return 0;
} else if(firstMove->lin != -1 && firstMove->col != -1){ //Verifica se as coordenadas do primeiro movimento foram setadas
if(*lt == 1 && m.lin != firstMove->lin){ //verifica se o criterio da rodada do usuario eh mesma LINHA e a linha inserida eh diferente da primeira jogada
invalidMove(); //imprime mensagem de erro
return 0;
} else if(*lt == 2 && m.col != firstMove->col){ //verifica se o criterio da rodada do usuario eh mesma COLUNA e a coluna inserida eh diferente da primeira jogada
invalidMove(); //imprime mensagem de erro
return 0;
} else if(*lt == 0 && !(firstMove->col == m.col || firstMove->lin == m.lin)){ //verifica se o criterio da rodada do usuario eh INDEFINIDO e a coluna/linha inserida eh diferente da primeira jogada
invalidMove(); //imprime mensagem de erro
return 0;
}
if(!verifySameLine(g, m, *firstMove)){ //verifica se a primeira peca e a peca da jogada atual estao em uma mesma linha
invalidMove(); //imprime mensagem de erro
return 0;
}
}
short isPossible_up = 0, isPossible_down = 0, isPossible_left = 0, isPossible_right = 0; //indicam a possibilidade de jogada em cada uma das direcoes
Block up, down, left, right; //indicam os blocos ao redor da posicao indica em m
short empty = 0; //indica quantos blocos ao redor estao vazios
if(m.lin > 0) { //Verifica se a linha indicada eh maior que 0
up = g->board[m.lin - 1][m.col]; //atribui a peca acima a up
if(up.letter == '\0'){ //verifica se ela eh vazia
isPossible_up = 1; //Se sim, indica que a ha possibilidade de adicao nas coordenadas m
empty++;
}
} else { //Se for igual a 0, automaticamente eh vazia (borda do tabuleiro)
isPossible_up = 1;
empty++;
}
if(m.lin < g->max_lin) { //Verifica se a linha indicada eh menor que o max do tabuleiro
down = g->board[m.lin + 1][m.col]; //atribui a peca abaixo a down
if(down.letter == '\0'){ //verifica se ela eh vazia
isPossible_down = 1; //Se sim, indica que a ha possibilidade de adicao nas coordenadas m
empty++;
}
} else {
isPossible_down = 1; //Se for igual ao max do tabuleiro, automaticamente eh vazia (borda do tabuleiro)
empty++;
}
if(m.col > 0) { //Verifica se a coluna indicada eh maior que 0
left = g->board[m.lin][m.col - 1]; //atribui a peca a esquerda a left
if(left.letter == '\0'){ //verifica se ela eh vazia
isPossible_left = 1; //Se sim, indica que a ha possibilidade de adicao nas coordenadas m
empty++;
}
} else { //Se for igual a 0, automaticamente eh vazia (borda do tabuleiro)
isPossible_left = 1;
empty++;
}
if(m.col < g->max_col) { //Verifica se a coluna indicada eh menor que o max do tabuleiro
right = g->board[m.lin][m.col + 1]; //atribui a peca a direita a right
if(right.letter == '\0'){ //verifica se ela eh vazia
isPossible_right = 1; //Se sim, indica que a ha possibilidade de adicao nas coordenadas m
empty++;
}
} else {
isPossible_right = 1; //Se for igual a 0, automaticamente eh vazia (borda do tabuleiro)
empty++;
}
short duplicatedVertical = 1, duplicatedHorizontal = 1;
if(isPossible_down == 0 && isPossible_up == 0){ //Verifica se eh possivel ocorrer a uniao de duas linhas
duplicatedVertical = verifyDuplicatesJoinedVertical(g, m); //Verifica se havera duplifcados na vertical caso a juncao ocorra
}
if(isPossible_left == 0 && isPossible_right == 0){ //Verifica se eh possivel ocorrer a uniao de duas linhas
duplicatedHorizontal = verifyDuplicatesJoinedHorizontal(g, m); //Verifica se havera duplifcados na horizontal caso a juncao ocorra
}
if(duplicatedVertical && duplicatedHorizontal){ //Verifica se nao existe a possibilidade de duplicadas caso ocorra uniao de linhas/colunas
if(empty < 4){ //Verifica se a peca nao esta isolada
if(isPossible_up == 0){ //Nao vazio e existente
if(up.relation.vertical == 0){ //verifica se a relacao da peca super na vertical ja foi definida
if(b.letter == up.letter){ //Senao, se a letra coincidir com b define a relacao para 1
b.relation.vertical = 1;
up.relation.vertical = 1;
isPossible_up = 1;
} else if(b.number == up.number) { //Senao, se o numero coincidir com b define a relacao para 1
b.relation.vertical = 2;
up.relation.vertical = 2;
isPossible_up = 1;
}
} else if(up.relation.vertical == 1){ //Se estiver definida como 1, verifica se as letras coincidem
if(b.letter == up.letter){
b.relation.vertical = 1;
isPossible_up = 1;
}
} else { //Caso contrario (se estiver definida como 2), verifica se os numeros coincidem
if(b.number == up.number){
b.relation.vertical = 2;
isPossible_up = 1;
}
}
}
/*
* Ideia semelhante ao de cima, mas para o bloco debaixo
*/
if(isPossible_down == 0){ //Nao vazio e existente
if(down.relation.vertical == 0){
if(b.letter == down.letter){
if(b.relation.vertical < 2){
b.relation.vertical = 1;
down.relation.vertical = 1;
isPossible_down = 1;
}
} else if(b.number == down.number) {
if(b.relation.vertical != 1){
b.relation.vertical = 2;
down.relation.vertical = 2;
isPossible_down = 1;
}
}
} else if(down.relation.vertical == 1){
if(b.letter == down.letter){
if(b.relation.vertical < 2){
b.relation.vertical = 1;
isPossible_down = 1;
}
}
} else {
if(b.number == down.number){
if(b.relation.vertical != 1){
b.relation.vertical = 2;
isPossible_down = 1;
}
}
}
}
/*
* Ideia semelhante ao de cima, mas para o bloco da esquerda
*/
if(isPossible_left == 0){ //Nao vazio e existente
if(left.relation.horizontal == 0){
if(b.letter == left.letter){
b.relation.horizontal = 1;
left.relation.horizontal = 1;
isPossible_left = 1;
} else if(b.number == left.number) {
b.relation.horizontal = 2;
left.relation.horizontal = 2;
isPossible_left = 1;
}
} else if(left.relation.horizontal == 1){
if(b.letter == left.letter){
b.relation.horizontal = 1;
isPossible_left = 1;
}
} else {
if(b.number == left.number){
b.relation.horizontal = 2;
isPossible_left = 1;
}
}
}
/*
* Ideia semelhante ao de cima, mas para o bloco da direita
*/
if(isPossible_right == 0){ //Nao vazio e existente
if(right.relation.horizontal == 0){
if(b.letter == right.letter){
if(b.relation.horizontal < 2){
b.relation.horizontal = 1;
right.relation.horizontal = 1;
isPossible_right = 1;
}
} else if(b.number == right.number) {
if(b.relation.horizontal != 1){
b.relation.horizontal = 2;
right.relation.horizontal = 2;
isPossible_right = 1;
}
}
} else if(right.relation.horizontal == 1){
if(b.letter == right.letter){
if(b.relation.horizontal < 2){
b.relation.horizontal = 1;
isPossible_right = 1;
}
}
} else {
if(b.number == right.number){
if(b.relation.horizontal != 1){
b.relation.horizontal = 2;
isPossible_right = 1;
}
}
}
}
/*
* Verifica se existe possibilidade de adicao nas 4 direcoes
*/
if(isPossible_down == 1 && isPossible_up == 1 && isPossible_right == 1 && isPossible_left == 1){
if(verifyDuplicates(g, b, m)){ //Verifica se ira existir duplicadas na linha que sera inserida
if(m.lin > 0 && up.letter != '\0'){ //Senao, verifica se a linha da jogada eh maior que 0
g->board[m.lin - 1][m.col].relation.vertical = up.relation.vertical; //Se sim, atribui a nova relacao ao bloco acima
}
if(m.lin < g->max_lin && down.letter != '\0') { //Verifica se a linha da jogada eh menor que a linha max do tabuleiro
g->board[m.lin + 1][m.col].relation.vertical = down.relation.vertical; //Se sim, atribui a nova relacao ao bloco abaixo
}
if(m.col > 0 && left.letter != '\0') { //Verifica se a coluna da jogada eh maior que 0
g->board[m.lin][m.col - 1].relation.horizontal = left.relation.horizontal; //Se sim, atribui a nova relacao ao bloco a esquerda
}
if(m.col < g->max_col && right.letter != '\0') { //Verifica se a coluna da jogada eh menor que a coluna max do tabuleiro
g->board[m.lin][m.col + 1].relation.horizontal = right.relation.horizontal; //Se sim, atribui a nova relacao ao bloco a direita
}
if(firstMove->col == -1 && firstMove->lin == -1){ //Verifica se o primeiro movimento da jogada esta indefinido
firstMove->col = m.col; //Se sim, esse eh o primeiro movimento
firstMove->lin = m.lin;
} else if(*lt == 0){ //Verifica se a linha da jogada eh indefinida
if(firstMove->lin == m.lin){ //Se sim, atribui a semelhanca do primeiro movimento com esse como a linha da jogada
*lt = 1; //1: mesma linha
} else {
*lt = 2; //2: mesma coluna
}
}
makeMoviment(g, b, m, firstMove); //Realiza o movimento
return 1;
} else {
invalidMove();
}
} else {
invalidMove();
}
} else {
invalidMove();
}
} else {
invalidMove();
}
return 0;
}
/*
* Verifica se a peca b ja existe na linha em que sera adicionada
*/
short verifyDuplicates(Game *g, Block b, Move m){
int i = 1;
//Verificar letras duplicadas acima da posicao indicada em m
while((i <= m.lin) && g->board[m.lin - i][m.col].letter != '\0'){
if((g->board[m.lin - i][m.col].letter == b.letter) && (g->board[m.lin - i][m.col].number == b.number)){
return 0;
}
i++;
}
i = 1;
//Verifica letras duplicadas abaixo da posicao indicada em m
while((i <= (g->max_lin - m.lin)) && g->board[m.lin + i][m.col].letter != '\0'){
if((g->board[m.lin + i][m.col].letter == b.letter) && (g->board[m.lin + i][m.col].number == b.number)){
return 0;
}
i++;
}
i = 1;
//Verifica letras duplicadas a esquerda da posicao indicada em m
while((i <= m.col) && g->board[m.lin][m.col - i].letter != '\0'){
if((g->board[m.lin][m.col - i].letter == b.letter) && (g->board[m.lin][m.col - i].number == b.number)){
return 0;
}
i++;
}
i = 1;
//Verifica letras duplicadas a direita da posicao indicada em m
while((i <= (g->max_col - m.col)) && g->board[m.lin][m.col + i].letter != '\0'){
if((g->board[m.lin][m.col + i].letter == b.letter) && (g->board[m.lin][m.col + i].number == b.number)){
return 0;
}
i++;
}
return 1;
}
/*
* Realiza um movimento que ja foi verificado e eh possivel
*/
int makeMoviment(Game *g, Block b, Move m, Move *firstMove){
g->board[m.lin][m.col] = b;
Block empty; //Cria um bloco vazio
empty.letter = '\0';
empty.number = 0;
empty.relation.horizontal = 0;
empty.relation.vertical = 0;
/*
* Verifica se a linha indicada em m eh igual a linha max
* Se sim, utiliza realloc para aumentar o tabuleiro
*/
if(m.lin == g->max_lin){
g->max_lin++;
g->board = (Block **) realloc(g->board, (g->max_lin + 1) * sizeof(Block *));
g->board[g->max_lin] = (Block *) calloc(g->max_col + 1, sizeof(Block));
}
/*
* Verifica se a linha indicada em m eh igual a 0
* Se sim, utiliza realloc para aumentar o tabuleiro
*/
if(m.lin == 0){
g->max_lin++;
g->board = (Block **) realloc(g->board, (g->max_lin + 1) * sizeof(Block *));
g->board[g->max_lin] = (Block *) calloc(g->max_col + 1, sizeof(Block));
Block *temp = g->board[g->max_lin];
for(short i = g->max_lin; i > 0; i--){ //Move todo o tabuleiro para baixo
g->board[i] = g->board[i - 1];
}
g->board[0] = temp;
(firstMove->lin)++; //Move a posicao do primeiro movimento para baixo
}
/*
* Verifica se a coluna indicada em m eh igual a coluna max
* Se sim, utiliza realloc para aumentar o tabuleiro
*/
if(m.col == g->max_col){
g->max_col++;
for(short i = 0; i < g->max_lin + 1; i++){
g->board[i] = (Block *) realloc(g->board[i], (g->max_col + 1) * sizeof(Block));
g->board[i][g->max_col] = empty;
}
}
/*
* Verifica se a coluna indicada em m eh igual a 0
* Se sim, utiliza realloc para aumentar o tabuleiro
*/
if(m.col == 0){
g->max_col++;
for(short i = 0; i < g->max_lin + 1; i++){
g->board[i] = (Block *) realloc(g->board[i], (g->max_col + 1) * sizeof(Block));
for(short j = g->max_col; j > 0; j--){ //move as colunas para a direita
g->board[i][j] = g->board[i][j - 1];
}
g->board[i][0] = empty;
}
(firstMove->col)++; //Move a posicao do primeiro movimento para direita
}
}
/*
* Verifica por duplicadas caso haja possibilidade de duas linhas verticais serem unidas
*/
short verifyDuplicatesJoinedVertical(Game *g, Move m){
short i = 1;
Block b[10]; //5 acima e 5 abaixo da peça (maximo)
//Adiciona as pecas acima da posicao definida por m ao vetor b
while((m.lin - i >= 0) && (g->board[m.lin - i][m.col].letter != '\0')){
b[i - 1] = g->board[m.lin - i][m.col];
i++;
}
short j = i - 1;
i = 1;
//Adiciona as pecas abaixo da posicao definida por m ao vetor b
while((m.lin + i <= g->max_lin) && (g->board[m.lin + i][m.col].letter != '\0')){
b[j] = g->board[m.lin + i][m.col];
j++;
i++;
}
//Verifica se existe algum repetido
for(i = 0; i < j; i++){
for(short k = i + 1; k < j; k++){
if((b[i].letter == b[k].letter) && (b[i].number == b[k].number)){
return 0; //Se sim, retorna 0
}
}
}
return 1;
}
/*
* Verifica por duplicadas caso haja possibilidade de duas linhas horizontais serem unidas
*/
short verifyDuplicatesJoinedHorizontal(Game *g, Move m){
short i = 1;
Block b[10]; //5 acima e 5 abaixo da peça
//Adiciona as pecas a esquerda da posicao definida por m ao vetor b
while((m.col - i >= 0) && (g->board[m.lin][m.col - i].letter != '\0')){
b[i - 1] = g->board[m.lin][m.col - i];
i++;
}
short j = i - 1;
i = 1;
//Adiciona as pecas a direita da posicao definida por m ao vetor b
while((m.col + i <= g->max_col) && (g->board[m.lin][m.col + i].letter != '\0')){
b[j] = g->board[m.lin][m.col + i];
j++;
i++;
}
//Verifica se existe algum repetido
for(i = 0; i < j; i++){
for(short k = i + 1; k < j; k++){
if((b[i].letter == b[k].letter) && (b[i].number == b[k].number)){
return 0; //Se sim, retorna 0
}
}
}
return 1;
}
/*
* Verifica se uma peca em uma jogada esta na mesma linha da primeira peca jogada na vez de um dos jogadores
*/
short verifySameLine(Game *g, Move m, Move firstMove){
Block first = g->board[firstMove.lin][firstMove.col];
//Se as linhas de m e firstMove forem iguais
if(firstMove.lin == m.lin){
/*
* Se m.col > firstMove.col, verifica as pecas a esquerda da posicao m
* Se encontrar a peca presente em firstMove antes de uma vazia, esta na mesma linha
*/
if(m.col > firstMove.col){
while(g->board[m.lin][m.col - 1].letter != '\0'){
if((g->board[m.lin][m.col - 1].letter == first.letter) && (g->board[m.lin][m.col - 1].number == first.number)){
return 1;
}
m.col--;
}
} else {
/*
* Se m.col < firstMove.col, verifica as pecas a direita da posicao m
* Se encontrar a peca presente em firstMove antes de uma vazia, esta na mesma linha
*/
while(g->board[m.lin][m.col + 1].letter != '\0'){
if((g->board[m.lin][m.col + 1].letter == first.letter) && (g->board[m.lin][m.col + 1].number == first.number)){
return 1;
}
m.col++;
}
}
} else {
/*
* Se m.lin > firstMove.lin, verifica as pecas acima da posicao m
* Se encontrar a peca presente em firstMove antes de uma vazia, esta na mesma linha
*/
if(m.lin > firstMove.lin){
while(g->board[m.lin - 1][m.col].letter != '\0'){
if((g->board[m.lin - 1][m.col].letter == first.letter) && (g->board[m.lin - 1][m.col].number == first.number)){
return 1;
}
m.lin--;
}
} else {
/*
* Se m.lin < firstMove.lin, verifica as pecas abaixo da posicao m
* Se encontrar a peca presente em firstMove antes de uma vazia, esta na mesma linha
*/
while(g->board[m.lin + 1][m.col].letter != '\0'){
if((g->board[m.lin + 1][m.col].letter == first.letter) && (g->board[m.lin + 1][m.col].number == first.number)){
return 1;
}
m.lin++;
}
}
}
return 0;
}
/*
* Verifica se o jogo finalizou
*/
int verifyEndGame(Game *g, Player *players){
for(short i = 0; i < g->n_players; i++){ // verifica todos os jogadores
short j;
for(j = 0; j < HAND_LENGTH; j++){
if(players[i].tiles[j].letter != '\0'){ //Verifica se as peças do jogador sao vazias
break;
}
}
if(j == HAND_LENGTH){ //se o contador for igual a quantidade de pecas na mao do jogador (padrao: 6), existe um vencedor
players[i].score += 6; //bonus por finalizar as pecas
winner(g, players);
return 1;
}
}
return 0;
}
| 2.84375 | 3 |
2024-11-18T21:19:02.665104+00:00 | 2023-02-16T11:27:40 | 74e92d3c4be4efceee539732f29a207ec8b2ab2d | {
"blob_id": "74e92d3c4be4efceee539732f29a207ec8b2ab2d",
"branch_name": "refs/heads/main",
"committer_date": "2023-02-16T14:59:16",
"content_id": "c29cc168ecbb953c26553327f0fb1f9b2566dc68",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493",
"extension": "c",
"filename": "test_set_iq_sampling_enable.c",
"fork_events_count": 32,
"gha_created_at": "2016-08-05T22:14:50",
"gha_event_created_at": "2022-04-05T17:14:07",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 65052293,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9325,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tests/bluetooth/df/connectionless_cte_rx/src/test_set_iq_sampling_enable.c",
"provenance": "stackv2-0128.json.gz:298185",
"repo_name": "intel/zephyr",
"revision_date": "2023-02-16T11:27:40",
"revision_id": "06d5bc51b580777079bb0b7e769e4127598ea5ee",
"snapshot_id": "819362089aa44ae378a5558f3b222197aaa811f7",
"src_encoding": "UTF-8",
"star_events_count": 32,
"url": "https://raw.githubusercontent.com/intel/zephyr/06d5bc51b580777079bb0b7e769e4127598ea5ee/tests/bluetooth/df/connectionless_cte_rx/src/test_set_iq_sampling_enable.c",
"visit_date": "2023-09-04T00:20:35.217393"
} | stackv2 | /*
* Copyright (c) 2021 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h>
#include <stddef.h>
#include <zephyr/ztest.h>
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/hci.h>
#include <zephyr/sys/byteorder.h>
#include <host/hci_core.h>
#include <bt_common.h>
#include "common.h"
struct ut_bt_df_scan_cte_rx_params {
uint8_t slot_durations;
uint8_t cte_count;
uint8_t num_ant_ids;
uint8_t *ant_ids;
};
static uint8_t g_ant_ids[] = { 0x1, 0x2, 0x3, 0x4, 0x5 };
static struct ut_bt_df_scan_cte_rx_params g_params = {
.slot_durations = BT_HCI_LE_ANTENNA_SWITCHING_SLOT_1US,
.cte_count = BT_HCI_LE_SAMPLE_CTE_ALL,
.num_ant_ids = ARRAY_SIZE(g_ant_ids),
.ant_ids = &g_ant_ids[0]
};
/* Macros delivering common values for unit tests */
#define SYNC_HANDLE_INVALID (CONFIG_BT_PER_ADV_SYNC_MAX + 1)
#define ANTENNA_SWITCHING_SLOT_INVALID \
(BT_HCI_LE_ANTENNA_SWITCHING_SLOT_2US + 1)
#define CTE_COUNT_INVALID (BT_HCI_LE_SAMPLE_CTE_COUNT_MAX + 1)
#define SWITCH_PATTERN_LEN_INVALID \
(CONFIG_BT_CTLR_DF_MAX_ANT_SW_PATTERN_LEN + 1)
/* @brief Function sends HCI_LE_Set_Connectionless_CTE_Sampling_Enable
* to controller.
*
* @param sync_handle Handle of sync set.
* @param sync_flags Flags related with sync set.
* @param params CTE Sampling parameters.
* @param enable Enable or disable CTE RX
*
* @return Zero if success, non-zero value in case of failure.
*/
int send_set_scan_cte_rx_enable(uint16_t sync_handle,
struct ut_bt_df_scan_cte_rx_params *params,
bool enable)
{
struct bt_hci_cp_le_set_cl_cte_sampling_enable *cp;
struct net_buf *buf;
buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_CL_CTE_SAMPLING_ENABLE,
sizeof(*cp) + params->num_ant_ids);
if (!buf) {
return -ENOBUFS;
}
cp = net_buf_add(buf, sizeof(*cp));
(void)memset(cp, 0, sizeof(*cp));
cp->sync_handle = sys_cpu_to_le16(sync_handle);
cp->sampling_enable = enable ? 1 : 0;
cp->slot_durations = params->slot_durations;
cp->max_sampled_cte = params->cte_count;
if (params->num_ant_ids) {
if (params->ant_ids) {
uint8_t *dest_ant_ids =
net_buf_add(buf, params->num_ant_ids);
memcpy(dest_ant_ids, params->ant_ids,
params->num_ant_ids);
}
cp->switch_pattern_len = params->num_ant_ids;
} else {
cp->switch_pattern_len = 0;
}
return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_CL_CTE_SAMPLING_ENABLE,
buf, NULL);
}
ZTEST(test_hci_set_scan_cte_rx_enable, test_set_scan_cte_rx_enable_invalid_scan_set_handle)
{
int err;
err = send_set_scan_cte_rx_enable(SYNC_HANDLE_INVALID, &g_params, true);
zassert_equal(err, -EIO,
"Unexpected error value for enable IQ sampling with wrong sync handle");
}
ZTEST(test_hci_set_scan_cte_rx_enable, test_set_scan_cte_rx_enable_invalid_antenna_slots_value)
{
int err;
uint8_t slot_durations_prev = g_params.slot_durations;
g_params.slot_durations = ANTENNA_SWITCHING_SLOT_INVALID;
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, true);
zassert_equal(err, -EIO,
"Unexpected error value for enable IQ sampling with wrong antenna switching"
" slots value");
g_params.slot_durations = slot_durations_prev;
}
ZTEST(test_hci_set_scan_cte_rx_enable, test_set_scan_cte_rx_enable_invalid_antenna_pattern_num)
{
int err;
uint8_t num_ant_ids_prev = g_params.num_ant_ids;
uint8_t *ant_ids_prev = g_params.ant_ids;
uint8_t ant_ids[SWITCH_PATTERN_LEN_INVALID] = { 0 };
g_params.num_ant_ids = SWITCH_PATTERN_LEN_INVALID;
g_params.ant_ids = &ant_ids[0];
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, true);
zassert_equal(err, -EIO,
"Unexpected error value for enable IQ sampling with wrong number"
" of antenna ids.");
g_params.num_ant_ids = num_ant_ids_prev;
g_params.ant_ids = ant_ids_prev;
}
ZTEST(test_hci_set_scan_cte_rx_enable, test_set_scan_cte_rx_enable_invalid_cte_count_value)
{
int err;
uint8_t cte_count_prev = g_params.cte_count;
g_params.cte_count = CTE_COUNT_INVALID;
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, true);
zassert_equal(err, -EIO,
"Unexpected error value for enable IQ sampling with wrong number of CTEs"
" to sample.");
g_params.cte_count = cte_count_prev;
}
ZTEST(test_hci_set_scan_cte_rx_enable, test_set_scan_cte_rx_enable_with_slot_duration_2us)
{
int err;
uint8_t slot_durations_prev = g_params.slot_durations;
g_params.slot_durations = BT_HCI_LE_ANTENNA_SWITCHING_SLOT_2US;
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, true);
zassert_equal(err, 0, "Unexpected error value for enable IQ sampling");
g_params.slot_durations = slot_durations_prev;
}
ZTEST(test_hci_set_scan_cte_rx_enable, test_set_scan_cte_rx_enable_with_slot_duration_1us)
{
int err;
uint8_t slot_durations_prev = g_params.slot_durations;
g_params.slot_durations = BT_HCI_LE_ANTENNA_SWITCHING_SLOT_1US;
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, true);
zassert_equal(err, 0,
"Unexpected error value for enable IQ sampling with 1us slot durations");
g_params.slot_durations = slot_durations_prev;
}
ZTEST(test_hci_set_scan_cte_rx_enable, test_set_scan_cte_rx_enable_with_sample_cte_count_min)
{
int err;
uint8_t cte_count_prev = g_params.cte_count;
g_params.cte_count = BT_HCI_LE_SAMPLE_CTE_COUNT_MIN;
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, true);
zassert_equal(err, 0,
"Unexpected error value for enable IQ sampling with CTEs count set"
" to min value.");
g_params.cte_count = cte_count_prev;
}
ZTEST(test_hci_set_scan_cte_rx_enable, test_set_scan_cte_rx_enable_with_sample_cte_count_max)
{
int err;
uint8_t cte_count_prev = g_params.cte_count;
g_params.cte_count = BT_HCI_LE_SAMPLE_CTE_COUNT_MAX;
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, true);
zassert_equal(err, 0,
"Unexpected error value for enable IQ sampling with CTEs count set"
" to max value.");
g_params.cte_count = cte_count_prev;
}
ZTEST(test_hci_set_scan_cte_rx_enable, test_set_scan_cte_rx_enable_with_antenna_switch_patterns_min)
{
int err;
uint8_t num_ant_ids_prev = g_params.num_ant_ids;
uint8_t *ant_ids_prev = g_params.ant_ids;
uint8_t ant_ids[BT_HCI_LE_MAX_SWITCH_PATTERN_LEN_MIN] = { 0 };
g_params.num_ant_ids = BT_HCI_LE_MAX_SWITCH_PATTERN_LEN_MIN;
g_params.ant_ids = &ant_ids[0];
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, true);
zassert_equal(err, 0,
"Unexpected error value for enable IQ sampling with min number of"
" antenna ids.");
g_params.num_ant_ids = num_ant_ids_prev;
g_params.ant_ids = ant_ids_prev;
}
ZTEST(test_hci_set_scan_cte_rx_enable, test_set_scan_cte_rx_enable_with_antenna_switch_patterns_max)
{
int err;
uint8_t num_ant_ids_prev = g_params.num_ant_ids;
uint8_t *ant_ids_prev = g_params.ant_ids;
uint8_t ant_ids[CONFIG_BT_CTLR_DF_MAX_ANT_SW_PATTERN_LEN] = { 0 };
g_params.num_ant_ids = CONFIG_BT_CTLR_DF_MAX_ANT_SW_PATTERN_LEN;
g_params.ant_ids = &ant_ids[0];
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, true);
zassert_equal(err, 0,
"Unexpected error value for enable IQ sampling with max number of antenna"
" ids.");
g_params.num_ant_ids = num_ant_ids_prev;
g_params.ant_ids = ant_ids_prev;
}
ZTEST(test_hci_set_scan_cte_rx_disable,
test_set_scan_cte_rx_disable_with_correct_sampling_parameters)
{
int err;
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, false);
zassert_equal(err, 0, "Unexpected error value for disable IQ sampling.");
}
ZTEST(test_hci_set_scan_cte_rx_disable,
test_set_scan_cte_rx_disable_with_invalid_sampling_parameters)
{
int err;
static struct ut_bt_df_scan_cte_rx_params params_invalid = {
.slot_durations = ANTENNA_SWITCHING_SLOT_INVALID,
.cte_count = CTE_COUNT_INVALID,
.num_ant_ids = 0,
.ant_ids = NULL
};
err = send_set_scan_cte_rx_enable(g_per_sync->handle, ¶ms_invalid,
false);
zassert_equal(err, 0, "Unexpected error value for disable IQ sampling.");
}
ZTEST(test_hci_set_scan_cte_rx_disable, test_set_scan_cte_rx_disable_when_disabled)
{
int err;
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, false);
zassert_equal(err, 0,
"Unexpected error value for disable IQ sampling when it is disabled.");
}
void set_scan_cte_rx_enable_teardown(void *data)
{
int err;
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, false);
zassert_equal(err, 0, "Unexpected error value for disable IQ sampling.");
}
void set_scan_cte_rx_disable_setup(void *data)
{
int err;
err = send_set_scan_cte_rx_enable(g_per_sync->handle, &g_params, true);
zassert_equal(err, 0, "Unexpected error value for enable IQ sampling.");
}
static void *common_per_sync_setup(void)
{
ut_bt_setup();
common_create_per_sync_set();
return NULL;
}
ZTEST_SUITE(test_hci_set_scan_cte_rx_enable, NULL, common_per_sync_setup, NULL,
set_scan_cte_rx_enable_teardown, ut_bt_teardown);
ZTEST_SUITE(test_hci_set_scan_cte_rx_disable, NULL, common_per_sync_setup,
set_scan_cte_rx_disable_setup, NULL, ut_bt_teardown);
| 2.28125 | 2 |
2024-11-18T21:19:02.906626+00:00 | 2020-12-03T16:06:55 | 601527d03169fea066c7be9648eb7af6a81123a2 | {
"blob_id": "601527d03169fea066c7be9648eb7af6a81123a2",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-03T16:06:55",
"content_id": "071859ef8db9f7857fb96897ed52f746819934c2",
"detected_licenses": [
"MIT"
],
"directory_id": "5fbdca9947e7cc0c7b2583eca1fc98b93cfed144",
"extension": "c",
"filename": "mx_get_sms.c",
"fork_events_count": 0,
"gha_created_at": "2020-09-25T19:42:54",
"gha_event_created_at": "2020-12-03T16:06:57",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 298665136,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1056,
"license": "MIT",
"license_type": "permissive",
"path": "/server/src/dal/mx_get_sms.c",
"provenance": "stackv2-0128.json.gz:298444",
"repo_name": "vrudkovsky/uchat",
"revision_date": "2020-12-03T16:06:55",
"revision_id": "43047542c8e08557983f8a3e52a5f3a429e41aff",
"snapshot_id": "2bb1ec4b155b9925ded9eb3583149fef2fc93359",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vrudkovsky/uchat/43047542c8e08557983f8a3e52a5f3a429e41aff/server/src/dal/mx_get_sms.c",
"visit_date": "2023-01-30T14:45:21.319930"
} | stackv2 | #include "server.h"
#include <sqlite3.h>
sqlite3 *db;
sqlite3_stmt* stmt;
static void startDB() {
if (sqlite3_open("uchat.db", &db))
printf("Ошибка открытия БД: %s\n", sqlite3_errmsg(db));
}
static void endDB(){
sqlite3_close(db);
}
static char *mx_msg_text(char *arr, int chat_id) {
int rc = 0;
int i = 0;
char zSql[]="SELECT * FROM messages";
do {
sqlite3_prepare(db, zSql, -1, &stmt, 0);
while (SQLITE_ROW == sqlite3_step(stmt)) {
if (sqlite3_column_int(stmt, 0) == chat_id) {
arr = mx_strdup((const char*)sqlite3_column_text(stmt, 3));
i++;
}
}
rc = sqlite3_finalize(stmt);
}
while (rc == SQLITE_SCHEMA); {}
return arr;
}
char **mx_get_msg_text(int *msg_id, int count_sms) {
char **arr = malloc(sizeof(char*) * (count_sms + 1));
arr[count_sms] = NULL;
startDB();
for (int i = 0; i < count_sms; i++)
arr[i] = mx_msg_text(arr[i], msg_id[i]);
endDB();
return arr;
}
| 2.328125 | 2 |
2024-11-18T21:19:02.957544+00:00 | 2020-06-28T01:33:43 | cf16692ee5c34f49860fecf404dd2b9e40125c04 | {
"blob_id": "cf16692ee5c34f49860fecf404dd2b9e40125c04",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-28T01:33:43",
"content_id": "b62d939c6975635e8898d46417575b36e5fc6d2f",
"detected_licenses": [
"Unlicense"
],
"directory_id": "bdd39a62ceea54e4cd3f9c18db7c3623b52c4cbd",
"extension": "c",
"filename": "bow.c",
"fork_events_count": 0,
"gha_created_at": "2020-06-29T06:38:10",
"gha_event_created_at": "2020-06-29T06:38:11",
"gha_language": null,
"gha_license_id": "Unlicense",
"github_id": 275751299,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1037,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/vc/bow.c",
"provenance": "stackv2-0128.json.gz:298574",
"repo_name": "tripleee/SpamSoup",
"revision_date": "2020-06-28T01:33:43",
"revision_id": "6b72d8253c9b70751e53c765b4d1cf3ed9ee53d0",
"snapshot_id": "3b17fb2ecad22720b539a5616acbef6a6f49328b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tripleee/SpamSoup/6b72d8253c9b70751e53c765b4d1cf3ed9ee53d0/src/vc/bow.c",
"visit_date": "2022-11-13T15:18:25.750680"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include "vcutils.h"
int main(){
/* This program implements bag-of-word hashing, a hashing algorithm converting a list of phrases to
* a list of 32 bits integer hashes, with each hash determined by the corresponding phrase.
* Input format:
* Input may consist many lines, with one phrase on each line. An EOF signal shall be sent when input ends.
* Output format:
* Output consists many lines, with one hash on each line. Each hash is represented by a base 10 integer.
* The number of lines in the output is the same as that of input. An EOF signal will be sent when output ends. */
unsigned char *phrase;
size_t size_phrase = 0;
ssize_t len_phrase;
unsigned long hash_result;
while ((len_phrase = getline((char **)(&phrase), &size_phrase, stdin)) != -1){
strip_endl(phrase, &len_phrase);
hash_result = str_hash(phrase, (size_t)(len_phrase));
printf("%lu\n", hash_result);
}
free(phrase);
return 0;
}
| 2.734375 | 3 |
2024-11-18T21:19:03.748236+00:00 | 2019-04-03T09:02:39 | 59bdfba5def40250c8827fc180199d1b8b1b570e | {
"blob_id": "59bdfba5def40250c8827fc180199d1b8b1b570e",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-03T09:02:39",
"content_id": "9fed6dd21861fcbaa4c1682d0fa685c604025d8d",
"detected_licenses": [
"MIT"
],
"directory_id": "8f20f30a840ce38dd1d6261e9b8f3d86c3576439",
"extension": "c",
"filename": "narray_helper.c",
"fork_events_count": 11,
"gha_created_at": "2017-08-28T14:41:33",
"gha_event_created_at": "2020-12-22T13:16:07",
"gha_language": "Ruby",
"gha_license_id": "MIT",
"github_id": 101652920,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2369,
"license": "MIT",
"license_type": "permissive",
"path": "/ext/mxnet/narray_helper/narray_helper.c",
"provenance": "stackv2-0128.json.gz:298841",
"repo_name": "mrkn/mxnet.rb",
"revision_date": "2019-04-03T09:02:39",
"revision_id": "edc85f60baa51cab0b9bcecd307e1fefaacbcbf4",
"snapshot_id": "9c4f9bebb656f1715a3379adc79e189f72165c54",
"src_encoding": "UTF-8",
"star_events_count": 54,
"url": "https://raw.githubusercontent.com/mrkn/mxnet.rb/edc85f60baa51cab0b9bcecd307e1fefaacbcbf4/ext/mxnet/narray_helper/narray_helper.c",
"visit_date": "2021-01-20T10:50:44.102570"
} | stackv2 | #include "../mxnet_internal.h"
#include <numo/narray.h>
#include <limits.h>
static VALUE
ndarray_to_narray(VALUE obj)
{
NDArrayHandle handle;
mx_uint mx_ndim;
mx_uint const* mx_shape;
int mx_dtype_id, na_ndim, i;
VALUE nary_type, nary, na_shape_str;
size_t *na_shape, na_size;
char *na_ptr;
handle = mxnet_ndarray_get_handle(obj);
CHECK_CALL(MXNET_API(MXNDArrayGetShape)(handle, &mx_ndim, &mx_shape));
CHECK_CALL(MXNET_API(MXNDArrayGetDType)(handle, &mx_dtype_id));
if (INT_MAX < mx_ndim) {
rb_raise(rb_eRuntimeError, "The number of dimensions is too large for Numo::NArray");
}
na_ndim = (int)mx_ndim;
switch (mx_dtype_id) {
case kFloat32:
nary_type = numo_cSFloat;
break;
case kFloat64:
nary_type = numo_cDFloat;
break;
case kFloat16:
nary_type = numo_cSFloat;
break;
case kUint8:
nary_type = numo_cUInt8;
break;
case kInt32:
nary_type = numo_cInt32;
break;
case kInt8:
nary_type = numo_cInt8;
break;
case kInt64:
nary_type = numo_cInt64;
break;
default:
rb_raise(rb_eRuntimeError, "Unknown dtype of MXNet::NDArray (%d)", mx_dtype_id);
}
na_shape_str = rb_str_tmp_new(sizeof(size_t) * na_ndim);
na_shape = (size_t *)RSTRING_PTR(na_shape_str);
for (i = 0; i < na_ndim; ++i) {
na_shape[i] = mx_shape[i];
}
nary = nary_new(nary_type, na_ndim, na_shape);
na_ptr = nary_get_pointer_for_write(nary);
na_size = RNARRAY_SIZE(nary);
CHECK_CALL(MXNET_API(MXNDArraySyncCopyToCPU)(handle, na_ptr, na_size));
return nary;
}
static VALUE
m_sync_copyfrom(VALUE mod, VALUE nd_obj, VALUE nary)
{
NDArrayHandle handle;
narray_t *na;
void *data;
size_t size;
mxnet_check_ndarray(nd_obj);
if (!RTEST(nary_check_contiguous(nary))) {
nary = nary_dup(nary);
}
GetNArray(nary, na);
data = NA_DATA_PTR(na);
size = NA_SIZE(na);
handle = mxnet_ndarray_get_handle(nd_obj);
CHECK_CALL(MXNET_API(MXNDArraySyncCopyFromCPU)(handle, data, size));
return nd_obj;
}
void
Init_narray_helper(void)
{
VALUE mHelper;
rb_undef_method(mxnet_cNDArray, "to_narray");
rb_define_method(mxnet_cNDArray, "to_narray", ndarray_to_narray, 0);
mHelper = rb_define_module_under(mxnet_mMXNet, "NArrayHelper");
rb_define_module_function(mHelper, "sync_copyfrom", m_sync_copyfrom, 2);
}
| 2.234375 | 2 |
2024-11-18T21:19:04.018561+00:00 | 2020-11-08T08:12:28 | b88adc4c307bc648bacfcd3df34e045dd5d411f6 | {
"blob_id": "b88adc4c307bc648bacfcd3df34e045dd5d411f6",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-08T08:12:28",
"content_id": "71d303ef991523e2401638f5f4ae4989dcae9e62",
"detected_licenses": [
"MIT"
],
"directory_id": "1604d52d55ef8960215d4c43020f9951fb311c1d",
"extension": "c",
"filename": "malloc.c",
"fork_events_count": 0,
"gha_created_at": "2020-10-01T19:29:53",
"gha_event_created_at": "2020-10-29T19:06:40",
"gha_language": "Pascal",
"gha_license_id": "MIT",
"github_id": 300400282,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 744,
"license": "MIT",
"license_type": "permissive",
"path": "/memory/malloc.c",
"provenance": "stackv2-0128.json.gz:299103",
"repo_name": "ErandiGC/C",
"revision_date": "2020-11-08T08:12:28",
"revision_id": "0cd1f0e8d57db2ff0225ccd6bf522c2e25a5b483",
"snapshot_id": "aae6411663e0333c92382188c65e8a29b5b96e0f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ErandiGC/C/0cd1f0e8d57db2ff0225ccd6bf522c2e25a5b483/memory/malloc.c",
"visit_date": "2023-01-06T19:32:27.945819"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
int Cantidad() {
int cantidad;
printf("Números que deseas guardar: ");
scanf("%i", &cantidad);
return cantidad;
}
void leerNumeros(int cantidad, int *numeros) {
for (int i =0;i < cantidad; i++) {
printf("Número %d:",i + 1);
scanf("%i",&numeros[i]);
}
}
void imprimirNumeros(int cantidad, int *numeros) {
for (int i=0;i < cantidad; i++) {
printf("Número %d : %i ", i+1, numeros[i]);
}
}
int main(void) {
int cantidad = Cantidad();
/*(cast-type*) malloc(byte-size)*/
int *numeros = (int*) malloc(cantidad * sizeof(int));
leerNumeros(cantidad, numeros);
imprimirNumeros(cantidad, numeros);
free(numeros);
return 0;
}
| 3.421875 | 3 |
2024-11-18T21:19:04.105843+00:00 | 2020-09-29T13:28:14 | e4dfcf59e649256ef8fecd527107428d9d2df725 | {
"blob_id": "e4dfcf59e649256ef8fecd527107428d9d2df725",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-29T13:28:14",
"content_id": "14cd4219e68edf616895f21519812592d2906be5",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "6b240f881dc8cc946494a17c5a36a21fb8600b5a",
"extension": "h",
"filename": "cc_dh_kg.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": 9411,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/shared/include/crypto_api/cc_dh_kg.h",
"provenance": "stackv2-0128.json.gz:299236",
"repo_name": "Global19-atlassian-net/Cryptocell-713-TEE-Lib",
"revision_date": "2020-09-29T13:28:14",
"revision_id": "bc0aca96f9769bba1a5927aa2bc6b82ceee94dea",
"snapshot_id": "ed983a5decedc81d61992dc146ddf5a3525ca7c3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Global19-atlassian-net/Cryptocell-713-TEE-Lib/bc0aca96f9769bba1a5927aa2bc6b82ceee94dea/shared/include/crypto_api/cc_dh_kg.h",
"visit_date": "2022-12-18T16:31:25.864906"
} | stackv2 | /*
* Copyright (c) 2001-2019, Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause OR Arm's non-OSI source license
*
*/
#ifndef _CC_DH_KG_H
#define _CC_DH_KG_H
#include "cc_dh.h"
#ifdef __cplusplus
extern "C"
{
#endif
/*! @file
@brief This file defines the API that supports Diffie-Hellman domain.
*/
/*!
@addtogroup cc_dh_kg
@{
*/
/************************ Defines ******************************/
/*! Minimal size of DH seed in bytes. */
#define CC_DH_SEED_MIN_SIZE_IN_BYTES CC_HASH_SHA1_DIGEST_SIZE_IN_BYTES
/*! Minimal size of DH seed in bits. */
#define CC_DH_SEED_MIN_SIZE_IN_BITS (CC_DH_SEED_MIN_SIZE_IN_BYTES * 8)
/************************ Enums ********************************/
/************************ Typedefs ****************************/
/* temp buffers, used in different DH KG functions */
/*! Temporary data buffer structure for domain parameters generation in DH. */
typedef struct CCDhKgData_t
{
/* The aligned input and output temp buffers */
/*! Temporary buffer. */
uint32_t TempBuff1[CC_DH_MAX_MOD_BUFFER_SIZE_IN_WORDS];
/*! Temporary buffer. */
uint32_t TempBuff2[CC_DH_MAX_MOD_BUFFER_SIZE_IN_WORDS];
/*! Temporary buffer. */
uint32_t TempBuff3[CC_DH_MAX_MOD_BUFFER_SIZE_IN_WORDS];
/*! Temporary buffer. */
uint32_t TempBuff4[CC_DH_MAX_MOD_BUFFER_SIZE_IN_WORDS];
/*! Temporary buffer. */
uint32_t TempBuff5[CC_DH_MAX_MOD_BUFFER_SIZE_IN_WORDS];
/*! Temporary buffer. */
uint32_t TempBuff6[CC_DH_MAX_MOD_BUFFER_SIZE_IN_WORDS];
/*! Temporary buffer. */
CCDhTemp_t ExpTemps;
}CCDhKgData_t;
/*! Temporary buffer structure. */
typedef struct CCDhKgCheckTemp_t
{
/*! Temporary buffer. */
uint32_t CheckTempBuff[3*CC_DH_MAX_MOD_BUFFER_SIZE_IN_WORDS];
/*! Temporary buffer. */
CCDhKgData_t DhKgBuff;
}CCDhKgCheckTemp_t;
/* DH Domain generation values definitions */
/*! Minimal modulus size for X942 - 1024.*/
#define DH_X942_PRIME_MOD_MIN_VAL 1024
/*! Maximal modulus size for X942 - 2048.*/
#define DH_X942_PRIME_MOD_MAX_VAL 2048
/*! PGeneration counter for X942 - 4096.*/
#define DH_X942_PGEN_COUNTER_CONST 4096
/*! HASH size in bits for X942 - 160.*/
#define DH_X942_HASH_SIZE_BITS 160
/*! Maximal seed additional data size.*/
#define DH_SEED_MAX_ADDING_VAL 0xFFFFFFFF
/************************ Structs ******************************/
/************************ Public Variables **********************/
/************************ Public Functions **********************/
/******************************************************************************************/
/*!
@brief This function generates DH domain parameters in Galois prime field according to the ANSI X9.42-2003: Public Key Cryptography for the Financial Services Industry:
Agreement of Symmetric Keys Using Discrete Logarithm Cryptography standard.
It receives the required sizes (in bits) of the modulus, the generator's order, and the seed, and then generates the prime modulus and the generator
according to these parameters.
If generateSeed argument is set to 1, the function generates and outputs the random seed. Otherwise (if set to 0), the seed has to be passed as an input argument.
According to implementation value of the user passed seed should be not greater than (2^seedSizeBits - 2^32).
The Seed and some additional parameters, generated by the function (factorJ, pgenCounter), are used for checking that all domain parameters are generated
according to the standard and not forged.
\note All buffer parameters should be in big-endian form.
@return \c CC_OK on success.
@return A non-zero value on failure as defined cc_dh_error.h, cc_rnd_error.h or cc_hash_error.h.
*/
CIMPORT_C CCError_t CC_DhCreateDomainParams(
CCError_t (*f_rng)(void *, unsigned char *, size_t), /*!< in - Pointer to DRBG function*/
void *p_rng, /*!< in/out - Pointer to the random context - the input to f_rng.*/
uint32_t modPsizeBits, /*!< [in] Size of the modulus (Prime) in bits equal 256*n, where n >= 4. FIPS Publication 186-4: Digital
Signature Standard (DSS) defines sizes 1024 and 2048 bit. Maximal size is 4096 bits. */
uint32_t orderQsizeBits, /*!< [in] Size of the Generator's order in bits. FIPS Publication 186-4: Digital Signature Standard
(DSS) defines orderQSizeBits = 160 for modulus 1024 bit and 224 or 256 bit for modPSizeBits = 2048.
It is not recommended to use sizes > 256. The API returns an error if orderQSizeBits > modPSizeBits/4.
The allowed sizes are multiples of 32 bits. */
uint32_t seedSizeBits, /*!< [in] Seed size in bits. Requirements: modPSizeBits >= seedSizeBits >= orderQSizeBits
(the first is required by our implementation). */
uint8_t *modP_ptr, /*!< [out] Pointer to the modulus (Prime) buffer of defined structure. The size of the
buffer for output generated value must be no less than modulus size. */
uint8_t *orderQ_ptr, /*!< [out] Pointer to the order Q of generator. The size of the buffer for output generated
value must be no less than the order size. */
uint8_t *generatorG_ptr, /*!< [out] Pointer to the generator of multiplicative subgroup in GF(P).
If the user does not need this output, then both the pointer and the buffer size must be set
to 0. */
uint32_t *generGsizeBytes_ptr, /*!< [in/out] Pointer to the one word buffer for outputting the generator's size.
The passed size (if needed) must be no less than modulus size.
The function returns the actual size of the generator. */
uint8_t *factorJ_ptr, /*!< [out] Pointer to the buffer for integer factor J. If NULL, the function does not output
this parameter. */
uint32_t *JsizeBytes_ptr, /*!< [in/out] Pointer to the size of integer factor J. If NULL, the function does not output
this parameter. */
uint8_t *seedS_ptr, /*!< [in/out] Random seed used for prime generation. The size of the buffer for output
generated value must be at least the seed size. */
int8_t generateSeed, /*!< [in] Flag defining whether the seed should be generated randomly by the function
(1) or passed by the user (0). */
uint32_t *pgenCounter_ptr, /*!< [out] Pointer to counter of tries to generate the primes. If NULL, the function does not
output this parameter. */
CCDhKgData_t *DHKGbuff_ptr /*!< [out] The temp buffer of defined structure for internal calculations. */
);
/******************************************************************************************/
/*!
@brief This function receives DH domain parameters, seed and prime generation counter and then verifies that the domain was created according to
the ANSI X9.42-2003: Public Key Cryptography for the Financial Services Industry: Agreement of Symmetric Keys Using Discrete Logarithm
Cryptography standard. The seed should be no greater than (2^seedSizeBits - 2^32), otherwise an error is returned.
\note All buffer parameters should be in big-endian form. For a description of
the parameters see ::CC_EcpkiPublKeyBuildAndCheck.
@return \c CC_OK on success.
@return A non-zero value on failure as defined cc_dh_error.h, cc_rnd_error.h or cc_hash_error.h.
*/
CIMPORT_C CCError_t CC_DhCheckDomainParams(
CCRndGenerateVectWorkFunc_t f_rng, /*!< [in] Pointer to DRBG function*/
void *p_rng, /*!< [in/out] Pointer to the random context - the input to f_rng. */
uint8_t *modP_ptr, /*!< [in] Pointer to the modulus (Prime). */
uint32_t modPsizeBytes, /*!< [in] Size of the modulus (Prime) in bytes. */
uint8_t *orderQ_ptr, /*!< [in] Pointer to the order Q of generator. The size of the buffer for output generated value
must be no less than the order size. */
uint32_t orderQsizeBytes, /*!< [in] Size of the Generator's order in bytes. */
uint8_t *generatorG_ptr, /*!< [in] Pointer to the generator of the multiplicative subgroup in GF(P). */
uint32_t generatorSizeBytes, /*!< [in] Size of the generator in bytes. */
uint8_t *seedS_ptr, /*!< [in] Random seed used for prime generation. */
uint32_t seedSizeBits, /*!< [in] Seed size in bits. */
uint32_t pgenCounter, /*!< [in] Counter of prime generation attempts. */
CCDhKgCheckTemp_t *checkTempBuff_ptr /*!< [in] Temporary buffer for internal calculations. */
);
#ifdef __cplusplus
}
#endif
/**
@}
*/
#endif
| 2.125 | 2 |
2024-11-18T21:19:04.184110+00:00 | 2020-04-25T05:23:16 | 7be9365d68e28e4fe3dca37f070d307b2de37236 | {
"blob_id": "7be9365d68e28e4fe3dca37f070d307b2de37236",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-25T05:23:16",
"content_id": "8401fcd777f9ce2960934095ebf3192b1d999ded",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ab29742037f569530a7c1cdb44e5212c7cec975c",
"extension": "h",
"filename": "memops.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 235246991,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 951,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/mb/drm_audio_fw/src/memops.h",
"provenance": "stackv2-0128.json.gz:299368",
"repo_name": "CactiLab/2020-ectf-rit-system",
"revision_date": "2020-04-25T05:23:16",
"revision_id": "c42bfb4d49824a8135500451dc28aa5e18829a5e",
"snapshot_id": "2354e8765da96f3d45bd58fa78b3f5aac1e4f32c",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/CactiLab/2020-ectf-rit-system/c42bfb4d49824a8135500451dc28aa5e18829a5e/mb/drm_audio_fw/src/memops.h",
"visit_date": "2022-04-26T09:52:00.897390"
} | stackv2 | #pragma once
#ifndef MEMOPS_H
#define MEMOPS_H
//see memops.c for implementation
#include <stdint.h>
#include <stddef.h>
/*
returns buf.
*/
void* memset(void* buf, int c, size_t n);
/*
returns dest.
src and dest MAY NOT overlap.
*/
void* memcpy(void* dest, const void* src, size_t n);
/*
returns dest.
src and dest MAY overlap.
*/
void* memmove(void* dest, const void* src, size_t n);
/*
returns:
+ if s1>s2
0 if s1==s2
- if s1<s2
*/
int memcmp(const void* s1, const void* s2, size_t n);
/*
returns buf.
zeroes the memory at buf
*/
void* memzero(void* buf, size_t n);
/*
copies memory from fpga-only memory to a shared memory section the arm processor can access.
*/
void* copyfromlocal(void* arm_dest, const void* fpga_src, size_t n);
/*
copies memory from shared arm-accessible space to fpga-only ram.
*/
void* copytolocal(void* fpga_dest, const void* arm_src, size_t n);
#endif // !MEMOPS_H
| 2.421875 | 2 |
2024-11-18T21:19:04.367829+00:00 | 2019-12-18T21:20:37 | fd8e30a37d390aa6a862465d4b3505ccdcadecd4 | {
"blob_id": "fd8e30a37d390aa6a862465d4b3505ccdcadecd4",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-18T21:20:37",
"content_id": "13b029ac86db067b43bff648272c9cceb7551558",
"detected_licenses": [
"MIT"
],
"directory_id": "2548b6152ff6742876930629892398abc08a7eaf",
"extension": "c",
"filename": "es2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 228104861,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 569,
"license": "MIT",
"license_type": "permissive",
"path": "/Esercitazione 01/es2.c",
"provenance": "stackv2-0128.json.gz:299501",
"repo_name": "alessandro-antonelli/SOL-2016",
"revision_date": "2019-12-18T21:20:37",
"revision_id": "bbc051ef44b5d0f71fa761d94b7106e2149600d3",
"snapshot_id": "987af6f7b0ae375ea0f1a0ec34b4ffd4bb06d17c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alessandro-antonelli/SOL-2016/bbc051ef44b5d0f71fa761d94b7106e2149600d3/Esercitazione 01/es2.c",
"visit_date": "2020-11-24T10:21:41.867945"
} | stackv2 | #include <stdio.h>
int main(int argc, char* argv[], char* envp[])
{
printf("Sono stati passati al programma %d argomenti. Segue la lista:\n", argc);
int i = 0;
while(argv[i] != NULL)
{
printf("Argomento numero %d: %s\n", i, argv[i]);
i++;
}
printf("====================================================================================\n");
printf("Segue ora la lista delle variabili di ambiente:\n");
i = 0;
while(envp[i] != NULL)
{
printf("Variabile di ambiente numero %d: %s\n", i, envp[i]);
i++;
}
printf("Fine del programma\n");
return 0;
}
| 3.21875 | 3 |
2024-11-18T21:19:04.586329+00:00 | 2020-05-06T00:23:53 | 7ee6ee8a7c8dee9258f883902a1364ee0ef56960 | {
"blob_id": "7ee6ee8a7c8dee9258f883902a1364ee0ef56960",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-06T00:23:53",
"content_id": "77360ebfd3bbc3207cba78c3806109a70997837d",
"detected_licenses": [
"MIT"
],
"directory_id": "6883581f0f9e8ad0ad7bbe684e65cb6e0fbc8529",
"extension": "c",
"filename": "1042 - Sort Simples.c",
"fork_events_count": 22,
"gha_created_at": "2019-02-28T23:58:03",
"gha_event_created_at": "2021-11-24T16:48:51",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 173205680,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 725,
"license": "MIT",
"license_type": "permissive",
"path": "/C/1042 - Sort Simples.c",
"provenance": "stackv2-0128.json.gz:299632",
"repo_name": "NadiaaOliverr/Uri-Problem-Solutions",
"revision_date": "2020-05-06T00:23:53",
"revision_id": "4546a0f662b0d54c6f6076506771712646f2b6d8",
"snapshot_id": "20ca030b7335d5f9a69f60dfff5f00a9cfe72ec8",
"src_encoding": "UTF-8",
"star_events_count": 28,
"url": "https://raw.githubusercontent.com/NadiaaOliverr/Uri-Problem-Solutions/4546a0f662b0d54c6f6076506771712646f2b6d8/C/1042 - Sort Simples.c",
"visit_date": "2021-12-09T19:37:36.929362"
} | stackv2 | #include <stdio.h>
int main()
{
int vetor[3];
int aux[3],auxiliar;
int i,j;
for(i=0;i<3;i++)
{
scanf("%d",&vetor[i]);
aux[i] = vetor[i];
}
for(i=0;i<3;i++)
{
for(j=i+1;j<3;j++)
{
if ( vetor[i] > vetor[j] )
{
auxiliar = vetor[i]; //Recebe o valor anterior que ser� trocado, pois ele � maior ---> Anterior| Pr�ximo
vetor[i] = vetor[j]; //Colocando o valor pr�ximo, na posi��o do anterior, pois ele � menor
vetor[j] = auxiliar; //Colocando o valor anterior no lugar do pr�ximo, troca efetuada
}
}
}
for(i=0;i<3;i++)
{
printf("%d\n",vetor[i]);
}
printf("\n");
for(i=0;i<3;i++)
{
printf("%d\n",aux[i]);
}
return 0;
}
| 3.28125 | 3 |
2024-11-18T21:19:04.835707+00:00 | 2017-07-18T04:09:39 | 79c28a00d670141bf2305fd02a53b1c21b35ca94 | {
"blob_id": "79c28a00d670141bf2305fd02a53b1c21b35ca94",
"branch_name": "refs/heads/main",
"committer_date": "2017-07-18T04:09:39",
"content_id": "ab72ee62959ec7130d808b66316e92418b2eda65",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "5ea4cc34ed3ec98ba9163cb39584e0f730509e4f",
"extension": "c",
"filename": "response.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 97422659,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6357,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/file_transfer/response.c",
"provenance": "stackv2-0128.json.gz:300025",
"repo_name": "dengqiaoyu/Network_Backend_Application",
"revision_date": "2017-07-18T04:09:39",
"revision_id": "02a464378af4b32046109082e83d6c0882e74d13",
"snapshot_id": "aebc623ea2de1987a1125ea9de6a93e7797b356f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dengqiaoyu/Network_Backend_Application/02a464378af4b32046109082e83d6c0882e74d13/file_transfer/response.c",
"visit_date": "2021-01-01T06:24:38.188346"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bt_parse.h"
#include "constant.h"
#include "packet.h"
#include "request.h"
#include "response.h"
#include "send.h"
#include "chunk.h"
#include "hashtable.h"
#include "debug.h"
extern bt_config_t config;
response_struct *init_response_list()
{
response_struct *response_list = malloc(sizeof(response_struct));
memset(response_list, 0, sizeof(response_struct));
response_list->whohas_ptr = malloc(sizeof(response_item_struct));
return response_list;
}
inline char get_packet_type(packet_sturct *packet)
{
return *packet->packet_type;
}
inline unsigned short get_packet_len(packet_sturct *packet)
{
return *(unsigned short *)packet->total_packet_length;
}
ssize_t init_responses(response_struct *response_list, char *buf,
unsigned short buflen,
char *peer_addr, unsigned short peer_port)
{
unsigned short bufoffset = 0;
response_item_struct *last_whohas =
find_last_rep_ptr(response_list->whohas_ptr);
while (bufoffset < buflen)
{
packet2host((packet_sturct *)(buf + bufoffset));
char packet_type = get_packet_type((packet_sturct *)(buf + bufoffset));
unsigned short packet_len =
get_packet_len((packet_sturct *)(buf + bufoffset));
dbg_cp1_printf("packet_type: %d, packet_len: %hu\n",
packet_type, packet_len);
if (packet_len > buflen - bufoffset)
{
return -1;
}
switch ((int)packet_type)
{
case 0: // WHOHAS
dbg_cp1_printf("Entering WHOHAS\n");
last_whohas->next = malloc(sizeof(response_item_struct));
last_whohas = last_whohas->next;
memset(last_whohas, 0, sizeof(response_item_struct));
strncpy(last_whohas->peer_addr, peer_addr, 16);
last_whohas->peer_port = peer_port;
last_whohas->packet_ptr = malloc(packet_len);
memset(last_whohas->packet_ptr, 0, packet_len);
memcpy(last_whohas->packet_ptr, (packet_sturct *)buf + bufoffset,
packet_len);
break;
case 1:
dbg_cp1_printf("Entering IHAS\n");
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
break;
}
bufoffset += packet_len;
}
return 0;
}
ssize_t process_request(response_struct *response_list,
packet2send_sturct *sending_list,
hashtable_t *haschunk_hash_table)
{
response_item_struct *whohas_rover_last = response_list->whohas_ptr;
response_item_struct *whohas_rover = whohas_rover_last->next;
dbg_cp1_printf("process_request start!!!!!!!!!!!!!!!!\n");
while (whohas_rover != NULL)
{
packet2send_sturct *packet2send = get_ihave_response(whohas_rover,
haschunk_hash_table);
if (packet2send != NULL)
{
packet_add2sending_list(packet2send, sending_list);
#ifdef DEBUG_CP1
printf_packet(packet2send->packet_ptr);
#endif
}
whohas_rover_last->next = whohas_rover->next;
free(whohas_rover->packet_ptr);
free(whohas_rover);
whohas_rover = whohas_rover_last->next;
}
return 0;
}
packet2send_sturct *get_ihave_response(response_item_struct *response_item,
hashtable_t *haschunk_hash_table)
{
packet2send_sturct *ihave = NULL;
unsigned short *total_packet_length = NULL;
char *ihave_chunk_num = NULL;
unsigned short ihave_pay_load_offset = 0;
char *ihave_pay_load = NULL;
char *response_pay_load = response_item->packet_ptr->pay_load;
char response_chunk_num = *response_pay_load;
// dbg_cp1_printf("##response_chunk_num##: %d\n", response_chunk_num);
char i;
for (i = 0; i < response_chunk_num; i++)
{
char chunk_hash_hex[41] = {0};
binary2hex((uint8_t *)response_pay_load + 4 + i * 20, 20,
chunk_hash_hex);
// dbg_cp1_printf("chunk hash hex:%s\n", chunk_hash_hex);
int ret = ht_exists(haschunk_hash_table, chunk_hash_hex, 40);
// dbg_cp1_printf("ret: %d\n", ret);
if (ret == 1)
{
if (ihave == NULL)
{
ihave = malloc(sizeof(packet2send_sturct));
memset(ihave, 0, sizeof(packet2send_sturct));
set_ip_port(ihave, response_item->peer_addr,
response_item->peer_port);
ihave->packet_ptr = init_packet();
*(ihave->packet_ptr->packet_type) = 1;
total_packet_length =
(unsigned short *)ihave->packet_ptr->total_packet_length;
ihave_chunk_num = ihave->packet_ptr->pay_load;
ihave_pay_load = ihave->packet_ptr->pay_load;
*total_packet_length = 40;
*ihave_chunk_num = 1;
ihave_pay_load_offset = 4;
memcpy(ihave_pay_load + ihave_pay_load_offset,
response_pay_load + 4 + i * 20, 20);
ihave_pay_load_offset += 20;
}
else
{
*ihave_chunk_num = *ihave_chunk_num + 1;
*total_packet_length += 20;
memcpy(ihave_pay_load + ihave_pay_load_offset,
response_pay_load + 4 + i * 20, 20);
ihave_pay_load_offset += 20;
}
}
}
return ihave;
}
void packet_add2sending_list(packet2send_sturct *packet2send,
packet2send_sturct *sending_list)
{
packet2send_sturct *last = find_last_send_ptr(sending_list);
last->next = packet2send;
packet2send->next = NULL;
}
inline response_item_struct *find_last_rep_ptr(response_item_struct *item_ptr)
{
response_item_struct *rover = item_ptr;
while (rover->next != NULL)
{
rover = rover->next;
}
return rover;
} | 2.140625 | 2 |
2024-11-18T21:19:04.928917+00:00 | 2018-09-22T03:33:15 | 2a51b318405a003233f43af44574ec9c15deea43 | {
"blob_id": "2a51b318405a003233f43af44574ec9c15deea43",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-22T03:33:15",
"content_id": "1ef2d04ce4ed594991e487264a44bdf260ca1a61",
"detected_licenses": [
"MIT"
],
"directory_id": "ee24ba563cf8d7c5bb8c95ae8e10233b476b97cf",
"extension": "h",
"filename": "v2AsmMath.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 149842030,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8319,
"license": "MIT",
"license_type": "permissive",
"path": "/Editor/NativePlugin/RayTrace/src/core/Math/v2AsmMath.h",
"provenance": "stackv2-0128.json.gz:300154",
"repo_name": "wachel/block",
"revision_date": "2018-09-22T03:33:15",
"revision_id": "c04b4531f19ae3373e5dbec403af9c90719fc581",
"snapshot_id": "32f8334a70d053cdf9dc3eb0215f35ba9a1d788b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wachel/block/c04b4531f19ae3373e5dbec403af9c90719fc581/Editor/NativePlugin/RayTrace/src/core/Math/v2AsmMath.h",
"visit_date": "2020-03-29T11:13:28.371466"
} | stackv2 | //// This file is part of Origo Engine.
//// Copyright (C), Beijing Tuyasoft Co., Ltd.
///*
//-------------------------------------------------------------------------------
//Notes:
//This file is part of Origo Engine.
//The original version is from flipcode forums(http://www.flipcode.com/).
//ASM math routines posted by davepermen et al on flipcode forums
//-------------------------------------------------------------------------------
//*/
//
//#ifndef OO_ASM_MATH_
//#define OO_ASM_MATH_
//#include "..\Common\v2ObjStd.h"
//OO_NAMESPACE_BEGIN
//
//const float pi = 4.0*atan(1.0);
//const float half_pi = 0.5*pi;
//// ASM math routines posted by davepermen et al on flipcode forums
////----------------------------------------------------------------------------------------------------------
//// NB NO EXPLICIT RETURN REQUIRED FROM THESE METHODS!!
//#pragma warning( push )
//#pragma warning( disable: 4035 )
////----------------------------------------------------------------------------------------------------------
//inline float asm_arccos( float r )
//{
// // return half_pi + arctan( r / -sqr( 1.f - r * r ) );
// float asm_one = 1.f;
// float asm_half_pi = half_pi;
//#if defined( _MSC_VER )
//# ifdef _M_X64
// return acos(r);
//# else
// __asm {
// fld r // r0 = r
// fld r // r1 = r0, r0 = r
// fmul r // r0 = r0 * r
// fsubr asm_one // r0 = r0 - 1.f
// fsqrt // r0 = sqrtf( r0 )
// fchs // r0 = - r0
// fdiv // r0 = r1 / r0
// fld1 // {{ r0 = atan( r0 )
// fpatan // }}
// fadd asm_half_pi // r0 = r0 + pi / 2
// } // returns r0
//# endif
//#elif defined( __GNUC__ )
// asm("fld %0" : "=f" (r));
// asm("fld %0" : "=f" (r));
// asm("fmul %0" : "=f" (r));
// asm("fsubr %0" : "=f" (asm_one));
// asm("fsqrt");
// asm("fchs");
// asm("fdiv");
// asm("fld1");
// asm("fpatan");
// asm("fadd %0" : "=f" (asm_half_pi));
//#endif
//
//}
//
//inline float asm_arcsin( float r ) {
// // return arctan( r / sqr( 1.f - r * r ) );
// const float asm_one = 1.f;
//#if defined( _MSC_VER )
//# ifdef _M_X64
// return asin(r);
//# else
// __asm {
// fld r // r0 = r
// fld r // r1 = r0, r0 = r
// fmul r // r0 = r0 * r
// fsubr asm_one // r0 = r0 - 1.f
// fsqrt // r0 = sqrtf( r0 )
// fdiv // r0 = r1 / r0
// fld1 // {{ r0 = atan( r0 )
// fpatan // }}
// } // returns r0
//# endif
//#elif defined( __GNUC__ )
// asm("fld %0" : "=f" (r));
// asm("fld %0" : "=f" (r));
// asm("fmul %0" : "=f" (r));
// asm("fsubr %0" : "=f" (asm_one));
// asm("fsqrt");
// asm("fdiv");
// asm("fld1");
// asm("fpatan");
//#endif
//
//}
//
//inline float asm_arctan( float r ) {
//#if defined( _MSC_VER )
//# ifdef _M_X64
// return atan(r);
//# else
// __asm {
// fld r // r0 = r
// fld1 // {{ r0 = atan( r0 )
// fpatan // }}
// } // returns r0
//# endif
//#elif defined( __GNUC__ )
// asm("fld %0" : "=f" (r));
// asm("fld1");
// asm("fpatan");
//#endif
//
//}
//
//inline float asm_sin( float r ) {
//#ifdef _MSC_VER
//# ifdef _M_X64
// return asin(r);
//# else
// __asm {
// fld r // r0 = r
// fsin // r0 = sinf( r0 )
// } // returns r0
//# endif
//#elif defined( __GNUC__ )
// asm("fld %0" : "=f" (r));
// asm("fsin");
//#endif
//
//}
//
//inline float asm_cos( float r ) {
//#ifdef _MSC_VER
//# ifdef _M_X64
// return acos(r);
//# else
// __asm {
// fld r // r0 = r
// fcos // r0 = cosf( r0 )
// } // returns r0
//# endif
//#elif defined( __GNUC__ )
// asm("fld %0" : "=f" (r));
// asm("fcos");
//#endif
//
//}
//
//inline float asm_tan( float r ) {
//#ifdef _MSC_VER
//# ifdef _M_X64
// return tan(r);
//# else
// // return sin( r ) / cos( r );
// __asm {
// fld r // r0 = r
// fsin // r0 = sinf( r0 )
// fld r // r1 = r0, r0 = r
// fcos // r0 = cosf( r0 )
// fdiv // r0 = r1 / r0
// } // returns r0
//# endif
//#elif defined( __GNUC__ )
// asm("fld %0" : "=f" (r));
// asm("fsin");
// asm("fld %0" : "=f" (r));
// asm("fcos");
// asm("fdiv");
//#endif
//
//}
//
//inline float asm_sqrt( float r ) {
// // returns a for a * a = r
//#ifdef _MSC_VER
//# ifdef _M_X64
// return sqrt(r);
//# else
// __asm {
// fld r // r0 = r
// fsqrt // r0 = sqrtf( r0 )
// } // returns r0
//# endif
//#elif defined( __GNUC__ )
// asm("fld %0" : "=f" (r));
// asm("fsqrt");
//#endif
//
//}
//
//// -- Use this for Vector normalisation!!!
//inline float asm_rsq( float r ) {
// // returns 1 / a for a * a = r
//#ifdef _MSC_VER
//# ifdef _M_X64
// return 1.f/sqrt(r);
//# else
// __asm {
// fld1 // r0 = 1.f
// fld r // r1 = r0, r0 = r
// fsqrt // r0 = sqrtf( r0 )
// fdiv // r0 = r1 / r0
// } // returns r0
//# endif
//#elif defined( __GNUC__ )
// asm("fld1");
// asm("fld %0" : "=f" (r));
// asm("fsqrt");
// asm("fdiv");
//#endif
//
//}
//
////// Another version
////inline float apx_rsq( float r ) {
//// // returns 1 / a for a * a = r
//// const float asm_dot5 = 0.5f;
//// const float asm_1dot5 = 1.5f;
////
////#ifdef _MSC_VER
//// __asm {
//// fld r // r0 = r
//// fmul asm_dot5 // r0 = r0 * .5f
//// mov eax, r // eax = r
//// shr eax, 0x1 // eax = eax >> 1
//// neg eax // eax = -eax
//// add eax, 0x5F400000 // eax = eax & MAGICAL NUMBER
//// mov r, eax // r = eax
//// fmul r // r0 = r0 * r
//// fmul r // r0 = r0 * r
//// fsubr asm_1dot5 // r0 = 1.5f - r0
//// fmul r // r0 = r0 * r
//// } // returns r0
////#elif defined( __GNUC__ )
//// asm("fld %0" : "=f" (r));
//// asm("fmul %0" : "=f" (asm_dot5));
//// asm("mov eax, %0" : "f" (r));
//// asm("shr eax, 0x1");
//// asm("neg eax");
//// asm("add eax, 0x5F400000");
//// asm("mov %0, eax" : "=f" (r));
//// asm("fmul %0" : "=f" (r));
//// asm("fmul %0" : "=f" (r));
//// asm("fsubr %0" : "f" (asm_1dot5));
//// asm("fmul %0" : "=f" (r));
////#endif
////
////}
//
/////* very MS-specific, commented out for now
////// Finally the best InvSqrt implementation?
////// Use for vector normalisation instead of 1/length() * x,y,z
////*/
////#ifdef _MSC_VER
////
////inline __declspec(naked) float __fastcall InvSqrt(float fValue)
////{
//// __asm
//// {
//// mov eax, 0be6eb508h
//// mov dword ptr[esp-12],03fc00000h
//// sub eax, dword ptr[esp + 4]
//// sub dword ptr[esp+4], 800000h
//// shr eax, 1
//// mov dword ptr[esp - 8], eax
////
//// fld dword ptr[esp - 8]
//// fmul st, st
//// fld dword ptr[esp - 8]
//// fxch st(1)
//// fmul dword ptr[esp + 4]
//// fld dword ptr[esp - 12]
//// fld st(0)
//// fsub st,st(2)
////
//// fld st(1)
//// fxch st(1)
//// fmul st(3),st
//// fmul st(3),st
//// fmulp st(4),st
//// fsub st,st(2)
////
//// fmul st(2),st
//// fmul st(3),st
//// fmulp st(2),st
//// fxch st(1)
//// fsubp st(1),st
////
//// fmulp st(1), st
//// ret 4
//// }
////}
////
////#endif
//
////inline float asm_ln( float r ) {
//// // returns log2( r ) / log2( e )
//// const float asm_e = 2.71828182846f;
//// const float asm_1_div_log2_e = .693147180559f;
//// const float asm_neg1_div_3 = -.33333333333333333333333333333f;
//// const float asm_neg2_div_3 = -.66666666666666666666666666667f;
//// const float asm_2 = 2.f;
////
//// int log_2 = 0;
////#ifdef _MSC_VER
//// __asm {
//// // log_2 = ( ( r >> 0x17 ) & 0xFF ) - 0x80;
//// mov eax, r
//// sar eax, 0x17
//// and eax, 0xFF
//// sub eax, 0x80
//// mov log_2, eax
////
//// // r = ( r & 0x807fffff ) + 0x3f800000;
//// mov ebx, r
//// and ebx, 0x807FFFFF
//// add ebx, 0x3F800000
//// mov r, ebx
////
//// // r = ( asm_neg1_div_3 * r + asm_2 ) * r + asm_neg2_div_3; // (1)
//// fld r
//// fmul asm_neg1_div_3
//// fadd asm_2
//// fmul r
//// fadd asm_neg2_div_3
//// fild log_2
//// fadd
//// fmul asm_1_div_log2_e
//// }
////#elif defined( __GNUC__ )
//// asm("mov eax, r");
//// asm("sar eax, 0x17");
//// asm("and eax, 0xFF");
//// asm("sub eax, 0x80");
//// asm("mov log_2, eax");
//// asm("mov ebx, r");
//// asm("mov ebx, 0x807FFFFF");
//// asm("add ebx, 0x3F800000");
//// asm("mov r, ebx");
//// asm("fld r");
//// asm("fmul asm_neg1_div_3");
//// asm("fadd asm_2");
//// asm("fmul r");
//// asm("fadd asm_neg2_div_3");
//// asm("fild log_2");
//// asm("fadd");
//// asm("fmul asm_1_div_log2_e");
////#endif
////
////}
//
//#pragma warning( pop )
//
//OO_NAMESPACE_END
//
//#endif // #ifndef OO_ASM_MATH_
| 2.21875 | 2 |
2024-11-18T21:19:05.097881+00:00 | 2019-11-20T22:58:58 | c0802052f5ee4ccc13da8a5ad992582f6073f6bd | {
"blob_id": "c0802052f5ee4ccc13da8a5ad992582f6073f6bd",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-20T22:58:58",
"content_id": "bb947091d1ae05d1faf535be71e778bdc2728759",
"detected_licenses": [
"MIT"
],
"directory_id": "11bcd6995467b94c01754d46ddb0ccccce1e232d",
"extension": "c",
"filename": "semaphore_example.c",
"fork_events_count": 0,
"gha_created_at": "2018-09-08T20:44:03",
"gha_event_created_at": "2020-10-13T16:10:13",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 147968540,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1323,
"license": "MIT",
"license_type": "permissive",
"path": "/enrolled/os-intro-CS2106/lab-3/ex-2/demo/semaphore_example.c",
"provenance": "stackv2-0128.json.gz:300417",
"repo_name": "plty/nus",
"revision_date": "2019-11-20T22:58:58",
"revision_id": "3d75b6d1c54022a42edbc15317507ddc988a7231",
"snapshot_id": "5f647dfc06873accc9bf340287a75d82c24a0054",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/plty/nus/3d75b6d1c54022a42edbc15317507ddc988a7231/enrolled/os-intro-CS2106/lab-3/ex-2/demo/semaphore_example.c",
"visit_date": "2021-06-27T14:18:31.592531"
} | stackv2 | /*************************************
* Lab 3 Exercise 2
* Name:
* Matric No:
* Lab Group:
*************************************/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <semaphore.h>
int main()
{
int result, i, sV[3], aV[3];
int shdMemIdForS;
sem_t* semPtr;
//Create a shared memory region for Semaphore
shdMemIdForS = shmget( IPC_PRIVATE, sizeof(sem_t), IPC_CREAT | 0666 );
semPtr = (sem_t*) shmat(shdMemIdForS, NULL, 0);
sem_init(semPtr, 1, 1);
result = fork();
if (result){ //Parent
for(i = 0; i < 3; i++){
//TODO: how to protect?
printf("p\n");
sleep(3);
}
wait(NULL);
/*Important: Remember to detach the shared memory region*/
shmdt( (char*)semPtr );
} else { //Child
for(i = 0; i < 3; i++){
//TODO: how to protect?
printf("c\n");
sleep(1);
}
/*Important: Remember to detach the shared memory region*/
shmdt( (char*)semPtr );
return 0; //Child Ends here
}
/*Important: Remember to remove the shared memory region after use!*/
shmctl(shdMemIdForS, IPC_RMID, NULL);
return 0;
}
| 2.9375 | 3 |
2024-11-18T21:19:05.266592+00:00 | 2018-10-28T16:24:13 | 905a8a030454f5cbeac5334e78ee95b7094c6be8 | {
"blob_id": "905a8a030454f5cbeac5334e78ee95b7094c6be8",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-28T16:24:13",
"content_id": "e3a281c7aa84efa1a5382d61e92a40417ab8962e",
"detected_licenses": [
"MIT"
],
"directory_id": "7ddb2face914e04bad2ab54c0e02354596d7c21d",
"extension": "c",
"filename": "p6_1.c",
"fork_events_count": 6,
"gha_created_at": "2016-09-21T09:23:45",
"gha_event_created_at": "2018-10-28T10:44:22",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 68801193,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 890,
"license": "MIT",
"license_type": "permissive",
"path": "/src/av6/p6_1.c",
"provenance": "stackv2-0128.json.gz:300546",
"repo_name": "finki-mk/SP",
"revision_date": "2018-10-28T16:24:13",
"revision_id": "da1fffce9ba1096283f54ffa6a175b01900c335c",
"snapshot_id": "338101118c96cca422b4b060afe783663270d42d",
"src_encoding": "UTF-8",
"star_events_count": 16,
"url": "https://raw.githubusercontent.com/finki-mk/SP/da1fffce9ba1096283f54ffa6a175b01900c335c/src/av6/p6_1.c",
"visit_date": "2020-05-30T13:56:13.676368"
} | stackv2 | #include<stdio.h>
#define MAX 100
int main() {
int n1, n2, element, i;
int a[MAX], b[MAX];
printf("Golemina na prvata niza: ");
scanf("%d", &n1);
printf("Golemina na vtorata niza: ");
scanf("%d", &n2);
if (n1 != n2)
printf("Nizite ne se ednakvi\n");
else {
printf("Elementi na prvata niza: \n");
for (i = 0; i < n1; ++i) {
printf("a[%d] = ", i);
scanf("%d", &a[i]);
}
printf("Elementi na vtorata niza: \n");
for (i = 0; i < n2; ++i) {
printf("b[%d] = ", i);
scanf("%d", &b[i]);
}
// check if arrays are equal:
for (i = 0; i < n1; ++i)
if (a[i] != b[i])
break;
if (i == n1)
printf("Nizite se ednakvi\n");
else
printf("Nizite ne se ednakvi\n");
}
return 0;
}
| 3.4375 | 3 |
2024-11-18T21:19:05.347177+00:00 | 2019-08-06T14:32:58 | 6905296b727659609bdbfd9149684136a0f32507 | {
"blob_id": "6905296b727659609bdbfd9149684136a0f32507",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-06T14:32:58",
"content_id": "05f514c406e710cc22c2f8ecc397b9de9b494df6",
"detected_licenses": [
"MIT"
],
"directory_id": "f9d5cd60a025baace28e783d97ef7cb4c686bc72",
"extension": "c",
"filename": "JSON_parser.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 157360906,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2879,
"license": "MIT",
"license_type": "permissive",
"path": "/source/json_parser/JSON_parser.c",
"provenance": "stackv2-0128.json.gz:300677",
"repo_name": "Infineon/personalize-optiga-trust-x",
"revision_date": "2019-08-06T14:32:58",
"revision_id": "b083559a7b94dc3820db1536f5cbff4083129a6f",
"snapshot_id": "5003bff267a64d1150566978b59172d28f335284",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/Infineon/personalize-optiga-trust-x/b083559a7b94dc3820db1536f5cbff4083129a6f/source/json_parser/JSON_parser.c",
"visit_date": "2020-04-06T09:53:43.847112"
} | stackv2 | /*
* Hello_cJSON.c
*
* Created on: 16.01.2018
* Author: pi
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include "cJSON.h"
#include "JSON_parser.h"
int c_JSON_read_file (const char *path, char **buffer, int *file_length) {
FILE *in = fopen(path, "r");
if (!in) {
printf("Opening file failed!\n"); return(-1);
}
fseek(in, 0L, SEEK_END);
long lSize = ftell(in);
rewind(in);
/* allocate memory for entire content */
*buffer = malloc(lSize+1);
if ( !*buffer ) fclose(in), printf("Memory alloc fails\n"), exit(1);
/* copy the file into the buffer */
if( 1!=fread( *buffer, lSize, 1 , in)) {
fclose(in), free(*buffer), printf("Entire read fails\n"), exit(1);
}
*file_length = (int) lSize;
fclose(in);
return 0;
}
void c_JSON_print_string_pointer_as_string (char *t) {
if(*t == '\0') {
return;
}
printf("%c", *t);
c_JSON_print_string_pointer_as_string(++t);
}
char * c_JSON_CSR_print (cJSON * json, char * string)
{
const cJSON * object = cJSON_GetObjectItemCaseSensitive(json, string);
if(object) {
char * buf = calloc((strlen(string)+1), sizeof(char));
strcat(buf, string);
strcat(buf, "=");
char * print = cJSON_Print(object);
const char * com = ",";
print = print+1;
print[strlen(print)-1] = '\0';
char * str = calloc((strlen(buf)+strlen(com)+strlen(print)), sizeof(char));
strcat(str, buf);
strcat(str, print);
strcat(str, com);
return str;
}
else {
return NULL;
}
}
char * c_JSON_read_config (const char * filepath) {
char * buffer = NULL;
int file_length = 0;
int retVal = c_JSON_read_file(filepath, &buffer, &file_length);
if(retVal) {
printf("Reading not successful!\n");
return NULL;
}
printf("Data read:\n");
c_JSON_print_string_pointer_as_string(buffer);
cJSON *json = cJSON_Parse(buffer);
if (json == NULL){
printf("Not a JSON file\n");
return NULL;
}
char * CN = c_JSON_CSR_print(json, "CN");
char * O = c_JSON_CSR_print(json, "O");
char * C = c_JSON_CSR_print(json, "C");
char * ST = c_JSON_CSR_print(json, "ST");
char * OU = c_JSON_CSR_print(json, "OU");
char * email = c_JSON_CSR_print(json, "emailAddress");
int length = 0;
if (CN) {
length += strlen(CN);
} else {
printf("Major Error: CN not existent!");
return NULL;
}
if (O) {
length += strlen(O);
}
if (C) {
length += strlen(C);
}
if (ST) {
length += strlen(ST);
}
if (OU) {
length += strlen(OU);
}
if (email) {
length += strlen(email);
}
char * csr_return = calloc(length, sizeof(char));
strcat(csr_return, CN);
if (O) {
strcat(csr_return, O);
}
if (C) {
strcat(csr_return, C);
}
if (ST) {
strcat(csr_return, ST);
}
if (OU) {
strcat(csr_return, OU);
}
if (email) {
strcat(csr_return, email);
}
//remove last ","
csr_return[strlen(csr_return)-1] = '\0';
return csr_return;
}
| 2.90625 | 3 |
2024-11-18T21:19:05.432583+00:00 | 2022-12-08T03:34:58 | 8358e279fb27e9d0b384ca4420bbae7c3d6301bd | {
"blob_id": "8358e279fb27e9d0b384ca4420bbae7c3d6301bd",
"branch_name": "refs/heads/develop",
"committer_date": "2022-12-08T03:34:58",
"content_id": "62cd3983144fd1f201c7fddf394e1ef7770d6370",
"detected_licenses": [
"MIT"
],
"directory_id": "7d21462e3775644b03dc8fb2535aac09bb095859",
"extension": "c",
"filename": "sub_utils.c",
"fork_events_count": 20,
"gha_created_at": "2018-09-25T02:28:48",
"gha_event_created_at": "2022-12-08T03:34:59",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 150196401,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3996,
"license": "MIT",
"license_type": "permissive",
"path": "/connectivity/mqtt/sub_utils.c",
"provenance": "stackv2-0128.json.gz:300805",
"repo_name": "DLTcollab/tangle-accelerator",
"revision_date": "2022-12-08T03:34:58",
"revision_id": "c775a7834301a34c76bc5f2bd953a4891e46e732",
"snapshot_id": "552161d97ac5acb4472ef193f7291044e2a321a5",
"src_encoding": "UTF-8",
"star_events_count": 24,
"url": "https://raw.githubusercontent.com/DLTcollab/tangle-accelerator/c775a7834301a34c76bc5f2bd953a4891e46e732/connectivity/mqtt/sub_utils.c",
"visit_date": "2023-08-29T05:49:18.679733"
} | stackv2 | /*
* Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors
* All Rights Reserved.
* This is free software; you can redistribute it and/or modify it under the
* terms of the MIT license. A copy of the license can be found in the file
* "LICENSE" at the root of this distribution.
*/
#include "sub_utils.h"
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include "common/logger.h"
#define MQTT_SUB_LOGGER "sub_utils"
static logger_id_t logger_id;
void mqtt_sub_logger_init() { logger_id = logger_helper_enable(MQTT_SUB_LOGGER, LOGGER_DEBUG, true); }
int mqtt_sub_logger_release() {
logger_helper_release(logger_id);
if (logger_helper_destroy() != RC_OK) {
ta_log_error("Destroying logger failed %s.\n", MQTT_SUB_LOGGER);
return EXIT_FAILURE;
}
return 0;
}
static status_t dump_message(mosq_config_t *cfg, const struct mosquitto_message *message) {
if (cfg == NULL || message == NULL || message->payload == NULL || message->payloadlen == 0) {
ta_log_error("%s\n", ta_error_to_string(SC_NULL));
return SC_NULL;
}
cfg->sub_config->recv_message = strdup(message->payload);
return SC_OK;
}
void publish_callback_sub_func(struct mosquitto *mosq, void *obj, int mid, int reason_code,
const mosquitto_property *properties) {
mosq_config_t *cfg = (mosq_config_t *)obj;
UNUSED(reason_code);
UNUSED(properties);
if ((mid == cfg->general_config->last_mid || cfg->general_config->last_mid == 0)) {
mosquitto_disconnect_v5(mosq, 0, cfg->property_config->disconnect_props);
}
}
void message_callback_sub_func(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message,
const mosquitto_property *properties) {
mosq_config_t *cfg = (mosq_config_t *)obj;
UNUSED(properties);
if (cfg->sub_config->remove_retained && message->retain) {
mosquitto_publish(mosq, &cfg->general_config->last_mid, message->topic, 0, NULL, 1, true);
}
if (cfg->sub_config->retained_only && !message->retain) {
if (cfg->general_config->last_mid == 0) {
mosquitto_disconnect_v5(mosq, 0, cfg->property_config->disconnect_props);
}
return;
}
if (message->retain && cfg->sub_config->no_retain) return;
// Copy the message into `cfg` to allow other functions use the message
dump_message(cfg, message);
// Uncomment the following code would cause: once we received a message, then disconnect the connection.
// mosquitto_disconnect_v5(mosq, 0, cfg->property_config->disconnect_props);
}
void connect_callback_sub_func(struct mosquitto *mosq, void *obj, int result, int flags,
const mosquitto_property *properties) {
mosq_config_t *cfg = (mosq_config_t *)obj;
UNUSED(flags);
UNUSED(properties);
if (!result) {
mosquitto_subscribe_multiple(mosq, NULL, cfg->sub_config->topic_count, cfg->sub_config->topics,
cfg->general_config->qos, 0, cfg->property_config->subscribe_props);
for (int i = 0; i < cfg->sub_config->unsub_topic_count; i++) {
mosquitto_unsubscribe_v5(mosq, NULL, cfg->sub_config->unsub_topics[i], cfg->property_config->unsubscribe_props);
}
} else {
if (result) {
if (cfg->general_config->protocol_version == MQTT_PROTOCOL_V5) {
ta_log_error(":%s\n", mosquitto_reason_string(result));
} else {
ta_log_error(":%s\n", mosquitto_connack_string(result));
}
}
mosquitto_disconnect_v5(mosq, 0, cfg->property_config->disconnect_props);
}
}
void subscribe_callback_sub_func(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) {
UNUSED(mosq);
UNUSED(obj);
char *qos_str = (char *)calloc(qos_count, 3);
char qos_digit[4];
for (int i = 1; i < qos_count; i++) {
snprintf(qos_digit, 4, ", %d", granted_qos[i]);
strcat(qos_str, qos_digit);
}
log_info(logger_id, "Subscribed (mid: %d): %d%s\n", mid, granted_qos[0], qos_str);
free(qos_str);
}
| 2.046875 | 2 |
2024-11-18T21:19:05.560655+00:00 | 2019-11-15T20:21:59 | 66cf84dc2c121b2a36262796cb0414bc823d41e3 | {
"blob_id": "66cf84dc2c121b2a36262796cb0414bc823d41e3",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-15T20:21:59",
"content_id": "2fe8353bd3057ac101cfcbb2fd027422fe4d245b",
"detected_licenses": [
"Unlicense"
],
"directory_id": "1f04e26bf8d0153a0d714dbc76187ac53ca0a626",
"extension": "c",
"filename": "11.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1327,
"license": "Unlicense",
"license_type": "permissive",
"path": "/Programming/Labs/7/Examples/11.c",
"provenance": "stackv2-0128.json.gz:300935",
"repo_name": "ffaawgh/University",
"revision_date": "2019-11-15T20:21:59",
"revision_id": "764f668f840da3d4169914244c9b42750d96ab20",
"snapshot_id": "d6604b4993a55e87229c5f70437ee2f2d8a3fe77",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ffaawgh/University/764f668f840da3d4169914244c9b42750d96ab20/Programming/Labs/7/Examples/11.c",
"visit_date": "2022-03-22T13:40:56.103381"
} | stackv2 | #include <stdio.h>
/* Function prototypes */
int sum(int, int);
int product(int, int);
int difference(int, int);
void main()
{
int i = 0; /* Loop counter */
int a = 10; /* Initial value for a */
int b = 5; /* Initial value for b */
int result = 0; /* Storage for results */
int (*pfun[3])(int, int); /* Function pointer array declaration */
/* Initialize pointers */
pfun[0] = sum;
pfun[1] = product;
pfun[2] = difference;
/* Execute each function pointed to */
for( i = 0 ; i < 3 ; i++)
{
result = pfun[i](a, b); /* Call the function through a pointer */
printf("\nresult = %d", result); /* Display the result */
}
/* Call all three functions through pointers in an expression */
result = pfun[1](pfun[0](a, b), pfun[2](a, b));
printf("\n\nThe product of the sum and the difference = %d", result );
}
/* Definition of the function sum */
int sum(int x, int y)
{
return x + y;
}
/* Definition of the function product */
int product(int x, int y)
{
return x * y;
}
/* Definition of the function difference */
int difference(int x, int y)
{
return x - y;
}
| 3.796875 | 4 |
2024-11-18T21:19:05.860879+00:00 | 2018-10-30T21:20:46 | 58a13234a4805c49863374fbb05f1c6c27ccb419 | {
"blob_id": "58a13234a4805c49863374fbb05f1c6c27ccb419",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-30T21:20:46",
"content_id": "41e8ede97c4cbb876127e4ea988b820c6cedc502",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a06dd6ea78c230a963a1cdb78851555f902b5550",
"extension": "c",
"filename": "multi_reading_linsolve.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 143794371,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3289,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/precomputation/multi_reading_linsolve.c",
"provenance": "stackv2-0128.json.gz:301063",
"repo_name": "kevinjlang/cpc",
"revision_date": "2018-10-30T21:20:46",
"revision_id": "fda96c0ea51d0972a8ca081c24e04e036945ecbb",
"snapshot_id": "643324c2edb60dd7eaebfbfcd7f41994871f35a7",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/kevinjlang/cpc/fda96c0ea51d0972a8ca081c24e04e036945ecbb/precomputation/multi_reading_linsolve.c",
"visit_date": "2020-03-25T12:48:08.733881"
} | stackv2 | // Copyright 2018, Kevin Lang, Oath Research
/*
gcc -Wall -pedantic -Iinclude -Llib -o multi_reading_linsolve multi_reading_linsolve.c -lgsl -lgslcblas
*/
#include <stdio.h>
#include <assert.h>
#include <gsl/gsl_linalg.h>
/*****************************************************************************/
#ifdef EXAMPLE_FOR_INTUITION
#define NUMEQNS 5
#define NUMVARS 4
double a_data[] =
{ 0.18, 0.60, 0.57, 0.96,
0.41, 0.24, 0.99, 0.58,
0.14, 0.30, 0.97, 0.66,
0.51, 0.13, 0.19, 0.85,
0.65, 0.43, 1.16, 1.51
};
double b_data[] =
{ 1.0, 2.0, 3.0, 4.0,
7.0
};
#endif
/*****************************************************************************/
void read_a_data (int num_eqns, int num_vars, double * a_data) {
int i, j, nxt;
double tmp;
nxt = 0;
for (i = 0; i < num_eqns; i++) {
for (j = 0; j < num_vars; j++) {
int got = scanf ("%lf", &tmp);
assert (got == 1);
a_data[nxt++] = tmp;
}
}
assert (nxt == num_eqns * num_vars);
}
/*****************************************************************************/
void read_b_data (int num_eqns, double * b_data) {
int i, nxt;
double tmp;
nxt = 0;
for (i = 0; i < num_eqns; i++) {
int got = scanf ("%lf", &tmp);
assert (got == 1);
b_data[nxt++] = tmp;
}
assert (nxt == num_eqns);
}
/*****************************************************************************/
int main (int argc, char ** argv)
{
if (argc != 3) {
fprintf (stderr, "Usage: %s num_eqns num_vars < data_file\n", argv[0]);
fprintf (stderr, " The data_file contains a matrix followed by a target vector.\n");
fprintf (stderr, " The matrix should be in equation major order.\n");
fprintf (stderr, " This version solves multiple problems with matching matrix dimensions.\n");
fprintf (stderr, " Each problem should be preceding by a '1'.\n");
fprintf (stderr, " The last problem should be followed by a '0'.\n");
return (-1);
}
int num_eqns = atoi(argv[1]);
int num_vars = atoi(argv[2]);
double * a_data = (double *) malloc (num_eqns * num_vars * sizeof(double));
assert (a_data != NULL);
double * b_data = (double *) malloc (num_eqns * sizeof(double));
assert (b_data != NULL);
while (1) {
int keep_going = 0;
int got = scanf ("%d", &keep_going);
assert (got == 1);
if (keep_going == 0) return 0;
read_a_data (num_eqns, num_vars, a_data);
read_b_data (num_eqns, b_data);
gsl_matrix_view m = gsl_matrix_view_array (a_data, num_eqns, num_vars);
gsl_vector *x = gsl_vector_alloc (num_vars);
gsl_vector *tau = gsl_vector_alloc (num_vars);
gsl_vector *residual = gsl_vector_alloc (num_eqns);
gsl_vector_view b = gsl_vector_view_array (b_data, num_eqns);
int s;
s = gsl_linalg_QR_decomp (&m.matrix, tau);
s = gsl_linalg_QR_lssolve (&m.matrix, tau, &b.vector, x, residual);
gsl_vector_fprintf (stdout, x, "%.15g"); fflush (stdout);
gsl_vector_free (x);
gsl_vector_free (tau);
gsl_vector_free (residual);
}
return 0;
}
// printf ("residual = \n"); gsl_vector_fprintf (stdout, residual, "%g");
// printf("solver got A: %d %d %.19g\n", i, j, tmp);
// printf("solver got B: %d %.19g\n", i, tmp);
| 2.34375 | 2 |
2024-11-18T21:19:05.909942+00:00 | 2021-07-16T17:37:13 | e0df7ecd88a66f2b78f78ae41d678fd9c2dd2e36 | {
"blob_id": "e0df7ecd88a66f2b78f78ae41d678fd9c2dd2e36",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-18T17:37:13",
"content_id": "4d83310e6b04169c653b4f3c4bde263309d0b795",
"detected_licenses": [
"MIT"
],
"directory_id": "ebe4ce2525ee0ec1fddd95c79e1243cfdcb8f328",
"extension": "c",
"filename": "Voting-Elegibility.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": 392,
"license": "MIT",
"license_type": "permissive",
"path": "/C/Voting-Elegibility.c",
"provenance": "stackv2-0128.json.gz:301191",
"repo_name": "wirepro/code-it-up",
"revision_date": "2021-07-16T17:37:13",
"revision_id": "3032c37b2e6009e5adafc79ab3f4e0a3ee3b686d",
"snapshot_id": "1f126a870a3096af13d1c9d62fc5ed793dda6ee8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wirepro/code-it-up/3032c37b2e6009e5adafc79ab3f4e0a3ee3b686d/C/Voting-Elegibility.c",
"visit_date": "2023-08-23T08:48:43.610052"
} | stackv2 | /*Question : To check wether a person is eledgible to vote or not
Input : User input age
Output : Eledgible or Not Eledgible */
#include <stdio.h>
int main()
{
int age;
printf("Enter the Age :");
scanf("%d",& age);
if (age>=18)
printf("Age %d is elegible to vote.",age);
else
printf("Age %d is not elegible to vote.",age);
return 0;
}
| 3.515625 | 4 |
2024-11-18T21:19:07.751634+00:00 | 2021-06-20T04:06:22 | ef14d623a18826b54711ec14617eccaed693f82b | {
"blob_id": "ef14d623a18826b54711ec14617eccaed693f82b",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-20T04:06:22",
"content_id": "88037358013cf5c8dedbe06de2e26c282c8ec22f",
"detected_licenses": [
"MIT"
],
"directory_id": "984dc240fe32e91f553dfe7195c666484fccafe1",
"extension": "c",
"filename": "exp1_1.c",
"fork_events_count": 1,
"gha_created_at": "2021-04-26T13:43:24",
"gha_event_created_at": "2021-06-05T15:53:10",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 361765211,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7904,
"license": "MIT",
"license_type": "permissive",
"path": "/A2000TM4/exp1/exp1_1.c",
"provenance": "stackv2-0128.json.gz:301844",
"repo_name": "grwei/SJTU_2020-2021-2-EI227",
"revision_date": "2021-06-20T04:06:22",
"revision_id": "13d9c922ec84268959784913597efed99ab2da3c",
"snapshot_id": "a218f1a59d2ea4fbb52b405ade9539dade7a1d5e",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/grwei/SJTU_2020-2021-2-EI227/13d9c922ec84268959784913597efed99ab2da3c/A2000TM4/exp1/exp1_1.c",
"visit_date": "2023-06-01T16:54:38.716814"
} | stackv2 | //**************************************************************************************
//
// Copyright: 2020-2021, 上海交通大学电子工程系实验教学中心
// File name: exp1_1.c
// Description: 初始时,LED4(D4-PF0) 大约以 6 秒为周期缓慢闪烁;
// 当按下 PUSH1(USR_SW1-PJ0) 键,LED4(D4-PF0) 大约以 100 毫秒为周期快速闪烁;
// 松开 PUSH1(USR_SW1-PJ0) 键,LED4(D4-PF0) 恢复以 6 秒为周期缓慢闪烁.
// Author: 上海交通大学电子工程系实验教学中心;危国锐(313017602@qq.com)
// Version: 1.0.0.20201228
// Date:2020-12-28
// History:
// 2021-04-26 修改.
//**************************************************************************************
//**************************************************************************************
//
// 头文件
//
//**************************************************************************************
#include <stdint.h>
#include <stdbool.h>
#include "inc/hw_memmap.h" // 基址宏定义
#include "inc/hw_types.h" // 数据类型宏定义,寄存器访问函数
#include "driverlib/debug.h" // 调试用
#include "driverlib/gpio.h" // 通用IO口宏定义
#include "driverlib/pin_map.h" // TM4C系列MCU外围设备管脚宏定义
#include "driverlib/sysctl.h" // 系统控制宏定义
#include "driverlib/uart.h" // UART相关宏定义
#include "utils/uartstdio.h" // UART0作为控制台相关函数原型声明
//**************************************************************************************
//
// 宏定义
//
//**************************************************************************************
#define MilliSecond 4000 // 形成1ms时延所需循环次数
#define FASTFLASHTIME 50 // 短延时(50ms)
#define SLOWFLASHTIME 3000 // 长延时(3000ms)
//**************************************************************************************
//
// 函数原型声明
//
//**************************************************************************************
void DelayMilliSec(uint32_t ui32DelaySecond); // 延迟一定时长,单位为毫秒
void GPIOInit(void); // GPIO初始化
void PF0Flash(uint8_t ui8KeyValue); // 根据传入的按键值,决定PF0快闪或慢闪
uint32_t exp1_1_SysClockSel(uint8_t number); // 实验1,表格1-1
//uint32_t ui32SysClock;
//**************************************************************************************
//
// 主程序
//
//**************************************************************************************
int main(void)
{
uint8_t ui8KeyValue;
volatile uint32_t ui32SysClock, g_ui32SysClock;
// g_ui32SysClock = exp1_1_SysClockSel(7); // 用于完成实验1的表格1-1
ui32SysClock = SysCtlClockFreqSet(SYSCTL_XTAL_25MHZ | SYSCTL_OSC_MAIN | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_320, 16000000);
GPIOInit(); // GPIO初始化
while (1) // 无限循环
{
// 读取 PJ0 键值 0-按下 1-松开
ui8KeyValue = GPIOPinRead(GPIO_PORTJ_BASE, GPIO_PIN_0);
// 根据传入的按键参数,决定PF0快闪或慢闪
PF0Flash(ui8KeyValue);
}
}
//**************************************************************************************
//
// 函数原型:void DelayMilliSec(uint32_t ui32DelaySecond)
// 函数功能:延迟一定时长,单位为毫秒
// 函数参数:ui32DelaySecond:延迟毫秒数
//
//**************************************************************************************
void DelayMilliSec(uint32_t ui32DelaySecond)
{
uint32_t ui32Loop;
ui32DelaySecond = ui32DelaySecond * MilliSecond;
for (ui32Loop = 0; ui32Loop < ui32DelaySecond; ui32Loop++)
{
};
}
//**************************************************************************************
//
// 函数原型:void GPIOInit(void)
// 函数功能:GPIO初始化. 使能PortF,设置PF0为输出;使能PortJ,设置PJ0为输入
// 函数参数:无
//
//**************************************************************************************
void GPIOInit(void)
{
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF); // 使能端口 F
while (!SysCtlPeripheralReady(SYSCTL_PERIPH_GPIOF))
; // 等待端口 F准备完毕
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOJ); // 使能端口 J
while (!SysCtlPeripheralReady(SYSCTL_PERIPH_GPIOJ))
{
}; // 等待端口 J准备完毕
// 设置端口 F的第0位(PF0)为输出引脚
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_0);
// 设置端口 J的第0位(PJ0)为输入引脚
GPIOPinTypeGPIOInput(GPIO_PORTJ_BASE, GPIO_PIN_0);
// 端口 J的第0位作为按键输入,类型设置成“推挽上拉”
GPIOPadConfigSet(GPIO_PORTJ_BASE, GPIO_PIN_0, GPIO_STRENGTH_2MA,
GPIO_PIN_TYPE_STD_WPU);
}
//**************************************************************************************
//
// 函数原型:void PF0Flash(uint8_t ui8KeyValue)
// 函数功能:根据传入的按键值,决定PF0快闪或慢闪. 0-快闪,1-慢闪
// 函数参数:ui8KeyValue:按键值
//
//**************************************************************************************
void PF0Flash(uint8_t ui8KeyValue)
{
uint32_t ui32DelayTime;
if (ui8KeyValue == 0) // PUSH1(USR_SW1-PJ0) 按下(低有效)
ui32DelayTime = FASTFLASHTIME;
else // PUSH1(USR_SW1-PJ0) 松开
ui32DelayTime = SLOWFLASHTIME;
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_0, GPIO_PIN_0); // 点亮 LED4(D4-PF0)
DelayMilliSec(ui32DelayTime); // 延时ui32DelayTime毫秒
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_0, 0x0); // 关闭 LED4(D4-PF0)
DelayMilliSec(ui32DelayTime); // 延时ui32DelayTime毫秒
}
/**
* @brief 表格 1-1
*
* @param number 序号
* @return uint32_t The actual configured system clock frequency in Hz or zero if the value could not be changed
due to a parameter error or PLL lock failure.
*/
uint32_t exp1_1_SysClockSel(uint8_t number)
{
uint32_t ui32SysClock;
switch (number)
{
case 1:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_OSC_INT | SYSCTL_USE_OSC, 16000000);
break;
case 2:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_OSC_INT | SYSCTL_USE_OSC, 12000000);
break;
case 3:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_OSC_INT | SYSCTL_USE_OSC, 8000000);
break;
case 4:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_XTAL_25MHZ | SYSCTL_OSC_MAIN | SYSCTL_USE_OSC, 25000000);
break;
case 5:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_XTAL_25MHZ | SYSCTL_OSC_MAIN | SYSCTL_USE_OSC, 12000000);
break;
case 6:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_XTAL_25MHZ | SYSCTL_OSC_MAIN | SYSCTL_USE_OSC, 1000000);
break;
case 7:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_XTAL_25MHZ | SYSCTL_OSC_MAIN | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_480, 25000000);
break;
case 8:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_XTAL_25MHZ | SYSCTL_OSC_MAIN | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_480, 20000000);
break;
case 9:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_XTAL_25MHZ | SYSCTL_OSC_MAIN | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_480, 8000000);
break;
case 10:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_OSC_INT | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_480, 20000000);
break;
case 11:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_OSC_INT | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_480, 8000000);
break;
case 12:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_OSC_INT | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_480, 1000000);
break;
default:
ui32SysClock = SysCtlClockFreqSet(SYSCTL_OSC_INT | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_480, 8000000);
break;
}
return ui32SysClock;
}
| 2.59375 | 3 |
2024-11-18T21:19:08.325510+00:00 | 2020-06-17T17:45:50 | 93dc51dd9d8b16b856eb7481b0a2431a1493a2ce | {
"blob_id": "93dc51dd9d8b16b856eb7481b0a2431a1493a2ce",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-17T17:45:50",
"content_id": "6b2106748d495f76a4626141246fec73c6de5bfe",
"detected_licenses": [
"ISC"
],
"directory_id": "766aab3ae97e3affa4f0838802f4518728aa946d",
"extension": "c",
"filename": "instruction_emulation.c",
"fork_events_count": 0,
"gha_created_at": "2020-05-12T16:51:40",
"gha_event_created_at": "2020-05-12T16:51:41",
"gha_language": null,
"gha_license_id": "ISC",
"github_id": 263396885,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5058,
"license": "ISC",
"license_type": "permissive",
"path": "/arch/mips/baikal-t1/instruction_emulation.c",
"provenance": "stackv2-0128.json.gz:302104",
"repo_name": "zanon005/hellfire-hypervisor",
"revision_date": "2020-06-17T17:45:50",
"revision_id": "695ebba6ce8cd5c7c547158d68c8351c4f43ddef",
"snapshot_id": "3d213d322a01192a37dd373b16e88305050dec3a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zanon005/hellfire-hypervisor/695ebba6ce8cd5c7c547158d68c8351c4f43ddef/arch/mips/baikal-t1/instruction_emulation.c",
"visit_date": "2022-11-10T20:30:54.560561"
} | stackv2 | /*
* Copyright (c) 2016, prpl Foundation
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with or without
* fee is hereby granted, provided that the above copyright notice and this permission notice appear
* in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
* FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* This code was written by Carlos Moratelli at Embedded System Group (GSE) at PUCRS/Brazil.
*
*/
/**
* @file instruction_emulation.c
*
* @section DESCRIPTION Functions to perform instruction emulation. This should be part of the vcpu.c file.
* However, not all platforms will require it. For example, platorms that only perform baremetal applications
* do not require instruction emulation. Platforms that virtualize Linux instances will require.
*/
#include <libc.h>
#include <vcpu.h>
#include <mips_cp0.h>
#include <gpr_context.h>
#include <globals.h>
#include <instruction_emulation.h>
/**
* @brief Emulate instructions with CO field.
*
* @param badinstr Instruction that caused the trap.
* @return 0 on success, otherwise error.
*/
static uint32_t co_instructions(uint32_t badinstr){
switch (FUNC(badinstr)){
case WAIT: /* wait instruction. */
return 1;
default:
return 1;
}
return 0;
}
/**
* @brief Emulate mfc0 instructions.
*
* @param badinstr Instruction that caused the trap.
* @return 0 on success, otherwise error.
*/
static uint32_t mfc0_instructions(uint32_t badinstr){
uint32_t rd = RD(badinstr);
uint32_t rt = RT(badinstr);
uint32_t regvalue;
switch (rd){
case 12:
if(SEL(badinstr) == 2){
/* read from COP0 (12, 2) SRSCTL */
regvalue = mfc0(CP0_SRSCTL, 2);
regvalue = regvalue & ~SRSCLT_HSS;
MoveToPreviousGuestGPR(rt, regvalue);
return 0;
}
return 1;
case 15:
if (SEL(badinstr) == 0){
/* read from COP0 (15, 0) PRID */
//regvalue = (mfc0(CP0_PRID, 0) & ~0xff00) | 0x8000;
regvalue = mfc0(CP0_PRID, 0);
MoveToPreviousGuestGPR(rt, regvalue);
return 0;
}
return 1;
case 18:
if (SEL(badinstr) == 0){
/* read from COP0 (18, 0) WATCHLo0 */
regvalue = mfgc0(CP0_WATCHLO, 0);
MoveToPreviousGuestGPR(rt, regvalue);
return 0;
}else if (SEL(badinstr) == 1){
/* read from COP0 (18, 0) WATCHLo1 */
MoveToPreviousGuestGPR(rt, 0);
return 0;
}
return 1;
case 19:
if (SEL(badinstr) == 0){
/* read from COP0 (18, 0) WATCHHi0 */
regvalue = mfgc0(CP0_WATCHHI, 0);
MoveToPreviousGuestGPR(rt, regvalue);
return 0;
}else if (SEL(badinstr) == 1){
/* read from COP0 (18, 0) WATCHHi1 */
MoveToPreviousGuestGPR(rt, 0);
return 0;
}
return 1;
default:
return 1;
}
return 0;
}
/**
* @brief Emulate mtc0 instructions.
*
* @param badinstr Instruction that caused the trap.
* @return 0 on success, otherwise error.
*/
static uint32_t mtc0_instructions(uint32_t badinstr){
uint32_t rd = RD(badinstr);
uint32_t rt = RT(badinstr);
uint32_t regvalue;
switch (rd){
case 18:
if (SEL(badinstr) == 0){
/* write to COP0 (18, 0) WATCHLo0 */
regvalue = MoveFromPreviousGuestGPR(rd);
mtgc0(CP0_WATCHLO, 0, regvalue);
return 0;
}else if (SEL(badinstr) == 1){
/* write to COP0 (18, 1) WATCHLo1 */
return 0;
}
return 1;
case 19:
if (SEL(badinstr) == 0){
/* write to COP0 (19, 0) WATCHHi0 */
regvalue = MoveFromPreviousGuestGPR(rd);
mtgc0(CP0_WATCHHI, 0, regvalue);
return 0;
}else if (SEL(badinstr) == 1){
/* write to COP0 (19, 1) WATCHHi1 */
return 0;
}
return 1;
default:
return 1;
}
return 0;
}
/**
* @brief Instruction emulation entry.
*
*/
uint32_t __instruction_emulation(uint32_t epc){
uint32_t badinstr = getBadInstruction();
uint32_t rs;
switch(OPCODE(badinstr)){
/* COP0 instructions */
case CP0:
switch (CO(badinstr)){
case 0x1:
if(co_instructions(badinstr)){
goto instr_not_supported;
}
break;
case 0:
rs = RS(badinstr);
switch (rs){
case MTC:
if(mtc0_instructions(badinstr)){
goto instr_not_supported;
}
break;
case MFC:
if(mfc0_instructions(badinstr)){
goto instr_not_supported;
}
break;
default:
goto instr_not_supported;
}
break;
default:
goto instr_not_supported;
}
break;
/* Cache instructions */
case CACHE:
goto instr_not_supported;
default:
goto instr_not_supported;
}
return 0;
instr_not_supported:
WARNING("Instruction 0x%x emulation at 0x%x not supported.", badinstr, epc);
return 1;
} | 2.203125 | 2 |
2024-11-18T21:19:08.493285+00:00 | 2021-02-01T16:44:21 | 6f014f31700ab4787aa65a277a83884a914e301b | {
"blob_id": "6f014f31700ab4787aa65a277a83884a914e301b",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-01T16:44:21",
"content_id": "92d3f0fd829d0d936746034ac017538c92bd1341",
"detected_licenses": [
"MIT"
],
"directory_id": "cbac54a4cdf89839bc5a459cd8c62695ae3f3537",
"extension": "c",
"filename": "01.BaseProgrammer.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 115875555,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 394,
"license": "MIT",
"license_type": "permissive",
"path": "/01.BaseProgrammer.c",
"provenance": "stackv2-0128.json.gz:302363",
"repo_name": "MinhasKamal/ProgrammerTransformation",
"revision_date": "2021-02-01T16:44:21",
"revision_id": "b2f3c4f6ee452e14fee8899cd0f17f393b487eae",
"snapshot_id": "9b5d451201187ea86465ceed769f7e9fe5acc883",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/MinhasKamal/ProgrammerTransformation/b2f3c4f6ee452e14fee8899cd0f17f393b487eae/01.BaseProgrammer.c",
"visit_date": "2021-06-03T19:48:53.098929"
} | stackv2 | /// Though u knew how prime number works (of course u r good @ math),
/// it took a long time to come up with the logic. Also, u made several
/// mistakes on the way. And now, u are proud of ur brilliant solution.
/// YES!!!
int func(int a)
{
int x,i, r;
x = 0;
i = 0 ;
for(i=1; i<=a ; i=i+1 )
{
if(a%i == 0)
{x=x+1 ;}
}
if( x == 2)
{r = 1;}
else
{r = 0;}
return r ;
}
| 2.703125 | 3 |
2024-11-18T21:19:09.450923+00:00 | 2023-08-07T00:26:03 | 7e1dc8c202881741b3545de3affbec22a3018241 | {
"blob_id": "7e1dc8c202881741b3545de3affbec22a3018241",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-07T00:26:03",
"content_id": "5fc3d3bcfd829c273ac89318fc3f512eda2f3d25",
"detected_licenses": [
"MIT"
],
"directory_id": "78c4a0b029ef1af4ac9ef90305eef85ef866ad35",
"extension": "c",
"filename": "prdeathsig.c",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 46625839,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 632,
"license": "MIT",
"license_type": "permissive",
"path": "/snippets/linux/prdeathsig.c",
"provenance": "stackv2-0128.json.gz:302885",
"repo_name": "qeedquan/misc_utilities",
"revision_date": "2023-08-07T00:26:03",
"revision_id": "e8319e6572dd92efceebb5a2d52a00cb993492b2",
"snapshot_id": "7727e33e01a9f45275e3efdd165c90053d8ba10a",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/qeedquan/misc_utilities/e8319e6572dd92efceebb5a2d52a00cb993492b2/snippets/linux/prdeathsig.c",
"visit_date": "2023-08-08T13:24:18.213741"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <sys/prctl.h>
#include <unistd.h>
#include <err.h>
volatile sig_atomic_t done;
void
sigusr1(int sig)
{
done = 1;
(void)sig;
}
int
main(void)
{
time_t t;
srand(time(NULL));
switch (fork()) {
case -1:
err(1, "fork");
break;
case 0:
if (signal(SIGUSR1, sigusr1) == SIG_ERR)
err(1, "signal");
if (prctl(PR_SET_PDEATHSIG, SIGUSR1) < 0)
err(1, "prctl");
t = time(NULL);
while (!done)
sleep(1);
printf("parent died in %lu seconds\n\n", time(NULL) - t);
break;
default:
sleep(rand() % 8);
break;
}
return 0;
}
| 2.625 | 3 |
2024-11-18T21:19:09.556950+00:00 | 2019-05-30T16:28:23 | 2ed96c44a82d887a4c9effc13aae5471c9ec73c1 | {
"blob_id": "2ed96c44a82d887a4c9effc13aae5471c9ec73c1",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-30T16:28:23",
"content_id": "225a99701a42a26bab83b8e0775f31645995af66",
"detected_licenses": [
"MIT"
],
"directory_id": "1823f24165f19449288eb45bd5969832a98ca04a",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2017-06-29T21:33:45",
"gha_event_created_at": "2019-05-30T13:06:46",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 95821799,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2812,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0128.json.gz:303016",
"repo_name": "aloha-kohola/Wordclock",
"revision_date": "2019-05-30T16:28:23",
"revision_id": "4a171003918bf0c7a80870af5434afa3e9555cca",
"snapshot_id": "b31fbffd9fa2cc4a2defc13e7da9d3318bbcf699",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/aloha-kohola/Wordclock/4a171003918bf0c7a80870af5434afa3e9555cca/main.c",
"visit_date": "2021-06-06T04:06:00.028346"
} | stackv2 | #include "espressif/esp_common.h"
#include "esp/uart.h"
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include "semphr.h"
#include "queue.h"
#include "driver/ws2812b.h"
#include "wordclock.h"
#include "httpserver_raw/httpd_callbacks.h"
#include <httpd/httpd.h>
#include <mdnsresponder.h>
#include <sntp.h>
#include <time.h>
#include <string.h>
#include "ssid_config.h"
#define SNTP_SERVERS "0.pool.ntp.org", "1.pool.ntp.org", \
"2.pool.ntp.org", "3.pool.ntp.org"
#define vTaskDelayMs(ms) vTaskDelay((ms)/portTICK_PERIOD_MS)
static TaskHandle_t getSNTPTaskHandle;
void readNTPTime(void* pvParameters)
{
/* Wait until we have joined AP and are assigned an IP */
while (sdk_wifi_station_get_connect_status() != STATION_GOT_IP) {
vTaskDelayMs(1000);
printf("%s\n", "Connecting..");
}
/* Use mDNS to spread the name in local network */
mdns_init();
mdns_add_facility("Wordclock", "_http", NULL, mdns_TCP + mdns_Browsable, 80, 600);
const char *servers[] = {SNTP_SERVERS};
/* SNTP will request an update each 5 minutes */
sntp_set_update_delay(15000);
/* Set GMT+1 zone, daylight savings middle european style*/
const struct timezone tz = {0*60, 0};
//Central European Timezone + Daylight Saving
putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
/* SNTP initialization */
sntp_initialize(&tz);
/* Servers must be configured right after initialization */
sntp_set_servers(servers, sizeof(servers) / sizeof(char*));
/* Print date and time each 5 seconds */
while(1) {
vTaskDelayMs(5000);
time_t current_time = time(NULL);
//printf("TIME: %s", ctime(¤t_time));
wordclock_show(current_time);
}
}
void user_init(void)
{
uart_set_baud(0, 115200);
printf("SDK version:%s\n", sdk_system_get_sdk_version());
struct sdk_station_config config = {
.ssid = WIFI_SSID,
.password = WIFI_PASS,
.bssid_set = 0,
};
sdk_wifi_set_opmode(STATION_MODE);
sdk_wifi_station_set_config(&config);
struct ip_info info;
info.ip.addr = ipaddr_addr("192.168.0.8");
info.gw.addr = ipaddr_addr("192.168.0.1");
info.netmask.addr = ipaddr_addr("255.255.255");
sdk_wifi_set_ip_info(STATION_IF, &info);
ws2812b_init();
wordclock_init();
/* Set Foreground Color to green */
struct rgb fg = {0x0B, 0x28, 0x0B};
wordclock_set_fg_color(&fg);
struct rgb bg = {0x00, 0x00, 0x00};
wordclock_set_bg_color(&bg);
vTaskDelay((5 * 1000) / portTICK_PERIOD_MS);
/* Initialize HTTP-Server to set colors etc. */
httpd_init_cgi_handler();
httpd_init_ssi_handler();
httpd_init();
xTaskCreate(readNTPTime, "NTPTask", 1024, NULL, 1, &getSNTPTaskHandle);
} | 2.21875 | 2 |
2024-11-18T21:19:09.618569+00:00 | 2021-09-30T07:13:29 | 1437138748799c00345b83aa8f327b4ba27eb614 | {
"blob_id": "1437138748799c00345b83aa8f327b4ba27eb614",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-30T07:13:29",
"content_id": "ce2eadc1c841eafeeeb86c6961b2055dfb9f7c24",
"detected_licenses": [
"MIT"
],
"directory_id": "eb0de1a391bf912f7834737e0a56e5c13be5097d",
"extension": "c",
"filename": "hw1.c",
"fork_events_count": 0,
"gha_created_at": "2015-02-22T17:15:12",
"gha_event_created_at": "2022-06-23T10:16:15",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 31171182,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2596,
"license": "MIT",
"license_type": "permissive",
"path": "/Message Passing Interface/Homework/hw1.c",
"provenance": "stackv2-0128.json.gz:303145",
"repo_name": "cbries/utilities",
"revision_date": "2021-09-30T07:13:29",
"revision_id": "86ce97d2c3e0d13b9beb0fc6ec79d31945c14461",
"snapshot_id": "b3ec91b76db0e7c30166bfe04959e6cd156a3566",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cbries/utilities/86ce97d2c3e0d13b9beb0fc6ec79d31945c14461/Message Passing Interface/Homework/hw1.c",
"visit_date": "2022-12-13T00:08:47.757700"
} | stackv2 | /*
* License: MIT
* Author: Christian Benjamin Ries
* Source: https://github.com/cbries/utilities
*/
/*
** DESCRIPTION: Rahmen für MPI-Programme
** COMPILE: mpicc -o hw1 hw1.c
** RUN: mpirun -np 4 -machinefile machines hw1 arg1 arg2 ...
*/
/*
* Homework description:
* Initialize real array A on processor of rank 0,
* A(i) = float(i) for i = 1,n where n = 4.
* Send A to processor of rank 1 and add 1 to
* each element receiving A in array B.
* Then send B from processor of rank 1 to
* processor of rank 2 into array C.
* Add 1 to each element of C and then send C
* to processor of rank 0 receiving C into
* array D. Print the values of D on the
* processor of rank 0.
* Use only mpi_send and mpi_recv and use p = 4.
**/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <mpi.h>
#define DIMENSION 4
#define TAG 123
int main (int argc, char **argv)
{
int i;
int myrank, nprocs;
int namelen;
char name[MPI_MAX_PROCESSOR_NAME];
double A[DIMENSION] = {0};
double B[DIMENSION] = {0};
double C[DIMENSION] = {0};
double D[DIMENSION] = {0};
MPI_Status status;
/* MPI initialisieren und Argumente setzen */
MPI_Init(&argc, &argv);
/* Anzahl der Prozesse erfragen */
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
/* Eigenen Rang erfragen */
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
/* Rechnernamen erfragen */
MPI_Get_processor_name(name, &namelen);
printf("nprocs=%d\n", nprocs);
printf("my rank=%d\n", myrank);
if(myrank == 0) {
for(i=0; i<DIMENSION; i++) {
A[i] = (double) i + 1;
}
MPI_Send(A, DIMENSION, MPI_DOUBLE, 1, TAG, MPI_COMM_WORLD);
MPI_Recv(D, DIMENSION, MPI_DOUBLE, 2, TAG, MPI_COMM_WORLD, &status);
for(i=0; i<DIMENSION; i++) {
printf("D[%d]=%lf on processor of rank %d\n", i, D[i], myrank);
fflush(stdout);
}
} else if(myrank == 1) {
MPI_Recv(B, DIMENSION, MPI_DOUBLE, 0, TAG, MPI_COMM_WORLD, &status);
for(i=0; i<DIMENSION; i++) {
B[i] = B[i] + 1.0;
}
MPI_Send(B, DIMENSION, MPI_DOUBLE, 2, TAG, MPI_COMM_WORLD);
} else if(myrank == 2) {
MPI_Recv(C, DIMENSION, MPI_DOUBLE, 1, TAG, MPI_COMM_WORLD, &status);
for(i=0; i<DIMENSION; i++) {
C[i] = C[i] + 1.0;
}
MPI_Send(C, DIMENSION, MPI_DOUBLE, 0, TAG, MPI_COMM_WORLD);
} else {
printf("rank=%d - Nothing to do...\n", myrank);
fflush(stdout);
}
/* MPI geordnet beenden */
MPI_Finalize();
return 0;
}
/* Result:
* rank=3 - Nothing to do...
* D[0]=3.000000 on processor of rank 0
* D[1]=4.000000 on processor of rank 0
* D[2]=5.000000 on processor of rank 0
* D[3]=6.000000 on processor of rank 0
*/
| 3.34375 | 3 |
2024-11-18T21:19:09.916551+00:00 | 2020-09-02T10:30:54 | 5dbece572e22b83afaf8b55868d25099b240e895 | {
"blob_id": "5dbece572e22b83afaf8b55868d25099b240e895",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-02T10:30:54",
"content_id": "6482322c2197eb099658efa521e7a729ac48f4c8",
"detected_licenses": [
"MIT"
],
"directory_id": "9fd2f6b586bbaf1999d3658631763aa32957d045",
"extension": "c",
"filename": "normaliseC.c",
"fork_events_count": 3,
"gha_created_at": "2020-06-29T04:27:13",
"gha_event_created_at": "2020-08-14T03:23:03",
"gha_language": "HTML",
"gha_license_id": "MIT",
"github_id": 275729881,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 656,
"license": "MIT",
"license_type": "permissive",
"path": "/Covid_GGPLDS/lib/kalmanall/KPMtools/normaliseC.c",
"provenance": "stackv2-0128.json.gz:303404",
"repo_name": "dds-covid19/dds-covid19.github.io",
"revision_date": "2020-09-02T10:30:54",
"revision_id": "ad38e550fc11b255287d54db3d4d43709add6d76",
"snapshot_id": "f53a195abbbf406cfc9c50fbf04f4f8a9e6ff44c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dds-covid19/dds-covid19.github.io/ad38e550fc11b255287d54db3d4d43709add6d76/Covid_GGPLDS/lib/kalmanall/KPMtools/normaliseC.c",
"visit_date": "2022-12-08T05:50:50.352190"
} | stackv2 | /* C mex version of normalise.m in misc directory */
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double *T, *sum_ptr, sum;
int i, N;
plhs[0] = mxDuplicateArray(prhs[0]);
T = mxGetPr(plhs[0]);
if(mxIsSparse(plhs[0])) N = mxGetJc(plhs[0])[mxGetN(plhs[0])];
else N = mxGetNumberOfElements(plhs[0]);
plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
sum_ptr = mxGetPr(plhs[1]);
sum = 0;
for (i = 0; i < N; i++) {
sum += *T++;
}
T = mxGetPr(plhs[0]);
if (sum > 0) {
for (i = 0; i < N; i++) {
*T++ /= sum;
}
}
*sum_ptr = sum;
}
| 2.078125 | 2 |
2024-11-18T21:19:09.980976+00:00 | 2019-05-26T23:31:00 | 98a77ab6930febc0989eea564e0ba24ba79a2dad | {
"blob_id": "98a77ab6930febc0989eea564e0ba24ba79a2dad",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-26T23:31:00",
"content_id": "47c16e310a3261386abf8408e373d285fd42c069",
"detected_licenses": [
"MIT"
],
"directory_id": "d6f419604323c9dabcb6f658c20212b1c4440bc1",
"extension": "c",
"filename": "dictionary.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 188681694,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4332,
"license": "MIT",
"license_type": "permissive",
"path": "/Brece-cs50-2018-x-challenges-speller/dictionary.c",
"provenance": "stackv2-0128.json.gz:303533",
"repo_name": "Brece/CS50",
"revision_date": "2019-05-26T23:31:00",
"revision_id": "05647f250edf2bccd979401b431052f70771204b",
"snapshot_id": "174d3d26b5730a2077044629d3d82403ad4a3a7c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Brece/CS50/05647f250edf2bccd979401b431052f70771204b/Brece-cs50-2018-x-challenges-speller/dictionary.c",
"visit_date": "2020-05-27T15:29:45.831979"
} | stackv2 | // Implements a dictionary's functionality
#include <stdio.h>
#include <stdbool.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdint.h>
#include "dictionary.h"
//define node structure
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
node *hashtable[26];
//word counter for SIZE
int word_counter = 0;
//boolean for SIZE
bool loaded = false;
//sdbm hash function
int c;
static unsigned long hash (char *str)
{
unsigned long hash = 0;
while (c == *str++)
{
hash = c + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
if(loaded)
{
//declare pointer to string array that stores the lower case version of the words to check in the dictionary
int orgn_len = strlen(word);
char *lo_word = malloc( sizeof(char) * (orgn_len+1) );
//copy lower case version in lo_word
for(int i = 0; i < orgn_len; i++)
{
lo_word[i] = tolower(word[i]);
}
lo_word[orgn_len] = '\0';
//get index where the word is being stored
int index = hash(lo_word);
//create node cursor to compare it to the ones on the linked lists
//node *cursor = malloc(sizeof(node));
//traversing linked lists where the word whould be found in the hash table
node *cursor = hashtable[index];
while(cursor != NULL)
{
//word exists if the string that the cursor is pointing to is equal to lo_word
if(strcmp(cursor->word, lo_word) == 0)
{
//word is in dictionary
return true;
}
//point to the next node
cursor = cursor->next;
}
free(lo_word);
//free(cursor);
return false;
}
else
{
return false;
}
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
//open dictionary to read
FILE *file = fopen(dictionary, "r");
//if the dictionary is not accessible or out of memory
if(file == NULL)
{
return false;
}
//define string to copy the word to
char word[LENGTH +1] = {'\0'};
//scan dictionary word by word
//malloc a node * for each new word, unload if NULL-pointer
//malloc returns NULL when no memory is available
while(fscanf(file, "%s", word) != EOF)
{
//increase word counter for SIZE
word_counter++;
node *new_node = malloc(sizeof(node));
//copy string stored in word to the node value 'word'
strcpy(new_node->word, word);
//call the hashfunction and get the hash code where the word should be stored in the hash table
int index = hash(word);
//insert if hashtable is empty at index
if(hashtable[index] == NULL)
{
hashtable[index] = new_node;
new_node->next = NULL;
}
//append node to the hashtable in the right index and make it the new head of the linked list
else
{
new_node->next = hashtable[index];
hashtable[index] = new_node;
}
}
loaded = true;
fclose(file);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
return word_counter;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
if(loaded)
{
//unload all indexes of the hash table
for(int i = 0; i < sizeof(hashtable); i++)
{
//create pointer to the head of the linked lists in the hashtable
node *cursor = hashtable[i];
//traverse the linked lists with help of a temporary pointer,
//two pointers are needed because cursor points to the next node, if the temp (current) pointer points to the last node then cursor points to NULL
while(cursor != NULL)
{
node *temp = cursor;
cursor = cursor->next;
free(temp);
}
}
loaded = false;
return true;
}
else
{
return false;
}
}
| 3.234375 | 3 |
2024-11-18T21:19:10.153191+00:00 | 2022-03-18T19:06:33 | 6e9cc813b76ae43e08bbf7fd37c61c5e0065af5c | {
"blob_id": "6e9cc813b76ae43e08bbf7fd37c61c5e0065af5c",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-18T19:06:33",
"content_id": "b458a459eda6ef6229c9a899fa8be93d33fd3dbd",
"detected_licenses": [
"MIT"
],
"directory_id": "512b058dcdff449aad2f270a033ee5e6bd93f958",
"extension": "c",
"filename": "rb_cglm_cam.c",
"fork_events_count": 0,
"gha_created_at": "2018-11-07T04:07:12",
"gha_event_created_at": "2021-01-11T19:38:03",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 156488830,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13572,
"license": "MIT",
"license_type": "permissive",
"path": "/ext/cglm/rb_cglm_cam.c",
"provenance": "stackv2-0128.json.gz:303662",
"repo_name": "sinisterchipmunk/cglm-ruby",
"revision_date": "2022-03-18T19:06:33",
"revision_id": "a452371022d50b0aa8fd0704808f6859eae911c5",
"snapshot_id": "6ae728d760df26d5f3f94e3bc165937eb26f735a",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/sinisterchipmunk/cglm-ruby/a452371022d50b0aa8fd0704808f6859eae911c5/ext/cglm/rb_cglm_cam.c",
"visit_date": "2022-05-07T08:07:18.100299"
} | stackv2 | #include "rb_cglm.h"
/* call-seq: aspect => Numeric */
VALUE rb_cglm_cam_decomp_aspect(VALUE self) {
return DBL2NUM(glm_persp_aspect(VAL2MAT4(self)));
}
/* call-seq: fovy => Numeric */
VALUE rb_cglm_cam_decomp_fovy(VALUE self) {
return DBL2NUM(glm_persp_fovy(VAL2MAT4(self)));
}
/* call-seq: left_and_right => Array */
VALUE rb_cglm_cam_decomp_left_and_right(VALUE self) {
float left, right;
glm_persp_decomp_x(VAL2MAT4(self), &left, &right);
return rb_ary_new_from_args(2, DBL2NUM(left), DBL2NUM(right));
}
/* call-seq: sizes([fovy]) => Hash
*
* Returns the sizes of the near and far planes of this perspective
* projection. The return value has the following format:
*
* { near: [width, height], far: [width, height] }
*
* If `fovy` is omitted, it will be decomposed from the current matrix.
*/
VALUE rb_cglm_cam_sizes(int argc, VALUE *argv, VALUE self) {
VALUE fovy = Qnil;
if (argc == 0) fovy = rb_cglm_cam_decomp_fovy(self);
else fovy = argv[0];
vec4 out;
glm_persp_sizes(VAL2MAT4(self), NUM2FLT(fovy), out);
VALUE n = rb_ary_new_from_args(2, DBL2NUM(out[0]), DBL2NUM(out[1]));
VALUE f = rb_ary_new_from_args(2, DBL2NUM(out[2]), DBL2NUM(out[3]));
VALUE dest = rb_hash_new();
rb_hash_aset(dest, ID2SYM(rb_intern("near")), n);
rb_hash_aset(dest, ID2SYM(rb_intern("far")), f);
return dest;
}
/* call-seq: top_and_bottom => Array */
VALUE rb_cglm_cam_decomp_top_and_bottom(VALUE self) {
float top, bottom;
glm_persp_decomp_y(VAL2MAT4(self), &top, &bottom);
return rb_ary_new_from_args(2, DBL2NUM(top), DBL2NUM(bottom));
}
/* call-seq: near_and_far => Array */
VALUE rb_cglm_cam_decomp_near_and_far(VALUE self) {
float n, f;
glm_persp_decomp_z(VAL2MAT4(self), &n, &f);
return rb_ary_new_from_args(2, DBL2NUM(n), DBL2NUM(f));
}
/* call-seq: left => Numeric */
VALUE rb_cglm_cam_decomp_left(VALUE self) {
float left, right;
glm_persp_decomp_x(VAL2MAT4(self), &left, &right);
return DBL2NUM(left);
}
/* call-seq: right => Numeric */
VALUE rb_cglm_cam_decomp_right(VALUE self) {
float left, right;
glm_persp_decomp_x(VAL2MAT4(self), &left, &right);
return DBL2NUM(right);
}
/* call-seq: top => Numeric */
VALUE rb_cglm_cam_decomp_top(VALUE self) {
float top, bottom;
glm_persp_decomp_y(VAL2MAT4(self), &top, &bottom);
return DBL2NUM(top);
}
/* call-seq: bottom => Numeric */
VALUE rb_cglm_cam_decomp_bottom(VALUE self) {
float top, bottom;
glm_persp_decomp_y(VAL2MAT4(self), &top, &bottom);
return DBL2NUM(bottom);
}
/* call-seq: near => Numeric */
VALUE rb_cglm_cam_decomp_near(VALUE self) {
float n;
glm_persp_decomp_near(VAL2MAT4(self), &n);
return DBL2NUM(n);
}
/* call-seq: far => Numeric */
VALUE rb_cglm_cam_decomp_far(VALUE self) {
float f;
glm_persp_decomp_far(VAL2MAT4(self), &f);
return DBL2NUM(f);
}
/*
* call-seq: frustum() => Hash
*
* Decomposes this perspective matrix into a hash containing the 6 frustum
* values: `:near`, `:far`, `:top`, `:bottom`, `:left`, and `:right`.
*/
VALUE rb_cglm_cam_frustum_decomp(VALUE self) {
VALUE hash = rb_hash_new();
float left, top, right, bottom, n, f;
glm_persp_decomp(VAL2MAT4(self), &n, &f, &top, &bottom, &left, &right);
rb_hash_aset(hash, ID2SYM(rb_intern("near")), DBL2NUM(n));
rb_hash_aset(hash, ID2SYM(rb_intern("far")), DBL2NUM(f));
rb_hash_aset(hash, ID2SYM(rb_intern("left")), DBL2NUM(left));
rb_hash_aset(hash, ID2SYM(rb_intern("right")), DBL2NUM(right));
rb_hash_aset(hash, ID2SYM(rb_intern("bottom")), DBL2NUM(bottom));
rb_hash_aset(hash, ID2SYM(rb_intern("top")), DBL2NUM(top));
return hash;
}
/* call-seq: look(eye, direction[, up, dest]) => dest | new Mat4
*
* Convenience wrapper for {look_at} for if you only have direction and not
* the target position.
*
* If `up` is omitted (or nil), it is assumed that you don't care what it is,
* and one will be computed for you.
*
* Note: The `up` vector must not be parallel to the line of sight from the
* eye point to the reference point.
*/
VALUE rb_cglm_cam_look(int argc, VALUE *argv, VALUE self) {
VALUE dest, eye, dir, up;
rb_scan_args(argc, argv, "31", &eye, &dir, &up, &dest);
if (NIL_P(dest)) dest = MAT4_NEW(ALLOC_MAT4);
if (NIL_P(up))
glm_look_anyup(VAL2VEC3(eye), VAL2VEC3(dir), VAL2MAT4(dest));
else
glm_look(VAL2VEC3(eye), VAL2VEC3(dir), VAL2VEC3(up), VAL2MAT4(dest));
return dest;
}
/* call-seq: look_at(eye, target_position, up[, dest]) => dest | new Mat4
*
* Sets up a view matrix.
*
* NOTE: The `up` vector must not be parallel to the line of sight from the
* eye point to the reference point.
*/
VALUE rb_cglm_cam_look_at(int argc, VALUE *argv, VALUE self) {
VALUE dest, eye, center, up;
rb_scan_args(argc, argv, "31", &eye, ¢er, &up, &dest);
if (NIL_P(dest)) dest = MAT4_NEW(ALLOC_MAT4);
glm_lookat(VAL2VEC3(eye), VAL2VEC3(center), VAL2VEC3(up), VAL2MAT4(dest));
return dest;
}
/* call-seq: perspective_resize!(aspect) => self
*
* Resizes this perspective matrix by the given aspect ratio (`width / height`).
* This makes it very easy to resize the projective matrix when the window or
* viewport is changed.
*/
VALUE rb_cglm_cam_perspective_resize_self(VALUE self, VALUE aspect) {
glm_perspective_resize(NUM2FLT(aspect), VAL2MAT4(self));
return self;
}
/* call-seq: perspective([dest], fovy: PI/4, aspect:, near: 0.1, far: 100.0) => dest | new Mat4
*
* Sets up a perspective projection matrix.
*/
VALUE rb_cglm_cam_perspective(int argc, VALUE *argv, VALUE self) {
static ID kwargs_ids[4];
if (!kwargs_ids[0]) {
kwargs_ids[0] = rb_intern_const("aspect");
kwargs_ids[1] = rb_intern_const("fovy");
kwargs_ids[2] = rb_intern_const("near");
kwargs_ids[3] = rb_intern_const("far");
};
VALUE dest, kwargs[4], opts;
rb_scan_args(argc, argv, "01:", &dest, &opts);
rb_get_kwargs(opts, kwargs_ids, 1, 3, kwargs);
if (NIL_P(dest)) dest = MAT4_NEW(ALLOC_MAT4);
if (RB_TYPE_P(kwargs[1], T_UNDEF)) kwargs[1] = DBL2NUM(GLM_PI_4f);
if (RB_TYPE_P(kwargs[2], T_UNDEF)) kwargs[2] = DBL2NUM(0.1);
if (RB_TYPE_P(kwargs[3], T_UNDEF)) kwargs[3] = DBL2NUM(100.0);
glm_perspective(NUM2FLT(kwargs[1]),
NUM2FLT(kwargs[0]),
NUM2FLT(kwargs[2]),
NUM2FLT(kwargs[3]),
VAL2MAT4(dest));
return dest;
}
/* call-seq: ortho_cube(aspect, size[, dest]) => dest | new Mat4
*
* Sets up a new cubed orthographic projection matrix (it has the same size in
* all dimensions).
*/
VALUE rb_cglm_cam_ortho_cube(int argc, VALUE *argv, VALUE self) {
VALUE aspect, size, dest;
rb_scan_args(argc, argv, "21", &aspect, &size, &dest);
if (NIL_P(dest)) dest = MAT4_NEW(ALLOC_MAT4);
glm_ortho_default_s(NUM2FLT(aspect), NUM2FLT(size), VAL2MAT4(dest));
return dest;
}
/* call-seq: ortho_unit(aspect[, dest]) => dest | new Mat4
*
* Sets up a unit orthographic projection matrix.
*/
VALUE rb_cglm_cam_ortho_unit(int argc, VALUE *argv, VALUE self) {
VALUE aspect, dest;
rb_scan_args(argc, argv, "11", &aspect, &dest);
if (NIL_P(dest)) dest = MAT4_NEW(ALLOC_MAT4);
glm_ortho_default(NUM2FLT(aspect), VAL2MAT4(dest));
return dest;
}
/* call-seq: ortho_aabb(aabb[, dest], padding: 0, padding_z: 0) => dest | new Mat4
*
* Sets up an orthographic projection matrix using the given bounding box.
*
* If `dest` is omitted, a new Mat4 will be allocated and returned. Otherwise,
* the result will be placed into `dest` and returned.
*
* If `padding` is present and `padding_z` is omitted, then the entire projection
* will have the same padding (including near/far values). If both are present,
* the near/far values will use `padding_z` while all other values will be
* padded with `padding`.
*/
VALUE rb_cglm_cam_ortho_aabb(int argc, VALUE *argv, VALUE self) {
VALUE boxv, dest, opts;
static ID kwargs_ids[2];
if (!kwargs_ids[0]) {
kwargs_ids[0] = rb_intern_const("padding");
kwargs_ids[1] = rb_intern_const("padding_z");
}
VALUE kwargs[2];
rb_scan_args(argc, argv, "11:", &boxv, &dest, &opts);
rb_get_kwargs(opts, kwargs_ids, 0, 2, kwargs);
aabb box = VAL2AABB(boxv);
if (NIL_P(dest)) dest = MAT4_NEW(ALLOC_MAT4);
if (RB_TYPE_P(kwargs[0], T_UNDEF)) {
if (RB_TYPE_P(kwargs[1], T_UNDEF)) {
glm_ortho_aabb(box.corners, VAL2MAT4(dest));
} else {
glm_ortho_aabb_pz(box.corners, NUM2FLT(kwargs[1]), VAL2MAT4(dest));
}
}
else{
if (RB_TYPE_P(kwargs[1], T_UNDEF)) {
glm_ortho_aabb_p(box.corners, NUM2FLT(kwargs[0]), VAL2MAT4(dest));
} else {
float padding = NUM2FLT(kwargs[0]);
float paddingz = NUM2FLT(kwargs[1]);
glm_ortho(box.corners[0][0] - padding, box.corners[1][0] + padding,
box.corners[0][1] - padding, box.corners[1][1] + padding,
-(box.corners[1][2] + paddingz), -(box.corners[0][2] - paddingz),
VAL2MAT4(dest));
}
}
return dest;
}
/* call-seq: ortho([dest], left:, right:, bottom:, top:, near:, far:) => dest | new Mat4
*
* Sets up an orthographic projection matrix. `dest` is a Mat4. If it is
* omitted, it is created.
*
* * `left` is the viewport left
* * `right` is the viewport right
* * `bottom` is the viewport bottom
* * `top` is the viewport top
* * `near` is the near clipping plane
* * `far` is the far clipping plane
* * `dest` is the result matrix
*
*/
VALUE rb_cglm_cam_ortho(int argc, VALUE *argv, VALUE klass) {
static ID kwargs_ids[6];
if (!kwargs_ids[0]) {
kwargs_ids[0] = rb_intern_const("left");
kwargs_ids[1] = rb_intern_const("right");
kwargs_ids[2] = rb_intern_const("bottom");
kwargs_ids[3] = rb_intern_const("top");
kwargs_ids[4] = rb_intern_const("near");
kwargs_ids[5] = rb_intern_const("far");
};
VALUE dest, kwargs[6], opts;
rb_scan_args(argc, argv, "01:", &dest, &opts);
rb_get_kwargs(opts, kwargs_ids, 6, 0, kwargs);
if (NIL_P(dest)) dest = MAT4_NEW(ALLOC_MAT4);
glm_ortho(NUM2FLT(kwargs[0]),
NUM2FLT(kwargs[1]),
NUM2FLT(kwargs[2]),
NUM2FLT(kwargs[3]),
NUM2FLT(kwargs[4]),
NUM2FLT(kwargs[5]),
VAL2MAT4(dest));
return dest;
}
/* call-seq: frustum([dest], left:, right:, bottom:, top:, near:, far:) => dest | new Mat4
*
* Sets up a perspective projection matrix. `dest` is a Mat4. If it is
* omitted, it is created.
*
* * `left` is the viewport left
* * `right` is the viewport right
* * `bottom` is the viewport bottom
* * `top` is the viewport top
* * `near` is the near clipping plane
* * `far` is the far clipping plane
* * `dest` is the result matrix
*
*/
VALUE rb_cglm_cam_frustum(int argc, VALUE *argv, VALUE klass) {
static ID kwargs_ids[6];
if (!kwargs_ids[0]) {
kwargs_ids[0] = rb_intern_const("left");
kwargs_ids[1] = rb_intern_const("right");
kwargs_ids[2] = rb_intern_const("bottom");
kwargs_ids[3] = rb_intern_const("top");
kwargs_ids[4] = rb_intern_const("near");
kwargs_ids[5] = rb_intern_const("far");
};
VALUE dest, kwargs[6], opts;
rb_scan_args(argc, argv, "01:", &dest, &opts);
rb_get_kwargs(opts, kwargs_ids, 6, 0, kwargs);
if (NIL_P(dest)) dest = MAT4_NEW(ALLOC_MAT4);
glm_frustum(NUM2FLT(kwargs[0]),
NUM2FLT(kwargs[1]),
NUM2FLT(kwargs[2]),
NUM2FLT(kwargs[3]),
NUM2FLT(kwargs[4]),
NUM2FLT(kwargs[5]),
VAL2MAT4(dest));
return dest;
}
void Init_cglm_cam() {
rb_define_method(rb_cMat4, "perspective_resize!", rb_cglm_cam_perspective_resize_self, 1);
rb_define_method(rb_cMat4, "frustum", rb_cglm_cam_frustum_decomp, 0);
rb_define_method(rb_cMat4, "left_and_right", rb_cglm_cam_decomp_left_and_right, 0);
rb_define_method(rb_cMat4, "top_and_bottom", rb_cglm_cam_decomp_top_and_bottom, 0);
rb_define_method(rb_cMat4, "near_and_far", rb_cglm_cam_decomp_near_and_far, 0);
rb_define_method(rb_cMat4, "left", rb_cglm_cam_decomp_left, 0);
rb_define_method(rb_cMat4, "right", rb_cglm_cam_decomp_right, 0);
rb_define_method(rb_cMat4, "top", rb_cglm_cam_decomp_top, 0);
rb_define_method(rb_cMat4, "bottom", rb_cglm_cam_decomp_bottom, 0);
rb_define_method(rb_cMat4, "near", rb_cglm_cam_decomp_near, 0);
rb_define_method(rb_cMat4, "far", rb_cglm_cam_decomp_far, 0);
rb_define_method(rb_cMat4, "fovy", rb_cglm_cam_decomp_fovy, 0);
rb_define_method(rb_cMat4, "aspect", rb_cglm_cam_decomp_aspect, 0);
rb_define_method(rb_cMat4, "sizes", rb_cglm_cam_sizes, -1);
rb_define_singleton_method(rb_cMat4, "frustum", rb_cglm_cam_frustum, -1);
rb_define_singleton_method(rb_cMat4, "ortho", rb_cglm_cam_ortho, -1);
rb_define_singleton_method(rb_cMat4, "ortho_aabb", rb_cglm_cam_ortho_aabb, -1);
rb_define_singleton_method(rb_cMat4, "ortho_unit", rb_cglm_cam_ortho_unit, -1);
rb_define_singleton_method(rb_cMat4, "ortho_cube", rb_cglm_cam_ortho_cube, -1);
rb_define_singleton_method(rb_cMat4, "perspective", rb_cglm_cam_perspective, -1);
rb_define_singleton_method(rb_cMat4, "look_at", rb_cglm_cam_look_at, -1);
rb_define_singleton_method(rb_cMat4, "look", rb_cglm_cam_look, -1);
}
| 2.1875 | 2 |
2024-11-18T21:19:10.330250+00:00 | 2021-11-08T03:26:00 | ddd612682389203f04334356fbcb65af1ced7c18 | {
"blob_id": "ddd612682389203f04334356fbcb65af1ced7c18",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-08T03:26:00",
"content_id": "cffe74c13dca051fa299fcf113ea2737f8536bd6",
"detected_licenses": [
"MIT"
],
"directory_id": "e2897f9663aa39e689fff6491165e118db905718",
"extension": "c",
"filename": "14_02_04.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 180817338,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1984,
"license": "MIT",
"license_type": "permissive",
"path": "/Doit/DoitC14_StandardInput/DoitC14_StandardInput/14_02_04.c",
"provenance": "stackv2-0128.json.gz:303791",
"repo_name": "BeginnerJay/C_STUDYING",
"revision_date": "2021-11-08T03:26:00",
"revision_id": "f9620420335fa0f778e193ae443c5c1fe56c0745",
"snapshot_id": "012548634cfa68b6dcd02ae1d491e1e5d7cb07f9",
"src_encoding": "UHC",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BeginnerJay/C_STUDYING/f9620420335fa0f778e193ae443c5c1fe56c0745/Doit/DoitC14_StandardInput/DoitC14_StandardInput/14_02_04.c",
"visit_date": "2023-09-03T13:10:33.106117"
} | stackv2 | // 문자열을 입력받는 gets 함수
// getchar와는 달리 gets 함수는 한 번에 여러 개의 문자를 입력받을 수 있으며,
// enter 키를 입력할 때까지 입력한 모든 문자를 하나의 문자열로 간주한다.
// 그리고 문자열을 저장하기 위해서 gets 함수의 매개변수에 char 배열로 선언된 변수의 시작 주소를 넘겨주어야 한다.
// 주소를 넘겨주는데 왜 & 연산자를 쓰지 않을까?
/*
배열의 각 요소는 메모리에 연속적으로 나열되기 때문에, 배열의 첫 번째 요소의 시작 주소는 배열의 시작 주소와 같다.
그렇기 때문에 배열의 시작 주소를 적을 때, 첫 번째 요소의 주소인 &input_string[0]으로 적는 것이 정확한 표헌이다.
하지만 첫 번째 요소의 시작 주소와 배열의 시작주소는 같기 때문에,
input_string이라고 적으면 컴파일러가 번열할 때에 &input_string[0]이라고 적은 것과 같게 번역한다.
물론 원칙대로 다 써도 되긴 한다.
배열의 시작 주소와 관련된 좀 더 자세한 내용은 15장에서 다룬다.
*/
//gets 함수로 문자열 입력 받기
#include <stdio.h>
main()
{
// 문자열은 마지막에 NULL 문자 0을 포함해야 하므로, 최대 9개의 문자까지 저장 가능함
char input_string[10];
fgets(input_string, 10, stdin); // 문자열을 입력받아 input_string에 저장함
printf("input : %s\n", input_string);
}
// fgets 함수는 enter 키까지 입력 버퍼에서 읽어 와 처피하므로, 입력 버퍼에 enter가 남아 있지 않다.
// 따라서 rewind 함수를 사용하여 입력 버퍼를 초기화할 필요가 없다.
// 그리고 enter 키를 입력 버퍼에서 가져 온다고 해서 enter키 값을 문자열에 포함시키는 것이 아니라
// 입력 완료의 기준으로만 사용하기 때문에, 실제 문자열에서는 enter 키를 입력한 위치에 NULL 문자 0이 들어가게 된다. | 3.609375 | 4 |
2024-11-18T21:19:10.421151+00:00 | 2021-08-15T00:08:37 | f47aa6ecc6f8575de4b1e2e5c368f6587fedbbd3 | {
"blob_id": "f47aa6ecc6f8575de4b1e2e5c368f6587fedbbd3",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-15T00:08:37",
"content_id": "fab988fce57ea48ce29e21ca5dfcae18e77fd4f7",
"detected_licenses": [
"MIT"
],
"directory_id": "9627f43d33e866205584db1b1e2ae7694d49d719",
"extension": "c",
"filename": "ps.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 396163921,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 648,
"license": "MIT",
"license_type": "permissive",
"path": "/ps.c",
"provenance": "stackv2-0128.json.gz:303923",
"repo_name": "MahmoudF98/Lottery-Scheduler-on-XV6-operating-system",
"revision_date": "2021-08-15T00:08:37",
"revision_id": "89e13cfe4d2c01424b58a5ee7db8acd78fe95980",
"snapshot_id": "b23524dc1a9eaa24fa3d9d65beeb3d8bc840833c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MahmoudF98/Lottery-Scheduler-on-XV6-operating-system/89e13cfe4d2c01424b58a5ee7db8acd78fe95980/ps.c",
"visit_date": "2023-07-11T06:00:06.855057"
} | stackv2 | /* This utility runs unit tests*/
#include "types.h"
#include "pstat.h"
#include "user.h"
int ps(){
// Get process info first
struct pstat pinfo = {0};
if(-1 == getpinfo(&pinfo)){
return 0;
printf(1, "\n\t FAILURE\n");
}
printf(1,"This process: %d\n",
getpid());
printf(1,"Total tickets: %d\n\n",
pinfo.total_tickets);
printf(1,
"PID\tTicks\tTickets\tState\tinuse\n");
for(int i=0;i<NPROC;i++){
if(pinfo.pid[i]==0)continue;
printf(1,"%d\t%d\t%d\t%d\t%d\n",
pinfo.pid[i],
pinfo.ticks[i],
pinfo.tickets[i],
pinfo.state[i],pinfo.inuse[i]); }
return 1;
}
int main(int argc, char *argv[])
{
ps();
exit();
} | 2.484375 | 2 |
2024-11-18T21:19:10.480183+00:00 | 2015-11-07T23:34:33 | 73d663cc65490e8b8574d9c28701aaac11a35969 | {
"blob_id": "73d663cc65490e8b8574d9c28701aaac11a35969",
"branch_name": "refs/heads/master",
"committer_date": "2015-11-07T23:34:33",
"content_id": "8628df8065cb8d0e706b8a807e0792a9f7417fd0",
"detected_licenses": [
"MIT"
],
"directory_id": "05899580e1b04d27f0511007ecfd1ee55ea2310b",
"extension": "h",
"filename": "obmap.h",
"fork_events_count": 2,
"gha_created_at": "2012-07-22T05:52:37",
"gha_event_created_at": "2013-06-19T05:46:55",
"gha_language": "C",
"gha_license_id": null,
"github_id": 5139464,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2610,
"license": "MIT",
"license_type": "permissive",
"path": "/include/obmap.h",
"provenance": "stackv2-0128.json.gz:304053",
"repo_name": "theck01/offbrand_lib",
"revision_date": "2015-11-07T23:34:33",
"revision_id": "888af70f574418154d0d4a42555f089b3268c7a0",
"snapshot_id": "9a6914208dc24c2f2831ddbf14a6294e4fd03fa1",
"src_encoding": "UTF-8",
"star_events_count": 16,
"url": "https://raw.githubusercontent.com/theck01/offbrand_lib/888af70f574418154d0d4a42555f089b3268c7a0/include/obmap.h",
"visit_date": "2020-04-24T17:37:16.134823"
} | stackv2 | /**
* @file obmap.h
* @brief obmap Public Interface
* @author theck
*/
#ifndef OBMAP_H
#define OBMAP_H
#include "offbrand.h"
/** Class type declaration */
typedef struct obmap_struct obmap;
/* PUBLIC METHODS */
/**
* @brief Constructor, creates a new, empty, obmap instance with a small initial
* capacity
* @return Pointer to the newly created obmap instance
*/
obmap * obmap_new(void);
/**
* @brief Constructor, creates a new, empty obmap instance with capacity given
* @param capacity Capacity required for obmap instance
* @return Pointer to the newly created obmap instance
*/
obmap * obmap_new_with_capacity(uint32_t capacity);
/**
* @brief Copy constructor, creates a new obmap with the exact same contents
* of another obmap
* @param to_copy Pointer to an instance of obmap to copy
* @return A copy of the provided obmap
*/
obmap * obmap_copy(const obmap *to_copy);
/**
* @brief Add a key-value pair to an obmap
*
* @param m Pointer to an instance of obmap
* @param key Pointer to any Offbrand compatible class to use as a lookup key
* @param value Pointer to any Offbrand compatible class
*
* @details If the key is already contained within the m then the old value
* stored at that key is replaced with the new value
*/
void obmap_insert(obmap *m, obj *key, obj *value);
/**
* @brief Lookup the value stored at key in an obmap
*
* @param m Pointer to an instance of obmap
* @param key Pointer to any Offbrand compatible class to use as a lookup key
*
* @retval NULL Key not found in obmap instance or key bound to NULL value
* @retval non-NULL Value found at key in obmap
*/
obj * obmap_lookup(const obmap *m, const obj *key);
/**
* @brief Removes a key-value pair from an obmap
*
* @param m Pointer to an instance of obmap
* @param key Pointer to any Offbrand compatible class to use as a lookup key
*
* @details If no key exists then the funciton will silently do nothing
*
* @warning This function runs in O(n), and is inherently more expensive
* than an add or lookup.
*/
void obmap_remove(obmap *m, obj *key);
/**
* @brief Rehashes all elements contained in an obmap
*
* @param m Pointer to an instance of obmap
*
* @details This method is useful for ensuring that mutable keys will still lead
* to valid lookups of the associated values even after key(s) have been altered
*/
void obmap_rehash(obmap *m);
/**
* @brief Clears an obmap of all key-value pairs, essentially restoring it
* to the initial empty state that existed after creation
*
* @param m Pointer to an instance of obmap
*/
void obmap_clear(obmap *m);
#endif
| 2.640625 | 3 |
2024-11-18T21:19:10.944958+00:00 | 2020-10-13T01:54:50 | f5baccd2a376f2ef2876d85d8e2a813593378c0f | {
"blob_id": "f5baccd2a376f2ef2876d85d8e2a813593378c0f",
"branch_name": "refs/heads/latest",
"committer_date": "2020-10-13T01:54:50",
"content_id": "c6f4835098760ecd808eea7d41fe51e931341005",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "72d08a9b4017af55877dd2dc547f0837dac7b153",
"extension": "c",
"filename": "element.c",
"fork_events_count": 0,
"gha_created_at": "2020-10-13T11:38:07",
"gha_event_created_at": "2020-10-13T11:38:08",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 303682969,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10264,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/element.c",
"provenance": "stackv2-0128.json.gz:304184",
"repo_name": "IgorSivy/stumpless",
"revision_date": "2020-10-13T01:54:50",
"revision_id": "1630f637d6bb23e8122136be2127f241bc4701f0",
"snapshot_id": "bcc9d11415a2c0eac5339e412e24ac46855ff9da",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/IgorSivy/stumpless/1630f637d6bb23e8122136be2127f241bc4701f0/src/element.c",
"visit_date": "2022-12-30T22:42:21.844095"
} | stackv2 | // SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2018-2020 Joel E. Anderson
*
* 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 <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <stumpless/element.h>
#include <stumpless/param.h>
#include "private/config/locale/wrapper.h"
#include "private/element.h"
#include "private/error.h"
#include "private/memory.h"
#include "private/strhelper.h"
#include "private/validate.h"
struct stumpless_element *
stumpless_add_new_param( struct stumpless_element *element,
const char *param_name,
const char *param_value ) {
struct stumpless_param *new_param;
struct stumpless_element *result;
new_param = stumpless_new_param( param_name, param_value );
if( !new_param ) {
return NULL;
}
result = stumpless_add_param( element, new_param );
if( !result ) {
stumpless_destroy_param( new_param );
}
return result;
}
struct stumpless_element *
stumpless_add_param( struct stumpless_element *element,
struct stumpless_param *param ) {
struct stumpless_param **new_params;
size_t old_params_size;
size_t new_params_size;
VALIDATE_ARG_NOT_NULL( element );
VALIDATE_ARG_NOT_NULL( param );
old_params_size = sizeof( param ) * element->param_count;
new_params_size = old_params_size + sizeof( param );
new_params = realloc_mem( element->params, new_params_size );
if( !new_params ) {
return NULL;
}
new_params[element->param_count] = param;
element->param_count++;
element->params = new_params;
clear_error( );
return element;
}
struct stumpless_element *
stumpless_copy_element( const struct stumpless_element *element ) {
struct stumpless_element *copy;
size_t i;
struct stumpless_param *param_copy;
copy = stumpless_new_element( stumpless_get_element_name( element ) );
if( !copy ) {
goto fail;
}
copy->params = alloc_mem( element->param_count * sizeof( param_copy ) );
if( !copy->params ) {
goto fail_param_copy;
}
for( i = 0; i < element->param_count; i++ ) {
param_copy = stumpless_copy_param( element->params[i] );
if( !param_copy ) {
goto fail_param_copy;
}
copy->params[i] = param_copy;
copy->param_count++;
}
return copy;
fail_param_copy:
stumpless_destroy_element_and_contents( copy );
fail:
return NULL;
}
void
stumpless_destroy_element( const struct stumpless_element *element ) {
stumpless_destroy_element_and_contents( element );
}
void
stumpless_destroy_element_and_contents( const struct stumpless_element *element ) {
size_t i;
if( !element ) {
return;
}
for( i = 0; i < element->param_count; i++ ) {
stumpless_destroy_param( element->params[i] );
}
unchecked_destroy_element( element );
}
void
stumpless_destroy_element_only( const struct stumpless_element *element ) {
if( !element ) {
return;
}
unchecked_destroy_element( element );
}
bool
stumpless_element_has_param( const struct stumpless_element *element,
const char *name ) {
size_t i;
if( !element ) {
raise_argument_empty( L10N_NULL_ARG_ERROR_MESSAGE( "element" ) );
return false;
}
if( !name ) {
raise_argument_empty( L10N_NULL_ARG_ERROR_MESSAGE( "name" ) );
return false;
}
for( i = 0; i < element->param_count; i++ ) {
if( strcmp( element->params[i]->name, name ) == 0 ) {
return true;
}
}
return false;
}
const char *
stumpless_get_element_name( const struct stumpless_element *element ) {
VALIDATE_ARG_NOT_NULL( element );
clear_error( );
return element->name;
}
struct stumpless_param *
stumpless_get_param_by_index( const struct stumpless_element *element,
size_t index ) {
VALIDATE_ARG_NOT_NULL( element );
if( index >= element->param_count ) {
raise_index_out_of_bounds( L10N_INVALID_INDEX_ERROR_MESSAGE( "param" ),
index );
return NULL;
}
clear_error( );
return element->params[index];
}
struct stumpless_param *
stumpless_get_param_by_name( const struct stumpless_element *element,
const char *name ) {
size_t i;
struct stumpless_param *param;
VALIDATE_ARG_NOT_NULL( element );
VALIDATE_ARG_NOT_NULL( name );
for( i = 0; i < element->param_count; i++ ) {
param = element->params[i];
if( strcmp( param->name, name ) == 0 ) {
clear_error( );
return param;
}
}
raise_param_not_found( );
return NULL;
}
size_t
stumpless_get_param_count( const struct stumpless_element *element ) {
if( !element ) {
raise_argument_empty( L10N_NULL_ARG_ERROR_MESSAGE( "element" ) );
return 0;
}
clear_error( );
return element->param_count;
}
size_t
stumpless_get_param_index( const struct stumpless_element *element,
const char *name ) {
size_t i;
const struct stumpless_param *param;
if( !element ) {
raise_argument_empty( L10N_NULL_ARG_ERROR_MESSAGE( "element" ) );
return 0;
}
if( !name ) {
raise_argument_empty( L10N_NULL_ARG_ERROR_MESSAGE( "name" ) );
return 0;
}
for( i = 0; i < element->param_count; i++ ) {
param = element->params[i];
if( strcmp( param->name, name ) == 0 ) {
clear_error( );
return i;
}
}
raise_param_not_found( );
return 0;
}
const char *
stumpless_get_param_name_by_index( const struct stumpless_element *element,
size_t index ) {
const struct stumpless_param *param;
param = stumpless_get_param_by_index( element, index );
if( !param ) {
return NULL;
}
return stumpless_get_param_name( param );
}
size_t
stumpless_get_param_name_count( const struct stumpless_element *element,
const char *name ) {
size_t i;
size_t count = 0;
const struct stumpless_param *param;
if( !element ) {
raise_argument_empty( L10N_NULL_ARG_ERROR_MESSAGE( "element" ) );
return 0;
}
if( !name ) {
raise_argument_empty( L10N_NULL_ARG_ERROR_MESSAGE( "name" ) );
return 0;
}
for( i = 0; i < element->param_count; i++ ) {
param = element->params[i];
if( strcmp( param->name, name ) == 0 ) {
count++;
}
}
clear_error( );
return count;
}
const char *
stumpless_get_param_value_by_index( const struct stumpless_element *element,
size_t index ) {
const struct stumpless_param *param;
param = stumpless_get_param_by_index( element, index );
if( !param ) {
return NULL;
}
return stumpless_get_param_value( param );
}
const char *
stumpless_get_param_value_by_name( const struct stumpless_element *element,
const char *name ) {
const struct stumpless_param *param;
param = stumpless_get_param_by_name( element, name );
if( !param ) {
return NULL;
}
return stumpless_get_param_value( param );
}
struct stumpless_element *
stumpless_new_element( const char *name ) {
struct stumpless_element *element;
VALIDATE_ARG_NOT_NULL( name );
element = alloc_mem( sizeof( *element ) );
if( !element ) {
goto fail;
}
element->name = copy_cstring_with_length( name, &( element->name_length ) );
if( !element->name ) {
goto fail_name;
}
element->params = NULL;
element->param_count = 0;
clear_error( );
return element;
fail_name:
free_mem( element );
fail:
return NULL;
}
struct stumpless_element *
stumpless_set_element_name( struct stumpless_element *element,
const char *name ) {
char *temp_name;
size_t temp_size;
VALIDATE_ARG_NOT_NULL( element );
VALIDATE_ARG_NOT_NULL( name );
temp_name = copy_cstring_with_length( name, &temp_size );
if( !temp_name ) {
goto fail;
}
free_mem( element->name );
element->name = temp_name;
element->name_length = temp_size;
clear_error( );
return element;
fail:
return NULL;
}
struct stumpless_element *
stumpless_set_param( struct stumpless_element *element,
size_t index,
struct stumpless_param *param ) {
VALIDATE_ARG_NOT_NULL( element );
VALIDATE_ARG_NOT_NULL( param );
if( index >= element->param_count ) {
raise_index_out_of_bounds( L10N_INVALID_INDEX_ERROR_MESSAGE( "param" ),
index );
return NULL;
}
element->params[index] = param;
clear_error( );
return element;
}
struct stumpless_element *
stumpless_set_param_value_by_index( struct stumpless_element *element,
size_t index,
const char *value ) {
struct stumpless_param *param;
const struct stumpless_param *result;
param = stumpless_get_param_by_index( element, index );
if( !param ) {
return NULL;
}
result = stumpless_set_param_value( param, value );
if( !result ) {
return NULL;
}
return element;
}
struct stumpless_element *
stumpless_set_param_value_by_name( struct stumpless_element *element,
const char *name,
const char *value ) {
struct stumpless_param *param;
const void *result;
VALIDATE_ARG_NOT_NULL( element );
VALIDATE_ARG_NOT_NULL( name );
param = stumpless_get_param_by_name( element, name );
if( param ) {
result = stumpless_set_param_value( param, value );
} else {
result = stumpless_add_new_param( element, name, value );
}
if( !result ) {
return NULL;
}
return element;
}
/* private functions */
void
unchecked_destroy_element( const struct stumpless_element *element ) {
free_mem( element->params );
free_mem( element->name );
free_mem( element );
}
| 2.109375 | 2 |
2024-11-18T21:19:11.306835+00:00 | 2023-08-31T14:51:12 | 8de669f83c6fa02650b8572012fbb94f753d75ac | {
"blob_id": "8de669f83c6fa02650b8572012fbb94f753d75ac",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T14:51:12",
"content_id": "e0b2a03cd308fc4991854db62e4a934ebc143a48",
"detected_licenses": [],
"directory_id": "9de0cec678bc4a3bec2b4adabef9f39ff5b4afac",
"extension": "c",
"filename": "readStarEventsSimple.C",
"fork_events_count": 1150,
"gha_created_at": "2016-06-21T19:31:29",
"gha_event_created_at": "2023-09-14T18:48:45",
"gha_language": "C++",
"gha_license_id": "BSD-3-Clause",
"github_id": 61661378,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1369,
"license": "",
"license_type": "permissive",
"path": "/PWGCF/FLOW/macros/readStarEventsSimple.C",
"provenance": "stackv2-0128.json.gz:304321",
"repo_name": "alisw/AliPhysics",
"revision_date": "2023-08-31T14:51:12",
"revision_id": "5df28b2b415e78e81273b0d9bf5c1b99feda3348",
"snapshot_id": "91bf1bd01ab2af656a25ff10b25e618a63667d3e",
"src_encoding": "UTF-8",
"star_events_count": 129,
"url": "https://raw.githubusercontent.com/alisw/AliPhysics/5df28b2b415e78e81273b0d9bf5c1b99feda3348/PWGCF/FLOW/macros/readStarEventsSimple.C",
"visit_date": "2023-08-31T20:41:44.927176"
} | stackv2 | //example script on what to do with the star events
//run e.g. like this:
// root readStarEventSimple.C
void readStarEventsSimple()
{
gSystem->Load("libTree");
gSystem->Load("libVMC");
gSystem->Load("libPhysics");
gSystem->Load("libPWGflowBase");
Int_t maxNumberOfEvents = 1000;
//define reference particles
AliStarTrackCuts* rpCuts = AliStarTrackCuts::StandardCuts();
//define particles of interest
AliStarTrackCuts* poiCuts = AliStarTrackCuts::StandardCuts();
poiCuts->SetPtMin(1.0);
//define event cuts
AliStarEventCuts* starEventCuts = AliStarEventCuts::StandardCuts();
Int_t i=0;
AliStarEventReader starReader("/data/alice3/jthomas/testData/") ;
while ( starReader.GetNextEvent() ) // Get next event
{
AliStarEvent* starEvent = starReader.GetEvent();
if ( !starEventCuts->PassesCuts(starEvent) ) continue; // Test if the event is good
AliFlowEventSimple* flowEvent = new AliFlowEventStar(starEvent,rpCuts,poiCuts); // make a flow event from a star event (aka "the magic")
/////analysis here////////////////
//////////////////////////////////
//starEvent->Print("all");
flowEvent->Print();
delete flowEvent;
i++;
if (i>maxNumberOfEvents) break;
}
delete rpCuts;
delete poiCuts;
delete starEventCuts;
}
| 2.234375 | 2 |
2024-11-18T21:19:11.493896+00:00 | 2023-09-01T13:02:25 | d8e97349bfc8bcbdb116b52ba3774fe5ec828840 | {
"blob_id": "d8e97349bfc8bcbdb116b52ba3774fe5ec828840",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-01T13:02:25",
"content_id": "d9c69acdadc9c68aea9c0c975145a364b166e060",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "baa9fffc817a2a993d4ecc774d3f277783308c20",
"extension": "h",
"filename": "memtype_cache.h",
"fork_events_count": 420,
"gha_created_at": "2014-10-17T22:17:24",
"gha_event_created_at": "2023-09-14T12:29:35",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 25379390,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3858,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/ucs/memory/memtype_cache.h",
"provenance": "stackv2-0128.json.gz:304582",
"repo_name": "openucx/ucx",
"revision_date": "2023-09-01T13:02:25",
"revision_id": "73a48700badb7cbace64d94b82f408e2a26fca32",
"snapshot_id": "9a0f2205295afbdf3cff14b5d24af781b123f5ea",
"src_encoding": "UTF-8",
"star_events_count": 966,
"url": "https://raw.githubusercontent.com/openucx/ucx/73a48700badb7cbace64d94b82f408e2a26fca32/src/ucs/memory/memtype_cache.h",
"visit_date": "2023-09-01T16:51:26.913950"
} | stackv2 | /**
* Copyright (c) NVIDIA CORPORATION & AFFILIATES, 2018. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#ifndef UCS_MEMTYPE_CACHE_H_
#define UCS_MEMTYPE_CACHE_H_
#include "memory_type.h"
#include <ucs/datastruct/pgtable.h>
#include <ucs/datastruct/list.h>
#include <ucs/stats/stats_fwd.h>
#include <ucs/sys/compiler_def.h>
#include <ucs/sys/topo/base/topo.h>
#include <ucs/type/spinlock.h>
#include <pthread.h>
BEGIN_C_DECLS
typedef struct ucs_memtype_cache ucs_memtype_cache_t;
typedef struct ucs_memtype_cache_region ucs_memtype_cache_region_t;
/* The single global instance of memory type cache */
extern ucs_memtype_cache_t *ucs_memtype_cache_global_instance;
/* Memory information record */
typedef struct ucs_memory_info {
ucs_memory_type_t type; /**< Memory type */
ucs_sys_device_t sys_dev; /**< System device index */
void *base_address; /**< Base address of the underlying allocation */
size_t alloc_length; /**< Whole length of the underlying allocation */
} ucs_memory_info_t;
struct ucs_memtype_cache {
ucs_spinlock_t lock; /**< protests the page table */
ucs_pgtable_t pgtable; /**< Page table to hold the regions */
};
void ucs_memtype_cache_global_init();
void ucs_memtype_cache_cleanup();
/**
* Find if address range is in memtype cache.
*
* @param [in] address Address to lookup.
* @param [in] size Length of the memory.
* @param [out] mem_info Set to the memory info of the address range.
* UCS_MEMORY_TYPE_UNKNOWN is a special value which
* means the memory type is an unknown non-host
* memory, and should be detected in another way.
*
* @return UCS_OK - an element was found and the memory info is valid.
* @return UCS_ERR_NO_ELEM - an element was not found.
* @return UCS_ERR_UNSUPPORTED - the memory type cache is disabled.
*/
ucs_status_t ucs_memtype_cache_lookup(const void *address, size_t size,
ucs_memory_info_t *mem_info);
/**
* Update the memory type of an address range.
* Can be used after @ucs_memtype_cache_lookup returns UCM_MEM_TYPE_LAST, to
* set the memory type after it was detected.
*
* @param [in] address Start address to update.
* @param [in] size Size of the memory to update.
* @param [in] mem_type Set the memory type of the address range to this
* value.
* @param [in] sys_dev Set the system device of the address range to
* this value.
*/
void ucs_memtype_cache_update(const void *address, size_t size,
ucs_memory_type_t mem_type,
ucs_sys_device_t sys_dev);
/**
* Remove the address range from a memtype cache.
*
* @param [in] address Start address to remove.
* @param [in] size Size of the memory to remove.
*/
void ucs_memtype_cache_remove(const void *address, size_t size);
/**
* Find if global memtype_cache is empty.
*
* @return 1 if empty 0 if otherwise.
*/
static UCS_F_ALWAYS_INLINE int ucs_memtype_cache_is_empty()
{
return (ucs_memtype_cache_global_instance != NULL) &&
(ucs_memtype_cache_global_instance->pgtable.num_regions == 0);
}
/**
* Helper function to set memory info structure to host memory type.
*
* @param [out] mem_info Pointer to memory info structure.
*/
static UCS_F_ALWAYS_INLINE void
ucs_memory_info_set_host(ucs_memory_info_t *mem_info)
{
mem_info->type = UCS_MEMORY_TYPE_HOST;
mem_info->sys_dev = UCS_SYS_DEVICE_ID_UNKNOWN;
mem_info->base_address = NULL;
mem_info->alloc_length = -1;
}
END_C_DECLS
#endif
| 2.140625 | 2 |
2024-11-18T21:19:11.696058+00:00 | 2021-04-19T01:53:12 | d0c1eeeabb8d62f0e20681a56b2f604d96533dc2 | {
"blob_id": "d0c1eeeabb8d62f0e20681a56b2f604d96533dc2",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-19T01:53:12",
"content_id": "a371b408606df8c0839ffd20388aae413eb617e8",
"detected_licenses": [
"MIT"
],
"directory_id": "1353e9c9c8baa4bd323784e3645457033d7bec2c",
"extension": "c",
"filename": "tracer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 314356671,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12404,
"license": "MIT",
"license_type": "permissive",
"path": "/src/tracer.c",
"provenance": "stackv2-0128.json.gz:304840",
"repo_name": "0xf4b1/kernel-fuzzer-for-kvm",
"revision_date": "2021-04-19T01:53:12",
"revision_id": "097b22c37ebe6d0656e8eef56f564065505723ac",
"snapshot_id": "43860750d592dc3697f4ae85312cd3023223b0ac",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/0xf4b1/kernel-fuzzer-for-kvm/097b22c37ebe6d0656e8eef56f564065505723ac/src/tracer.c",
"visit_date": "2023-04-10T15:29:57.663843"
} | stackv2 | #include "breakpoint.h"
#include "fuzz.h"
#include "sink.h"
#include "tracer_dynamic.h"
/*
* 1. start by disassembling code from the start address
* 2. find next control-flow instruction and start monitoring it
* 3. at control flow instruction remove monitor and create singlestep
* 4. after a singlestep set start address to current RIP
* 5. goto step 1
*/
#define HYPERCALL_BUFFER 0x1337133713371338
#define HYPERCALL_TESTCASE 0x1337133713371337
static const char *traptype[] = {
[VMI_EVENT_SINGLESTEP] = "singlestep",
[VMI_EVENT_CPUID] = "cpuid",
[VMI_EVENT_INTERRUPT] = "int3",
};
extern bool failure;
static vmi_event_t singlestep_event, cc_event;
static struct table *breakpoints;
static struct node *current_bp;
static addr_t reset_breakpoint;
event_response_t (*handle_event)(vmi_instance_t vmi, vmi_event_t *event);
static void write_coverage(unsigned long address) {
fprintf(coverage_fp, "0x%lx\n", address);
fflush(coverage_fp);
}
static event_response_t tracer_cb(vmi_instance_t vmi, vmi_event_t *event) {
if (trace_pid &&
VMI_SUCCESS != vmi_dtb_to_pid(vmi, event->x86_regs->cr3 & ~(0xfff), ¤t_pid))
printf("Can not get pid!\n");
if (debug)
printf("[TRACER %s] 0x%lx. PID: %u Limit: %lu/%lu\n", traptype[event->type],
event->x86_regs->rip, current_pid, tracer_counter, limit);
if (VMI_EVENT_SINGLESTEP == event->type) {
if (reset_breakpoint) {
access_context_t ctx = {.translate_mechanism = VMI_TM_PROCESS_DTB,
.dtb = event->x86_regs->cr3,
.addr = reset_breakpoint};
vmi_write_8(vmi, &ctx, &cc);
reset_breakpoint = 0;
return VMI_EVENT_RESPONSE_TOGGLE_SINGLESTEP;
}
return handle_event(vmi, event);
}
event->interrupt_event.reinject = 0;
// check for error sink
for (int c = 0; c < __SINK_MAX; c++) {
if (sink_vaddr[c] == event->x86_regs->rip) {
stop(true);
if (debug)
printf("\t Sink %s! Tracer counter: %lu.\n", sinks[c], tracer_counter);
// Restore instruction byte at sink address
vmi_write_va(vmi, sink_vaddr[c], 0, 1, &sink_backup[c], NULL);
// Restore BP for sink afterwards
reset_breakpoint = sink_vaddr[c];
return VMI_EVENT_RESPONSE_TOGGLE_SINGLESTEP;
}
}
if (event->x86_regs->rax == HYPERCALL_BUFFER) {
// Get physical address of buffer for input injection
if (VMI_FAILURE == vmi_pagetable_lookup(vmi, event->x86_regs->cr3 & ~(0xfff),
event->x86_regs->rbx, &address_pa)) {
printf("Failed to find physical address of target buffer!\n");
failure = true;
return 0;
}
// Get buffer length
input_limit = event->x86_regs->rcx;
if (input)
free(input);
input = malloc(input_limit);
event->x86_regs->rip += 1;
return VMI_EVENT_RESPONSE_SET_REGISTERS;
}
/*
* Reached start address for fuzzing, either the specified start address or the first
* encountered breakpoint that is not part of the target.
*/
if (event->x86_regs->rax == HYPERCALL_TESTCASE || event->x86_regs->rip == start) {
if (debug)
printf("VM reached the start address\n");
coverage_enabled = true;
harness_pid = current_pid;
tracer_counter = 0;
// Inject fuzz input
if (!fuzz() || (mode == DYNAMIC && !start_trace(vmi, event->x86_regs->rip))) {
failure = true;
return 0;
}
// Set BP for target address
if (target)
assert(VMI_SUCCESS == vmi_write_va(vmi, target, 0, 1, &cc, NULL));
// Breakpoint is compiled into the harness. Just increase RIP.
if (!start_offset) {
event->x86_regs->rax = 0;
event->x86_regs->rip += 1;
return VMI_EVENT_RESPONSE_SET_REGISTERS;
}
access_context_t ctx = {.translate_mechanism = VMI_TM_PROCESS_DTB,
.dtb = event->x86_regs->cr3,
.addr = event->x86_regs->rip};
// Restore instruction byte at start address
vmi_write_8(vmi, &ctx, &start_byte);
reset_breakpoint = start;
return VMI_EVENT_RESPONSE_TOGGLE_SINGLESTEP;
}
if (coverage_enabled && current_pid == harness_pid)
tracer_counter++;
return handle_event(vmi, event);
}
event_response_t handle_event_breakpoints(vmi_instance_t vmi, vmi_event_t *event) {
if (VMI_EVENT_SINGLESTEP == event->type) {
if (current_pid == harness_pid) {
if (mode == EDGE) {
// EDGE mode, only CF instruction and target chained together
afl_instrument_location_edge(current_bp->address,
event->x86_regs->rip - module_start);
} else {
// FULL mode, all blocks are chained together
afl_instrument_location(current_bp->address);
afl_instrument_location(event->x86_regs->rip - module_start);
}
if (current_bp->taken_addr + module_start == event->x86_regs->rip &&
!current_bp->taken) {
current_bp->taken = true;
write_coverage(current_bp->address);
write_coverage(current_bp->taken_addr);
} else if (current_bp->not_taken_addr + module_start == event->x86_regs->rip &&
current_bp->not_taken) {
current_bp->not_taken = true;
write_coverage(current_bp->address);
write_coverage(current_bp->not_taken_addr);
}
}
// Restore breakpoint
if (mode == FULL || (mode == EDGE && !(current_bp->taken && current_bp->not_taken)))
assert(VMI_SUCCESS ==
vmi_write_va(vmi, current_bp->address + module_start, 0, 1, &cc, NULL));
return VMI_EVENT_RESPONSE_TOGGLE_SINGLESTEP;
}
// Restore opcode
current_bp = get_address(breakpoints, event->x86_regs->rip - module_start);
assert(current_bp != NULL);
assert(VMI_SUCCESS == vmi_write_va(vmi, current_bp->address + module_start, 0, 1,
¤t_bp->cf_backup, NULL));
/*
* Switch to single-step for further breakpoint restore only when not in block coverage
* mode. Additionally ignore interrupts that occur before harness started. This helps to
* discard interrupts that are triggered independently and cause problems, such as interrupt
* handlers.
*/
if (mode != BLOCK && coverage_enabled)
return VMI_EVENT_RESPONSE_TOGGLE_SINGLESTEP;
// BLOCK mode, only block is reported
if (coverage_enabled && current_pid == harness_pid) {
current_bp->taken = true;
afl_instrument_location_block(event->x86_regs->rip - module_start);
write_coverage(current_bp->address);
}
return 0;
}
bool setup_trace(vmi_instance_t vmi) {
if (debug)
printf("Setup trace\n");
if (start && VMI_FAILURE == vmi_read_va(vmi, start, 0, 1, &start_byte, NULL))
return false;
if (start && VMI_FAILURE == vmi_write_va(vmi, start, 0, 1, &cc, NULL))
return false;
if (target && VMI_FAILURE == vmi_read_va(vmi, target, 0, 1, &target_byte, NULL))
return false;
if (mode != DYNAMIC) {
handle_event = &handle_event_breakpoints;
if (breakpoints == NULL) {
FILE *fp = fopen(bp_file, "r");
assert(fp);
breakpoints = create_table(0x1000);
char buf[1024];
while (fgets(buf, 1024, fp)) {
char *line = strtok(buf, "\n");
unsigned long address = strtoul(strtok(line, ","), NULL, 16);
unsigned long taken_addr = strtoul(strtok(NULL, ","), NULL, 16);
unsigned long not_taken_addr = strtoul(strtok(NULL, ","), NULL, 16);
unsigned char backup;
if (mode == BLOCK) {
assert(VMI_SUCCESS ==
vmi_read_va(vmi, address + module_start, 0, 1, &backup, NULL));
insert_breakpoint(breakpoints, address, 0, 0, backup);
assert(VMI_SUCCESS ==
vmi_read_va(vmi, taken_addr + module_start, 0, 1, &backup, NULL));
insert_breakpoint(breakpoints, taken_addr, 0, 0, backup);
assert(VMI_SUCCESS ==
vmi_read_va(vmi, not_taken_addr + module_start, 0, 1, &backup, NULL));
insert_breakpoint(breakpoints, not_taken_addr, 0, 0, backup);
} else {
assert(VMI_SUCCESS ==
vmi_read_va(vmi, address + module_start, 0, 1, &backup, NULL));
insert_breakpoint(breakpoints, address, taken_addr, not_taken_addr, backup);
}
}
fclose(fp);
}
for (int pos = 0; pos < breakpoints->size; pos++) {
struct node *node = breakpoints->nodes[pos];
while (node) {
if (mode == FULL || (mode == EDGE && !(node->taken && node->not_taken)) ||
(mode == BLOCK && !node->taken))
assert(VMI_SUCCESS ==
vmi_write_va(vmi, node->address + module_start, 0, 1, &cc, NULL));
node = node->next;
}
}
} else {
handle_event = &handle_event_dynamic;
}
char mask = 0;
for (unsigned char i = 0; i < vmi_get_num_vcpus(vmi); i++)
mask |= 1 << i;
SETUP_SINGLESTEP_EVENT(&singlestep_event, mask, tracer_cb, 0);
SETUP_INTERRUPT_EVENT(&cc_event, tracer_cb);
if (VMI_FAILURE == vmi_register_event(vmi, &singlestep_event))
return false;
if (VMI_FAILURE == vmi_register_event(vmi, &cc_event))
return false;
if (debug)
printf("Setup trace finished\n");
return true;
}
bool setup_sinks(vmi_instance_t vmi) {
for (int c = 0; c < __SINK_MAX; c++) {
if (!sink_vaddr[c] && VMI_FAILURE == vmi_translate_ksym2v(vmi, sinks[c], &sink_vaddr[c])) {
if (debug)
printf("Failed to find %s\n", sinks[c]);
return false;
}
registers_t regs = {0};
vmi_get_vcpuregs(vmi, ®s, 0);
if (!sink_paddr[c] &&
VMI_FAILURE == vmi_pagetable_lookup(vmi, regs.x86.cr3, sink_vaddr[c], &sink_paddr[c]))
return false;
if (VMI_FAILURE == vmi_read_pa(vmi, sink_paddr[c], 1, &sink_backup[c], NULL))
return false;
if (VMI_FAILURE == vmi_write_pa(vmi, sink_paddr[c], 1, &cc, NULL))
return false;
if (debug)
printf("[TRACER] Setting breakpoint on sink %s 0x%lx -> 0x%lx, backup 0x%x\n", sinks[c],
sink_vaddr[c], sink_paddr[c], sink_backup[c]);
}
return true;
}
void close_trace(vmi_instance_t vmi) {
vmi_clear_event(vmi, &singlestep_event, NULL);
vmi_clear_event(vmi, &cc_event, NULL);
if (start && start_byte != 0x90)
vmi_write_va(vmi, start, 0, 1, &start_byte, NULL);
if (target)
vmi_write_va(vmi, target, 0, 1, &target_byte, NULL);
if (mode != DYNAMIC) {
for (int i = 0; i < 0x1000; i++) {
struct node *node = breakpoints->nodes[i];
while (node) {
vmi_write_va(vmi, node->address, 0, 1, &node->cf_backup, NULL);
node = node->next;
}
}
}
if (debug)
printf("Closing tracer\n");
}
void clear_sinks(vmi_instance_t vmi) {
for (int c = 0; c < __SINK_MAX; c++)
vmi_write_pa(vmi, sink_paddr[c], 1, &sink_backup[c], NULL);
}
bool init_tracer(vmi_instance_t vmi) {
// Setup crashing sinks
if (!setup_sinks(vmi))
printf("Setup sinks failed! Crashes will not be reported!\n");
// Setup events and set breakpoints for the target
if (!setup_trace(vmi))
return false;
return true;
}
void teardown() {
close_trace(vmi);
clear_sinks(vmi);
free(input);
fclose(coverage_fp);
}
| 2.203125 | 2 |
2024-11-18T21:19:12.557247+00:00 | 2018-09-03T10:21:50 | 20448eeee56eb71bac094562ab828be960b1f5fc | {
"blob_id": "20448eeee56eb71bac094562ab828be960b1f5fc",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-03T10:21:50",
"content_id": "dc22b372dbfa1dd142dc35c663bb43cabfdb38c7",
"detected_licenses": [
"MIT"
],
"directory_id": "140c8b182fc1058f6a2a5bf338c018fe0eee57c5",
"extension": "c",
"filename": "command-line()필수예제.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": 354,
"license": "MIT",
"license_type": "permissive",
"path": "/lsp_2017/assignment/assignment11/command-line()필수예제.c",
"provenance": "stackv2-0128.json.gz:305494",
"repo_name": "qpakzk/ssu-cse-linux-system-programming",
"revision_date": "2018-09-03T10:21:50",
"revision_id": "c2badb12ab2fd9f3b6c2778c68ecf51338ee3371",
"snapshot_id": "cf6c2d878c9df1620e60d1fcfc17447f9e6cffcd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/qpakzk/ssu-cse-linux-system-programming/c2badb12ab2fd9f3b6c2778c68ecf51338ee3371/lsp_2017/assignment/assignment11/command-line()필수예제.c",
"visit_date": "2018-11-18T20:20:56.846485"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
//argc : shell 상에서 인자로 입력받은 문자열의 개수
//argv : shell 상에서 인자로 입력받은 문자열을 가리키는 포인터
int main(int argc, char *argv[]) {
int i;
//입력받은 문자열을 출력
for(i = 0; i < argc; i++)
printf("argv[%d] : %s\n", i, argv[i]);
exit(0);
}
| 3.203125 | 3 |
2024-11-18T21:19:13.051451+00:00 | 2019-08-10T18:05:44 | 5aa6d8ca38e099345e136de95897e516c8cf9991 | {
"blob_id": "5aa6d8ca38e099345e136de95897e516c8cf9991",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-10T18:05:44",
"content_id": "c437b5a99e071cc949790d426a3571408ae51806",
"detected_licenses": [
"MIT"
],
"directory_id": "5e2cc06a83b3532ff47de895fea6aeeb0a30c0b7",
"extension": "h",
"filename": "input_manager.h",
"fork_events_count": 0,
"gha_created_at": "2019-05-25T23:35:02",
"gha_event_created_at": "2019-08-10T18:05:45",
"gha_language": "C",
"gha_license_id": null,
"github_id": 188621725,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 657,
"license": "MIT",
"license_type": "permissive",
"path": "/input_manager.h",
"provenance": "stackv2-0128.json.gz:306013",
"repo_name": "MatheusSaloma0/Group_Shell",
"revision_date": "2019-08-10T18:05:44",
"revision_id": "9ea8d69885c80edce9edee8404a5d951ebc8da35",
"snapshot_id": "0153b30dfed792a11bef4b94f66da081a536f6b1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MatheusSaloma0/Group_Shell/9ea8d69885c80edce9edee8404a5d951ebc8da35/input_manager.h",
"visit_date": "2020-05-27T12:39:30.083211"
} | stackv2 | #ifndef INPUT_MANAGER_H_
#define INPUT_MANAGER_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
/**
* Estrutura que representa um comando.
*/
typedef struct command {
char** args; // Armazena o nome do comando e seus argumentos.
} Command;
/**
* Estrutura que representa uma linha de comando.
*/
typedef struct cmd_line {
Command* array; // Array de comandos.
unsigned int size; // Quantidade de comandos.
} CMD_Line;
CMD_Line splitter(char *);
void free_commands(CMD_Line);
#endif | 2.265625 | 2 |
2024-11-18T21:19:13.706821+00:00 | 2010-05-13T02:26:53 | da213fd8a5b0fb60c12c3b7e339d3114c9ea3c64 | {
"blob_id": "da213fd8a5b0fb60c12c3b7e339d3114c9ea3c64",
"branch_name": "refs/heads/master",
"committer_date": "2010-05-13T02:26:53",
"content_id": "5d27f5391079fdd3707a4427cfa07616e067a7fb",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "844570690912f433c2cf03abc1431adc23ecee39",
"extension": "c",
"filename": "fff_BPmatch.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 665081,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5475,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/libcstat/fff/fff_BPmatch.c",
"provenance": "stackv2-0128.json.gz:306532",
"repo_name": "fperez/nipy",
"revision_date": "2010-05-13T02:26:53",
"revision_id": "559f17150bd9fa8ead4fd088b330d7cf7db7aa79",
"snapshot_id": "1bb3671dc8efc1ffcd7e4e033a556428e5fddc35",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/fperez/nipy/559f17150bd9fa8ead4fd088b330d7cf7db7aa79/libcstat/fff/fff_BPmatch.c",
"visit_date": "2021-01-16T17:42:25.349349"
} | stackv2 | #include "fff_BPmatch.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
static int _fff_swapindex(fff_array *idx, const fff_graph *G);
static int _fff_matrix_normalize_rows(fff_matrix* A);
static int _fff_swapindex(fff_array *idx, const fff_graph *G)
{
int V = G->V;
int e,i, E = G->E;
fff_array *temp = fff_array_new1d(FFF_LONG,V*V);
fff_array_set_all(temp,-1);
for (e=0 ; e<E ; e++){
i = G->eA[e]*V+G->eB[e];
fff_array_set1d(temp,i,e);
}
for (e=0 ; e<E ; e++){
i = G->eB[e]*V+G->eA[e];
fff_array_set1d(idx,e,fff_array_get1d(temp,i));
}
fff_array_delete(temp);
return(0);
}
static int _fff_matrix_normalize_rows(fff_matrix* A)
{
/* normalize all the rows to sum 1 -when possible*/
int i;
double sv;
fff_vector v;
fff_vector* ones = fff_vector_new(A->size2);
fff_vector_set_all(ones,1);
for (i=0 ; i<A->size1 ; i++){
v = fff_matrix_row (A, i);
sv = fff_blas_ddot (&v, ones);
if (sv != 0)
fff_vector_scale(&v,1./sv);
}
fff_vector_delete(ones);
return(0);
}
extern int fff_BPmatch(fff_matrix * source, fff_matrix * target, fff_matrix * adjacency, fff_matrix * belief, double d0)
{
int i,j,k,e,A,B;
double dx,dist;
double dB,b=0;
double eps = 1.e-12;
int maxiter = 20;
int verbose = 0;
/* Some basic checks */
int n1 = source->size1;
int n2 = target->size1;
int p = source->size2;
double sqs = 2*d0*d0;
double dth = 4.5*sqs;
fff_vector wi,vi;
fff_graph *G;
int E;
fff_array *tag;
fff_matrix **T;
fff_vector *u, *v, *v1, *v2;
fff_matrix *Msg, *PMsg, *old_belief, *initial_belief;
if (source->size2 != target->size2){
FFF_WARNING("Incompaticle dimension four source and target\n");
return (0);
}
if (adjacency->size1 != adjacency->size2){
FFF_WARNING("adjacency is not square\n");
return (0);
}
if (adjacency->size1 != n1){
FFF_WARNING("Bad size for adjacency \n");
return (0);
}
if (belief->size1 != n1){
FFF_WARNING("Bad size for belief\n");
return (0);
}
if (belief->size2 != n2){
FFF_WARNING("Bad size for belief\n");
return (0);
}
fff_matrix_set_all(belief,0);
/* Initialization of the probabilistic correspondences */
for (i=0 ; i<n1 ; i++ ){
for (j=0 ; j<n2 ; j++){
dist = 0;
for ( k=0 ; k<p ; k++){
dx = fff_matrix_get(source,i,k)-fff_matrix_get(target,j,k);
dist += dx*dx;
if (dist>dth) break;
}
if (dist<dth)
b = exp(-dist/sqs);
else
b=0;
fff_matrix_set(belief,i,j,b);
}
}
_fff_matrix_normalize_rows(belief);
/* Initialization of the transition matrices */
vi = fff_matrix_diag(adjacency);
fff_vector_set_all(&vi,0);
fff_matrix_to_graph(&G, adjacency);
fff_remove_null_edges(&G);
if (G->E==0)
return(0);
E = G->E;
tag = fff_array_new1d(FFF_LONG,E);
_fff_swapindex(tag,G);
T = (fff_matrix **) calloc(E,sizeof(fff_matrix*));
u = fff_vector_new(p);
v = fff_vector_new(p);
for (e=0 ; e<E ; e++){
A = G->eA[e];
B = G->eB[e];
T[e] = fff_matrix_new(n2,n2);
vi = fff_matrix_row (source,A);
fff_vector_memcpy(u,&vi);
vi = fff_matrix_row(source,B);
fff_vector_sub(u,&vi);
for (i=0 ; i<n2 ; i++){
for (j=0 ; j<n2 ; j++){
fff_vector_memcpy(v,u);
vi = fff_matrix_row(target,i);
fff_vector_sub(v,&vi);
vi = fff_matrix_row(target,j);
fff_vector_add(v,&vi);
dist = fff_blas_ddot (v,v);
b = exp(-dist/sqs);
fff_matrix_set(T[e],i,j,b);
}
}
_fff_matrix_normalize_rows(T[e]);
}
/* Initialization of the messages */
Msg = fff_matrix_new(E,n2);
PMsg = fff_matrix_new(E,n2);
for (e=0 ; e<E ; e++){
int A = G->eA[e];
vi = fff_matrix_row (PMsg,e);
wi = fff_matrix_row (belief,A);
fff_vector_memcpy (&vi, &wi);
}
/* message passing algorithm */
old_belief = fff_matrix_new(n1,n2);
initial_belief = fff_matrix_new(n1,n2);
fff_matrix_memcpy(initial_belief, belief);
v1 = fff_vector_new(n2);
v2 = fff_vector_new(n2);
for (i=0 ; i<maxiter ; i++){
fff_matrix_memcpy(old_belief, belief);
fff_matrix_memcpy(belief, initial_belief);
fff_matrix_memcpy(Msg, PMsg);
/* compute the msgs */
for (e=0 ; e<E ; e++){
vi = fff_matrix_row (Msg,e);
fff_matrix_get_row(v1,Msg,e);
fff_blas_dgemv (CblasTrans, 1., T[e], v1, 0.,&vi);
}
_fff_matrix_normalize_rows(Msg);
/* update the beliefs */
for (e=0 ; e<E ; e++){
B = G->eB[e];
wi = fff_matrix_row (belief,B);
vi = fff_matrix_row (Msg,e);
fff_vector_mul (&wi,&vi );
}
_fff_matrix_normalize_rows(belief);
/* stopping criterion */
fff_matrix_sub (old_belief, belief);
fff_matrix_mul_elements (old_belief,old_belief );
dB = fff_matrix_sum(old_belief);
if (dB<eps){
if (verbose)
printf("iter %d, diff %f %f \n",i,dB,eps);
break;
}
/* Prepare the next messages */
for (e=0 ; e<E ; e++){
fff_matrix_get_row (v1,Msg,fff_array_get1d(tag,e));
for (j=0 ; j<n2 ;j++)
if (fff_vector_get(v1,j)<eps)
fff_vector_set(v1,j,eps);
fff_matrix_get_row (v2,belief, G->eA[e]);
fff_vector_div(v2,v1);
fff_matrix_set_row (PMsg, e, v2);
}
}
/* Final steps */
_fff_matrix_normalize_rows(belief);
fff_vector_delete(v2);
fff_vector_delete(v1);
fff_matrix_delete(old_belief);
fff_matrix_delete(initial_belief);
fff_matrix_delete(Msg);
fff_matrix_delete(PMsg);
for (e=0 ; e<E ; e++)
fff_matrix_delete(T[e]);
free(T);
fff_vector_delete(u);
fff_vector_delete(v);
fff_array_delete(tag);
fff_graph_delete(G);
return(1);
}
| 2.375 | 2 |
2024-11-18T21:19:13.777284+00:00 | 2019-03-30T19:06:37 | 680a83560f9217b3944bd72d6da1d1792d51d2fb | {
"blob_id": "680a83560f9217b3944bd72d6da1d1792d51d2fb",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-30T19:06:37",
"content_id": "7ede1dbd2e590894b45022856a59a988188da6fd",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "aab279291b9b5cfd2446e495996f6a566748dcba",
"extension": "c",
"filename": "mappingset.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": 1605,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/adt/mappingset.c",
"provenance": "stackv2-0128.json.gz:306664",
"repo_name": "ubuntu-repo/libfsm",
"revision_date": "2019-03-30T19:06:37",
"revision_id": "91e54adb32d90aa31abe92844b55eafe960630c5",
"snapshot_id": "0bb261057627d8ebcbe566b6f77d646fedba2b37",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ubuntu-repo/libfsm/91e54adb32d90aa31abe92844b55eafe960630c5/src/adt/mappingset.c",
"visit_date": "2020-05-05T06:01:08.139493"
} | stackv2 | /*
* Copyright 2019 Shannon F. Stewman
*
* See LICENCE for the full copyright terms.
*/
#include <assert.h>
#include <stdlib.h>
#include <adt/hashset.h>
#include <adt/mappingset.h>
/* Uses a hash set and a list to hold the items that are not yet done. */
struct mapping_set {
struct hashset *set;
};
struct mapping_set *
mapping_set_create(unsigned long (*hash)(const void *a), int (*cmp)(const void *a, const void *b))
{
struct mapping_set *set;
assert(hash != NULL);
assert(cmp != NULL);
set = malloc(sizeof *set);
if (set == NULL) {
return NULL;
}
set->set = hashset_create(hash, cmp);
if (set->set == NULL) {
free(set);
return NULL;
}
return set;
}
void
mapping_set_free(struct mapping_set *set)
{
if (set == NULL) {
return;
}
assert(set->set != NULL);
hashset_free(set->set);
free(set);
}
struct mapping *
mapping_set_add(struct mapping_set *set, struct mapping *item)
{
assert(set != NULL);
assert(set->set != NULL);
if (hashset_add(set->set, item) == NULL) {
return NULL;
}
return item;
}
struct mapping *
mapping_set_contains(const struct mapping_set *set, const struct mapping *item)
{
assert(set != NULL);
assert(set->set != NULL);
return hashset_contains(set->set, item);
}
void
mapping_set_clear(struct mapping_set *set)
{
assert(set != NULL);
assert(set->set != NULL);
hashset_clear(set->set);
}
struct mapping *
mapping_set_first(const struct mapping_set *set, struct mapping_iter *it)
{
return hashset_first(set->set, &it->iter);
}
struct mapping *
mapping_set_next(struct mapping_iter *it)
{
return hashset_next(&it->iter);
}
| 3.015625 | 3 |
2024-11-18T21:19:14.315821+00:00 | 2017-04-20T10:17:49 | 54e1988b4f35b7c90c3663451a06d704bd62a39a | {
"blob_id": "54e1988b4f35b7c90c3663451a06d704bd62a39a",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-20T10:17:49",
"content_id": "28013c06c5acffc4c2d442cbb2b075ef4c84de94",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ebd585fdafb22d31fcd6d04b209f81e88d1a2083",
"extension": "h",
"filename": "DDIRPM.h",
"fork_events_count": 10,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 88847837,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14275,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/boot_images/core/api/power/DDIRPM.h",
"provenance": "stackv2-0128.json.gz:307187",
"repo_name": "xusl/android-wilhelm",
"revision_date": "2017-04-20T10:17:49",
"revision_id": "13c59cb5b0913252fe0b5c672d8dc2bf938bb720",
"snapshot_id": "fd28144253cd9d7de0646f96ff27a1f4a9bec6e3",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/xusl/android-wilhelm/13c59cb5b0913252fe0b5c672d8dc2bf938bb720/boot_images/core/api/power/DDIRPM.h",
"visit_date": "2018-04-03T21:46:10.195170"
} | stackv2 | #ifndef __DDIRPM_H__
#define __DDIRPM_H__
#include "DalDevice.h"
#include "RPMTypes.h"
/***********************************
* DAL boilerplate *
***********************************/
#define DALRPM_INTERFACE_VERSION DALINTERFACE_VERSION(0,0)
typedef struct DalRPM DalRPM;
struct DalRPM
{
DalDevice DalDevice;
DALResult (*SendRequest)(DalDeviceHandle * _h, DAL_rpm_ResourceType Resource, uint32 DataLen, void * Data);
DALResult (*CreateMessage)(DalDeviceHandle * _h, DAL_rpm_MessageType * MessageHandle);
DALResult (*DestroyMessage)(DalDeviceHandle * _h, DAL_rpm_MessageType MessageHandle);
DALResult (*AppendRequest)(DalDeviceHandle * _h, DAL_rpm_MessageType MessageHandle, DAL_rpm_ResourceType Resource, uint32 DataLen, void * Data);
DALResult (*SendMessage)(DalDeviceHandle * _h, DAL_rpm_MessageType MessageHandle);
DALResult (*ConfigureSet)(DalDeviceHandle * _h, DAL_rpm_ConfigSetType ConfigSet);
DALResult (*SetAsyncMode)(DalDeviceHandle * _h, DALSYSEventHandle CompletedEvent, DALBOOL Polling);
DALResult (*RegisterForNotification)(DalDeviceHandle * _h, DAL_rpm_ResourceType Resource, DALSYSEventHandle UpdatedEvent);
DALResult (*GetStatus)(DalDeviceHandle * _h, DAL_rpm_ResourceType Resource, uint32 DataLen, void * Data);
DALResult (*SetTrigger)(DalDeviceHandle * _h, DAL_rpm_ConfigSetType FromSet, DAL_rpm_ConfigSetType ToSet, DAL_rpm_InterruptType Interrupts);
DALResult (*ClearTrigger)(DalDeviceHandle * _h, DAL_rpm_ConfigSetType FromSet, DAL_rpm_ConfigSetType ToSet, DAL_rpm_InterruptType Interrupts);
DALResult (*SetTimedTrigger)(DalDeviceHandle * _h, DAL_rpm_ConfigSetType FromSet, DAL_rpm_ConfigSetType ToSet, uint32 DurationSclks);
DALResult (*GetEnumByName)(DalDeviceHandle * _h, const char *Name, DAL_rpm_ResourceType *Resource);
DALResult (*GetResourceSize)(DalDeviceHandle * _h, DAL_rpm_ResourceType Resource, uint32 *ResourceSize);
};
typedef struct DalRPMHandle DalRPMHandle;
struct DalRPMHandle
{
uint32 dwDalHandleId;
const DalRPM * pVtbl;
void * pClientCtxt;
};
#define DAL_RPMDeviceAttach(DevId,hDalDevice)\
DAL_DeviceAttachEx(NULL,DevId,DALRPM_INTERFACE_VERSION,hDalDevice)
/***********************************
* Requests *
***********************************/
/* General blanket statement for requests: acknowledgements are returned in the
* very same structure you pass the request in. This works on the assumption
* that the ack mirrors the request on an accepted request, and resembles a
* valid request on a rejected request. */
/* Sends request to RPM. Which set the request is applied to and whether this
* call blocks is determined by the client state (see below for the functions
* used to manipulate your driver's state, however the default configuration
* is a synchronous call). The request is sent immediately. */
static __inline DALResult
DalRPM_SendRequest(DalDeviceHandle * _h, DAL_rpm_ResourceType Resource, uint32 DataLen, void * Data)
{
return ((DalRPMHandle *)_h)->pVtbl->SendRequest( _h, Resource, DataLen, Data);
}
/***********************************
* Multi-part Requests *
***********************************/
/* Allocate a workspace where a multiple-request message can be built. */
static __inline DALResult
DalRPM_CreateMessage(DalDeviceHandle * _h, DAL_rpm_MessageType * MessageHandle)
{
return ((DalRPMHandle *)_h)->pVtbl->CreateMessage( _h, MessageHandle);
}
/* Destroy a workspace previously allocated with CreateMessage. The handle
* 'MessageHandle' should not be used after this call. */
static __inline DALResult
DalRPM_DestroyMessage(DalDeviceHandle * _h, DAL_rpm_MessageType MessageHandle)
{
return ((DalRPMHandle *)_h)->pVtbl->DestroyMessage( _h, MessageHandle);
}
/* Appends a request to the message represented by MessageHandle (previously
* allocated by CreateMessage). This function will overwrite any previously
* appended requests for the same resource. The request is not sent to the
* RPM until SendMessage is called. */
static __inline DALResult
DalRPM_AppendRequest(DalDeviceHandle * _h, DAL_rpm_MessageType MessageHandle, DAL_rpm_ResourceType Resource, uint32 DataLen, void * Data)
{
return ((DalRPMHandle *)_h)->pVtbl->AppendRequest( _h, MessageHandle, Resource, DataLen, Data);
}
/* Send the message represented by MessageHandle (previously allocated by
* CreateMessage) to the RPM. Which set the request is applied to and
* whether this call blocks until acknowledged is determined by the client
* state, set using the functions below.
*
* Note: sending a message virtually 'clears' a message's contents. If you
* need to send the same request a second time, you will have to re-append it
* into the message to get it flagged as 'dirty' before sending again. A
* client configuration might be available to modify this behavior at a later
* date, please contact the author if you need it. */
static __inline DALResult
DalRPM_SendMessage(DalDeviceHandle * _h, DAL_rpm_MessageType MessageHandle)
{
return ((DalRPMHandle *)_h)->pVtbl->SendMessage( _h, MessageHandle);
}
/***********************************
* Client (per-driver) state *
***********************************/
/* First, a word about configuration sets.
*
* There can be 'n' configuration sets in a given system (where 'n' varies by
* target), and a set can be configured to be entered or left upon a certain
* trigger (e.g. an interrupt or timer). These sets can be pre-filled with
* requests for servicing a specific use case or mode.
*
* However, certain sets serve special purposes above and beyond merely being
* a set of cached requests. The first active set, referred to as
* DAL_RPM_CONFIG_SET_ACTIVE_0, is considered the "primary" set. When a driver
* on the RPM is evaluating whether enough resources are available to satisfy
* a request, the resources are available only if the primary requests from all
* other masters allow for it. Thus, the primary request for a given resource
* should always be the "most intensive" request, to assure that requests to
* other sets can be satisfied.
*
* Additionally, if a set other than the primary set becomes active, but no
* request has been set up for a resource in that set, the set inherits the
* current request configured for that resource in the primary set. */
/* Change which configuration set requests from this client are directed to.
* Most drivers will not need this function, as intially the configuration
* is always to configure the primary set. */
static __inline DALResult
DalRPM_ConfigureSet(DalDeviceHandle * _h, DAL_rpm_ConfigSetType ConfigSet)
{
return ((DalRPMHandle *)_h)->pVtbl->ConfigureSet( _h, ConfigSet);
}
/* Configure requests from this client to be either blocking or asynchronous.
* If a valid event handle is passed for CompletedEvent, all future requests
* (SendRequest, SendMessage) will be completed asynchronously and the event
* triggered when the acknowledgement has been received.
*
* If CompletedEvent == NULL, future calls will be blocking (synchronous).
*
* If Polling == TRUE, CompletedEvent is ignored, the call is blocking, and
* the RPM response interrupt is polled for in-function. This mode should
* only be used if interrupts are locked at the time of request. */
static __inline DALResult
DalRPM_SetAsyncMode(DalDeviceHandle * _h, DALSYSEventHandle CompletedEvent, DALBOOL Polling)
{
return ((DalRPMHandle *)_h)->pVtbl->SetAsyncMode( _h, CompletedEvent, Polling);
}
/***********************************
* Notification *
***********************************/
/* Client passes a valid event UpdatedEvent which will be triggered whenever
* a status change in the requested Resource is received. */
static __inline DALResult
DalRPM_RegisterForNotification(DalDeviceHandle * _h, DAL_rpm_ResourceType Resource, DALSYSEventHandle UpdatedEvent)
{
return ((DalRPMHandle *)_h)->pVtbl->RegisterForNotification( _h, Resource, UpdatedEvent);
}
/***********************************
* Status Lookup *
***********************************/
/* Retrieves the status of a resource and copies it into the user provided
* buffer. If the length of the buffer is insufficient, error is returned. */
static __inline DALResult
DalRPM_GetStatus(DalDeviceHandle * _h, DAL_rpm_ResourceType Resource, uint32 DataLen, void * Data)
{
return ((DalRPMHandle *)_h)->pVtbl->GetStatus( _h, Resource, DataLen, Data);
}
/***********************************
* Trigger Config *
***********************************/
/* Triggers are the mechanism used to switch between configuration sets. There
* are two basic kinds of triggers: interrupt-based triggers, and timer-based
* triggers.
*
*
* == Interrupt-Based Triggers ==
*
* Interrupt-based triggers are set and cleared through the SetTrigger and
* ClearTrigger functions below. Their last parameter is a
* DAL_rpm_InterruptType which represents the mask of all interrupts that
* can potentially be supported by the RPM for triggering.
*
* Issuing one of these requests will basically send a request to the RPM
* to set up the trigger. The RPM can deny the trigger request for 3 possible
* reasons:
* 1) The interrupt being requested is an interrupt that the requesting
* master does not have permission to monitor. Even though all possible
* interrupts are represented by the InterruptType, the RPM will filter
* the requested trigger interrupts so that security is maintained.
*
* 2) The interrupt being requested cannot be used to service the transition
* between the requested sets. For example, an interrupt that is mapped
* to the MPM can only be used for a transition from the sleep set to an
* active set--since the RPM doesn't have the interrupt mapped directly,
* it cannot be used for an active set to active set transition.
*
* 3) The interrupt is not supported by this version of the RPM.
*
*
* == Timer-Based Triggers ==
*
* Timer-based triggers are set and cleared through the SetTimedTrigger
* function. The last parameter is a uint32 representing the duration of the
* timer, in units of slow clock ticks (32768 Hz). Thus, the minimum time is
* 1 sclk (about 30.5 us) and the maximum time is 0xFFFFFFFF sclks (about
* 131,072 s or 36.4 hours). To clear a TimedTrigger, 'set' the trigger with
* a duration of '0'.
*
* When something causes the RPM to transition to the set represented by the
* FromSet of the timed trigger, the timer will start. If no other event
* causes a transition away from FromSet before the timer duration expires,
* then the RPM will transition this master to ToSet. If the master
* transitions away from FromSet before the timer expires, the timer is
* cancelled and restarted the next time FromSet is reached.
*
*
* == Config Set Wildcards ==
*
* Interrupt-based trigger functions accept DAL_RPM_CONFIG_SET_INVALID as a
* wildcard to either the FromSet or ToSet parameters (but not both at the
* same time).
*
* If the invalid set is passed as the FromSet parameter and your trigger is
* accepted, then any time that interrupt is received it will transition your
* master to ToSet, regardless of which set it was currently in.
*
* If the invalid set is passed as the ToSet parameter and your trigger is
* accepted, then whenever your trigger fires it will cause a transition to
* the previous *active* (not sleep) set that your master had selected. That
* language is hard to parse, so here's an example:
*
* [Master's state] <-- [Set a wildcarded ToSet would transition to]:
* - Active Set 0 <-- Active Set 0 (since there's no "history")
* - Active Set 2 <-- Active Set 0
* - Active Set 1 <-- Active Set 2
* - Active Set 4 <-- Active Set 1
* - Sleep Set <-- Active Set 4
* - Active Set 0 <-- Active Set 4 (sleep set is ignored by wildcarded ToSet)
* - Active Set 1 <-- Active Set 0
*
*
* == Wakeup Interrupts ==
*
* Wildcarding the ToSet parameter can be very useful for simply flagging an
* interrupt as a "wakeup" interrupt. For example, if you wanted to have
* the USB interrupt wake your master from sleep you could do
*
* DAL_rpm_InterruptType triggers = {0};
* triggers.u.bits.USB = 1;
* SetTrigger(<handle>, SLEEP_SET, INVALID_SET, triggers);
*
* That way, if the USB interrupt occurs while your master is sleeping, your
* master will automatically be transitioned back to its previously active set.
*/
/* sets the trigger */
static __inline DALResult
DalRPM_SetTrigger(DalDeviceHandle * _h, DAL_rpm_ConfigSetType FromSet, DAL_rpm_ConfigSetType ToSet, DAL_rpm_InterruptType Interrupts)
{
return ((DalRPMHandle *)_h)->pVtbl->SetTrigger( _h, FromSet, ToSet, Interrupts);
}
/* Clears Interrupts from triggering a transition from FromSet to ToSet.
* Note: Does not affect wildcarded triggers, which could still cause the
* transition being cleared here if the master happened to be in FromSet
* when the wildcarded trigger to ToSet came in. */
static __inline DALResult
DalRPM_ClearTrigger(DalDeviceHandle * _h, DAL_rpm_ConfigSetType FromSet, DAL_rpm_ConfigSetType ToSet, DAL_rpm_InterruptType Interrupts)
{
return ((DalRPMHandle *)_h)->pVtbl->ClearTrigger( _h, FromSet, ToSet, Interrupts);
}
/* sets or clears a timed trigger--use duration '0' to clear */
static __inline DALResult
DalRPM_SetTimedTrigger(DalDeviceHandle * _h, DAL_rpm_ConfigSetType FromSet, DAL_rpm_ConfigSetType ToSet, uint32 DurationSclks)
{
return ((DalRPMHandle *)_h)->pVtbl->SetTimedTrigger( _h, FromSet, ToSet, DurationSclks);
}
/***********************************
* Misc Functions *
***********************************/
static __inline DALResult
DalRPM_GetEnumByName(DalDeviceHandle * _h, const char *Name, DAL_rpm_ResourceType *Resource)
{
return ((DalRPMHandle *)_h)->pVtbl->GetEnumByName( _h, Name, Resource);
}
static __inline DALResult
DalRPM_GetResourceSize(DalDeviceHandle * _h, DAL_rpm_ResourceType Resource, uint32 *ResourceSize)
{
return ((DalRPMHandle *)_h)->pVtbl->GetResourceSize( _h, Resource, ResourceSize);
}
#endif
| 2.15625 | 2 |
2024-11-18T21:19:16.708120+00:00 | 2021-03-12T13:58:40 | 93afdbcf9ff4eababa5689eded3f33f73c09766c | {
"blob_id": "93afdbcf9ff4eababa5689eded3f33f73c09766c",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-12T13:58:40",
"content_id": "50ff32a7c4a754d08086b5107eb40fb71c009a14",
"detected_licenses": [
"MIT"
],
"directory_id": "7caaeb51133e00f8722fceab9a8a5c7283041905",
"extension": "h",
"filename": "thread.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": 1288,
"license": "MIT",
"license_type": "permissive",
"path": "/include/lk/thread.h",
"provenance": "stackv2-0128.json.gz:307584",
"repo_name": "lionkor/lk-c",
"revision_date": "2021-03-12T13:58:40",
"revision_id": "53c11a1c5ae2606c81b3130c50e48419fb8a5885",
"snapshot_id": "46384473171e141a01bb7c95adee79dcdb153252",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lionkor/lk-c/53c11a1c5ae2606c81b3130c50e48419fb8a5885/include/lk/thread.h",
"visit_date": "2023-03-17T22:13:56.233158"
} | stackv2 | #pragma once
#include "chan.h"
#include "common.h"
#include <stdlib.h>
#if defined(LK_WIN)
#error platform not yet implemented
#elif defined(LK_POSIX)
#define lk_compat_thread_type pthread_t
#define lk_compat_thread_create(thread, fn, args) pthread_create(thread, NULL, fn, args)
#define lk_compat_thread_join(thread, retval_ptr_ptr) pthread_join(thread, retval_ptr_ptr)
#define lk_compat_thread_exit(return_value) pthread_exit(return_value)
#define lk_compat_thread_detach(thread) pthread_detach(thread)
#else
#error platform not supported
#endif
typedef void* (*LKThreadFunction)(void*);
typedef struct {
long id;
lk_compat_thread_type _thread;
LKChannel _status_channel;
} LKThread;
// Creates a thread, starts it, returns when the thread is running.
// Unlike a normal pthread or similar OS-thread, this guarantees that the thread is valid
// and running after the call.
// After this call LKThread.id is also populated with the thread's id as assigned
// by the operating system.
bool LK_PUBLIC lk_thread_create(LKThread*, LKThreadFunction fn, void* restrict args);
// waits for the thread to terminate
bool LK_PUBLIC lk_thread_join(LKThread*, void** return_value);
void LK_PUBLIC LK_NORETURN lk_thread_exit(void* value);
bool LK_PUBLIC lk_thread_detach(LKThread*);
| 2.453125 | 2 |
2024-11-18T21:19:17.015304+00:00 | 2020-09-23T04:05:32 | 1dff5f3fcf73db8681cdd1972c4301709ad7ee26 | {
"blob_id": "1dff5f3fcf73db8681cdd1972c4301709ad7ee26",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-23T04:05:32",
"content_id": "8e7851aa92cd61f0621cd7feb5e49e49e55d813a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "81d8d99c64a901bbec13676cd5342c6605f17eab",
"extension": "h",
"filename": "ccCArray.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": 6577,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/tool/ccCArray.h",
"provenance": "stackv2-0128.json.gz:307844",
"repo_name": "vyouyou/kof",
"revision_date": "2020-09-23T04:05:32",
"revision_id": "fb7340b7eb61779cc299d135189b65550685b625",
"snapshot_id": "a6cfb17355efbffd41d9816ee21d07948329ca11",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vyouyou/kof/fb7340b7eb61779cc299d135189b65550685b625/src/tool/ccCArray.h",
"visit_date": "2022-12-28T21:05:40.376525"
} | stackv2 | /*******************************************************************************
author : ljc
version : <1.0>
--------------------------------------------------------------------------------
info :
--------------------------------------------------------------------------------
*******************************************************************************/
#ifndef CC_ARRAY_H
#define CC_ARRAY_H
#include "ccMacros.h"
#include "CObject.h"
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define CC_INVALID_INDEX 0xffffffff
// Easy integration
#define CCARRAYDATA_FOREACH(__array__, __object__) \
__object__=__array__->arr[0]; for(unsigned int i=0, num=__array__->num; i<num; i++, __object__=__array__->arr[i]) \
typedef struct _ccArray {
unsigned int num, max;
CObject** arr;
} ccArray;
/** Allocates and initializes a new array with specified capacity */
ccArray* ccArrayNew(unsigned int capacity);
/** Frees array after removing all remaining objects. Silently ignores nil arr. */
void ccArrayFree(ccArray*& arr);
/** Doubles array capacity */
void ccArrayDoubleCapacity(ccArray *arr);
/** Increases array capacity such that max >= num + extra. */
void ccArrayEnsureExtraCapacity(ccArray *arr, unsigned int extra);
/** shrinks the array so the memory footprint corresponds with the number of items */
void ccArrayShrink(ccArray *arr);
/** Returns index of first occurrence of object, NSNotFound if object not found. */
unsigned int ccArrayGetIndexOfObject(ccArray *arr, CObject* object);
/** Returns a Boolean value that indicates whether object is present in array. */
bool ccArrayContainsObject(ccArray *arr, CObject* object);
/** Appends an object. Behavior undefined if array doesn't have enough capacity. */
void ccArrayAppendObject(ccArray *arr, CObject* object);
/** Appends an object. Capacity of arr is increased if needed. */
void ccArrayAppendObjectWithResize(ccArray *arr, CObject* object);
/** Appends objects from plusArr to arr.
Behavior undefined if arr doesn't have enough capacity. */
void ccArrayAppendArray(ccArray *arr, ccArray *plusArr);
/** Appends objects from plusArr to arr. Capacity of arr is increased if needed. */
void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr);
/** Inserts an object at index */
void ccArrayInsertObjectAtIndex(ccArray *arr, CObject* object, unsigned int index);
/** Swaps two objects */
void ccArraySwapObjectsAtIndexes(ccArray *arr, unsigned int index1, unsigned int index2);
/** Removes all objects from arr */
void ccArrayRemoveAllObjects(ccArray *arr);
/** Removes object at specified index and pushes back all subsequent objects.
Behavior undefined if index outside [0, num-1]. */
void ccArrayRemoveObjectAtIndex(ccArray *arr, unsigned int index, bool bReleaseObj = true);
/** Removes object at specified index and fills the gap with the last object,
thereby avoiding the need to push back subsequent objects.
Behavior undefined if index outside [0, num-1]. */
void ccArrayFastRemoveObjectAtIndex(ccArray *arr, unsigned int index);
void ccArrayFastRemoveObject(ccArray *arr, CObject* object);
/** Searches for the first occurrence of object and removes it. If object is not
found the function has no effect. */
void ccArrayRemoveObject(ccArray *arr, CObject* object, bool bReleaseObj = true);
/** Removes from arr all objects in minusArr. For each object in minusArr, the
first matching instance in arr will be removed. */
void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr);
/** Removes from arr all objects in minusArr. For each object in minusArr, all
matching instances in arr will be removed. */
void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr);
// #pragma mark -
// #pragma mark ccCArray for Values (c structures)
typedef struct _ccCArray {
unsigned int num, max;
void** arr;
} ccCArray;
/** Allocates and initializes a new C array with specified capacity */
ccCArray* ccCArrayNew(unsigned int capacity);
/** Frees C array after removing all remaining values. Silently ignores nil arr. */
void ccCArrayFree(ccCArray *arr);
/** Doubles C array capacity */
void ccCArrayDoubleCapacity(ccCArray *arr);
/** Increases array capacity such that max >= num + extra. */
void ccCArrayEnsureExtraCapacity(ccCArray *arr, unsigned int extra);
/** Returns index of first occurrence of value, NSNotFound if value not found. */
unsigned int ccCArrayGetIndexOfValue(ccCArray *arr, void* value);
/** Returns a Boolean value that indicates whether value is present in the C array. */
bool ccCArrayContainsValue(ccCArray *arr, void* value);
/** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */
void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, unsigned int index);
/** Appends an value. Behavior undefined if array doesn't have enough capacity. */
void ccCArrayAppendValue(ccCArray *arr, void* value);
/** Appends an value. Capacity of arr is increased if needed. */
void ccCArrayAppendValueWithResize(ccCArray *arr, void* value);
/** Appends values from plusArr to arr. Behavior undefined if arr doesn't have
enough capacity. */
void ccCArrayAppendArray(ccCArray *arr, ccCArray *plusArr);
/** Appends values from plusArr to arr. Capacity of arr is increased if needed. */
void ccCArrayAppendArrayWithResize(ccCArray *arr, ccCArray *plusArr);
/** Removes all values from arr */
void ccCArrayRemoveAllValues(ccCArray *arr);
/** Removes value at specified index and pushes back all subsequent values.
Behavior undefined if index outside [0, num-1].
@since v0.99.4
*/
void ccCArrayRemoveValueAtIndex(ccCArray *arr, unsigned int index);
/** Removes value at specified index and fills the gap with the last value,
thereby avoiding the need to push back subsequent values.
Behavior undefined if index outside [0, num-1].
@since v0.99.4
*/
void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, unsigned int index);
/** Searches for the first occurrence of value and removes it. If value is not found the function has no effect.
@since v0.99.4
*/
void ccCArrayRemoveValue(ccCArray *arr, void* value);
/** Removes from arr all values in minusArr. For each Value in minusArr, the first matching instance in arr will be removed.
@since v0.99.4
*/
void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr);
/** Removes from arr all values in minusArr. For each value in minusArr, all matching instances in arr will be removed.
@since v0.99.4
*/
void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr);
#endif // CC_ARRAY_H
| 2.125 | 2 |
2024-11-18T21:19:18.589895+00:00 | 2018-01-30T16:02:50 | a764074204b40e34de893456a22ac47a90bd240a | {
"blob_id": "a764074204b40e34de893456a22ac47a90bd240a",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-30T16:02:50",
"content_id": "c77777b1e1f7a4df35e9a1612d88285172efc38f",
"detected_licenses": [
"MIT"
],
"directory_id": "1289309f5f4b858534c9614de0485a0d8911228e",
"extension": "c",
"filename": "util_libc_example.c",
"fork_events_count": 0,
"gha_created_at": "2017-09-18T15:45:16",
"gha_event_created_at": "2017-09-18T15:45:16",
"gha_language": null,
"gha_license_id": null,
"github_id": 103959113,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1439,
"license": "MIT",
"license_type": "permissive",
"path": "/libutil/util_libc_example.c",
"provenance": "stackv2-0128.json.gz:308105",
"repo_name": "tmh1999/s390-tools",
"revision_date": "2018-01-30T16:02:50",
"revision_id": "1e6a9dbd56d005304d6befe3d31493addab15d09",
"snapshot_id": "a48bfa5f885fe01053acb8f9f3c7919e8c5485f7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/tmh1999/s390-tools/1e6a9dbd56d005304d6befe3d31493addab15d09/libutil/util_libc_example.c",
"visit_date": "2021-09-06T15:51:16.968319"
} | stackv2 | /**
* util_libc_example - Example program for util_libc
*
* Copyright IBM Corp. 2016, 2017
*
* s390-tools is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
//! [code]
#include <stdio.h>
#include <stdlib.h>
#include "lib/util_libc.h"
#include "lib/util_panic.h"
/*
* Demonstrate that out of memory is automatically handled via panic()
*/
int main(void)
{
unsigned long ulong_max = (unsigned long)-1;
void *ptr;
char *zeroes, *str;
/* Use util_strcat_realloc() for string concatenation */
fprintf(stderr, "Try to concatenate \"Hello\", \", \" and \"world!\": ");
str = util_strdup("Hello");
str = util_strcat_realloc(str, ", ");
str = util_strcat_realloc(str, "world!");
fprintf(stderr, "result = \"%s\"\n", str);
free(str);
/* One byte allocation should work */
fprintf(stderr, "Try to allocate 1 byte: ");
ptr = util_malloc(1);
fprintf(stderr, "done\n");
/* One byte zeroed-allocation should work */
fprintf(stderr, "Try to allocate 1 byte initialized with zeroes: ");
zeroes = util_zalloc(1);
fprintf(stderr, "done\n");
util_assert(*zeroes == 0, "Garbage found in zero initialized memory\n");
/* The next allocation will probably fail */
fprintf(stderr, "Try to allocate %lu bytes:\n", ulong_max);
ptr = util_malloc(ulong_max);
fprintf(stderr, "You should not see me (ptr=%p)!\n", ptr);
return EXIT_FAILURE;
}
//! [code]
| 2.953125 | 3 |
2024-11-18T21:19:18.763880+00:00 | 2023-08-29T02:15:47 | 0efef5e83d30e31bb429f94c32e59fa53c0a4cc4 | {
"blob_id": "0efef5e83d30e31bb429f94c32e59fa53c0a4cc4",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-29T02:15:47",
"content_id": "a412b2e38535c5823b3980202b3a318c6c70f733",
"detected_licenses": [
"MIT"
],
"directory_id": "419b66709fb0e0251d09bf6e73d29215db3b03ee",
"extension": "c",
"filename": "connection.c",
"fork_events_count": 23,
"gha_created_at": "2018-12-18T22:49:52",
"gha_event_created_at": "2023-09-08T19:06:16",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 162354291,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5635,
"license": "MIT",
"license_type": "permissive",
"path": "/swclt_test/cases/connection.c",
"provenance": "stackv2-0128.json.gz:308362",
"repo_name": "signalwire/signalwire-c",
"revision_date": "2023-08-29T02:15:47",
"revision_id": "055572cdcaaabd1a178aaa88600e885d38e565d5",
"snapshot_id": "b4a8e6581149f9221560449c50ee33b48b656c20",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/signalwire/signalwire-c/055572cdcaaabd1a178aaa88600e885d38e565d5/swclt_test/cases/connection.c",
"visit_date": "2023-08-31T13:44:24.866426"
} | stackv2 | /*
* Copyright (c) 2018-2020 SignalWire, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "swclt_test.h"
#include "../../src/connection.c"
static uint32_t g_protocol_response_cb_called;
static ks_status_t __on_incoming_cmd(swclt_conn_t *conn, swclt_cmd_t *cmd, void *cb_data)
{
printf("ON INCOMING COMMAND\n");
return KS_STATUS_SUCCESS;
}
static void __on_protocol_timeout_response(swclt_cmd_reply_t *reply, void *cb_data)
{
REQUIRE(reply);
REQUIRE(reply->type == SWCLT_CMD_TYPE_FAILURE);
REQUIRE(reply->failure_reason);
REQUIRE(reply->failure_status == KS_STATUS_TIMEOUT);
printf("Validated failure code, message: %s\n", reply->failure_reason);
swclt_cmd_reply_destroy(&reply);
g_protocol_response_cb_called++;
}
static void __on_protocol_result_response(swclt_cmd_reply_t *reply, void *cb_data)
{
REQUIRE(swclt_cmd_reply_ok(reply) == KS_STATUS_SUCCESS);
swclt_cmd_reply_destroy(&reply);
g_protocol_response_cb_called++;
}
void test_async(ks_pool_t *pool)
{
swclt_cmd_t *cmd;
SSL_CTX *ssl = create_ssl_context();
swclt_conn_t *conn;
ks_json_t *channels;
int i;
REQUIRE(!swclt_conn_connect(&conn, __on_incoming_cmd, NULL, &g_target_ident, NULL, NULL, NULL, NULL, ssl));
channels = ks_json_create_array();
ks_json_add_item_to_array(channels, BLADE_CHANNEL_MARSHAL(&(blade_channel_t){"a_channel", 0, 0}));
/* Create an async command (bogus command but will generate a reply at least) */
REQUIRE(cmd = CREATE_BLADE_PROTOCOL_PROVIDER_ADD_CMD_ASYNC(
__on_protocol_result_response,
NULL,
"a_protocol",
0,
0,
0,
NULL,
&channels,
1,
NULL));
/* And submit it */
REQUIRE(!swclt_conn_submit_request(conn, &cmd, NULL));
/* Wait for it to respond */
for (i = 0; i < 5 && g_protocol_response_cb_called == 0; i++) {
ks_sleep_ms(1000);
}
REQUIRE(g_protocol_response_cb_called == 1);
swclt_cmd_destroy(&cmd);
swclt_conn_destroy(&conn);
swclt_ssl_destroy_context(&ssl);
}
void test_ttl(ks_pool_t *pool)
{
SSL_CTX *ssl = create_ssl_context();
swclt_conn_t *conn;
swclt_cmd_t *cmd;
SWCLT_CMD_TYPE cmd_type;
ks_json_t *channels;
int i;
g_protocol_response_cb_called = 0;
REQUIRE(!swclt_conn_connect(&conn, __on_incoming_cmd, NULL, &g_target_ident, NULL, NULL, NULL, NULL, ssl));
channels = ks_json_create_array();
ks_json_add_item_to_array(channels, BLADE_CHANNEL_MARSHAL(&(blade_channel_t){"b_channel", 0, 0}));
REQUIRE(cmd = CREATE_BLADE_PROTOCOL_PROVIDER_ADD_CMD_ASYNC(
__on_protocol_timeout_response,
NULL,
"b_protocol",
0,
0,
0,
NULL,
&channels,
1,
NULL));
/* Lock the reader so we never get a response, forcing a timeout */
REQUIRE(cmd->response_ttl_ms == BLADE_PROTOCOL_TTL_MS);
REQUIRE(cmd->flags == BLADE_PROTOCOL_FLAGS);
REQUIRE(!ks_mutex_lock(conn->wss->wss_mutex));
/* And submit it */
REQUIRE(!swclt_conn_submit_request(conn, &cmd, NULL));
/* Wait for it to respond */
for (i = 0; i < 7 && g_protocol_response_cb_called == 0; i++) {
ks_sleep_ms(1000);
}
REQUIRE(g_protocol_response_cb_called == 1);
/* Don't forget to unlock the poor websocket reader */
REQUIRE(!ks_mutex_unlock(conn->wss->wss_mutex));
swclt_cmd_destroy(&cmd);
swclt_conn_destroy(&conn);
swclt_ssl_destroy_context(&ssl);
}
void test_ttl_heap(ks_pool_t *pool)
{
swclt_ttl_tracker_t *ttl = NULL;
ttl_tracker_create(pool, &ttl, NULL);
if (ttl->thread) {
ks_thread_request_stop(ttl->thread);
ks_thread_join(ttl->thread);
ks_thread_destroy(&ttl->thread); // don't want it
}
int i;
int min = INT_MAX;
for (i = 0; i < 100; i++) {
ks_uuid_t uuid = { 0 };
ks_uuid(&uuid);
int expiry = rand();
if (expiry < min) {
min = expiry;
}
if (ttl_heap_insert(ttl, expiry, uuid) != KS_STATUS_SUCCESS) {
printf("Failed to insert UUID = %s, TTL = %d, min = %d, root = %d, count = %d\n", ks_uuid_thr_str(&uuid), expiry, min, ttl->heap[TTL_HEAP_ROOT].expiry, ttl->count);
} else {
printf("Insert UUID = %s, TTL = %d, min = %d, root = %d, count = %d\n", ks_uuid_thr_str(&uuid), expiry, min, ttl->heap[TTL_HEAP_ROOT].expiry, ttl->count);
}
REQUIRE(ttl->heap[TTL_HEAP_ROOT].expiry == min);
}
min = 0;
while (ttl->count) {
REQUIRE(ttl->heap[TTL_HEAP_ROOT].expiry > 0);
printf("Remove UUID = %s, TTL = %d, count = %d\n", ks_uuid_thr_str(&ttl->heap[TTL_HEAP_ROOT].id), ttl->heap[TTL_HEAP_ROOT].expiry, ttl->count);
REQUIRE(ttl->heap[TTL_HEAP_ROOT].expiry >= min);
min = ttl->heap[TTL_HEAP_ROOT].expiry;
ttl_heap_remove(ttl);
}
ttl_tracker_destroy(&ttl);
}
void test_connection(ks_pool_t *pool)
{
test_async(pool);
test_ttl(pool);
test_ttl_heap(pool);
}
| 2.046875 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.