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:10:02.798556+00:00
| 2017-04-14T04:50:20 |
a057703f510f0f0dd771ad61cb108d4a7d1b5580
|
{
"blob_id": "a057703f510f0f0dd771ad61cb108d4a7d1b5580",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-14T04:50:20",
"content_id": "d94358574462d965547d46d10717c3dff35c0f1d",
"detected_licenses": [
"MIT"
],
"directory_id": "4eaa53d1091027113c37e79fe2fdae9a303b8eb9",
"extension": "c",
"filename": "sort_bench.c",
"fork_events_count": 4,
"gha_created_at": "2010-08-02T10:29:01",
"gha_event_created_at": "2019-11-25T15:00:30",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 812045,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2245,
"license": "MIT",
"license_type": "permissive",
"path": "/c/sort_bench.c",
"provenance": "stackv2-0065.json.gz:24656",
"repo_name": "jkraemer/ferret",
"revision_date": "2017-04-14T04:50:20",
"revision_id": "903e5def137b28ce699a233d24712e07839bcf96",
"snapshot_id": "58341c446abb813bcce135d83bf40fa228064ce7",
"src_encoding": "UTF-8",
"star_events_count": 16,
"url": "https://raw.githubusercontent.com/jkraemer/ferret/903e5def137b28ce699a233d24712e07839bcf96/c/sort_bench.c",
"visit_date": "2020-12-24T23:29:00.808628"
}
|
stackv2
|
#include "index.h"
#include "store.h"
#include "search.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void create_index(Store *store, Config config)
{
int i;
IndexWriter *iw;
Analyzer *a = whitespace_analyzer_new(true);
FieldInfos *fis = fis_new(STORE_NO, INDEX_UNTOKENIZED, TERM_VECTOR_NO);
char data[1000];
Document *doc;
index_create(store, fis);
fis_deref(fis);
iw = iw_open(store, a, &config);
//config.merge_factor = 10;
//config.min_merge_docs = 1000;
for (i = 0; i < 99999; i++) {
if (i%10000 == 0) printf("up to %d\n", i);
doc = doc_new();
sprintf(data, "<%d>", rand() % 1000000);
doc_add_field(doc, df_add_data(df_new("num"), data));
iw_add_doc(iw, doc);
doc_destroy(doc);
}
//iw_optimize(iw);
iw_close(iw);
}
int main(int argc, char **argv)
{
Config config = default_config;
Store *store = open_fs_store("./bench_index/");
Searcher *searcher;
Sort *sort = sort_new();
Query *q = tq_new("num", "<1234>");
TopDocs *td;
config.max_field_length = 0x7FFFFFFF;
config.max_buffer_memory = 0x40000000;
config.chunk_size = 0x8000000;
config.max_buffered_docs = 1000;
config.merge_factor = 11;
(void)argv;
if (argc == 2) {
create_index(store, config);
}
printf("sort_test\n");
clock_t time_taken = clock();
searcher = isea_new(ir_open(store));
sort_add_sort_field(sort, sort_field_int_new("num", false));
td = searcher_search(searcher, q, 0, 10, NULL, sort, NULL);
td_destroy(td);
q_deref(q);
sort_destroy(sort);
time_taken = clock() - time_taken;
printf("Took: %lu clocks in %0.3lf seconds\n", time_taken,
(double)time_taken/CLOCKS_PER_SEC);
printf("rangeq_test\n");
time_taken = clock();
q = rq_new("num", "<100000>", "<800000>", true, true);
td = searcher_search(searcher, q, 0, 10, NULL, NULL, NULL);
td_destroy(td);
q_deref(q);
time_taken = clock() - time_taken;
printf("Took: %lu clocks in %0.3lf seconds\n", time_taken,
(double)time_taken/CLOCKS_PER_SEC);
searcher_close(searcher);
store_deref(store);
return 0;
}
| 2.328125 | 2 |
2024-11-18T21:10:03.545690+00:00
| 2018-03-23T20:49:51 |
ebf4067addf1815ac96d7e7f7c0e73719b547455
|
{
"blob_id": "ebf4067addf1815ac96d7e7f7c0e73719b547455",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-23T20:49:51",
"content_id": "826166d03ee2eabc283031fb16ecd74bc8fe6346",
"detected_licenses": [
"MIT"
],
"directory_id": "13f5da16298df20ccec1cae0260178f7c2395a77",
"extension": "c",
"filename": "common.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 126496947,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4154,
"license": "MIT",
"license_type": "permissive",
"path": "/common.c",
"provenance": "stackv2-0065.json.gz:25043",
"repo_name": "llnns/SMPI-CourseWare",
"revision_date": "2018-03-23T20:49:51",
"revision_id": "c81b839ae08fb87cc94160e32f7404322bb3e1b1",
"snapshot_id": "0ce64adb5b9aaf422515cb919b1bb9f393eecb45",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/llnns/SMPI-CourseWare/c81b839ae08fb87cc94160e32f7404322bb3e1b1/common.c",
"visit_date": "2021-04-15T10:17:23.847927"
}
|
stackv2
|
#ifndef JULIA_COMMON
#define JULIA_COMMON 1
#include "common.h"
/* write_bmp_header():
*
* In:
* f: A file open for writing ('w')
* (width, height): image dimensions
*
* Return:
* 0 on success, -1 on failure
*
*/
int write_bmp_header(FILE *f, int width, int height) {
unsigned int row_size_in_bytes = width * 3 +
((width * 3) % 4 == 0 ? 0 : (4 - (width * 3) % 4));
// Define all fields in the bmp header
char id[2] = "BM";
unsigned int filesize = 54 + (int)(row_size_in_bytes * height * sizeof(char));
short reserved[2] = {0,0};
unsigned int offset = 54;
unsigned int size = 40;
unsigned short planes = 1;
unsigned short bits = 24;
unsigned int compression = 0;
unsigned int image_size = width * height * 3 * sizeof(char);
int x_res = 0;
int y_res = 0;
unsigned int ncolors = 0;
unsigned int importantcolors = 0;
// Write the bytes to the file, keeping track of the
// number of written "objects"
size_t ret = 0;
ret += fwrite(id, sizeof(char), 2, f);
ret += fwrite(&filesize, sizeof(int), 1, f);
ret += fwrite(reserved, sizeof(short), 2, f);
ret += fwrite(&offset, sizeof(int), 1, f);
ret += fwrite(&size, sizeof(int), 1, f);
ret += fwrite(&width, sizeof(int), 1, f);
ret += fwrite(&height, sizeof(int), 1, f);
ret += fwrite(&planes, sizeof(short), 1, f);
ret += fwrite(&bits, sizeof(short), 1, f);
ret += fwrite(&compression, sizeof(int), 1, f);
ret += fwrite(&image_size, sizeof(int), 1, f);
ret += fwrite(&x_res, sizeof(int), 1, f);
ret += fwrite(&y_res, sizeof(int), 1, f);
ret += fwrite(&ncolors, sizeof(int), 1, f);
ret += fwrite(&importantcolors, sizeof(int), 1, f);
// Success means that we wrote 17 "objects" successfully
return (ret != 17);
}
/*
* compute_julia_pixel(): compute RBG values of a pixel in a
* particular Julia set image.
*
* In:
* (x,y): pixel coordinates
* (width, height): image dimensions
* tint_bias: a float to "tweak" the tint (1.0 is "no tint")
* Out:
* rgb: an already-allocated 3-byte array into which R, G, and B
* values are written.
*
* Return:
* 0 in success, -1 on failure
*
*/
int compute_julia_pixel(int x, int y, int width, int height, float tint_bias, unsigned char *rgb) {
// Check coordinates
if ((x < 0) || (x >= width) || (y < 0) || (y >= height)) {
fprintf(stderr,"Invalid (%d,%d) pixel coordinates in a %d x %d image\n", x, y, width, height);
return -1;
}
// "Zoom in" to a pleasing view of the Julia set
float X_MIN = -1.6, X_MAX = 1.6, Y_MIN = -0.9, Y_MAX = +0.9;
float float_y = (Y_MAX - Y_MIN) * (float)y / height + Y_MIN ;
float float_x = (X_MAX - X_MIN) * (float)x / width + X_MIN ;
// Point that defines the Julia set
float julia_real = -.79;
float julia_img = .15;
// Maximum number of iteration
int max_iter = 300;
// Compute the complex series convergence
float real=float_y, img=float_x;
int num_iter = max_iter;
while (( img * img + real * real < 2 * 2 ) && ( num_iter > 0 )) {
float xtemp = img * img - real * real + julia_real;
real = 2 * img * real + julia_img;
img = xtemp;
num_iter--;
}
// Paint pixel based on how many iterations were used, using some funky colors
float color_bias = (float) num_iter / max_iter;
rgb[0] = (num_iter == 0 ? 200 : - 500.0 * pow(tint_bias, 1.2) * pow(color_bias, 1.6));
rgb[1] = (num_iter == 0 ? 100 : -255.0 * pow(color_bias, 0.3));
rgb[2] = (num_iter == 0 ? 100 : 255 - 255.0 * pow(tint_bias, 1.2) * pow(color_bias, 3.0));
return 0;
}
/* save_julia_set(): Save data as a bmp file
*
* In:
* name: name of file to save
* (width, height): image dimensions
* data: array with rgb data to save
*
* Return:
* 0 on success, -1 on failure
*
*/
int save_julia_set(char* name, int width, int height, unsigned char* data){
FILE *fp;
fp = fopen(name, "w+");
write_bmp_header(fp, width, height);
int t = 0;
for(int i=0; i < width*height*3; i++){
t += fwrite(data+i, sizeof(char), 1, fp);
}
fclose(fp);
return 0;
}
#endif
| 2.390625 | 2 |
2024-11-18T21:10:03.934137+00:00
| 2018-08-06T17:06:53 |
0382c7a137b5bb4d50ff24fce68f52370ecb2e1a
|
{
"blob_id": "0382c7a137b5bb4d50ff24fce68f52370ecb2e1a",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-06T17:06:53",
"content_id": "f11e7e9c7d1539341f8ca3a41e69f876265e9217",
"detected_licenses": [
"MIT"
],
"directory_id": "cbdee83b1ad10127758cfcb5f2b249abec036cd5",
"extension": "c",
"filename": "MSP430_shortcuts.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 135009612,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10490,
"license": "MIT",
"license_type": "permissive",
"path": "/src/MSP430_shortcuts.c",
"provenance": "stackv2-0065.json.gz:25172",
"repo_name": "AndreLaranjeira/ProximityAlarm",
"revision_date": "2018-08-06T17:06:53",
"revision_id": "661ba953610917bd081aaafa11650b8885bd0c4a",
"snapshot_id": "3eb8ff81553c107a5508791f55c70993224f4444",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AndreLaranjeira/ProximityAlarm/661ba953610917bd081aaafa11650b8885bd0c4a/src/MSP430_shortcuts.c",
"visit_date": "2020-03-18T17:09:32.328639"
}
|
stackv2
|
// MSP430 shortcuts module - Source code.
// Includes:
#include "../inc/MSP430_shortcuts.h"
// Functions:
int ConfigI2CMaster0(uint8_t ADDR, uint8_t clock, uint8_t BR0, uint8_t BR1) {
UCB0CTL1 = UCSWRST; // Put USCI-B0 in configuration mode.
UCB0CTL0 = (UCMST | UCMODE_3 | UCSYNC);
UCB0CTL1 |= (clock << 6);
UCB0BR0 = BR0;
UCB0BR1 = BR1;
UCB0I2COA = ADDR;
UCB0CTL1 &= ~UCSWRST; // Bring USCI-B0 out of configuration mode.
return 0;
}
int ConfigI2CMaster1(uint8_t ADDR, uint8_t clock, uint8_t BR0, uint8_t BR1) {
UCB1CTL1 = UCSWRST; // Put USCI-B0 in configuration mode.
UCB1CTL0 = (UCMST | UCMODE_3 | UCSYNC);
UCB1CTL1 |= (clock << 6);
UCB1BR0 = BR0;
UCB1BR1 = BR1;
UCB1I2COA = ADDR;
UCB1CTL1 &= ~UCSWRST; // Bring USCI-B0 out of configuration mode.
return 0;
}
int ConfigI2CB0Ports(void) {
SetPort(P3, SEL, 0);
SetPort(P3, DIR, 0);
SetPort(P3, REN, 0);
SetPort(P3, OUT, 0);
SetPort(P3, SEL, 1);
SetPort(P3, DIR, 1);
SetPort(P3, REN, 1);
SetPort(P3, OUT, 1);
return 0;
}
int ConfigI2CB1Ports(void) {
SetPort(P4, SEL, 1);
SetPort(P4, DIR, 1);
SetPort(P4, REN, 1);
SetPort(P4, OUT, 1);
SetPort(P4, SEL, 2);
SetPort(P4, DIR, 2);
SetPort(P4, REN, 2);
SetPort(P4, OUT, 2);
return 0;
}
int ConfigI2CSlave0(uint8_t ADDR) {
UCB0CTL1 = UCSWRST; // Put USCI-B0 in configuration mode.
UCB0CTL0 = (UCMODE_3 | UCSYNC);
UCB0CTL1 |= 0;
UCB0I2COA = ADDR;
UCB0CTL1 &= ~UCSWRST; // Bring USCI-B0 out of configuration mode.
return 0;
}
int ConfigI2CSlave1(uint8_t ADDR) {
UCB1CTL1 = UCSWRST; // Put USCI-B0 in configuration mode.
UCB1CTL0 = (UCMODE_3 | UCSYNC);
UCB1CTL1 |= 0;
UCB1I2COA = ADDR;
UCB1CTL1 &= ~UCSWRST; // Bring USCI-B0 out of configuration mode.
return 0;
}
int ConfigLCDM0(uint8_t ADDR, uint8_t BL) {
I2CM0StartTransmission(ADDR);
LCDM0Start4BitMode(LCD_WAIT0);
LCDM0SendByte(0x28, BL, LCD_INST, LCD_WAIT1); // Utilize both display lines;
LCDM0SendByte(0x08, BL, LCD_INST, LCD_WAIT1); // Shut display off;
LCDM0SendByte(0x01, BL, LCD_INST, LCD_WAIT3); // Clear LCD;
LCDM0SendByte(0x06, BL, LCD_INST, LCD_WAIT1); // Puts display in entry mode with cursor moving to the right. No display shifiting.
LCDM0SendByte(0x0C, BL, LCD_INST, LCD_WAIT1); // Turns display on with cursor blinking.
I2CM0StopTransmission();
return 0;
}
int ConfigLED1(void) {
// LED vermelho (P1.0).
SetPort(P1, DIR, 0); // Saída = 1.
ClearPort(P1, OUT, 0); // Output = 0.
return 0;
}
int ConfigLED2(void) {
// LED verde (P4.7).
SetPort(P4, DIR, 7); // Saída = 1.
ClearPort(P4, OUT, 7); // Output = 0.
return 0;
}
int ConfigS1(void) {
// Chave S1 (P2.1).
ClearPort(P2, DIR, 1); // Entrada = 0.
SetPort(P2, REN, 1); // REN = 1 para entradas.
SetPort(P2, OUT, 1); // IN = 1 if !S1.
return 0;
}
int ConfigS2(void) {
// Chave S2 (P1.1).
ClearPort(P1, DIR, 1); // Entrada = 0.
SetPort(P1, REN, 1); // REN = 1 para entradas.
SetPort(P1, OUT, 1); // IN = 1 if !S2.
return 0;
}
int ConfigUARTModule0(uint8_t clock, uint16_t BRW, uint8_t BRF, uint8_t BRS) {
SetPort(P3, DIR, 3); // P3.3 = TX de USCI-A0.
SetPort(P3, SEL, 3);
ClearPort(P3, DIR, 4); // P3.4 = RX de USCI-A0.
SetPort(P3, SEL, 4);
UCA0CTL1 |= UCSWRST; // Reset UCA0 module
UCA0CTL0 = 0;
UCA0CTL1 |= ((clock & 0x03) << 6);
UCA0BRW = BRW;
UCA0MCTL = (((BRF & 0x0F) << 4) | ((BRS & 0x07) << 3));
UCA0CTL1 &= ~UCSWRST;
return 0;
}
int Debounce(void) {
volatile int counter = 0xDFFF;
while(counter != 0)
counter--;
return 0;
}
int DelayMicrosseconds(uint16_t number) {
TA2CTL = TimerAConfiguration(SMCLK, 2);
while(TA2R <= number);
return 0;
}
int Delay40Microsseconds(uint16_t number) {
TA2EX0 = 4; // Divide clock by 5.
TA2CTL = (TimerAConfiguration(SMCLK, 2) | ID_3); // Divide clock by 8.
while(TA2R <= number);
TA2EX0 = 0;
return 0;
}
int DelaySeconds(uint8_t number) {
TA2EX0 = 7; // Divide clock by 8.
TA2CTL = (TimerAConfiguration(ACLK, 2) | ID_3); // Divide clock by 8 again.
if(number <= 127)
while(TA2R <= (number << 9));
else {
while(TA2R == 0); // Make sure the timer has started once.
while(TA2R != 0); // Approximately 128 seconds (One full timer loop).
while(TA2R <= ((number & 0x7F) << 9)); // Wait for the remaining seconds.
}
TA2EX0 = 0;
return 0;
}
int InitializePorts(void) {
// Removes warnings of uninitialized ports.
// This will set all ports to inputs with a pull-down resistor.
// Port initialization:
PADIR = 0x0000;
PAREN = 0xFFFF;
PAOUT = 0x0000;
PBDIR = 0x0000;
PBREN = 0xFFFF;
PBOUT = 0x0000;
PCDIR = 0x0000;
PCREN = 0xFFFF;
PCOUT = 0x0000;
PDDIR = 0x0000;
PDREN = 0xFFFF;
PDOUT = 0x0000;
return 0;
}
int InterruptDisableS1(void) {
// Chave S1 (P2.1).
ClearPort(P2, IE, 1); // S1 não pode realizar interrupções.
ClearPort(P2, IFG, 1);
return 0;
}
int InterruptDisableS2(void) {
// Chave S2 (P1.1).
ClearPort(P1, IE, 1); // S2 não pode realizar interrupções.
ClearPort(P1, IFG, 1);
return 0;
}
int InterruptEnableS1(void) {
// Chave S1 (P2.1).
ClearPort(P2, IFG, 1); // Limpa a IFG de S1 para impedir uma interrupção imediata.
SetPort(P2, IE, 1); // S1 pode gerar interrupções.
SetPort(P2, IES, 1); // Interrupções ocorrem quando S1: 1 -> S1: 0.
return 0;
}
int InterruptEnableS2(void) {
// Chave S2 (P1.1).
ClearPort(P1, IFG, 1); // Limpa a IFG de S2 para impedir uma interrupção imediata.
SetPort(P1, IE, 1); // S2 pode gerar interrupções.
SetPort(P1, IES, 1); // Interrupções ocorrem quando S2: 1 -> S2: 0.
return 0;
}
uint8_t I2CM0ReceiveData(void) {
uint8_t data;
while((UCB0IFG & UCRXIFG) == 0);
data = UCB0RXBUF;
return data;
}
int I2CM0RestartTransmission(uint8_t ADDR, uint8_t MODE) {
UCB0CTL1 &= ~UCTR;
UCB0I2CSA = ADDR;
while((UCB0STAT & UCBBUSY) != 0);
UCB0CTL1 |= (MODE | UCTXSTT);
return 0;
}
int I2CM0SendData(uint8_t data, uint16_t delay) {
while((UCB0IFG & UCTXIFG) == 0);
UCB0TXBUF = data;
while((UCB0CTL1 & UCTXSTT) != 0);
if((UCB0IFG & UCNACKIFG) != 0)
return -1;
DelayMicrosseconds(delay);
return 0;
}
int I2CM0StartTransmission(uint8_t ADDR) {
UCB0I2CSA = ADDR;
while((UCB0STAT & UCBBUSY) != 0);
UCB0CTL1 |= (UCTR | UCTXSTT);
return 0;
}
int I2CM0StopTransmission(void) {
UCB0CTL1 |= UCTXSTP;
while((UCB0CTL1 & UCTXSTP) != 0);
return 0;
}
int I2CM0TransmitDataSet(uint8_t ADDR, uint8_t *data_set,
uint16_t length, uint16_t data_delay) {
I2CM0StartTransmission(ADDR);
while(length != 0) {
if(I2CM0SendData(*data_set, data_delay) == -1)
return length;
else {
data_set++;
length--;
}
}
I2CM0StopTransmission();
return 0;
}
int LCDM0BacklightOFF(void) {
LCDM0SendByte(0x0C, LCD_BL_OFF, LCD_INST, LCD_WAIT3);
return 0;
}
int LCDM0BacklightON(void) {
LCDM0SendByte(0x0C, LCD_BL_ON, LCD_INST, LCD_WAIT3);
return 0;
}
int LCDM0CreateCharacter(uint8_t char_ADDR, uint8_t *design) {
unsigned int i;
uint8_t CGRAM_ADDR;
uint8_t CGRAM_prefix = (char_ADDR << 3);
uint8_t line;
if(char_ADDR > 8)
return -1;
for(i = 0; i < 8; i++) {
line = *design; // Get one line of the new character.
design++; // Increment design to point to next line;
CGRAM_ADDR = (CGRAM_prefix | i); // Configure address of the line.
LCDM0SendByte((0x40 | CGRAM_ADDR), 0, LCD_INST, LCD_WAIT1); // Point cursor to address of the line.
LCDM0SendByte(line, 0, LCD_DATA, LCD_WAIT2); // Write line to address.
}
return 0;
}
int LCDM0SendByte(uint8_t byte, uint8_t BL, uint8_t command, uint16_t delay) {
LCDM0SendNibble((byte >> 4), BL, command);
DelayMicrosseconds(LCD_WAIT0);
LCDM0SendNibble((byte & 0x0F), BL, command);
DelayMicrosseconds(delay);
return 0;
}
int LCDM0SendNibble(uint8_t nibble, uint8_t BL, uint8_t command) {
I2CM0SendData(((nibble << 4) | BL | command), LCD_WAIT0);
I2CM0SendData(((nibble << 4) | BL | command | LCD_EN), LCD_WAIT0);
I2CM0SendData(((nibble << 4) | BL | command), LCD_WAIT0);
return 0;
}
int LCDM0Start4BitMode(uint16_t delay) {
unsigned int i;
uint8_t sequenceFor4BitMode[12] = {0x30, 0x34, 0x30, 0x30, 0x34, 0x30,
0x30, 0x34, 0x30, 0x20, 0x24, 0x20};
for(i = 0; i < 12; i++)
I2CM0SendData(sequenceFor4BitMode[i], delay);
return 0;
}
int LCDM0UpdatePositions(uint8_t left, uint8_t right, uint8_t down, uint8_t up) {
uint8_t i;
// First line:
LCDM0SendByte(0x80, LCD_BL_ON, LCD_INST, LCD_WAIT1); // Put cursor on address 0x00.
for(i = (7 - left); i != 0; i--)
LCDM0SendByte(LCD_SPACE, LCD_BL_ON, LCD_DATA, LCD_WAIT2); // Write the spaces of the left bar.
for(i = left; i != 0; i--)
LCDM0SendByte(LCD_SQUARE, LCD_BL_ON, LCD_DATA, LCD_WAIT2); // Write the squares of the left bar.
LCDM0SendByte(0x89, LCD_BL_ON, LCD_INST, LCD_WAIT1); // Put cursor on address 0x09.
for(i = right; i != 0; i--)
LCDM0SendByte(LCD_SQUARE, LCD_BL_ON, LCD_DATA, LCD_WAIT2); // Write the squares of the right bar.
for(i = (7 - right); i != 0; i--)
LCDM0SendByte(LCD_SPACE, LCD_BL_ON, LCD_DATA, LCD_WAIT2); // Write the spaces of the right bar.
// Second line:
LCDM0SendByte(0xC0, LCD_BL_ON, LCD_INST, LCD_WAIT1); // Put cursor on address 0x40.
for(i = (7 - down); i != 0; i--)
LCDM0SendByte(LCD_SPACE, LCD_BL_ON, LCD_DATA, LCD_WAIT2); // Write the spaces of the down bar.
for(i = down; i != 0; i--)
LCDM0SendByte(LCD_SQUARE, LCD_BL_ON, LCD_DATA, LCD_WAIT2); // Write the squares of the down bar.
LCDM0SendByte(0xC9, LCD_BL_ON, LCD_INST, LCD_WAIT1); // Put cursor on address 0x49.
for(i = up; i != 0; i--)
LCDM0SendByte(LCD_SQUARE, LCD_BL_ON, LCD_DATA, LCD_WAIT2); // Write the squares of the up bar.
for(i = (7 - up); i != 0; i--)
LCDM0SendByte(LCD_SPACE, LCD_BL_ON, LCD_DATA, LCD_WAIT2); // Write the spaces of the up bar.
return 0;
}
int UARTM0SendString(char *data, uint16_t size) {
while(size != 0) {
UCA0TXBUF = (*data & 0x7F);
while(UCA0STAT & UCBUSY);
data++;
size--;
}
return 0;
}
| 2.1875 | 2 |
2024-11-18T21:10:04.439926+00:00
| 2022-06-14T15:52:32 |
0337591e13631bc98bccb1cff9ddeceff575e97d
|
{
"blob_id": "0337591e13631bc98bccb1cff9ddeceff575e97d",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-14T15:52:32",
"content_id": "225a650fb23f74770142e77c6cc119d6562cb18f",
"detected_licenses": [
"0BSD"
],
"directory_id": "155a91764db7a4b9252ea8f2c7e06b399a68686d",
"extension": "c",
"filename": "test-logstr.c",
"fork_events_count": 3,
"gha_created_at": "2019-07-02T18:11:39",
"gha_event_created_at": "2022-06-14T15:52:34",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 194913058,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4083,
"license": "0BSD",
"license_type": "permissive",
"path": "/test/test-logstr.c",
"provenance": "stackv2-0065.json.gz:25560",
"repo_name": "GrumpyOldTroll/libmcrx",
"revision_date": "2022-06-14T15:52:32",
"revision_id": "586722995c2a75b7ae7fda89c035ec4a542f42ef",
"snapshot_id": "978db5821b02b1682cdff2dd14cba73dabedf6d7",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/GrumpyOldTroll/libmcrx/586722995c2a75b7ae7fda89c035ec4a542f42ef/test/test-logstr.c",
"visit_date": "2022-06-20T20:50:17.351049"
}
|
stackv2
|
/*
* libmcrx - multicast receiving library
*
* Copyright (C) 2019 by Akamai Technologies
* Jake Holland <jakeholland.net@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted.
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <mcrx/libmcrx.h>
struct sub_info {
int npackets;
int got_5;
int log_callbacks;
};
static int receive_cb(struct mcrx_packet* pkt) {
unsigned int length = mcrx_packet_get_contents(pkt, 0);
printf("got packet, length=%u\n", length);
struct mcrx_subscription* sub = mcrx_packet_get_subscription(pkt);
struct sub_info* info = (struct sub_info*)mcrx_subscription_get_userdata(sub);
info->npackets += 1;
mcrx_packet_unref(pkt);
pkt = NULL;
if (info->npackets > 5) {
printf("unsubscribing\n");
struct mcrx_ctx* ctx = mcrx_subscription_get_ctx(sub);
mcrx_ctx_set_log_string_fn(ctx, NULL);
mcrx_subscription_leave(sub);
info->got_5 = 1;
}
if (info->npackets > 100) {
fprintf(stderr, "did not stop at 5 packets\n");
exit(1);
return MCRX_RECEIVE_STOP_CTX;
}
return MCRX_RECEIVE_CONTINUE;
}
static void string_log_fn(
struct mcrx_ctx *ctx,
int priority,
const char *file,
int line,
const char *fn,
const char *str) {
(void)priority;
struct sub_info *info = (struct sub_info*)mcrx_ctx_get_userdata(ctx);
info->log_callbacks += 1;
fprintf(stderr, "string_cb(%s:%d(%s)): %s", file, line, fn, str);
}
int
main(int argc, char *argv[])
{
(void)(argc);
(void)(argv);
struct mcrx_ctx *ctx;
struct mcrx_subscription *sub = NULL;
int err;
struct sub_info info = { .npackets=0 };
err = mcrx_ctx_new(&ctx);
if (err < 0) {
fprintf(stderr, "ctx_new failed\n");
return EXIT_FAILURE;
}
mcrx_ctx_set_userdata(ctx, (intptr_t)&info);
mcrx_ctx_set_log_priority(ctx, MCRX_LOGLEVEL_DEBUG);
mcrx_ctx_set_log_string_fn(ctx, string_log_fn);
mcrx_ctx_log_msg(ctx, MCRX_LOGLEVEL_INFO, __FILE__, __LINE__, __func__,
"checking log err capability\n");
if (info.log_callbacks < 1) {
fprintf(stderr, "log_err failed\n");
mcrx_ctx_unref(ctx);
return EXIT_FAILURE;
}
struct mcrx_subscription_config cfg = MCRX_SUBSCRIPTION_CONFIG_INIT;
err = mcrx_subscription_config_pton(&cfg, "23.212.185.5", "232.1.1.1");
if (err != 0) {
fprintf(stderr, "subscription_config_pton failed\n");
mcrx_ctx_unref(ctx);
return EXIT_FAILURE;
}
cfg.port = 5001;
err = mcrx_subscription_new(ctx, &cfg, &sub);
if (err != 0) {
fprintf(stderr, "new subscription failed\n");
mcrx_ctx_unref(ctx);
return EXIT_FAILURE;
}
mcrx_subscription_set_userdata(sub, (intptr_t)&info);
mcrx_subscription_set_receive_cb(sub, receive_cb);
mcrx_ctx_set_wait_ms(ctx, 5000);
err = mcrx_subscription_join(sub);
if (err != 0) {
fprintf(stderr, "subscription join failed\n");
mcrx_subscription_unref(sub);
mcrx_ctx_unref(ctx);
return EXIT_FAILURE;
}
do {
err = mcrx_ctx_receive_packets(ctx);
} while (!err || err == MCRX_ERR_TIMEDOUT);
if (err != MCRX_ERR_NOTHING_JOINED) {
fprintf(stderr, "subscription receive failed: %s\n", strerror(err));
mcrx_subscription_unref(sub);
mcrx_ctx_unref(ctx);
return EXIT_FAILURE;
}
mcrx_subscription_unref(sub);
mcrx_ctx_unref(ctx);
if (info.log_callbacks > 3) {
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
}
| 2.234375 | 2 |
2024-11-18T21:10:04.533750+00:00
| 2021-07-09T19:58:55 |
7dc8ad0bf2ef1c8a8bcd860f56ddb0fef33f9747
|
{
"blob_id": "7dc8ad0bf2ef1c8a8bcd860f56ddb0fef33f9747",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-09T19:58:55",
"content_id": "22b99280d4741bda3fbfd124f999923548b5555b",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "ee002afcdc55912ec8df6bb9360097e0c7944ecb",
"extension": "c",
"filename": "lib.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 384197656,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3744,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/rdb/Kernel/lib.c",
"provenance": "stackv2-0065.json.gz:25689",
"repo_name": "ncomerci/TP-SO",
"revision_date": "2021-07-09T19:58:55",
"revision_id": "cc532fb6a59f90e0dbc3d45fae0107f10e95bb14",
"snapshot_id": "5b0707f0ef0f91a85d21cdd9cb02b21502b0b346",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ncomerci/TP-SO/cc532fb6a59f90e0dbc3d45fae0107f10e95bb14/rdb/Kernel/lib.c",
"visit_date": "2023-06-12T14:35:43.280448"
}
|
stackv2
|
#include <stdint.h>
#include <lib.h>
#include <screen.h>
static int wrapSprintf(char * buff, const char *format, va_list pa);
static void _64Hexfill(int n, char * buffer);
uint32_t uintToBase(uint64_t value, char * buffer, uint32_t base);
void * memset(void * destination, int32_t c, uint64_t length)
{
uint8_t chr = (uint8_t)c;
char * dst = (char*)destination;
while(length--)
dst[length] = chr;
return destination;
}
void * memcpy(void * destination, const void * source, uint64_t length)
{
/*
* memcpy does not support overlapping buffers, so always do it
* forwards. (Don't change this without adjusting memmove.)
*
* For speedy copying, optimize the common case where both pointers
* and the length are word-aligned, and copy word-at-a-time instead
* of byte-at-a-time. Otherwise, copy by bytes.
*
* The alignment logic below should be portable. We rely on
* the compiler to be reasonably intelligent about optimizing
* the divides and modulos out. Fortunately, it is.
*/
uint64_t i;
if ((uint64_t)destination % sizeof(uint32_t) == 0 &&
(uint64_t)source % sizeof(uint32_t) == 0 &&
length % sizeof(uint32_t) == 0)
{
uint32_t *d = (uint32_t *) destination;
const uint32_t *s = (const uint32_t *)source;
for (i = 0; i < length / sizeof(uint32_t); i++)
d[i] = s[i];
}
else
{
uint8_t * d = (uint8_t*)destination;
const uint8_t * s = (const uint8_t*)source;
for (i = 0; i < length; i++)
d[i] = s[i];
}
return destination;
}
unsigned int strlen(const char *str) {
int i = 0;
while (str[i++] != 0);
return i - 1;
}
int strcmp(const char *s1, const char *s2) {
unsigned char c1, c2;
while ((c1 = *s1++) == (c2 = *s2++)) {
if (c1 == '\0')
return 0;
}
return c1 - c2;
}
int strcpy(char *dst, const char *src) {
int i = 0;
do {
dst[i] = src[i];
} while(src[i++] != 0);
return i;
}
int strcat(char *dst, const char *src) {
return strcpy(dst + strlen(dst) + 1, src);
}
int sprintf(char * buff, const char *format, ...) {
va_list pa; // Lista de parámetros
va_start(pa, format);
int ret = wrapSprintf(buff, format, pa);
va_end(pa);
return ret;
}
static int wrapSprintf(char * buff, const char *format, va_list pa) {
unsigned int i = 0;
char *tmp;
int num;
uint64_t unum;
int size;
while (*format != '\0') {
if (*format != '%') {
buff[i++] = *format;
format++;
continue;
}
format++;
switch(*format) {
case 'd': // Si es un decimal
num = va_arg(pa, int);
if (num < 0) {
buff[i++] = '-'; // Agrego signo
num = -num; // Convierto en positivo
}
size = uintToBase(num, buff + i, 10);
i += size;
break;
case 'u':
unum = va_arg(pa, int);
size = uintToBase(unum, buff + i, 10);
i += size;
break;
case 'p': // Si es pointer
buff[i++] = '0';
buff[i++] = 'x';
case 'x': // Si es hexadecimal
num = va_arg(pa, uint64_t);
size = uintToBase(num, buff + i, 16);
i += size;
break;
case 'X':
num = va_arg(pa, unsigned int);
size = uintToBase(num, buff + i, 16);
_64Hexfill(16 - size, buff + i);
i += 16;
break;
case 'o': // Si es octal
num = va_arg(pa, unsigned int);
size = uintToBase(num, buff + i, 8);
i += size;
break;
case 'c':
num = va_arg(pa, int);
buff[i++] = num;
break;
case 's':
tmp = va_arg(pa, char *);
size = strcpy(buff + i, tmp) - 1;
i += size;
break;
}
format++;
}
buff[i++] = '\0';
return i;
}
static void _64Hexfill(int n, char * buffer) {
for (int i = 15; i >= 0; i--) {
if (i >= n)
buffer[i] = buffer[i - n];
else
buffer[i] = '0';
}
buffer[16] = 0;
}
| 2.90625 | 3 |
2024-11-18T21:10:04.756908+00:00
| 2023-08-10T09:04:44 |
1bc5017de43f1bddd411323c3a1b47544e0b7c17
|
{
"blob_id": "1bc5017de43f1bddd411323c3a1b47544e0b7c17",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-10T09:04:44",
"content_id": "f026e0f5de6ec0a7f61c53eebb23a0300a297dce",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c6759b857e55991fea3ef0b465dbcee53fa38714",
"extension": "c",
"filename": "eeprom.c",
"fork_events_count": 96,
"gha_created_at": "2018-05-14T07:50:29",
"gha_event_created_at": "2023-08-27T19:03:52",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 133324605,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4798,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/gap8/rtos/pulp/pulp-os/drivers_deprecated/i2c/eeprom.c",
"provenance": "stackv2-0065.json.gz:25947",
"repo_name": "GreenWaves-Technologies/gap_sdk",
"revision_date": "2023-08-10T09:04:44",
"revision_id": "3fea306d52ee33f923f2423c5a75d9eb1c07e904",
"snapshot_id": "1b343bba97b7a5ce62a24162bd72eef5cc67e269",
"src_encoding": "UTF-8",
"star_events_count": 145,
"url": "https://raw.githubusercontent.com/GreenWaves-Technologies/gap_sdk/3fea306d52ee33f923f2423c5a75d9eb1c07e904/gap8/rtos/pulp/pulp-os/drivers_deprecated/i2c/eeprom.c",
"visit_date": "2023-09-01T14:38:34.270427"
}
|
stackv2
|
/*
* Copyright (C) 2018 ETH Zurich, University of Bologna and
* GreenWaves Technologies
*
* 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.
*/
/*
* Authors: Germain Haugou, ETH (germain.haugou@iis.ee.ethz.ch)
*/
#include "rt/rt_api.h"
#define HEADER_DATA_SIZE 4
void rt_eeprom_conf_init(rt_eeprom_conf_t *conf)
{
}
rt_eeprom_t *rt_eeprom_open(char *dev_name, rt_eeprom_conf_t *conf, rt_event_t *event)
{
int irq = rt_irq_disable();
rt_eeprom_conf_t def_conf;
if (conf == NULL)
{
conf = &def_conf;
rt_eeprom_conf_init(conf);
}
rt_i2c_conf_t i2c_conf;
rt_i2c_conf_init(&i2c_conf);
i2c_conf.id = conf->id;
i2c_conf.max_baudrate = 200000;
i2c_conf.cs = conf->cs;
rt_eeprom_t *handle = rt_alloc(RT_ALLOC_FC_DATA, sizeof(rt_eeprom_t));
if (handle == NULL) goto error;
handle->i2c_handle = rt_i2c_open(dev_name, &i2c_conf, NULL);
if (handle->i2c_handle == NULL)
{
rt_free(RT_ALLOC_FC_DATA, handle, sizeof(rt_eeprom_t));
goto error;
}
handle->header_data = rt_alloc(RT_ALLOC_PERIPH, HEADER_DATA_SIZE);
if (handle->i2c_handle == NULL)
{
rt_free(RT_ALLOC_PERIPH, handle->header_data, HEADER_DATA_SIZE);
rt_free(RT_ALLOC_FC_DATA, handle, sizeof(rt_eeprom_t));
goto error;
}
handle->current_event = NULL;
handle->first_pending = NULL;
if (event)
__rt_event_enqueue(event);
rt_irq_restore(irq);
return handle;
error:
rt_warning("[EEPROM] Failed to open eeprom device\n");
return NULL;
}
void rt_eeprom_close(rt_eeprom_t *handle, rt_event_t *event)
{
int irq = rt_irq_disable();
rt_i2c_close(handle->i2c_handle, NULL);
rt_free(RT_ALLOC_FC_DATA, handle, sizeof(rt_eeprom_t));
rt_irq_restore(irq);
}
static void __rt_eeprom_handle_current_copy(rt_eeprom_t *handle)
{
if (handle->send_header)
{
handle->header_data[0] = handle->current_addr >> 8;
handle->header_data[1] = handle->current_addr & 0xff;
handle->send_header = 0;
rt_i2c_write(handle->i2c_handle, handle->header_data, 2, 1, handle->current_event);
}
else
{
int size = handle->current_size;
// Max size for read is 256 due to the repeat command used in the i2c driver
// and 128 for writes due to the page size in the eeprom
int max_size = handle->is_write ? 128 : 256;
if (size > max_size)
size = max_size;
handle->send_header = 1;
if (handle->is_write)
{
rt_i2c_write_append(handle->i2c_handle, handle->current_data, size, 0, handle->current_event);
}
else
{
rt_i2c_read(handle->i2c_handle, handle->current_data, size, 0, handle->current_event);
}
handle->current_addr += size;
handle->current_data += size;
handle->current_size -= size;
}
}
static void __rt_eeprom_enqueue_transfer(rt_eeprom_t *handle, uint32_t addr, uint8_t *data, int size, int is_write, rt_event_t *event)
{
int irq = rt_irq_disable();
int async = event != NULL;
rt_event_t *call_event = __rt_wait_event_prepare(event);
if (handle->current_event)
{
#if 0
if (handle->first_pending)
handle->last_pending->next = copy;
else
handle->first_pending = copy;
copy->next = NULL;
handle->last_pending = copy;
#endif
}
else
{
handle->current_event = call_event;
handle->current_addr = addr;
handle->current_data = data;
handle->current_size = size;
handle->is_write = is_write;
handle->send_header = 1;
if (async)
{
}
else
{
while (1)
{
__rt_eeprom_handle_current_copy(handle);
if (!async)
__rt_wait_event(handle->current_event);
if (is_write && handle->send_header)
rt_time_wait_us(6000);
if (handle->current_size <= 0)
break;
handle->current_event = __rt_wait_event_prepare_blocking();
}
handle->current_event = NULL;
}
}
__rt_wait_event_check(event, call_event);
rt_irq_restore(irq);
}
void rt_eeprom_write(rt_eeprom_t *handle, uint32_t addr, uint8_t *data, int size, rt_event_t *event)
{
__rt_eeprom_enqueue_transfer(handle, addr, data, size, 1, event);
}
void rt_eeprom_read(rt_eeprom_t *handle, uint32_t addr, uint8_t *data, int size, rt_event_t *event)
{
__rt_eeprom_enqueue_transfer(handle, addr, data, size, 0, event);
}
| 2.234375 | 2 |
2024-11-18T21:10:04.998390+00:00
| 2023-08-17T16:08:06 |
5e3c449fd0371bc706533ce0cad5bc66af23388b
|
{
"blob_id": "5e3c449fd0371bc706533ce0cad5bc66af23388b",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-17T16:08:06",
"content_id": "5e88eec87f397e44477d82d86f50b207aa4382b6",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "eecd5e4c50d8b78a769bcc2675250576bed34066",
"extension": "c",
"filename": "ex93.c",
"fork_events_count": 169,
"gha_created_at": "2013-03-10T20:55:21",
"gha_event_created_at": "2023-03-29T11:02:58",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 8691401,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7398,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/mat/tests/ex93.c",
"provenance": "stackv2-0065.json.gz:26332",
"repo_name": "petsc/petsc",
"revision_date": "2023-08-17T16:08:06",
"revision_id": "9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9",
"snapshot_id": "3b1a04fea71858e0292f9fd4d04ea11618c50969",
"src_encoding": "UTF-8",
"star_events_count": 341,
"url": "https://raw.githubusercontent.com/petsc/petsc/9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9/src/mat/tests/ex93.c",
"visit_date": "2023-08-17T20:51:16.507070"
}
|
stackv2
|
static char help[] = "Test MatMatMult() and MatPtAP() for AIJ matrices.\n\n";
#include <petscmat.h>
extern PetscErrorCode testPTAPRectangular(void);
int main(int argc, char **argv)
{
Mat A, B, C, D;
PetscScalar a[] = {1., 1., 0., 0., 1., 1., 0., 0., 1.};
PetscInt ij[] = {0, 1, 2};
PetscReal fill = 4.0;
PetscMPIInt size, rank;
PetscBool isequal;
#if defined(PETSC_HAVE_HYPRE)
PetscBool test_hypre = PETSC_FALSE;
#endif
PetscFunctionBeginUser;
PetscCall(PetscInitialize(&argc, &argv, (char *)0, help));
#if defined(PETSC_HAVE_HYPRE)
PetscCall(PetscOptionsGetBool(NULL, NULL, "-test_hypre", &test_hypre, NULL));
#endif
PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
PetscCall(MatCreate(PETSC_COMM_WORLD, &A));
PetscCall(MatSetSizes(A, PETSC_DECIDE, PETSC_DECIDE, 3, 3));
PetscCall(MatSetType(A, MATAIJ));
PetscCall(MatSetFromOptions(A));
PetscCall(MatSetUp(A));
PetscCall(MatSetOption(A, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
if (rank == 0) PetscCall(MatSetValues(A, 3, ij, 3, ij, a, ADD_VALUES));
PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
/* Test MatMatMult() */
PetscCall(MatTranspose(A, MAT_INITIAL_MATRIX, &B)); /* B = A^T */
PetscCall(MatMatMult(B, A, MAT_INITIAL_MATRIX, fill, &C)); /* C = B*A */
PetscCall(MatMatMult(B, A, MAT_REUSE_MATRIX, fill, &C)); /* recompute C=B*A */
PetscCall(MatSetOptionsPrefix(C, "C_"));
PetscCall(MatMatMultEqual(B, A, C, 10, &isequal));
PetscCheck(isequal, PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP, "MatMatMult: C != B*A");
PetscCall(MatMatMult(C, A, MAT_INITIAL_MATRIX, fill, &D)); /* D = C*A = (A^T*A)*A */
PetscCall(MatMatMult(C, A, MAT_REUSE_MATRIX, fill, &D));
PetscCall(MatMatMultEqual(C, A, D, 10, &isequal));
PetscCheck(isequal, PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP, "MatMatMult: D != C*A");
PetscCall(MatDestroy(&B));
PetscCall(MatDestroy(&C));
PetscCall(MatDestroy(&D));
/* Test MatPtAP */
PetscCall(MatDuplicate(A, MAT_COPY_VALUES, &B)); /* B = A */
PetscCall(MatPtAP(A, B, MAT_INITIAL_MATRIX, fill, &C)); /* C = B^T*A*B */
PetscCall(MatPtAPMultEqual(A, B, C, 10, &isequal));
PetscCheck(isequal, PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP, "MatPtAP: C != B^T*A*B");
/* Repeat MatPtAP to test symbolic/numeric separation for reuse of the symbolic product */
PetscCall(MatPtAP(A, B, MAT_REUSE_MATRIX, fill, &C));
PetscCall(MatPtAPMultEqual(A, B, C, 10, &isequal));
PetscCheck(isequal, PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP, "MatPtAP(reuse): C != B^T*A*B");
PetscCall(MatDestroy(&C));
/* Test MatPtAP with A as a dense matrix */
{
Mat Adense;
PetscCall(MatConvert(A, MATDENSE, MAT_INITIAL_MATRIX, &Adense));
PetscCall(MatPtAP(Adense, B, MAT_INITIAL_MATRIX, fill, &C));
PetscCall(MatPtAPMultEqual(Adense, B, C, 10, &isequal));
PetscCheck(isequal, PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP, "MatPtAP(reuse): C != B^T*Adense*B");
PetscCall(MatDestroy(&Adense));
}
if (size == 1) {
/* A test contributed by Tobias Neckel <neckel@in.tum.de> */
PetscCall(testPTAPRectangular());
/* test MatMatTransposeMult(): A*B^T */
PetscCall(MatMatTransposeMult(A, A, MAT_INITIAL_MATRIX, fill, &D)); /* D = A*A^T */
PetscCall(MatScale(A, 2.0));
PetscCall(MatMatTransposeMult(A, A, MAT_REUSE_MATRIX, fill, &D));
PetscCall(MatMatTransposeMultEqual(A, A, D, 10, &isequal));
PetscCheck(isequal, PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP, "MatMatTranspose: D != A*A^T");
}
PetscCall(MatDestroy(&A));
PetscCall(MatDestroy(&B));
PetscCall(MatDestroy(&C));
PetscCall(MatDestroy(&D));
PetscCall(PetscFinalize());
return 0;
}
/* a test contributed by Tobias Neckel <neckel@in.tum.de>, 02 Jul 2008 */
PetscErrorCode testPTAPRectangular(void)
{
const int rows = 3, cols = 5;
int i;
Mat A, P, C;
PetscFunctionBegin;
/* set up A */
PetscCall(MatCreateSeqAIJ(PETSC_COMM_WORLD, rows, rows, 1, NULL, &A));
for (i = 0; i < rows; i++) PetscCall(MatSetValue(A, i, i, 1.0, INSERT_VALUES));
PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
/* set up P */
PetscCall(MatCreateSeqAIJ(PETSC_COMM_WORLD, rows, cols, 5, NULL, &P));
PetscCall(MatSetValue(P, 0, 0, 1.0, INSERT_VALUES));
PetscCall(MatSetValue(P, 0, 1, 2.0, INSERT_VALUES));
PetscCall(MatSetValue(P, 0, 2, 0.0, INSERT_VALUES));
PetscCall(MatSetValue(P, 0, 3, -1.0, INSERT_VALUES));
PetscCall(MatSetValue(P, 1, 0, 0.0, INSERT_VALUES));
PetscCall(MatSetValue(P, 1, 1, -1.0, INSERT_VALUES));
PetscCall(MatSetValue(P, 1, 2, 1.0, INSERT_VALUES));
PetscCall(MatSetValue(P, 2, 0, 3.0, INSERT_VALUES));
PetscCall(MatSetValue(P, 2, 1, 0.0, INSERT_VALUES));
PetscCall(MatSetValue(P, 2, 2, -3.0, INSERT_VALUES));
PetscCall(MatAssemblyBegin(P, MAT_FINAL_ASSEMBLY));
PetscCall(MatAssemblyEnd(P, MAT_FINAL_ASSEMBLY));
/* compute C */
PetscCall(MatPtAP(A, P, MAT_INITIAL_MATRIX, 1.0, &C));
PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
/* compare results */
/*
printf("C:\n");
PetscCall(MatView(C,PETSC_VIEWER_STDOUT_WORLD));
blitz::Array<double,2> actualC(cols, cols);
actualC = 0.0;
for (int i=0; i<cols; i++) {
for (int j=0; j<cols; j++) {
PetscCall(MatGetValues(C, 1, &i, 1, &j, &actualC(i,j)));
}
}
blitz::Array<double,2> expectedC(cols, cols);
expectedC = 0.0;
expectedC(0,0) = 10.0;
expectedC(0,1) = 2.0;
expectedC(0,2) = -9.0;
expectedC(0,3) = -1.0;
expectedC(1,0) = 2.0;
expectedC(1,1) = 5.0;
expectedC(1,2) = -1.0;
expectedC(1,3) = -2.0;
expectedC(2,0) = -9.0;
expectedC(2,1) = -1.0;
expectedC(2,2) = 10.0;
expectedC(2,3) = 0.0;
expectedC(3,0) = -1.0;
expectedC(3,1) = -2.0;
expectedC(3,2) = 0.0;
expectedC(3,3) = 1.0;
int check = areBlitzArrays2NumericallyEqual(actualC,expectedC);
validateEqualsWithParams3(check, -1 , "testPTAPRectangular()", check, actualC(check), expectedC(check));
*/
PetscCall(MatDestroy(&A));
PetscCall(MatDestroy(&P));
PetscCall(MatDestroy(&C));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*TEST
test:
test:
suffix: 2
nsize: 2
args: -matmatmult_via nonscalable
output_file: output/ex93_1.out
test:
suffix: 3
nsize: 2
output_file: output/ex93_1.out
test:
suffix: 4
nsize: 2
args: -matptap_via scalable
output_file: output/ex93_1.out
test:
suffix: btheap
args: -matmatmult_via btheap -matmattransmult_via color
output_file: output/ex93_1.out
test:
suffix: heap
args: -matmatmult_via heap
output_file: output/ex93_1.out
#HYPRE PtAP is broken for complex numbers
test:
suffix: hypre
nsize: 3
requires: hypre !complex
args: -matmatmult_via hypre -matptap_via hypre -test_hypre
output_file: output/ex93_hypre.out
test:
suffix: llcondensed
args: -matmatmult_via llcondensed
output_file: output/ex93_1.out
test:
suffix: scalable
args: -matmatmult_via scalable
output_file: output/ex93_1.out
test:
suffix: scalable_fast
args: -matmatmult_via scalable_fast
output_file: output/ex93_1.out
TEST*/
| 2.265625 | 2 |
2024-11-18T21:10:05.093270+00:00
| 2021-03-31T08:56:04 |
71d18cb1aa4340f145160d3fa5604e46147ec63f
|
{
"blob_id": "71d18cb1aa4340f145160d3fa5604e46147ec63f",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-31T08:56:04",
"content_id": "acf6e55b165013ecb5f567783841b9bd63df003f",
"detected_licenses": [
"MIT"
],
"directory_id": "68c453a90652d6dfb276dd134d56aeb6a4790c14",
"extension": "c",
"filename": "ss.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 352962023,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10181,
"license": "MIT",
"license_type": "permissive",
"path": "/lower/bdbm_drv/examples/stringsearch/ss.c",
"provenance": "stackv2-0065.json.gz:26460",
"repo_name": "dgist-datalab/BlockSSD",
"revision_date": "2021-03-31T08:56:04",
"revision_id": "f944a94455f56a42ee3a888431b71d7e555b7671",
"snapshot_id": "f8d8f027afc1f474f54c547c148ca800f4808ab3",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/dgist-datalab/BlockSSD/f944a94455f56a42ee3a888431b71d7e555b7671/lower/bdbm_drv/examples/stringsearch/ss.c",
"visit_date": "2023-03-30T22:37:10.271487"
}
|
stackv2
|
/*
The MIT License (MIT)
Copyright (c) 2014-2015 CSAIL, MIT
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <fcntl.h>
#include <linux/limits.h>
#include <linux/hdreg.h>
#include <linux/fs.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <blkid/blkid.h>
#include "ss_impl.h"
uint8_t* blk_buf = NULL;
typedef int (*compr_func)(const int fd_dev, const char* pattern, const int start_blk, const int len);
int __get_dev_start_ofs (char* devname)
{
int fd;
struct hd_geometry geo;
if ((fd = open (devname, O_RDONLY | O_NONBLOCK)) < 0) {
return -1;
}
if ((ioctl (fd, HDIO_GETGEO, &geo)) < 0) {
close (fd);
return -1;
}
close (fd);
return geo.start;
}
void __fibmap_display_file (const char* fname)
{
struct stat st;
int fd, nr_blks, blksz, i, ret;
char* devname = NULL;
int dev_start_blk = 0;
int spb = 0;
int start_blk = -1;
int len = 1;
#define TOLBA(spb, blk_no) (spb * blk_no)
if ((fd = open (fname, O_RDONLY | O_DIRECT | O_SYNC)) < 0) {
fprintf (stderr, "Cannot open %s: %s\n", fname, strerror (errno));
return;
}
/* get the block size */
if ((ret = ioctl (fd, FIGETBSZ, &blksz)) < 0) {
fprintf (stderr, "Cannot get block size of %s: %s\n", fname, strerror (errno));
close (fd);
return;
}
/* get fstat */
if ((ret = fstat (fd, &st)) < 0) {
fprintf (stderr, "Cannot fstat %s: %s\n", fname, strerror (errno));
close(fd);
return;
}
/* get the device name */
devname = blkid_devno_to_devname (st.st_dev);
/* get the start offset of the device */
dev_start_blk = __get_dev_start_ofs (devname);
printf ("\n");
printf ("%s:\n", devname);
printf ("start LBA = %d\n", dev_start_blk);
printf ("\n");
/* get # of blks for a file */
nr_blks = (st.st_size + blksz - 1) / blksz;
spb = blksz / 512;
printf ("%s:\n", fname);
printf ("# of blocks(4KB)/sectors(512B): %d/%d\n", nr_blks, nr_blks * spb);
printf ("\n");
printf ("-----------------------------------------------\n");
printf ("%15s\t%15s\t%15s\n", "begin_LBA", "end_LBA", "sectors");
for (i = 0; i < nr_blks; i++) {
int lba = i;
if ((ret = ioctl (fd, FIBMAP, &lba)) < 0) {
fprintf (stderr, "ioctl on %s failed: %s\n", fname, strerror (errno));
close (fd);
return;
}
if (start_blk == -1) {
start_blk = lba;
len = 1;
} else if (len == 32768) {
printf ("%15d\t%15d\t%15d\n",
TOLBA(spb, start_blk) + dev_start_blk,
TOLBA(spb, start_blk) + TOLBA(spb, len) + dev_start_blk - 1,
TOLBA(spb, len));
start_blk = lba;
len = 1;
} else if (lba == start_blk + len) {
len++;
} else {
printf ("%15d\t%15d\t%15d\n",
TOLBA(spb, start_blk) + dev_start_blk,
TOLBA(spb, start_blk) + TOLBA(spb, len) + dev_start_blk - 1,
TOLBA(spb, len));
start_blk = lba;
len = 1;
}
}
printf ("%15d\t%15d\t%15d\n",
TOLBA(spb, start_blk) + dev_start_blk,
TOLBA(spb, start_blk) + TOLBA(spb, len) + dev_start_blk - 1,
TOLBA(spb, len));
close (fd);
}
int __fibmap_search_file (const char* pattern, const char* fname, compr_func fp_comp)
{
struct stat st;
int fd, fd_dev, nr_blks, blksz, i, ret;
char* devname = NULL;
int start_blk = -1;
int len = 1;
int match = 0;
if ((fd = open (fname, O_RDONLY)) < 0) {
fprintf (stderr, "Cannot open %s: %s\n", fname, strerror (errno));
return -1;
}
/* get the block size */
if ((ret = ioctl (fd, FIGETBSZ, &blksz)) < 0) {
fprintf (stderr, "Cannot get block size of %s: %s\n", fname, strerror (errno));
close (fd);
return -1;
}
/* get fstat */
if ((ret = fstat (fd, &st)) < 0) {
fprintf (stderr, "Cannot fstat %s: %s\n", fname, strerror (errno));
close (fd);
return -1;
}
/* get the device name */
devname = blkid_devno_to_devname (st.st_dev);
if ((fd_dev = open64 (devname, O_RDONLY)) < 0) {
fprintf (stderr, "Cannot open %s: %s\n", devname, strerror (errno));
close (fd);
return -1;
}
/* get # of blks for a file */
nr_blks = (st.st_size + blksz - 1) / blksz;
/* if 'nr_blks' is 0, return 0 */
if (nr_blks == 0) {
close (fd);
close (fd_dev);
return 0;
}
for (i = 0; i < nr_blks; i++) {
int lba = i;
if ((ret = ioctl (fd, FIBMAP, &lba)) < 0) {
fprintf (stderr, "ioctl on %s failed: %s\n", fname, strerror (errno));
close (fd);
close (fd_dev);
return -1;
}
if (start_blk == -1) {
start_blk = lba;
len = 1;
} else if (len == 32768) {
if ((ret = fp_comp (fd_dev, pattern, start_blk, len)) < 0) {
printf ("fp_comp failed: %s %s %s %d %d\n", fname, devname, pattern, start_blk, len);
ret = 0;
}
match += ret;
start_blk = lba;
len = 1;
} else if (lba == start_blk + len) {
len++;
} else {
if ((ret = fp_comp (fd_dev, pattern, start_blk, len)) < 0) {
printf ("fp_comp failed: %s %s %s %d %d\n", fname, devname, pattern, start_blk, len);
ret = 0;
}
match += ret;
start_blk = lba;
len = 1;
}
}
if ((ret = fp_comp (fd_dev, pattern, start_blk, len)) < 0) {
printf ("fp_comp failed: %s %s %s %d %d\n", fname, devname, pattern, start_blk, len);
ret = 0;
}
match += ret;
close (fd);
close (fd_dev);
return match;
}
/* search the pattern in a single file */
int __fs_search_file (const char* pattern, const char* fname)
{
FILE* fp = NULL;
uint8_t* buf = NULL;
struct stat st;
off_t len;
int match = 0;
if ((fp = fopen (fname, "r")) == NULL) {
printf ("errors occur while opening a file (%s) (errno=%s)\n", fname, strerror (errno));
return -1;
}
if (fstat (fp->_fileno, &st)) {
printf ("errors occur while getting the size of a file (errno=%d)\n", errno);
fclose (fp);
return -1;
}
if (strlen (pattern) > st.st_size) {
fclose (fp);
return 0;
}
/* time taken to read a file */
if ((buf = (uint8_t*)malloc (sizeof (uint8_t) * st.st_size)) == NULL) {
fclose (fp);
return -1;
}
for (len = 0; len < st.st_size; ) {
len += fread (buf + len, 1, st.st_size - len, fp);
}
/* time taken to find a pattern */
for (len = 0; len <= st.st_size - strlen (pattern); len++) {
if (bcmp (buf + len, pattern, strlen (pattern)) == 0) {
match++;
}
}
if (buf)
free (buf);
if (fp)
fclose (fp);
return match;
}
/* NOTE: options
* - __fibmap_display_file: it is the same as hdparam --fibmap
* - __fibmap_search_file: search patterns using FIBMAP by SW or HW
* - __fs_search_file: search patterns using FS
*/
int search_pattern_file (const char* pattern, const char* fname)
{
int match = 0;
/*__fibmap_display_file (fname); *//* same as hdparam --fibmap */
/*match = __fibmap_search_file (pattern, fname, sw_comp);*/
/*match = __fibmap_search_file (pattern, fname, hw_comp);*/
match = __fs_search_file (pattern, fname);
return match;
}
int search_pattern_directory (const char* pattern, const char* fname, int lvl)
{
DIR* d_fh = NULL;
struct dirent* entry = NULL;
char longest_name[PATH_MAX+1];
int match = 0;
int ret;
if ((d_fh = opendir (fname)) == NULL) {
if (errno == ENOTDIR) {
/* if 'fname' is a normal file, then we run search_pattern_file */
/*printf ("%s\n", fname);*/
if ((ret = search_pattern_file (pattern, fname)) == -1) {
fprintf (stderr, "Couldn't search a file %s: %s\n", longest_name, strerror (errno));
exit (-1);
}
match += ret;
return match;
} else {
fprintf (stderr, "Couldn't open directory: %s (%d)\n", fname, errno);
exit (-1);
}
}
while ((entry = readdir (d_fh)) != NULL) {
/* exclude a current directory & a previous directory */
if (strlen (entry->d_name) == 2 && strncmp (entry->d_name, "..", 2) == 0)
continue;
if (strlen (entry->d_name) == 1 && strncmp (entry->d_name, ".", 1) == 0)
continue;
/* make a full name */
strncpy (longest_name, fname, PATH_MAX);
strncat (longest_name, "/", PATH_MAX);
strncat (longest_name, entry->d_name, PATH_MAX);
if (entry->d_type == DT_DIR) {
/*printf ("%s\n", longest_name);*/
if ((ret = search_pattern_directory (pattern, longest_name, lvl + 1)) == -1) {
fprintf (stderr, "Couldn't search a directory %s: %s\n", longest_name, strerror (errno));
exit (-1);
}
match += ret;
}
else {
/*printf ("%s\n", longest_name);*/
if ((ret = search_pattern_file (pattern, longest_name)) == -1) {
fprintf (stderr, "Couldn't search a file %s: %s\n", longest_name, strerror (errno));
exit (-1);
}
match += ret;
}
}
closedir (d_fh);
return match;
}
/* parse input arguments */
int parse_args (int argc, char** argv, char** pattern, char** fname)
{
if (argc == 3) {
*pattern = argv[1];
*fname = argv[2];
return 0;
}
return 1;
}
/* entry point */
int main (int argc, char** argv)
{
char* pattern = NULL;
char* fname = NULL;
int ret = 0;
if (parse_args (argc, argv, &pattern, &fname)) {
fprintf (stderr, "Usage: ss PATTERN FILE\n");
exit (-1);
}
if ((blk_buf = (uint8_t*)malloc (32768 * 4096)) == NULL) {
fprintf (stderr, "Cannot allocate memory for reading files: %s\n", strerror (errno));
exit (-1);
}
ret = search_pattern_directory (pattern, fname, 0);
printf ("%d\n", ret);
if (blk_buf)
free (blk_buf);
return ret;
}
| 2.296875 | 2 |
2024-11-18T21:10:05.271132+00:00
| 2016-09-21T12:02:53 |
f2fef1c47c8fb44cd60b76923df12a29a12a8130
|
{
"blob_id": "f2fef1c47c8fb44cd60b76923df12a29a12a8130",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-21T12:02:53",
"content_id": "1ddc36e749056ce070545bac7f8b8e31304b60a5",
"detected_licenses": [
"MIT"
],
"directory_id": "ecf246ceb7d111f6d0c88c6f4ac4f209a04567ab",
"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": 19308596,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2084,
"license": "MIT",
"license_type": "permissive",
"path": "/src/boot/main.c",
"provenance": "stackv2-0065.json.gz:26716",
"repo_name": "flukso/kube",
"revision_date": "2016-09-21T12:02:53",
"revision_id": "5ab6116f86ea0cd4e05c3d18b87367836dad088c",
"snapshot_id": "268a0852a7d3196620dcc11b2589f0007876c7b1",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/flukso/kube/5ab6116f86ea0cd4e05c3d18b87367836dad088c/src/boot/main.c",
"visit_date": "2021-08-06T22:37:20.419479"
}
|
stackv2
|
#define REMOTE_TYPE 0x4B12
#define PAIRING_GROUP 212
#define __VTOR_PRESENT 1
#include "LPC8xx.h"
#include <stdio.h>
#include "uart.h"
#include "rf69_12.h"
#include "iap_driver.h"
#ifndef DEBUG
#define printf(...)
#define dump(...)
#endif
static volatile uint32_t msTicks;
void SysTick_Handler (void) {
++msTicks;
}
static uint32_t millis () {
return msTicks;
}
static void sleep (uint32_t ms) {
uint32_t now = millis();
while ((millis() - now) < ms)
;
}
extern uint16_t _crc16_update (uint16_t crc, uint8_t data);
uint32_t hwId [4];
#include "boot.h"
static void configurePins (void) {
/* Enable clocks to IOCON & SWM */
LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 18) | (1 << 7);
#ifndef printf
/* UART0_TXD 9 */
/* UART0_RXD 8 */
LPC_SWM->PINASSIGN0 = 0xffff0809UL;
#endif
#define MODE0 3
#define MODE1 4
/* SPI0_SCK 7 */
LPC_IOCON->PIO0_7 &= ~(1 << MODE1);
LPC_SWM->PINASSIGN3 = 0x07ffffffUL;
/* SPI0_MOSI 4 */
LPC_IOCON->PIO0_4 &= ~(1 << MODE1);
/* SPI0_MISO 13 (repeater mode) */
LPC_IOCON->PIO0_13 |= (1 << MODE0);
/* SPI0_SSEL 14 */
LPC_IOCON->PIO0_14 &= ~(1 << MODE1);
LPC_SWM->PINASSIGN4 = 0xff0e0d04UL;
/* IRQ 17 */
LPC_IOCON->PIO0_17 &= ~(1 << MODE1);
/* EKMB INT */
LPC_IOCON->PIO0_15 &= ~(1 << MODE1);
/* LED 0 */
#define LED_PIN 0
LPC_GPIO_PORT->DIR0 |= (1 << LED_PIN);
#define MODE1 4
LPC_IOCON->PIO0_0 &= ~(1 << MODE1);
}
static void launchApp() {
printf("launchApp\n");
SCB->VTOR = (uint32_t) BASE_ADDR;
// __asm("LDR SP, [R0] ;Load new stack pointer address")
void (*fun)() = (void (*)()) ((uint32_t*) BASE_ADDR)[1];
printf("go!\n");
fun();
printf("launchApp failed\n");
}
int main (void) {
configurePins();
#ifndef printf
uart0Init(115200);
#endif
SysTick_Config(__SYSTEM_CLOCK/1000-1); // 1000 Hz
printf("clock %lu\n", __SYSTEM_CLOCK);
// int e = iap_init();
// printf("iap init %d\n", e);
uint32_t partId;
iap_read_part_id(&partId);
printf("part id 0x%04X\n", (int) partId);
iap_read_unique_id(hwId);
bootLoader();
launchApp();
return 0;
}
| 2.078125 | 2 |
2024-11-18T21:10:05.631594+00:00
| 2022-04-19T20:30:55 |
aca28eac3171f4c2c6a7b4249ac8653f9df1267f
|
{
"blob_id": "aca28eac3171f4c2c6a7b4249ac8653f9df1267f",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-19T20:30:55",
"content_id": "e5f373678bdc2a17125521444d85fb4f277cc14d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "109f2617ebdf3bbf0fc1119ca6dd9ee53645c828",
"extension": "c",
"filename": "stats.c",
"fork_events_count": 0,
"gha_created_at": "2016-08-23T23:37:53",
"gha_event_created_at": "2016-08-23T23:37:54",
"gha_language": null,
"gha_license_id": null,
"github_id": 66411628,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5468,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ext/couchbase_ext/stats.c",
"provenance": "stackv2-0065.json.gz:27101",
"repo_name": "3dna/couchbase-ruby-client",
"revision_date": "2022-04-19T20:30:55",
"revision_id": "827c14b38faf90a363a0b2a0a9f9f2089d60a5f3",
"snapshot_id": "be753f269794c4133365588d9c6d66a06e3b1ef8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/3dna/couchbase-ruby-client/827c14b38faf90a363a0b2a0a9f9f2089d60a5f3/ext/couchbase_ext/stats.c",
"visit_date": "2022-04-28T12:48:07.356566"
}
|
stackv2
|
/* vim: ft=c et ts=8 sts=4 sw=4 cino=
*
* Copyright 2011, 2012 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "couchbase_ext.h"
void
cb_stat_callback(lcb_t handle, const void *cookie, lcb_error_t error, const lcb_server_stat_resp_t *resp)
{
struct cb_context_st *ctx = (struct cb_context_st *)cookie;
struct cb_bucket_st *bucket = ctx->bucket;
VALUE stats, node, key, val, exc = Qnil, res;
node = resp->v.v0.server_endpoint ? STR_NEW_CSTR(resp->v.v0.server_endpoint) : Qnil;
exc = cb_check_error(error, "failed to fetch stats", node);
if (exc != Qnil) {
rb_ivar_set(exc, cb_id_iv_operation, cb_sym_stats);
ctx->exception = exc;
}
if (node != Qnil) {
key = STR_NEW((const char*)resp->v.v0.key, resp->v.v0.nkey);
val = STR_NEW((const char*)resp->v.v0.bytes, resp->v.v0.nbytes);
if (bucket->async) { /* asynchronous */
if (ctx->proc != Qnil) {
res = rb_class_new_instance(0, NULL, cb_cResult);
rb_ivar_set(res, cb_id_iv_error, exc);
rb_ivar_set(res, cb_id_iv_operation, cb_sym_stats);
rb_ivar_set(res, cb_id_iv_node, node);
rb_ivar_set(res, cb_id_iv_key, key);
rb_ivar_set(res, cb_id_iv_value, val);
cb_proc_call(bucket, ctx->proc, 1, res);
}
} else { /* synchronous */
if (NIL_P(exc)) {
stats = rb_hash_aref(ctx->rv, key);
if (NIL_P(stats)) {
stats = rb_hash_new();
rb_hash_aset(ctx->rv, key, stats);
}
rb_hash_aset(stats, node, val);
}
}
} else {
ctx->proc = Qnil;
if (bucket->async) {
cb_context_free(ctx);
}
}
(void)handle;
}
/*
* Request server statistics.
*
* @since 1.0.0
*
* Fetches stats from each node in cluster. Without a key specified the
* server will respond with a "default" set of statistical information. In
* asynchronous mode each statistic is returned in separate call where the
* Result object yielded (+#key+ contains the name of the statistical item
* and the +#value+ contains the value, the +#node+ will indicate the server
* address). In synchronous mode it returns the hash of stats keys and
* node-value pairs as a value.
*
* @overload stats(arg = nil)
* @param [String] arg argument to STATS query
* @yieldparam [Result] ret the object with +node+, +key+ and +value+
* attributes.
*
* @example Found how many items in the bucket
* total = 0
* c.stats["total_items"].each do |key, value|
* total += value.to_i
* end
*
* @example Found total items number asynchronously
* total = 0
* c.run do
* c.stats do |ret|
* if ret.key == "total_items"
* total += ret.value.to_i
* end
* end
* end
*
* @example Get memory stats (works on couchbase buckets)
* c.stats(:memory) #=> {"mem_used"=>{...}, ...}
*
* @return [Hash] where keys are stat keys, values are host-value pairs
*
* @raise [Couchbase::Error::Connect] if connection closed (see {Bucket#reconnect})
* @raise [ArgumentError] when passing the block in synchronous mode
*/
VALUE
cb_bucket_stats(int argc, VALUE *argv, VALUE self)
{
struct cb_bucket_st *bucket = DATA_PTR(self);
struct cb_context_st *ctx;
VALUE rv, exc, proc;
lcb_error_t err;
struct cb_params_st params;
if (!cb_bucket_connected_bang(bucket, cb_sym_stats)) {
return Qnil;
}
memset(¶ms, 0, sizeof(struct cb_params_st));
rb_scan_args(argc, argv, "0*&", ¶ms.args, &proc);
if (!bucket->async && proc != Qnil) {
rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
}
params.type = cb_cmd_stats;
params.bucket = bucket;
cb_params_build(¶ms);
ctx = cb_context_alloc_common(bucket, proc, params.cmd.stats.num);
err = lcb_server_stats(bucket->handle, (const void *)ctx,
params.cmd.stats.num, params.cmd.stats.ptr);
exc = cb_check_error(err, "failed to schedule stat request", Qnil);
cb_params_destroy(¶ms);
if (exc != Qnil) {
cb_context_free(ctx);
rb_exc_raise(exc);
}
bucket->nbytes += params.npayload;
if (bucket->async) {
cb_maybe_do_loop(bucket);
return Qnil;
} else {
if (ctx->nqueries > 0) {
/* we have some operations pending */
lcb_wait(bucket->handle);
}
exc = ctx->exception;
rv = ctx->rv;
cb_context_free(ctx);
if (exc != Qnil) {
rb_exc_raise(exc);
}
exc = bucket->exception;
if (exc != Qnil) {
bucket->exception = Qnil;
rb_exc_raise(exc);
}
return rv;
}
return Qnil;
}
| 2.078125 | 2 |
2024-11-18T21:10:05.822754+00:00
| 2020-12-29T00:07:07 |
423d2f1de2987538896309c99f4f90f76aa9716a
|
{
"blob_id": "423d2f1de2987538896309c99f4f90f76aa9716a",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-29T00:07:07",
"content_id": "d93dafb5113d75d0665ebaec7cad5e4f67e666d4",
"detected_licenses": [
"MIT"
],
"directory_id": "1bccb5b186a6f22eae4654b6e6b5f762fff2745d",
"extension": "c",
"filename": "Lab14-10(media-divisori-primo).c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 325136967,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2797,
"license": "MIT",
"license_type": "permissive",
"path": "/Laboratorio esercizi/Lab14-10(media-divisori-primo).c",
"provenance": "stackv2-0065.json.gz:27360",
"repo_name": "igor-lirussi/C-Exercises",
"revision_date": "2020-12-29T00:07:07",
"revision_id": "857a953c7a51ab45a7a58aa98f742fb57c63ffb7",
"snapshot_id": "babd1bbffed3b575c820b474c0a440a7545cfce9",
"src_encoding": "WINDOWS-1252",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/igor-lirussi/C-Exercises/857a953c7a51ab45a7a58aa98f742fb57c63ffb7/Laboratorio esercizi/Lab14-10(media-divisori-primo).c",
"visit_date": "2023-02-08T14:05:47.948532"
}
|
stackv2
|
#include <stdio.h>
main() {
// verificare se una digitazione sia un numero o una lettera
char lettera;
printf(" LETTERA O NUMERO? \n");
printf("inserisci una singola lettera o un singolo numero: \n");
scanf ("%c", &lettera );
switch (lettera)
{
case 65 ... 90:
printf("hai inserito lettera maiuscola");
break;
case 97 ... 122: // oppure case 'a' ... 'z' :
printf("hai inserito lettera minuscola");
break;
case 48 ... 57:
printf("hai inserito numero");
break;
default:
printf("nessun riscontro");
}
//dati n valori fare la media
/*media valori*/
printf("\n\n CALCOLO MEDIA \n");
int i, somma;
int voto, check;
float media;
somma = 0;
check = 1;
for (i=0;check == 1;i++)
{
check = scanf("%d", &voto); // check assume valore 0 se voto non è un intero
if (check == 1)
{
somma +=voto;
}
}
if (i>1) {
media = (float)somma / (i-1);
printf("media :%f", media);
}
else{
printf("nessun valore inserito");
}
//preso in ingresso num intero maggiore di 0 indicare tutti i divisori
/*DIVISORI*/
printf("\n\n DIVISORI \n\n");
int num, divisore, resto;
fflush(stdin);
printf("inserisci un numero maggiore di 0:");
scanf("%d", &num);
if (num <= 0)
printf("\nnon valido");
printf("\ndivisori:\n");
printf("\n%d",num); //divisibile per se stesso
divisore = num/2;
while (divisore>0)
{
resto = num % divisore;
if (resto==0)
{
printf("\n%d", divisore);
}
divisore -= 1;
}
// variante con il FOR
/*
for (i=2;i<=n/2;i++) {
if (n%i==0) {
printf("%d\n",i);
}
}
printf("%d",n);
*/
//dato un numero indicare se e' primo oppure no (primo = maggiore di uno e divisibile solo per se stesso)
printf("\n\n NUMERO PRIMO?\n\ninserisci un numero:");
int prim;
scanf("%d", &prim);
if (num<=1)
printf("\nnon valido\n");
divisore = prim/2;
while (divisore > 1){
if (prim%divisore==0)
{
printf("\n non e' primo!\n");
divisore = 0;
}
else
divisore-=1;
}
if (divisore==1) {
printf(" E' primo!");
}
//dato un numero indicare tutti i numeri primi inferiori
printf("\n NUMERI PRIMI INFERIORI A \n");
int z, ha_divisori;
printf("dammi un numero: ");
scanf("%d", &z);
for (ha_divisori=0;z>1 ; z--){
ha_divisori=0;
for (divisore=z/2; divisore>=2 && ha_divisori ==0 ; divisore--)
if ( z % divisore == 0 ) {
ha_divisori++;
}
}
if (ha_divisori==0) {
printf("%d \n", z);
}
return 0;
}
| 3.765625 | 4 |
2024-11-18T21:10:07.564587+00:00
| 2019-02-26T12:04:31 |
2edeb5a231bb6785848465a206a5ee9dfa474f0f
|
{
"blob_id": "2edeb5a231bb6785848465a206a5ee9dfa474f0f",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-26T12:04:31",
"content_id": "40a65855f1d6a93413e2350508a89e3815317e06",
"detected_licenses": [
"MIT"
],
"directory_id": "5a7ffb9d4d986971cc8982240ec86f4ab8fe985c",
"extension": "c",
"filename": "create_testdata.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 170435095,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 472,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/create_testdata.c",
"provenance": "stackv2-0065.json.gz:28003",
"repo_name": "takeoverjp/dlt-tools",
"revision_date": "2019-02-26T12:04:31",
"revision_id": "e5b111372d3b778e8764551136ed14365b149cc5",
"snapshot_id": "8f171f4db26b2ff7e57e366b5237f7cc51de747f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/takeoverjp/dlt-tools/e5b111372d3b778e8764551136ed14365b149cc5/tests/create_testdata.c",
"visit_date": "2020-04-22T14:12:07.059239"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <dlt/dlt.h>
DLT_DECLARE_CONTEXT(con_exa1);
int
main (void)
{
DLT_REGISTER_APP("EXA1", "First Example");
DLT_REGISTER_CONTEXT(con_exa1, "CON", "First context");
for (int i = 0; i < 10; i++)
DLT_LOG(con_exa1, DLT_LOG_INFO, DLT_STRING("Hello world!"), DLT_INT32(i));
DLT_LOG(con_exa1, DLT_LOG_INFO, DLT_STRING("line1\nline2\nline3"));
usleep(1000);
DLT_UNREGISTER_CONTEXT(con_exa1);
DLT_UNREGISTER_APP();
}
| 2.21875 | 2 |
2024-11-18T21:10:08.317879+00:00
| 2020-10-26T17:38:29 |
407b8c993f51a5ba3ae5e55edc367fc87af078e8
|
{
"blob_id": "407b8c993f51a5ba3ae5e55edc367fc87af078e8",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-26T17:46:03",
"content_id": "2be5ea76383beea25228b5fd8dc70a7406f3b2a3",
"detected_licenses": [
"MIT"
],
"directory_id": "5d6dcf6b34f923516276658f1c7a16d8bf4d8e75",
"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": 293584722,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6908,
"license": "MIT",
"license_type": "permissive",
"path": "/exercise8/main.c",
"provenance": "stackv2-0065.json.gz:28131",
"repo_name": "mortepau/TTK4147",
"revision_date": "2020-10-26T17:38:29",
"revision_id": "9831008dd6e2e859aa4cd4ddb44c533c5bc490b0",
"snapshot_id": "879cd45504134e9a5939a8a559af9863141ad472",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mortepau/TTK4147/9831008dd6e2e859aa4cd4ddb44c533c5bc490b0/exercise8/main.c",
"visit_date": "2023-01-04T12:47:16.377600"
}
|
stackv2
|
#include <native/task.h>
#include <native/timer.h>
#include <native/sem.h>
#include <native/mutex.h>
#include <sys/mman.h>
#include <rtdk.h>
#define BILLION 1000*1000*1000
#define MILLION 1000*1000
#define USE_MUTEX 1
#define DEADLOCK 1
RT_SEM barrier;
#if DEADLOCK
RT_MUTEX mtx_a, mtx_b;
typedef struct mutex {
RT_MUTEX *mtx;
int priority;
} mutex_t;
mutex_t mutex_a, mutex_b;
typedef struct task {
RT_TASK *task;
int base;
int current;
int last;
} task_t;
task_t task_low, task_high;
#else
#if USE_MUTEX
RT_MUTEX mtx;
#else
RT_SEM sem;
#endif
#endif
SRTIME time_step;
void busy_wait_us(unsigned long delay){
for(; delay > 0; delay--) {
rt_timer_spin(1000);
}
}
#if DEADLOCK
void icpp_lock(mutex_t mutex, task_t *task) {
rt_task_set_priority(task->task, mutex.priority);
if (task->current < mutex.priority) {
task->last = task->current;
task->current = mutex.priority;
}
rt_mutex_acquire(mutex.mtx, TM_INFINITE);
}
void icpp_unlock(mutex_t mutex, task_t *task) {
rt_mutex_release(mutex.mtx);
rt_task_set_priority(task->task, task->base);
if (task->current == mutex.priority) {
task->current = task->last;
task->last = task->base;
}
}
void fn_low(void* args){
rt_printf("LOW: Waiting...\n");
rt_sem_p(&barrier, TM_INFINITE);
rt_printf("LOW: Start\n");
rt_printf("LOW: Priority (%i, %i)\n", task_low.base, task_low.current);
icpp_lock(mutex_a, &task_low);
rt_printf("LOW: Resource A acquired\n");
rt_printf("LOW: Priority (%i, %i)\n", task_low.base, task_low.current);
busy_wait_us(3 * 1000);
rt_printf("LOW: Priority (%i, %i)\n", task_low.base, task_low.current);
icpp_lock(mutex_b, &task_low);
rt_printf("LOW: Resource B acquired\n");
rt_printf("LOW: Priority (%i, %i)\n", task_low.base, task_low.current);
rt_printf("LOW: Resource B released\n");
icpp_unlock(mutex_b, &task_low);
rt_printf("LOW: Priority (%i, %i)\n", task_low.base, task_low.current);
rt_printf("LOW: Resource A released\n");
icpp_unlock(mutex_a, &task_low);
rt_printf("LOW: Priority (%i, %i)\n", task_low.base, task_low.current);
busy_wait_us(1 * 1000);
rt_printf("LOW: Finished\n");
}
void fn_high(void* args){
rt_printf("HIGH: Waiting...\n");
rt_sem_p(&barrier, TM_INFINITE);
rt_printf("HIGH: Start\n");
rt_task_sleep(1 * time_step);
rt_printf("HIGH: Priority (%i, %i)\n", task_high.base, task_high.current);
icpp_lock(mutex_b, &task_high);
rt_printf("HIGH: Resource B acquired\n");
rt_printf("HIGH: Priority (%i, %i)\n", task_high.base, task_high.current);
busy_wait_us(1 * 1000);
rt_printf("HIGH: Priority (%i, %i)\n", task_high.base, task_high.current);
icpp_lock(mutex_a, &task_high);
rt_printf("HIGH: Resource A acquired\n");
rt_printf("HIGH: Priority (%i, %i)\n", task_high.base, task_high.current);
busy_wait_us(2 * 1000);
rt_printf("HIGH: Resource A released\n");
icpp_unlock(mutex_a, &task_high);
rt_printf("HIGH: Priority (%i, %i)\n", task_high.base, task_high.current);
rt_printf("HIGH: Resource B released\n");
icpp_unlock(mutex_b, &task_high);
rt_printf("HIGH: Priority (%i, %i)\n", task_high.base, task_high.current);
busy_wait_us(1 * 1000);
rt_printf("HIGH: Finished\n");
}
#else
void low(void* args){
rt_printf("LOW: Waiting...\n");
rt_sem_p(&barrier, TM_INFINITE);
RT_TASK *curtask;
RT_TASK_INFO curtaskinfo;
curtask = rt_task_self();
rt_task_inquire(curtask, &curtaskinfo);
rt_printf("LOW: Start\n");
#if USE_MUTEX
rt_mutex_acquire(&mtx, TM_INFINITE);
rt_task_inquire(curtask, &curtaskinfo);
rt_printf("LOW: Base (%i), Current (%i)\n", curtaskinfo.bprio, curtaskinfo.cprio);
#else
rt_sem_p(&sem, TM_INFINITE);
#endif
rt_printf("LOW: Aquired resource\n");
busy_wait_us(3 * 1000);
rt_printf("LOW: Finished\n");
#if USE_MUTEX
rt_mutex_release(&mtx);
#else
rt_sem_v(&sem);
#endif
}
void med(void* args){
rt_printf("MED: Waiting...\n");
rt_sem_p(&barrier, TM_INFINITE);
RT_TASK *curtask;
RT_TASK_INFO curtaskinfo;
curtask = rt_task_self();
rt_task_inquire(curtask, &curtaskinfo);
rt_printf("MED: Start\n");
rt_task_sleep(1 * time_step);
rt_printf("MED: Sleep finished\n");
busy_wait_us(5 * 1000);
rt_printf("MED: Finished\n");
}
void high(void* args){
rt_printf("HIGH: Waiting...\n");
rt_sem_p(&barrier, TM_INFINITE);
RT_TASK *curtask;
RT_TASK_INFO curtaskinfo;
curtask = rt_task_self();
rt_task_inquire(curtask, &curtaskinfo);
rt_printf("HIGH: Start\n");
rt_task_sleep(2 * time_step);
rt_printf("HIGH: Sleep finished\n");
#if USE_MUTEX
rt_mutex_acquire(&mtx, TM_INFINITE);
rt_task_inquire(curtask, &curtaskinfo);
rt_printf("HIGH: Base (%i), Current (%i)\n", curtaskinfo.bprio, curtaskinfo.cprio);
#else
rt_sem_p(&sem, TM_INFINITE);
#endif
rt_printf("HIGH: Aquired resource\n");
busy_wait_us(2 * 1000);
rt_printf("HIGH: Finished\n");
#if USE_MUTEX
rt_mutex_release(&mtx);
#else
rt_sem_v(&sem);
#endif
}
#endif
void synchronize(void* args){
rt_printf("SYNCHRONIZE\n\r");
rt_timer_spin(100*MILLION);
rt_sem_broadcast(&barrier);
rt_timer_spin(100*MILLION);
rt_sem_delete(&barrier);
}
int main(){
#if DEADLOCK
mlockall(MCL_CURRENT|MCL_FUTURE);
rt_print_auto_init(1);
time_step = rt_timer_ns2ticks(MILLION);
RT_TASK task_h;
RT_TASK task_l;
RT_TASK synchronizer;
task_low.task = &task_l;
task_high.task = &task_h;
rt_mutex_create(&mtx_a, "mutex A");
rt_mutex_create(&mtx_b, "mutex B");
mutex_a.mtx = &mtx_a;
mutex_a.priority = 10;
mutex_b.mtx = &mtx_b;
mutex_b.priority = 15;
rt_sem_create(&barrier, "barrier", 0, S_PRIO);
rt_task_create(&synchronizer, "SYNCHRONIZER", 0, 5, T_CPU(1));
rt_task_create(&task_l, "LOW", 0, 1, T_CPU(1));
task_low.current = 1;
task_low.base = 1;
task_low.last = 1;
rt_task_create(&task_h, "HIGH", 0, 3, T_CPU(1));
task_high.current = 3;
task_high.base = 3;
task_high.last = 3;
rt_task_start(&task_l, &fn_low, NULL);
rt_task_start(&task_h, &fn_high, NULL);
busy_wait_us(100);
rt_task_start(&synchronizer, &synchronize, NULL);
while(1);
rt_mutex_delete(&mtx_a);
rt_mutex_delete(&mtx_b);
return 0;
#else
mlockall(MCL_CURRENT|MCL_FUTURE);
rt_print_auto_init(1);
time_step = rt_timer_ns2ticks(MILLION);
RT_TASK tasks[3];
RT_TASK synchronizer;
#if USE_MUTEX
rt_mutex_create(&mtx, "mutex");
#else
rt_sem_create(&sem, "sem", 1, S_PRIO);
#endif
rt_sem_create(&barrier, "barrier", 0, S_PRIO);
rt_task_create(&synchronizer, "SYNCHRONIZER", 0, 5, T_CPU(1));
rt_task_create(&tasks[0], "LOW", 0, 1, T_CPU(1));
rt_task_create(&tasks[1], "MED", 0, 2, T_CPU(1));
rt_task_create(&tasks[2], "HIGH", 0, 3, T_CPU(1));
rt_task_start(&tasks[0], &low, NULL);
rt_task_start(&tasks[1], &med, NULL);
rt_task_start(&tasks[2], &high, NULL);
busy_wait_us(100);
rt_task_start(&synchronizer, &synchronize, NULL);
while(1);
#if USE_MUTEX
rt_mutex_delete(&mtx);
#else
rt_sem_delete(&sem);
#endif
return 0;
#endif
}
| 2.765625 | 3 |
2024-11-18T21:10:08.696998+00:00
| 2020-04-25T10:08:38 |
dfcdaeb6af09bccbf2cfbacdbd7f46e65e1c19e0
|
{
"blob_id": "dfcdaeb6af09bccbf2cfbacdbd7f46e65e1c19e0",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-25T10:08:38",
"content_id": "0520d4e2ca82715b5ac08257782da89e8542b86e",
"detected_licenses": [
"MIT"
],
"directory_id": "b3edb21ab5407167e064fd12b19ba850147e9790",
"extension": "c",
"filename": "Ret.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 257907218,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2170,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Flow/Ret.c",
"provenance": "stackv2-0065.json.gz:28388",
"repo_name": "fplu/Flow",
"revision_date": "2020-04-25T10:08:38",
"revision_id": "99570c1f257b5e4b2698e09a503b8898666d42e5",
"snapshot_id": "e2e624a25389e4b1644c6a11c06a45a004399bc7",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/fplu/Flow/99570c1f257b5e4b2698e09a503b8898666d42e5/src/Flow/Ret.c",
"visit_date": "2022-04-22T13:47:15.752551"
}
|
stackv2
|
#include "FlowMain.h"
BOOL ManageRet(
_In_ DOCKER* docker,
_In_opt_ THREAD_CONTEXT* context,
_In_ INSTRUCTION_READ* instructionRead,
_Inout_ OPCODE* buffer,
_Inout_ DWORD* bufferIndex,
_In_ DWORD bufferLength
) {
BOOL success = TRUE;
DWORD newInstructionLength = 0;
__try {
//STEP 0 check argument
if (context == NULL) {
success = FALSE;
__leave;
}
//STEP 1 : calc new instructions length
if (instructionRead->Opcode[instructionRead->EndOfPrefix] == IRET) {
//TODO
while (1) {
Beep(1000, 1000);
}
}
else if (instructionRead->Opcode[instructionRead->EndOfPrefix] == 0xC2) {
newInstructionLength += 8;
}
else if (instructionRead->Opcode[instructionRead->EndOfPrefix] == 0xC3) {
newInstructionLength += 8;
}
//STEP 2 : check if there is enough space for the new instruction
if (newInstructionLength + *bufferIndex + JMP_REL32_SIZE >= BUFFER_OPCODE_SIZE) {
success = FALSE;
__leave;
}
//STEP 3 : write the new instruction
if (instructionRead->Opcode[instructionRead->EndOfPrefix] == IRET) {
//TODO
}
else if (instructionRead->Opcode[instructionRead->EndOfPrefix] == 0xC2) {
buffer[*bufferIndex + 0] = 0x48; // lea rsp [rsp + 8 + imm16] // add rsp, 8 + imm16 without affecting rflag
buffer[*bufferIndex + 1] = 0x8D;
buffer[*bufferIndex + 2] = 0xA4;
buffer[*bufferIndex + 3] = 0x24;
*(DWORD*)(buffer + *bufferIndex + 4) = 0x8 + *(SHORT*)(instructionRead->Opcode + instructionRead->EndOfPrefix + 1);
*bufferIndex += 8;
}
else if (instructionRead->Opcode[instructionRead->EndOfPrefix] == 0xC3) {
buffer[*bufferIndex + 0] = 0x48; // lea rsp [rsp + 8 + imm16] // add rsp, 8 + imm16 without affecting rflag
buffer[*bufferIndex + 1] = 0x8D;
buffer[*bufferIndex + 2] = 0xA4;
buffer[*bufferIndex + 3] = 0x24;
*(DWORD*)(buffer + *bufferIndex + 4) = 0x8;
*bufferIndex += 8;
}
//STEP 4 : give the new value of Rip
docker->Rip = (void*)GetRetDest(instructionRead->Opcode + instructionRead->EndOfPrefix, (const void*)context->Rip, instructionRead->Length, (void*)context->Rsp, instructionRead->HasOperandSizePrefix);
}
__finally {
}
return success;
}
| 2.046875 | 2 |
2024-11-18T21:10:09.022619+00:00
| 2021-08-02T02:45:59 |
9ff21732e83e2fc45240ca3ca14198603a4945c3
|
{
"blob_id": "9ff21732e83e2fc45240ca3ca14198603a4945c3",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-02T02:45:59",
"content_id": "b684c800884d14cd22ab0c7fd2e2217a8ad94e1d",
"detected_licenses": [
"MIT"
],
"directory_id": "85d93c5b65ff1c4ca9660e15a70b2f9624d66c5c",
"extension": "c",
"filename": "180164170_a04.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 390206924,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7520,
"license": "MIT",
"license_type": "permissive",
"path": "/180164170_a04.c",
"provenance": "stackv2-0065.json.gz:28645",
"repo_name": "Xing-J/Assignment-4",
"revision_date": "2021-08-02T02:45:59",
"revision_id": "06581a0dbb071370ffbf5a85c8784502875baa5f",
"snapshot_id": "a7802b861d83c7049d099eb60ab35ae8a59d04e1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Xing-J/Assignment-4/06581a0dbb071370ffbf5a85c8784502875baa5f/180164170_a04.c",
"visit_date": "2023-06-29T11:18:47.176401"
}
|
stackv2
|
//CP386 Assignment 4
//Xing Jia 180164170
//Github URL: https://github.com/Xing-J/Assignment-4
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/stat.h>
#include <time.h>
#include <semaphore.h>
void *thread_run(void *thread);
void Run(int seq[]);
int comp(int one[],int two[]);
void try_all(int order,int q[],int Available[]);
typedef struct Customer{
int C_ID;
int Allocation[4];
int max[4];
int Need[4];
}Customer;
Customer *customers;
int matrix[5][4]={{6,4,7,3},{4,2,3,2},{2,5,3,3},{6,3,3,2},{5,5,7,5}};
int Available[4];
void request(int order,int q[],int Available[],int safe_sequence[]);
int safty_check(int Available[],int safe_sequence[]);
int release(int n,int rel[],int Available[]);
int status(int Available[]);
int main(int argc, char *argv[]){
printf("Number of Customers: 5\n");
int safe_sequence[5];
Customer* current_customers = (Customer*) malloc(sizeof(Customer)*5);
customers=current_customers;
for (int c=0;c<5;c++){
current_customers[c].C_ID=c;
for(int r=0;r<4;r++){
current_customers[c].Allocation[r]=0;
current_customers[c].max[r]=matrix[c][r];
current_customers[c].Need[r]=matrix[c][r];
}
}
int p =1;
int k=0;
while(argv[p]!=NULL){
k = atoi(argv[p]);
Available[p-1]=k;
p++;
}
printf("Currently Available resources: ");
for(k=0;k<4;k++){
printf("%d ",Available[k]);
}
printf("\n");
printf("Maximum resources from file:\n");
for(int k =0;k<5;k++){
for(int i = 0;i<4;i++){
printf("%d ",customers[k].max[i]);
}
printf("\n");
}
if (safty_check(Available,safe_sequence)==0){
printf("Error: not safe\n");
return;
}else{
char* command = malloc(sizeof(char*)*300);
while(1){
int input[4];
int thread_id;
printf("Enter command:\n");
fgets(command, 300, stdin);
char* token = strtok(command," ");
int i =0;
int mode =0;
while (token!=NULL){
if (i==0){
if(strcmp("RQ",token)==0){
mode =1;
}else if (strcmp("RL",token)==0){
mode = 2;
}else if (strcmp("Status\n",token)==0){
mode=3;
}else if (strcmp("Run\n",token)==0){
mode= 4;
}else if (strcmp("Exit\n",token)==0){
mode =5;
}else{
printf("ERROR: PLEASE INPUT RIGHT MODE COMMAND\n");
return;
}
}
else if (i==1){
thread_id = atoi(token);
}else{
input[i-2]=atoi(token);
}
token = strtok(NULL," ");
i++;
}
switch(mode){
case(1):
request(thread_id,input,Available,safe_sequence);
break;
case(2):
release(thread_id,input,Available);
break;
case(3):
status(Available);
break;
case(4):
if(safty_check(Available,safe_sequence)==1){
Run(safe_sequence);
for(int x =0;x<5;x++){
pthread_t c_thread;
pthread_attr_t n_thread;
pthread_attr_init(&n_thread);
c_thread = pthread_create(&c_thread,&n_thread,thread_run,&customers[safe_sequence[x]].C_ID);
sleep(2);
if(c_thread !=0){
printf("Thread Failed");
}
}pthread_exit(NULL);
}else{
printf("Current thread list is not safe, can not perform run threads\n");
return;
}
break;
case(5):
printf("Exiting");
exit(0);
break;
default:
printf("Error, Command is not correct");
break;
}
}
}
}
int safty_check(int Available[],int safe_sequence[]){
int temp[4];
int k = 0;
while(k<4){
temp[k] = Available[k];
k++;
}
int o=0;
int is_safe[5]={0,0,0,0,0};
for(int m=0;m<5;m++){
if(is_safe[m]==0 && customers[m].Need[0] <= temp[0] && customers[m].Need[1] <= temp[1] && customers[m].Need[2] <= temp[2] && customers[m].Need[3] <= temp[3]){
temp[0] += customers[m].Allocation[0];
temp[1] += customers[m].Allocation[1];
temp[2] += customers[m].Allocation[2];
temp[3] += customers[m].Allocation[3];
is_safe[m] = 1;
safe_sequence[o++] = m;
m=-1;
}
}
for (int i =0;i<5;i++){
if(is_safe[i]==0){
return 0;
}
}
return 1;
}
void request(int order,int q[],int Available[],int safe_sequence[]){
if(comp(q,customers[order].Need)==0){
printf("requests fail\n");
return 0;
}
else if(comp(q,Available)==1){
try_all(order,q,Available);
if(safty_check(Available,safe_sequence)==0){
for(int r=0;r<4;r++){
Available[r] = Available[r] + q[r];
customers[order].Allocation[r] -= q[r];
customers[order].Need[r] += q[r];
}
printf("not ok\n");
}
else{
printf("State is safe, and request is satisfied\n");
}
}
}
void try_all(int order,int q[],int Available[]){
for(int r=0;r<4;r++){
Available[r] = Available[r] - q[r];
customers[order].Allocation[r] += q[r];
customers[order].Need[r] -= q[r];
}
}
int comp(int one[],int two[]){
int i = 0;
while(i < 4){
if(i<4 || one[i]>two[i]){
break;
return 0;
}
i++;
}
return 1;
}
int release(int n,int rel[],int Available[]){
if(comp(rel,customers[n].Allocation)==1){
for(int i = 0;i<4;i++){
customers[n].Allocation[i] -= rel[i];
Available[i] += rel[i];
}
printf("The resources have been released successfully\n");
}
else{
printf("invalid release");
}
}
int status(int Available[]){
printf("Available Resources:\n");
int w = 0;
while(w<4){
printf("%d ",Available[w]);
w++;
}
printf("\n");
printf("Maximum Resources:\n");
for(int w =0;w<5;w++){
for(int i=0;i<4;i++){
printf("%d ",customers[w].max[i]);
}
printf("\n");
}
printf("\n");
printf("Allocated Resources:\n");
for(int k =0;k<5;k++){
for(int i=0;i<4;i++){
printf("%d ",customers[k].Allocation[i]);
}
printf("\n");
}
printf("\n");
printf("Need Resources:\n");
for(int k =0;k<5;k++){
for(int i=0;i<4;i++){
printf("%d ",customers[k].Need[i]);
}
printf("\n");
}
printf("\n");
}
void Run(int seq[]){
printf("Safe Sequence is:");
for(int i =0;i<5;i++){
printf("%d ",seq[i]);
}
printf("\n");
}
void thread_Start(int *threadID) {
printf(" Thread has started\n");
return;
}
void thread_Finish(int *threadID) {
printf(" Thread has finished\n");
return;
}
void thread_release(int *threadID) {
printf(" Thread is realseasing resources\n");
int idx = *threadID;
for( int x =0;x<4;x++){
Available[x]+=customers[idx].Allocation[x];
}
return;
}
void *thread_run(void *thread){
int *thread_id = (int*)thread;
printf("--> Customer/Thread %d\n",*thread_id);
printf(" Allocated resources:");
for (int x = 0; x <4 ;x++){
printf(" %d",customers[*thread_id].Allocation[x]);
}
printf("\n");
printf(" Needed:");
for (int y= 0;y<4;y++){
printf(" %d",customers[*thread_id].Need[y]);
}
printf("\n");
printf(" Available:");
for(int z = 0;z<4;z++){
printf(" %d",Available[z]);
}
printf("\n");
thread_Start(thread_id);
thread_Finish(thread_id);
thread_release(thread_id);
printf(" New Available:");
for(int n=0;n<4;n++){
printf(" %d",Available[n]);
}
printf("\n");
return 0;
}
| 2.875 | 3 |
2024-11-18T21:10:10.782340+00:00
| 2020-06-05T14:17:09 |
5845196b67deca80d547c8f6222eda8a0af26e06
|
{
"blob_id": "5845196b67deca80d547c8f6222eda8a0af26e06",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-05T14:17:09",
"content_id": "e8b9a01b18b987be78b420f7c3a8993b443da695",
"detected_licenses": [
"BSD-2-Clause-Views"
],
"directory_id": "1ca3c12872f50b35f2df58d0b94a43dc15143d61",
"extension": "c",
"filename": "69.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 269656692,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 443,
"license": "BSD-2-Clause-Views",
"license_type": "permissive",
"path": "/src/69.c",
"provenance": "stackv2-0065.json.gz:29163",
"repo_name": "333-9/code-dump",
"revision_date": "2020-06-05T14:17:09",
"revision_id": "fed881467828a0551bff018b50d49893a1ed4de0",
"snapshot_id": "e8047217db18f3f35238dc1b9a03f5566a31c521",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/333-9/code-dump/fed881467828a0551bff018b50d49893a1ed4de0/src/69.c",
"visit_date": "2022-09-21T05:42:50.787089"
}
|
stackv2
|
// 4 kyu
// Count ones in a segment
long long
count(int n)
{
long long result = 0;
int i = 1, r = 1, lsb;
while (n) {
lsb = n & 1;
result += r * lsb;
r += i * lsb;
n >>= 1;
result += n * i;
i *= 2;
};
return (result);
}
int
count_b(int n)
{
int result = 0;
for (; n; n >>= 1) {
result += n & 1;
};
return (result);
}
long long
countOnes(int left, int right)
{
return (count(right) - count(left) + count_b(left));
}
| 3.34375 | 3 |
2024-11-18T21:10:11.616823+00:00
| 2021-05-12T13:40:48 |
56156dde431f5367d5b8e2f56f40988e0a014e66
|
{
"blob_id": "56156dde431f5367d5b8e2f56f40988e0a014e66",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-12T13:40:48",
"content_id": "5d5dcf76353dbe3fa441c89333794d9157cd9c4e",
"detected_licenses": [
"MIT"
],
"directory_id": "139b70ba09a421d9183f0beacd27100b954029af",
"extension": "c",
"filename": "configuration.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 357642897,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1070,
"license": "MIT",
"license_type": "permissive",
"path": "/EE_API_LIB/src/configuration.c",
"provenance": "stackv2-0065.json.gz:29677",
"repo_name": "TiniTinyTerminator/vga_controller",
"revision_date": "2021-05-12T13:40:48",
"revision_id": "97c3a96e910157e0302ec64bb96601561ca12340",
"snapshot_id": "71de76b51c59fe4a6bc3b35d87eced73c8e3862b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TiniTinyTerminator/vga_controller/97c3a96e910157e0302ec64bb96601561ca12340/EE_API_LIB/src/configuration.c",
"visit_date": "2023-04-25T13:40:09.677914"
}
|
stackv2
|
/**
* @file configuration.c
* @author Max Bensink (Max.bensink@student.hu.nl)
* @brief a file that is used for setting specific values
* @date 2021-04-25
*
* @copyright Copyright (c) 2021
*
*/
#include "graphics.h"
#include <stddef.h>
///@brief internal width variable
uint32_t _w;
///@brief internal height variable
uint32_t _h;
void API_Set_resolution(uint32_t w, uint32_t h)
{
/**
* @brief set the width and height variable
*
*/
_w = w;
_h = h;
}
///@brief set pixel callback
SetPixelCallback_t _set_pixel_callback = NULL;
inline void API_Bind_set_pixel_callback(SetPixelCallback_t callback)
{
_set_pixel_callback = callback;
}
///@brief fill screen callback
SetFillScreenCallback_t _fill_screen_callback = NULL;
inline void API_Bind_fill_screen_callback(SetFillScreenCallback_t callback)
{
_fill_screen_callback = callback;
}
///@brief get pixel callback
GetPixelCallback_t _get_pixel_callback = NULL;
inline void API_Bind_get_pixel_callback(GetPixelCallback_t callback)
{
_get_pixel_callback = callback;
}
| 2.53125 | 3 |
2024-11-18T21:10:11.837823+00:00
| 2020-04-30T22:20:14 |
221676e39a1687c5ff991b3d726ff00359ba8089
|
{
"blob_id": "221676e39a1687c5ff991b3d726ff00359ba8089",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-30T22:20:14",
"content_id": "ff4400c80a67f38a58f2a9a9e4987921f16b421b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2b1b4308c3633282e037c276aea139ed0c8f0c11",
"extension": "c",
"filename": "wavreader.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 231082597,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6842,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test/wavfile/wavreader.c",
"provenance": "stackv2-0065.json.gz:29935",
"repo_name": "DmitryYudin/wavalign",
"revision_date": "2020-04-30T22:20:14",
"revision_id": "0077e7d394e513dadc28019af8742d2b37d0dd76",
"snapshot_id": "00fd903d279c5b51ddfaed5795e7486b9dc851d2",
"src_encoding": "WINDOWS-1252",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/DmitryYudin/wavalign/0077e7d394e513dadc28019af8742d2b37d0dd76/test/wavfile/wavreader.c",
"visit_date": "2022-05-28T19:07:34.250544"
}
|
stackv2
|
/*
* Copyright © 2019 Dmitry Yudin. All rights reserved.
* Licensed under the Apache License, Version 2.0
*/
#include "wavreader.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <assert.h>
#include "pcm_conv.h"
#define WAVE_FORMAT_EXTENSIBLE 0xFFFE
typedef struct {
unsigned format;
unsigned channels;
uint32_t sample_rate;
unsigned bits_per_sample;
unsigned block_align;
uint32_t samples_per_channel;
uint32_t data_length;
FILE *fp;
unsigned char *buf; // internal buffer to perform data transformation into format requested
unsigned bufSize;
} WR;
static int check_consistency()
{
WavReader *wavReader = NULL;
WR *wr = NULL;
return \
&wavReader->format == &wr->format && \
&wavReader->channels == &wr->channels && \
&wavReader->sample_rate == &wr->sample_rate && \
&wavReader->bits_per_sample == &wr->bits_per_sample && \
&wavReader->block_align == &wr->block_align && \
&wavReader->samples_per_channel == &wr->samples_per_channel;
}
#define TAG(a, b, c, d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
static uint32_t read_tag32(WR* wr)
{
uint32_t tag = 0;
tag = (tag << 8) | fgetc(wr->fp);
tag = (tag << 8) | fgetc(wr->fp);
tag = (tag << 8) | fgetc(wr->fp);
tag = (tag << 8) | fgetc(wr->fp);
return tag;
}
static uint32_t read_int32(WR* wr)
{
uint32_t value = 0;
value |= fgetc(wr->fp) << 0;
value |= fgetc(wr->fp) << 8;
value |= fgetc(wr->fp) << 16;
value |= fgetc(wr->fp) << 24;
return value;
}
static uint16_t read_int16(WR* wr)
{
uint16_t value = 0;
value |= fgetc(wr->fp) << 0;
value |= fgetc(wr->fp) << 8;
return value;
}
static void skip(FILE *fp, unsigned n)
{
for (unsigned i = 0; i < n; i++) {
fgetc(fp);
}
}
WavReader* WR_open(const char *filename)
{
if( !check_consistency() ) {
return NULL;
}
WR* wr = (WR*)malloc(sizeof(*wr));
memset(wr, 0, sizeof(*wr));
wr->fp = fopen(filename, "rb");
if (wr->fp == NULL) {
goto exit;
}
uint32_t tag = read_tag32(wr);
uint32_t len = read_int32(wr);
if (tag != TAG('R', 'I', 'F', 'F') || len < 4) {
goto exit;
}
tag = read_tag32(wr); len -= 4;
if (tag != TAG('W', 'A', 'V', 'E')) {
goto exit;
}
while (len >= 8) {
uint32_t chunk = read_tag32(wr);
uint32_t chunk_len = read_int32(wr);
len -= 8;
if (chunk_len > len) {
break;
}
len -= chunk_len;
if (chunk == TAG('f', 'm', 't', ' ')) {
if (chunk_len < 16) { // Insufficient data for 'fmt '
break;
}
wr->format = read_int16(wr);
wr->channels = read_int16(wr);
wr->sample_rate = read_int32(wr);
int byte_rate = read_int32(wr);
wr->block_align = read_int16(wr);
wr->bits_per_sample = read_int16(wr); chunk_len -= 16;
if(wr->block_align == 0 || wr->bits_per_sample == 0) {
break;
}
if (wr->format == WAVE_FORMAT_EXTENSIBLE) {
if (chunk_len < 12) { // Insufficient data for waveformatex
return NULL;
}
skip(wr->fp, 8); chunk_len -= 8;
wr->format = read_int32(wr); chunk_len -= 4;
} else if (chunk_len == 4) {
int cbSize = read_int16(wr); chunk_len -= 2;
if (cbSize == 2) {
unsigned audition = read_int16(wr); chunk_len -= 2;
if( audition == 1 ) {
wr->format = WAVE_FORMAT_FLOAT_AUDITION;
}
}
}
skip(wr->fp, chunk_len);
if(wr->bits_per_sample == 24 && wr->block_align == 4*wr->channels) {
wr->format = WAVE_FORMAT_FLOAT_AUDITION;
}
if( wr->format != WAVE_FORMAT_PCM &&
wr->format != WAVE_FORMAT_IEEE_FLOAT &&
wr->format != WAVE_FORMAT_FLOAT_AUDITION) {
break;
}
} else if (chunk == TAG('d', 'a', 't', 'a')) {
if (chunk_len) {
wr->data_length = chunk_len;
} else {
long pos = ftell(wr->fp);
if(0 != fseek(wr->fp, 0, SEEK_END)) {
break;
}
wr->data_length = ftell(wr->fp) - pos;
if(0 != fseek(wr->fp, pos, SEEK_SET)) {
break;
}
}
wr->samples_per_channel = wr->data_length/wr->block_align;
wr->data_length = wr->samples_per_channel*wr->block_align;
return (WavReader*)wr;
} else {
skip(wr->fp, chunk_len);
}
}
exit:
if (wr->fp) {
fclose(wr->fp);
}
free(wr);
return NULL;
}
void WR_close(WavReader* wavReader)
{
WR* wr = (WR*)wavReader;
fclose(wr->fp);
if(wr->buf) {
free(wr->buf);
}
free(wr);
}
int WR_readRaw(WavReader* wavReader, uint8_t* data, unsigned spc)
{
WR* wr = (WR*)wavReader;
if (spc > wr->data_length/wr->block_align) {
spc = wr->data_length/wr->block_align;
}
unsigned n = (unsigned)fread(data, wr->block_align, spc, wr->fp);
wr->data_length -= n*wr->block_align;
return n;
}
typedef enum {
SMPL_FMT_16,
SMPL_FMT_32,
SMPL_FMT_24,
SMPL_FMT_FLOAT,
SMPL_FMT_DOUBLE,
} SmplFmt;
static int read_internal(WavReader* wavReader, void* _data, unsigned spc, SmplFmt smpl_fmt)
{
WR* wr = (WR*)wavReader;
if(wr->bufSize < spc*wr->block_align) {
unsigned n = spc*wr->block_align;
void *buf_new = realloc(wr->buf, n);
if(!buf_new) {
return 0;
}
wr->buf = buf_new;
wr->bufSize = n;
}
spc = WR_readRaw(wavReader, wr->buf, spc);
unsigned sample_block = wr->block_align/wr->channels;
unsigned char* data = (unsigned char*)_data;
const unsigned char *pcm = wr->buf;
int format = wr->format, bits_per_sample = wr->bits_per_sample, err_sticky = 0;
for(unsigned i = 0; i < spc*wr->channels; i++) {
if(smpl_fmt == SMPL_FMT_16 || smpl_fmt == SMPL_FMT_24 || smpl_fmt == SMPL_FMT_32) {
int32_t x = pcmconv_to_int32(pcm, format, bits_per_sample, &err_sticky);
if(smpl_fmt == SMPL_FMT_16) {
*(short *)data = (short)(x>>16);
data += 2;
} else if(smpl_fmt == SMPL_FMT_24) {
*data++ = (unsigned char)(x>>8);
*data++ = (unsigned char)(x>>16);
*data++ = (unsigned char)(x>>24);
} else {
*(int32_t *)data = x;
data += 4;
}
} else if (smpl_fmt == SMPL_FMT_FLOAT || smpl_fmt == SMPL_FMT_DOUBLE) {
double x = pcmconv_to_double(pcm, format, bits_per_sample, &err_sticky);
if(smpl_fmt == SMPL_FMT_FLOAT) {
*(float *)data = (float)x;
data += sizeof(float);
} else {
*(double *)data = x;
data += sizeof(double);
}
} else {
return 0;
}
pcm += sample_block;
}
return err_sticky ? -1 : spc;
}
int WR_readInt16(WavReader* wavReader, int16_t* data, unsigned spc) {
return read_internal(wavReader, data, spc, SMPL_FMT_16);
}
int WR_readInt24p(WavReader* wavReader, uint8_t* data, unsigned spc) {
return read_internal(wavReader, data, spc, SMPL_FMT_24);
}
int WR_readInt32(WavReader* wavReader, int32_t* data, unsigned spc) {
return read_internal(wavReader, data, spc, SMPL_FMT_32);
}
int WR_readFloat(WavReader* wavReader, float* data, unsigned spc) {
return read_internal(wavReader, data, spc, SMPL_FMT_FLOAT);
}
int WR_readDouble(WavReader* wavReader, double* data, unsigned spc) {
return read_internal(wavReader, data, spc, SMPL_FMT_DOUBLE);
}
| 2.546875 | 3 |
2024-11-18T21:10:11.964315+00:00
| 2022-05-12T07:33:06 |
c23a774159e4a36d786865332f5e47d726f4ed77
|
{
"blob_id": "c23a774159e4a36d786865332f5e47d726f4ed77",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-12T07:33:06",
"content_id": "de3ecccecb2f89c600e2c8f31fb3082118d05772",
"detected_licenses": [
"Unlicense"
],
"directory_id": "3ccfc888aab02b385b950101f8363ecc4dfa4d8a",
"extension": "h",
"filename": "cesl_format.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 188212095,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2819,
"license": "Unlicense",
"license_type": "permissive",
"path": "/cesl/cesl_strings/cesl_format.h",
"provenance": "stackv2-0065.json.gz:30192",
"repo_name": "mlutken/nestle",
"revision_date": "2022-05-12T07:33:06",
"revision_id": "b9e2dd44ae2fea888b8f21ce8697d9dcd995879d",
"snapshot_id": "fedae627545f5469a18ddcb9931ad1ebaa5b785c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/mlutken/nestle/b9e2dd44ae2fea888b8f21ce8697d9dcd995879d/cesl/cesl_strings/cesl_format.h",
"visit_date": "2022-06-01T18:44:23.002601"
}
|
stackv2
|
/**@file
*/
#ifndef CESL_STRINGS_CESL_FORMAT_H
#define CESL_STRINGS_CESL_FORMAT_H
#include <cesl_compiler/cesl_extern_c.h>
#include <cesl_compiler/cesl_align_macros.h>
#include <stddef.h>
#include <stdint.h>
// -----------------
// PUBLIC: types ---
// -----------------
#define cesl_format_buffer_full_error 1
struct cesl_format_t
{
size_t buf_max_size;
size_t cur_pos;
int32_t error_code;
char* buf;
struct cesl_format_t* (*rst)(struct cesl_format_t* self);
struct cesl_format_t* (*dbg)(struct cesl_format_t* self);
struct cesl_format_t* (*print)(struct cesl_format_t* self);
struct cesl_format_t* (*s)(struct cesl_format_t* self, const char* string);
struct cesl_format_t* (*i64)(struct cesl_format_t* self, int64_t value);
struct cesl_format_t* (*i32)(struct cesl_format_t* self, int32_t value);
struct cesl_format_t* (*i)(struct cesl_format_t* self, int value);
struct cesl_format_t* (*l)(struct cesl_format_t* self, long value);
struct cesl_format_t* (*ui64)(struct cesl_format_t* self, uint64_t value);
struct cesl_format_t* (*ui32)(struct cesl_format_t* self, uint32_t value);
struct cesl_format_t* (*ui)(struct cesl_format_t* self, unsigned int value);
struct cesl_format_t* (*ul)(struct cesl_format_t* self, unsigned long value);
};
typedef struct cesl_format_t cesl_format_t;
// ---------------------
// PUBLIC: functions ---
// ---------------------
extern_C cesl_format_t* cesl_format_create (cesl_format_t* self, size_t buf_max_size,
char* format_buffer);
extern_C cesl_format_t* cesl_format_rst (cesl_format_t* self);
extern_C cesl_format_t* cesl_format_dbg (cesl_format_t* self);
extern_C cesl_format_t* cesl_format_print (cesl_format_t* self);
extern_C cesl_format_t* cesl_format_s (cesl_format_t* self, const char* string);
extern_C cesl_format_t* cesl_format_i64 (cesl_format_t* self, int64_t value);
extern_C cesl_format_t* cesl_format_i32 (cesl_format_t* self, int32_t value);
extern_C cesl_format_t* cesl_format_l (cesl_format_t *self, long value);
extern_C cesl_format_t* cesl_format_i (cesl_format_t *self, int value);
extern_C cesl_format_t* cesl_format_ui64 (cesl_format_t *self, uint64_t value);
extern_C cesl_format_t* cesl_format_ui32 (cesl_format_t *self, uint32_t value);
extern_C cesl_format_t* cesl_format_ul (cesl_format_t *self, unsigned long value);
extern_C cesl_format_t* cesl_format_ui (cesl_format_t *self, unsigned int value);
// PUBLIC: Convenience functions
extern_C cesl_format_t* rst (cesl_format_t* self);
extern_C cesl_format_t* dbg (cesl_format_t* self);
#endif //CESL_STRINGS_CESL_FORMAT_H
| 2.25 | 2 |
2024-11-18T21:10:12.121639+00:00
| 2020-03-12T14:39:21 |
2b34f4671aafc3429c76165fca4e39b5201cd452
|
{
"blob_id": "2b34f4671aafc3429c76165fca4e39b5201cd452",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-12T14:39:21",
"content_id": "094bdccc8689bf318bc905eb0ab12c30cebd6baf",
"detected_licenses": [
"MIT"
],
"directory_id": "c157a975896b2ef6df568205dc4212a12b0e6e91",
"extension": "c",
"filename": "savFileLister.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 130467377,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 17243,
"license": "MIT",
"license_type": "permissive",
"path": "/Lister/savFileLister.c",
"provenance": "stackv2-0065.json.gz:30448",
"repo_name": "NormanDunbar/C68Port",
"revision_date": "2020-03-12T14:39:21",
"revision_id": "de143dd75eecb941ec48971e946f60090b51b321",
"snapshot_id": "b8663b7dd3f239a3c6badbed589f39a7e05b6edc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NormanDunbar/C68Port/de143dd75eecb941ec48971e946f60090b51b321/Lister/savFileLister.c",
"visit_date": "2021-08-22T15:28:36.669611"
}
|
stackv2
|
/*=============================================================================
* C68 "_sav" file decoder and converter to C68 source. (Maybe!)
* Reads the file on arvg[1], which should be a _sav file, created by QSAVE
* and converts it back to SuperBASIC. This is a trial run of working out how
* to convert the SAV file to a C source file a-la CPORT, which is old and
* somewhat broken, and no source code exists.
*
* Wish me luck!
*
* Norman Dunbar
* August 24 2019. (Started!)
*===========================================================================*/
#include "c68port.h"
/*=============================================================================
* MAIN() Start here. Expects the input file on argv[1] and writes the output
* to stdout with messages and errors on stderr - might as well use them!
*===========================================================================*/
int main (int argc, char *argv[]) {
ushort nameTableEntries = 0;
ushort programLines = 0;
FILE *fp;
if (argc != 2) {
fprintf(stderr, "%s requires 1 argument, the SAV file name.\n", argv[0]);
return -1;
}
/* Can we open the SAV file? */
fp = fopen(argv[1], "rb");
if (!fp) {
fprintf(stderr, "FATAL ERROR: main(): Cannot open SAV file '%s'.\n", argv[1]);
return -1;
}
fprintf(stderr, "SAV File..............: %s\n", argv[1]);
/* Can we read the header? */
if ((decodeHeader(fp, &nameTableEntries, &programLines)) != 0) {
fprintf(stderr, "FATAL ERROR: decodeHeader() failed.\n");
return -1;
}
/* Allocate the name table. */
nameTable = malloc(nameTableEntries * sizeof(nameTableEntry));
if (!nameTable) {
fprintf(stderr, "FATAL ERROR: Cannot allocate memory for name table. (%d entries).\n", nameTableEntries);
return -1;
}
/* Fill in the name table. */
if (decodeNameTable(nameTableEntries, fp) != 0) {
fprintf(stderr, "FATAL ERROR: decodeNameTable() failed.\n");
return -1;
}
/* Decode the program. */
if (decodeProgram(programLines, fp, argv[1]) != 0) {
fprintf(stderr, "FATAL ERROR: decodeProgram() failed.\n");
return -1;
}
/* All done, exit with no errors. */
if (nameTable) {
free(nameTable);
}
fclose(fp);
return 0;
}
/*=============================================================================
* DECODEHEADER() Decodes the header of the _save file and makes sure it's
* valid, otherwise we abort.
*===========================================================================*/
ushort decodeHeader(FILE *fp, ushort *entries, ushort *lines) {
uchar head[4];
ushort valid;
ushort nameTableLength = 0;
ushort programLines = 0;
ushort nameTableEntries = 0;
quit = 0;
/* Can we read the 4 byte header? */
if (fread(head, 1, 4, fp) != 4) {
fprintf(stderr, "\n\nERROR: decodeHeader(): Cannot read SAV file header.\n");
return 1;
}
/* Is the header valid? */
/* Valid values are:
* 'Q', '1', 0, 0
* 'Q', '1', 2, 192
* 'Q', '1', 3, 128
* 'Q', '1', 0, 128
*/
valid = 0;
if (head[0] == 'Q' && head[1] == '1') {
if (head[2] == 0 && head[3] == 0)
valid = 1;
else if (head[2] == 0 && head[3] == 128)
valid = 1;
else if (head[2] == 2 && head[3] == 192)
valid = 1;
else if (head[2] == 3 && head[3] == 128)
valid = 1;
}
if (!valid) {
fprintf(stderr, "\n\nERROR: decodeHeader(): Invalid SAV file header. [\"%c%c\",%d,%d]\n", head[0], head[1], head[2], head[3]);
return 1;
}
/* Looks like a valid SAV file, read the header details. */
nameTableEntries = getWord(fp);
nameTableLength = getWord(fp);
programLines = getWord(fp);
fprintf(stderr, "\nHEADER DETAILS\n==============\n");
fprintf(stderr, "\nName Table Entries....: %5d", nameTableEntries);
fprintf(stderr, "\nName Table length.....: %5d", nameTableLength);
fprintf(stderr, "\nProgram Lines.........: %5d\n", programLines);
fflush(stderr);
*entries = nameTableEntries;
*lines = programLines;
return 0;
}
/*=============================================================================
* DECODENAMETABLE() Builds the internal name table by reading the SAV file's
* name table.
*===========================================================================*/
ushort decodeNameTable(ushort entries, FILE *fp) {
ushort x;
uchar ch;
ushort size = 0;
ushort procCount = 0;
ushort fnCount[3] = {0,0,0}; /* FN$, FN, FN% counters */
for (x = 0; x < entries; x++) {
nameTable[x].offset = ftell(fp);
nameTable[x].nameType = getWord(fp);
nameTable[x].lineNumber = getWord(fp);
nameTable[x].nameLength = getWord(fp);
/* Count up the details. */
switch (nameTable[x].nameType) {
case 0x1402: procCount++; break;
case 0x1501:
case 0x1502:
case 0x1503: fnCount[nameTable[x].nameType - 0x1501]++; break;
}
/* Do we need a recompile? */
if (nameTable[x].nameLength >= MAXNAMESIZE) {
size = MAXNAMESIZE - 1;
fread(nameTable[x].name, 1, size, fp);
fprintf(stderr, "\n\nWARNING: Cannot read a name with >= %d characters. Please amend the SAV file, or, recompile C68Port.\n", MAXNAMESIZE);
fprintf(stderr, "The offending name is '%*.*s'\n.", MAXNAMESIZE, MAXNAMESIZE, nameTable[x].name);
return 1;
}
fread(nameTable[x].name, 1, nameTable[x].nameLength, fp);
/* Odd length names are padded. */
if (nameTable[x].nameLength & 1)
ch = fgetc(fp);
}
fprintf(stderr, "\nNAME TABLE\n==========\n");
fprintf(stderr, "\nNumber of Procedures..: %4d", procCount);
fprintf(stderr, "\nNumber of Function$...: %4d", fnCount[0]);
fprintf(stderr, "\nNumber of Function....: %4d", fnCount[1]);
fprintf(stderr, "\nNumber of Function%%...: %4d\n", fnCount[2]);
for (x = 0; x < entries; x++) {
fprintf(stderr, "\n%4.4X: ", nameTable[x].offset);
fprintf(stderr, "NameTable[%4d]: ", x);
fprintf(stderr, "Name Type: %4d ($%4.4X), ", nameTable[x].nameType, nameTable[x].nameType);
fprintf(stderr, "Line Number: %5d, ", nameTable[x].lineNumber);
fprintf(stderr, "Name: Size = %3d, ", nameTable[x].nameLength);
fprintf(stderr, "%*.*s", nameTable[x].nameLength, nameTable[x].nameLength, nameTable[x].name);
}
fflush(stderr);
return 0;
}
/*=============================================================================
* DECODEPROGRAM disassembles the SAV file's contants representing the program
* listing. Eventually, this will convert the SuperBASIC to C68 style C code.
* (I hope!)
*===========================================================================*/
ushort decodeProgram(ushort lines, FILE *fp, char *fileName) {
ushort x;
uchar typeByte;
ushort programLine;
ushort lineSize = 0;
ushort flag;
ulong offset;
uchar endOfLine;
char logFile[40]; /* Listing file name - big enough for a QL. */
FILE *listingFile;
/* The format of a program line is:
* ushort - change in size over previous line;
* ushort - 0x8D00 line number flag;
* ushort - line number;
* bytes - rest of the line.
/* Open a listing file, replace SAV with LST. */
if (strlen(fileName) > 39) {
fprintf(stderr, "\n\nERROR: decodeProgram(): Cannot create listing file, filename too long.\n");
return 1;
}
strncpy(logFile, fileName, 39);
logFile[strlen(fileName) > 39 ? 39 : strlen(fileName)] = '\0';
// Change the extension, from SAV to LST */
if (logFile[strlen(logFile) - 4] == '_' || logFile[strlen(logFile) - 4] == '.') {
strcpy(&logFile[strlen(logFile) - 3], "LST");
} else {
}
listingFile = fopen(logFile, "w");
if (!listingFile) {
fprintf(stderr, "\n\nERROR: decodeProgram(): Cannot open listing file, 'c68port.lst'.\n");
return 1;
}
for (x = 0; x < lines; x++) {
lineSize += getWord(fp);
if ((flag = getWord(fp)) != TYPE_LINENUMBER) {
fprintf(stderr, "\n\nERROR: decodeProgram(): Program out of step at offset %ld ($%08lx).\n", ftell(fp), ftell(fp));
fprintf(stderr, "Expected 0x8D00, found %xd.\n", flag);
fclose(listingFile);
return 1;
}
/* Line number */
fprintf(listingFile, "%d ", getWord(fp));
/* Line contents */
while (1) {
/* Type Byte */
typeByte = fgetc(fp);
endOfLine = 0;
switch(typeByte) {
case TYPE_MULTISPACE: doMultiSpaces(fp, listingFile); break;
case TYPE_KEYWORD: doKeywords(fp, listingFile); break;
case TYPE_SYMBOL: endOfLine = doSymbols(fp, listingFile); break;
case TYPE_OPERATOR: doOperators(fp, listingFile); break;
case TYPE_MONADIC: doMonadics(fp, listingFile); break;
case TYPE_NAME: doNames(fp, listingFile); break;
case TYPE_STRING: doStrings(fp, listingFile); break;
case TYPE_TEXT: doText(fp, listingFile); break;
case TYPE_SEPARATOR: doSeparators(fp, listingFile); break;
/* Floats come in three formats, each with 16 leading bytes! */
case TYPE_FP_BIN_MIN ... TYPE_FP_BIN_MIN:
case TYPE_FP_HEX_MIN ... TYPE_FP_HEX_MAX:
case TYPE_FP_DEC_MIN ... TYPE_FP_DEC_MAX:
doFloatingPoint(fp, listingFile, typeByte); break;
default:
offset = ftell(fp);
fprintf(stderr, "\n\nERROR: decodeProgram(): At offset %ld ($%08lx), read byte %d (%c). Out of sync.", offset, offset, typeByte, (typeByte > 31 ? typeByte : '.'));
fclose(listingFile);
return 1;
}
/* Exit the while loop when we print an end of line character. */
if (endOfLine) {
fflush(listingFile);
break;
}
}
}
return 0;
}
void doMultiSpaces(FILE *fp, FILE *listing){
/* 0x80.nn = Print nn spaces */
uchar nn = fgetc(fp);
fprintf(listing, "%*.*s", nn, nn, " ");
}
void doKeywords(FILE *fp, FILE *listing){
/* 0x81.nn = Print keywords[nn] */
static char *keywords[] = {
"END", "FOR", "IF", "REPeat", "SELect", "WHEN", "DEFine",
"PROCedure", "FuNction", "GO", "TO", "SUB", "", "ERRor", "",
"", "RESTORE", "NEXT", "EXIT", "ELSE", "ON", "RETurn",
"REMAINDER", "DATA", "DIM", "LOCal", "LET", "THEN", "STEP",
"REMark", "MISTAKE"
};
uchar nn = fgetc(fp) -1;
fprintf(listing, "%s ", keywords[nn]);
}
uchar doSymbols(FILE *fp, FILE *listing){
/* 0x84.nn = Print symbols[nn] */
static char *symbols = "=:#,(){} \n";
uchar nn = fgetc(fp) -1;
fprintf(listing, "%c", symbols[nn]);
/* Return 1 for end of line. 0 otherwise. */
return (nn == 0x09);
}
void doOperators(FILE *fp, FILE *listing){
/* 0x85.nn = Print operators[nn] */
static char *operators[] = {
"+", "-", "*", "/", ">=", ">", "==", "=", "<>", "<=", "<",
"||", "&&", "^^", "^", "&", "OR", "AND", "XOR", "MOD",
"DIV", "INSTR"
};
uchar nn = fgetc(fp) -1;
fprintf(listing, "%s", operators[nn]);
}
void doMonadics(FILE *fp, FILE *listing){
/* 0x86.nn = Print monadics[nn] */
static char *monadics[] = {
"+", "-", "~~", "NOT"
};
uchar nn = fgetc(fp) -1;
fprintf(listing, "%s", monadics[nn]);
}
void doNames(FILE *fp, FILE *listing){
/* 0x8800 = Print name[nn] */
uchar nn = fgetc(fp); /* ignore */
ushort entry = getWord(fp);
fprintf(listing, "%*.*s", nameTable[entry].nameLength, nameTable[entry].nameLength, nameTable[entry].name);
}
void doStrings(FILE *fp, FILE *listing){
/* 0x8B.delim.size.bytes.[padding] = Print delimited string */
uchar delim = fgetc(fp); /* Delimiter */
ushort size = getWord(fp); /* String length */
ushort x;
fputc(delim, listing);
for (x = 0; x < size; x++) {
fputc(fgetc(fp), listing);
}
fputc(delim, listing);
if (size & 1)
fgetc(fp); /* Padding */
}
void doText(FILE *fp, FILE *listing){
/* 0x8C00.size.bytes = Print undelimited text
*/
uchar ignore = fgetc(fp); /* 00 byte */
ushort size = getWord(fp); /* String length */
ushort x;
for (x = 0; x < size; x++) {
fputc(fgetc(fp), listing);
}
if (size & 1)
fgetc(fp); /* Padding */
}
void doSeparators(FILE *fp, FILE *listing){
/* 0x8E.nn = Print separators[nn] */
static char *separators[] = {
",", ";", "\\", "!", "TO"
};
uchar nn = fgetc(fp) -1;
fprintf(listing, "%s", separators[nn]);
}
void doFloatingPoint(FILE *fp, FILE *listing, uchar leading){
/* Floating points come in three variations:
* 0xDn = % Binary
* 0xEn = $ Hexadecimal
* 0xFn = Normal.
*
* Each one is followed by 5 bytes.
*/
ushort x;
uchar fpType = ((leading & 0xF0) >> 4) - 13;
char fpPrefix = (fpType == 0 ? '%' : fpType == 1 ? '$' : ' ');
/* 6 byte QL Float structure */
union {
QLFLOAT_t buffer;
ushort sh[3];
} fpVariable;
/* Print the Float prefix character, if necessary. */
if (fpType == 0 || fpType == 1) {
fprintf(listing, "%c", fpPrefix);
}
/* Backup up one byte. We can read the whole FP then. */
fseek(fp, -1, SEEK_CUR);
#ifndef QDOS
/* This reads a QL Float for wrong endian systems! */
fpVariable.sh[0] = getWord(fp);
fpVariable.sh[2] = getWord(fp);
fpVariable.sh[1] = getWord(fp);
fprintf(listing, "%f", qlfpToDouble(&fpVariable.buffer));
#else
/* But the QL is correct endian! */
fread(&fpVariable.buffer, 1, sizeof(QLFLOAT_t), fp);
fprintf(listing, "%f", qlfp_to_d(&fpVariable.buffer));
#endif
}
/*=============================================================================
* GETWORD() Reads a signed short value from the SAV file. On Linux, where I
* tested, I have to reverse the order of the two bytes. Linux is "wrong"
* endian, unlike QDOS.
*===========================================================================*/
short getWord(FILE *fp) {
union {
ushort val;
uchar bytes[2];
} data;
/* I tested on Linux, which is wrong endian! */
#ifdef QDOS
fread(&data.val, 1, sizeof(ushort), fp);
#else
fread(&data.bytes[1], 1, 1, fp);
fread(&data.bytes[0], 1, 1, fp);
#endif
return data.val;
}
#ifndef QDOS
/*=============================================================================
* QLFPTODOUBLE() Converts a QL 6 byte floating point value to a double in IEEE
* format. This is a C conversion of the assembly routine qlfp_to_d() from the
* C68 source code. There are three styles of float:
*
* 0xDx xx xx xx xx xx = Binary %101010101 etc.
* 0xEx xx xx xx xx xx = Hexadecimal $abcdef etc.
* 0xFx xx xx xx xx xx = Decimal 12345 etc.
*
* The top nibble, D, E or F, must be masked out before converting but will
* return the correct type in the fpType parameter.
*
* According to https://en.wikipedia.org/wiki/Double-precision_floating-point_format
* an IEEE double is:
*
* 1 sign bit
* 11 exponent bits offset by 1023
* 1 implied plus 52 fractional bits.
*
* The number is usually:
*
* -1^^Sign * 2^^(exp-2013) * 1.Fractional Bits
*
* Where the 1 is the implied bit.
*===========================================================================*/
double qlfpToDouble(QLFLOAT_t *qlfp) {
ulong sign;
ulong exponent = qlfp->exponent & 0x0fff;
ulong mantissa = qlfp->mantissa;
ulong temp;
struct ieeeFloat {
ulong ieeeExponent;
ulong ieeeMantissa;
} result;
/* Lose the type marker. */
exponent &= 0xFFFF0FFFL;
/* Simple case first, is it zero? */
if (exponent == 0 && mantissa == 0) {
return (double)0;
}
/* Positive or negative? */
sign = (mantissa & 0x80000000L);
if (sign) {
/* Negative. */
exponent *= -1;
if (mantissa & 0x40000000L) {
exponent++;
}
/* Then drop in below. */
}
/* Positive. */
exponent -= 0x402;
exponent <<= 4;
exponent <<= 16;
exponent |= sign;
mantissa <<= 2;
temp = (short)mantissa;
temp <<= 4;
temp <<= 16;
mantissa >>= 12;
mantissa |= exponent;
/* Exponent bits = 1 sign, 11 exponent, (1 implied), 20 fractionals
* Mantissa bits = 32 bits of fractional */
result.ieeeExponent = (long unsigned)temp;
result.ieeeMantissa = (long unsigned)mantissa;
return *((double *)(&result));
}
#endif
| 2.484375 | 2 |
2024-11-18T21:10:12.183703+00:00
| 2020-05-12T20:36:25 |
718b090ee3e318c2971dc0b1f63de743ad415ab9
|
{
"blob_id": "718b090ee3e318c2971dc0b1f63de743ad415ab9",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-12T20:36:25",
"content_id": "1383881659e4a8ab968e986de99e62725992af91",
"detected_licenses": [
"MIT"
],
"directory_id": "6af043c42300484a2e4002ee8c077ca4a58591fb",
"extension": "c",
"filename": "Grunt2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 244011164,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5080,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Grunt2.c",
"provenance": "stackv2-0065.json.gz:30576",
"repo_name": "dm554/2dgame",
"revision_date": "2020-05-12T20:36:25",
"revision_id": "14f28d572a1ff8f13c6e87f48438227d2da158da",
"snapshot_id": "b2eb7cb1956572aeb0989bb4be370177e26de7b6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dm554/2dgame/14f28d572a1ff8f13c6e87f48438227d2da158da/src/Grunt2.c",
"visit_date": "2021-02-07T09:52:10.259246"
}
|
stackv2
|
#include "simple_logger.h"
#include "Grunt2.h"
#include "Level.h"
Entity *playerTarget;
static int attackTimer = 0;
Entity *grunt2_new(Entity *target){
Entity *self;
playerTarget = target;
self = entity_new();
Uint8 randomspawns = rand() % 8;
Vector2D oppspawn;
Vector2D spawn1 = vector2d(-700, 800);
Vector2D spawn2 = vector2d(-800, 500);
Vector2D spawn3 = vector2d(-750, 600);
Vector2D spawn4 = vector2d(-1000, 450);
Vector2D spawn5 = vector2d(1125, 400);
Vector2D spawn6 = vector2d(1000, 600);
Vector2D spawn7 = vector2d(1200, 700);
Vector2D spawn8 = vector2d(800, 500);
switch (randomspawns){
case 1:
oppspawn = spawn1;
break;
case 2:
oppspawn = spawn2;
break;
case 3:
oppspawn = spawn3;
break;
case 4:
oppspawn = spawn4;
break;
case 5:
oppspawn = spawn5;
break;
case 6:
oppspawn = spawn6;
break;
case 7:
oppspawn = spawn7;
break;
case 8:
oppspawn = spawn8;
break;
}
self->position = oppspawn;
self->sprite = gf2d_sprite_load_all("images/Grunt2idle.png", 64, 64, 5);
self->think = grunt2_think;
self->collide = grunt2_collide;
self->bodyHitbox.x = self->position.x;
self->bodyHitbox.y = self->position.y;
self->bodyHitbox.w = 64;
self->bodyHitbox.h = 64;
self->minFrame = 0;
self->maxFrame = 5;
self->attacking = 0;
self->type = 2;
self->health = 10;
self->hitstun = 0;
self->hitstunTimer = 0;
self->bonk = gfc_sound_load("audio/bonk.mp3", 1, 2);
return self;
}
void grunt2_think(Entity *self){
grunt2_move(self, playerTarget);
if (self->health < 1){
playerTarget->xp += 4 + entity_get_perkxp();
entity_free(self);
return;
}
}
void grunt2_move(Entity *self, Entity *target){
vector2d_set(self->velocity, 1, 1);
float xDistance = abs(self->position.x - target->position.x);
float yDistance = abs(self->position.y - target->position.y);
if (self->position.x > target->position.x){
self->forward = 0;
self->sprite = gf2d_sprite_load_all("images/Grunt2idleflip.png", 64, 64, 5);
}
if (self->position.x < target->position.x){
self->forward = 1;
self->sprite = gf2d_sprite_load_all("images/Grunt2idle.png", 64, 64, 5);
}
if (!self->attacking && !self->hitstun){
if (xDistance > 50){
if (self->position.x > target->position.x){
self->position.x -= 1 * entity_get_perkspeed();
return;
}
if (self->position.x < target->position.x){
self->position.x += 1 * entity_get_perkspeed();
return;
}
}
if (yDistance > 50){
if (self->position.y > target->position.y){
self->position.y -= 1 * entity_get_perkspeed();
return;
}
if (self->position.y < target->position.y){
self->position.y += 1 * entity_get_perkspeed();
return;
}
}
if (xDistance > 10){
if (self->position.x > target->position.x){
self->position.x -= 1 * entity_get_perkspeed();
return;
}
if (self->position.x < target->position.x){
self->position.x += 1 * entity_get_perkspeed();
return;
}
}
}
if (self->hitstun){
if (self->hitstunTimer < 50 + entity_get_perkstun()){
self->hitstunTimer++;
return;
}
self->hitstun = 0;
self->hitstunTimer = 0;
}
grunt2_attack(self);
}
void grunt2_attack(Entity *self){
if (attackTimer < 60){
attackTimer++;
return;
}
self->minFrame = 56;
self->maxFrame = 61;
if (attackTimer < 120){
self->attacking = 1;
if (self->forward){
self->sprite = gf2d_sprite_load_all("images/Grunt2attack.png", 64, 64, 12);
self->minFrame = 56;
self->maxFrame = 61;
}
if (!self->forward){
self->sprite = gf2d_sprite_load_all("images/Grunt2attackflip.png", 64, 64, 12);
self->minFrame = 49;
self->maxFrame = 53;
}
attackTimer++;
return;
}
attackTimer = 0;
self->attacking = 0;
self->minFrame = 0;
self->maxFrame = 5;
self->sprite = gf2d_sprite_load_all("images/Grunt2idle.png", 64, 64, 5);
}
void grunt2_collide(Entity*self, Entity *other){
if (other->type == 1){
if (other->attacking && self->forward != other->forward){
if (other->lastAttack == 1){
self->health -= 1;
if (self->forward){
self->position.x -= 10;
}
if (!self->forward){
self->position.x += 10;
}
}
if (other->lastAttack == 2){
self->health -= 1;
if (self->forward){
self->position.x -= 10;
self->position.y -= 15;
}
if (!self->forward){
self->position.x += 10;
self->position.y -= 15;
}
}
if (other->lastAttack == 3){
self->health -= 1;
if (self->forward){
self->position.x -= 25;
}
if (!self->forward){
self->position.x += 25;
}
}
if (other->lastAttack == 4){
self->health -= 1;
if (self->forward){
self->position.x -= 10;
self->position.y += 15;
}
if (!self->forward){
self->position.x += 10;
self->position.y += 15;
}
}
if (other->lastAttack == 1){
self->health -= 1;
if (self->forward){
self->position.x -= 10;
}
if (!self->forward){
self->position.x += 10;
}
}
gfc_sound_play(self->bonk, 0, 0.5, -1, -1);
self->hitstun = true;
}
}
}
| 2.28125 | 2 |
2024-11-18T21:10:12.273773+00:00
| 2023-02-24T18:32:15 |
fdf19e020ce28175540284d97ce69dd3578e9628
|
{
"blob_id": "fdf19e020ce28175540284d97ce69dd3578e9628",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-24T18:32:15",
"content_id": "176c9c9da40e7ec869e960e8b5f95fd5ff465c47",
"detected_licenses": [
"MIT",
"BSD-3-Clause"
],
"directory_id": "784ee664cd72d712e091698b95e964527859e1b3",
"extension": "c",
"filename": "ex_ratio_1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 204336162,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1038,
"license": "MIT,BSD-3-Clause",
"license_type": "permissive",
"path": "/test/ex_ratio_1.c",
"provenance": "stackv2-0065.json.gz:30705",
"repo_name": "ClaudioDaffra/cx",
"revision_date": "2023-02-24T18:32:15",
"revision_id": "c1e8553dc98e0d352367f19ce81242090a744bee",
"snapshot_id": "35173f868fc258094b4d5638bcfe40b8fcc9fe7b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ClaudioDaffra/cx/c1e8553dc98e0d352367f19ce81242090a744bee/test/ex_ratio_1.c",
"visit_date": "2023-03-05T23:55:58.463587"
}
|
stackv2
|
#include "../lib/ratio.h"
#include "../lib/type.h"
#include <stdio.h>
/*
cl test\ex_ratio_1.c lib\ratio.c lib\mutility.c /Fex.exe
gcc test\ex_ratio_1.c lib\ratio.c lib\mutility.c -o x.exe
gcc test/ex_ratio_1.c lib/ratio.c lib/mutility.c -o x
*/
int main(void)
{
ratio_t a = { 1,2 } ;
ratio_t b = { 1,3 } ;
printf ( "\n equal %d",ratioEQ(a,b) ) ;
printf ( "\n ! equal %d",ratioNE(a,b) ) ;
printf ( "\n < %d",ratioLT(a,b) ) ;
printf ( "\n ratio %g",ratio(a) ) ;
ratio_t result;
ratioAdd(&result,a,b) ;
printf ( "\n add "$i80()"/"$i80()".",result.num,result.den );
ratioSub(&result,a,b) ;
printf ( "\n sub "$i80()"/"$i80()".",result.num,result.den );
ratioMul(&result,a,b);
printf ( "\n mul "$i80()"/"$i80()".",result.num,result.den );
ratioDiv(&result,a,b);
printf ( "\n Div "$i80()"/"$i80()".",result.num,result.den );
printf ( "\n EXA : %e \n",ratio(exa) );
return 0;
}
| 2.5625 | 3 |
2024-11-18T21:10:12.560764+00:00
| 2023-08-12T07:52:03 |
42dc482b8f29ba019a65b32c47ae3eb9505b3823
|
{
"blob_id": "42dc482b8f29ba019a65b32c47ae3eb9505b3823",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-12T13:24:08",
"content_id": "3a1422a9b2077c2766abef2c241a9d537706238a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "1a0276218c8a103c9a76409e510df5b5690f44e5",
"extension": "c",
"filename": "nsc_encode.c",
"fork_events_count": 8,
"gha_created_at": "2012-10-29T14:06:58",
"gha_event_created_at": "2021-08-23T18:33:02",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 6441472,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14889,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/libfreerdp/codec/nsc_encode.c",
"provenance": "stackv2-0065.json.gz:30834",
"repo_name": "awakecoding/FreeRDP",
"revision_date": "2023-08-12T07:52:03",
"revision_id": "56324906a2d5b2538675e2f10b9f1ffe4a27de79",
"snapshot_id": "4add891a6c5f06db9c7ee110cce4f6b46b71bdc8",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/awakecoding/FreeRDP/56324906a2d5b2538675e2f10b9f1ffe4a27de79/libfreerdp/codec/nsc_encode.c",
"visit_date": "2023-08-17T15:47:00.604064"
}
|
stackv2
|
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* NSCodec Encoder
*
* Copyright 2012 Vic Lee
* Copyright 2016 Armin Novak <armin.novak@thincast.com>
* Copyright 2016 Thincast Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <freerdp/config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/crt.h>
#include <freerdp/codec/nsc.h>
#include <freerdp/codec/color.h>
#include "nsc_types.h"
#include "nsc_encode.h"
typedef struct
{
UINT32 x;
UINT32 y;
UINT32 width;
UINT32 height;
const BYTE* data;
UINT32 scanline;
BYTE* PlaneBuffer;
UINT32 MaxPlaneSize;
BYTE* PlaneBuffers[5];
UINT32 OrgByteCount[4];
UINT32 LumaPlaneByteCount;
UINT32 OrangeChromaPlaneByteCount;
UINT32 GreenChromaPlaneByteCount;
UINT32 AlphaPlaneByteCount;
UINT8 ColorLossLevel;
UINT8 ChromaSubsamplingLevel;
} NSC_MESSAGE;
static BOOL nsc_write_message(NSC_CONTEXT* context, wStream* s, const NSC_MESSAGE* message);
static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context)
{
int i;
UINT32 length;
UINT32 tempWidth;
UINT32 tempHeight;
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
/* The maximum length a decoded plane can reach in all cases */
length = tempWidth * tempHeight + 16;
if (length > context->priv->PlaneBuffersLength)
{
for (i = 0; i < 5; i++)
{
BYTE* tmp = (BYTE*)winpr_aligned_recalloc(context->priv->PlaneBuffers[i], length,
sizeof(BYTE), 32);
if (!tmp)
goto fail;
context->priv->PlaneBuffers[i] = tmp;
}
context->priv->PlaneBuffersLength = length;
}
if (context->ChromaSubsamplingLevel)
{
context->OrgByteCount[0] = tempWidth * context->height;
context->OrgByteCount[1] = tempWidth * tempHeight / 4;
context->OrgByteCount[2] = tempWidth * tempHeight / 4;
context->OrgByteCount[3] = context->width * context->height;
}
else
{
context->OrgByteCount[0] = context->width * context->height;
context->OrgByteCount[1] = context->width * context->height;
context->OrgByteCount[2] = context->width * context->height;
context->OrgByteCount[3] = context->width * context->height;
}
return TRUE;
fail:
if (length > context->priv->PlaneBuffersLength)
{
for (i = 0; i < 5; i++)
winpr_aligned_free(context->priv->PlaneBuffers[i]);
}
return FALSE;
}
static BOOL nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data, UINT32 scanline)
{
UINT16 x;
UINT16 y;
UINT16 rw;
BYTE ccl;
const BYTE* src;
const UINT32* src_32;
const UINT16* src_16;
BYTE* yplane = NULL;
BYTE* coplane = NULL;
BYTE* cgplane = NULL;
BYTE* aplane = NULL;
INT16 r_val;
INT16 g_val;
INT16 b_val;
BYTE a_val;
UINT32 tempWidth;
tempWidth = ROUND_UP_TO(context->width, 8);
rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width);
ccl = context->ColorLossLevel;
for (y = 0; y < context->height; y++)
{
src = data + (context->height - 1 - y) * scanline;
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
aplane = context->priv->PlaneBuffers[3] + y * context->width;
src_32 = (UINT32*)src;
src_16 = (UINT16*)src;
for (x = 0; x < context->width; x++)
{
switch (context->format)
{
case PIXEL_FORMAT_BGRX32:
b_val = (INT16)(*src_32 & 0xFF);
g_val = (INT16)((*src_32 >> 8) & 0xFF);
r_val = (INT16)((*src_32 >> 16) & 0xFF);
a_val = 0xFF;
src_32++;
break;
case PIXEL_FORMAT_BGRA32:
b_val = (INT16)(*src_32 & 0xFF);
g_val = (INT16)((*src_32 >> 8) & 0xFF);
r_val = (INT16)((*src_32 >> 16) & 0xFF);
a_val = (INT16)((*src_32 >> 24) & 0xFF);
src_32++;
break;
case PIXEL_FORMAT_RGBX32:
r_val = (INT16)(*src_32 & 0xFF);
g_val = (INT16)((*src_32 >> 8) & 0xFF);
b_val = (INT16)((*src_32 >> 16) & 0xFF);
a_val = 0xFF;
src_32++;
break;
case PIXEL_FORMAT_RGBA32:
r_val = (INT16)(*src_32 & 0xFF);
g_val = (INT16)((*src_32 >> 8) & 0xFF);
b_val = (INT16)((*src_32 >> 16) & 0xFF);
a_val = (INT16)((*src_32 >> 24) & 0xFF);
src_32++;
break;
case PIXEL_FORMAT_BGR24:
#ifdef __LITTLE_ENDIAN__
b_val = *src++;
g_val = *src++;
r_val = *src++;
#else
r_val = *src++;
g_val = *src++;
b_val = *src++;
#endif
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB24:
#ifdef __LITTLE_ENDIAN__
r_val = *src++;
g_val = *src++;
b_val = *src++;
#else
b_val = *src++;
g_val = *src++;
r_val = *src++;
#endif
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGR16:
b_val = (INT16)((*src_16) & 0x1F);
g_val = (INT16)((*src_16 >> 5) & 0x3F);
r_val = (INT16)((*src_16 >> 11) & 0x1F);
a_val = 0xFF;
src_16++;
break;
case PIXEL_FORMAT_RGB16:
r_val = (INT16)((*src_16) & 0x1F);
g_val = (INT16)((*src_16 >> 5) & 0x3F);
b_val = (INT16)((*src_16 >> 11) & 0x1F);
a_val = 0xFF;
src_16++;
break;
case PIXEL_FORMAT_A4:
{
int shift;
BYTE idx;
shift = (7 - (x % 8));
idx = (BYTE)(((*src_32 & 0xFF) >> shift) & 1);
idx |= (BYTE)(((((*src_32 >> 8) & 0xFF) >> shift) & 1) << 1);
idx |= (BYTE)(((((*src_32 >> 16) & 0xFF) >> shift) & 1) << 2);
idx |= (BYTE)(((((*src_32 >> 24) & 0xFF) >> shift) & 1) << 3);
idx *= 3;
r_val = (INT16)context->palette[idx];
g_val = (INT16)context->palette[idx + 1];
b_val = (INT16)context->palette[idx + 2];
if (shift == 0)
src_32++;
}
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB8:
{
int idx = (*src) * 3;
r_val = (INT16)context->palette[idx];
g_val = (INT16)context->palette[idx + 1];
b_val = (INT16)context->palette[idx + 2];
src++;
}
a_val = 0xFF;
break;
default:
r_val = g_val = b_val = a_val = 0;
break;
}
*yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2));
/* Perform color loss reduction here */
*coplane++ = (BYTE)((r_val - b_val) >> ccl);
*cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl);
*aplane++ = a_val;
}
if (context->ChromaSubsamplingLevel && (x % 2) == 1)
{
*yplane = *(yplane - 1);
*coplane = *(coplane - 1);
*cgplane = *(cgplane - 1);
}
}
if (context->ChromaSubsamplingLevel && (y % 2) == 1)
{
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
CopyMemory(yplane, yplane - rw, rw);
CopyMemory(coplane, coplane - rw, rw);
CopyMemory(cgplane, cgplane - rw, rw);
}
return TRUE;
}
static BOOL nsc_encode_subsampling(NSC_CONTEXT* context)
{
UINT32 y;
UINT32 tempWidth;
UINT32 tempHeight;
if (!context)
return FALSE;
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
if (tempHeight == 0)
return FALSE;
if (tempWidth > context->priv->PlaneBuffersLength / tempHeight)
return FALSE;
for (y = 0; y < tempHeight >> 1; y++)
{
UINT32 x;
BYTE* co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1);
BYTE* cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1);
const INT8* co_src0 = (INT8*)context->priv->PlaneBuffers[1] + (y << 1) * tempWidth;
const INT8* co_src1 = co_src0 + tempWidth;
const INT8* cg_src0 = (INT8*)context->priv->PlaneBuffers[2] + (y << 1) * tempWidth;
const INT8* cg_src1 = cg_src0 + tempWidth;
for (x = 0; x < tempWidth >> 1; x++)
{
*co_dst++ = (BYTE)(((INT16)*co_src0 + (INT16) * (co_src0 + 1) + (INT16)*co_src1 +
(INT16) * (co_src1 + 1)) >>
2);
*cg_dst++ = (BYTE)(((INT16)*cg_src0 + (INT16) * (cg_src0 + 1) + (INT16)*cg_src1 +
(INT16) * (cg_src1 + 1)) >>
2);
co_src0 += 2;
co_src1 += 2;
cg_src0 += 2;
cg_src1 += 2;
}
}
return TRUE;
}
BOOL nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)
{
if (!context || !bmpdata || (rowstride == 0))
return FALSE;
if (!nsc_encode_argb_to_aycocg(context, bmpdata, rowstride))
return FALSE;
if (context->ChromaSubsamplingLevel)
{
if (!nsc_encode_subsampling(context))
return FALSE;
}
return TRUE;
}
static UINT32 nsc_rle_encode(const BYTE* in, BYTE* out, UINT32 originalSize)
{
UINT32 left;
UINT32 runlength = 1;
UINT32 planeSize = 0;
left = originalSize;
/**
* We quit the loop if the running compressed size is larger than the original.
* In such cases data will be sent uncompressed.
*/
while (left > 4 && planeSize < originalSize - 4)
{
if (left > 5 && *in == *(in + 1))
{
runlength++;
}
else if (runlength == 1)
{
*out++ = *in;
planeSize++;
}
else if (runlength < 256)
{
*out++ = *in;
*out++ = *in;
*out++ = runlength - 2;
runlength = 1;
planeSize += 3;
}
else
{
*out++ = *in;
*out++ = *in;
*out++ = 0xFF;
*out++ = (runlength & 0x000000FF);
*out++ = (runlength & 0x0000FF00) >> 8;
*out++ = (runlength & 0x00FF0000) >> 16;
*out++ = (runlength & 0xFF000000) >> 24;
runlength = 1;
planeSize += 7;
}
in++;
left--;
}
if (planeSize < originalSize - 4)
CopyMemory(out, in, 4);
planeSize += 4;
return planeSize;
}
static void nsc_rle_compress_data(NSC_CONTEXT* context)
{
UINT16 i;
UINT32 planeSize;
UINT32 originalSize;
for (i = 0; i < 4; i++)
{
originalSize = context->OrgByteCount[i];
if (originalSize == 0)
{
planeSize = 0;
}
else
{
planeSize = nsc_rle_encode(context->priv->PlaneBuffers[i],
context->priv->PlaneBuffers[4], originalSize);
if (planeSize < originalSize)
CopyMemory(context->priv->PlaneBuffers[i], context->priv->PlaneBuffers[4],
planeSize);
else
planeSize = originalSize;
}
context->PlaneByteCount[i] = planeSize;
}
}
static UINT32 nsc_compute_byte_count(NSC_CONTEXT* context, UINT32* ByteCount, UINT32 width,
UINT32 height)
{
UINT32 tempWidth;
UINT32 tempHeight;
UINT32 maxPlaneSize;
tempWidth = ROUND_UP_TO(width, 8);
tempHeight = ROUND_UP_TO(height, 2);
maxPlaneSize = tempWidth * tempHeight + 16;
if (context->ChromaSubsamplingLevel)
{
ByteCount[0] = tempWidth * height;
ByteCount[1] = tempWidth * tempHeight / 4;
ByteCount[2] = tempWidth * tempHeight / 4;
ByteCount[3] = width * height;
}
else
{
ByteCount[0] = width * height;
ByteCount[1] = width * height;
ByteCount[2] = width * height;
ByteCount[3] = width * height;
}
return maxPlaneSize;
}
BOOL nsc_write_message(NSC_CONTEXT* context, wStream* s, const NSC_MESSAGE* message)
{
UINT32 totalPlaneByteCount;
totalPlaneByteCount = message->LumaPlaneByteCount + message->OrangeChromaPlaneByteCount +
message->GreenChromaPlaneByteCount + message->AlphaPlaneByteCount;
if (!Stream_EnsureRemainingCapacity(s, 20 + totalPlaneByteCount))
return FALSE;
Stream_Write_UINT32(s, message->LumaPlaneByteCount); /* LumaPlaneByteCount (4 bytes) */
Stream_Write_UINT32(
s, message->OrangeChromaPlaneByteCount); /* OrangeChromaPlaneByteCount (4 bytes) */
Stream_Write_UINT32(
s, message->GreenChromaPlaneByteCount); /* GreenChromaPlaneByteCount (4 bytes) */
Stream_Write_UINT32(s, message->AlphaPlaneByteCount); /* AlphaPlaneByteCount (4 bytes) */
Stream_Write_UINT8(s, message->ColorLossLevel); /* ColorLossLevel (1 byte) */
Stream_Write_UINT8(s, message->ChromaSubsamplingLevel); /* ChromaSubsamplingLevel (1 byte) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
if (message->LumaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[0], message->LumaPlaneByteCount); /* LumaPlane */
if (message->OrangeChromaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[1],
message->OrangeChromaPlaneByteCount); /* OrangeChromaPlane */
if (message->GreenChromaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[2],
message->GreenChromaPlaneByteCount); /* GreenChromaPlane */
if (message->AlphaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[3], message->AlphaPlaneByteCount); /* AlphaPlane */
return TRUE;
}
BOOL nsc_compose_message(NSC_CONTEXT* context, wStream* s, const BYTE* data, UINT32 width,
UINT32 height, UINT32 scanline)
{
BOOL rc;
NSC_MESSAGE message = { 0 };
if (!context || !s || !data)
return FALSE;
context->width = width;
context->height = height;
if (!nsc_context_initialize_encode(context))
return FALSE;
/* ARGB to AYCoCg conversion, chroma subsampling and colorloss reduction */
PROFILER_ENTER(context->priv->prof_nsc_encode)
rc = context->encode(context, data, scanline);
PROFILER_EXIT(context->priv->prof_nsc_encode)
if (!rc)
return FALSE;
/* RLE encode */
PROFILER_ENTER(context->priv->prof_nsc_rle_compress_data)
nsc_rle_compress_data(context);
PROFILER_EXIT(context->priv->prof_nsc_rle_compress_data)
message.PlaneBuffers[0] = context->priv->PlaneBuffers[0];
message.PlaneBuffers[1] = context->priv->PlaneBuffers[1];
message.PlaneBuffers[2] = context->priv->PlaneBuffers[2];
message.PlaneBuffers[3] = context->priv->PlaneBuffers[3];
message.LumaPlaneByteCount = context->PlaneByteCount[0];
message.OrangeChromaPlaneByteCount = context->PlaneByteCount[1];
message.GreenChromaPlaneByteCount = context->PlaneByteCount[2];
message.AlphaPlaneByteCount = context->PlaneByteCount[3];
message.ColorLossLevel = context->ColorLossLevel;
message.ChromaSubsamplingLevel = context->ChromaSubsamplingLevel;
return nsc_write_message(context, s, &message);
}
BOOL nsc_decompose_message(NSC_CONTEXT* context, wStream* s, BYTE* bmpdata, UINT32 x, UINT32 y,
UINT32 width, UINT32 height, UINT32 rowstride, UINT32 format,
UINT32 flip)
{
size_t size = Stream_GetRemainingLength(s);
if (size > UINT32_MAX)
return FALSE;
if (!nsc_process_message(context, (UINT16)FreeRDPGetBitsPerPixel(context->format), width,
height, Stream_Pointer(s), (UINT32)size, bmpdata, format, rowstride, x,
y, width, height, flip))
return FALSE;
Stream_Seek(s, size);
return TRUE;
}
| 2.171875 | 2 |
2024-11-18T21:10:13.013818+00:00
| 2020-10-22T02:17:09 |
0df6c439f712f6492416b3dcf1362dd5f539e3bd
|
{
"blob_id": "0df6c439f712f6492416b3dcf1362dd5f539e3bd",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-22T02:17:09",
"content_id": "ea5c0bc8122aedb78ef317678137b8b7bd38d0e3",
"detected_licenses": [
"MIT"
],
"directory_id": "2ef03a2179d271e972766cc07981e9302263199c",
"extension": "c",
"filename": "exe1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 292146297,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 638,
"license": "MIT",
"license_type": "permissive",
"path": "/tarefa01/exe1.c",
"provenance": "stackv2-0065.json.gz:30964",
"repo_name": "joaobispo2077/tads-pfda1",
"revision_date": "2020-10-22T02:17:09",
"revision_id": "7c906276cb27d16f23f3b3f2164ea539098c4136",
"snapshot_id": "c2e3418563fb5f1697470c919537bd1da2c05b2c",
"src_encoding": "ISO-8859-1",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/joaobispo2077/tads-pfda1/7c906276cb27d16f23f3b3f2164ea539098c4136/tarefa01/exe1.c",
"visit_date": "2022-12-30T17:51:10.644911"
}
|
stackv2
|
#include <stdio.h>
#include <locale.h>
int main ()
{
setlocale(LC_ALL, "Portuguese");
float height, radius, volume;
printf("\n------------Cálculo do volume de uma lata de Óleo------------\n");
printf("\n*********Para calcular o volume da lata você deve digitar os valores do raio e altura da lata*********\n");
printf("\nDigite o raio(cm) da lata de óleo: ");
scanf("%f", &radius);
printf("\nAgora, digite a altura(cm) a da lata de óleo: ");
scanf("%f", &height);
volume = (3.14159 * (radius*radius) * height);
printf("\nO volume da lata de óleo em mililitros é %.1fml", volume);
}
| 3.46875 | 3 |
2024-11-18T21:10:13.065553+00:00
| 2020-06-03T04:51:59 |
25b4bfb7b7cddb44357b4a804be114481b599da6
|
{
"blob_id": "25b4bfb7b7cddb44357b4a804be114481b599da6",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-03T04:51:59",
"content_id": "dd52ff4ad55b6bd4e933db2238b9481b4d4b9f6c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cec302f1b0a1f4c41c3a0b5f9b90d4ab902005a6",
"extension": "h",
"filename": "sgx_signal_util.h",
"fork_events_count": 0,
"gha_created_at": "2020-05-25T04:53:14",
"gha_event_created_at": "2020-05-25T04:53:14",
"gha_language": null,
"gha_license_id": null,
"github_id": 266686111,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1544,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/case-studies/bzip2/src/MyEnclave/include/sgx_signal_util.h",
"provenance": "stackv2-0065.json.gz:31092",
"repo_name": "kripa432/Panoply",
"revision_date": "2020-06-03T04:51:59",
"revision_id": "6287e7feacc49c4bc6cc0229e793600b49545251",
"snapshot_id": "cf4ea0f63cd3c1216f7a97bc1cf77a14afa019af",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kripa432/Panoply/6287e7feacc49c4bc6cc0229e793600b49545251/case-studies/bzip2/src/MyEnclave/include/sgx_signal_util.h",
"visit_date": "2022-09-11T15:06:22.609854"
}
|
stackv2
|
/**
* @author ${kekkaishivn} - dattl@ifi.uio.no
*
* ${tags}
*/
#ifndef SGX_SIGNAL_UTIL_H
#define SGX_SIGNAL_UTIL_H
#include <struct/sgx_signal_struct.h>
#ifdef __cplusplus
extern "C" {
#endif
extern int sgx_wrapper_sigemptyset(sigset_t *set);
extern int sgx_wrapper_sigfillset(sigset_t *set);
extern int sgx_wrapper_sigaddset(sigset_t *set, int signo);
extern int sgx_wrapper_sigdelset(sigset_t *set, int signo);
extern int sgx_wrapper_sigismember(const sigset_t *set, int signo);
extern int sgx_wrapper_sigsuspend(const sigset_t *set);
extern int sgx_wrapper_sigaction(int sig, struct sigaction *act, struct sigaction *oact);
extern int sgx_wrapper_sigpending(sigset_t *set);
extern int sgx_wrapper_sigwait(const sigset_t *set, int *sig);
extern __sighandler_t sgx_wrapper_signal(int __sig, __sighandler_t __handler);
extern int sgx_wrapper_raise(int signal);
extern int sgx_wrapper_kill(pid_t pid, int sig);
#ifdef __cplusplus
}
#endif
#define sigemptyset(A) sgx_wrapper_sigemptyset(A)
#define sigfillset(A) sgx_wrapper_sigfillset(A)
#define sigaddset(A, B) sgx_wrapper_sigaddset(A, B)
#define sigdelset(A, B) sgx_wrapper_sigdelset(A, B)
#define sigismember(A, B) sgx_wrapper_sigismember(A, B)
#define sigsuspend(A) sgx_wrapper_sigsuspend(A)
#define sigaction(A, B, C) sgx_wrapper_sigaction(A, B, C)
#define sigpending(A) sgx_wrapper_sigpending(A)
#define sigwait(A, B) sgx_wrapper_sigwait(A, B)
#define signal(A, B) sgx_wrapper_signal(A, B)
#define raise(A) sgx_wrapper_raise(A)
#define kill(A, B) sgx_wrapper_kill(A, B)
#endif
| 2.140625 | 2 |
2024-11-18T21:10:13.175631+00:00
| 2021-11-05T23:13:00 |
0c8ea605da813581edf8f858010853cd3afed839
|
{
"blob_id": "0c8ea605da813581edf8f858010853cd3afed839",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-05T23:13:00",
"content_id": "114c6029f5433ed87c94b45007f3c9f3b6fb37ba",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "62cf9edf9e1d5d63c23120d5bb05a1178d86541b",
"extension": "h",
"filename": "rosc.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 425105548,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3569,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/pico_fw/src/lib/pico-sdk/src/rp2040/hardware_structs/include/hardware/structs/rosc.h",
"provenance": "stackv2-0065.json.gz:31220",
"repo_name": "leekilhun/stmIDE_rpi_pico",
"revision_date": "2021-11-05T23:13:00",
"revision_id": "e3c8db024415e5c9ff173e9a98c679925d169649",
"snapshot_id": "9815606db36c8e856a90325fe3ac758fd61c9bd8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/leekilhun/stmIDE_rpi_pico/e3c8db024415e5c9ff173e9a98c679925d169649/pico_fw/src/lib/pico-sdk/src/rp2040/hardware_structs/include/hardware/structs/rosc.h",
"visit_date": "2023-08-22T23:42:41.425100"
}
|
stackv2
|
// THIS HEADER FILE IS AUTOMATICALLY GENERATED -- DO NOT EDIT
/*
* Copyright (c) 2021 Raspberry Pi (Trading) Ltd.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _HARDWARE_STRUCTS_ROSC_H
#define _HARDWARE_STRUCTS_ROSC_H
#include "hardware/address_mapped.h"
#include "hardware/regs/rosc.h"
// Reference to datasheet: https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf#tab-registerlist_rosc
//
// The _REG_ macro is intended to help make the register navigable in your IDE (for example, using the "Go to Definition" feature)
// _REG_(x) will link to the corresponding register in hardware/regs/rosc.h.
//
// Bit-field descriptions are of the form:
// BITMASK [BITRANGE]: FIELDNAME (RESETVALUE): DESCRIPTION
typedef struct {
_REG_(ROSC_CTRL_OFFSET) // ROSC_CTRL
// Ring Oscillator control
// 0x00fff000 [23:12] : ENABLE (0): On power-up this field is initialised to ENABLE
// 0x00000fff [11:0] : FREQ_RANGE (0xaa0): Controls the number of delay stages in the ROSC ring
io_rw_32 ctrl;
_REG_(ROSC_FREQA_OFFSET) // ROSC_FREQA
// The FREQA & FREQB registers control the frequency by controlling the drive strength of each stage
// 0xffff0000 [31:16] : PASSWD (0): Set to 0x9696 to apply the settings
// 0x00007000 [14:12] : DS3 (0): Stage 3 drive strength
// 0x00000700 [10:8] : DS2 (0): Stage 2 drive strength
// 0x00000070 [6:4] : DS1 (0): Stage 1 drive strength
// 0x00000007 [2:0] : DS0 (0): Stage 0 drive strength
io_rw_32 freqa;
_REG_(ROSC_FREQB_OFFSET) // ROSC_FREQB
// For a detailed description see freqa register
// 0xffff0000 [31:16] : PASSWD (0): Set to 0x9696 to apply the settings
// 0x00007000 [14:12] : DS7 (0): Stage 7 drive strength
// 0x00000700 [10:8] : DS6 (0): Stage 6 drive strength
// 0x00000070 [6:4] : DS5 (0): Stage 5 drive strength
// 0x00000007 [2:0] : DS4 (0): Stage 4 drive strength
io_rw_32 freqb;
_REG_(ROSC_DORMANT_OFFSET) // ROSC_DORMANT
// Ring Oscillator pause control
io_rw_32 dormant;
_REG_(ROSC_DIV_OFFSET) // ROSC_DIV
// Controls the output divider
// 0x00000fff [11:0] : DIV (0): set to 0xaa0 + div where
io_rw_32 div;
_REG_(ROSC_PHASE_OFFSET) // ROSC_PHASE
// Controls the phase shifted output
// 0x00000ff0 [11:4] : PASSWD (0): set to 0xaa
// 0x00000008 [3] : ENABLE (1): enable the phase-shifted output
// 0x00000004 [2] : FLIP (0): invert the phase-shifted output
// 0x00000003 [1:0] : SHIFT (0): phase shift the phase-shifted output by SHIFT input clocks
io_rw_32 phase;
_REG_(ROSC_STATUS_OFFSET) // ROSC_STATUS
// Ring Oscillator Status
// 0x80000000 [31] : STABLE (0): Oscillator is running and stable
// 0x01000000 [24] : BADWRITE (0): An invalid value has been written to CTRL_ENABLE or CTRL_FREQ_RANGE or FREQA or...
// 0x00010000 [16] : DIV_RUNNING (0): post-divider is running
// 0x00001000 [12] : ENABLED (0): Oscillator is enabled but not necessarily running and stable
io_rw_32 status;
_REG_(ROSC_RANDOMBIT_OFFSET) // ROSC_RANDOMBIT
// This just reads the state of the oscillator output so randomness is compromised if the ring oscillator is stopped or...
// 0x00000001 [0] : RANDOMBIT (1)
io_ro_32 randombit;
_REG_(ROSC_COUNT_OFFSET) // ROSC_COUNT
// A down counter running at the ROSC frequency which counts to zero and stops
// 0x000000ff [7:0] : COUNT (0)
io_rw_32 count;
} rosc_hw_t;
#define rosc_hw ((rosc_hw_t *const)ROSC_BASE)
#endif
| 2.0625 | 2 |
2024-11-18T21:10:15.431926+00:00
| 2023-08-17T13:00:20 |
3d1a0e5a3db4e22ccbd2aec93b9abff0cc301dbf
|
{
"blob_id": "3d1a0e5a3db4e22ccbd2aec93b9abff0cc301dbf",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T07:43:37",
"content_id": "58dbe822111e12c383a869134cb4d8c900079c63",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c9bc99866cfab223c777cfb741083be3e9439d81",
"extension": "c",
"filename": "mod_armv8m_mpu.c",
"fork_events_count": 165,
"gha_created_at": "2018-05-22T10:35:56",
"gha_event_created_at": "2023-09-13T14:27:10",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 134399880,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1251,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/module/armv8m_mpu/src/mod_armv8m_mpu.c",
"provenance": "stackv2-0065.json.gz:31605",
"repo_name": "ARM-software/SCP-firmware",
"revision_date": "2023-08-17T13:00:20",
"revision_id": "f6bcca436768359ffeadd84d65e8ea0c3efc7ef1",
"snapshot_id": "4738ca86ce42d82588ddafc2226a1f353ff2c797",
"src_encoding": "UTF-8",
"star_events_count": 211,
"url": "https://raw.githubusercontent.com/ARM-software/SCP-firmware/f6bcca436768359ffeadd84d65e8ea0c3efc7ef1/module/armv8m_mpu/src/mod_armv8m_mpu.c",
"visit_date": "2023-09-01T16:13:36.962036"
}
|
stackv2
|
/*
* Arm SCP/MCP Software
* Copyright (c) 2022, Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "mod_armv8m_mpu.h"
#include <fwk_assert.h>
#include <fwk_id.h>
#include <fwk_module.h>
#include <fwk_status.h>
#include <fmw_cmsis.h>
static int armv8m_mpu_init(
fwk_id_t module_id,
unsigned int element_count,
const void *data)
{
const struct mod_armv8m_mpu_config *config;
uint8_t attr_index;
int status;
fwk_assert(element_count == 0);
fwk_assert(data != NULL);
config = data;
if (config->attributes_count <= (uint8_t)MPU_MAX_ATTR_COUNT) {
ARM_MPU_Disable();
for (attr_index = 0U; attr_index < config->attributes_count;
attr_index++) {
ARM_MPU_SetMemAttr(attr_index, config->attributes[attr_index]);
}
ARM_MPU_Load(
config->first_region_number, config->regions, config->region_count);
ARM_MPU_Enable(MPU_CTRL_HFNMIENA_Msk);
status = FWK_SUCCESS;
} else {
status = FWK_E_RANGE;
}
return status;
}
/* Module description */
const struct fwk_module module_armv8m_mpu = {
.type = FWK_MODULE_TYPE_DRIVER,
.init = armv8m_mpu_init,
};
| 2.046875 | 2 |
2024-11-18T21:10:15.620652+00:00
| 2018-05-04T12:23:02 |
e7394f676e285a6929c0913a71f27f0eba015d69
|
{
"blob_id": "e7394f676e285a6929c0913a71f27f0eba015d69",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-04T12:23:02",
"content_id": "c192d9e548664fd92804d6df47e95dd84006fef2",
"detected_licenses": [
"MIT"
],
"directory_id": "341712d8a4382286c6e4a4edb68332656603928f",
"extension": "c",
"filename": "bang_search.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 131995340,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2043,
"license": "MIT",
"license_type": "permissive",
"path": "/srcs/bang/bang_search.c",
"provenance": "stackv2-0065.json.gz:31862",
"repo_name": "fbertoia/42sh",
"revision_date": "2018-05-04T12:23:02",
"revision_id": "5dc12587c58b26814c55a50b8c83b198796ca91a",
"snapshot_id": "d5d4311efd4ef4285b6dedc4e96ff5e9f4c82524",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/fbertoia/42sh/5dc12587c58b26814c55a50b8c83b198796ca91a/srcs/bang/bang_search.c",
"visit_date": "2020-03-15T05:50:01.779129"
}
|
stackv2
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* bang_search.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hfontain <hfontain@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/26 15:13:59 by fbertoia #+# #+# */
/* Updated: 2018/05/02 13:30:08 by hfontain ### ########.fr */
/* */
/* ************************************************************************** */
#include "sh21.h"
char *get_history_at(int nb, int *j)
{
const t_list *list = get_ft_shell()->history;
int len;
t_list *ptr;
char *iota;
len = ft_lstsize((t_list*)list);
nb += nb < 0 ? len + 1 : 0;
if (nb <= 0 || nb > len)
{
ft_error(-9, "!");
return (NULL);
}
iota = ft_itoa(nb);
*j += ft_strlen(iota);
ptr = (t_list*)list;
while (len != nb && len > 0)
{
ptr = ptr->next;
len--;
}
if (len != nb)
ft_error(-9, "!");
ft_strdel(&iota);
return (len == nb ?
ft_strdup(((t_ft_hist_entry*)(ptr->content))->command) : NULL);
}
char *cmp_history(char *str, int *j)
{
char *tmp;
char *ret;
while (str[*j] && ft_isalpha(str[*j]))
*j += 1;
tmp = ft_strndup(str, *j + 1);
ret = search_history_nav(get_ft_shell(), tmp, 1);
if (!ret)
ft_error(-9, tmp);
ft_strdel(&tmp);
return (ret ? ft_strdup(ret) : NULL);
}
void replace_bang(char **str, int *i, int *j, char *bang)
{
char *ret;
int len;
len = ft_strlen(*str) + ft_strlen(bang) + 1;
ret = ft_strnew(len);
ft_strncpy(ret, *str, *i);
ft_strcat(ret, bang);
ft_strlcat(ret, *str + (*i + *j ? *i + *j + 1 : *i + *j), len);
ft_strdel(str);
*str = ret;
}
| 2.28125 | 2 |
2024-11-18T21:10:15.682178+00:00
| 2014-08-06T13:32:49 |
01615f6c35d57fdff99e176c87b685a745addf1f
|
{
"blob_id": "01615f6c35d57fdff99e176c87b685a745addf1f",
"branch_name": "refs/heads/master",
"committer_date": "2014-08-06T13:32:49",
"content_id": "9fe82bec9e3bc1af1531af3d95ab0d1e5b06a887",
"detected_licenses": [
"MIT"
],
"directory_id": "708fcc3f25fca69d279c7a34ce82e70a0bbf9164",
"extension": "c",
"filename": "udf_sha256_latin.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": 589,
"license": "MIT",
"license_type": "permissive",
"path": "/src/udf_sha256_latin.c",
"provenance": "stackv2-0065.json.gz:31990",
"repo_name": "cgvarela/teradata-udf-sha2",
"revision_date": "2014-08-06T13:32:49",
"revision_id": "be6cc23a7018c4af8a6ff449af3fb686e98298ce",
"snapshot_id": "16b77d0a0bddb7b62d1883d4968623e1ae06ba92",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cgvarela/teradata-udf-sha2/be6cc23a7018c4af8a6ff449af3fb686e98298ce/src/udf_sha256_latin.c",
"visit_date": "2020-03-17T18:57:27.388101"
}
|
stackv2
|
#define SQL_TEXT Latin_Text
#include "sqltypes_td.h"
#include <stdlib.h>
#include <string.h>
#define DIGEST_LEN_SHA256 32
#define UDF_OK "00000"
void sha256(const unsigned char message[], int len, unsigned char result[]);
void sha256_latin(VARCHAR_LATIN *arg, CHARACTER_LATIN *result,
char sqlstate[])
{
int i;
unsigned char outbuf[DIGEST_LEN_SHA256];
sha256((unsigned char *)arg, strlen((char *)arg), outbuf);
for (i = 0; i < DIGEST_LEN_SHA256; i++) {
sprintf(result + i*2, "%02x", outbuf[i]);
}
sprintf(sqlstate, UDF_OK);
}
| 2.0625 | 2 |
2024-11-18T21:10:15.808480+00:00
| 2017-12-14T16:30:11 |
119bae2aa3242aa78ef1757f29aa2406de45db3f
|
{
"blob_id": "119bae2aa3242aa78ef1757f29aa2406de45db3f",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-14T16:30:11",
"content_id": "2250e65dfeaab7402d9487fd57a1ef2fe43aef83",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "bca39ef7b72a5ea14e43f2e970f5bae5c19d017c",
"extension": "c",
"filename": "exe3-1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 112916968,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1905,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/chapter-3/exe3-1.c",
"provenance": "stackv2-0065.json.gz:32118",
"repo_name": "arist1213/k-r",
"revision_date": "2017-12-14T16:30:11",
"revision_id": "1fc900ede16d29ac50dcbce74df6bfcef3edf46a",
"snapshot_id": "e18f9dc3bae432d8caff3c30df6a60cced58b607",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/arist1213/k-r/1fc900ede16d29ac50dcbce74df6bfcef3edf46a/chapter-3/exe3-1.c",
"visit_date": "2021-05-06T22:33:35.236690"
}
|
stackv2
|
#include <stdio.h>
#include <time.h>
#define MAX_ELEMENT 2000000
#define MAX_ITER_TIME 10000000 /* 查找次数*/
/* two tests */
int binarySearch1(int x, int v[], int n) {
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high) {
mid = (low+high) / 2;
if (x < v[mid])
high = mid - 1;
else if (v[mid] < x)
low = mid + 1;
else
return mid;
}
return -1;
}
/* one test */
int binarySearch2(int x, int v[], int n) {
int low, high, mid;
low = 0;
high = n;
/* 在区间[low, high)查找x */
while (low < high - 1) {
mid = (low + high) >> 1; // 以mid为中心
// 比较后查找 [low, mid) 或 [mid, high)
if (x < v[mid])
high = mid;
else
low = mid;
} //出口时, high = low + 1, 查找区间仅剩 v[low] - [low, high)
return v[low] == x ? low : -1;
}
int main(int argc, char *argv[]) {
int testdata[MAX_ELEMENT];
int i;
int index;
clock_t time_taken;
int n = 1; // 查找当前元素,测试查找时间效率
printf("search element %d in %d sizes for %d times.\n", n, MAX_ELEMENT, MAX_ITER_TIME);
for ( i = 0; i < MAX_ELEMENT; ++i )
testdata[i] = i;
for(i=0, time_taken = clock(); i < MAX_ITER_TIME; i++)
binarySearch1(n, testdata, MAX_ELEMENT);
time_taken = clock() - time_taken;
printf("binarySearch1 took %lu clocks (%lu seconds)\n",
(unsigned long) time_taken,
(unsigned long) time_taken / CLOCKS_PER_SEC);
for(i=0, time_taken = clock(); i < MAX_ITER_TIME; i++)
binarySearch2(n, testdata, MAX_ELEMENT);
time_taken = clock() - time_taken;
printf("binarySearch2 took %lu clocks (%lu seconds)\n",
(unsigned long) time_taken,
(unsigned long) time_taken / CLOCKS_PER_SEC);
return 0;
}
| 3.296875 | 3 |
2024-11-18T21:10:15.889061+00:00
| 2019-08-06T14:24:54 |
4c6daeaba5cb7c1c1c7d65d683c89163c556feaf
|
{
"blob_id": "4c6daeaba5cb7c1c1c7d65d683c89163c556feaf",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-06T14:24:54",
"content_id": "de6570106bcff2f983b35f58c132361d2adcf8ae",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "021a3ccdcb91d84629f1de7343981b572840b169",
"extension": "c",
"filename": "ex15.c",
"fork_events_count": 8,
"gha_created_at": "2016-02-22T11:40:41",
"gha_event_created_at": "2023-04-11T09:20:08",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 52269402,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1675,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/vec/vec/examples/tests/ex15.c",
"provenance": "stackv2-0065.json.gz:32246",
"repo_name": "firedrakeproject/petsc",
"revision_date": "2019-08-06T14:24:54",
"revision_id": "7afe75c1a0a66862f32d7a0f5c0c5ae5079c4c77",
"snapshot_id": "dcf7b32e83bdc88d37099904960d7a4c3c4a89e4",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/firedrakeproject/petsc/7afe75c1a0a66862f32d7a0f5c0c5ae5079c4c77/src/vec/vec/examples/tests/ex15.c",
"visit_date": "2023-08-31T22:16:45.175956"
}
|
stackv2
|
static char help[] = "Tests VecSetValuesBlocked() on sequential vectors.\n\n";
#include <petscvec.h>
int main(int argc,char **argv)
{
PetscErrorCode ierr;
PetscMPIInt size;
PetscInt n = 9,bs = 3,indices[2],i;
PetscScalar values[6];
Vec x;
ierr = PetscInitialize(&argc,&argv,(char*)0,help);if (ierr) return ierr;
ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
if (size != 1) SETERRQ(PETSC_COMM_SELF,1,"Must be run with one processor");
/* create vector */
ierr = VecCreate(PETSC_COMM_SELF,&x);CHKERRQ(ierr);
ierr = VecSetSizes(x,n,n);CHKERRQ(ierr);
ierr = VecSetBlockSize(x,bs);CHKERRQ(ierr);
ierr = VecSetType(x,VECSEQ);CHKERRQ(ierr);
for (i=0; i<6; i++) values[i] = 4.0*i;
indices[0] = 0;
indices[1] = 2;
ierr = VecSetValuesBlocked(x,2,indices,values,INSERT_VALUES);CHKERRQ(ierr);
ierr = VecAssemblyBegin(x);CHKERRQ(ierr);
ierr = VecAssemblyEnd(x);CHKERRQ(ierr);
/*
Resulting vector should be 0 4 8 0 0 0 12 16 20
*/
ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
/* test insertion with negative indices */
ierr = VecSetOption(x,VEC_IGNORE_NEGATIVE_INDICES,PETSC_TRUE);CHKERRQ(ierr);
for (i=0; i<6; i++) values[i] = -4.0*i;
indices[0] = -1;
indices[1] = 2;
ierr = VecSetValuesBlocked(x,2,indices,values,ADD_VALUES);CHKERRQ(ierr);
ierr = VecAssemblyBegin(x);CHKERRQ(ierr);
ierr = VecAssemblyEnd(x);CHKERRQ(ierr);
/*
Resulting vector should be 0 4 8 0 0 0 0 0 0
*/
ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
ierr = VecDestroy(&x);CHKERRQ(ierr);
ierr = PetscFinalize();
return ierr;
}
/*TEST
test:
TEST*/
| 2.546875 | 3 |
2024-11-18T21:10:16.173025+00:00
| 2013-06-11T16:30:14 |
2ff0b75c88ececf3991a5c93805a444ec110745a
|
{
"blob_id": "2ff0b75c88ececf3991a5c93805a444ec110745a",
"branch_name": "refs/heads/master",
"committer_date": "2013-06-11T16:30:14",
"content_id": "f72da42b70ccbd0076e162f521dc4bffeadbceaa",
"detected_licenses": [
"MIT"
],
"directory_id": "7b9f2fcd8dd0607a650fd56957eb1f83721d31d8",
"extension": "h",
"filename": "daemonize.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": 2004,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/src/daemonize.h",
"provenance": "stackv2-0065.json.gz:32630",
"repo_name": "mk-qi/daemonize",
"revision_date": "2013-06-11T16:30:14",
"revision_id": "7612b7236cde45878a97f0e180ef3d49a4a00294",
"snapshot_id": "ae264cd3081d4799812c26f8693f4b81f6f36373",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mk-qi/daemonize/7612b7236cde45878a97f0e180ef3d49a4a00294/lib/src/daemonize.h",
"visit_date": "2021-03-12T23:17:58.245918"
}
|
stackv2
|
#ifndef DAEMONIZE_H_
#define DAEMONIZE_H_
#include <sys/types.h>
#include <unistd.h>
#include <stdbool.h>
/*
* function:
* daemonize
* description:
* After calling this function the process has taken all actions
* to be able to run as a daemon, except creating and writing to log
* files. After a successful function call the application shall not make
* use of stderr, stdout and stdin.
*
* @mask:
* value gained by or'ing the following values:
*
* S_IRWXU 00700 mask for file owner permissions
* S_IRUSR 00400 owner has read permission
* S_IWUSR 00200 owner has write permission
* S_IXUSR 00100 owner has execute permission
* S_IRWXG 00070 mask for group permissions
* S_IRGRP 00040 group has read permission
* S_IWGRP 00020 group has write permission
* S_IXGRP 00010 group has execute permission
* S_IRWXO 00007 mask for permissions for others (not in group)
* S_IROTH 00004 others have read permission
* S_IWOTH 00002 others have write permission
* S_IXOTH 00001 others have execute permission
*
* @dir:
* Working directory of the daemon.
*
* @close_fds:
* close and redirect stdin, stdout and stderr to /dev/null
*
* @return:
* Session id of the daemon or -1 on failure.
*
*
* example usage:
*
* #include <unistd.h>
* #include "daemonize.h"
*
* int main(int argc, char *argv[])
* {
* if(daemonize(S_IXUSR | S_IWGRP | S_IXGRP | S_IWOTH | S_IXOTH, "/") < 0)
* exit(EXIT_FAILURE);
*
* init_other_stuff();
*
* while(1) {
* do_daemon_stuff();
* }
*
* return EXIT_SUCCESS;
* }
*/
pid_t daemonize(mode_t mask, const char *__restrict dir, bool close_fds);
#endif /* DAEMONIZE_H_ */
| 2.375 | 2 |
2024-11-18T21:10:16.243261+00:00
| 2020-09-30T00:04:38 |
7b80354024effba316b4926ee6007268f1cbbb30
|
{
"blob_id": "7b80354024effba316b4926ee6007268f1cbbb30",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-30T00:04:38",
"content_id": "69a7b32b515b8114bd6d86983487c82007430bc5",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "669b4204800593f8e847c229aa73e3e85b2a7359",
"extension": "c",
"filename": "update.c",
"fork_events_count": 0,
"gha_created_at": "2020-03-18T01:54:47",
"gha_event_created_at": "2020-03-18T01:54:48",
"gha_language": null,
"gha_license_id": null,
"github_id": 248114614,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5140,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/common/update.c",
"provenance": "stackv2-0065.json.gz:32759",
"repo_name": "mkuyper/basicloader",
"revision_date": "2020-09-30T00:04:38",
"revision_id": "658bf7ce2bcd344a6f8b14611309146294d19696",
"snapshot_id": "18366a06ad9871f575436a40f38b107e29b62a92",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/mkuyper/basicloader/658bf7ce2bcd344a6f8b14611309146294d19696/src/common/update.c",
"visit_date": "2021-03-31T14:58:48.736297"
}
|
stackv2
|
// Copyright (C) 2020-2020 Michael Kuyper. All rights reserved.
// Copyright (C) 2016-2019 Semtech (International) AG. All rights reserved.
//
// This file is subject to the terms and conditions defined in file 'LICENSE',
// which is part of this source code package.
#include "bootloader.h"
#include "update.h"
#include "sha2.h"
#include "lz4.h"
#if !defined(UP_PAGEBUFFER_SZ) || ((UP_PAGEBUFFER_SZ & 3) != 0) || ((UP_PAGEBUFFER_SZ & (UP_PAGEBUFFER_SZ - 1)) != 0)
#error "UP_PAGEBUFFER_SZ must be defined as a multiple of 4 and a power of 2"
#endif
#define PB_WORDS (UP_PAGEBUFFER_SZ >> 2)
// ------------------------------------------------
// Update functions
// write flash pages (src can be in flash too)
static void flashcopy (void* ctx, uint32_t* dst, const uint32_t* src, uint32_t nwords) {
while (nwords > 0) {
uint32_t buf[PB_WORDS];
int i, m = (nwords < PB_WORDS) ? nwords : PB_WORDS;
nwords -= m;
for (i = 0; i < m; i++) {
buf[i] = *src++;
}
for (; i < PB_WORDS; i++) {
buf[i] = 0; // pad last page with 0
}
up_flash_wr_page(ctx, dst, buf);
dst += PB_WORDS;
}
}
static inline uint32_t* _aligned (void* p) {
return p;
}
static uint32_t update_plain (void* ctx, boot_uphdr* fwup, bool install) {
uint32_t* src = (uint32_t*) (fwup + 1);
uint32_t* dst;
uint32_t rv;
// perform size check and get install address
if ((rv = up_install_init(ctx, fwup->fwsize, (void**) &dst, 0, NULL, NULL)) != BOOT_OK) {
return rv;
}
// copy new firmware to destination
if (install) {
up_flash_unlock(ctx);
flashcopy(ctx, dst, src, fwup->fwsize >> 2);
up_flash_lock(ctx);
}
return BOOT_OK;
}
// process LZ4-compressed self-contained update
static uint32_t update_lz4 (void* ctx, boot_uphdr* fwup, bool install) {
uint8_t* dst;
uint8_t* src = (uint8_t*) fwup + sizeof(boot_uphdr);
uint32_t srclen = fwup->size - sizeof(boot_uphdr);
uint32_t lz4len = srclen - src[srclen-1]; // strip word padding
uint32_t rv;
// perform size check and get install address
if ((rv = up_install_init(ctx, fwup->fwsize, (void**) &dst, 0, NULL, NULL)) != BOOT_OK) {
return rv;
}
if (install) {
up_flash_unlock(ctx);
// uncompress new firmware and replace current firmware at destination
lz4_decompress(ctx, src, lz4len, dst, NULL, 0);
up_flash_lock(ctx);
}
return BOOT_OK;
}
static bool checkhash (const uint8_t* msg, uint32_t len, uint32_t* hash) {
uint32_t tmp[8];
sha256(tmp, msg, len);
return (tmp[0] == hash[0] && tmp[1] == hash[1]);
}
// process LZ4-compressed block-delta update
static uint32_t update_lz4delta (void* ctx, boot_uphdr* fwup, bool install) {
boot_updeltahdr* dhdr = (boot_updeltahdr*) ((uint8_t*) fwup + sizeof(boot_uphdr));
uint8_t* src = (uint8_t*) dhdr + sizeof(boot_updeltahdr);
uint8_t* end = (uint8_t*) fwup + fwup->size;
uint32_t blksize = dhdr->blksize;
uint8_t* dst;
uint8_t* tmp;
boot_fwhdr* fwhdr;
uint32_t rv;
// perform size check and get install address and temp area
if ((rv = up_install_init(ctx, fwup->fwsize, (void**) &dst, blksize, (void**) &tmp, &fwhdr)) != BOOT_OK) {
return rv;
}
// check reference firmware crc and size before installing (will be overwritten during install)
if (!install && (dhdr->refcrc != fwhdr->crc || dhdr->refsize != fwhdr->size)) {
return BOOT_E_GENERAL;
}
// process delta blocks
while (src < end) {
boot_updeltablk* b = (boot_updeltablk*) src; // delta block
uint32_t boff = b->blkidx * blksize;
uint32_t doff = b->dictidx * blksize;
if (boff > fwup->fwsize || doff + b->dictlen > dhdr->refsize) {
return BOOT_E_SIZE;
}
uint8_t* baddr = dst + boff;
uint32_t bsz = (fwup->fwsize - boff < blksize) ? fwup->fwsize - boff : blksize; // current block size (last block might be shorter)
if (install) {
// verify target block
if (!checkhash(baddr, bsz, _aligned(b->hash))) {
up_flash_unlock(ctx);
// verify temp block
if (!checkhash(tmp, bsz, _aligned(b->hash))) {
// uncompress delta to temp block
if (lz4_decompress(ctx, b->lz4data, b->lz4len, tmp, (uint8_t*) fwhdr + doff, b->dictlen) != bsz) {
return BOOT_E_GENERAL; // unrecoverable error - should not happen!
}
// verify temp block
if (!checkhash(tmp, bsz, _aligned(b->hash))) {
return BOOT_E_GENERAL; // unrecoverable error - should not happen!
}
}
// copy temp block to target
flashcopy(ctx, (uint32_t*) baddr, (uint32_t*) tmp, bsz >> 2);
up_flash_lock(ctx);
}
}
// advance to next delta block (4-aligned)
src += (sizeof(boot_updeltablk) + b->lz4len + 3) & ~0x3;
}
return BOOT_OK;
}
uint32_t update (void* ctx, boot_uphdr* fwup, bool install) {
// Note: The integrity of the update pointed to by fwup has
// been verified at this point.
switch (fwup->uptype) {
case BOOT_UPTYPE_PLAIN:
return update_plain(ctx, fwup, install);
case BOOT_UPTYPE_LZ4:
return update_lz4(ctx, fwup, install);
case BOOT_UPTYPE_LZ4DELTA:
return update_lz4delta(ctx, fwup, install);
default:
return BOOT_E_NOIMPL;
}
}
| 2.34375 | 2 |
2024-11-18T21:10:16.470831+00:00
| 2018-05-04T12:29:26 |
9f497f1b04a05419425d0ae8020d30f445e73a32
|
{
"blob_id": "9f497f1b04a05419425d0ae8020d30f445e73a32",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-04T12:29:26",
"content_id": "ff8caf55be25ffafeca2d68e9bbf672f8dc0d626",
"detected_licenses": [
"MIT"
],
"directory_id": "6584afa228e014e9c61e5380dfe845b93c20f759",
"extension": "c",
"filename": "server_test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2648,
"license": "MIT",
"license_type": "permissive",
"path": "/testing/server_test.c",
"provenance": "stackv2-0065.json.gz:33020",
"repo_name": "hylonGG/p2psocket",
"revision_date": "2018-05-04T12:29:26",
"revision_id": "a21ac21e6a703a819b8a2aa2fbe2b8576d9b08fa",
"snapshot_id": "05cd092cbd3e491ec4ba05f6a6ec57060d5c5624",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hylonGG/p2psocket/a21ac21e6a703a819b8a2aa2fbe2b8576d9b08fa/testing/server_test.c",
"visit_date": "2021-09-13T21:29:23.605318"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(__WIN32__)
#include <winsock2.h>
#define close(fd) closesocket(fd)
#else
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#endif
#if defined(_WIN32) || defined(__WIN32__) || defined (WIN32)
#define c_sleep(x) Sleep(1*x)
#define _errno WSAGetLastError()
#else
#include <unistd.h>
#define c_sleep(x) usleep(1000*x)
#define _errno errno
#endif
int main(int argc, char **argv)
{
struct sockaddr_in saddr;
struct sockaddr_in caddr;
int caddr_len = sizeof(caddr);
int sfd = 0;
int cfd = 0;
int ret = 0;
int opt_val = 1;
if (argc != 2) {
printf("Usage: %s port\n", argv[0]);
return -1;
}
#if defined(__WIN32__)
WSADATA wsa_data = {0};
int res = WSAStartup(MAKEWORD(2,2), &wsa_data);
if (res != 0) {
printf("WSAStartup error\n");
return -1;
}
#endif
sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd < 0) {
printf("socket error:%d\n", _errno);
return -1;
}
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&opt_val, sizeof(opt_val));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(INADDR_ANY);
saddr.sin_port = htons(atoi(argv[1]));
ret = bind(sfd, (struct sockaddr *)&saddr, sizeof(saddr));
if (ret < 0) {
printf("bind error(err:%d)\n", _errno);
close(sfd);
return -1;
}
ret = listen(sfd, 5);
if (ret < 0) {
printf("listen error(err:%d)\n", _errno);
close(sfd);
return -1;
}
cfd = accept(sfd, (struct sockaddr *)&caddr, &caddr_len);
if (cfd < 0) {
printf("accept error(err:%d)\n", _errno);
close(sfd);
return -1;
}
while (1) {
static int times = 0;
char buf[32] = {0};
char msg[] = "server message";
printf("wating to read.\n");
ret = recv(cfd, buf, sizeof(buf), 0);
if (ret < 0) {
printf("recv error (err:%d)\n", _errno);
break;
}
printf("received a message [%d]:%s (len:%d)\n", times++, buf, ret);
ret = send(cfd, msg, strlen(msg), 0);
if (ret < 0) {
printf("send error (err:%d)\n", _errno);
break;
}
printf("sent (%d)bytes message.\n", ret);
c_sleep(1);
}
printf("exit.\n");
close(cfd);
close(sfd);
#if defined(__WIN32__)
WSACleanup();
#endif
return 0;
}
| 2.609375 | 3 |
2024-11-18T21:10:16.814515+00:00
| 2018-08-08T10:30:10 |
f27078dee24e03613d5a35a10b0d5e4825e917d4
|
{
"blob_id": "f27078dee24e03613d5a35a10b0d5e4825e917d4",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-08T10:30:10",
"content_id": "2de71255128dbe02a624c81dfa2a3c061d880338",
"detected_licenses": [
"Unlicense"
],
"directory_id": "f03b87756bdf310fa929a624849bcddd0d4cb0c0",
"extension": "c",
"filename": "all.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 143899314,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1750,
"license": "Unlicense",
"license_type": "permissive",
"path": "/all.c",
"provenance": "stackv2-0065.json.gz:33533",
"repo_name": "simplerjiang/My_Fucking_Learning_Code",
"revision_date": "2018-08-08T10:30:10",
"revision_id": "bf746475576c37d1748626695626ac5b43003617",
"snapshot_id": "40c327d966b1390f9251dfc84a28ca987601e86c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/simplerjiang/My_Fucking_Learning_Code/bf746475576c37d1748626695626ac5b43003617/all.c",
"visit_date": "2020-03-25T15:44:13.974567"
}
|
stackv2
|
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#define MAX 256
long total;
int countLines(const char *filename);
int isCode(const char *filename);
void findAllDirs(const char *path);
int countLines(const char *filename)
{
FILE *fp;
int count = 0;
int temp;
if ((fp = fopen(filename, "r")) == NULL)
{
fprintf(stderr, "Can not open the file: %s\n", filename);
return 0;
}
while ((temp = fgetc(fp)) != EOF)
{
if (temp == '\n')
{
count++;
}
}
fclose(fp);
return count;
}
int isCode(const char *filename)
{
int length;
length = strlen(filename);
if (!strcmp(filename + (length - 2), ".c"))
{
return 1;
}
else
{
return 0;
}
}
void findAllDirs(const char *path)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp = opendir(path)) == NULL)
{
fprintf(stderr, "The path %s is wrong!\n", path);
return;
}
chdir(path);
while ((entry = readdir(dp)) != NULL)
{
lstat(entry->d_name, &statbuf);
if (!strcmp(".", entry->d_name) || !strcmp("..", entry->d_name))
continue;
if (S_ISDIR(statbuf.st_mode))
{
findAllDirs(entry->d_name);
}
else
{
if (isCode(entry->d_name))
{
total += countLines(entry->d_name);
}
}
}
chdir("..");
closedir(dp);
}
int main()
{
char path[MAX] = ".";
printf("计算中...\n");
findAllDirs(path);
printf("目前你总共写了 %ld 行代码!\n\n", total);
return 0;
}
| 3.390625 | 3 |
2024-11-18T21:10:16.968744+00:00
| 2017-12-31T14:51:40 |
1267c593d6f209cf62ecda7ab3c19b71bccb8321
|
{
"blob_id": "1267c593d6f209cf62ecda7ab3c19b71bccb8321",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-31T14:51:40",
"content_id": "ab4fd5f43e0368f126962fe19491ea86b85b47d4",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "89e765cd4233cf627fffc1ee15738fa3ae7606b9",
"extension": "c",
"filename": "testDL.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 102879370,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5098,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/hw2/unit_tests/testDL.c",
"provenance": "stackv2-0065.json.gz:33790",
"repo_name": "rajkumarsubramaniam/AES",
"revision_date": "2017-12-31T14:51:40",
"revision_id": "8236a8aacb89dbd00333f80d5af1873af770a821",
"snapshot_id": "37d1eb3d12244cf6842d586305dafd08984b68c5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rajkumarsubramaniam/AES/8236a8aacb89dbd00333f80d5af1873af770a821/hw2/unit_tests/testDL.c",
"visit_date": "2021-03-12T19:27:49.542672"
}
|
stackv2
|
/**
* @file testDL.c
* @brief cmocka unit testing of the doubly linked list function
* @author Raj Kumar Subramaniam
* @date September 18,2017
**/
#include <math.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <stdint.h>
#include "doublyLinked.h"
void test_DL_Destroy(void **state)
{
DL_t * cPtr = (DL_t *)malloc(sizeof(DL_t)); /*Allocating and destroying to check the pointer*/
DL_Status status;
status = DL_Destroy(&cPtr);
assert_int_equal(status,DL_SUCCESS);
assert_null ((void*)cPtr);
}
void test_DL_AddNodes(void **state)
{
DL_t* n1 = NULL;
DL_Status status;
status = DL_AddNode(&n1, 3, 2); /*Index not in range*/
assert_int_equal(status,DL_INDEX_ERROR);
status = DL_AddNode(&n1, 3, 0); /*Index addition*/
assert_int_equal(status,DL_SUCCESS);
assert_int_equal(n1->data, 3); /*Checking the Data added*/
status = DL_Destroy(&n1);
assert_int_equal(status,DL_SUCCESS);
}
void test_DL_AddNodes_middle(void **state)
{
DL_t* n1 = NULL;
DL_Status status;
status = DL_AddNode(&n1, 3, 0); /*Index addition*/
status = DL_AddNode(&n1, 5, 1);
status = DL_AddNode(&n1, 7, 2);
status = DL_AddNode(&n1, 9, 3);
assert_int_equal(status,DL_SUCCESS);
status = DL_AddNode(&n1, 10, 2); /*add node in the middle*/
assert_int_equal(status,DL_SUCCESS);
for(int i=0;i<2;i++)
{
n1 = n1->next;
}
assert_int_equal(n1->data,10);
status = DL_Destroy(&n1);
assert_int_equal(status,DL_SUCCESS);
}
void test_DL_RemoveNodes(void **state)
{
DL_t* n1 = NULL;
DL_Status status;
uint32_t data;
status = DL_AddNode(&n1, 3, 0); /*Index addition*/
assert_int_equal(status,DL_SUCCESS);
status = DL_RemoveNode(&n1,&data,4);
assert_int_equal(n1->data, 3); /*Checking the Data added*/
assert_int_equal(status,DL_INDEX_ERROR); /*Wrong error*/
status = DL_RemoveNode(&n1,&data,0);
assert_int_equal(status,DL_SUCCESS);
assert_int_equal(data, 3); /*Checking the Data removed*/
}
void test_DL_RemoveNodes_empty(void **state)
{
DL_t* n1 = NULL;
DL_Status status;
uint32_t data;
status = DL_RemoveNode(&n1,&data,0); /*removing from Empty List*/
assert_int_equal(status,DL_INDEX_ERROR);
}
void test_DL_RemoveNodes_middle_end(void **state)
{
DL_t* n1 = NULL;
DL_Status status;
uint32_t data;
status = DL_AddNode(&n1, 3, 0); /*Index addition*/
status = DL_AddNode(&n1, 5, 1);
status = DL_AddNode(&n1, 7, 2);
status = DL_AddNode(&n1, 9, 3);
assert_int_equal(status,DL_SUCCESS);
status = DL_RemoveNode(&n1,&data,2); /*Removing from the middle*/
assert_int_equal(status,DL_SUCCESS);
assert_int_equal(data, 7); /*Checking the Data removed*/
status = DL_RemoveNode(&n1,&data,2); /*Removing from the end*/
assert_int_equal(status,DL_SUCCESS);
assert_int_equal(data, 9); /*Checking the Data removed*/
status = DL_Destroy(&n1);
assert_int_equal(status,DL_SUCCESS);
}
void test_DL_Search(void **state)
{
DL_t* n1 = NULL;
DL_Status status;
size_t index;
status = DL_AddNode(&n1, 3, 0); /*Index addition*/
status = DL_AddNode(&n1, 5, 1);
status = DL_AddNode(&n1, 7, 2);
status = DL_AddNode(&n1, 9, 3);
assert_int_equal(status,DL_SUCCESS);
/*Search first element*/
status = DL_Search(n1, 3, &index);
assert_int_equal(status,DL_SUCCESS);
assert_int_equal(index,0);
/*Search last element*/
status = DL_Search(n1, 9, &index);
assert_int_equal(status,DL_SUCCESS);
assert_int_equal(index,3);
/*Search middle element*/
status = DL_Search(n1, 7, &index);
assert_int_equal(status,DL_SUCCESS);
assert_int_equal(index,2);
/*Destroy*/
status = DL_Destroy(&n1);
assert_int_equal(status,DL_SUCCESS);
}
void test_DL_Size(void **state)
{
DL_t* n1 = NULL;
DL_Status status;
size_t size;
status = DL_Size(n1, &size); /*Size when 0*/
assert_int_equal(status,DL_SUCCESS);
assert_int_equal(size,0);
status = DL_AddNode(&n1, 3, 0); /*Element addition*/
status = DL_AddNode(&n1, 5, 1);
status = DL_AddNode(&n1, 7, 2);
status = DL_AddNode(&n1, 9, 3);
assert_int_equal(status,DL_SUCCESS);
status = DL_Size(n1, &size); /*Size when 4*/
assert_int_equal(status,DL_SUCCESS);
assert_int_equal(size,4);
status = DL_Destroy(&n1);
assert_int_equal(status,DL_SUCCESS);
}
int main(int argc, char **argv) /*this is main()*/
{
const struct CMUnitTest tests[] = {
/*doublyLinked.c Tests*/
cmocka_unit_test(test_DL_Destroy),
cmocka_unit_test(test_DL_AddNodes),
cmocka_unit_test(test_DL_AddNodes_middle),
cmocka_unit_test(test_DL_RemoveNodes),
cmocka_unit_test(test_DL_RemoveNodes_empty),
cmocka_unit_test(test_DL_RemoveNodes_middle_end),
cmocka_unit_test(test_DL_Search),
cmocka_unit_test(test_DL_Size),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
| 3.140625 | 3 |
2024-11-18T21:10:17.030304+00:00
| 2021-02-18T09:21:59 |
cbcee7ee1084dafb40ec7f700ade8fe2652bf5ce
|
{
"blob_id": "cbcee7ee1084dafb40ec7f700ade8fe2652bf5ce",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-18T09:21:59",
"content_id": "c8cb4100a56a96e9bfefc4c7803412c6a6677387",
"detected_licenses": [
"MIT"
],
"directory_id": "aa3dbc259abc49fb85ecc3e956a83d296bc690c9",
"extension": "h",
"filename": "mem.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 27408751,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3605,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lockfree/src/mem.h",
"provenance": "stackv2-0065.json.gz:33918",
"repo_name": "jinnaiyuu/Parallel-Best-First-Searches",
"revision_date": "2021-02-18T09:21:59",
"revision_id": "d197723e7499a91e2c15042de243ccab2cb0f9d5",
"snapshot_id": "f2e9eb4cdf6cd5719ca580b82d61284af87999a8",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/jinnaiyuu/Parallel-Best-First-Searches/d197723e7499a91e2c15042de243ccab2cb0f9d5/src/lockfree/src/mem.h",
"visit_date": "2023-03-04T05:26:33.628542"
}
|
stackv2
|
/* © 2014 the PBNF Authors under the MIT license. See AUTHORS for the list of authors.*/
/**
* \file mem.h
*
* Implementation for lock-free memory management from ``Correction of
* a Memory Management Method for Lock-Free Data Structures'' -- By
* M. Michael and M. Scott. (refer to Figure 6)
*
* \author eaburns
* \date 2009-03-17
*/
#if !defined(_MEM_H_)
#define _MEM_H_
#include <stdint.h>
/**
* Test if a pointer is marked
*/
#define IS_MARKED(p) (((intptr_t) (p)) & 0x1)
/**
* Get the marked version of a pointer
*/
#define GET_MARKED(p) ((void*) (((intptr_t) (p)) | 0x1))
/**
* Get the marked version of a pointer
*/
#define GET_UNMARKED(p) ((void*) (((intptr_t) (p)) & (~0x1)))
/**
* A reference which has been deleted
*/
#define DELETED_REFERENCE (GET_MARKED(NULL))
struct node {
intptr_t refct_claim;
/* Links that can be used when nodes must have pointers to
* other nodes in data structure implementations. */
struct node **links;
};
struct freelist {
struct node *head;
/* Number of links per element. */
size_t nlinks;
/* Number of nodes which are currently free. */
size_t nfreed;
/* Number of allocated nodes. */
size_t nalloced;
};
/**
* Create a new free list of nodes. Nodes can be over-allocated using
* the elmsize parameter. This allows the user to have extra data in
* each node using casting tricks:
*
* \param nbrelm The number of elements in the list.
*
* \param nlinks The number of links in each node (allocated
* seperately from the node structure itself).
*
* \param elmsize The size of each element (should be at least
* sizeof(struct node).
*
* \return A freelist pointer on success or NULL on error and errno is
* set:
* - ENOMEM: Unable to allocate memory for the free list.
* - EINVAL: The elmsize parameter is too small.
* - EINVAL: The nbrelm parameter is zero.
*/
struct freelist *mem_freelist_create(size_t nbrelm,
size_t nlinks,
size_t elmsize);
/**
* Destroy the free list, deallocating all of the memory for the nodes
* which are currently on it.
*
* \return The number of elements that were freed.
*/
size_t mem_freelist_destroy(struct freelist *fl);
/**
* Allocate a new element off of the free list.
*
* \return A new node on success or NULL on error and errno is set.
* - ENOMEM: No nodes left on the free list.
*/
void *mem_new(struct freelist *fl);
/**
* Increment the reference counter of a node and get a pointer to it.
*
* \param p Must be a (struct node **) cast into a (void *).
*/
void *mem_safe_read(struct freelist *fl, void *p);
/**
* Same as mem_safe_read, but returns NULL if the node that is read is
* marked.
*/
void *mem_safe_read_null_on_mark(struct freelist *fl, void *p);
/**
* Increment the reference counter of a node. You should only call
* this if you already have a pointer to the node that you know won't
* change.
*
* This function can be safely called on a marked reference.
*
* \param p Must be a (struct node *) cast into a (void *).
*/
void mem_incr_ref(void *p);
/**
* Release a node (decrementing the ref-counter and possibly
* reclaiming it). If the node is reclaimed the links[] array is
* released recursively starting from links[0] until a NULL link is
* found. If a link is marked as a DELETED_REFERENCE it is not
* considered NULL.
*
* This function can be safely called on a marked reference.
*
* \param p Must be a (struct node *) cast into a (void *).
*/
void mem_release(struct freelist *fl, void *p);
#endif /* !_MEM_H_ */
| 2.9375 | 3 |
2024-11-18T21:10:17.180177+00:00
| 2020-02-28T09:55:48 |
fa8312a40ff1c75782d371ca6f507ac841dcdb47
|
{
"blob_id": "fa8312a40ff1c75782d371ca6f507ac841dcdb47",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-28T09:55:48",
"content_id": "ef39587a4fbf74354425fdb21f912cf012a56947",
"detected_licenses": [
"MIT"
],
"directory_id": "d9542fec9f0f0c74ca58cdd7a130ac4f59e5ae74",
"extension": "c",
"filename": "loop.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 127914560,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2202,
"license": "MIT",
"license_type": "permissive",
"path": "/loop.c",
"provenance": "stackv2-0065.json.gz:34175",
"repo_name": "dave96/libminiomp",
"revision_date": "2020-02-28T09:55:48",
"revision_id": "332541f6a5cf8cafa435f6e2b8b4118c5ce3eb38",
"snapshot_id": "650f5d8df663a838acf8f508466e3d85145cdd33",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dave96/libminiomp/332541f6a5cf8cafa435f6e2b8b4118c5ce3eb38/loop.c",
"visit_date": "2022-04-10T23:28:22.462549"
}
|
stackv2
|
#include "libminiomp.h"
// Declaratiuon of global variable for loop work descriptor
miniomp_loop_t miniomp_loop;
/* The *_next routines are called when the thread completes processing of
the iteration block currently assigned to it. If the work-share
construct is bound directly to a parallel construct, then the iteration
bounds may have been set up before the parallel. In which case, this
may be the first iteration for the thread.
Returns true if there is work remaining to be performed; *ISTART and
*IEND are filled with a new iteration block. Returns false if all work
has been assigned. */
bool
GOMP_loop_dynamic_next (long *istart, long *iend) {
printf("TBI: Asking for more iterations? I gave you all at the beginning, no more left ...\n");
return(false);
}
/* The *_start routines are called when first encountering a loop construct
that is not bound directly to a parallel construct. The first thread
that arrives will create the work-share construct; subsequent threads
will see the construct exists and allocate work from it.
START, END, INCR are the bounds of the loop; CHUNK_SIZE is the
scheduling parameter.
Returns true if there's any work for this thread to perform. If so,
*ISTART and *IEND are filled with the bounds of the iteration block
allocated to this thread. Returns false if all work was assigned to
other threads prior to this thread's arrival. */
bool
GOMP_loop_dynamic_start (long start, long end, long incr, long chunk_size,
long *istart, long *iend)
{
printf("TBI: What a mess! Starting a non-static for worksharing construct and dont know what to do, I'll take it all\n");
*istart = start;
*iend = end;
return(true);
}
/* The GOMP_loop_end* routines are called after the thread is told that
all loop iterations are complete. The first version synchronize
all threads; the nowait version does not. */
void
GOMP_loop_end (void) {
printf("TBI: Finishing a for worksharing construct with non static schedule\n");
}
void
GOMP_loop_end_nowait (void) {
printf("TBI: Finishing a for worksharing construct with non static schedule, with nowait clause\n");
}
| 2.6875 | 3 |
2024-11-18T21:10:17.475937+00:00
| 2021-02-02T19:51:04 |
11aceb43b39a928269623c6466b10a1d3f5ff96d
|
{
"blob_id": "11aceb43b39a928269623c6466b10a1d3f5ff96d",
"branch_name": "refs/heads/develop",
"committer_date": "2021-02-02T19:51:04",
"content_id": "b4f3906ac9c692118d1bc4eaa15337a52c0f5aef",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d56bab7245193c2260b3f292fb77f9c82141f0a2",
"extension": "c",
"filename": "bufr_check_descriptors.c",
"fork_events_count": 0,
"gha_created_at": "2020-07-07T19:35:47",
"gha_event_created_at": "2021-02-02T19:51:06",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 277906014,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1873,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tests/bufr_check_descriptors.c",
"provenance": "stackv2-0065.json.gz:34432",
"repo_name": "bbakernoaa/eccodes",
"revision_date": "2021-02-02T19:51:04",
"revision_id": "61eb6daac46f6f2b9959b506df5565fb9e763c40",
"snapshot_id": "bbb127eed4fde4837e96aeb4657aadf2777b9fd4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bbakernoaa/eccodes/61eb6daac46f6f2b9959b506df5565fb9e763c40/tests/bufr_check_descriptors.c",
"visit_date": "2023-02-26T16:22:10.955863"
}
|
stackv2
|
/*
* (C) Copyright 2005- ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*
* In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
* virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
*/
#include <assert.h>
#include "grib_api_internal.h"
int main(int argc, char** argv)
{
char* filename = NULL;
FILE* fp = NULL;
char line[1024] = {0,};
char** list = NULL;
size_t i = 0, line_number = 0;
char* str_key = NULL;
char* str_units = NULL;
bufr_descriptor v;
const size_t maxlen_keyName = sizeof(v.shortName);
const size_t maxlen_units = sizeof(v.units);
Assert(argc == 2);
filename = argv[1];
fp = fopen(filename, "r");
Assert(fp);
while (fgets(line, sizeof(line) - 1, fp)) {
++line_number;
Assert(strlen(line) > 0);
if (line[0] == '#') continue; /* Ignore first line with column titles */
list = string_split(line, "|");
Assert(list);
str_key = list[1];
str_units = list[4];
if (strlen(str_key) >= maxlen_keyName) {
fprintf(stderr, "Error on line %lu: bufr_descriptor key name '%s' exceeds %lu characters.\n",
line_number, str_key, maxlen_keyName);
return 1;
}
if (strlen(str_units) >= maxlen_units) {
fprintf(stderr, "Error on line %lu: bufr_descriptor units '%s' exceeds %lu characters.\n",
line_number, str_units, maxlen_units);
return 1;
}
for (i = 0; list[i] != NULL; ++i) free(list[i]);
free(list);
}
fclose(fp);
grib_context_delete(grib_context_get_default());
return 0;
}
| 2.09375 | 2 |
2024-11-18T21:10:17.727167+00:00
| 2020-03-25T07:08:49 |
367516e8e6d43205386039741aa1b3ff0533ce1d
|
{
"blob_id": "367516e8e6d43205386039741aa1b3ff0533ce1d",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-25T07:08:49",
"content_id": "6a2b95a28c87c2cead42d63b5feb252e67dfbd03",
"detected_licenses": [
"MIT"
],
"directory_id": "c807ca12ac4c849e22e27b39c3995df02df76417",
"extension": "c",
"filename": "rw5.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 237142060,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1859,
"license": "MIT",
"license_type": "permissive",
"path": "/chapter12/readers-writers/rw5.c",
"provenance": "stackv2-0065.json.gz:34691",
"repo_name": "BugenZhao/CSAPP3e",
"revision_date": "2020-03-25T07:08:49",
"revision_id": "d031fa7046ad3b8f6ecb6780c9aa2fd2264b637a",
"snapshot_id": "e92a865874582ae00cce61276e5ed2ef95e0cace",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/BugenZhao/CSAPP3e/d031fa7046ad3b8f6ecb6780c9aa2fd2264b637a/chapter12/readers-writers/rw5.c",
"visit_date": "2022-04-10T21:23:48.856758"
}
|
stackv2
|
//
// Created by Bugen Zhao on 2020/3/6.
//
#include "rw.h"
const char desc[80] = "RW2 - Priority to writers - Better";
int writecnt;
int readcnt;
sem_t *wcmutex, *rcmutex, *w, *r;
int writetimes;
int readtimes;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-noreturn"
void reader() {
int i = 10000;
while (i--) {
P(r);
P(rcmutex);
readcnt++;
if (readcnt == 1) P(w);
V(rcmutex);
readtimes++;
V(r);
// Reading...
P(rcmutex);
readcnt--;
if (readcnt == 0) V(w);
V(rcmutex);
}
}
void writer() {
while (1) {
P(wcmutex);
writecnt++;
if (writecnt == 1) P(r); // do not read anymore
V(wcmutex);
P(w); // all readers are finished
// Writing...
writetimes++;
if (writetimes % 100 == 0) {
printf("read/write: %d/%d\n", readtimes, writetimes);
if (writetimes >= 1000)
exit(0);
}
writecnt--;
V(w);
P(wcmutex);
writecnt--;
if (writecnt == 0) V(r);
V(wcmutex);
}
}
void init() {
#ifndef BUGENCSAPP3E_BZCSAPP_H
// mode 0600 is critical!!
mutex = sem_open("/bz_mutex_", O_CREAT | O_EXCL, 0600, 1);
w = sem_open("/bz_w_", O_CREAT | O_EXCL, 0600, 1);
// IMMEDIATELY unlink the semaphores to make sure they will be closed (sem_close) correctly
// after program exits.
sem_unlink("/bz_mutex_");
sem_unlink("/bz_w_");
#else
rcmutex = Sem_open_and_unlink("/bz_rc_mutex_", 1);
wcmutex = Sem_open_and_unlink("bz_wc_mutex_", 1);
r = Sem_open_and_unlink("/bz_r_", 1);
w = Sem_open_and_unlink("/bz_w_", 1);
#endif
readtimes = 0;
writetimes = 0;
readcnt = 0;
writecnt = 0;
}
#pragma clang diagnostic pop
| 2.5 | 2 |
2024-11-18T21:10:17.797059+00:00
| 2021-08-12T06:17:00 |
9d21ea88aef548fd5a1febf5cf6678827414b194
|
{
"blob_id": "9d21ea88aef548fd5a1febf5cf6678827414b194",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-12T06:17:00",
"content_id": "83e90ad7b2c4b100201a0784f0abb777d8263818",
"detected_licenses": [
"MIT"
],
"directory_id": "e5c0ec5c1ea24042682a428f45820bd0b777ebb5",
"extension": "c",
"filename": "test_preferences.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 292488028,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1560,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/test_preferences.c",
"provenance": "stackv2-0065.json.gz:34820",
"repo_name": "orbitrc/liblaniakea",
"revision_date": "2021-08-12T06:17:00",
"revision_id": "43552218abcbb9b6190a1ccd5a8c25ef8a73d2c8",
"snapshot_id": "01b66d67cd635c524da5c1566b2f0a44b469707a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/orbitrc/liblaniakea/43552218abcbb9b6190a1ccd5a8c25ef8a73d2c8/tests/test_preferences.c",
"visit_date": "2023-07-05T16:40:14.231863"
}
|
stackv2
|
#include <stdio.h>
#include <laniakea/preferences.h>
int main()
{
la_preferences *preferences;
preferences = la_preferences_new();
int err = la_preferences_load(preferences);
if (err != LA_FILE_ERROR_SUCCESS) {
fprintf(stderr, "Error: %d\n", err);
}
bool dark_mode = la_preferences_appearance_dark_mode(preferences);
fprintf(stderr, "dark_mode: %d\n", dark_mode);
const char *wallpaper = la_preferences_desktop_wallpaper(preferences);
fprintf(stderr, "wallpaper: %s\n", wallpaper);
const char *caps_lock_behavior =
la_preferences_keyboard_caps_lock_behavior(preferences);
fprintf(stderr, "caps_lock_behavior: %s\n", caps_lock_behavior);
// Reload test.
printf("Test reload\n");
printf("=================\n");
fprintf(stderr, "1st free\n");
la_preferences_free(preferences);
fprintf(stderr, "1st new\n");
preferences = la_preferences_new();
fprintf(stderr, "1st load\n");
err = la_preferences_load(preferences);
fprintf(stderr, "1st err: %d\n", err);
fprintf(stderr, "2nd free\n");
la_preferences_free(preferences);
fprintf(stderr, "2nd new\n");
preferences = la_preferences_new();
fprintf(stderr, "2nd load\n");
err = la_preferences_load(preferences);
fprintf(stderr, "2nd err: %d\n", err);
fprintf(stderr, "2nd reloaded.\n");
fprintf(stderr, "freeing...\n");
fprintf(stderr, "preferences->conf: %p\n", preferences->conf);
la_preferences_free(preferences);
fprintf(stderr, "done.\n");
return 0;
}
| 2.34375 | 2 |
2024-11-18T21:10:18.127962+00:00
| 2019-03-03T03:36:28 |
cb68218edf80f5e00a7f2345791a92b759ef47cd
|
{
"blob_id": "cb68218edf80f5e00a7f2345791a92b759ef47cd",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-03T03:36:28",
"content_id": "882712736e232172b8770bb49c5b61f7d0c434ae",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fb6ec083e662adbbd1e72253b6ee2e93efbd8334",
"extension": "c",
"filename": "bsearch_variant.c",
"fork_events_count": 1,
"gha_created_at": "2019-01-30T06:16:17",
"gha_event_created_at": "2019-05-21T02:01:00",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 168289857,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5308,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/c-cpp/16_bsearch/bsearch_variant.c",
"provenance": "stackv2-0065.json.gz:35078",
"repo_name": "FLyingLSJ/algo",
"revision_date": "2019-03-03T03:36:28",
"revision_id": "26146a4ac7416b1591069bb9f21b1c8ae7cef81d",
"snapshot_id": "6e28aeb738099f665a71006ecfb4fa9fbd11da29",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/FLyingLSJ/algo/26146a4ac7416b1591069bb9f21b1c8ae7cef81d/c-cpp/16_bsearch/bsearch_variant.c",
"visit_date": "2021-06-26T15:35:31.796726"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int binary_search(int *arr, int size, int val)
{
int low = 0, high = size - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == val)
return mid;
if (arr[mid] < val)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
/*
* find the first index with *val*
*
* This is a little tricky because the calculation of mid is integer based, it
* will be cast to the lower bound of an integer.
*
* In case the [low, high] range is of size 1 or 2 and arr[mid] >= val, we will
* have:
*
* mid = (low + high) / 2 = low
* high = mid - 1 = low - 1 < low, which break the loop
*
*/
int binary_search_first(int *arr, int size, int val)
{
int low = 0, high = size - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
//printf("[%d-%d] %d\n", low, high, mid);
if (arr[mid] >= val)
high = mid - 1;
else
low = mid + 1;
}
//printf("[%d-%d] %d\n", low, high, mid);
if (arr[low] == val)
return low;
else
return -1;
}
int binary_search_last(int *arr, int size, int val)
{
int low = 0, high = size - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] <= val)
low = mid + 1;
else
high = mid - 1;
}
if (arr[high] == val)
return high;
else
return -1;
}
int binary_search_first_r(int *arr, int size, int val)
{
int mid = size / 2;
int idx;
if (size <= 0)
return -1;
// we find *val* at mid, try first half
if (arr[mid] == val) {
idx = binary_search_first_r(arr, mid, val);
return idx != -1 ? idx : mid;
}
// mid == 0 means size == 1
// so the only element in array doesn't equal to val
if (!mid)
return -1;
if (arr[mid] < val) {
idx = binary_search_first_r(arr + mid + 1, size - mid - 1, val);
if (idx != -1)
idx += mid + 1;
} else {
idx = binary_search_first_r(arr, mid, val);
}
return idx;
}
int binary_search_last_r(int *arr, int size, int val)
{
int mid = size / 2;
int idx;
if (size <= 0)
return -1;
// we find *val* at mid, try last half
if (arr[mid] == val) {
idx = binary_search_last_r(arr+mid+1, size-mid-1, val);
if (idx != -1)
mid += idx + 1;
return mid;
}
// mid == 0 means size == 1
// so the only element in array doesn't equal to val
if (!mid)
return -1;
if (arr[mid] < val) {
idx = binary_search_last_r(arr + mid + 1, size - mid - 1, val);
if (idx != -1)
idx += mid + 1;
} else {
idx = binary_search_last_r(arr, mid, val);
}
return idx;
}
int binary_search_first_bigger(int *arr, int size, int val)
{
int low = 0, high = size - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] >= val) {
if (mid == 0 || arr[mid-1] < val)
return mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
int binary_search_first_bigger_r(int *arr, int size, int val)
{
int mid = size / 2;
int idx;
if (size <= 0)
return -1;
if (arr[mid] >= val) {
// find one bigger than val, try first half
idx = binary_search_first_bigger_r(arr, mid, val);
if (idx == -1)
idx = mid;
} else {
// the bigger one may sit in second half
idx = binary_search_first_bigger_r(arr + mid + 1, size - mid - 1, val);
if (idx != -1)
idx += mid + 1;
}
return idx;
}
int binary_search_last_smaller(int *arr, int size, int val)
{
int low = 0, high = size - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] <= val) {
if (mid == 0 || arr[mid+1] > val)
return mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
int binary_search_last_smaller_r(int *arr, int size, int val)
{
int mid = size / 2;
int idx;
if (size <= 0)
return -1;
if (arr[mid] <= val) {
// find one smaller than val, try second half
idx = binary_search_last_smaller_r(arr + mid + 1, size - mid - 1, val);
if (idx != -1)
idx += mid + 1;
else
idx = mid;
} else {
// the smaller one may sit in first half
idx = binary_search_last_smaller_r(arr, mid, val);
}
return idx;
}
int main()
{
int arr[10] = {1, 4, 5, 9, 12, 14, 19, 19, 31, 36};
int idx;
printf("Test Array:\n");
for (idx = 0; idx < 10; idx++)
printf("%8d", arr[idx]);
printf("\n");
idx = binary_search_first(arr, 10, 19);
if (idx != -1)
printf("first 19 at %d\n", idx);
else
printf("19 not in arr \n");
idx = binary_search_first_r(arr, 10, 19);
if (idx != -1)
printf("first 19 at %d\n", idx);
else
printf("19 not in arr \n");
idx = binary_search_last(arr, 10, 19);
if (idx != -1)
printf("last 19 at %d\n", idx);
else
printf("19 not in arr \n");
idx = binary_search_last_r(arr, 10, 19);
if (idx != -1)
printf("last 19 at %d\n", idx);
else
printf("19 not in arr \n");
idx = binary_search_first_bigger(arr, 10, 12);
if (idx != -1)
printf("first bigger 12 at %d\n", idx);
else
printf("12 not in arr \n");
idx = binary_search_first_bigger_r(arr, 10, 12);
if (idx != -1)
printf("first bigger 12 at %d\n", idx);
else
printf("12 not in arr \n");
idx = binary_search_last_smaller(arr, 10, 12);
if (idx != -1)
printf("last smaller 12 at %d\n", idx);
else
printf("12 not in arr \n");
idx = binary_search_last_smaller_r(arr, 10, 12);
if (idx != -1)
printf("last smaller 12 at %d\n", idx);
else
printf("12 not in arr \n");
return 0;
}
| 3.875 | 4 |
2024-11-18T21:10:19.141238+00:00
| 2019-01-08T00:58:48 |
4b274e72e80e058628c932819110322a0ae0cf1f
|
{
"blob_id": "4b274e72e80e058628c932819110322a0ae0cf1f",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-08T00:58:48",
"content_id": "0f88e1d73f4f1b420b152a4958e32282a5ad9d77",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0ffac202cba7c7d7eccf2b58fd93947021d2b452",
"extension": "c",
"filename": "dac121c085.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 164523702,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2201,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/dac121c085.c",
"provenance": "stackv2-0065.json.gz:35850",
"repo_name": "xaviergh/dac121c085",
"revision_date": "2019-01-08T00:58:48",
"revision_id": "a64fa4a3220b5e45f470a713d2eb0a5db62e831d",
"snapshot_id": "1e80c967907b0fd24ac0d1756c20f76f90c34496",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/xaviergh/dac121c085/a64fa4a3220b5e45f470a713d2eb0a5db62e831d/dac121c085.c",
"visit_date": "2020-04-15T08:36:39.289371"
}
|
stackv2
|
/*!
* @file dac121c085.c
*
* @brief Library for the TI DAC121C085 with I2C interface.
*
* @author Xavier Garcia Herrera.
*
* @par
* Version 1.0 2014
*/
#include "dac121c085.h"
#ifdef __XC8
#define delay_ms __delay_ms
#else
#use i2c(master,I2C1,slow) //to use with CSS PIC only
#endif
/*!
*\fn void dac121c085_i2c_init (void)
* @brief Init microcontroller I2C.
* @return nothing.
*/
void
dac121c085_i2c_init (void)
{
//Standard Mode: 100kHz
//Fast Mode: 400kHz
i2c_init(100000);
}
/*!
*\fn void dac121c085_init (void)
* @brief Init dac121c085 with 0V and normal mode.
* @return nothing.
*/
void
dac121c085_init (void)
{
i2c_start();
i2c_write(SLAVE_ADDR | SLAVE_WRITE);
i2c_write(0x00);
i2c_write(0x00);
i2c_stop();
}
/*!
*\fn void dac121c085_read (void)
* @brief Read dac121c085 current value.
* @return 12bit DAC value.
*/
uint16_t
dac121c085_read (void)
{
uint8_t msb, lsb;
uint16_t dac_value;
i2c_start();
i2c_write(SLAVE_ADDR | SLAVE_READ);
msb = i2c_read(); //ACK
lsb = i2c_read(0); //NACK
i2c_stop();
dac_value = make16(msb,lsb);
dac_value = dac_value && 0x0FFF; //take only the 12bit part
return dac_value;
}
/*!
*\fn void dac121c085_write (uint16_t dac_value)
* @brief write the desired 12bit value to the DAC in normal mode.
* @param[in] dac_value 12bit DAC value.
* @return nothing.
*/
void
dac121c085_write (uint16_t dac_value)
{
dac_value = dac_value && 0x0FFF; //clean the 12bit part and set normal mode 0b00
i2c_start();
i2c_write(SLAVE_ADDR | SLAVE_WRITE);
i2c_write((dac_value >> 8)); //msb
i2c_write(dac_value); //lsb
i2c_stop();
}
/*!
*\fn void dac121c085_burst_write (uint16_t dac_value)
* @brief Write continuous 12bit value to the DAC in normal mode.
* @param[in] dac_value pointer to the 12bit values to write.
* @param[in] len length of the array to the dac_value.
* @return nothing.
*/
void
dac121c085_burst_write (uint16_t *dac_value, uint8_t len)
{
i2c_start();
i2c_write(SLAVE_ADDR | SLAVE_WRITE);
while (len--)
{
i2c_write((*dac_value >> 8)); //msb
i2c_write(*dac_value); //lsb
dac_value++;
}
i2c_stop();
}
| 2.765625 | 3 |
2024-11-18T21:10:19.208591+00:00
| 2021-07-07T22:28:15 |
4389c907bfcb1a280dcce677d06466bd9b370b7a
|
{
"blob_id": "4389c907bfcb1a280dcce677d06466bd9b370b7a",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-07T22:28:15",
"content_id": "2da4b768073ce74fb208c4721e228ac88031536e",
"detected_licenses": [
"MIT"
],
"directory_id": "06e5e6d3ee73c9a32b70074c23fecac7150ebc25",
"extension": "c",
"filename": "aluno.c",
"fork_events_count": 0,
"gha_created_at": "2021-02-24T23:19:38",
"gha_event_created_at": "2021-07-07T22:28:16",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 342062848,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12641,
"license": "MIT",
"license_type": "permissive",
"path": "/atividades/Escola/v01/aluno.c",
"provenance": "stackv2-0065.json.gz:35978",
"repo_name": "studTon/inf029-evertondasilva",
"revision_date": "2021-07-07T22:28:15",
"revision_id": "901b90fb9c52b9659a05bd399aa219cf3869b333",
"snapshot_id": "af14db65ebd76622074134fa330037c50b6798d4",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/studTon/inf029-evertondasilva/901b90fb9c52b9659a05bd399aa219cf3869b333/atividades/Escola/v01/aluno.c",
"visit_date": "2023-06-11T23:52:41.177309"
}
|
stackv2
|
#include <stdio.h>
#include "aluNo.h"
/*Variáveis para auxiliar a contagem dos aluNos*/
int chaveDeValidar;
int cadastrosComSucesso = 0;
/*Registro*/
cadastroAluNo aluNo[QTD_DE_ALUNoS];
/*menu AluNo*/
void menuAluNo()
{
char escolha = '1';
while(escolha != '0')
{
printf("******************************\n");
printf("* INFO ALUNo *\n");
printf("******************************\n");
printf("\nEscolha uma opcao a seguir:\n0 - Voltar\n1 - Inserir aluNo\n2 - Listar aluNos\n::");
scanf("%1c%*c", &escolha);
while(getchar() != '\n');/*Pular o char new line No input*/
switch(escolha)
{
case '0':
{
printf("Voltar...\n");
}break;
case '1':
{
inserirAluNo();
}break;
case '2':
{
listarAluNos();
}break;
default:
{
printf("INPUT INVALIDO\n");
}break;
}
}
}
/*Geração de matrícula*/
void gerarMatricula(int inputIndiceAluNo)
{
if(inputIndiceAluNo < QTD_DE_ALUNoS)
{
/*É necessário somar o char '0' a todos os valores inteiros na
*conversão de inteiro para char, pois o valor inteiro do char
*'0' somado ao número inteiro equivale ao seu char correspon-
*dente.
*/
//Decomposição do índice do aluNo
char centenaAluNo = (inputIndiceAluNo / 100) + '0';
char dezenaAluNo = ((inputIndiceAluNo % 100) / 10) + '0';
char unidadeAluNo = (inputIndiceAluNo % 10) + '0';
//ANo e semestre
char aNo[CARACTER_ANo] = "2021\0";
char semestre = '1';
//Criação da string que representa a matrícula
int contador = 0;
while(contador < 11)
{
if(contador >= 0 && contador <= 3)
{
aluNo[inputIndiceAluNo].matricula[contador] = aNo[contador];
}
if(contador == 4||contador == 6)
{
aluNo[inputIndiceAluNo].matricula[contador] = '.';
}
if(contador == 5)
{
aluNo[inputIndiceAluNo].matricula[contador] = semestre;
}
if(contador == 7)
{
aluNo[inputIndiceAluNo].matricula[contador] = centenaAluNo;
}
if(contador == 8)
{
aluNo[inputIndiceAluNo].matricula[contador] = dezenaAluNo;
}
if(contador == 9)
{
aluNo[inputIndiceAluNo].matricula[contador] = unidadeAluNo;
}
contador++;
}
if(contador == 10)
aluNo[inputIndiceAluNo].matricula[contador] = '\0';
printf("MATRICULA GERADA: %s\n", aluNo[inputIndiceAluNo].matricula);
}
else
{
printf("SEM VAGAS PARA CADASTRO DE MAIS ALUNoS\n");
}
}
/*Verificações da entrada de dados do cadastro*/
void validarNome(char inputNome[])
{
int tamanhoInputNome = 0;
while(inputNome[tamanhoInputNome] != '\0') tamanhoInputNome++;
int tamanhoNomeReal = 0;
int contador = 0;
while(inputNome[contador] != '\0')
{
if(
(inputNome[contador] >= 'a' && inputNome[contador] <= 'z')||
(inputNome[contador] >= 'A' && inputNome[contador] <= 'Z')||
(inputNome[contador] == ' '))
tamanhoNomeReal++;
contador++;
}
if(tamanhoInputNome == tamanhoNomeReal)
{
printf("NoME VALIDO\n");
chaveDeValidar++;
}
else
printf("ERRO: Nome invalido\n");
}
void validarCPF(char cpf[])
{
/*Análise dos campo CPF*/
int tamDoInput = 0;
int contadorCaracterPonto = 0;
int contadorCaracterHifen = 0;
int contadorNumeros = 0;
while(cpf[tamDoInput] != '\0')
{
if(cpf[tamDoInput] >= '0' && cpf[tamDoInput] <= '9' &&
(tamDoInput != 3 && tamDoInput != 7 && tamDoInput != 11))
{
contadorNumeros++;
}
if(cpf[tamDoInput] == '.' && (tamDoInput == 3 || tamDoInput == 7))
{
contadorCaracterPonto++;
}
if(cpf[tamDoInput] == '-' && tamDoInput == 11)
{
contadorCaracterHifen++;
}
tamDoInput++;
}
int somaContadores = contadorCaracterHifen + contadorCaracterPonto + contadorNumeros;
/*Conclusão*/
if(somaContadores == 14)
{
printf("CPF VALIDO\n");
chaveDeValidar++;
}
else
{
printf("ERRO: CPF invalido\n");
//contaErros++;
}
}
void validarSexo(char sexo)
{
if(sexo == 'M'||sexo == 'F'||sexo == 'O')
{
printf("SEXO VALIDO\n");
chaveDeValidar++;
}
else
{
printf("ERRO: Sexo invalido\n");
}
}
void validarNasc(char data[])
{
int errosData = 0;
/*Decomposição da data*/
int tamDoInput = 0;
int contaCaracterBarra = 0;
int contaDiaNumero = 0;
int contaMesNumero = 0;
int contaANoNumero = 0;
while(data[tamDoInput] != '\0')
{
if(tamDoInput != 2 && tamDoInput != 5)
{
if(tamDoInput < 2)
{
if(data[tamDoInput] >= '0' && data[tamDoInput] <= '9')
contaDiaNumero++;
}
if(tamDoInput > 2 && tamDoInput < 5)
{
if(data[tamDoInput] >= '0' && data[tamDoInput] <= '9')
contaMesNumero++;
}
if(tamDoInput > 5 && tamDoInput < 10)
{
if(data[tamDoInput] >= '0' && data[tamDoInput] <= '9')
contaANoNumero++;
}
}
if ((tamDoInput == 2 || tamDoInput == 5 )&& data[tamDoInput] == '/')
{
contaCaracterBarra++;
}
tamDoInput++;
}
if(contaDiaNumero != 2||contaMesNumero != 2||contaANoNumero != 4||contaCaracterBarra != 2)
errosData++;
else
{
/*Aquisição das partes da data*/
char diaChar[CARACTER_DIA];
char mesChar[CARACTER_MES];
char aNoChar[CARACTER_ANo];
//dia
int iContador = 0;
int jContador = 0;
while (jContador < CARACTER_DIA - 1)
{
diaChar[jContador] = data[iContador];
iContador++;
jContador++;
}
diaChar[jContador] = '\0';
//mês
jContador = 0;
iContador++;
while (jContador < CARACTER_MES - 1)
{
mesChar[jContador] = data[iContador];
iContador++;
jContador++;
}
mesChar[jContador] = '\0';
//aNo
jContador = 0;
iContador++;
while (jContador < CARACTER_ANo - 1)
{
aNoChar[jContador] = data[iContador];
iContador++;
jContador++;
}
aNoChar[jContador] = '\0';
/*Conversão para inteiros*/
//Conversão da string dia
int indiceDoAlgarismo = 0;
int diaData = 0;
while (indiceDoAlgarismo < CARACTER_DIA - 1)
{
switch(indiceDoAlgarismo)
{
case 0:{
diaData += (diaChar[indiceDoAlgarismo] - '0') * 10;
}break;
case 1:{
diaData += (diaChar[indiceDoAlgarismo] - '0') * 1;
}break;
}
indiceDoAlgarismo++;
}
//Conversão da string mês
int mesData = 0;
indiceDoAlgarismo = 0;
while(indiceDoAlgarismo < CARACTER_MES - 1)
{
switch(indiceDoAlgarismo)
{
case 0:{
mesData += (mesChar[indiceDoAlgarismo] - '0') * 10;
}break;
case 1:{
mesData += (mesChar[indiceDoAlgarismo] - '0') * 1;
}break;
}
indiceDoAlgarismo++;
}
//Conversão da string aNo
int aNoData = 0;
indiceDoAlgarismo = 0;
while(indiceDoAlgarismo < CARACTER_ANo - 1)
{
switch(indiceDoAlgarismo)
{
case 0:{
aNoData += (aNoChar[indiceDoAlgarismo] - '0') * 1000;
}break;
case 1:{
aNoData += (aNoChar[indiceDoAlgarismo] - '0') * 100;
}break;
case 2:{
aNoData += (aNoChar[indiceDoAlgarismo] - '0') * 10;
}break;
case 3:{
aNoData += (aNoChar[indiceDoAlgarismo] - '0') * 1;
}break;
}
indiceDoAlgarismo++;
}
/*Verificação de aNo bissexto*/
int bissexto = 0; //0 - Comum | 1 - Bissexto
if(aNoData % 400 == 0)
bissexto = 1;
else
if(aNoData % 4 == 0 && (aNoData % 100 != 0))
{
bissexto = 1;
}
/*Verificação da data conforme calendário*/
if(bissexto == 1)
{
//Meses
if(mesData < 1 || mesData > 12)
errosData++;
//Dias
if(mesData == 1||mesData == 3||mesData == 5||mesData == 7||
mesData == 8||mesData == 10||mesData == 12)
if(diaData < 1 || diaData > 31)
errosData++;
if(mesData == 4||mesData == 6||mesData == 9||mesData == 11)
if(diaData < 1 || diaData > 30)
errosData++;
if(mesData == 2 && (diaData < 1 || diaData > 29))
errosData++;
}
else
{
//Meses
if(mesData < 1 || mesData > 12)
errosData++;
//Dias
if(mesData == 1||mesData == 3||mesData == 5||mesData == 7||
mesData == 8||mesData == 10||mesData == 12)
if(diaData < 1 || diaData > 31)
errosData++;
if(mesData == 4||mesData == 6||mesData == 9||mesData == 11)
if(diaData < 1 || diaData > 30)
errosData++;
if(mesData == 2 && (diaData < 1 || diaData > 28))
errosData++;
}
}
/*Conclusão da validação*/
if (errosData == 0)
{
printf("DATA VALIDA\n");
chaveDeValidar++;
}
else
{
printf("ERRO: Data invalida\n");
}
}
/*********************************************************/
//Inserir aluNo
void inserirAluNo()
{
chaveDeValidar = 0;
printf("***Cadastrar aluNo***\n");
//Matrícula
/*Gerar matrícula*/
gerarMatricula(cadastrosComSucesso + 1);
//Nome
printf("Digite o Nome do(a) estudante: ");
scanf("%51[^\n]%*c", aluNo[cadastrosComSucesso + 1].Nome);
//Sexo
printf("Digite o sexo do(a) estudante(F - FeminiNo|M - MasculiNo|O - Outro): ");
scanf("%1c%*c", &aluNo[cadastrosComSucesso + 1].sexo);
if(aluNo[cadastrosComSucesso + 1].sexo >= 'a' && aluNo[cadastrosComSucesso + 1].sexo <= 'z')
aluNo[cadastrosComSucesso + 1].sexo -= 32; //Tornar o input com letras maiúsculas
//Data de nascimento
printf("Digite a data de nascimento(dd/mm/aaaa): ");
scanf("%[^\n]%*c", &aluNo[cadastrosComSucesso + 1].dataNasc);
//CPF
printf("Digite o CPF do(a) estudante(XXX.XXX.XXX-XX): ");
scanf("%[^\n]%*c", &aluNo[cadastrosComSucesso + 1].cpf);
/*Validações*/
validarNome(aluNo[cadastrosComSucesso + 1].Nome);
validarSexo(aluNo[cadastrosComSucesso + 1].sexo);
validarNasc(aluNo[cadastrosComSucesso + 1].dataNasc);
validarCPF(aluNo[cadastrosComSucesso + 1].cpf);
if(chaveDeValidar == 4)
cadastrosComSucesso++;
}
//Listar aluNo
void listarAluNos()
{
printf("\nLista de aluNos cadastrados\n*******************************\n\n");
int iContador = 0;
while(iContador <= cadastrosComSucesso)
{
printf("MATRICULA: %s\n", aluNo[iContador].matricula);
printf("NoME: %s\n", aluNo[iContador].Nome);
printf("SEXO: %c\n", aluNo[iContador].sexo);
printf("DATA DE NASC.: %s\n", aluNo[iContador].dataNasc);
printf("CPF: %s\n", aluNo[iContador].cpf);
printf("*******************************\n");
iContador++;
}
printf("Listagem completa...\n\n");
}
| 2.796875 | 3 |
2024-11-18T21:10:19.447799+00:00
| 2020-04-22T22:59:27 |
12f76dc4a8101db732b3dbb93247361ad1c7783c
|
{
"blob_id": "12f76dc4a8101db732b3dbb93247361ad1c7783c",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-22T22:59:27",
"content_id": "e52f57570904f69a281519b6ec8db6605c82fb3b",
"detected_licenses": [
"MIT"
],
"directory_id": "18eaff1f22bf818ac82633963c5ba67aff0a8edc",
"extension": "c",
"filename": "EXERCICIO 8.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": 980,
"license": "MIT",
"license_type": "permissive",
"path": "/LISTA_3/EXERCICIO 8.c",
"provenance": "stackv2-0065.json.gz:36234",
"repo_name": "odanielrodrigues/C-Training",
"revision_date": "2020-04-22T22:59:27",
"revision_id": "61559bf1eb8f37ed85b0484f9cd908c74dd8741d",
"snapshot_id": "8a7a50103416bca6e2a8bc3eae04330b1b0b93c3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/odanielrodrigues/C-Training/61559bf1eb8f37ed85b0484f9cd908c74dd8741d/LISTA_3/EXERCICIO 8.c",
"visit_date": "2022-05-28T11:07:57.808002"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct aluno_
{
char nome[101];
char curso[101];
int idade;
float notas[3];
}dados;
void analise(char a[101],char b[101],int c,float d[3])
{
printf("Nome:");
puts(a);
printf("Curso:");
puts(b);
printf("Idade:%d", c);
int i;
float media=0;
for(i=0;i<3;i++)
{
media=media+d[i];
}
media=media/3;
printf("\n");
if(media>=60.0)
{
printf("APROVADO!");
}
else
{
printf("REPROVADO!");
}
}
int main()
{
dados aluno;
int i;
puts("Digite o nome do aluno");
gets(aluno.nome);
puts("Digite o curso:");
gets(aluno.curso);
printf("Digite a idade:");
scanf("%d", &aluno.idade);
for(i=0;i<3;i++)
{
printf("Digite a nota da prova %d:",i+1);
scanf("%f",&aluno.notas[i]);
}
analise(aluno.nome,aluno.curso,aluno.idade,aluno.notas);
return 0;
}
| 3.203125 | 3 |
2024-11-18T21:10:20.086403+00:00
| 2016-01-09T03:34:27 |
ae0f8eb0e2c73a99500bb61579eb1db9bdf284ce
|
{
"blob_id": "ae0f8eb0e2c73a99500bb61579eb1db9bdf284ce",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-09T03:34:27",
"content_id": "eb5efb9c8c02bd8300488f9ddb4d74d36f3cd850",
"detected_licenses": [
"MIT"
],
"directory_id": "d3f52cbb4336cd693217c6fb5284a135732382de",
"extension": "c",
"filename": "Character.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": 2911,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Character.c",
"provenance": "stackv2-0065.json.gz:36879",
"repo_name": "ciguangbo/MiniAdventure",
"revision_date": "2016-01-09T03:34:27",
"revision_id": "f9ec4987740b689e7ae85d721019959f4a084784",
"snapshot_id": "593bc25d46e3c7bbed8734fb3c565bd9c1ecdc89",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ciguangbo/MiniAdventure/f9ec4987740b689e7ae85d721019959f4a084784/src/Character.c",
"visit_date": "2021-01-18T17:14:40.170608"
}
|
stackv2
|
#include "pebble.h"
#include "Adventure.h"
#include "Character.h"
#include "CombatantClass.h"
#include "Logging.h"
#include "ResourceStory.h"
#include "Utils.h"
typedef struct Character
{
uint16_t classType;
int level;
int currentHealth;
uint16_t currentXP;
uint16_t skillCooldowns[MAX_SKILLS_IN_LIST];
} Character;
Character character;
void Character_SetCooldowns(uint16_t *cooldowns)
{
for(int i = 0; i < MAX_SKILLS_IN_LIST; ++i)
{
character.skillCooldowns[i] = cooldowns[i];
}
}
uint16_t *Character_GetCooldowns(void)
{
return character.skillCooldowns;
}
void Character_SetClass(int type)
{
character.classType = type;
}
int Character_GetHealth(void)
{
return character.currentHealth;
}
void Character_SetHealth(int health)
{
character.currentHealth = health;
}
int Character_GetLevel(void)
{
return character.level;
}
Character *GetCharacter(void)
{
return &character;
}
size_t Character_GetDataSize(void)
{
return sizeof(Character);
}
void Character_Rest(void)
{
character.currentHealth = CombatantClass_GetHealth(&BattlerWrapper_GetPlayerWrapper()->battler.combatantClass, character.level);
for(int i = 0; i < MAX_SKILLS_IN_LIST; ++i)
{
character.skillCooldowns[i] = 0;
}
}
void Character_GrantLevel(void)
{
character.level++;
character.currentHealth = CombatantClass_GetHealth(&BattlerWrapper_GetPlayerWrapper()->battler.combatantClass, character.level);
}
void Character_GrantXP(uint16_t monsterLevel)
{
uint16_t xpMonstersPerLevel = ResourceStory_GetCurrentStoryXPMonstersPerLevel();
uint16_t xpDifferenceScale = ResourceStory_GetCurrentStoryXPDifferenceScale();
if(xpMonstersPerLevel == 0)
return;
// We add 1 to work around truncation issues.
uint16_t xpGain = (XP_TO_LEVEL_UP * (100 + (monsterLevel - character.level) * xpDifferenceScale)) / (xpMonstersPerLevel * 100) + 1;
character.currentXP += xpGain;
while(character.currentXP >= XP_TO_LEVEL_UP)
{
character.level++;
character.currentXP -= XP_TO_LEVEL_UP;
character.currentHealth = CombatantClass_GetHealth(&BattlerWrapper_GetPlayerWrapper()->battler.combatantClass, character.level);
}
}
void Character_ReadPersistedData(int index)
{
persist_read_data(index, &character, sizeof(Character));
ResourceBattler_LoadPlayer(character.classType);
}
void Character_WritePersistedData(int index)
{
persist_write_data(index, &character, sizeof(Character));
}
void Character_Initialize(void)
{
INFO_LOG("Initializing character.");
character.classType = 0; // Get the first class in the story
ResourceBattler_LoadPlayer(character.classType);
character.level = 1;
character.currentXP = 0;
character.currentHealth = CombatantClass_GetHealth(&BattlerWrapper_GetPlayerWrapper()->battler.combatantClass, character.level);
}
| 2.328125 | 2 |
2024-11-18T21:10:20.402144+00:00
| 2018-12-02T07:44:23 |
52f00364a1e721c6b11ea19c875db234e14877bf
|
{
"blob_id": "52f00364a1e721c6b11ea19c875db234e14877bf",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-02T07:44:23",
"content_id": "e2b8b240c2f3ab19a30de43e5b87fb3dcf46c636",
"detected_licenses": [
"MIT"
],
"directory_id": "366a2c80d07b4e9733699d70d162685ceffac05a",
"extension": "c",
"filename": "modbus.c",
"fork_events_count": 0,
"gha_created_at": "2020-08-13T10:03:30",
"gha_event_created_at": "2020-08-13T10:03:30",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 287244193,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7854,
"license": "MIT",
"license_type": "permissive",
"path": "/smartbus/modbus.c",
"provenance": "stackv2-0065.json.gz:37392",
"repo_name": "jerryzhang126/smart-home-socket",
"revision_date": "2018-12-02T07:44:23",
"revision_id": "382b5b9114686fa13325d5c93124f8ec9a9a3df5",
"snapshot_id": "1392a096f9d82c6824865901434cb346297510db",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jerryzhang126/smart-home-socket/382b5b9114686fa13325d5c93124f8ec9a9a3df5/smartbus/modbus.c",
"visit_date": "2021-10-03T00:43:04.852595"
}
|
stackv2
|
//
// Created by delta54 on 10/2/16.
//
#include <stdio.h>
#include <assert.h>
#include <stdbool.h>
#include "modbus.h"
#include "commands.h"
#include "../rtos/EERTOS.h"
#include "../socket/uart.h"
#define MB_ASCII_DEFAULT_CR '\r' /*!< Default CR character for Modbus ASCII. */
#define MB_ASCII_DEFAULT_LF '\n' /*!< Default LF character for Modbus ASCII. */
#define MB_SER_PDU_SIZE_MAX 256 /*!< Maximum size of a Modbus ASCII frame. */
typedef enum
{
STATE_RX_IDLE, /*!< Receiver is in idle state. */
STATE_RX_RCV, /*!< Frame is beeing received. */
STATE_RX_WAIT_EOF /*!< Wait for End of Frame. */
} eMBRcvState;
typedef enum
{
STATE_TX_IDLE, /*!< Transmitter is in idle state. */
STATE_TX_START, /*!< Starting transmission (':' sent). */
STATE_TX_DATA, /*!< Sending of data (Address, Data, LRC). */
STATE_TX_END, /*!< End of transmission. */
STATE_TX_NOTIFY /*!< Notify sender that the frame has been sent. */
} eMBSndState;
typedef enum
{
BYTE_HIGH_NIBBLE, /*!< Character for high nibble of byte. */
BYTE_LOW_NIBBLE /*!< Character for low nibble of byte. */
} eMBBytePos;
u08 RxBuf[MaxLenghtRxBuf]; // буфер принимаемых данных
u08 TxBuf[MaxLenghtTxBuf]; // буфер передаваемых данных
u08 ucResult;
static eMBRcvState curRxState;
static eMBBytePos curRxBytePos;
static eMBSndState curTxState;
static volatile u08 curTxBufferCount;
static volatile u08 curRxBufferPos;
static volatile u08 *curRxBuffer = RxBuf;
static volatile u08 *curTxBuffer;
void ModbusInit() {
curRxState = STATE_RX_IDLE;
}
void ModBusCheckPack(u08 NumByte) {
if (curRxBuffer[0] != DEVICE_ADDRESS && curRxBuffer[0] != 0) //адрес устройства
return;
if (LRC((u08 *) curRxBuffer, NumByte) == 0) { //подсчет LRC в принятой посылке
errorMessage(ILLEGAL_LRC);
return;
}
// этот пакет адресован нам
switch (curRxBuffer[1]) {
case 0x64: //100
echo((const u08 *) curRxBuffer, NumByte);
break;
case 0x03:
read_state((const u08 *) curRxBuffer);
break;
case 0x04:
write_state((const u08 *) curRxBuffer);
break;
default:
errorMessage(ILLEGAL_FUNCTION);
break;
}
}
void ModBusReceiveFSM(const u08 ucByte) {
// u08 ucByte = getchar();
if (ucByte == EOF)
return;
// putchar( ucByte ); //
switch (curRxState) {
case STATE_RX_RCV:
if( ucByte == ':' ) {
curRxBytePos = BYTE_HIGH_NIBBLE;
curRxBufferPos = 0;
} else if( ucByte == MB_ASCII_DEFAULT_CR ) {
curRxState = STATE_RX_WAIT_EOF;
} else {
ucResult = char2bin(ucByte);
switch ( curRxBytePos )
{
case BYTE_HIGH_NIBBLE:
if( curRxBufferPos < MB_SER_PDU_SIZE_MAX ) {
curRxBuffer[curRxBufferPos] = ( u08 )( ucResult << 4 );
curRxBytePos = BYTE_LOW_NIBBLE;
break;
} else {
curRxState = STATE_RX_IDLE;
}
break;
case BYTE_LOW_NIBBLE:
curRxBuffer[curRxBufferPos] |= ( u08 )( ucResult & 0xFF );
curRxBufferPos++;
curRxBytePos = BYTE_HIGH_NIBBLE;
break;
}
}
break;
case STATE_RX_WAIT_EOF:
if (ucByte == MB_ASCII_DEFAULT_LF) {
curRxState = STATE_RX_IDLE;
ModBusCheckPack(curRxBufferPos);
} else if( ucByte == ':' ) {
curRxBytePos = BYTE_HIGH_NIBBLE;
curRxBufferPos = 0;
curRxState = STATE_RX_RCV;
} else {
curRxState = STATE_RX_IDLE;
}
break;
case STATE_RX_IDLE:
if (ucByte == ':') {
curRxBufferPos = 0;
curRxBytePos = BYTE_HIGH_NIBBLE;
curRxState = STATE_RX_RCV;
}
break;
}
}
void MobBusTransmitFSM() {
u08 ucByte;
switch ( curTxState )
{
case STATE_TX_START:
ucByte = ':';
uart_putc((u08)ucByte);
curTxState = STATE_TX_DATA;
curRxBytePos = BYTE_HIGH_NIBBLE;
MobBusTransmitFSM();
break;
case STATE_TX_DATA:
if( curTxBufferCount > 0 )
{
switch ( curRxBytePos )
{
case BYTE_HIGH_NIBBLE:
ucByte = bin2char((u08) (*curTxBuffer >> 4));
uart_putc((u08)ucByte);
curRxBytePos = BYTE_LOW_NIBBLE;
break;
case BYTE_LOW_NIBBLE:
ucByte = bin2char((u08) (*curTxBuffer & 0x0F));
uart_putc((u08)ucByte);
curTxBuffer++;
curRxBytePos = BYTE_HIGH_NIBBLE;
curTxBufferCount--;
break;
}
} else {
uart_putc((u08)MB_ASCII_DEFAULT_CR);
curTxState = STATE_TX_END;
}
MobBusTransmitFSM();
break;
case STATE_TX_END:
curTxBufferCount = 0;
uart_putc((u08)MB_ASCII_DEFAULT_LF);
curTxState = STATE_TX_NOTIFY;
MobBusTransmitFSM();
break;
case STATE_TX_NOTIFY:
curTxState = STATE_TX_IDLE;
MobBusTransmitFSM();
break;
case STATE_TX_IDLE:
SetTimerTask(ModbusSetRead, 10);
// ModbusSetRead();
break;
}
}
void MobBusSend(const u08 *frame, const u08 length) {
ModbusSetWrite(); //rs458
curTxBuffer = (u08*)TxBuf;
memcpy((u08*)curTxBuffer + 2, frame, length);
curTxBufferCount = 2;
curTxBuffer[0] = DEVICE_ADDRESS;
curTxBuffer[1] = curRxBuffer[1]; //команда
curTxBufferCount += length;
u08 lrc = LRC((u08 *) curTxBuffer, curTxBufferCount);
curTxBuffer[curTxBufferCount++] = lrc;
curTxState = STATE_TX_START;
MobBusTransmitFSM();
}
static u08 LRC(u08 *pucFrame, u08 usLen) {
u08 lrc = 0; /* LRC char initialized */
while( usLen-- )
{
lrc += *pucFrame++; /* Add buffer byte without carry */
}
/* Return twos complement */
lrc = ( u08 ) ( -( ( CHAR ) lrc ) );
return lrc;
}
static u08 char2bin(u08 ucByte) {
if( ( ucByte >= '0' ) && ( ucByte <= '9' ) ) {
return ( u08 )( ucByte - '0' );
} else if( ( ucByte >= 'A' ) && ( ucByte <= 'F' ) ) {
return ( u08 )( ucByte - 'A' + 0x0A );
} else {
return 0xFF;
}
}
static u08 bin2char(u08 ucByte) {
if( ucByte <= 0x09 ) {
return ( u08 )( '0' + ucByte );
} else if( ( ucByte >= 0x0A ) && ( ucByte <= 0x0F ) ) {
return ( u08 )( ucByte - 0x0A + 'A' );
}
return '0';
}
// 1 - address u08
// 2 - function u08 + error bite
// 3 - error u08
// 4 - lrc u08
void errorMessage(u08 error) {
u08 lrc;
curTxBuffer[0] = DEVICE_ADDRESS;
curTxBuffer[1] = (u08) (curRxBuffer[1] | 0x80);
curTxBuffer[2] = error;
lrc = LRC((u08 *) curTxBuffer, 3);
curTxBuffer[3] = lrc;
curTxBufferCount = 4;
/* Activate the transmitter. */
curTxState = STATE_TX_START;
MobBusTransmitFSM();
}
| 2.53125 | 3 |
2024-11-18T21:10:20.549511+00:00
| 2020-05-26T22:16:37 |
410d02dcd501e54b65b4d4927dfaef0d7e4f29ef
|
{
"blob_id": "410d02dcd501e54b65b4d4927dfaef0d7e4f29ef",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-26T22:16:37",
"content_id": "bc6268be0587eadbafa5cb9b179e5c44221aafe3",
"detected_licenses": [
"Zlib"
],
"directory_id": "dac186d34ac4d9971ade91238acb327a12f00cef",
"extension": "h",
"filename": "zidx.h",
"fork_events_count": 1,
"gha_created_at": "2018-06-02T19:55:18",
"gha_event_created_at": "2020-05-08T23:13:29",
"gha_language": "C",
"gha_license_id": "Zlib",
"github_id": 135847971,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7670,
"license": "Zlib",
"license_type": "permissive",
"path": "/src/zidx.h",
"provenance": "stackv2-0065.json.gz:37649",
"repo_name": "ozars/libzidx",
"revision_date": "2020-05-26T22:16:37",
"revision_id": "15592e2ae4044a837db33e78fd4c106b0c8416f8",
"snapshot_id": "3fdae47a68ee0debb127c338fa3a6f5ce3ac0baa",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/ozars/libzidx/15592e2ae4044a837db33e78fd4c106b0c8416f8/src/zidx.h",
"visit_date": "2022-05-19T19:09:09.694659"
}
|
stackv2
|
/**
* \file
* libzidx API header.
*/
#ifndef ZIDX_H
#define ZIDX_H
#include <stdio.h> // FILE*
#include <stdint.h>
#include <sys/types.h> // off_t
#include <streamlike.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* \name DefaultValues
*
* Default initialization values used by zidx_index_init() call.
*
* @{
*/
/** Default value for initial capacity of checkpoint list. */
#define ZX_DEFAULT_INITIAL_LIST_CAPACITY (8)
/** Default value for zlib window size. */
#define ZX_DEFAULT_WINDOW_SIZE (32768)
/** Default value for size of the buffer used for decompression. */
#define ZX_DEFAULT_COMPRESSED_DATA_BUFFER_SIZE (32768)
/**
* Default value for the size of buffer for discarding unused data while
* seeking to an offset inside a compressed block.
*/
#define ZX_DEFAULT_SEEKING_DATA_BUFFER_SIZE (32768)
/** }@ */
/**
* \name ReturnValues
*
* Return values used by zidx functions.
*
* All error codes must be negative. Users can get return value of callback
* functions, however it's users responsibility to avoid conflicting return
* values in callbacks. Users are encouraged to leave return values in the
* range of -1 to -256 library use.
*
* Errors caused by zlib library will be returned by passing through
* ZX_ERR_ZLIB() macro, so user can use this macro to check for errors.
*
* @{
*/
#define ZX_RET_OK (0) /**< Sucessful call. */
#define ZX_ERR_PARAMS (-1) /**< Error in function parameter. */
#define ZX_ERR_MEMORY (-2) /**< Error in memory allocation. */
#define ZX_ERR_CORRUPTED (-3) /**< Corrupted file or data structure. */
#define ZX_ERR_STREAM_READ (-4) /**< Error in reading stream. */
#define ZX_ERR_STREAM_EOF (-5) /**< Unexpected EOF error in stream. */
#define ZX_ERR_STREAM_SEEK (-6) /**< Error in seeking stream. */
#define ZX_ERR_INVALID_OP (-7) /**< Invalid operation. */
#define ZX_ERR_NOT_FOUND (-8) /**< Requested item is not found. */
#define ZX_ERR_OVERFLOW (-9) /**< Data does not fit to the given data
structure. */
#define ZX_ERR_NOT_IMPLEMENTED (-10) /**< Feature is not implemented. */
#define ZX_ERR_ZLIB(err) (-64 + err) /**< Error caused by zlib. */
/** @} */
/**
* \name OpaqueDataStructures
* Opaque data structures.
*
* @{
*/
#ifndef ZLIB_H
/** Opaque declaration of z_stream, if not declared by zlib header already. */
typedef struct z_stream_s z_stream;
#endif
/**
* Keeps state of opened zidx stream state as well as other data structures
* needed.
*/
typedef struct zidx_index_s zidx_index;
/**
* Keeps information about a single checkpoint.
*/
typedef struct zidx_checkpoint_s zidx_checkpoint;
/**
* Keeps information about compressed and uncompressed offsets.
*/
typedef struct zidx_checkpoint_offset_s zidx_checkpoint_offset;
/** @} */
/**
* \name ConfigurationValues
*
* Types defined for denoting various configuration.
* @{
*/
/**
* Type of the input stream file. There isn't "just zlib file type" option due
* to design of zlib library.
*/
typedef enum zidx_stream_type
{
ZX_STREAM_DEFLATE = 1, /**< DEFLATE format. */
ZX_STREAM_GZIP = 2, /**< GZIP format. */
ZX_STREAM_GZIP_OR_ZLIB = 3 /**< GZIP or ZLIB format determined by file
header. */
} zidx_stream_type;
/**
* Type of the checksum algorithm.
*
* Since the library treats all data as deflate blocks, underlying checksum
* control mechanism of zlib is disabled. Instead, this library can be
* configured for a given checksum mechanism.
*/
typedef enum zidx_checksum_option
{
ZX_CHECKSUM_DISABLED = 0, /**< Do not use any checksum algorithm. */
ZX_CHECKSUM_DEFAULT = 1, /**< Use default checksum algorithm for the
file type. By default DEFLATE doesn't use
any checksum mechanisms, GZIP uses CRC-32,
and ZLIB uses Adler-32. */
ZX_CHECKSUM_FORCE_CRC32 = 2, /**< Force using CRC-32. */
ZX_CHECKSUM_FORCE_ADLER32 = 3 /**< Force using Adler-32. */
} zidx_checksum_option;
/** @} */
typedef
int (*zidx_block_callback)(void *context,
zidx_index *index,
zidx_checkpoint_offset *offset,
int is_last_block);
zidx_index* zidx_index_create();
int zidx_index_init(zidx_index* index,
streamlike_t* comp_stream);
int zidx_index_init_ex(zidx_index* index,
streamlike_t* comp_stream,
zidx_stream_type stream_type,
zidx_checksum_option checksum_option,
z_stream* z_stream_ptr,
int initial_capacity,
int window_size,
int comp_data_buffer_size,
int seeking_data_buffer_size);
int zidx_index_destroy(zidx_index* index);
int zidx_read(zidx_index* index, void *buffer, int nbytes);
int zidx_read_ex(zidx_index* index,
void *buffer,
int nbytes,
zidx_block_callback block_callback,
void *callback_context);
int zidx_seek(zidx_index* index, off_t offset);
int zidx_seek_ex(zidx_index* index,
off_t offset,
zidx_block_callback block_callback,
void *callback_context);
off_t zidx_tell(zidx_index* index);
int zidx_rewind(zidx_index* index);
int zidx_eof(zidx_index* index);
int zidx_error(zidx_index* index);
int zidx_uncomp_size(zidx_index* index);
int zidx_build_index(zidx_index* index,
off_t spacing_length,
char is_uncompressed);
int zidx_build_index_ex(zidx_index* index,
zidx_block_callback block_callback,
void *callback_context);
zidx_checkpoint* zidx_create_checkpoint();
int zidx_fill_checkpoint(zidx_index* index,
zidx_checkpoint* new_checkpoint,
zidx_checkpoint_offset* offset);
int zidx_add_checkpoint(zidx_index* index, zidx_checkpoint* checkpoint);
int zidx_get_checkpoint_idx(zidx_index* index, off_t offset);
zidx_checkpoint* zidx_get_checkpoint(zidx_index* index, int idx);
int zidx_checkpoint_count(zidx_index* index);
/* TODO: Consider dropping consts before release. */
off_t zidx_get_checkpoint_offset(const zidx_checkpoint* ckp);
size_t zidx_get_checkpoint_window(const zidx_checkpoint* ckp,
const void** result);
int zidx_extend_index_size(zidx_index* index, int nmembers);
int zidx_shrink_index_size(zidx_index* index, int nmembers);
int zidx_fit_index_size(zidx_index* index);
/* index import/export functions */
typedef
int (*zidx_import_filter_callback)(void *filter_context,
zidx_index *index,
zidx_checkpoint_offset *offset);
typedef
int (*zidx_export_filter_callback)(void *filter_context,
zidx_index *index,
zidx_checkpoint *offset);
int zidx_import_ex(zidx_index *index,
streamlike_t *stream,
zidx_import_filter_callback filter,
void *filter_context);
int zidx_export_ex(zidx_index *index,
streamlike_t *stream,
zidx_export_filter_callback filter,
void *filter_context);
int zidx_import(zidx_index *index, streamlike_t *stream);
int zidx_export(zidx_index *index, streamlike_t* output_index_file);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // ZIDX_H
| 2.265625 | 2 |
2024-11-18T21:10:20.880690+00:00
| 2021-10-30T18:27:13 |
a85061f4304de86c53cf0e8e43f7bb3345063a8d
|
{
"blob_id": "a85061f4304de86c53cf0e8e43f7bb3345063a8d",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-30T18:27:13",
"content_id": "68a305c772ec65777c78bd3dafd8d0b1bee63a7f",
"detected_licenses": [
"MIT"
],
"directory_id": "3723e3b24033a8cf2a0aa92b4e93ddce50dc934c",
"extension": "h",
"filename": "diagonal_distribution.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": 13068,
"license": "MIT",
"license_type": "permissive",
"path": "/src/diagonal_distribution.h",
"provenance": "stackv2-0065.json.gz:37905",
"repo_name": "yekutielyehuda/qunundrum",
"revision_date": "2021-10-30T18:27:13",
"revision_id": "54c1ea1913f087841fa9c7201159c5a5d95bd399",
"snapshot_id": "b968d48b1815a6430ec9e6ec4bc2a104b7e1195e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yekutielyehuda/qunundrum/54c1ea1913f087841fa9c7201159c5a5d95bd399/src/diagonal_distribution.h",
"visit_date": "2023-08-21T08:34:53.983954"
}
|
stackv2
|
/*!
* \file diagonal_distribution.h
* \ingroup diagonal_distribution
*
* \brief The declaration of data structures representing diagonal probability
* distributions, and of functions for manipulating such distributions.
*
* Diagonal probability distributions are used to represent the probability
* distribution induced by Shor's algorithm for computing general discrete
* logarithms [1] when modified as in [2] to start with a uniform superposition.
*
* [1] Shor, P.W.: Polynomial-time algorithms for prime factorization and
* discrete logarithms on a quantum computer. In: SIAM Journal on Scientific
* Computing (SISC), volume 26(5), pp. 1484 (1997).
*
* [2] Ekerå, M.: Revisiting Shor's quantum algorithm for computing general
* discrete logarithms. In: ArXiv Pre-Print 1905.09084v2.
*/
/*!
* \defgroup diagonal_distribution Diagonal probability distributions
* \ingroup distribution
*
* \brief A module for diagonal probability distributions.
*
* Diagonal probability distributions are used to represent the probability
* distribution induced by Shor's algorithm for computing general discrete
* logarithms [1] when modified as in [2] to start with a uniform superposition.
*
* [1] Shor, P.W.: Polynomial-time algorithms for prime factorization and
* discrete logarithms on a quantum computer. In: SIAM Journal on Scientific
* Computing (SISC), volume 26(5), pp. 1484 (1997).
*
* [2] Ekerå, M.: Revisiting Shor's quantum algorithm for computing general
* discrete logarithms. In: ArXiv Pre-Print 1905.09084v2.
*/
#ifndef DIAGONAL_DISTRIBUTION_H
#define DIAGONAL_DISTRIBUTION_H
#include "common.h"
#include "diagonal_distribution_slice.h"
#include "diagonal_parameters.h"
#include "random.h"
#include <gmp.h>
#include <stdint.h>
#include <stdio.h>
/*!
* \brief An enumeration of flags indicating how the logarithm d or order r
* were selected.
*/
enum {
/*!
* \brief A flag indicating that the distribution was constructed by
* deterministically setting d or r from Catalan's constant.
*
* For more information, see parameters_deterministic().
*/
DIAGONAL_DISTRIBUTION_FLAG_DETERMINISTIC = 0,
/*!
* \brief A flag indicating that the distribution was constructed by
* setting a minimal r = 2^(m - 1) + 1 and random d.
*
* \note This flag is currently not used.
*/
DIAGONAL_DISTRIBUTION_FLAG_MINIMAL = 4,
/*!
* \brief A flag indicating that the distribution was constructed by
* setting a maximal r = 2^m - 1 and random d.
*
* \note This flag is currently not used.
*/
DIAGONAL_DISTRIBUTION_FLAG_MAXIMAL = 8,
/*!
* \brief A flag indicating that the distribution was constructed by
* randomly selecting d or r on (2^(m-1), 2^m).
*
* For more information, see parameters_selection_random_d_or_r().
*/
DIAGONAL_DISTRIBUTION_FLAG_RANDOM = 16,
/*!
* \brief A flag indicating that the distribution was constructed by
* explicitly setting d or r to a value provided by the caller.
*/
DIAGONAL_DISTRIBUTION_FLAG_EXPLICIT = 32
};
/*!
* \brief A data structure representing a diagonal probability distribution.
*
* \ingroup diagonal_distribution
*/
typedef struct {
/*! \brief A vector of pointers to slices. */
Diagonal_Distribution_Slice ** slices;
/*! \brief The total number of pointers to slices allocated. */
uint32_t capacity;
/*! \brief The number of slices inserted into the distribution. */
uint32_t count;
/*! \brief The distribution parameters. */
Diagonal_Parameters parameters;
/*! \brief The total probability summed over all slices. */
long double total_probability;
/*! \brief The total error summed over all slices. */
long double total_error;
/*! \brief The distribution flags. */
uint32_t flags;
/*!
* \brief The precision using which the distribution was computed.
*
* \remark Incorrect precisions may be reported for distributions imported
* and exported using binaries compiled to use different precision
* levels, especially if the distribution is modified by computing
* or recomputing slices inbetween import and export operations. */
uint32_t precision;
} Diagonal_Distribution;
/*!
* \name Memory allocation
* \{
*/
/*!
* \brief Allocates memory for a distribution.
*
* \return The pointer to the memory allocated for the distribution.
*/
Diagonal_Distribution * diagonal_distribution_alloc();
/*!
* \brief Deallocates the memory previously allocated for a distribution.
*
* \param[in, out] distribution A pointer to a pointer to the memory allocated
* for the distribution. This function assigns
* NULL to the pointer as it deallocates the
* memory to which it refers.
*/
void diagonal_distribution_dealloc(
Diagonal_Distribution ** const distribution);
/*!
* \}
*/
/*!
* \name Initialization
* \{
*/
/*!
* \brief Initializes a distribution with a given set of parameters.
*
* This function allocates memory for the slices in the distribution.
*
* \param[in, out] distribution The distribution to initialize.
* \param[in] parameters The parameters to use to initialize the
* distribution.
* \param[in] flags The distribution flags.
* \param[in] capacity The distribution capacity in slices.
*
* \remark The parameter data structure is copied into the distribution data
* structure, rather than being referenced.
*/
void diagonal_distribution_init(
Diagonal_Distribution * const distribution,
const Diagonal_Parameters * const parameters,
const uint32_t flags,
const uint32_t capacity);
/*!
* \brief Initializes a distribution by reading from an already initialized
* source distribution and scaling down its dimension.
*
* This function allocates memory for the slices in the distribution.
*
* \param[in, out] dst_distribution The distribution to initialize.
* \param[in] src_distribution The source distribution to be scaled.
* \param[in] dimension The dimension to be used for the
* destination distribution. Must divide the
* dimension of the source distribution.
*
* \remark Used by the plotting functions to scale down the resolution in the
* probability distributions.
*/
void diagonal_distribution_init_copy_scale(
Diagonal_Distribution * const dst_distribution,
const Diagonal_Distribution * const src_distribution,
const uint32_t dimension);
/*!
* \brief Clears a distribution.
*
* This function deallocates memory for slices in the distribution.
*
* \param[in, out] distribution The distribution to clear.
*/
void diagonal_distribution_clear(
Diagonal_Distribution * const distribution);
/*!
* \}
*/
/*!
* \name Importing and exporting
* \{
*/
/*!
* \brief Initializes a distribution by importing it from a file.
*
* \param[in, out] distribution The distribution to initialize.
* \param[in, out] file The file from which to read the distribution.
*/
void diagonal_distribution_init_import(
Diagonal_Distribution * const distribution,
FILE * const file);
/*!
* \brief Exports a probability distribution to file.
*
* \param[in] distribution The distribution to export to file.
* \param[in, out] file The file to which to export the distribution.
*/
void diagonal_distribution_export(
const Diagonal_Distribution * const distribution,
FILE * const file);
/*!
* \brief Exports information about a probability distribution to file.
*
* \param[in] distribution The distribution to export to file.
* \param[in, out] file The file to which to export information.
* \param[in] export_slices Export verbose information on slices.
* \param[in] export_regions Export verbose information on regions.
*/
void diagonal_distribution_export_info(
const Diagonal_Distribution * const distribution,
FILE * const file,
const bool export_slices = TRUE,
const bool export_regions = TRUE);
/*!
* \}
*/
/*!
* \name Message passing
* \{
*/
/*!
* \brief Initializes a distribution by receiving a broadcast from a node.
*
* \param[in, out] distribution The distribution to initialize.
* \param[in] root The rank of the node from which to receive.
*/
void diagonal_distribution_init_bcast_recv(
Diagonal_Distribution * const distribution,
const int root);
/*!
* \brief Broadcasts a distribution to all other nodes.
*
* \param[in] distribution The distribution to broadcast.
* \param[in] root The rank of the root node.
*/
void diagonal_distribution_bcast_send(
const Diagonal_Distribution * const distribution,
const int root);
/*!
* \}
*/
/*!
* \name Managing slices
* \{
*/
/*!
* \brief Inserts a slice into the distribution.
*
* \param[in, out] distribution The distribution in which to insert the slice.
* \param[in, out] slice The slice to insert into the distribution.
*
* \remark The slice data structure is referenced from the distribution data
* structure, rather than being copied into the structure. You may
* not modify or deallocate the slice after calling this function.
*/
void diagonal_distribution_insert_slice(
Diagonal_Distribution * const distribution,
Diagonal_Distribution_Slice * const slice);
/*!
* \brief Sorts the slices in the distribution in decreasing order with
* respect to the total probability of observing the slice.
*
* \remark This function should be called prior to sampling the distribution.
* As the distribution slices are traversed in order when sampling,
* sampling a distribution in which the slices are sorted in decreasing
* order with respect to the total probability of observing the slice
* is much faster.
*
* \param[in, out] distribution The distribution in which to sort the slices.
*/
void diagonal_distribution_sort_slices(
Diagonal_Distribution * const distribution);
/*!
* \}
*/
/*!
* \name Sampling
* \{
*/
/*!
* \brief Samples a slice from the distribution.
*
* \param[in] distribution The distribution to sample.
* \param[in, out] random_state The random state to use when sampling.
*
* \return A pointer to the slice sampled, or NULL if the slice sampled
* is outside the range of the distribution.
*/
const Diagonal_Distribution_Slice * diagonal_distribution_sample_slice(
const Diagonal_Distribution * const distribution,
Random_State * const random_state);
/*!
* \brief Samples a region on the alpha axis from the probability distribution
* and returns its bounds.
*
* \remark The region bounds are represented as signed logarithmic alpha values
* log_alpha such that alpha = sgn(log_alpha) 2^(abs(log_alpha)).
*
* \param[in] distribution The distribution to sample.
* \param[in, out] random_state The random state to use when sampling.
*
* \param[out] min_log_alpha_r The minimum signed logarithmic alpha_r.
* \param[out] max_log_alpha_r The maximum signed logarithmic alpha_r.
*
* \return Returns #TRUE if a region was successfully sampled, #FALSE if the
* region sampled is outside the range of the distribution.
*/
bool diagonal_distribution_sample_region(
const Diagonal_Distribution * const distribution,
Random_State * const random_state,
double * const min_log_alpha_r,
double * const max_log_alpha_r);
/*!
* \brief Samples an argument alpha_r from the probability distribution.
*
* The argument alpha_r is sampled with high resolution, and is guaranteed to be
* admissible.
*
* \param[in] distribution The distribution to sample.
* \param[in, out] random_state The random state to use when sampling.
*
* \param[in, out] alpha_r The argument alpha_r.
*
* \return Returns #TRUE if the argument alpha was successfully sampled, #FALSE
* if the argument sampled is outside the range of the distribution.
*/
bool diagonal_distribution_sample_alpha_r(
const Diagonal_Distribution * const distribution,
Random_State * const random_state,
mpz_t alpha_r);
/*!
* \brief Samples an integer pair (j, k) from the probability distribution and
* returns the components of the pair.
*
* \param[in] distribution The distribution to sample.
* \param[in, out] random_state The random state to use when sampling.
*
* \param[in, out] j The integer j.
* \param[in, out] k The integer k.
*/
bool diagonal_distribution_sample_pair_j_k(
const Diagonal_Distribution * const distribution,
Random_State * const random_state,
mpz_t j,
mpz_t k);
/*!
* \}
*/
#endif /* DIAGONAL_DISTRIBUTION_H */
| 2.265625 | 2 |
2024-11-18T21:10:21.152849+00:00
| 2020-01-25T02:37:43 |
25e732581a944484187173c5d36967ecde8e355a
|
{
"blob_id": "25e732581a944484187173c5d36967ecde8e355a",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-25T02:37:43",
"content_id": "0e2603578828dd8b8275d2732baf19cffdcec1f5",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "53994424a9f3ce98986f50462c39108456609632",
"extension": "h",
"filename": "common.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 140652588,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1101,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/interpreter/include/common.h",
"provenance": "stackv2-0065.json.gz:38293",
"repo_name": "ethan2-0/Slang",
"revision_date": "2020-01-25T02:37:43",
"revision_id": "ce0844777b550f51b84d6eba7c80f1a5acf612ce",
"snapshot_id": "e87e73f118006e124ff741792133023a4ecede0f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ethan2-0/Slang/ce0844777b550f51b84d6eba7c80f1a5acf612ce/interpreter/include/common.h",
"visit_date": "2020-03-22T21:03:14.678505"
}
|
stackv2
|
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#ifndef COMMON_H
#define COMMON_H
#define DEBUG 0
#define ASSERTIONS 0
void fatal(char* description);
void fatal_with_errcode(char* description, int errcode);
void assert(bool b);
struct fr_STATE {
FILE* fp;
char* buffer;
size_t bufflen;
int index;
};
struct fr_STATE* fr_new(FILE* fp);
struct fr_STATE* fr_new_from_buffer(int bufflen, char* buffer);
void fr_destroy(struct fr_STATE* state);
void fr_advance(struct fr_STATE* state, int qty);
bool fr_iseof(struct fr_STATE* state);
char fr_getchar(struct fr_STATE* state);
void fr_rewind(struct fr_STATE* state);
uint8_t fr_getuint8(struct fr_STATE* state);
int8_t fr_getint8(struct fr_STATE* state);
uint16_t fr_getuint16(struct fr_STATE* state);
int16_t fr_getint16(struct fr_STATE* state);
uint32_t fr_getuint32(struct fr_STATE* state);
int32_t fr_getint32(struct fr_STATE* state);
uint64_t fr_getuint64(struct fr_STATE* state);
int64_t fr_getint64(struct fr_STATE* state);
char* fr_getstr(struct fr_STATE* state);
void* mm_malloc(size_t size);
#endif /* COMMON_H */
| 2.046875 | 2 |
2024-11-18T21:10:21.764735+00:00
| 2023-05-20T10:31:06 |
c5659082252474cbd191d60c86cb3340812a620b
|
{
"blob_id": "c5659082252474cbd191d60c86cb3340812a620b",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-20T10:31:06",
"content_id": "2e980f284930d7de0bbec3fa36e048fb901e7e57",
"detected_licenses": [
"MIT"
],
"directory_id": "c59984a5f9b68c830e9fb4472e1ef641ac30144a",
"extension": "c",
"filename": "example_script.c",
"fork_events_count": 9,
"gha_created_at": "2017-04-22T06:07:32",
"gha_event_created_at": "2022-12-12T22:32:21",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 89048480,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 578,
"license": "MIT",
"license_type": "permissive",
"path": "/tccengine/example_script.c",
"provenance": "stackv2-0065.json.gz:38680",
"repo_name": "cnlohr/cntools",
"revision_date": "2023-05-20T10:31:06",
"revision_id": "d13416c2366b61560c4ac489356eb7c246f4660d",
"snapshot_id": "40bae6ca911db7609a63bebf91c36f065f8f2f55",
"src_encoding": "UTF-8",
"star_events_count": 16,
"url": "https://raw.githubusercontent.com/cnlohr/cntools/d13416c2366b61560c4ac489356eb7c246f4660d/tccengine/example_script.c",
"visit_date": "2023-05-23T22:13:17.676286"
}
|
stackv2
|
#include "tccexports.h"
#include "../os_generic.h"
static int k;
struct ScriptStructure
{
int compiles;
};
int inner2()
{
if( k % 10 == 9 )
{
char * v = 0;
*v = 5;
}
}
int init( struct ScriptStructure * cid )
{
printf( "Init\n" );
}
int start( struct ScriptStructure * cid )
{
printf( "Start\n" );
k = 0;
cid->compiles++;
}
int inner()
{
k++;
inner2();
}
int stop( struct ScriptStructure * cid )
{
printf( "Stop\n" );
}
int update( struct ScriptStructure * cid )
{
inner();
printf( "Update: %d %f\n", cid->compiles, OGGetAbsoluteTime() );
}
| 2.15625 | 2 |
2024-11-18T21:10:21.994549+00:00
| 2015-11-18T18:01:02 |
952ea60726074f621f0bc1b51a831c5c11b097fd
|
{
"blob_id": "952ea60726074f621f0bc1b51a831c5c11b097fd",
"branch_name": "refs/heads/master",
"committer_date": "2015-11-18T18:01:02",
"content_id": "afbd7f0e131836302856579d4d457c0c95479895",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "dd20f911ca9d6331e6b04fb6a4ad8db08a27e693",
"extension": "c",
"filename": "fiob.c",
"fork_events_count": 1,
"gha_created_at": "2015-11-19T08:03:20",
"gha_event_created_at": "2015-11-19T08:03:20",
"gha_language": null,
"gha_license_id": null,
"github_id": 46477229,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8521,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/fiob.c",
"provenance": "stackv2-0065.json.gz:38937",
"repo_name": "LogInsight/tarantool",
"revision_date": "2015-11-18T18:01:02",
"revision_id": "b2d0b7af40fe7252f75642a6ed6c2cc120d4cc55",
"snapshot_id": "9b34f4aa10da30fc39554fa4e9ed030f9707e45f",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/LogInsight/tarantool/b2d0b7af40fe7252f75642a6ed6c2cc120d4cc55/src/fiob.c",
"visit_date": "2020-12-01T11:37:36.252940"
}
|
stackv2
|
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <fiob.h>
#include <sys/types.h>
#include <stdbool.h>
#include <sys/uio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <say.h>
#include <assert.h>
#include <unistd.h>
#include <trivia/config.h>
#include <trivia/util.h>
/* Use special implemention if we have O_DIRECT and FOPENCOOKIE or FUNOPEN */
#if defined(O_DIRECT) && (defined(HAVE_FUNOPEN) || defined(HAVE_FOPENCOOKIE))
#define FIOB_DIRECT
#endif
#if defined(FIOB_DIRECT)
enum {
FIOB_ALIGN = 4096,
FIOB_BSIZE = FIOB_ALIGN * 256
};
struct fiob {
int fd;
size_t bsize;
size_t bfill;
void *buf;
char *path;
#ifdef HAVE_FUNOPEN
struct {
int (*read)(void *cookie, char *buf, int len);
int (*write)(void *cookie, const char *buf, int len);
fpos_t (*seek)(void *cookie, fpos_t pos, int whence);
int (*close)(void *cookie);
} io;
#else
cookie_io_functions_t io;
#endif
};
static inline off_t
fiob_ceil(off_t off)
{
/* ceil to FIOB_ALIGN */
return (off + FIOB_ALIGN - 1) & ~(off_t) (FIOB_ALIGN - 1);
}
#ifdef HAVE_FUNOPEN
static int
fiob_read(void *cookie, char *buf, int count)
#else
static ssize_t
fiob_read(void *cookie, char *buf, size_t count)
#endif
{
struct fiob *f = (struct fiob *)cookie;
ssize_t to_read = (ssize_t) count;
/* The number of starting bytes in f->buf to skip due to alignment */
off_t skip = 0;
while (to_read > 0) {
/* Align `to_read' FIOB_ALIGN to be <= size of f->buf */
ssize_t to_read_al = MIN(fiob_ceil(to_read), f->bsize);
/*
* Optimistically try to read aligned size into the aligned
* buffer. If the current file position is not aligned then
* read(2) returns EINVAL. In this case seek to an aligned
* position and try again. This trick saves one extra
* syscall for general workflow.
*/
ssize_t nrd = read(f->fd, f->buf, to_read_al);
if (nrd < 0) {
if (errno == EINTR) {
errno = 0;
continue;
} else if (errno == EINVAL && skip == 0) {
/*
* read(2) can return EINVAL only in 3 cases:
* 1. read buffer is not aligned - handled in
* fiob_open().
* 2. read size is not aligned - handled above
* 3. current file position is not aligned -
* handled here.
*/
off_t pos = lseek(f->fd, 0, SEEK_CUR);
if (pos < 0) {
say_syserror("lseek, [%s]", f->path);
return -1;
}
/* Calculate aligned position */
skip = pos % FIOB_ALIGN;
pos -= skip;
if (skip == 0) {
/* Position is aligned. */
errno = EINVAL;
say_error("read, [%s]", f->path);
return -1;
}
/* Seek to the new position */
if (lseek(f->fd, pos, SEEK_SET) != pos) {
say_syserror("lseek, [%s]", f->path);
return -1;
}
/* Try to read again. */
continue;
}
say_syserror("read, [%s]", f->path);
return -1; /* XXX: file position is unspecified */
}
/* Ignore starting bytes if the position was aligned. */
nrd -= skip;
if (nrd == 0)
break;
if (nrd > to_read) {
/*
* A few more bytes have been read because `to_read'
* is not aligned to FIOB_ALIGN. Set the file position
* to the expected libc value and ignore extra bytes.
*/
if (lseek(f->fd, to_read - nrd, SEEK_CUR) < 0) {
say_syserror("lseek, [%s]", f->path);
return -1;
}
nrd = to_read;
}
memcpy(buf, f->buf + skip, nrd); /* see nrd -= skip */
skip = 0; /* reset alignment offset */
buf += nrd;
to_read -= nrd;
}
return count - to_read;
}
static ssize_t
fiob_writef(struct fiob *f, const char *buf, size_t count)
{
int fd = f->fd;
ssize_t to_write = (ssize_t) count;
while (to_write > 0) {
ssize_t nwr = write(fd, buf, to_write);
if (nwr < 0) {
if (errno == EINTR) {
errno = 0;
continue;
}
say_syserror("write, [%s]", f->path);
return -1; /* XXX: file position is unspecified */
}
if (nwr == 0)
break;
buf += nwr;
to_write -= nwr;
}
return count - to_write;
}
static int
fiob_flushb(struct fiob *f)
{
if (!f->bfill)
return 0;
size_t tlen = fiob_ceil(f->bfill);
if (fiob_writef(f, f->buf, tlen) < 0) {
return -1;
}
off_t size = lseek(f->fd, (off_t)(f->bfill) - tlen, SEEK_CUR);
if (size == (off_t)-1) {
return -1;
}
int res = ftruncate(f->fd, size);
f->bfill = 0;
return res;
}
#ifdef HAVE_FUNOPEN
int
fiob_write(void *cookie, const char *buf, int len)
#else
ssize_t
fiob_write(void *cookie, const char *buf, size_t len)
#endif
{
struct fiob *f = (struct fiob *)cookie;
if (len == 0)
return 0;
ssize_t bytes_left = len;
ssize_t tocopy;
if (f->bfill < f->bsize) {
ssize_t available_buf_size = f->bsize - f->bfill;
tocopy = available_buf_size > bytes_left ?
bytes_left : available_buf_size;
memcpy(f->buf + f->bfill, buf, tocopy);
bytes_left -= tocopy;
buf += tocopy;
f->bfill += tocopy;
}
while (bytes_left > 0) {
assert(f->bfill == f->bsize);
ssize_t res = fiob_writef(f, f->buf, f->bsize);
if (res < 0)
#if defined(HAVE_FUNOPEN)
return res;
#else
return 0;
#endif
tocopy = f->bsize > bytes_left ? bytes_left : f->bsize;
/*
* We must memcpy because O_DIRECT requires
* an aligned chunk.
*/
memcpy(f->buf, buf, tocopy);
bytes_left -= tocopy;
buf += tocopy;
f->bfill = tocopy;
}
return len;
}
#ifdef HAVE_FUNOPEN
static fpos_t
fiob_seek(void *cookie, fpos_t pos, int whence)
{
struct fiob *f = (struct fiob *)cookie;
if (fiob_flushb(f) < 0)
return -1;
return lseek(f->fd, pos, whence);
}
#else
static int
fiob_seek(void *cookie, off64_t *pos, int whence)
{
struct fiob *f = (struct fiob *)cookie;
if (fiob_flushb(f) < 0)
return -1;
off_t newpos = lseek(f->fd, *pos, whence);
if (newpos == (off_t)-1)
return -1;
*pos = newpos;
return 0;
}
#endif
static int
fiob_close(void *cookie)
{
struct fiob *f = (struct fiob *)cookie;
int res = fiob_flushb(f);
int save_errno = errno;
if (close(f->fd) < 0 && res == 0) {
res = -1;
save_errno = errno;
}
free(f->buf);
free(f->path);
free(f);
errno = save_errno;
return res;
}
#endif /* defined(FIOB_DIRECT) */
/** open file. The same as fopen but receives additional open (2) flags */
FILE *
fiob_open(const char *path, const char *mode)
{
int omode = 0666;
int flags = 0;
int save_errno;
int fd = -1;
FILE *file = NULL;
#if defined (FIOB_DIRECT)
struct fiob *f = NULL;
#endif /* defined(FIOB_DIRECT) */
int um = umask(0722);
umask(um);
omode &= ~um;
if (strchr(mode, 'r')) {
if (strchr(mode, '+'))
flags |= O_RDWR;
else
flags |= O_RDONLY;
} else if (strchr(mode, 'w')) {
flags |= O_TRUNC | O_CREAT;
if (strchr(mode, '+'))
flags |= O_RDWR;
else
flags |= O_WRONLY;
} else if (strchr(mode, 'a')) {
flags |= O_CREAT | O_APPEND;
if (strchr(mode, '+'))
flags |= O_RDWR;
else
flags |= O_WRONLY;
} else {
errno = EINVAL;
return NULL;
}
/* O_EXCL */
#ifdef O_EXCL
if (strchr(mode, 'x'))
flags |= O_EXCL;
#endif
/* O_SYNC */
if (strchr(mode, 's')) {
flags |= WAL_SYNC_FLAG;
}
fd = open(path, flags, omode);
if (fd < 0)
goto error;
#if defined(FIOB_DIRECT)
if (strchr(mode, 'd') == NULL)
goto fdopen;
/* Try to enable O_DIRECT */
flags = fcntl(fd, F_GETFL);
if (flags != -1 && fcntl(fd, F_SETFL, flags | O_DIRECT) != -1) {
say_debug("using O_DIRECT for %s", path);
} else {
#if defined(NDEBUG) /* Don't use opencookie in release mode without O_DIRECT */
goto fdopen;
#endif /* defined(NDEBUG) */
}
f = (struct fiob *)calloc(1, sizeof(struct fiob));
if (!f)
goto error;
f->fd = fd;
f->bsize = FIOB_BSIZE;
if (posix_memalign(&f->buf, FIOB_ALIGN, f->bsize))
goto error;
/* for valgrind */
memset(f->buf, 0, f->bsize);
f->path = strdup(path);
if (!f->path)
goto error;
f->io.read = fiob_read;
f->io.write = fiob_write;
f->io.seek = fiob_seek;
f->io.close = fiob_close;
#ifdef HAVE_FUNOPEN
file = funopen(f,
f->io.read, f->io.write, f->io.seek, f->io.close);
#else
file = fopencookie(f, mode, f->io);
#endif
if (!file)
goto error;
#ifdef TARGET_OS_LINUX
file->_fileno = f->fd;
#else
file->_file = f->fd;
#endif
return file;
fdopen:
#endif /* defined(FIOB_DIRECT) */
/* Fallback to libc implementation */
file = fdopen(fd, mode);
if (!file)
goto error;
return file;
error:
save_errno = errno;
say_syserror("Can't open '%s'", path);
if (fd >= 0)
close(fd);
#if defined(FIOB_DIRECT)
if (f) {
free(f->buf);
free(f->path);
free(f);
}
#endif /* FIOB_DIRECT */
errno = save_errno;
return NULL;
}
| 2.515625 | 3 |
2024-11-18T21:10:22.319321+00:00
| 2019-02-21T22:28:42 |
84e2df002d341770fefd91073184b81f5ec2574a
|
{
"blob_id": "84e2df002d341770fefd91073184b81f5ec2574a",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-21T22:28:42",
"content_id": "377e86d5c2b5542e536a90eb8694f890019074bd",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "dbe74fdf6bded2ceb98eec965fe05ddf7d6dd931",
"extension": "c",
"filename": "spi.c",
"fork_events_count": 27,
"gha_created_at": "2013-08-13T14:59:47",
"gha_event_created_at": "2019-01-02T17:22:41",
"gha_language": "Java",
"gha_license_id": "BSD-3-Clause",
"github_id": 12084628,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4873,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/models/Minitower/components/CAN_Driver/spi/src/spi.c",
"provenance": "stackv2-0065.json.gz:39193",
"repo_name": "smaccm/smaccm",
"revision_date": "2019-02-21T22:28:42",
"revision_id": "7393c423b5aca1a272a88cbb89b5dcfd08a5a47c",
"snapshot_id": "7f79bf5fe74bb1b856d69625fab4ffb1e138101e",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/smaccm/smaccm/7393c423b5aca1a272a88cbb89b5dcfd08a5a47c/models/Minitower/components/CAN_Driver/spi/src/spi.c",
"visit_date": "2021-01-23T15:51:42.639585"
}
|
stackv2
|
/*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(NICTA_BSD)
*/
#include <spi_inf.h>
#include <platsupport/spi.h>
#include <platsupport/gpio.h>
#include <utils.h>
#include <string.h>
#include <camkes.h>
#include <errno.h>
#include <common.h>
#define SPI_PORT SPI1
#define SPI_SPEED_DEFAULT 10000000
#define SPI_CS_RELEASE 1
#define SPI_CS_ASSERT 0
struct spi_slave_params {
int id;
spi_dev_port_p* port;
int speed_hz;
int nss_usdelay;
void (*cs)(int state);
};
/**
* Slave parameters. An ID in the table should match the id of an incoming request
*/
#define SLAVE_PARAMS(i, p, s, d, g) \
{ \
.id = i, \
.port = (spi_dev_port_p*)p, \
.speed_hz = s, \
.nss_usdelay = d, \
.cs = g \
}
const static struct spi_slave_params slave_params[] = {
SLAVE_PARAMS(CAN_APP_ID, &spi1_can, 10000000, 10, &gpio_spi_can_nss),
SLAVE_PARAMS(-1 , NULL , 0, 0, &gpio_spi_mpu_nss),
SLAVE_PARAMS(-1 , NULL , 0, 0, &gpio_spi_acc_mag_nss),
SLAVE_PARAMS(-1 , NULL , 0, 0, &gpio_spi_gyro_nss),
SLAVE_PARAMS(-1 , NULL , 0, 0, &gpio_spi_baro_nss),
SLAVE_PARAMS(-1 , NULL , 0, 0, &gpio_spi_ext_nss)
};
/// A handle to the SPI bus that this component drives
static spi_bus_t* spi_bus;
/// The current speed of the bus to avoid unnecessary recalibration
static long spi_cur_speed;
/**
* Pulls the slave configuration from the database
*/
static const struct spi_slave_params*
get_slave_config(int id)
{
int i;
for(i = 0; i < ARRAY_SIZE(slave_params); i++){
if(slave_params[i].id == id){
return &slave_params[i];
}
}
return NULL;
}
static inline void
chip_select(const struct spi_slave_params* cfg, int state)
{
cfg->cs(state);
udelay(cfg->nss_usdelay);
}
static inline void
set_speed(const struct spi_slave_params* cfg)
{
if(spi_cur_speed != cfg->speed_hz){
clktree_set_spi1_freq(cfg->speed_hz);
spi_cur_speed = cfg->speed_hz;
}
}
/**
* SPI driver calls this when the transfer is complete.
* All we need to do is store the status and post on the semaphore
* that the main thread is waiting on.
*/
static void
spi_complete_callback(spi_bus_t* bus, int status, void* token)
{
*(int*)token = status;
bus_sem_post();
}
/**
* Called on every SPI IRQ. Redirect control to the driver
*/
void
spi1_int_handle(void)
{
spi_handle_irq(spi_bus);
spi1_int_acknowledge();
}
/* Camkes entry point */
void
spi__init(void)
{
int err;
clktree_set_spi1_freq(SPI_SPEED_DEFAULT);
spi_cur_speed = SPI_SPEED_DEFAULT;
/* Initialise the SPI bus */
err = exynos_spi_init(SPI_PORT, spi1_reg, NULL, NULL, &spi_bus);
assert(!err);
if(err){
LOG_ERROR("Failed to initialise SPI port\n");
return;
}
/* Prime the semaphore such that the first call to 'wait' will block */
bus_sem_wait();
/* Register an IRQ callback for the driver */
spi1_int_acknowledge();
}
/**
* Performs an SPI transfer
*/
static int
do_spi_transfer(const struct spi_slave_params* cfg, void* txbuf, unsigned int wcount,
void* rxbuf, unsigned int rcount)
{
int ret;
int status;
set_speed(cfg);
chip_select(cfg, SPI_CS_ASSERT);
/* Begin the transfer */
ret = spi_xfer(spi_bus, txbuf, wcount, rxbuf, rcount, spi_complete_callback, &status);
if(ret >= 0){
bus_sem_wait();
ret = status;
}
chip_select(cfg, SPI_CS_RELEASE);
return ret;
}
/**
* Initiate the transfer of shared data
*/
int
spi_transfer(int id, unsigned int wcount, unsigned int rcount)
{
const struct spi_slave_params* cfg;
/* Find the slave configuration */
cfg = get_slave_config(id);
assert(cfg);
if(cfg == NULL){
return -1;
}
/* Transfer the data from the shared data port */
return do_spi_transfer(cfg, (*cfg->port)->txbuf, wcount, (*cfg->port)->rxbuf, rcount);
}
/**
* Initiate the transfer of a single byte, passed as an argument. Return the byte received.
*/
int
spi_transfer_byte(int id, char byte)
{
const struct spi_slave_params* cfg;
char data[2];
int ret;
/* Find the slave configuration */
cfg = get_slave_config(id);
assert(cfg);
if(cfg == NULL){
return -1;
}
/* Transfer the data from the provided arguments */
ret = do_spi_transfer(cfg, &byte, 1, data, 1);
if(ret < 0){
return ret;
}else{
return data[1];
}
}
| 2.203125 | 2 |
2024-11-18T21:10:22.363250+00:00
| 2018-02-17T00:05:31 |
bf0426e40472b69bcf75764a734a636b11068f7e
|
{
"blob_id": "bf0426e40472b69bcf75764a734a636b11068f7e",
"branch_name": "refs/heads/windows",
"committer_date": "2018-02-17T00:05:31",
"content_id": "6722b42e8ad14b30e8f0dce1b3ab7d7bb70bbd25",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a7803d38c49c393009bd85ce54659bb8678840b8",
"extension": "c",
"filename": "query.c",
"fork_events_count": 1,
"gha_created_at": "2017-10-21T16:00:43",
"gha_event_created_at": "2021-08-06T09:12:35",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 107794254,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 47310,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/runtime/flang/query.c",
"provenance": "stackv2-0065.json.gz:39321",
"repo_name": "isuruf/flang",
"revision_date": "2018-02-17T00:05:31",
"revision_id": "e160efee8cd4603f57ad2fcab5f3ab42c6ada972",
"snapshot_id": "6f86265a529a22859f352bf4d528f6032c5d765e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/isuruf/flang/e160efee8cd4603f57ad2fcab5f3ab42c6ada972/runtime/flang/query.c",
"visit_date": "2022-06-13T19:20:55.548223"
}
|
stackv2
|
/*
* Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/* clang-format off */
/* hpf_library, hpf_local_library, and system inquiry routines */
/* FIXME: how much (if any) of this is used/needed */
#include "stdioInterf.h"
#include "fioMacros.h"
static int I8(fetch_int)(void *b, F90_Desc *s)
{
dtype kind = TYPEKIND(s);
switch (kind) {
case __INT1:
return (int)(*(__INT1_T *)b);
case __INT2:
return (int)(*(__INT2_T *)b);
case __INT4:
return (int)(*(__INT4_T *)b);
case __INT8:
return (int)(*(__INT8_T *)b);
default:
__fort_abort("fetch_int: invalid argument type");
return 0;
}
}
static int I8(fetch_log)(void *b, F90_Desc *s)
{
dtype kind = TYPEKIND(s);
switch (kind) {
case __LOG1:
return (*(__LOG1_T *)b & GET_DIST_MASK_LOG1) != 0;
case __LOG2:
return (*(__LOG2_T *)b & GET_DIST_MASK_LOG2) != 0;
case __LOG4:
return (*(__LOG4_T *)b & GET_DIST_MASK_LOG4) != 0;
case __LOG8:
return (*(__LOG8_T *)b & GET_DIST_MASK_LOG8) != 0;
default:
__fort_abort("fetch_log: invalid argument type");
return 0;
}
}
static void I8(fetch_vector)(void *ab, F90_Desc *as, __INT_T *vector,
int veclen)
{
__INT_T *la;
__INT_T i;
if (F90_RANK_G(as) != 1)
__fort_abort("fetch_vector: incorrect argument rank");
for (i = F90_DIM_LBOUND_G(as, 0); --veclen >= 0; ++i) {
la = I8(__fort_local_address)(ab, as, &i);
if (la == NULL)
__fort_abort("fetch_vector: argument inaccessible");
*vector++ = I8(fetch_int)(la, as);
}
}
static void I8(store_int)(void *b, F90_Desc *s, __INT_T val)
{
dtype kind = TYPEKIND(s);
switch (kind) {
case __INT1:
*(__INT1_T *)b = (__INT1_T)val;
break;
case __INT2:
*(__INT2_T *)b = (__INT2_T)val;
break;
case __INT4:
*(__INT4_T *)b = (__INT4_T)val;
break;
case __INT8:
*(__INT8_T *)b = (__INT8_T)val;
break;
default:
__fort_abort("store_int: invalid argument type (integer expected)");
}
}
static void I8(store_log)(void *b, F90_Desc *s, int val)
{
dtype kind = TYPEKIND(s);
switch (kind) {
case __LOG1:
*(__LOG1_T *)b = val ? GET_DIST_TRUE_LOG1 : 0;
break;
case __LOG2:
*(__LOG2_T *)b = val ? GET_DIST_TRUE_LOG2 : 0;
break;
case __LOG4:
*(__LOG4_T *)b = val ? GET_DIST_TRUE_LOG4 : 0;
break;
case __LOG8:
*(__LOG8_T *)b = val ? GET_DIST_TRUE_LOG8 : 0;
break;
default:
__fort_abort("store_log: invalid argument type (logical expected)");
}
}
static void I8(store_element)(void *ab, F90_Desc *as, int index, int val)
{
__INT_T *la;
__INT_T i;
if (F90_RANK_G(as) != 1)
__fort_abort("store_element: incorrect argument rank");
i = F90_DIM_LBOUND_G(as, 0) - 1 + index;
la = I8(__fort_local_address)(ab, as, &i);
if (la != NULL)
I8(store_int)(la, as, val);
}
static void I8(store_vector)(void *ab, F90_Desc *as, __INT_T *vector,
__INT_T veclen)
{
__INT_T *la;
__INT_T i;
if (F90_RANK_G(as) != 1)
__fort_abort("store_vector: incorrect argument rank");
for (i = F90_DIM_LBOUND_G(as, 0); --veclen >= 0; ++i) {
la = I8(__fort_local_address)(ab, as, &i);
if (la != NULL)
I8(store_int)(la, as, *vector);
++vector;
}
}
static void I8(store_vector_int)(void *ab, F90_Desc *as, int *vector,
__INT_T veclen)
{
__INT_T *la;
__INT_T i;
if (F90_RANK_G(as) != 1)
__fort_abort("store_vector_int: incorrect argument rank");
for (i = F90_DIM_LBOUND_G(as, 0); --veclen >= 0; ++i) {
la = I8(__fort_local_address)(ab, as, &i);
if (la != NULL)
I8(store_int)(la, as, *vector);
++vector;
}
}
static void ftnstrcpy(char *dst, /* destination string, blank-filled */
int len, /* length of destination space */
char *src) /* null terminated source string */
{
char *end = dst + len;
while (dst < end && *src != '\0')
*dst++ = *src++;
while (dst < end)
*dst++ = ' ';
}
/* FIXME: still used ? */
/* hpf_library mapping inquiry routines */
void ENTFTN(DIST_ALIGNMENT,
dist_alignment)(void *alignee_b, void *lb, void *ub, void *stride,
void *axis_map, void *identity_map, void *dynamic,
void *ncopies, F90_Desc *alignee, F90_Desc *lb_s,
F90_Desc *ub_s, F90_Desc *stride_s,
F90_Desc *axis_map_s, F90_Desc *identity_map_s,
F90_Desc *dynamic_s, F90_Desc *ncopies_s)
{
DECL_DIM_PTRS(ad);
proc *p;
procdim *pd;
__INT_T aextent, i, idm, ncp, px, rank, textent, vector[MAXDIMS];
rank = (F90_TAG_G(alignee) == __DESC) ? F90_RANK_G(alignee) : 0;
if (ISPRESENT(lb)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ad, alignee, i);
vector[i] = DIST_DPTR_TSTRIDE_G(ad) * F90_DPTR_LBOUND_G(ad) +
DIST_DPTR_TOFFSET_G(ad) - DIST_DPTR_TLB_G(ad) + 1;
}
I8(store_vector)(lb, lb_s, vector, rank);
}
if (ISPRESENT(ub)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ad, alignee, i);
vector[i] = DIST_DPTR_TSTRIDE_G(ad) * DPTR_UBOUND_G(ad) +
DIST_DPTR_TOFFSET_G(ad) - DIST_DPTR_TLB_G(ad) + 1;
}
I8(store_vector)(ub, ub_s, vector, rank);
}
if (ISPRESENT(stride)) {
for (i = rank; --i >= 0;) {
if (DFMT(alignee, i + 1) != DFMT_COLLAPSED) {
SET_DIM_PTRS(ad, alignee, i);
vector[i] = DIST_DPTR_TSTRIDE_G(ad);
} else {
vector[i] = 0;
}
}
I8(store_vector)(stride, stride_s, vector, rank);
}
if (ISPRESENT(axis_map)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ad, alignee, i);
vector[i] = DIST_DPTR_TAXIS_G(ad);
}
I8(store_vector)(axis_map, axis_map_s, vector, rank);
}
if (ISPRESENT(identity_map)) {
idm = (rank == 0 || rank == F90_RANK_G(DIST_ALIGN_TARGET_G(alignee)));
for (i = rank; idm && --i >= 0;) {
SET_DIM_PTRS(ad, alignee, i);
idm = (DIST_DPTR_TAXIS_G(ad) == i + 1 && DIST_DPTR_TSTRIDE_G(ad) == 1 &&
F90_DPTR_LBOUND_G(ad) == DIST_DPTR_TLB_G(ad) &&
DPTR_UBOUND_G(ad) == DIST_DPTR_TUB_G(ad));
}
I8(store_log)(identity_map, identity_map_s, idm);
}
if (ISPRESENT(dynamic)) {
I8(store_log)(dynamic, dynamic_s, (rank > 0 && F90_FLAGS_G(alignee) & __DYNAMIC));
}
if (ISPRESENT(ncopies)) {
if (rank > 0) {
p = DIST_DIST_TARGET_G(alignee);
ncp = 1;
for (px = 0; px < p->rank; ++px) {
if (DIST_REPLICATED_G(alignee) >> px & 1) {
pd = &p->dim[px];
ncp *= pd->shape;
}
}
} else
ncp = GET_DIST_TCPUS;
I8(store_int)(ncopies, ncopies_s, ncp);
}
}
/* FIXME: still used */
void ENTFTN(DIST_DISTRIBUTION, dist_distribution)(
void *distributee_b, DCHAR(axis_type), void *axis_info, void *proc_rank,
void *proc_shape, void *plb, void *pub, void *pstride, void *low_shadow,
void *high_shadow, F90_Desc *distributee, F90_Desc *axis_type_s,
F90_Desc *axis_info_s, F90_Desc *proc_rank_s, F90_Desc *proc_shape_s,
F90_Desc *plb_s, F90_Desc *pub_s, F90_Desc *pstride_s,
F90_Desc *low_shadow_s, F90_Desc *high_shadow_s DCLEN(axis_type))
{
DECL_HDR_PTRS(u);
DECL_DIM_PTRS(ud);
DECL_DIM_PTRS(dd);
proc *p;
procdim *pd;
__INT_T i, len, rank, vector[MAXDIMS];
char *src;
if (F90_TAG_G(distributee) == __DESC) {
u = DIST_ALIGN_TARGET_G(distributee);
p = DIST_DIST_TARGET_G(distributee);
rank = F90_RANK_G(u);
} else {
u = NULL;
p = NULL;
rank = 0;
}
if (ISPRESENTC(axis_type)) {
len = CLEN(axis_type);
for (i = rank; i > 0; --i) {
switch (DFMT(u, i)) {
case DFMT_COLLAPSED:
src = "COLLAPSED";
break;
case DFMT_BLOCK:
case DFMT_BLOCK_K:
src = "BLOCK";
break;
case DFMT_CYCLIC:
case DFMT_CYCLIC_K:
src = "CYCLIC";
break;
case DFMT_GEN_BLOCK:
src = "GEN_BLOCK";
break;
case DFMT_INDIRECT:
src = "INDIRECT";
break;
default:
__fort_abort("DIST_DISTRIBUTION: unsupported dist-format");
}
ftnstrcpy(CADR(axis_type) + (i - 1) * len, len, src);
}
}
if (ISPRESENT(axis_info)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = DIST_DPTR_BLOCK_G(ud);
}
I8(store_vector)(axis_info, axis_info_s, vector, rank);
}
if (ISPRESENT(proc_rank)) {
I8(store_int)(proc_rank, proc_rank_s, p != NULL ? p->rank : 0);
}
if (ISPRESENT(proc_shape) && p != NULL) {
for (i = p->rank; --i >= 0;) {
pd = &p->dim[i];
vector[i] = pd->shape;
}
I8(store_vector)(proc_shape, proc_shape_s, vector, p->rank);
}
if (ISPRESENT(plb)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = 1;
}
I8(store_vector)(plb, plb_s, vector, rank);
}
if (ISPRESENT(pub)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = DIST_DPTR_PSHAPE_G(ud);
}
I8(store_vector)(pub, pub_s, vector, rank);
}
if (ISPRESENT(pstride)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = DIST_DPTR_PSTRIDE_G(ud);
}
I8(store_vector)(pstride, pstride_s, vector, rank);
}
/* Return low_shadow and high_shadow values for the 'distributee'
argument. HPF 2 spec makes no sense where it says these should
come from the distributee's ultimate align target. */
rank = (F90_TAG_G(distributee) == __DESC) ? F90_RANK_G(distributee) : 0;
if (ISPRESENT(low_shadow)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(dd, distributee, i);
vector[i] = DIST_DPTR_NO_G(dd);
}
I8(store_vector)(low_shadow, low_shadow_s, vector, rank);
}
if (ISPRESENT(high_shadow)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(dd, distributee, i);
vector[i] = DIST_DPTR_PO_G(dd);
}
I8(store_vector)(high_shadow, high_shadow_s, vector, rank);
}
}
/* FIXME: not used */
void ENTFTN(DIST_TEMPLATE,
dist_template)(void *alignee_b, void *template_rank, void *lb,
void *ub, DCHAR(axis_type), void *axis_info,
void *number_aligned, void *dynamic,
F90_Desc *alignee, F90_Desc *template_rank_s,
F90_Desc *lb_s, F90_Desc *ub_s, F90_Desc *axis_type_s,
F90_Desc *axis_info_s, F90_Desc *number_aligned_s,
F90_Desc *dynamic_s DCLEN(axis_type))
{
DECL_HDR_PTRS(u);
DECL_HDR_PTRS(a);
DECL_DIM_PTRS(ud);
proc *p;
__INT_T i, rank, len, n_alnd, ux;
__INT_T alignee_axis[MAXDIMS], vector[MAXDIMS];
char *src;
if (F90_TAG_G(alignee) == __DESC) {
u = DIST_ALIGN_TARGET_G(alignee);
p = DIST_DIST_TARGET_G(alignee);
rank = F90_RANK_G(u);
for (i = rank; --i >= 0;)
alignee_axis[i] = 0;
for (i = F90_RANK_G(alignee); --i >= 0;) {
ux = DIST_DIM_TAXIS_G(alignee, i);
if (ux > 0)
alignee_axis[ux - 1] = i + 1;
}
} else
rank = 0;
if (ISPRESENT(template_rank)) {
I8(store_int)(template_rank, template_rank_s, rank);
}
if (ISPRESENT(lb)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = F90_DPTR_LBOUND_G(ud);
}
I8(store_vector)(lb, lb_s, vector, rank);
}
if (ISPRESENT(ub)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = DPTR_UBOUND_G(ud);
}
I8(store_vector)(ub, ub_s, vector, rank);
}
if (ISPRESENTC(axis_type)) {
len = CLEN(axis_type);
for (i = rank; --i >= 0;) {
if (alignee_axis[i] > 0)
src = "NORMAL";
else if (DIST_SINGLE_G(alignee) >> i & 1)
src = "SINGLE";
else
src = "REPLICATED";
ftnstrcpy(CADR(axis_type) + i * len, len, src);
}
}
if (ISPRESENT(axis_info)) {
for (i = rank; --i >= 0;) {
if (alignee_axis[i] > 0)
vector[i] = alignee_axis[i];
else if (DIST_SINGLE_G(alignee) >> i & 1)
vector[i] = DIST_INFO_G(alignee, i);
else {
SET_DIM_PTRS(ud, u, i);
vector[i] = (DIST_DPTR_PAXIS_G(ud) > 0) ? DIST_DPTR_PSHAPE_G(ud) : 1;
}
}
I8(store_vector)(axis_info, axis_info_s, vector, rank);
}
if (ISPRESENT(number_aligned)) {
if (!(F90_FLAGS_G(u) & __DYNAMIC)) {
__fort_abort(
"DIST_TEMPLATE: NUMBER_ALIGNED not supported for static align target");
}
n_alnd = 0;
if (rank > 0) {
if (u)
for (a = DIST_NEXT_ALIGNEE_G(u); a != NULL; a = DIST_NEXT_ALIGNEE_G(a)) {
++n_alnd;
}
}
I8(store_int)(number_aligned, number_aligned_s, n_alnd);
}
if (ISPRESENT(dynamic)) {
I8(store_log)(dynamic, dynamic_s, rank > 0 && F90_FLAGS_G(u) & __DYNAMIC);
}
}
void ENTFTN(GLOBAL_ALIGNMENT,
global_alignment)(void *array_b, void *lb, void *ub, void *stride,
void *axis_map, void *identity_map, void *dynamic,
void *ncopies, F90_Desc *array_s, F90_Desc *lb_s,
F90_Desc *ub_s, F90_Desc *stride_s,
F90_Desc *axis_map_s, F90_Desc *identity_map_s,
F90_Desc *dynamic_s, F90_Desc *ncopies_s)
{
DECL_HDR_PTRS(alignee);
DECL_DIM_PTRS(ad);
proc *p;
__INT_T i, idm, n, rank, vector[MAXDIMS];
if (F90_TAG_G(array_s) == __DESC) {
alignee = DIST_ACTUAL_ARG_G(array_s);
if (alignee == NULL)
__fort_abort("GLOBAL_ALIGNMENT: array is not associated"
" with global actual argument");
rank = F90_RANK_G(alignee);
} else
rank = 0;
if (ISPRESENT(lb)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ad, alignee, i);
vector[i] = DIST_DPTR_TSTRIDE_G(ad) * F90_DPTR_LBOUND_G(ad) +
DIST_DPTR_TOFFSET_G(ad) - DIST_DPTR_TLB_G(ad) + 1;
}
I8(store_vector)(lb, lb_s, vector, rank);
}
if (ISPRESENT(ub)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ad, alignee, i);
vector[i] = DIST_DPTR_TSTRIDE_G(ad) * DPTR_UBOUND_G(ad) +
DIST_DPTR_TOFFSET_G(ad) - DIST_DPTR_TLB_G(ad) + 1;
}
I8(store_vector)(ub, ub_s, vector, rank);
}
if (ISPRESENT(stride)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ad, alignee, i);
vector[i] = DIST_DPTR_TSTRIDE_G(ad);
}
I8(store_vector)(stride, stride_s, vector, rank);
}
if (ISPRESENT(axis_map)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ad, alignee, i);
vector[i] = DIST_DPTR_TAXIS_G(ad);
}
I8(store_vector)(axis_map, axis_map_s, vector, rank);
}
if (ISPRESENT(identity_map)) {
idm = (rank == 0 || rank == F90_TAG_G(DIST_ALIGN_TARGET_G(alignee)));
for (i = rank; idm && --i >= 0;) {
SET_DIM_PTRS(ad, alignee, i);
idm = (DIST_DPTR_TAXIS_G(ad) == i + 1 && DIST_DPTR_TSTRIDE_G(ad) == 1 &&
F90_DPTR_LBOUND_G(ad) == DIST_DPTR_TLB_G(ad) &&
DPTR_UBOUND_G(ad) == DIST_DPTR_TUB_G(ad));
}
I8(store_log)(identity_map, identity_map_s, idm);
}
if (ISPRESENT(dynamic)) {
I8(store_log)(dynamic, dynamic_s, rank > 0 && F90_FLAGS_G(alignee) & __DYNAMIC);
}
if (ISPRESENT(ncopies)) {
if (rank > 0) {
n = 1;
p = DIST_DIST_TARGET_G(alignee);
for (i = p->rank; --i >= 0;) {
if (DIST_REPLICATED_G(alignee) >> i & 1)
n *= p->dim[i].shape;
}
} else
n = GET_DIST_TCPUS;
I8(store_int)(ncopies, ncopies_s, n);
}
}
void ENTFTN(GLOBAL_DISTRIBUTION, global_distribution)(
void *array_b, DCHAR(axis_type), void *axis_info, void *proc_rank,
void *proc_shape, void *plb, void *pub, void *pstride, void *low_shadow,
void *high_shadow, F90_Desc *array_s, F90_Desc *axis_type_s,
F90_Desc *axis_info_s, F90_Desc *proc_rank_s, F90_Desc *proc_shape_s,
F90_Desc *plb_s, F90_Desc *pub_s, F90_Desc *pstride_s,
F90_Desc *low_shadow_s, F90_Desc *high_shadow_s DCLEN(axis_type))
{
DECL_HDR_PTRS(u);
DECL_HDR_PTRS(distributee);
DECL_DIM_PTRS(ud);
DECL_DIM_PTRS(dd);
proc *p;
procdim *pd;
__INT_T i, rank, len, vector[MAXDIMS];
char *src;
if (F90_TAG_G(array_s) == __DESC) {
distributee = DIST_ACTUAL_ARG_G(array_s);
if (distributee == NULL)
__fort_abort("GLOBAL_DISTRIBUTION: array is not associated"
" with global actual argument");
u = DIST_ALIGN_TARGET_G(distributee);
p = DIST_DIST_TARGET_G(distributee);
rank = F90_RANK_G(u);
} else {
distributee = NULL;
u = NULL;
p = NULL;
rank = 0;
}
if (ISPRESENTC(axis_type)) {
len = CLEN(axis_type);
for (i = rank; i > 0; --i) {
switch (DFMT(u, i)) {
case DFMT_COLLAPSED:
src = "COLLAPSED";
break;
case DFMT_BLOCK:
case DFMT_BLOCK_K:
src = "BLOCK";
break;
case DFMT_CYCLIC:
case DFMT_CYCLIC_K:
src = "CYCLIC";
break;
case DFMT_GEN_BLOCK:
src = "GEN_BLOCK";
break;
case DFMT_INDIRECT:
src = "INDIRECT";
break;
default:
__fort_abort("GLOBAL_DISTRIBUTION: unsupported dist-format");
}
ftnstrcpy(CADR(axis_type) + (i - 1) * len, len, src);
}
}
if (ISPRESENT(axis_info)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = DIST_DPTR_BLOCK_G(ud);
}
I8(store_vector)(axis_info, axis_info_s, vector, rank);
}
if (ISPRESENT(proc_rank)) {
I8(store_int)(proc_rank, proc_rank_s, p != NULL ? p->rank : 0);
}
if (ISPRESENT(proc_shape) && p != NULL) {
for (i = p->rank; --i >= 0;) {
pd = &p->dim[i];
vector[i] = pd->shape;
}
I8(store_vector)(proc_shape, proc_shape_s, vector, p->rank);
}
if (ISPRESENT(plb)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = 1;
}
I8(store_vector)(plb, plb_s, vector, rank);
}
if (ISPRESENT(pub)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = DIST_DPTR_PSHAPE_G(ud);
}
I8(store_vector)(pub, pub_s, vector, rank);
}
if (ISPRESENT(pstride)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = DIST_DPTR_PSTRIDE_G(ud);
}
I8(store_vector)(pstride, pstride_s, vector, rank);
}
/* Return low_shadow and high_shadow values for the 'distributee'
argument. HPF 2 spec makes no sense where it says these should
come from the distributee's ultimate align target. */
rank = (distributee != NULL && F90_TAG_G(distributee) == __DESC)
? F90_RANK_G(distributee)
: 0;
if (ISPRESENT(low_shadow)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(dd, distributee, i);
vector[i] = DIST_DPTR_NO_G(dd);
}
I8(store_vector)(low_shadow, low_shadow_s, vector, rank);
}
if (ISPRESENT(high_shadow)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(dd, distributee, i);
vector[i] = DIST_DPTR_PO_G(dd);
}
I8(store_vector)(high_shadow, high_shadow_s, vector, rank);
}
}
void ENTFTN(GLOBAL_TEMPLATE, global_template)(
void *array_b, void *template_rank, void *lb, void *ub, DCHAR(axis_type),
void *axis_info, void *number_aligned, void *dynamic, F90_Desc *array_s,
F90_Desc *template_rank_s, F90_Desc *lb_s, F90_Desc *ub_s,
F90_Desc *axis_type_s, F90_Desc *axis_info_s, F90_Desc *number_aligned_s,
F90_Desc *dynamic_s DCLEN(axis_type))
{
DECL_HDR_PTRS(u);
DECL_HDR_PTRS(alignee);
DECL_HDR_PTRS(a);
DECL_DIM_PTRS(ud);
proc *p;
__INT_T i, rank, len, n_alnd, ux;
__INT_T alignee_axis[MAXDIMS], vector[MAXDIMS];
char *src;
if (F90_TAG_G(array_s) == __DESC) {
alignee = DIST_ACTUAL_ARG_G(array_s);
if (alignee == NULL)
__fort_abort("GLOBAL_TEMPLATE: array is not associated"
" with global actual argument");
u = DIST_ALIGN_TARGET_G(alignee);
p = DIST_DIST_TARGET_G(alignee);
rank = F90_RANK_G(u);
for (i = rank; --i >= 0;)
alignee_axis[i] = 0;
for (i = F90_RANK_G(alignee); --i >= 0;) {
ux = DIST_DIM_TAXIS_G(alignee, i);
if (ux > 0)
alignee_axis[ux - 1] = i + 1;
}
} else
rank = 0;
if (ISPRESENT(template_rank)) {
I8(store_int)(template_rank, template_rank_s, rank);
}
if (ISPRESENT(lb)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = F90_DPTR_LBOUND_G(ud);
}
I8(store_vector)(lb, lb_s, vector, rank);
}
if (ISPRESENT(ub)) {
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(ud, u, i);
vector[i] = DPTR_UBOUND_G(ud);
}
I8(store_vector)(ub, ub_s, vector, rank);
}
if (ISPRESENTC(axis_type)) {
len = CLEN(axis_type);
for (i = rank; --i >= 0;) {
if (alignee_axis[i] > 0)
src = "NORMAL";
else if (DIST_SINGLE_G(alignee) >> i & 1)
src = "SINGLE";
else
src = "REPLICATED";
ftnstrcpy(CADR(axis_type) + i * len, len, src);
}
}
if (ISPRESENT(axis_info)) {
for (i = rank; --i >= 0;) {
if (alignee_axis[i] > 0)
vector[i] = alignee_axis[i];
else if (DIST_SINGLE_G(alignee) >> i & 1)
vector[i] = DIST_INFO_G(alignee, i);
else {
SET_DIM_PTRS(ud, u, i);
vector[i] = (DIST_DPTR_PAXIS_G(ud) > 0) ? DIST_DPTR_PSHAPE_G(ud) : 1;
}
}
I8(store_vector)(axis_info, axis_info_s, vector, rank);
}
if (ISPRESENT(number_aligned)) {
n_alnd = 0;
if (rank > 0) {
for (a = u; a != NULL; a = DIST_NEXT_ALIGNEE_G(a))
++n_alnd;
}
I8(store_int)(number_aligned, number_aligned_s, n_alnd);
}
if (ISPRESENT(dynamic)) {
I8(store_log)(dynamic, dynamic_s, rank > 0 && F90_FLAGS_G(u) & __DYNAMIC);
}
}
void ENTFTN(GLOBAL_LBOUND, global_lbound)(void *lbound_b, void *array_b,
void *dim_b, F90_Desc *lbound_s,
F90_Desc *array_s, F90_Desc *dim_s)
{
DECL_HDR_PTRS(g);
__INT_T i, dim, rank, vector[MAXDIMS];
if (F90_TAG_G(array_s) == __DESC) {
g = DIST_ACTUAL_ARG_G(array_s);
if (g == NULL)
__fort_abort("GLOBAL_LBOUND: array is not associated"
" with global actual argument");
rank = F90_RANK_G(g);
} else
rank = 0;
if (ISPRESENT(dim_b)) {
dim = I8(fetch_int)(dim_b, dim_s);
if (dim < 1 || dim > rank)
__fort_abort("GLOBAL_LBOUND: invalid dim");
I8(store_int)(lbound_b, lbound_s, F90_DIM_LBOUND_G(g, dim - 1));
} else {
for (i = rank; --i >= 0;)
vector[i] = F90_DIM_LBOUND_G(g, i);
I8(store_vector)(lbound_b, lbound_s, vector, rank);
}
}
void ENTFTN(GLOBAL_SHAPE, global_shape)(void *shape_b, void *source_b,
F90_Desc *shape_s, F90_Desc *source_s)
{
DECL_HDR_PTRS(g);
DECL_DIM_PTRS(gd);
__INT_T i, extent, rank, vector[MAXDIMS];
if (F90_TAG_G(source_s) == __DESC) {
g = DIST_ACTUAL_ARG_G(source_s);
if (g == NULL)
__fort_abort("GLOBAL_SHAPE: source is not associated with"
" global actual argument");
rank = F90_RANK_G(g);
} else
rank = 0;
for (i = rank; --i >= 0;) {
SET_DIM_PTRS(gd, g, i);
extent = F90_DPTR_EXTENT_G(gd);
if (extent < 0)
extent = 0;
vector[i] = extent;
}
I8(store_vector)(shape_b, shape_s, vector, rank);
}
void ENTFTN(GLOBAL_SIZE, global_size)(void *size_b, void *array_b, void *dim_b,
F90_Desc *size_s, F90_Desc *array_s,
F90_Desc *dim_s)
{
DECL_HDR_PTRS(g);
DECL_DIM_PTRS(gd);
__INT_T i, dim, rank, size;
if (F90_TAG_G(array_s) == __DESC) {
g = DIST_ACTUAL_ARG_G(array_s);
if (g == NULL)
__fort_abort("GLOBAL_SIZE: array is not associated with"
" global actual argument");
rank = F90_RANK_G(g);
SET_DIM_PTRS(gd, g, 0);
} else
rank = 0;
if (ISPRESENT(dim_b)) {
dim = I8(fetch_int)(dim_b, dim_s);
if (dim < 1 || dim > rank)
__fort_abort("GLOBAL_SIZE: invalid dim");
SET_DIM_PTRS(gd, g, dim - 1);
size = F90_DPTR_EXTENT_G(gd);
if (size < 0)
size = 0;
} else if (rank > 0)
size = F90_GSIZE_G(g);
else
size = 1;
I8(store_int)(size_b, size_s, size);
}
void ENTFTN(GLOBAL_UBOUND, global_ubound)(void *ubound_b, void *array_b,
void *dim_b, F90_Desc *ubound_s,
F90_Desc *array_s, F90_Desc *dim_s)
{
DECL_HDR_PTRS(g);
__INT_T i, dim, rank, vector[MAXDIMS];
if (F90_TAG_G(array_s) == __DESC) {
g = DIST_ACTUAL_ARG_G(array_s);
if (g == NULL)
__fort_abort("GLOBAL_UBOUND: array is not associated with"
"global actual argument");
rank = F90_RANK_G(g);
} else
rank = 0;
if (ISPRESENT(dim_b)) {
dim = I8(fetch_int)(dim_b, dim_s);
if (dim < 1 || dim > rank)
__fort_abort("GLOBAL_UBOUND: invalid dim");
I8(store_int)(ubound_b, ubound_s, DIM_UBOUND_G(g, dim - 1));
} else {
for (i = rank; --i >= 0;)
vector[i] = DIM_UBOUND_G(g, i);
I8(store_vector)(ubound_b, ubound_s, vector, rank);
}
}
void ENTFTN(ABSTRACT_TO_PHYSICAL,
abstract_to_physical)(void *array_b, void *index_b, void *proc_b,
F90_Desc *array_s, F90_Desc *index_s,
F90_Desc *proc_s)
{
DECL_HDR_PTRS(g);
proc *p;
procdim *pd;
__INT_T i, index[MAXDIMS], proc;
if (F90_TAG_G(array_s) != __DESC)
__fort_abort("ABSTRACT_TO_PHYSICAL: argument must be array");
g = DIST_ACTUAL_ARG_G(array_s);
if (g == NULL)
__fort_abort("ABSTRACT_TO_PHYSICAL: array is not associated"
" with global actual argument");
p = DIST_DIST_TARGET_G(g);
I8(fetch_vector)(index_b, index_s, index, p->rank);
proc = p->base;
for (i = p->rank; --i >= 0;) {
pd = &p->dim[i];
if (index[i] < 1 || index[i] > pd->shape)
__fort_abort("ABSTRACT_TO_PHYSICAL: invalid processor coordinate");
proc += pd->stride * (index[i] - 1);
}
I8(store_int)(proc_b, proc_s, proc);
}
void ENTFTN(PHYSICAL_TO_ABSTRACT,
physical_to_abstract)(void *array_b, void *proc_b, void *index_b,
F90_Desc *array_s, F90_Desc *proc_s,
F90_Desc *index_s)
{
DECL_HDR_PTRS(g);
proc *p;
procdim *pd;
__INT_T i, index[MAXDIMS], proc;
if (F90_TAG_G(array_s) != __DESC)
__fort_abort("PHYSICAL_TO_ABSTRACT: argument must be array");
g = DIST_ACTUAL_ARG_G(array_s);
if (g == NULL)
__fort_abort("PHYSICAL_TO_ABSTRACT: array is not associated"
" with global actual argument");
p = DIST_DIST_TARGET_G(g);
proc = I8(fetch_int)(proc_b, proc_s);
proc -= p->base;
if (proc < 0 || proc >= p->size)
__fort_abort("PHYSICAL_TO_ABSTRACT: invalid processor number");
for (i = 0; i < p->rank; ++i) {
pd = &p->dim[i];
RECIP_DIVMOD(&proc, &index[i], proc, pd->shape);
index[i]++;
}
I8(store_vector)(index_b, index_s, index, p->rank);
}
/* Translate local indices to global indices */
void ENTFTN(LOCAL_TO_GLOBAL,
local_to_global)(void *array_b, void *l_index_b, void *g_index_b,
F90_Desc *array_s, F90_Desc *l_index_s,
F90_Desc *g_index_s)
{
DECL_HDR_PTRS(gs);
DECL_DIM_PTRS(gsd);
DECL_DIM_PTRS(asd);
__INT_T i, j, local, gof, procno, *procs;
__INT_T index[MAXDIMS], pcoord[MAXDIMS];
__INT_T lb, ub, lof;
__INT_T lboffset, adjindex, cyclenum, cyclepos, gstride;
if (F90_TAG_G(array_s) != __DESC)
__fort_abort("LOCAL_TO_GLOBAL: argument must be array");
gs = DIST_ACTUAL_ARG_G(array_s);
if (gs == NULL || F90_TAG_G(gs) != __DESC)
__fort_abort("LOCAL_TO_GLOBAL: array is not associated with"
" global actual argument");
#if defined(DEBUG)
if (F90_RANK_G(gs) != F90_RANK_G(array_s))
__fort_abort("LOCAL_TO_GLOBAL: global vs. local rank mismatch");
#endif
/* get the local index vector */
I8(fetch_vector)(l_index_b, l_index_s, index, F90_RANK_G(gs));
/* translate local array indices to global array indices */
for (i = 1; i <= F90_RANK_G(gs); ++i) { /* iterate through dimensions */
SET_DIM_PTRS(asd, array_s, i - 1);
SET_DIM_PTRS(gsd, gs, i - 1);
/* index must be within local array bounds */
if (index[i - 1] < F90_DPTR_LBOUND_G(asd) ||
index[i - 1] > DPTR_UBOUND_G(asd)) {
__fort_abort("LOCAL_TO_GLOBAL: index outside local array bounds\n");
}
switch (DFMT(gs, i)) {
case DFMT_CYCLIC:
case DFMT_CYCLIC_K:
if (DIST_DPTR_TSTRIDE_G(gsd) != 1) {
int ii, startblocks, off;
int elem_per_cycle, elem, my_cycle_lb, my_cycle_ub, first;
int tstride, abs_tstride, gblock, pcoord, lbound;
tstride = DIST_DPTR_TSTRIDE_G(gsd);
abs_tstride = Abs(tstride);
gblock = DIST_DPTR_BLOCK_G(gsd);
pcoord = DIST_DPTR_PCOORD_G(gsd);
lbound = F90_DPTR_LBOUND_G(gsd);
off = DIST_DPTR_TOFFSET_G(gsd);
first = (lbound * tstride + off) - 1;
elem = first + 1;
if (tstride < 0) {
int start_cpu, ext, text, partialblocks, tlb, tub, cpus;
tlb = DIST_DPTR_TLB_G(gsd);
tub = DIST_DPTR_TUB_G(gsd);
ext = elem - tlb + 1;
text = tub - tlb + 1;
cpus = Min(DIST_DPTR_PSHAPE_G(gsd), Ceil(text, gblock));
elem_per_cycle = (gblock * cpus);
partialblocks = (ext % elem_per_cycle);
if (!partialblocks) {
start_cpu = cpus - 1;
startblocks = gblock * Abs(pcoord - start_cpu);
} else if (partialblocks <= gblock) {
start_cpu = 0;
startblocks = partialblocks * Abs(pcoord - start_cpu);
if (!startblocks)
startblocks = partialblocks - gblock;
} else {
RECIP_DIV(&start_cpu, partialblocks, DIST_DPTR_BLOCK_G(gsd));
if (start_cpu < 0)
start_cpu += cpus;
else if (start_cpu >= cpus)
start_cpu -= cpus;
startblocks = Abs(pcoord - start_cpu);
startblocks *= (partialblocks - gblock);
}
elem = tub - elem + 1;
first = elem - 1;
} else {
elem_per_cycle = DIST_DPTR_CYCLE_G(gsd);
startblocks = pcoord * gblock;
}
my_cycle_lb = (lbound + startblocks);
if (my_cycle_lb > lbound) {
while (elem > my_cycle_lb)
my_cycle_lb += elem_per_cycle;
}
my_cycle_ub = my_cycle_lb + (gblock - 1);
elem -= abs_tstride;
for (ii = F90_DPTR_LBOUND_G(asd); ii <= index[i - 1];) {
if (elem > my_cycle_ub) {
my_cycle_lb += elem_per_cycle;
my_cycle_ub += elem_per_cycle;
} else
elem += abs_tstride;
if (elem >= my_cycle_lb && elem <= my_cycle_ub) {
++ii;
}
}
index[i - 1] =
(elem - first) / abs_tstride + (elem - first) % abs_tstride;
break;
}
if (DIST_DPTR_OLB_G(gsd) == F90_DPTR_LBOUND_G(gsd)) { /* First element */
lboffset = 0;
} else {
lboffset = 0;
}
adjindex = index[i - 1] - F90_DPTR_LBOUND_G(asd) + lboffset;
RECIP_DIVMOD(&cyclenum, &cyclepos, adjindex, DIST_DPTR_BLOCK_G(gsd));
index[i - 1] = cyclenum * DIST_DPTR_CYCLE_G(gsd) + cyclepos +
DIST_DPTR_OLB_G(gsd) - lboffset;
break;
default: /* block */
index[i - 1] += DIST_DPTR_OLB_G(gsd) - F90_DPTR_LBOUND_G(asd);
}
}
/* return the global index vector */
I8(store_vector)(g_index_b, g_index_s, index, F90_RANK_G(gs));
}
/* Translate global indices to local indices */
void ENTFTN(GLOBAL_TO_LOCAL,
global_to_local)(void *array_b, void *g_index_b, void *l_index_b,
void *local_b, void *ncopies_b, void *procs_b,
F90_Desc *array_s, F90_Desc *g_index_s,
F90_Desc *l_index_s, F90_Desc *local_s,
F90_Desc *ncopies_s, F90_Desc *procs_s)
{
DECL_DIM_PTRS(asd); /* local array dimensions */
DECL_HDR_PTRS(gs); /* global section */
DECL_DIM_PTRS(gsd); /* global section dimensions */
proc *p;
repl_t repl; /* replication descriptor */
__INT_T i, j, local, lof, n, procno;
__INT_T *procs;
__INT_T gindex[MAXDIMS], lindex[MAXDIMS], pcoord[MAXDIMS];
if (F90_TAG_G(array_s) != __DESC)
__fort_abort("GLOBAL_TO_LOCAL: argument must be array");
gs = DIST_ACTUAL_ARG_G(array_s);
if (gs == NULL || F90_TAG_G(gs) != __DESC)
__fort_abort("GLOBAL_TO_LOCAL: array is not associated with"
" global actual argument");
#if defined(DEBUG)
if (F90_RANK_G(gs) != F90_RANK_G(array_s))
__fort_abort("GLOBAL_TO_LOCAL: global vs. local rank mismatch");
#endif
/* get the global index vector */
I8(fetch_vector)(g_index_b, g_index_s, gindex, F90_RANK_G(gs));
/* check if element is local */
local = I8(__fort_islocal)(gs, gindex);
if (local && ISPRESENT(l_index_b)) {
for (i = F90_RANK_G(gs); i > 0; --i) {
SET_DIM_PTRS(asd, array_s, i - 1);
SET_DIM_PTRS(gsd, gs, i - 1);
switch (DFMT(gs, i)) {
case DFMT_CYCLIC:
case DFMT_CYCLIC_K: {
__INT_T aolb, aoub;
aolb = DIST_DPTR_OLB_G(asd);
aoub = DIST_DPTR_OUB_G(asd);
/* compute local offset for cyclic distribution */
j = DIST_DPTR_TSTRIDE_G(gsd) * gindex[i - 1] + DIST_DPTR_TOFFSET_G(gsd) -
DIST_DPTR_CLB_G(gsd);
j = Abs(j);
RECIP_DIV(&j, j, DIST_DPTR_CYCLE_G(gsd));
lof = j * DIST_DPTR_COFSTR_G(gsd);
lindex[i - 1] = F90_DPTR_SSTRIDE_G(gsd) * gindex[i - 1] +
F90_DPTR_SOFFSET_G(gsd) - lof -
(DIST_DPTR_OLB_G(gsd) - aolb);
while (lindex[i - 1] > aoub) {
lindex[i - 1] -= (DIST_DPTR_CYCLE_G(gsd) - DIST_DPTR_BLOCK_G(gsd));
}
while (lindex[i - 1] < aolb) {
lindex[i - 1] += (aoub - aolb + 1);
}
break;
}
default:
/* block or unmapped: subtract the difference between
global and local owned bounds */
lindex[i - 1] =
gindex[i - 1] - (DIST_DPTR_OLB_G(gsd) - DIST_DPTR_OLB_G(asd));
}
}
I8(store_vector)(l_index_b, l_index_s, lindex, F90_RANK_G(gs));
}
if (ISPRESENT(local_b))
I8(store_log)(local_b, local_s, local);
/* if needed, get replication info */
if (ISPRESENT(ncopies_b) || ISPRESENT(procs_b))
I8(__fort_describe_replication)(gs, &repl);
if (ISPRESENT(ncopies_b))
I8(store_int)(ncopies_b, ncopies_s, repl.ncopies);
if (ISPRESENT(procs_b)) {
procno = I8(__fort_owner)(gs, gindex);
if (repl.ncopies == 1)
I8(store_vector)(procs_b, procs_s, &procno, 1);
else {
procs = (__INT_T *)__fort_malloc(repl.ncopies * sizeof(__INT_T));
for (i = repl.ndim; --i >= 0;)
pcoord[i] = 0;
i = j = 0;
while (j < repl.ndim) {
if (pcoord[j] < repl.pcnt[j]) {
procs[i++] = procno;
procno += repl.pstr[j];
++pcoord[j];
j = 0;
} else {
procno -= repl.pcnt[j] * repl.pstr[j];
pcoord[j++] = 0;
}
}
#if defined(DEBUG)
if (i != repl.ncopies)
__fort_abort("GLOBAL_TO_LOCAL: replication info incorrect");
#endif
I8(store_vector)(procs_b, procs_s, procs, repl.ncopies);
__fort_free(procs);
}
}
}
/* Return the number of non-empty blocks in all or a specified dimension. */
void ENTFTN(LOCAL_BLKCNT, local_blkcnt)(void *blkcnt_b, void *array_b,
void *dim_b, void *proc_b,
F90_Desc *blkcnt_s, F90_Desc *array_s,
F90_Desc *dim_s, F90_Desc *proc_s)
{
DECL_HDR_PTRS(gs);
DECL_DIM_PTRS(gsd);
__INT_T dim, proc;
__INT_T blkcnt[MAXDIMS];
__INT_T cl, cn, il, iu;
if (F90_TAG_G(array_s) != __DESC)
__fort_abort("LOCAL_BLKCNT: argument must be array");
if ((gs = DIST_ACTUAL_ARG_G(array_s)) == NULL)
__fort_abort("LOCAL_BLKCNT: array is not associated with global"
" actual argument");
if (ISPRESENT(dim_b)) {
dim = I8(fetch_int)(dim_b, dim_s);
if (dim < 1 || dim > F90_RANK_G(gs))
__fort_abort("LOCAL_BLKCNT: invalid dim");
} else
dim = 0;
if (ISPRESENT(proc_b)) {
if ((proc = I8(fetch_int)(proc_b, proc_s)) < 0 || proc >= GET_DIST_TCPUS)
__fort_abort("LOCAL_BLKCNT: invalid proc");
if (proc != GET_DIST_LCPU)
__fort_abort("LOCAL_BLKCNT: proc .ne. my_processor() unsupported");
} else
proc = GET_DIST_LCPU;
if (dim != 0) {
/* compute blkcnt for specified dimension */
blkcnt[0] = 0;
if (~F90_FLAGS_G(gs) & __OFF_TEMPLATE) {
I8(__fort_cycle_bounds)(gs);
SET_DIM_PTRS(gsd, gs, dim - 1);
for (cl = DIST_DPTR_CL_G(gsd), cn = DIST_DPTR_CN_G(gsd); --cn >= 0;
cl += DIST_DPTR_CS_G(gsd))
if (I8(__fort_block_bounds)(gs, dim, cl, &il, &iu) > 0)
blkcnt[0]++;
}
I8(store_int)(blkcnt_b, blkcnt_s, blkcnt[0]);
} else {
/* compute blkcnt for all dimensions */
for (dim = F90_RANK_G(gs); dim > 0; --dim)
blkcnt[dim - 1] = 0;
if (~F90_FLAGS_G(gs) & __OFF_TEMPLATE) {
I8(__fort_cycle_bounds)(gs);
for (dim = F90_RANK_G(gs); dim > 0; --dim) {
SET_DIM_PTRS(gsd, gs, dim - 1);
for (cl = DIST_DPTR_CL_G(gsd), cn = DIST_DPTR_CN_G(gsd); --cn >= 0;
cl += DIST_DPTR_CS_G(gsd))
if (I8(__fort_block_bounds)(gs, dim, cl, &il, &iu) > 0)
blkcnt[dim - 1]++;
}
}
I8(store_vector)(blkcnt_b, blkcnt_s, blkcnt, F90_RANK_G(gs));
}
}
/* Return the lower indices of all non-empty blocks. */
void ENTFTN(LOCAL_LINDEX, local_lindex)(void *lindex_b, void *array_b,
void *dim_b, void *proc_b,
F90_Desc *lindex_s, F90_Desc *array_s,
F90_Desc *dim_s, F90_Desc *proc_s)
{
DECL_HDR_PTRS(gs);
DECL_DIM_PTRS(gsd);
__INT_T dim;
__INT_T proc;
__INT_T blkcnt, cl, cn, il, iu;
/* check array argument */
if (F90_TAG_G(array_s) != __DESC)
__fort_abort("LOCAL_LINDEX: argument must be array");
if ((gs = DIST_ACTUAL_ARG_G(array_s)) == NULL)
__fort_abort("LOCAL_LINDEX: array is not associated with global"
" actual argument");
/* check dim argument */
dim = I8(fetch_int)(dim_b, dim_s);
if (dim < 1 || dim > F90_RANK_G(gs))
__fort_abort("LOCAL_LINDEX: invalid dim argument");
/* check proc argument */
if (ISPRESENT(proc_b)) {
proc = I8(fetch_int)(proc_b, proc_s);
if (proc < 0 || proc >= GET_DIST_TCPUS)
__fort_abort("LOCAL_LINDEX: invalid proc argument");
if (proc != GET_DIST_LCPU)
__fort_abort("LOCAL_LINDEX: proc .ne. my_processor() unsupported");
} else
proc = GET_DIST_LCPU;
/* compute lower indices of all non-empty blocks */
if (~F90_FLAGS_G(gs) & __OFF_TEMPLATE) {
I8(__fort_cycle_bounds)(gs);
SET_DIM_PTRS(gsd, gs, dim - 1);
blkcnt = 0;
for (cl = DIST_DPTR_CL_G(gsd), cn = DIST_DPTR_CN_G(gsd); --cn >= 0;
cl += DIST_DPTR_CS_G(gsd)) {
if (I8(__fort_block_bounds)(gs, dim, cl, &il, &iu) > 0) {
DECL_DIM_PTRS(asd);
SET_DIM_PTRS(asd, array_s, dim - 1);
switch (DFMT(gs, dim)) {
case DFMT_CYCLIC:
case DFMT_CYCLIC_K: {
__INT_T aolb, aoub, j, lof;
aolb = DIST_DPTR_OLB_G(asd);
aoub = DIST_DPTR_OUB_G(asd);
/* compute local offset for cyclic distribution */
j = DIST_DPTR_TSTRIDE_G(gsd) * il + DIST_DPTR_TOFFSET_G(gsd) -
DIST_DPTR_CLB_G(gsd);
j = Abs(j);
RECIP_DIV(&j, j, DIST_DPTR_CYCLE_G(gsd));
lof = j * DIST_DPTR_COFSTR_G(gsd);
il = F90_DPTR_SSTRIDE_G(gsd) * il + F90_DPTR_SOFFSET_G(gsd) - lof -
(DIST_DPTR_OLB_G(gsd) - aolb);
while (il > aoub) {
il -= (DIST_DPTR_CYCLE_G(gsd) - DIST_DPTR_BLOCK_G(gsd));
}
while (il < aolb) {
il += (aoub - aolb + 1);
}
break;
}
default:
/* block or unmapped: subtract the difference between
global and local owned bounds */
il -= (DIST_DPTR_OLB_G(gsd) - DIST_DPTR_OLB_G(asd));
}
I8(store_element)(lindex_b, lindex_s, ++blkcnt, il);
}
}
}
}
/* Return the upper indices of all non-empty blocks */
void ENTFTN(LOCAL_UINDEX, local_uindex)(void *uindex_b, void *array_b,
void *dim_b, void *proc_b,
F90_Desc *uindex_s, F90_Desc *array_s,
F90_Desc *dim_s, F90_Desc *proc_s)
{
DECL_HDR_PTRS(gs);
DECL_DIM_PTRS(gsd);
__INT_T dim;
__INT_T proc;
__INT_T blkcnt, cl, cn, il, iu;
/* check array argument */
if (F90_TAG_G(array_s) != __DESC)
__fort_abort("LOCAL_UINDEX: argument must be array");
if ((gs = DIST_ACTUAL_ARG_G(array_s)) == NULL)
__fort_abort("LOCAL_UINDEX: array is not associated with global"
" actual argument");
/* check dim argument */
dim = I8(fetch_int)(dim_b, dim_s);
if (dim < 1 || dim > F90_RANK_G(gs))
__fort_abort("LOCAL_UINDEX: invalid dim argument");
/* check proc argument */
if (ISPRESENT(proc_b)) {
proc = I8(fetch_int)(proc_b, proc_s);
if (proc < 0 || proc >= GET_DIST_TCPUS)
__fort_abort("LOCAL_UINDEX: invalid proc argument");
if (proc != GET_DIST_LCPU)
__fort_abort("LOCAL_UINDEX: proc .ne. my_processor() unsupported");
} else
proc = GET_DIST_LCPU;
/* compute upper indices of all non-empty blocks */
if (~F90_FLAGS_G(gs) & __OFF_TEMPLATE) {
I8(__fort_cycle_bounds)(gs);
SET_DIM_PTRS(gsd, gs, dim - 1);
blkcnt = 0;
for (cl = DIST_DPTR_CL_G(gsd), cn = DIST_DPTR_CN_G(gsd); --cn >= 0;
cl += DIST_DPTR_CS_G(gsd)) {
if (I8(__fort_block_bounds)(gs, dim, cl, &il, &iu) > 0) {
DECL_DIM_PTRS(asd);
SET_DIM_PTRS(asd, array_s, dim - 1);
switch (DFMT(gs, dim)) {
case DFMT_CYCLIC:
case DFMT_CYCLIC_K: {
__INT_T aolb, aoub, j, lof;
aolb = DIST_DPTR_OLB_G(asd);
aoub = DIST_DPTR_OUB_G(asd);
/* compute local offset for cyclic distribution */
j = DIST_DPTR_TSTRIDE_G(gsd) * iu + DIST_DPTR_TOFFSET_G(gsd) -
DIST_DPTR_CLB_G(gsd);
j = Abs(j);
RECIP_DIV(&j, j, DIST_DPTR_CYCLE_G(gsd));
lof = j * DIST_DPTR_COFSTR_G(gsd);
iu = F90_DPTR_SSTRIDE_G(gsd) * iu + F90_DPTR_SOFFSET_G(gsd) - lof -
(DIST_DPTR_OLB_G(gsd) - aolb);
while (iu > aoub) {
iu -= (DIST_DPTR_CYCLE_G(gsd) - DIST_DPTR_BLOCK_G(gsd));
}
while (iu < aolb) {
iu += (aoub - aolb + 1);
}
break;
}
default:
/* block or unmapped: subtract the difference between
global and local owned bounds */
iu -= (DIST_DPTR_OLB_G(gsd) - DIST_DPTR_OLB_G(asd));
}
I8(store_element)(uindex_b, uindex_s, ++blkcnt, iu);
}
}
}
}
/* system inquiry routines */
void ENTFTN(PROCESSORS_SHAPE, processors_shape)(__INT_T *shape,
F90_Desc *shape_s)
{
I8(store_vector_int)(shape, shape_s, GET_DIST_TCPUS_ADDR, 1);
}
__INT_T
ENTFTN(MY_PROCESSOR, my_processor)() { return GET_DIST_LCPU; }
__INT_T
ENTFTN(MYPROCNUM, myprocnum)() { return GET_DIST_LCPU; }
int
__fort_nprocs()
{
return GET_DIST_TCPUS;
}
__INT_T
ENTFTN(NPROCS, nprocs)() { return GET_DIST_TCPUS; }
__INT_T
ENTFTN(NUMBER_OF_PROCESSORS, number_of_processors)
(__INT_T *dim, __INT_T *szdim)
{
int d, np;
np = GET_DIST_TCPUS;
if (ISPRESENT(dim)) {
d = __fort_varying_int(dim, szdim);
if (d != 1)
np = 1;
}
return np;
}
__INT8_T
ENTFTN(KNUMBER_OF_PROCESSORS, knumber_of_processors)
(__INT_T *dim, __INT_T *szdim)
{
/*
* -i8 variant of NUMBER_OF_PROCESSORS
*/
int d, np;
np = GET_DIST_TCPUS;
if (ISPRESENT(dim)) {
d = __fort_varying_int(dim, szdim);
if (d != 1)
np = 1;
}
return np;
}
__INT_T
ENTFTN(PROCESSORS_RANK, processors_rank)() { return 1; }
__INT8_T
ENTFTN(KPROCESSORS_RANK, kprocessors_rank)()
{
/*
* -i8 variant of PROCESSORS_RANK
*/
return 1;
}
/* Translate processor number to processor grid coordinates.
rank and shape describe the processor grid. The processor
number given by procnum is translated to grid coordinates returned
in coord. Grid coordinates are integers between 1 and the size of
the corresponding grid dimension. If the processor number is
outside the bounds of the processor grid, zeroes are returned in
coord. */
void
__fort_procnum_to_coord(int procnum, int rank, __INT_T *shape, __INT_T *coord)
{
int i, m;
if (procnum >= 0) {
for (i = 0; i < rank; ++i) {
if (shape[i] <= 0)
__fort_abort("PROCNUM_TO_COORD: invalid processor shape");
m = procnum / shape[i];
coord[i] = procnum - m * shape[i] + 1;
procnum = m;
}
}
if (procnum != 0) {
for (i = rank; --i >= 0;)
coord[i] = 0;
}
}
void ENTFTN(PROCNUM_TO_COORD, procnum_to_coord)(__INT_T *procnum, __INT_T *rank,
__INT_T *shape, __INT_T *coord)
{
__fort_procnum_to_coord(*procnum, *rank, shape, coord);
}
/* Translate processor grid coordinates to processor number.
rank and shape describe the processor grid. The processor grid
coordinates in coord are translated to a processor number.
Grid coordinates are integers between 1 and the size of the
corresponding grid dimension. If the coordinates are outside the
bounds of the processor grid, -1 is returned. */
int
__fort_coord_to_procnum(__INT_T rank, __INT_T *shape, __INT_T *coord)
{
int i, m, p;
m = 1;
p = 0;
for (i = 0; i < rank; ++i) {
if (shape[i] <= 0)
__fort_abort("COORD_TO_PROCNUM: invalid processor shape");
if (coord[i]<1 | coord[i]> shape[i])
return -1;
p += (coord[i] - 1) * m;
m *= shape[i];
}
return p;
}
__INT_T
ENTFTN(COORD_TO_PROCNUM, coord_to_procnum)
(__INT_T *rank, __INT_T *shape, __INT_T *coord)
{
return __fort_coord_to_procnum(*rank, shape, coord);
}
| 2.09375 | 2 |
2024-11-18T21:10:22.673074+00:00
| 2023-01-26T13:04:05 |
f487062bc8920f7aef14a14fe1368579f12545c7
|
{
"blob_id": "f487062bc8920f7aef14a14fe1368579f12545c7",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-26T13:04:05",
"content_id": "1db618c4c960917ceeecdff3d60761547e9bcc94",
"detected_licenses": [
"MIT"
],
"directory_id": "994feb2e8a600c35ffc376a52ca30984b628fff9",
"extension": "c",
"filename": "compress_parms.c",
"fork_events_count": 3,
"gha_created_at": "2016-02-04T14:21:19",
"gha_event_created_at": "2023-01-25T15:31:19",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 51080637,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 31812,
"license": "MIT",
"license_type": "permissive",
"path": "/source/kernel/compress_parms.c",
"provenance": "stackv2-0065.json.gz:39705",
"repo_name": "vincentloechner/polylib",
"revision_date": "2023-01-26T13:04:05",
"revision_id": "2f8a512b07fb9d3412d2237c6c930853ba524f7f",
"snapshot_id": "a125f515f24b77f1838adafe06a3b5d14e1425ec",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/vincentloechner/polylib/2f8a512b07fb9d3412d2237c6c930853ba524f7f/source/kernel/compress_parms.c",
"visit_date": "2023-02-12T23:00:19.359343"
}
|
stackv2
|
/**
* $Id: compress_parms.c,v 1.32 2006/11/03 17:34:26 skimo Exp $
*
* The integer points in a parametric linear subspace of Q^n are generally
* lying on a sub-lattice of Z^n.
* Functions here use and compute validity lattices, i.e. lattices induced on a
* set of variables by such equalities involving another set of integer
* variables.
* @author B. Meister 12/2003-2006 meister@icps.u-strasbg.fr
* LSIIT -ICPS
* UMR 7005 CNRS
* Louis Pasteur University (ULP), Strasbourg, France
*/
#include <stdlib.h>
#include <polylib/polylib.h>
/**
* debug flags (2 levels)
*/
#define dbgCompParm 0
#define dbgCompParmMore 0
#define dbgStart(a) if (dbgCompParmMore) { printf(" -- begin "); \
printf(#a); \
printf(" --\n"); } \
while(0)
#define dbgEnd(a) if (dbgCompParmMore) { printf(" -- end "); \
printf(#a); \
printf(" --\n"); } \
while(0)
/**
* Given a full-row-rank nxm matrix M made of m row-vectors), computes the
* basis K (made of n-m column-vectors) of the integer kernel of the rows of M
* so we have: M.K = 0
*/
Matrix * int_ker(Matrix * M) {
Matrix *U, *Q, *H, *H2, *K=NULL;
int i, j, rk;
if (dbgCompParm)
show_matrix(M);
/* eliminate redundant rows : UM = H*/
right_hermite(M, &H, &Q, &U);
for (rk=H->NbRows-1; (rk>=0) && Vector_IsZero(H->p[rk], H->NbColumns); rk--);
rk++;
if (dbgCompParmMore) {
printf("rank = %d\n", rk);
}
/* there is a non-null kernel if and only if the dimension m of
the space spanned by the rows
is inferior to the number n of variables */
if (M->NbColumns <= rk) {
Matrix_Free(H);
Matrix_Free(Q);
Matrix_Free(U);
K = Matrix_Alloc(M->NbColumns, 0);
return K;
}
Matrix_Free(U);
Matrix_Free(Q);
/* fool left_hermite by giving NbRows =rank of M*/
H->NbRows=rk;
/* computes MU = [H 0] */
left_hermite(H, &H2, &Q, &U);
if (dbgCompParmMore) {
printf("-- Int. Kernel -- \n");
show_matrix(M);
printf(" = \n");
show_matrix(H2);
show_matrix(U);
}
H->NbRows=M->NbRows;
Matrix_Free(H);
/* the Integer Kernel is made of the last n-rk columns of U */
Matrix_subMatrix(U, 0, rk, U->NbRows, U->NbColumns, &K);
/* clean up */
Matrix_Free(H2);
Matrix_Free(U);
Matrix_Free(Q);
return K;
} /* int_ker */
/**
* Computes the intersection of two linear lattices, whose base vectors are
* respectively represented in A and B.
* If I and/or Lb is set to NULL, then the matrix is allocated.
* Else, the matrix is assumed to be allocated already.
* I and Lb are rk x rk, where rk is the rank of A (or B).
* @param A the full-row rank matrix whose column-vectors are the basis for the
* first linear lattice.
* @param B the matrix whose column-vectors are the basis for the second linear
* lattice.
* @param Lb the matrix such that B.Lb = I, where I is the intersection.
* @return their intersection.
*/
static void linearInter(Matrix * A, Matrix * B, Matrix ** I, Matrix **Lb) {
Matrix * AB=NULL;
int rk = A->NbRows;
int a = A->NbColumns;
int b = B->NbColumns;
int i,j, z=0;
Matrix * H, *U, *Q;
/* ensure that the spanning vectors are in the same space */
assert(B->NbRows==rk);
/* 1- build the matrix
* (A 0 1)
* (0 B 1)
*/
AB = Matrix_Alloc(2*rk, a+b+rk);
Matrix_copySubMatrix(A, 0, 0, rk, a, AB, 0, 0);
Matrix_copySubMatrix(B, 0, 0, rk, b, AB, rk, a);
for (i=0; i< rk; i++) {
value_set_si(AB->p[i][a+b+i], 1);
value_set_si(AB->p[i+rk][a+b+i], 1);
}
if (dbgCompParm) {
show_matrix(AB);
}
/* 2- Compute its left Hermite normal form. AB.U = [H 0] */
left_hermite(AB, &H, &Q, &U);
Matrix_Free(AB);
Matrix_Free(Q);
/* count the number of non-zero colums in H */
for (z=H->NbColumns-1; value_zero_p(H->p[H->NbRows-1][z]); z--);
z++;
if (dbgCompParm) {
show_matrix(H);
printf("z=%d\n", z);
}
Matrix_Free(H);
/* if you split U in 9 submatrices, you have:
* A.U_13 = -U_33
* B.U_23 = -U_33,
* where the nb of cols of U_{*3} equals the nb of zero-cols of H
* U_33 is a (the smallest) combination of col-vectors of A and B at the same
* time: their intersection.
*/
Matrix_subMatrix(U, a+b, z, U->NbColumns, U->NbColumns, I);
Matrix_subMatrix(U, a, z, a+b, U->NbColumns, Lb);
if (dbgCompParm) {
show_matrix(U);
}
Matrix_Free(U);
} /* linearInter */
/**
* Given a system of equalities, looks if it has an integer solution in the
* combined space, and if yes, returns one solution.
* <p>pre-condition: the equalities are full-row rank (without the constant
* part)</p>
* @param Eqs the system of equations (as constraints)
* @param I a feasible integer solution if it exists, else NULL. Allocated if
* initially set to NULL, else reused.
*/
void Equalities_integerSolution(Matrix * Eqs, Matrix **I) {
Matrix * Hm, *H=NULL, *U, *Q, *M=NULL, *C=NULL, *Hi;
Matrix *Ip;
int i;
Value mod;
unsigned int rk;
if (Eqs==NULL){
if ((*I)!=NULL) Matrix_Free(*I);
I = NULL;
return;
}
/* we use: AI = C = (Ha 0).Q.I = (Ha 0)(I' 0)^T */
/* with I = Qinv.I' = U.I'*/
/* 1- compute I' = Hainv.(-C) */
/* HYP: the equalities are full-row rank */
rk = Eqs->NbRows;
Matrix_subMatrix(Eqs, 0, 1, rk, Eqs->NbColumns-1, &M);
left_hermite(M, &Hm, &Q, &U);
Matrix_Free(M);
Matrix_subMatrix(Hm, 0, 0, rk, rk, &H);
if (dbgCompParmMore) {
show_matrix(Hm);
show_matrix(H);
show_matrix(U);
}
Matrix_Free(Q);
Matrix_Free(Hm);
Matrix_subMatrix(Eqs, 0, Eqs->NbColumns-1, rk, Eqs->NbColumns, &C);
Matrix_oppose(C);
Hi = Matrix_Alloc(rk, rk+1);
MatInverse(H, Hi);
if (dbgCompParmMore) {
show_matrix(C);
show_matrix(Hi);
}
/* put the numerator of Hinv back into H */
Matrix_subMatrix(Hi, 0, 0, rk, rk, &H);
Ip = Matrix_Alloc(Eqs->NbColumns-2, 1);
/* fool Matrix_Product on the size of Ip */
Ip->NbRows = rk;
Matrix_Product(H, C, Ip);
Ip->NbRows = Eqs->NbColumns-2;
Matrix_Free(H);
Matrix_Free(C);
value_init(mod);
for (i=0; i< rk; i++) {
/* if Hinv.C is not integer, return NULL (no solution) */
value_pmodulus(mod, Ip->p[i][0], Hi->p[i][rk]);
if (value_notzero_p(mod)) {
if ((*I)!=NULL) Matrix_Free(*I);
value_clear(mod);
Matrix_Free(U);
Matrix_Free(Ip);
Matrix_Free(Hi);
I = NULL;
return;
}
else {
value_pdivision(Ip->p[i][0], Ip->p[i][0], Hi->p[i][rk]);
}
}
/* fill the rest of I' with zeros */
for (i=rk; i< Eqs->NbColumns-2; i++) {
value_set_si(Ip->p[i][0], 0);
}
value_clear(mod);
Matrix_Free(Hi);
/* 2 - Compute the particular solution I = U.(I' 0) */
ensureMatrix((*I), Eqs->NbColumns-2, 1);
Matrix_Product(U, Ip, (*I));
Matrix_Free(U);
Matrix_Free(Ip);
if (dbgCompParm) {
show_matrix(*I);
}
}
/**
* Computes the validity lattice of a set of equalities. I.e., the lattice
* induced on the last <tt>b</tt> variables by the equalities involving the
* first <tt>a</tt> integer existential variables. The submatrix of Eqs that
* concerns only the existential variables (so the first a columns) is assumed
* to be full-row rank.
* @param Eqs the equalities
* @param a the number of existential integer variables, placed as first
* variables
* @param vl the (returned) validity lattice, in homogeneous form. It is
* allocated if initially set to null, or reused if already allocated.
*/
void Equalities_validityLattice(Matrix * Eqs, int a, Matrix** vl) {
unsigned int b = Eqs->NbColumns-2-a;
unsigned int r = Eqs->NbRows;
Matrix * A=NULL, * B=NULL, *I = NULL, *Lb=NULL, *sol=NULL;
Matrix *H, *U, *Q;
unsigned int i;
if (dbgCompParm) {
printf("Computing validity lattice induced by the %d first variables of:"
,a);
show_matrix(Eqs);
}
if (b==0) {
ensureMatrix((*vl), 1, 1);
value_set_si((*vl)->p[0][0], 1);
return;
}
/* 1- check that there is an integer solution to the equalities */
/* OPT: could change integerSolution's profile to allocate or not*/
Equalities_integerSolution(Eqs, &sol);
/* if there is no integer solution, there is no validity lattice */
if (sol==NULL) {
if ((*vl)!=NULL) Matrix_Free(*vl);
return;
}
Matrix_subMatrix(Eqs, 0, 1, r, 1+a, &A);
Matrix_subMatrix(Eqs, 0, 1+a, r, 1+a+b, &B);
linearInter(A, B, &I, &Lb);
Matrix_Free(A);
Matrix_Free(B);
Matrix_Free(I);
if (dbgCompParm) {
show_matrix(Lb);
}
/* 2- The linear part of the validity lattice is the left HNF of Lb */
left_hermite(Lb, &H, &Q, &U);
Matrix_Free(Lb);
Matrix_Free(Q);
Matrix_Free(U);
/* 3- build the validity lattice */
ensureMatrix((*vl), b+1, b+1);
Matrix_copySubMatrix(H, 0, 0, b, b, (*vl), 0,0);
Matrix_Free(H);
for (i=0; i< b; i++) {
value_assign((*vl)->p[i][b], sol->p[0][a+i]);
}
Matrix_Free(sol);
Vector_Set((*vl)->p[b],0, b);
value_set_si((*vl)->p[b][b], 1);
} /* validityLattice */
/**
* Eliminate the columns corresponding to a list of eliminated parameters.
* @param M the constraints matrix whose columns are to be removed
* @param nbVars an offset to be added to the ranks of the variables to be
* removed
* @param elimParms the list of ranks of the variables to be removed
* @param newM (output) the matrix without the removed columns
*/
void Constraints_removeElimCols(Matrix * M, unsigned int nbVars,
unsigned int *elimParms, Matrix ** newM) {
unsigned int i, j, k;
if (elimParms[0]==0) {
Matrix_clone(M, newM);
return;
}
if ((*newM)==NULL) {
(*newM) = Matrix_Alloc(M->NbRows, M->NbColumns - elimParms[0]);
}
else {
assert ((*newM)->NbColumns==M->NbColumns - elimParms[0]);
}
for (i=0; i< M->NbRows; i++) {
value_assign((*newM)->p[i][0], M->p[i][0]); /* kind of cstr */
k=0;
Vector_Copy(&(M->p[i][1]), &((*newM)->p[i][1]), nbVars);
for (j=0; j< M->NbColumns-2-nbVars; j++) {
if (j!=elimParms[k+1]) {
value_assign((*newM)->p[i][j-k+nbVars+1], M->p[i][j+nbVars+1]);
}
else {
k++;
}
}
value_assign((*newM)->p[i][(*newM)->NbColumns-1],
M->p[i][M->NbColumns-1]); /* cst part */
}
} /* Constraints_removeElimCols */
/**
* Eliminates all the equalities in a set of constraints and returns the set of
* constraints defining a full-dimensional polyhedron, such that there is a
* bijection between integer points of the original polyhedron and these of the
* resulting (projected) polyhedron).
* If VL is set to NULL, this funciton allocates it. Else, it assumes that
* (*VL) points to a matrix of the right size.
* <p> The following things are done:
* <ol>
* <li> remove equalities involving only parameters, and remove as many
* parameters as there are such equalities. From that, the list of
* eliminated parameters <i>elimParms</i> is built.
* <li> remove equalities that involve variables. This requires a compression
* of the parameters and of the other variables that are not eliminated.
* The affine compresson is represented by matrix VL (for <i>validity
* lattice</i>) and is such that (N I 1)^T = VL.(N' I' 1), where N', I'
* are integer (they are the parameters and variables after compression).
*</ol>
*</p>
*/
void Constraints_fullDimensionize(Matrix ** M, Matrix ** C, Matrix ** VL,
Matrix ** Eqs, Matrix ** ParmEqs,
unsigned int ** elimVars,
unsigned int ** elimParms,
int maxRays) {
unsigned int i, j;
Matrix * A=NULL, *B=NULL;
Matrix * Ineqs=NULL;
unsigned int nbVars = (*M)->NbColumns - (*C)->NbColumns;
unsigned int nbParms;
int nbElimVars;
Matrix * fullDim = NULL;
/* variables for permutations */
unsigned int * permutation;
Matrix * permutedEqs=NULL, * permutedIneqs=NULL;
/* 1- Eliminate the equalities involving only parameters. */
(*ParmEqs) = Constraints_removeParmEqs(M, C, 0, elimParms);
/* if the polyehdron is empty, return now. */
if ((*M)->NbColumns==0) return;
/* eliminate the columns corresponding to the eliminated parameters */
if (elimParms[0]!=0) {
Constraints_removeElimCols(*M, nbVars, (*elimParms), &A);
Matrix_Free(*M);
(*M) = A;
Constraints_removeElimCols(*C, 0, (*elimParms), &B);
Matrix_Free(*C);
(*C) = B;
if (dbgCompParm) {
printf("After false parameter elimination: \n");
show_matrix(*M);
show_matrix(*C);
}
}
nbParms = (*C)->NbColumns-2;
/* 2- Eliminate the equalities involving variables */
/* a- extract the (remaining) equalities from the poyhedron */
split_constraints((*M), Eqs, &Ineqs);
nbElimVars = (*Eqs)->NbRows;
/* if the polyhedron is already full-dimensional, return */
if ((*Eqs)->NbRows==0) {
Matrix_identity(nbParms+1, VL);
return;
}
/* b- choose variables to be eliminated */
permutation = find_a_permutation((*Eqs), nbParms);
if (dbgCompParm) {
printf("Permuting the vars/parms this way: [ ");
for (i=0; i< (*Eqs)->NbColumns-2; i++) {
printf("%d ", permutation[i]);
}
printf("]\n");
}
Constraints_permute((*Eqs), permutation, &permutedEqs);
Equalities_validityLattice(permutedEqs, (*Eqs)->NbRows, VL);
if (dbgCompParm) {
printf("Validity lattice: ");
show_matrix(*VL);
}
Constraints_compressLastVars(permutedEqs, (*VL));
Constraints_permute(Ineqs, permutation, &permutedIneqs);
if (dbgCompParmMore) {
show_matrix(permutedIneqs);
show_matrix(permutedEqs);
}
Matrix_Free(*Eqs);
Matrix_Free(Ineqs);
Constraints_compressLastVars(permutedIneqs, (*VL));
if (dbgCompParm) {
printf("After compression: ");
show_matrix(permutedIneqs);
}
/* c- eliminate the first variables */
assert(Constraints_eliminateFirstVars(permutedEqs, permutedIneqs));
if (dbgCompParmMore) {
printf("After elimination of the variables: ");
show_matrix(permutedIneqs);
}
/* d- get rid of the first (zero) columns,
which are now useless, and put the parameters back at the end */
fullDim = Matrix_Alloc(permutedIneqs->NbRows,
permutedIneqs->NbColumns-nbElimVars);
for (i=0; i< permutedIneqs->NbRows; i++) {
value_set_si(fullDim->p[i][0], 1);
for (j=0; j< nbParms; j++) {
value_assign(fullDim->p[i][j+fullDim->NbColumns-nbParms-1],
permutedIneqs->p[i][j+nbElimVars+1]);
}
for (j=0; j< permutedIneqs->NbColumns-nbParms-2-nbElimVars; j++) {
value_assign(fullDim->p[i][j+1],
permutedIneqs->p[i][nbElimVars+nbParms+j+1]);
}
value_assign(fullDim->p[i][fullDim->NbColumns-1],
permutedIneqs->p[i][permutedIneqs->NbColumns-1]);
}
Matrix_Free(permutedIneqs);
} /* Constraints_fullDimensionize */
/**
* Given a matrix that defines a full-dimensional affine lattice, returns the
* affine sub-lattice spanned in the k first dimensions.
* Useful for instance when you only look for the parameters' validity lattice.
* @param lat the original full-dimensional lattice
* @param subLat the sublattice
*/
void Lattice_extractSubLattice(Matrix * lat, unsigned int k, Matrix ** subLat) {
Matrix * H, *Q, *U, *linLat = NULL;
unsigned int i;
dbgStart(Lattice_extractSubLattice);
/* if the dimension is already good, just copy the initial lattice */
if (k==lat->NbRows-1) {
if (*subLat==NULL) {
(*subLat) = Matrix_Copy(lat);
}
else {
Matrix_copySubMatrix(lat, 0, 0, lat->NbRows, lat->NbColumns, (*subLat), 0, 0);
}
return;
}
assert(k<lat->NbRows-1);
/* 1- Make the linear part of the lattice triangular to eliminate terms from
other dimensions */
Matrix_subMatrix(lat, 0, 0, lat->NbRows, lat->NbColumns-1, &linLat);
/* OPT: any integer column-vector elimination is ok indeed. */
/* OPT: could test if the lattice is already in triangular form. */
left_hermite(linLat, &H, &Q, &U);
if (dbgCompParmMore) {
show_matrix(H);
}
Matrix_Free(Q);
Matrix_Free(U);
Matrix_Free(linLat);
/* if not allocated yet, allocate it */
if (*subLat==NULL) {
(*subLat) = Matrix_Alloc(k+1, k+1);
}
Matrix_copySubMatrix(H, 0, 0, k, k, (*subLat), 0, 0);
Matrix_Free(H);
Matrix_copySubMatrix(lat, 0, lat->NbColumns-1, k, 1, (*subLat), 0, k);
for (i=0; i<k; i++) {
value_set_si((*subLat)->p[k][i], 0);
}
value_set_si((*subLat)->p[k][k], 1);
dbgEnd(Lattice_extractSubLattice);
} /* Lattice_extractSubLattice */
/**
* Computes the overall period of the variables I for (MI) mod |d|, where M is
* a matrix and |d| a vector. Produce a diagonal matrix S = (s_k) where s_k is
* the overall period of i_k
* @param M the set of affine functions of I (row-vectors)
* @param d the column-vector representing the modulos
*/
Matrix * affine_periods(Matrix * M, Matrix * d) {
Matrix * S;
unsigned int i,j;
Value tmp;
Value * periods = (Value *)malloc(sizeof(Value) * M->NbColumns);
value_init(tmp);
for(i=0; i< M->NbColumns; i++) {
value_init(periods[i]);
value_set_si(periods[i], 1);
}
for (i=0; i<M->NbRows; i++) {
for (j=0; j< M->NbColumns; j++) {
value_gcd(tmp, d->p[i][0], M->p[i][j]);
value_divexact(tmp, d->p[i][0], tmp);
value_lcm(periods[j], periods[j], tmp);
}
}
value_clear(tmp);
/* 2- build S */
S = Matrix_Alloc(M->NbColumns, M->NbColumns);
for (i=0; i< M->NbColumns; i++)
for (j=0; j< M->NbColumns; j++)
if (i==j) value_assign(S->p[i][j],periods[j]);
else value_set_si(S->p[i][j], 0);
/* 3- clean up */
for(i=0; i< M->NbColumns; i++) value_clear(periods[i]);
free(periods);
return S;
} /* affine_periods */
/**
* Given an integer matrix B with m rows and integer m-vectors C and d,
* computes the basis of the integer solutions to (BN+C) mod d = 0 (1).
* This is an affine lattice (G): (N 1)^T= G(N' 1)^T, forall N' in Z^b.
* If there is no solution, returns NULL.
* @param B B, a (m x b) matrix
* @param C C, a (m x 1) integer matrix
* @param d d, a (1 x m) integer matrix
* @param imb the affine (b+1)x(b+1) basis of solutions, in the homogeneous
* form. Allocated if initially set to NULL, reused if not.
*/
void Equalities_intModBasis(Matrix * B, Matrix * C, Matrix * d, Matrix ** imb) {
int b = B->NbColumns;
/* FIXME: treat the case d=0 as a regular equality B_kN+C_k = 0: */
/* OPT: could keep only equalities for which d>1 */
int nbEqs = B->NbRows;
unsigned int i;
/* 1- buid the problem DI+BN+C = 0 */
Matrix * eqs = Matrix_Alloc(nbEqs, nbEqs+b+1);
for (i=0; i< nbEqs; i++) {
value_assign(eqs->p[i][i], d->p[0][i]);
}
Matrix_copySubMatrix(B, 0, 0, nbEqs, b, eqs, 0, nbEqs);
Matrix_copySubMatrix(C, 0, 0, nbEqs, 1, eqs, 0, nbEqs+b);
/* 2- the solution is the validity lattice of the equalities */
Equalities_validityLattice(eqs, nbEqs, imb);
Matrix_Free(eqs);
} /* Equalities_intModBasis */
/** kept here for backwards compatiblity. Wrapper to Equalities_intModBasis() */
Matrix * int_mod_basis(Matrix * B, Matrix * C, Matrix * d) {
Matrix * imb = NULL;
Equalities_intModBasis(B, C, d, &imb);
return imb;
} /* int_mod_basis */
/**
* Given a parameterized constraints matrix with m equalities, computes the
* compression matrix G such that there is an integer solution in the variables
* space for each value of N', with N = G N' (N are the "nb_parms" parameters)
* @param E a matrix of parametric equalities @param nb_parms the number of
* parameters
* <b>Note: </b>this function is mostly here for backwards
* compatibility. Prefer the use of <tt>Equalities_validityLattice</tt>.
*/
Matrix * compress_parms(Matrix * E, int nbParms) {
Matrix * vl=NULL;
Equalities_validityLattice(E, E->NbColumns-2-nbParms, &vl);
return vl;
}/* compress_parms */
/** Removes the equalities that involve only parameters, by eliminating some
* parameters in the polyhedron's constraints and in the context.<p>
* <b>Updates M and Ctxt.</b>
* @param M1 the polyhedron's constraints
* @param Ctxt1 the constraints of the polyhedron's context
* @param renderSpace tells if the returned equalities must be expressed in the
* parameters space (renderSpace=0) or in the combined var/parms space
* (renderSpace = 1)
* @param elimParms the list of parameters that have been removed: an array
* whose 1st element is the number of elements in the list. (returned)
* @return the system of equalities that involve only parameters.
*/
Matrix * Constraints_Remove_parm_eqs(Matrix ** M1, Matrix ** Ctxt1,
int renderSpace,
unsigned int ** elimParms) {
int i, j, k, nbEqsParms =0;
int nbEqsM, nbEqsCtxt, allZeros, nbTautoM = 0, nbTautoCtxt = 0;
Matrix * M = (*M1);
Matrix * Ctxt = (*Ctxt1);
int nbVars = M->NbColumns-Ctxt->NbColumns;
Matrix * Eqs;
Matrix * EqsMTmp;
/* 1- build the equality matrix(ces) */
nbEqsM = 0;
for (i=0; i< M->NbRows; i++) {
k = First_Non_Zero(M->p[i], M->NbColumns);
/* if it is a tautology, count it as such */
if (k==-1) {
nbTautoM++;
}
else {
/* if it only involves parameters, count it */
if (k>= nbVars+1) nbEqsM++;
}
}
nbEqsCtxt = 0;
for (i=0; i< Ctxt->NbRows; i++) {
if (value_zero_p(Ctxt->p[i][0])) {
if (First_Non_Zero(Ctxt->p[i], Ctxt->NbColumns)==-1) {
nbTautoCtxt++;
}
else {
nbEqsCtxt ++;
}
}
}
nbEqsParms = nbEqsM + nbEqsCtxt;
/* nothing to do in this case */
if (nbEqsParms+nbTautoM+nbTautoCtxt==0) {
(*elimParms) = (unsigned int*) malloc(sizeof(int));
(*elimParms)[0] = 0;
if (renderSpace==0) {
return Matrix_Alloc(0,Ctxt->NbColumns);
}
else {
return Matrix_Alloc(0,M->NbColumns);
}
}
Eqs= Matrix_Alloc(nbEqsParms, Ctxt->NbColumns);
EqsMTmp= Matrix_Alloc(nbEqsParms, M->NbColumns);
/* copy equalities from the context */
k = 0;
for (i=0; i< Ctxt->NbRows; i++) {
if (value_zero_p(Ctxt->p[i][0])
&& First_Non_Zero(Ctxt->p[i], Ctxt->NbColumns)!=-1) {
Vector_Copy(Ctxt->p[i], Eqs->p[k], Ctxt->NbColumns);
Vector_Copy(Ctxt->p[i]+1, EqsMTmp->p[k]+nbVars+1,
Ctxt->NbColumns-1);
k++;
}
}
for (i=0; i< M->NbRows; i++) {
j=First_Non_Zero(M->p[i], M->NbColumns);
/* copy equalities that involve only parameters from M */
if (j>=nbVars+1) {
Vector_Copy(M->p[i]+nbVars+1, Eqs->p[k]+1, Ctxt->NbColumns-1);
Vector_Copy(M->p[i]+nbVars+1, EqsMTmp->p[k]+nbVars+1,
Ctxt->NbColumns-1);
/* mark these equalities for removal */
value_set_si(M->p[i][0], 2);
k++;
}
/* mark the all-zero equalities for removal */
if (j==-1) {
value_set_si(M->p[i][0], 2);
}
}
/* 2- eliminate parameters until all equalities are used or until we find a
contradiction (overconstrained system) */
(*elimParms) = (unsigned int *) malloc((Eqs->NbRows+1) * sizeof(int));
(*elimParms)[0] = 0;
allZeros = 0;
for (i=0; i< Eqs->NbRows; i++) {
/* find a variable that can be eliminated */
k = First_Non_Zero(Eqs->p[i], Eqs->NbColumns);
if (k!=-1) { /* nothing special to do for tautologies */
/* if there is a contradiction, return empty matrices */
if (k==Eqs->NbColumns-1) {
printf("Contradiction in %dth row of Eqs: ",k);
show_matrix(Eqs);
Matrix_Free(Eqs);
Matrix_Free(EqsMTmp);
(*M1) = Matrix_Alloc(0, M->NbColumns);
Matrix_Free(M);
(*Ctxt1) = Matrix_Alloc(0,Ctxt->NbColumns);
Matrix_Free(Ctxt);
free(*elimParms);
(*elimParms) = (unsigned int *) malloc(sizeof(int));
(*elimParms)[0] = 0;
if (renderSpace==1) {
return Matrix_Alloc(0,(*M1)->NbColumns);
}
else {
return Matrix_Alloc(0,(*Ctxt1)->NbColumns);
}
}
/* if we have something we can eliminate, do it in 3 places:
Eqs, Ctxt, and M */
else {
k--; /* k is the rank of the variable, now */
(*elimParms)[0]++;
(*elimParms)[(*elimParms[0])]=k;
for (j=0; j< Eqs->NbRows; j++) {
if (i!=j) {
eliminate_var_with_constr(Eqs, i, Eqs, j, k);
eliminate_var_with_constr(EqsMTmp, i, EqsMTmp, j, k+nbVars);
}
}
for (j=0; j< Ctxt->NbRows; j++) {
if (value_notzero_p(Ctxt->p[i][0])) {
eliminate_var_with_constr(Eqs, i, Ctxt, j, k);
}
}
for (j=0; j< M->NbRows; j++) {
if (value_cmp_si(M->p[i][0], 2)) {
eliminate_var_with_constr(EqsMTmp, i, M, j, k+nbVars);
}
}
}
}
/* if (k==-1): count the tautologies in Eqs to remove them later */
else {
allZeros++;
}
}
/* elimParms may have been overallocated. Now we know how many parms have
been eliminated so we can reallocate the right amount of memory. */
if (!realloc((*elimParms), ((*elimParms)[0]+1)*sizeof(int))) {
fprintf(stderr, "Constraints_Remove_parm_eqs > cannot realloc()");
}
Matrix_Free(EqsMTmp);
/* 3- remove the "bad" equalities from the input matrices
and copy the equalities involving only parameters */
EqsMTmp = Matrix_Alloc(M->NbRows-nbEqsM-nbTautoM, M->NbColumns);
k=0;
for (i=0; i< M->NbRows; i++) {
if (value_cmp_si(M->p[i][0], 2)) {
Vector_Copy(M->p[i], EqsMTmp->p[k], M->NbColumns);
k++;
}
}
Matrix_Free(M);
(*M1) = EqsMTmp;
EqsMTmp = Matrix_Alloc(Ctxt->NbRows-nbEqsCtxt-nbTautoCtxt, Ctxt->NbColumns);
k=0;
for (i=0; i< Ctxt->NbRows; i++) {
if (value_notzero_p(Ctxt->p[i][0])) {
Vector_Copy(Ctxt->p[i], EqsMTmp->p[k], Ctxt->NbColumns);
k++;
}
}
Matrix_Free(Ctxt);
(*Ctxt1) = EqsMTmp;
if (renderSpace==0) {/* renderSpace=0: equalities in the parameter space */
EqsMTmp = Matrix_Alloc(Eqs->NbRows-allZeros, Eqs->NbColumns);
k=0;
for (i=0; i<Eqs->NbRows; i++) {
if (First_Non_Zero(Eqs->p[i], Eqs->NbColumns)!=-1) {
Vector_Copy(Eqs->p[i], EqsMTmp->p[k], Eqs->NbColumns);
k++;
}
}
}
else {/* renderSpace=1: equalities rendered in the combined space */
EqsMTmp = Matrix_Alloc(Eqs->NbRows-allZeros, (*M1)->NbColumns);
k=0;
for (i=0; i<Eqs->NbRows; i++) {
if (First_Non_Zero(Eqs->p[i], Eqs->NbColumns)!=-1) {
Vector_Copy(Eqs->p[i], &(EqsMTmp->p[k][nbVars]), Eqs->NbColumns);
k++;
}
}
}
Matrix_Free(Eqs);
Eqs = EqsMTmp;
return Eqs;
} /* Constraints_Remove_parm_eqs */
/** Removes equalities involving only parameters, but starting from a
* Polyhedron and its context.
* @param P the polyhedron
* @param C P's context
* @param renderSpace: 0 for the parameter space, =1 for the combined space.
* @maxRays Polylib's usual <i>workspace</i>.
*/
Polyhedron * Polyhedron_Remove_parm_eqs(Polyhedron ** P, Polyhedron ** C,
int renderSpace,
unsigned int ** elimParms,
int maxRays) {
Matrix * Eqs;
Polyhedron * Peqs;
Matrix * M = Polyhedron2Constraints((*P));
Matrix * Ct = Polyhedron2Constraints((*C));
/* if the Minkowski representation is not computed yet, do not compute it in
Constraints2Polyhedron */
if (F_ISSET((*P), POL_VALID | POL_INEQUALITIES) &&
(F_ISSET((*C), POL_VALID | POL_INEQUALITIES))) {
FL_INIT(maxRays, POL_NO_DUAL);
}
Eqs = Constraints_Remove_parm_eqs(&M, &Ct, renderSpace, elimParms);
Peqs = Constraints2Polyhedron(Eqs, maxRays);
Matrix_Free(Eqs);
/* particular case: no equality involving only parms is found */
if (Eqs->NbRows==0) {
Matrix_Free(M);
Matrix_Free(Ct);
return Peqs;
}
Polyhedron_Free(*P);
Polyhedron_Free(*C);
(*P) = Constraints2Polyhedron(M, maxRays);
(*C) = Constraints2Polyhedron(Ct, maxRays);
Matrix_Free(M);
Matrix_Free(Ct);
return Peqs;
} /* Polyhedron_Remove_parm_eqs */
/**
* Given a matrix with m parameterized equations, compress the nb_parms
* parameters and n-m variables so that m variables are integer, and transform
* the variable space into a n-m space by eliminating the m variables (using
* the equalities) the variables to be eliminated are chosen automatically by
* the function.
* <b>Deprecated.</b> Try to use Constraints_fullDimensionize instead.
* @param M the constraints
* @param the number of parameters
* @param validityLattice the the integer lattice underlying the integer
* solutions.
*/
Matrix * full_dimensionize(Matrix const * M, int nbParms,
Matrix ** validityLattice) {
Matrix * Eqs, * Ineqs;
Matrix * permutedEqs, * permutedIneqs;
Matrix * Full_Dim;
Matrix * WVL; /* The Whole Validity Lattice (vars+parms) */
unsigned int i,j;
int nbElimVars;
unsigned int * permutation, * permutationInv;
/* 0- Split the equalities and inequalities from each other */
split_constraints(M, &Eqs, &Ineqs);
/* 1- if the polyhedron is already full-dimensional, return it */
if (Eqs->NbRows==0) {
Matrix_Free(Eqs);
(*validityLattice) = Identity_Matrix(nbParms+1);
return Ineqs;
}
nbElimVars = Eqs->NbRows;
/* 2- put the vars to be eliminated at the first positions,
and compress the other vars/parms
-> [ variables to eliminate / parameters / variables to keep ] */
permutation = find_a_permutation(Eqs, nbParms);
if (dbgCompParm) {
printf("Permuting the vars/parms this way: [ ");
for (i=0; i< Eqs->NbColumns; i++) {
printf("%d ", permutation[i]);
}
printf("]\n");
}
permutedEqs = mpolyhedron_permute(Eqs, permutation);
WVL = compress_parms(permutedEqs, Eqs->NbColumns-2-Eqs->NbRows);
/* Check for empty WVL (no solution) */
if( !WVL )
{
fprintf(stderr,"full_dimensionize > parameters compression failed.\n");
Matrix_Free(Eqs);
Matrix_Free(Ineqs);
(*validityLattice) = Identity_Matrix(nbParms+1);
return NULL;
}
if (dbgCompParm) {
printf("Whole validity lattice: ");
show_matrix(WVL);
}
mpolyhedron_compress_last_vars(permutedEqs, WVL);
permutedIneqs = mpolyhedron_permute(Ineqs, permutation);
if (dbgCompParm) {
show_matrix(permutedEqs);
}
Matrix_Free(Eqs);
Matrix_Free(Ineqs);
mpolyhedron_compress_last_vars(permutedIneqs, WVL);
if (dbgCompParm) {
printf("After compression: ");
show_matrix(permutedIneqs);
}
/* 3- eliminate the first variables */
if (!mpolyhedron_eliminate_first_variables(permutedEqs, permutedIneqs)) {
fprintf(stderr,"full_dimensionize > variable elimination failed.\n");
Matrix_Free(permutedIneqs);
(*validityLattice) = Identity_Matrix(nbParms+1);
return NULL;
}
if (dbgCompParm) {
printf("After elimination of the variables: ");
show_matrix(permutedIneqs);
}
/* 4- get rid of the first (zero) columns,
which are now useless, and put the parameters back at the end */
Full_Dim = Matrix_Alloc(permutedIneqs->NbRows,
permutedIneqs->NbColumns-nbElimVars);
for (i=0; i< permutedIneqs->NbRows; i++) {
value_set_si(Full_Dim->p[i][0], 1);
for (j=0; j< nbParms; j++)
value_assign(Full_Dim->p[i][j+Full_Dim->NbColumns-nbParms-1],
permutedIneqs->p[i][j+nbElimVars+1]);
for (j=0; j< permutedIneqs->NbColumns-nbParms-2-nbElimVars; j++)
value_assign(Full_Dim->p[i][j+1],
permutedIneqs->p[i][nbElimVars+nbParms+j+1]);
value_assign(Full_Dim->p[i][Full_Dim->NbColumns-1],
permutedIneqs->p[i][permutedIneqs->NbColumns-1]);
}
Matrix_Free(permutedIneqs);
/* 5- Keep only the the validity lattice restricted to the parameters */
*validityLattice = Matrix_Alloc(nbParms+1, nbParms+1);
for (i=0; i< nbParms; i++) {
for (j=0; j< nbParms; j++)
value_assign((*validityLattice)->p[i][j],
WVL->p[i][j]);
value_assign((*validityLattice)->p[i][nbParms],
WVL->p[i][WVL->NbColumns-1]);
}
for (j=0; j< nbParms; j++)
value_set_si((*validityLattice)->p[nbParms][j], 0);
value_assign((*validityLattice)->p[nbParms][nbParms],
WVL->p[WVL->NbColumns-1][WVL->NbColumns-1]);
/* 6- Clean up */
Matrix_Free(WVL);
return Full_Dim;
} /* full_dimensionize */
#undef dbgCompParm
#undef dbgCompParmMore
| 2.65625 | 3 |
2024-11-18T21:10:22.749148+00:00
| 2021-03-29T12:57:25 |
002a58e6694fe08f17aa3a7280a6b739df270a0d
|
{
"blob_id": "002a58e6694fe08f17aa3a7280a6b739df270a0d",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-29T12:57:25",
"content_id": "6671588240cf3ebded15453ed716017046be561e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "17e4f3794efea07ea2afb7c432b265fe96a8c916",
"extension": "c",
"filename": "pdo_external_position_reg.c",
"fork_events_count": 7,
"gha_created_at": "2018-06-22T14:55:02",
"gha_event_created_at": "2018-09-14T09:26:34",
"gha_language": "C",
"gha_license_id": null,
"github_id": 138314986,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6595,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/c/tutorial/pdo_external_position_reg.c",
"provenance": "stackv2-0065.json.gz:39833",
"repo_name": "rozum-robotics/Rozum-Servo-Drives-API",
"revision_date": "2021-03-29T12:57:25",
"revision_id": "6657372870e6235089e38a68a422ea2d4dc4b0c3",
"snapshot_id": "751a71ddaa8412654a236034a92ac519292db0cf",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/rozum-robotics/Rozum-Servo-Drives-API/6657372870e6235089e38a68a422ea2d4dc4b0c3/c/tutorial/pdo_external_position_reg.c",
"visit_date": "2021-06-06T19:49:11.380481"
}
|
stackv2
|
/*
This example shows how to control servo by position with external position controller.
Servo itself runs in velocity mode. This program can be easily extended to number of devices
making some synchronized movements.
Servo will move to desired position (actual position + TDIST) and back.
*/
#ifndef WIN32
#define LINUX_RT_FEATURES
#endif
//have to be incleded first
#include "rt.h"
#include "api.h"
#include "pprof.h"
#include "vdelay.h"
#include "math_macro.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <sys/time.h>
//profiler instance
pprof_t p;
//delay instance
//used to compensate delay in actual position
//due to communication
vdelay_t vd;
//set profiler config
const double VMAX = 50.0, AMAX = 100;
//set proportional position regulator gain
//position regulator will be simply P-regulator
const double PKP = 20.0;
//define control loop cycle time
const double dt = 1.0 / 250.0;
//storage for desired position
float pd;
//setup travel distance
const double TDIST = 300.0;
//file discriptor to write data to
FILE *fout = 0;
//small state machine to control desired position
typedef enum
{
ST_START_DELAY,
ST_GO_FORWARD,
ST_MIDLE_DELAY,
ST_GO_BACK,
ST_FINAL_DELAY,
ST_FINISHED
} state_t;
state_t state = 0;
double dly_cntr = 0;
//Here is definition of PDO objects to communicate with servo
typedef struct
{
uint8_t mode;
uint8_t iwin;
int16_t des_curr;
float des_vel;
} rpdo0_t; //to servo
typedef struct
{
float pos;
int16_t act_vel;
int16_t act_curr;
} tpdo0_t; //from servo
/*
Callback function for receiving incoming PDO
*/
void pdo_cb(rr_can_interface_t *iface, int id, rr_pdo_n_t pdo_n, int len, uint8_t *data)
{
switch(pdo_n)
{
case TPDO0:
{
tpdo0_t tpdo0;
memcpy(&tpdo0, data, len);
//store previous velocity
double v = p.v;
//profiler needs some oversampling for better performance
for(int i = 0; i < 100; i++)
{
pprof_process(&p, pd, VMAX, AMAX, dt / 100.0);
}
vdelay_process(&vd, p.p);
//calculate acceleration
double a = (p.v - v) / dt;
//calculate velocity setpoint: profiler velocity command plus Kp * pos_error
double des_vel = p.v + PKP * (vd.y - tpdo0.pos);
//RD60 rotor inertia
const double jm = 1.7e-5;
//gear ratio
const double kg = 100;
//RD60 torque constant
const double kt = 0.059;
//static friction
const double fs = 0.02;
//feed-forward current
double ff = ((a * kg * M_PI / 180.0) * jm + SIGN(p.v) * fs) / kt;
//prepare PDO for transmitting
rpdo0_t rpdo0 =
{
.mode = 2, // velocity with feed-forward
.iwin = 255, // 100% of max. current
.des_vel = des_vel / 0.06, //converting deg/s to RPMs on fast shaft (gear ratio 100)
.des_curr = ff / 0.0016,
};
rr_send_pdo(iface, id, RPDO0, sizeof(rpdo0), (uint8_t *)&rpdo0);
fprintf(fout, "%f, %f, %f, %f, %f, %f, %f\n",
vd.y, p.v, a, ff,
tpdo0.pos, tpdo0.act_vel * 0.02, tpdo0.act_curr * 0.0016);
//process state machine
switch(state)
{
case ST_START_DELAY:
if(dly_cntr < 0.5)
{
dly_cntr += dt;
}
else
{
dly_cntr = 0;
state = ST_GO_FORWARD;
pd += TDIST;
}
break;
case ST_GO_FORWARD:
if(!pprof_is_running(&p))
{
state = ST_MIDLE_DELAY;
}
break;
case ST_MIDLE_DELAY:
if(dly_cntr < 0.5)
{
dly_cntr += dt;
}
else
{
dly_cntr = 0;
state = ST_GO_BACK;
pd -= TDIST;
}
break;
case ST_GO_BACK:
if(!pprof_is_running(&p))
{
state = ST_FINAL_DELAY;
}
break;
case ST_FINAL_DELAY:
if(dly_cntr < 0.5)
{
dly_cntr += dt;
}
else
{
state = ST_FINISHED;
}
break;
default:
break;
}
}
break;
case TPDO1:
break;
case TPDO2:
break;
case TPDO3:
break;
}
return;
}
int main(int argc, char *argv[])
{
bool high_prio = false;
uint8_t id;
if(argc >= 3)
{
id = strtol(argv[2], NULL, 0);
}
else
{
API_DEBUG("Wrong format!\nUsage: %s interface id [output file]\n", argv[0]);
return 1;
}
rr_can_interface_t *iface = rr_init_interface(argv[1]);
if(!iface)
{
API_DEBUG("Interface init error\n");
return 1;
}
rr_servo_t *servo = rr_init_servo(iface, id);
if(!servo)
{
API_DEBUG("Servo init error\n");
return 1;
}
if(argc == 4)
{
fout = fopen(argv[3], "wb");
}
else
{
fout = stdout;
}
#ifdef LINUX_RT_FEATURES
/*
For real effect from RT features it's recommended to
use RT kernel patch together with
'isolcpus = {your-preffered-cpu-number}' kernel option.
*/
#define CPU_N 0
/*
When working through an ethernet adapter set this
field to your network interface name.
Binding process and NIC interrupt to the same CPU
removes unnecessary inter-CPU data exchange thus
reducing latency and cycle time stability.
*/
#define NIC_NAME "enp59s0"
//disable CPU sleep states
set_latency_target(0);
//bind process to specified CPU
set_cpu_affinity(1 << CPU_N);
//bind network card interrupt to specified CPU
set_nic_irq_affinity(NIC_NAME, 1 << CPU_N);
//set lowest process niceness
set_process_niceness(-20);
//set process priority to some high value
high_prio = set_process_priority(pthread_self(), 98);
#endif
rr_setup_pdo_callback(iface, pdo_cb);
//reset cycle time
rr_pdo_set_cycle_time(servo, 0);
//reset communication (and cycle time errors if they are)
rr_servo_reset_communication(servo);
rr_servo_set_state_operational(servo);
//read current servo position
if(rr_read_parameter(servo, APP_PARAM_POSITION, &pd) != RET_OK)
{
printf("error: can't read servo position\n");
}
float vel_rate_orig;
//get current velocity rate to restore later
rr_get_velocity_rate(servo, &vel_rate_orig);
//set very high velocity rate, profiler will take care of changing velocity with correct rate
rr_set_velocity_rate(servo, 1e6);
//prepare profiler
pprof_init(&p);
pprof_set(&p, pd, 0);
//prepare delay
vdelay_init(&vd, pd, 2.0);
//set cycle time, the servo will turn off if cycle time exceeded 1.5 times the nominal value
if(high_prio)
{
//make sure we are running high priority process
//process with generic priority may suffer from high jitter
//and servo may go to pre-op state if cycly time violated
rr_pdo_set_cycle_time(servo, 1.0e6 * dt);
}
interval_sleep(0);
//start sending sync with rate of control loop
while(state != ST_FINISHED)
{
rr_send_pdo_sync(iface);
interval_sleep(1.0e9 * dt);
}
rr_set_velocity_rate(servo, vel_rate_orig);
}
| 2.6875 | 3 |
2024-11-18T21:10:22.824305+00:00
| 2023-01-03T21:21:24 |
d3ce25c97831599234adf79733ec22892d69079d
|
{
"blob_id": "d3ce25c97831599234adf79733ec22892d69079d",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-03T21:21:24",
"content_id": "c558d3268edff7383cbddddaa2adf3944d6c2b7a",
"detected_licenses": [
"MIT"
],
"directory_id": "7c8808f864a87a8dd846a1a9fb3e577e2cad8da4",
"extension": "c",
"filename": "kmathlib.c",
"fork_events_count": 9,
"gha_created_at": "2012-05-09T03:07:22",
"gha_event_created_at": "2021-05-05T15:24:57",
"gha_language": "C",
"gha_license_id": null,
"github_id": 4267872,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7368,
"license": "MIT",
"license_type": "permissive",
"path": "/src/kmathlib.c",
"provenance": "stackv2-0065.json.gz:39961",
"repo_name": "ex/Killa",
"revision_date": "2023-01-03T21:21:24",
"revision_id": "d0fb8f930b3271d0cf94539fbf4c1efddb25b1e2",
"snapshot_id": "f42fe3ebe5604750f418c21bdf408d19685e8622",
"src_encoding": "UTF-8",
"star_events_count": 49,
"url": "https://raw.githubusercontent.com/ex/Killa/d0fb8f930b3271d0cf94539fbf4c1efddb25b1e2/src/kmathlib.c",
"visit_date": "2023-01-27T19:18:54.810936"
}
|
stackv2
|
/* ========================================================================== */
/* Standard mathematical library */
/* -------------------------------------------------------------------------- */
/* Copyright (c) 2012 Laurens Rodriguez Oscanoa. */
/* Copyright (C) 1994-2012 Lua.org, PUC-Rio. */
/* */
/* This code is licensed under the MIT license: */
/* http://www.opensource.org/licenses/mit-license.php */
/* -------------------------------------------------------------------------- */
#include <stdlib.h>
#include <math.h>
#define KILLA_LIB
#include "killa.h"
#include "kauxlib.h"
#include "killalib.h"
#undef PI
#define PI (3.14159265358979323846)
#define RADIANS_PER_DEGREE (PI/180.0)
/* macro 'l_tg' allows the addition of an 'l' or 'f' to all math operations */
#if !defined(l_tg)
#define l_tg(x) (x)
#endif
static int math_abs (killa_State *L) {
killa_pushnumber(L, l_tg(fabs)(killaL_checknumber(L, 1)));
return 1;
}
static int math_sin (killa_State *L) {
killa_pushnumber(L, l_tg(sin)(killaL_checknumber(L, 1)));
return 1;
}
static int math_sinh (killa_State *L) {
killa_pushnumber(L, l_tg(sinh)(killaL_checknumber(L, 1)));
return 1;
}
static int math_cos (killa_State *L) {
killa_pushnumber(L, l_tg(cos)(killaL_checknumber(L, 1)));
return 1;
}
static int math_cosh (killa_State *L) {
killa_pushnumber(L, l_tg(cosh)(killaL_checknumber(L, 1)));
return 1;
}
static int math_tan (killa_State *L) {
killa_pushnumber(L, l_tg(tan)(killaL_checknumber(L, 1)));
return 1;
}
static int math_tanh (killa_State *L) {
killa_pushnumber(L, l_tg(tanh)(killaL_checknumber(L, 1)));
return 1;
}
static int math_asin (killa_State *L) {
killa_pushnumber(L, l_tg(asin)(killaL_checknumber(L, 1)));
return 1;
}
static int math_acos (killa_State *L) {
killa_pushnumber(L, l_tg(acos)(killaL_checknumber(L, 1)));
return 1;
}
static int math_atan (killa_State *L) {
killa_pushnumber(L, l_tg(atan)(killaL_checknumber(L, 1)));
return 1;
}
static int math_atan2 (killa_State *L) {
killa_pushnumber(L, l_tg(atan2)(killaL_checknumber(L, 1),
killaL_checknumber(L, 2)));
return 1;
}
static int math_ceil (killa_State *L) {
killa_pushnumber(L, l_tg(ceil)(killaL_checknumber(L, 1)));
return 1;
}
static int math_floor (killa_State *L) {
killa_pushnumber(L, l_tg(floor)(killaL_checknumber(L, 1)));
return 1;
}
static int math_fmod (killa_State *L) {
killa_pushnumber(L, l_tg(fmod)(killaL_checknumber(L, 1),
killaL_checknumber(L, 2)));
return 1;
}
static int math_modf (killa_State *L) {
killa_Number ip;
killa_Number fp = l_tg(modf)(killaL_checknumber(L, 1), &ip);
killa_pushnumber(L, ip);
killa_pushnumber(L, fp);
return 2;
}
static int math_sqrt (killa_State *L) {
killa_pushnumber(L, l_tg(sqrt)(killaL_checknumber(L, 1)));
return 1;
}
static int math_pow (killa_State *L) {
killa_pushnumber(L, l_tg(pow)(killaL_checknumber(L, 1),
killaL_checknumber(L, 2)));
return 1;
}
static int math_log (killa_State *L) {
killa_Number x = killaL_checknumber(L, 1);
killa_Number res;
if (killa_isnoneornull(L, 2))
res = l_tg(log)(x);
else {
killa_Number base = killaL_checknumber(L, 2);
if (base == 10.0) res = l_tg(log10)(x);
else res = l_tg(log)(x)/l_tg(log)(base);
}
killa_pushnumber(L, res);
return 1;
}
#if defined(KILLA_COMPAT_LOG10)
static int math_log10 (killa_State *L) {
killa_pushnumber(L, l_tg(log10)(killaL_checknumber(L, 1)));
return 1;
}
#endif
static int math_exp (killa_State *L) {
killa_pushnumber(L, l_tg(exp)(killaL_checknumber(L, 1)));
return 1;
}
static int math_deg (killa_State *L) {
killa_pushnumber(L, killaL_checknumber(L, 1)/RADIANS_PER_DEGREE);
return 1;
}
static int math_rad (killa_State *L) {
killa_pushnumber(L, killaL_checknumber(L, 1)*RADIANS_PER_DEGREE);
return 1;
}
static int math_frexp (killa_State *L) {
int e;
killa_pushnumber(L, l_tg(frexp)(killaL_checknumber(L, 1), &e));
killa_pushinteger(L, e);
return 2;
}
static int math_ldexp (killa_State *L) {
killa_pushnumber(L, l_tg(ldexp)(killaL_checknumber(L, 1),
killaL_checkint(L, 2)));
return 1;
}
static int math_min (killa_State *L) {
int n = killa_gettop(L); /* number of arguments */
killa_Number dmin = killaL_checknumber(L, 1);
int i;
for (i=2; i<=n; i++) {
killa_Number d = killaL_checknumber(L, i);
if (d < dmin)
dmin = d;
}
killa_pushnumber(L, dmin);
return 1;
}
static int math_max (killa_State *L) {
int n = killa_gettop(L); /* number of arguments */
killa_Number dmax = killaL_checknumber(L, 1);
int i;
for (i=2; i<=n; i++) {
killa_Number d = killaL_checknumber(L, i);
if (d > dmax)
dmax = d;
}
killa_pushnumber(L, dmax);
return 1;
}
static int math_random (killa_State *L) {
/* the `%' avoids the (rare) case of r==1, and is needed also because on
some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */
killa_Number r = (killa_Number)(rand()%RAND_MAX) / (killa_Number)RAND_MAX;
switch (killa_gettop(L)) { /* check number of arguments */
case 0: { /* no arguments */
killa_pushnumber(L, r); /* Number between 0 and 1 */
break;
}
case 1: { /* only upper limit */
killa_Number u = killaL_checknumber(L, 1);
killaL_argcheck(L, 1.0 <= u, 1, "interval is empty");
killa_pushnumber(L, l_tg(floor)(r*u) + 1.0); /* int in [1, u] */
break;
}
case 2: { /* lower and upper limits */
killa_Number l = killaL_checknumber(L, 1);
killa_Number u = killaL_checknumber(L, 2);
killaL_argcheck(L, l <= u, 2, "interval is empty");
killa_pushnumber(L, l_tg(floor)(r*(u-l+1)) + l); /* int in [l, u] */
break;
}
default: return killaL_error(L, "wrong number of arguments");
}
return 1;
}
static int math_randomseed (killa_State *L) {
srand(killaL_checkunsigned(L, 1));
(void)rand(); /* discard first value to avoid undesirable correlations */
return 0;
}
static const killaL_Reg mathlib[] = {
{"abs", math_abs},
{"acos", math_acos},
{"asin", math_asin},
{"atan2", math_atan2},
{"atan", math_atan},
{"ceil", math_ceil},
{"cosh", math_cosh},
{"cos", math_cos},
{"deg", math_deg},
{"exp", math_exp},
{"floor", math_floor},
{"fmod", math_fmod},
{"frexp", math_frexp},
{"ldexp", math_ldexp},
#if defined(KILLA_COMPAT_LOG10)
{"log10", math_log10},
#endif
{"log", math_log},
{"max", math_max},
{"min", math_min},
{"modf", math_modf},
{"pow", math_pow},
{"rad", math_rad},
{"random", math_random},
{"randomseed", math_randomseed},
{"sinh", math_sinh},
{"sin", math_sin},
{"sqrt", math_sqrt},
{"tanh", math_tanh},
{"tan", math_tan},
{NULL, NULL}
};
/*
** Open math library
*/
KILLAMOD_API int killaopen_math (killa_State *L) {
killaL_newlib(L, mathlib);
killa_pushnumber(L, PI);
killa_setfield(L, -2, "pi");
killa_pushnumber(L, HUGE_VAL);
killa_setfield(L, -2, "huge");
return 1;
}
| 2.21875 | 2 |
2024-11-18T21:10:22.915976+00:00
| 2019-04-08T04:49:38 |
57e474e374eededdf25eacda0b888b39a5b3a402
|
{
"blob_id": "57e474e374eededdf25eacda0b888b39a5b3a402",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-08T04:49:38",
"content_id": "d854ad132ce659a6439d7a8a65de156d0a5c6b34",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "727fc6d6e4489fc1287da2ed202d73f2218a08e3",
"extension": "c",
"filename": "intHandlers.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 133698332,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8561,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/Kernel/interruptions/intHandlers.c",
"provenance": "stackv2-0065.json.gz:40089",
"repo_name": "atharos1/Leah",
"revision_date": "2019-04-08T04:49:38",
"revision_id": "b12872f1e69a4f3c1112bec8bca5953563f70ff9",
"snapshot_id": "eae6d14ebbeaf83de4268b3e23f200e6d676a64e",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/atharos1/Leah/b12872f1e69a4f3c1112bec8bca5953563f70ff9/Kernel/interruptions/intHandlers.c",
"visit_date": "2020-03-17T15:06:05.537970"
}
|
stackv2
|
#include <stdint.h>
#include "../asm/libasm.h"
#include "../drivers/include/console.h"
#include "../drivers/include/kb_driver.h"
#include "../drivers/include/speaker.h"
#include "../drivers/include/timer.h"
#include "../drivers/include/video_vm.h"
#include "../include/fileSystem.h"
#include "../include/memoryManagerTest.h"
#include "../include/roundRobinWithPriority.h"
#include "../include/scheduler.h"
#include "../include/sleep.h"
#include "../drivers/include/kb_driver.h"
struct bgnode {
thread_t* thread;
struct bgnode* next;
};
typedef struct bgnode* bgNode;
bgNode bgQueue = NULL;
int foregroundPID = 0;
int getForegroundPID() { return foregroundPID; }
void giveForeground(int pid) {
// if(!isValidProcess(pid) || pid == foregroundPID)
if (pid == foregroundPID) return;
foregroundPID = pid;
bgNode curr = bgQueue;
bgNode prev = NULL, aux;
while (curr != NULL) {
if (curr->thread->process == pid) {
scheduler_enqueue(curr->thread, 0);
if (prev == NULL) { // primero
bgQueue = curr->next;
} else {
prev->next = curr->next;
}
aux = curr;
curr = curr->next;
freeMemory(aux);
} else {
prev = curr;
curr = curr->next;
}
}
}
int int80Handler(uint64_t rdi, uint64_t rsi, uint64_t rdx, uint64_t rcx,
uint64_t r8) {
switch (rdi) {
case 1: // Exit
while (1) {
printf("Codigo de salida: %d\n", rsi);
_halt();
}
break;
case 3: // Read
if (rsi == 0 &&
getProcessByPID(getCurrentPID())->fd_table[rsi] == NULL &&
getCurrentPID() != foregroundPID) { // No es el current
thread_t* current = scheduler_dequeue_current();
bgNode n = getMemory(sizeof(struct bgnode));
n->thread = current;
if (bgQueue == NULL)
bgQueue = n;
else
bgQueue->next = n;
_force_scheduler();
}
return readFromFD(rsi, (char*)rdx, rcx);
break;
case 4: // Write
if ((rsi == 1 || rsi == 2) &&
getProcessByPID(getCurrentPID())->fd_table[rsi] == NULL) {
if (rsi == 2) { // STD_ERR
setFontColor(0x000000);
setBackgroundColor(0xDC143C);
}
char* str = (char*)rdx;
int i;
for (i = 0; i < rcx; i++) printChar(str[i]);
return i;
} else {
return writeToFD(rsi, (char*)rdx, rcx);
}
break;
case 5: // ClearScreen
clearScreen();
return 0;
break;
case 6: // setFontColor
setFontColor(rsi);
// printf("color: %d", rsi);
return 0;
break;
case 7: // setBackgroundColor
setBackgroundColor(rsi);
return 0;
break;
case 8: // setFontSize
setFontSize(rsi);
return 0;
break;
case 9:
return getFontColor();
break;
case 10:
return getBackgroundColor();
break;
case 11:
return getFontSize();
break;
case 12: // drawPixel
drawPixel(rsi, rdx, rcx);
return 0;
break;
case 13: // setCursor
setCursor(rsi, rdx);
return 0;
break;
case 14: // setGraphicCursorStatus
setGraphicCursorStatus(rsi);
return 0;
break;
case 15:
return SCREEN_HEIGHT;
break;
case 16:
return SCREEN_WIDTH;
break;
case 17: // sys_memoryManagerTest
memoryManagerTest(rsi);
break;
case 18: // sys_listDir
listDir((char*)rsi);
break;
case 19: // sys_makeFile
makeFile((char*)rsi, rdx);
break;
case 20: // sys_removeFile
return removeFileFromPath((char*)rsi);
break;
case 21: // sys_open
return openFileFromPathToFD((char*)rsi, rdx);
break;
case 22: // sys_close
closeFileFromFD(rsi);
break;
case 23: // sys_semCreate
semCreate((char*)rsi, rdx);
break;
case 24: // sys_semDelete
semDelete((char*)rsi);
break;
case 25: // sys_semOpen
return semOpen((char*)rsi);
break;
case 26: // sys_semClose
semClose(rsi);
break;
case 27: // sys_semSet
semSet(rsi, rdx);
break;
case 28: // sys_semWait
semWait(rsi);
break;
case 29: // sys_semSignal
semSignal(rsi);
break;
case 30: // sys_mutexCreate
mutexCreate((char*)rsi);
break;
case 31: // sys_mutexDelete
mutexDelete((char*)rsi);
break;
case 32: // sys_mutexOpen
return mutexOpen((char*)rsi);
break;
case 33: // sys_mutexClose
mutexClose(rsi);
break;
case 34: // sys_mutexLock
mutexLock(rsi);
break;
case 35: // sys_mutexUnlock
mutexUnlock(rsi);
break;
case 36: // sys_chdir
changeCWD((char*)rsi);
break;
case 37: // sys_getcwd
getCWDPath((char*)rsi);
break;
case 38: // sys_pipe
openUnnamedPipe((int*)rsi);
break;
case 39: // sys_execCreate
execCreate((char*)rsi, (void*)rdx);
break;
case 40: // sleep
sleepCurrentThread(rsi);
break;
case 41: // ps
listProcess((ps_struct*)rsi, (int*)rdx);
break;
case 42: // new process
return createProcess((char*)rsi, (void*)rdx, (char**)rcx, 4, 4,
(int**)r8);
break;
case 43: // waitpid
return waitpid(rsi);
break;
case 44: // getHeapSize
return getHeapSize(getCurrentPID());
break;
case 45: // getHeapBase
return (uint64_t)getHeapBase(getCurrentPID());
break;
case 46: // killProcess
killProcess((int)rsi, -1);
break;
case 47: // exit
killProcess(getCurrentPID(), (int)rsi);
break;
case 48: // giveForeground
giveForeground((int)rsi);
break;
case 49: // dup2
dup2(rsi, rdx);
break;
case 50: // new thread
return createThread(getProcessByPID(getCurrentPID()), (void*)rsi,
(void*)rdx, 4, FALSE)
->tid;
break;
case 51: // thread join
threadJoin(rsi, (void**)rdx);
break;
case 52: // thread cancel
killThread(getCurrentPID(), rsi, FALSE);
break;
case 53: // nice
return setNiceness(rsi, rdx);
break;
case 100: // timerAppend, return 0 if successful, -1 if error
// printf("\nParametros: RAX %d rsi %d rdx %d RDX %d\n", rdi, rsi,
// rdx, rcx);
return timer_appendFunction((function)rsi, rdx);
break;
case 101: // timerRemove, return 0 if successful, -1 if error
return timer_removeFunction((function)rsi);
break;
case 102: // beep
beep(rsi, rdx);
return 0;
break;
case 103: // nosound
nosound();
return 0;
break;
case 200: // RTC
//_outportb(0x70, rsi);
// return _inportb(0x71);
return _RTC(rsi);
break;
}
return 0;
}
| 2.40625 | 2 |
2024-11-18T21:10:23.010182+00:00
| 2022-03-01T22:33:16 |
c317307a596ea788fc501a82ac476a3e96aef6aa
|
{
"blob_id": "c317307a596ea788fc501a82ac476a3e96aef6aa",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-12T17:03:27",
"content_id": "f711f9231c00ceaaf85a888e0577a56c3f4329a4",
"detected_licenses": [
"MIT"
],
"directory_id": "c7308b6f7534ec1d08d02ff7882020636f42a2cb",
"extension": "c",
"filename": "shadow_compatible.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": 253,
"license": "MIT",
"license_type": "permissive",
"path": "/test/cases/scope/shadow_compatible.c",
"provenance": "stackv2-0065.json.gz:40218",
"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/scope/shadow_compatible.c",
"visit_date": "2023-06-21T22:25:07.825365"
}
|
stackv2
|
// RUN: %check --only %s -Wshadow=compatible-local -Wno-sym-never-written
void f()
{
int i; // no warning here
{
char i; // CHECK: note: local declaration here
{
char i; // CHECK: warning: declaration of "i" shadows local declaration
}
}
}
| 2.234375 | 2 |
2024-11-18T21:10:24.357841+00:00
| 2018-04-26T19:36:41 |
8f6d6db363e892e7494c6a59972e2926f8f25350
|
{
"blob_id": "8f6d6db363e892e7494c6a59972e2926f8f25350",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-26T19:36:41",
"content_id": "858866c997ad852406e65be33da560563d1b4036",
"detected_licenses": [
"MIT"
],
"directory_id": "24e06e0fec590172490f7031f329390b3bc7f65c",
"extension": "c",
"filename": "mpi.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 119591512,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 801,
"license": "MIT",
"license_type": "permissive",
"path": "/L11/L11/mpi.c",
"provenance": "stackv2-0065.json.gz:40476",
"repo_name": "taylorkd/CMDA3634",
"revision_date": "2018-04-26T19:36:41",
"revision_id": "96a1f5834bc51ad77d301b54b980c92885f6a72d",
"snapshot_id": "a3355ab1888070928978a40c9e1a49ab14fb5216",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/taylorkd/CMDA3634/96a1f5834bc51ad77d301b54b980c92885f6a72d/L11/L11/mpi.c",
"visit_date": "2021-05-08T20:02:25.552272"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "mpi.h"
int main(int argc, int **argv){
//need running tallies
int rank,size;
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
long long int Ntotal;
long long int Ncircle;
//seed random number generator
double seed = 1.0;
srand48(seed);
for( rank=0;rank<size;rank++)
{
printf("Rank:%d Size:%d",rank,size);
double rand1 = drand48();//drand48 returns a number between 0 and 1
double rand2 = drand48();
double x = -1 +2*rand1;//shift to [-1,1]
double y = -1 +2*rand2;
MPI_Allreduce(&x,&y,1,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
if(sqrt(x*x+y*y)<=1) Ncircle++;
Ntotal++;
}
double pi = 4.0*Ncircle/ (double) Ntotal;
if(rank==0){
printf("Our estimate of pi is %f \n",pi);
}
MPI_Finalize();
return 0;
}
| 2.65625 | 3 |
2024-11-18T21:10:24.476027+00:00
| 2020-09-23T09:11:48 |
b2edbe64a7568eb25398b92d28c796b2553e962e
|
{
"blob_id": "b2edbe64a7568eb25398b92d28c796b2553e962e",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-23T09:11:48",
"content_id": "5b437000c6f1a89cd2c6a28e3cfc26ac7b42e7bb",
"detected_licenses": [
"MIT"
],
"directory_id": "2bb354ef07f9043ddaad5ffb09a20b34447cd9d5",
"extension": "c",
"filename": "queue.C",
"fork_events_count": 6,
"gha_created_at": "2019-02-11T15:15:03",
"gha_event_created_at": "2019-02-16T06:49:23",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 170150311,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1366,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/queue.C",
"provenance": "stackv2-0065.json.gz:40604",
"repo_name": "niravcodes/huffman_compression",
"revision_date": "2020-09-23T09:11:48",
"revision_id": "c0ef06429b617a16aa236082423f36fb0516299c",
"snapshot_id": "ddfcfbdd8f7357da4852febb72171422988f3a6c",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/niravcodes/huffman_compression/c0ef06429b617a16aa236082423f36fb0516299c/tests/queue.C",
"visit_date": "2021-07-02T05:12:07.908344"
}
|
stackv2
|
#include "../corelib/priority_queue.h"
#include "../corelib/tree.h"
#include <iostream>
using namespace std;
void interactive_q()
{
char c = 0;
unsigned data, freq;
tree::node x;
queue q;
while (c != 'q')
{
cout << endl;
cout << "a to enqueue, s to dequeue" << endl
<< "i to print whole queue, q to quit" << endl;
cin >> c;
if (c == 'a')
{
cout << "input data freq" << endl;
cin >> data >> freq;
x = tree::node(data, freq, 0, 0);
q.enqueue(x);
}
else if (c == 's')
{
if (q.is_empty())
{
cout << "empty queue" << endl;
}
//dequeue should not crash if empty
cout << q.dequeue() << endl;
if (q.is_empty())
{
cout << "empty queue" << endl;
}
}
else if (c == 'i')
{
while (!q.is_empty())
{
cout << q.dequeue() << endl;
}
cout << "q emptied" << endl;
}
}
}
void simple_test()
{
queue q;
tree::node x(2, 10, 0, 0);
q.enqueue(x);
x = tree::node(1, 4, 0, 0);
q.enqueue(x);
cout << q.dequeue() << endl;
cout << q.dequeue() << endl;
}
int main()
{
interactive_q();
}
| 2.890625 | 3 |
2024-11-18T21:08:23.194168+00:00
| 2013-04-29T16:19:52 |
df13cfb4df6364aa58642540c0dce4d9c71301d9
|
{
"blob_id": "df13cfb4df6364aa58642540c0dce4d9c71301d9",
"branch_name": "refs/heads/master",
"committer_date": "2013-04-29T16:19:52",
"content_id": "c84290d786fea4dbf4e05cbb265d2e79b6dcf633",
"detected_licenses": [
"MIT"
],
"directory_id": "f832a94d06938e4605b36ab0405c3e12db1b292d",
"extension": "c",
"filename": "stopwatch.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": 7645,
"license": "MIT",
"license_type": "permissive",
"path": "/src/stopwatch.c",
"provenance": "stackv2-0069.json.gz:237772",
"repo_name": "BitHangar/app-stopwatch",
"revision_date": "2013-04-29T16:19:52",
"revision_id": "2c23a3cf0d29a6876313d60998fc4a33b237d8cd",
"snapshot_id": "5f4ffba92d585e13aea89fa05b33c72a0a07fe69",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BitHangar/app-stopwatch/2c23a3cf0d29a6876313d60998fc4a33b237d8cd/src/stopwatch.c",
"visit_date": "2016-09-05T20:56:09.714250"
}
|
stackv2
|
/*Copyright (c) 2013 Bit Hangar
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 "pebble_os.h"
#include "pebble_app.h"
#include "pebble_fonts.h"
#include "timer.h"
#define MY_UUID { 0x7D, 0xAF, 0xEB, 0x68, 0xBF, 0x5C, 0x4B, 0x9F, 0xB6, 0xA3, 0x73, 0x8F, 0x6A, 0xBC, 0xE7, 0xEF }
//function prototypes
void secondTick();
void handle_timer(AppContextRef app_ctx, AppTimerHandle handle, uint32_t cookie);
void start_button_handler(ClickRecognizerRef recognizer, Window *window);
void reset_button_handler(ClickRecognizerRef recognizer, Window *window);
void split_button_handler(ClickRecognizerRef recognizer, Window *window);
void config_provider(ClickConfig **config, Window *window);
void handle_init_app(AppContextRef app_ctx);
void handle_deinit(AppContextRef ctx);
void pbl_main(void *params);
PBL_APP_INFO(MY_UUID,
"Stopwatch", "Bit Hangar",
1, 1, /* App version */
RESOURCE_ID_MENU_ICON,
0);
//Application window
Window window;
AppContextRef global_ctx;
//Background layer for stopwatch
static BmpContainer backgroundImage;
//Text layers for time
static TextLayer countLayer;
static TextLayer dSecondsLayer;
static TextLayer splitLayer;
static AppTimerHandle timer_handle;
static char timeText[] = "00:00:00";
static int dSeconds = 0;
void secondTick() {
//Recalculate time with Pebble time
PblTm outTime = get_display_time();
//format and display
string_format_time(timeText, sizeof(timeText), "%T", &outTime);
text_layer_set_text(&countLayer, timeText);
}
void handle_timer(AppContextRef app_ctx, AppTimerHandle handle, uint32_t cookie) {
(void)app_ctx;
(void)handle;
dSeconds = update_timer();
//Static due to pebble 'set_text'
static char out[] = ".0";
//Convert decisecond to character
out[1] = (char)dSeconds+48;
text_layer_set_text(&dSecondsLayer, out);
//After 10 deciseconds, get full time by Pebble time comparison
if (dSeconds == 0)
secondTick();
//Keep timer going for each decisecond
if (is_timer_running())
timer_handle = app_timer_send_event(app_ctx, 100 , cookie);
}
void start_button_handler(ClickRecognizerRef recognizer, Window *window) {
(void)recognizer;
(void)window;
//Start if not running, Stop if running
if (!is_timer_running() && !is_max_time_reached()) {
timer_start();
//Initialize timer for ever
timer_handle = app_timer_send_event(global_ctx, 100, 1);
} else
{
timer_stop();
app_timer_cancel_event(global_ctx, timer_handle);
}
}
void reset_button_handler(ClickRecognizerRef recognizer, Window *window) {
(void)recognizer;
(void)window;
//Cancel timer from firing
if (is_timer_running())
app_timer_cancel_event(global_ctx, timer_handle);
//clear out static variables
reset();
//Reset all text on display
text_layer_set_text(&countLayer, "00:00:00");
text_layer_set_text(&dSecondsLayer, ".0");
text_layer_set_text(&splitLayer, "");
//If reset while running, continute to run
if (is_timer_running()) {
//get_time(&startTime);
timer_handle = app_timer_send_event(global_ctx, 100, 1);
}
}
void split_button_handler(ClickRecognizerRef recognizer, Window *window) {
(void)recognizer;
(void)window;
if (is_timer_running())
{
//Static due to pebble 'set_text'
static char out[] = "Split: 00:00:00.0";
//Used to hold time from Pebble clock
char splitTime[] = "00:00:00";
//*out = 0;
//Build up text, start with 'split'
strcpy(out, "Split: ");
//Add total time
PblTm outTime = get_pebble_time();
string_format_time(splitTime, sizeof(splitTime), "%T", &outTime);
strcat(out, splitTime);
//Add decisecond
strcat(out, ".");
out[16] = (char)dSeconds+48;
//Update display
text_layer_set_text(&splitLayer, out);
}
}
void config_provider(ClickConfig **config, Window *window) {
(void)window;
//Set button handlers
config[BUTTON_ID_SELECT]->click.handler = (ClickHandler) start_button_handler;
config[BUTTON_ID_UP]->click.handler = (ClickHandler) reset_button_handler;
config[BUTTON_ID_DOWN]->click.handler = (ClickHandler) split_button_handler;
}
void handle_init_app(AppContextRef app_ctx) {
(void)app_ctx;
(void)global_ctx;
global_ctx = app_ctx;
resource_init_current_app(&APP_RESOURCES);
window_init(&window, "Stopwatch");
window_stack_push(&window, true /* Animated */);
//Set up the layout of the application
bmp_init_container(RESOURCE_ID_WATCH_BACKGROUND, &backgroundImage);
layer_add_child(&window.layer, &backgroundImage.layer.layer);
text_layer_init(&countLayer, GRect(2, 95, 120, 40));
text_layer_set_text_color(&countLayer, GColorBlack);
text_layer_set_background_color(&countLayer, GColorClear);
text_layer_set_font(&countLayer, fonts_get_system_font(FONT_KEY_DROID_SERIF_28_BOLD));
text_layer_set_text(&countLayer, "00:00:00");
layer_add_child(&window.layer, &countLayer.layer);
text_layer_init(&dSecondsLayer, GRect(115, 95, 28, 40));
dSecondsLayer.text_alignment = GTextAlignmentLeft;
text_layer_set_text_color(&dSecondsLayer, GColorBlack);
text_layer_set_background_color(&dSecondsLayer, GColorClear);
text_layer_set_font(&dSecondsLayer, fonts_get_system_font(FONT_KEY_DROID_SERIF_28_BOLD));
text_layer_set_text(&dSecondsLayer, ".0");
layer_add_child(&window.layer, &dSecondsLayer.layer);
text_layer_init(&splitLayer, GRect(50, 75, 90, 40));
splitLayer.text_alignment = GTextAlignmentLeft;
text_layer_set_text_color(&splitLayer, GColorBlack);
text_layer_set_background_color(&splitLayer, GColorClear);
text_layer_set_font(&splitLayer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD));
layer_add_child(&window.layer, &splitLayer.layer);
// Attach our desired button functionality
window_set_click_config_provider(&window, (ClickConfigProvider) config_provider);
// Initialize timer with AppContextRef, AppTimerHandle, and max seconds
init_timer(app_ctx, timer_handle, 359999);
}
void handle_deinit(AppContextRef ctx) {
(void)ctx;
//Remove bmp
bmp_deinit_container(&backgroundImage);
}
void pbl_main(void *params) {
//Set up handlers
PebbleAppHandlers handlers = {
.init_handler = &handle_init_app,
.deinit_handler = &handle_deinit,
.timer_handler = &handle_timer,
};
app_event_loop(params, &handlers);
}
| 2.09375 | 2 |
2024-11-18T21:08:23.863407+00:00
| 2023-06-08T15:43:05 |
c086ca09d9de7c42107c5ff8206bbc8aff221dc0
|
{
"blob_id": "c086ca09d9de7c42107c5ff8206bbc8aff221dc0",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-08T15:43:05",
"content_id": "57b1ac21e18d16e9e38bb6be53ea22ab5fdf15b7",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "1deb5a41ceff80755587fea8b4eae455dcd54ecd",
"extension": "c",
"filename": "ngx_stream_realip_module.c",
"fork_events_count": 25,
"gha_created_at": "2019-12-20T08:21:50",
"gha_event_created_at": "2020-05-30T18:48:17",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 229221885,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10006,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/stream/ngx_stream_realip_module.c",
"provenance": "stackv2-0069.json.gz:238674",
"repo_name": "jntass/Nginx_Tassl",
"revision_date": "2023-06-08T15:43:05",
"revision_id": "5faec722cc4411ee2a83eec9bb74fa854acf14d1",
"snapshot_id": "46ca8fed80ca8bc469da775f05a4325ff7f5eff0",
"src_encoding": "UTF-8",
"star_events_count": 56,
"url": "https://raw.githubusercontent.com/jntass/Nginx_Tassl/5faec722cc4411ee2a83eec9bb74fa854acf14d1/src/stream/ngx_stream_realip_module.c",
"visit_date": "2023-08-21T19:46:44.602491"
}
|
stackv2
|
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Nginx, Inc.
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_stream.h>
typedef struct {
ngx_array_t *from; /* array of ngx_cidr_t */
} ngx_stream_realip_srv_conf_t;
typedef struct {
struct sockaddr *sockaddr;
socklen_t socklen;
ngx_str_t addr_text;
} ngx_stream_realip_ctx_t;
static ngx_int_t ngx_stream_realip_handler(ngx_stream_session_t *s);
static ngx_int_t ngx_stream_realip_set_addr(ngx_stream_session_t *s,
ngx_addr_t *addr);
static char *ngx_stream_realip_from(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static void *ngx_stream_realip_create_srv_conf(ngx_conf_t *cf);
static char *ngx_stream_realip_merge_srv_conf(ngx_conf_t *cf, void *parent,
void *child);
static ngx_int_t ngx_stream_realip_add_variables(ngx_conf_t *cf);
static ngx_int_t ngx_stream_realip_init(ngx_conf_t *cf);
static ngx_int_t ngx_stream_realip_remote_addr_variable(ngx_stream_session_t *s,
ngx_stream_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_stream_realip_remote_port_variable(ngx_stream_session_t *s,
ngx_stream_variable_value_t *v, uintptr_t data);
static ngx_command_t ngx_stream_realip_commands[] = {
{ ngx_string("set_real_ip_from"),
NGX_STREAM_MAIN_CONF|NGX_STREAM_SRV_CONF|NGX_CONF_TAKE1,
ngx_stream_realip_from,
NGX_STREAM_SRV_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
static ngx_stream_module_t ngx_stream_realip_module_ctx = {
ngx_stream_realip_add_variables, /* preconfiguration */
ngx_stream_realip_init, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
ngx_stream_realip_create_srv_conf, /* create server configuration */
ngx_stream_realip_merge_srv_conf /* merge server configuration */
};
ngx_module_t ngx_stream_realip_module = {
NGX_MODULE_V1,
&ngx_stream_realip_module_ctx, /* module context */
ngx_stream_realip_commands, /* module directives */
NGX_STREAM_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static ngx_stream_variable_t ngx_stream_realip_vars[] = {
{ ngx_string("realip_remote_addr"), NULL,
ngx_stream_realip_remote_addr_variable, 0, 0, 0 },
{ ngx_string("realip_remote_port"), NULL,
ngx_stream_realip_remote_port_variable, 0, 0, 0 },
ngx_stream_null_variable
};
static ngx_int_t
ngx_stream_realip_handler(ngx_stream_session_t *s)
{
ngx_addr_t addr;
ngx_connection_t *c;
ngx_stream_realip_srv_conf_t *rscf;
rscf = ngx_stream_get_module_srv_conf(s, ngx_stream_realip_module);
if (rscf->from == NULL) {
return NGX_DECLINED;
}
c = s->connection;
if (c->proxy_protocol_addr.len == 0) {
return NGX_DECLINED;
}
if (ngx_cidr_match(c->sockaddr, rscf->from) != NGX_OK) {
return NGX_DECLINED;
}
if (ngx_parse_addr(c->pool, &addr, c->proxy_protocol_addr.data,
c->proxy_protocol_addr.len)
!= NGX_OK)
{
return NGX_DECLINED;
}
ngx_inet_set_port(addr.sockaddr, c->proxy_protocol_port);
return ngx_stream_realip_set_addr(s, &addr);
}
static ngx_int_t
ngx_stream_realip_set_addr(ngx_stream_session_t *s, ngx_addr_t *addr)
{
size_t len;
u_char *p;
u_char text[NGX_SOCKADDR_STRLEN];
ngx_connection_t *c;
ngx_stream_realip_ctx_t *ctx;
c = s->connection;
ctx = ngx_palloc(c->pool, sizeof(ngx_stream_realip_ctx_t));
if (ctx == NULL) {
return NGX_ERROR;
}
len = ngx_sock_ntop(addr->sockaddr, addr->socklen, text,
NGX_SOCKADDR_STRLEN, 0);
if (len == 0) {
return NGX_ERROR;
}
p = ngx_pnalloc(c->pool, len);
if (p == NULL) {
return NGX_ERROR;
}
ngx_memcpy(p, text, len);
ngx_stream_set_ctx(s, ctx, ngx_stream_realip_module);
ctx->sockaddr = c->sockaddr;
ctx->socklen = c->socklen;
ctx->addr_text = c->addr_text;
c->sockaddr = addr->sockaddr;
c->socklen = addr->socklen;
c->addr_text.len = len;
c->addr_text.data = p;
return NGX_DECLINED;
}
static char *
ngx_stream_realip_from(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_stream_realip_srv_conf_t *rscf = conf;
ngx_int_t rc;
ngx_str_t *value;
ngx_url_t u;
ngx_cidr_t c, *cidr;
ngx_uint_t i;
struct sockaddr_in *sin;
#if (NGX_HAVE_INET6)
struct sockaddr_in6 *sin6;
#endif
value = cf->args->elts;
if (rscf->from == NULL) {
rscf->from = ngx_array_create(cf->pool, 2,
sizeof(ngx_cidr_t));
if (rscf->from == NULL) {
return NGX_CONF_ERROR;
}
}
#if (NGX_HAVE_UNIX_DOMAIN)
if (ngx_strcmp(value[1].data, "unix:") == 0) {
cidr = ngx_array_push(rscf->from);
if (cidr == NULL) {
return NGX_CONF_ERROR;
}
cidr->family = AF_UNIX;
return NGX_CONF_OK;
}
#endif
rc = ngx_ptocidr(&value[1], &c);
if (rc != NGX_ERROR) {
if (rc == NGX_DONE) {
ngx_conf_log_error(NGX_LOG_WARN, cf, 0,
"low address bits of %V are meaningless",
&value[1]);
}
cidr = ngx_array_push(rscf->from);
if (cidr == NULL) {
return NGX_CONF_ERROR;
}
*cidr = c;
return NGX_CONF_OK;
}
ngx_memzero(&u, sizeof(ngx_url_t));
u.host = value[1];
if (ngx_inet_resolve_host(cf->pool, &u) != NGX_OK) {
if (u.err) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"%s in set_real_ip_from \"%V\"",
u.err, &u.host);
}
return NGX_CONF_ERROR;
}
cidr = ngx_array_push_n(rscf->from, u.naddrs);
if (cidr == NULL) {
return NGX_CONF_ERROR;
}
ngx_memzero(cidr, u.naddrs * sizeof(ngx_cidr_t));
for (i = 0; i < u.naddrs; i++) {
cidr[i].family = u.addrs[i].sockaddr->sa_family;
switch (cidr[i].family) {
#if (NGX_HAVE_INET6)
case AF_INET6:
sin6 = (struct sockaddr_in6 *) u.addrs[i].sockaddr;
cidr[i].u.in6.addr = sin6->sin6_addr;
ngx_memset(cidr[i].u.in6.mask.s6_addr, 0xff, 16);
break;
#endif
default: /* AF_INET */
sin = (struct sockaddr_in *) u.addrs[i].sockaddr;
cidr[i].u.in.addr = sin->sin_addr.s_addr;
cidr[i].u.in.mask = 0xffffffff;
break;
}
}
return NGX_CONF_OK;
}
static void *
ngx_stream_realip_create_srv_conf(ngx_conf_t *cf)
{
ngx_stream_realip_srv_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_stream_realip_srv_conf_t));
if (conf == NULL) {
return NULL;
}
/*
* set by ngx_pcalloc():
*
* conf->from = NULL;
*/
return conf;
}
static char *
ngx_stream_realip_merge_srv_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_stream_realip_srv_conf_t *prev = parent;
ngx_stream_realip_srv_conf_t *conf = child;
if (conf->from == NULL) {
conf->from = prev->from;
}
return NGX_CONF_OK;
}
static ngx_int_t
ngx_stream_realip_add_variables(ngx_conf_t *cf)
{
ngx_stream_variable_t *var, *v;
for (v = ngx_stream_realip_vars; v->name.len; v++) {
var = ngx_stream_add_variable(cf, &v->name, v->flags);
if (var == NULL) {
return NGX_ERROR;
}
var->get_handler = v->get_handler;
var->data = v->data;
}
return NGX_OK;
}
static ngx_int_t
ngx_stream_realip_init(ngx_conf_t *cf)
{
ngx_stream_handler_pt *h;
ngx_stream_core_main_conf_t *cmcf;
cmcf = ngx_stream_conf_get_module_main_conf(cf, ngx_stream_core_module);
h = ngx_array_push(&cmcf->phases[NGX_STREAM_POST_ACCEPT_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
*h = ngx_stream_realip_handler;
return NGX_OK;
}
static ngx_int_t
ngx_stream_realip_remote_addr_variable(ngx_stream_session_t *s,
ngx_stream_variable_value_t *v, uintptr_t data)
{
ngx_str_t *addr_text;
ngx_stream_realip_ctx_t *ctx;
ctx = ngx_stream_get_module_ctx(s, ngx_stream_realip_module);
addr_text = ctx ? &ctx->addr_text : &s->connection->addr_text;
v->len = addr_text->len;
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
v->data = addr_text->data;
return NGX_OK;
}
static ngx_int_t
ngx_stream_realip_remote_port_variable(ngx_stream_session_t *s,
ngx_stream_variable_value_t *v, uintptr_t data)
{
ngx_uint_t port;
struct sockaddr *sa;
ngx_stream_realip_ctx_t *ctx;
ctx = ngx_stream_get_module_ctx(s, ngx_stream_realip_module);
sa = ctx ? ctx->sockaddr : s->connection->sockaddr;
v->len = 0;
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
v->data = ngx_pnalloc(s->connection->pool, sizeof("65535") - 1);
if (v->data == NULL) {
return NGX_ERROR;
}
port = ngx_inet_get_port(sa);
if (port > 0 && port < 65536) {
v->len = ngx_sprintf(v->data, "%ui", port) - v->data;
}
return NGX_OK;
}
| 2.03125 | 2 |
2024-11-18T21:08:24.073837+00:00
| 2020-10-07T05:34:30 |
c789ed9d9a7e4a6041cf989e17e61e8ecbe9408d
|
{
"blob_id": "c789ed9d9a7e4a6041cf989e17e61e8ecbe9408d",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-07T05:34:30",
"content_id": "d7dee45b3c796d0760502d7a8a24092959bb8c82",
"detected_licenses": [
"MIT"
],
"directory_id": "de85651c7ceff58fbfefa9392eaa8957d6b45387",
"extension": "c",
"filename": "CircularLL.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 295931787,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3311,
"license": "MIT",
"license_type": "permissive",
"path": "/Linked Lists/CircularLL.c",
"provenance": "stackv2-0069.json.gz:238802",
"repo_name": "Sant268/Data-Structures-in-C",
"revision_date": "2020-10-07T05:34:30",
"revision_id": "ab552eeefe3b0b6c58a7a734ea04f52772c89df0",
"snapshot_id": "4966b1cbe89e7a7b88ea23bbcfd6be6567fb37a5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Sant268/Data-Structures-in-C/ab552eeefe3b0b6c58a7a734ea04f52772c89df0/Linked Lists/CircularLL.c",
"visit_date": "2022-12-23T17:07:13.017405"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
} *head = NULL;
void printLL()
{
printf("\n The Linked List currently is:");
struct Node *temp = head;
if (head != NULL)
{
do
{
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
}
}
void insertEnd(int value)
{
struct Node *newNode;
newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = value;
if (head == NULL)
{
head = newNode;
newNode->next = head;
}
else
{
struct Node *temp = head;
while (temp->next != head)
temp = temp->next;
temp->next = newNode;
newNode->next = head;
}
printf("\nInsertion successful \n");
}
void insertBegin(int value)
{
struct Node *newNode;
newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = value;
if (head == NULL)
{
head = newNode;
newNode->next = head;
}
else
{
struct Node *temp = head;
while (temp->next != head)
temp = temp->next;
newNode->next = head;
head = newNode;
temp->next = head;
}
printf("\nInsertion successful \n");
}
void delEnd()
{
if (head == NULL)
printf("List is Empty");
else
{
struct Node *temp1 = head, *temp2;
if (temp1->next == head)
{
head = NULL;
free(temp1);
}
else
{
while (temp1->next != head)
{
temp2 = temp1;
temp1 = temp1->next;
}
temp2->next = head;
free(temp1);
}
printf("\nDeletion successful \n");
}
}
void delBegin()
{
if (head == NULL)
printf("List is Empty");
else
{
struct Node *temp = head, *last = NULL;
if (temp->next == head)
{
head = NULL;
free(temp);
}
else
{
while (temp->next != head)
temp = temp->next;
last = temp;
temp = head;
head = head->next;
free(temp);
last->next = head;
}
printf("\nDeletion successful \n");
}
}
void main()
{
int ch = -1, x = 0;
while (ch != 99)
{
printf("\n 1. Insert at Beginning of CLL");
printf("\n 2. Insert at End of CLL");
printf("\n 3. Delete Beginning Node");
printf("\n 4. Delete End Node");
printf("\n 99. Exit the Program");
printf("\n Enter your choice:");
scanf("%d", &ch);
if (ch == 1 || ch == 2)
{
printf("\n Enter Value to Insert:");
scanf("%d", &x);
}
switch (ch)
{
case 1:
insertBegin(x);
printLL();
break;
case 2:
insertEnd(x);
printLL();
break;
case 3:
delBegin();
printLL();
break;
case 4:
delEnd();
printLL();
break;
case 99:
printf("\n Thank You");
break;
default:
break;
}
}
}
| 3.9375 | 4 |
2024-11-18T21:08:24.141992+00:00
| 2019-06-12T00:48:01 |
7cec66c197893b607c588ab902b8edee0f5bdfa6
|
{
"blob_id": "7cec66c197893b607c588ab902b8edee0f5bdfa6",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-12T00:48:01",
"content_id": "75764cb2e4a62ed6de0eb2ed6116f4791084ca96",
"detected_licenses": [
"MIT"
],
"directory_id": "213d09d18010b001c57177928799a29eaec4d22f",
"extension": "h",
"filename": "conversions.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 57934621,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1412,
"license": "MIT",
"license_type": "permissive",
"path": "/src/conversions.h",
"provenance": "stackv2-0069.json.gz:238931",
"repo_name": "prostory/mruby-fiddle",
"revision_date": "2019-06-12T00:48:01",
"revision_id": "b20e751d9c96f23b00aa12d4c12a355fff7c5cd1",
"snapshot_id": "fe7e5c322cce47d457bc725238b94b85789a10ce",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/prostory/mruby-fiddle/b20e751d9c96f23b00aa12d4c12a355fff7c5cd1/src/conversions.h",
"visit_date": "2021-06-06T03:17:57.257081"
}
|
stackv2
|
#ifndef FIDDLE_CONVERSIONS_H
#define FIDDLE_CONVERSIONS_H
#include "fiddle.h"
typedef union
{
ffi_arg fffi_arg; /* rvalue smaller than unsigned long */
ffi_sarg fffi_sarg; /* rvalue smaller than signed long */
unsigned char uchar; /* ffi_type_uchar */
signed char schar; /* ffi_type_schar */
unsigned short ushort; /* ffi_type_sshort */
signed short sshort; /* ffi_type_ushort */
unsigned int uint; /* ffi_type_uint */
signed int sint; /* ffi_type_sint */
unsigned long ulong; /* ffi_type_ulong */
signed long slong; /* ffi_type_slong */
float ffloat; /* ffi_type_float */
double ddouble; /* ffi_type_double */
#if HAVE_LONG_LONG
unsigned LONG_LONG ulong_long; /* ffi_type_ulong_long */
signed LONG_LONG slong_long; /* ffi_type_ulong_long */
#endif
void * pointer; /* ffi_type_pointer */
} fiddle_generic;
ffi_type * int_to_ffi_type(mrb_state *mrb, int type);
void value_to_generic(mrb_state *mrb, int type, mrb_value src, fiddle_generic * dst);
mrb_value generic_to_value(mrb_state *mrb, mrb_value rettype, fiddle_generic retval);
#define VALUE2GENERIC(_mrb, _type, _src, _dst) value_to_generic((_mrb), (_type), (_src), (_dst))
#define INT2FFI_TYPE(_mrb, _type) int_to_ffi_type((_mrb), (_type))
#define GENERIC2VALUE(_mrb, _type, _retval) generic_to_value((_mrb), (_type), (_retval))
#endif
| 2.21875 | 2 |
2024-11-18T21:08:24.862005+00:00
| 2019-10-26T09:04:36 |
c89ced5f0d0c26834d2b5d13654dbac538abbd2f
|
{
"blob_id": "c89ced5f0d0c26834d2b5d13654dbac538abbd2f",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-26T09:04:36",
"content_id": "6c609c91d8f3989dcf065c3180bf6c5a1176f47d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cad4703a2213ca90612f473e59968bc0634eaeef",
"extension": "c",
"filename": "Error.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 76883232,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1073,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Error.c",
"provenance": "stackv2-0069.json.gz:239187",
"repo_name": "AbyxBelgium/Huffman",
"revision_date": "2019-10-26T09:04:36",
"revision_id": "471ef2d93dba98d81d1bffed60e1f521049c9a41",
"snapshot_id": "7e629f281b6d75138ea8741e40d7f2aa2bd50097",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AbyxBelgium/Huffman/471ef2d93dba98d81d1bffed60e1f521049c9a41/Error.c",
"visit_date": "2021-01-11T11:37:45.784545"
}
|
stackv2
|
#include "Error.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
Error* error_init(char* message, int errorCode) {
Error* error = (Error*) mem_alloc(sizeof(Error));
error->message = message;
error->errorCode = errorCode;
return error;
}
void error_free(Error* error) {
free(error);
}
void handle_error(Error* error) {
int code = error->errorCode;
if (code == OUT_OF_MEMORY_ERROR) {
fprintf(stderr, "Out of memory!\n");
} else if (code == OUT_OF_BOUNDS_ERROR) {
fprintf(stderr, "Out of bounds! You tried to access a list's element that does not exist!\n");
} else if (code == FILE_NOT_FOUND_ERROR) {
fprintf(stderr, "The requested file could not be found...\n");
} else if (code == FILE_NOT_CREATED_ERROR) {
fprintf(stderr, "The requested file could not be created...\n");
} else {
fprintf(stderr, "An unknown error occurred!\n");
}
fprintf(stderr, "%s", error->message);
fprintf(stderr, "\n");
printf("Press any key to continue...\n");
getchar();
// Clean up memory used by error...
error_free(error);
exit(error->errorCode);
}
| 3.015625 | 3 |
2024-11-18T21:08:26.126030+00:00
| 2016-06-02T23:25:36 |
a01f7b309c2d4260671b43387d679245b9dc520c
|
{
"blob_id": "a01f7b309c2d4260671b43387d679245b9dc520c",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-02T23:25:36",
"content_id": "25957e9accc3b5022d42215b51f7043a0410b926",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "962daae186afad97e1f848f3306f8393ecbd905a",
"extension": "c",
"filename": "ListaCompacta.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 14175397,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2980,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ListaCompacta.c",
"provenance": "stackv2-0069.json.gz:239444",
"repo_name": "fiuba-7541/elemental",
"revision_date": "2016-06-02T23:25:36",
"revision_id": "e435f979414f875ce462452ac546855388331f2a",
"snapshot_id": "ff088cd2fa8a34543b3aae4c119bc5e3cad567a0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fiuba-7541/elemental/e435f979414f875ce462452ac546855388331f2a/ListaCompacta.c",
"visit_date": "2021-01-17T09:10:36.636487"
}
|
stackv2
|
/*
* ListaCompacta.c
*
* Created on: 25/04/2011
* Author: anibal
*/
#include "ListaCompacta.h"
void LC_Crear(TListaCompacta *pLs, int TamanioDato)
{
pLs->corriente = NULL;
pLs->primero = NULL;
pLs->tamanioDato = TamanioDato;
}
void LC_Vaciar(TListaCompacta *pLs)
{
TNodoListaCompacta *pNodo, *siguiente;
for(pNodo = pLs->primero;(pNodo);pNodo=siguiente)
{
siguiente = pNodo->siguiente;
free(pNodo);
}
pLs->primero=pLs->corriente=NULL;
}
int LC_Vacia(TListaCompacta Ls)
{
return (Ls.primero == NULL);
}
void LC_Elem_Cte(TListaCompacta Ls, void *pE)
{
memcpy(pE, (Ls.corriente)+1, Ls.tamanioDato);
}
int LC_Mover_Cte(TListaCompacta *pLs, TMovimiento_Lc M)
{
switch (M)
{
case L_Primero:
pLs->corriente=pLs->primero;
break;
case L_Siguiente:
if (pLs->corriente->siguiente==NULL)
return FALSE;
else
pLs->corriente=pLs->corriente->siguiente;
break;
case L_Anterior:return FALSE;
}
return TRUE;
}
void LC_Borrar_Cte(TListaCompacta *pLs)
{
TNodoListaCompacta *pNodo=pLs->corriente;
if (pLs->corriente==pLs->primero)
{
pLs->primero = pLs->corriente->siguiente;
pLs->corriente = pLs->primero;
}
else
{
if(pLs->corriente->siguiente){
/* En este caso en que el corriente no es el ultimo, puedo evitarme
* recorrer toda la lista buscando el anterior */
pNodo=pLs->corriente->siguiente;
memcpy((pLs->corriente)+1, (pNodo)+1, pLs->tamanioDato);
pLs->corriente->siguiente = pNodo->siguiente;
}else {
TNodoListaCompacta *pAux=pLs->primero;
while (pAux->siguiente!=pLs->corriente)
pAux = pAux->siguiente;
pAux->siguiente=pLs->corriente->siguiente;
pLs->corriente = pAux; /*Si es el �ltimo queda en el Anterior al borrado */
}
}
free(pNodo);
}
int LC_Insertar_Cte(TListaCompacta *pLs, TMovimiento_Lc M, void* pE)
{
TNodoListaCompacta *pNodo = (TNodoListaCompacta*) malloc(sizeof(TNodoListaCompacta) + pLs->tamanioDato);
if (!pNodo)
return FALSE; /* No hay memoria disponible */
memcpy(pNodo+1, pE, pLs->tamanioDato);
if ((pLs->primero == NULL) || (M==L_Primero) || ((M==L_Anterior) && (pLs->primero==pLs->corriente)))
{
/*Si est� vac�a o hay que insertar en el Primero o
hay que insertar en el Anterior y el actual es el Primero */
pNodo->siguiente = pLs->primero;
pLs->primero = pLs->corriente = pNodo;
}
else
{
/* Siempre inserto como siguiente, el nodo nuevo, porque es más fácil */
pNodo->siguiente = pLs->corriente->siguiente;
pLs->corriente->siguiente = pNodo;
if (M == L_Anterior)
{
/* Pero cuando el movimiento es Anterior, entonces swapeo los
* elementos */
void* tmp = malloc(pLs->tamanioDato);
memcpy(tmp, pNodo+1, pLs->tamanioDato);
memcpy(pNodo+1, (pLs->corriente)+1, pLs->tamanioDato);
memcpy((pLs->corriente)+1, tmp, pLs->tamanioDato);
free(tmp);
}
}
pLs->corriente=pNodo;
return TRUE;
}
| 3.015625 | 3 |
2024-11-18T21:08:26.222664+00:00
| 2020-03-28T21:23:34 |
b8d569456968e0ed9852a448cbf18ec6eab9a038
|
{
"blob_id": "b8d569456968e0ed9852a448cbf18ec6eab9a038",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-28T21:23:34",
"content_id": "3156380034eb552b8c88aec7554f89ad80813810",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "ac4df5b052508689cc6ca52e0c2330893f08c63e",
"extension": "c",
"filename": "reppanel_machine.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": 3227,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/main/reppanel_machine.c",
"provenance": "stackv2-0069.json.gz:239573",
"repo_name": "MooreY/RepPanel_ESP32",
"revision_date": "2020-03-28T21:23:34",
"revision_id": "49a5341ad2473f10969ef3153bcbc748a6e622d9",
"snapshot_id": "d31be231b0a691281d7e8c3e63352a28b31b730a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MooreY/RepPanel_ESP32/49a5341ad2473f10969ef3153bcbc748a6e622d9/main/reppanel_machine.c",
"visit_date": "2021-05-19T19:34:46.762630"
}
|
stackv2
|
//
// Copyright (c) 2020 Wolfgang Christl
// Licensed under Apache License, Version 2.0 - https://opensource.org/licenses/Apache-2.0
#include <lvgl/src/lv_objx/lv_page.h>
#include <lvgl/src/lv_objx/lv_ddlist.h>
#include <esp_log.h>
#include "reppanel_machine.h"
#include "reppanel_helper.h"
#include "reppanel_request.h"
#include "reppanel.h"
#define TAG "Machine"
static char *cali_opt_map[] = {"True Bed Leveling", "Mesh Bed Leveling"};
static char *cali_opt_list = {"True Bed Leveling\nMesh Bed Leveling"};
lv_obj_t *machine_page;
lv_obj_t *ddlist_cali_options;
static void _home_all_event(lv_obj_t *obj, lv_event_t event) {
if (event == LV_EVENT_RELEASED) {
reprap_send_gcode("G28");
}
}
static void _home_x_event(lv_obj_t *obj, lv_event_t event) {
if (event == LV_EVENT_RELEASED) {
reprap_send_gcode("G28 X");
}
}
static void _home_y_event(lv_obj_t *obj, lv_event_t event) {
if (event == LV_EVENT_RELEASED) {
reprap_send_gcode("G28 Y");
}
}
static void _home_z_event(lv_obj_t *obj, lv_event_t event) {
if (event == LV_EVENT_RELEASED) {
reprap_send_gcode("G28 Z");
}
}
static void _start_cali_event(lv_obj_t *obj, lv_event_t event) {
if (event == LV_EVENT_RELEASED) {
char val_txt_buff[50];
lv_ddlist_get_selected_str(obj, val_txt_buff, 50);
if (strcmp(val_txt_buff, cali_opt_map[0]) == 0) {
ESP_LOGI(TAG, "true bed leveling");
// TODO: Implement true bed leveling call
} else if (strcmp(val_txt_buff, cali_opt_map[1]) == 0) {
// TODO: Implement mesh bed leveling call
ESP_LOGI(TAG, "mesh bed leveling");
}
}
}
void draw_machine(lv_obj_t *parent_screen) {
machine_page = lv_page_create(parent_screen, NULL);
lv_obj_set_size(machine_page, lv_disp_get_hor_res(NULL), lv_disp_get_ver_res(NULL) - (lv_obj_get_height(cont_header) + 5));
lv_page_set_scrl_fit2(machine_page, LV_FIT_FILL, LV_FIT_FILL);
lv_page_set_scrl_layout(machine_page, LV_LAYOUT_COL_M);
lv_obj_t *cont_cali = lv_cont_create(machine_page, NULL);
lv_cont_set_fit(cont_cali, LV_FIT_TIGHT);
lv_cont_set_layout(cont_cali, LV_LAYOUT_ROW_M);
ddlist_cali_options = lv_ddlist_create(cont_cali, NULL);
lv_ddlist_set_options(ddlist_cali_options, cali_opt_list);
lv_ddlist_set_draw_arrow(ddlist_cali_options, true);
lv_ddlist_set_fix_height(ddlist_cali_options, 110);
lv_ddlist_set_sb_mode(ddlist_cali_options, LV_SB_MODE_AUTO);
static lv_obj_t *do_cali_butn;
create_button(cont_cali, do_cali_butn, "Start", _start_cali_event);
lv_obj_t *home_cont = lv_cont_create(machine_page, NULL);
lv_cont_set_layout(home_cont, LV_LAYOUT_ROW_M);
lv_cont_set_fit(home_cont, LV_FIT_TIGHT);
lv_obj_t *label_home = lv_label_create(home_cont, NULL);
lv_label_set_text(label_home, "Home:");
static lv_obj_t *btn_home_all, *btn_home_y, *btn_home_x, *btn_home_z;
create_button(home_cont, btn_home_all, " All Axis ", _home_all_event);
create_button(home_cont, btn_home_x, " X ", _home_x_event);
create_button(home_cont, btn_home_y, " Y ", _home_y_event);
create_button(home_cont, btn_home_z, " Z ", _home_z_event);
}
| 2.234375 | 2 |
2024-11-18T21:08:26.340380+00:00
| 2017-01-05T09:46:29 |
31be65fc67b2cb444af46eb3c8ac68e067fdc8b8
|
{
"blob_id": "31be65fc67b2cb444af46eb3c8ac68e067fdc8b8",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-05T09:46:29",
"content_id": "a42afd067df1a55db9daeb16ecbdaae2276c61b7",
"detected_licenses": [
"MIT"
],
"directory_id": "cebe919c145a6d5adc22d0fcbfc6c55e3ddc19e6",
"extension": "h",
"filename": "graphic.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 76646324,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2831,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/graphic.h",
"provenance": "stackv2-0069.json.gz:239701",
"repo_name": "paullaffitte/wolf3d_autograder",
"revision_date": "2017-01-05T09:46:29",
"revision_id": "7c23c42c66fda3900445e27db2d99ff2803cb9a8",
"snapshot_id": "858e6ddb3d902343b52229ce43fe0936b26d6d2d",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/paullaffitte/wolf3d_autograder/7c23c42c66fda3900445e27db2d99ff2803cb9a8/tests/graphic.h",
"visit_date": "2021-01-12T08:39:45.006718"
}
|
stackv2
|
/*
** MIT License
**
** Copyright (c) 2016 Paul Laffitte
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
*/
#ifndef MY_LIB_GRAPH_H_
# define MY_LIB_GRAPH_H_
# include <SFML/Graphics.h>
typedef struct s_my_framebuffer
{
sfUint8* pixels;
int width;
int height;
} t_my_framebuffer;
t_my_framebuffer* _my_framebuffer_create(int width, int height);
int _my_framebuffer_fill(t_my_framebuffer *framebuffer,
sfColor color);
int _my_framebuffer_cmp(t_my_framebuffer *fb1,
t_my_framebuffer *fb2);
int _my_framebuffer_destroy(t_my_framebuffer
*framebuffer);
int _calc_id_max(t_my_framebuffer *framebuffer);
int _calc_id_pixel(t_my_framebuffer *framebuffer,
int x, int y);
int _cmp_pixel(sfUint8 *p1, sfUint8 *p2);
void _my_put_pixel(t_my_framebuffer *framebuffer,
int x, int y, sfColor color);
void _my_draw_line(t_my_framebuffer *framebuffer,
sfVector2i from, sfVector2i to,
sfColor color);
void _my_draw_line2(t_my_framebuffer *framebuffer,
sfVector2i from, sfVector2i to,
sfColor color);
sfVector2i _my_parallel_projection(sfVector3f pos3d,
float angle);
sfVector2i _my_isometric_projection(sfVector3f pos3d);
sfColor _my_color_create(int r, int g, int b, int a);
sfVector3f *_init_vector3f(sfVector3f *vector, float x,
float y, float z);
sfVector2f *_init_vector2f(sfVector2f *vector, float x, float y);
sfVector2i *_init_vector2i(sfVector2i *vector, int x, int y);
sfVector3f *_cpy_vector3f(sfVector3f *dest, sfVector3f *src);
sfVector2f *_cpy_vector2f(sfVector2f *dest, sfVector2f *src);
sfVector2i *_cpy_vector2i(sfVector2i *dest, sfVector2i *src);
sfVector2f _move_forward(sfVector2f pos,
float direction, float distance);
#endif /* !MY_LIB_GRAPH_H_ */
| 2.140625 | 2 |
2024-11-18T21:08:26.830957+00:00
| 2020-07-30T00:43:36 |
d5d9c567ce315b4ae0009984d7ba1df07cc80224
|
{
"blob_id": "d5d9c567ce315b4ae0009984d7ba1df07cc80224",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-30T00:43:36",
"content_id": "f2974e8c80b890a66fe73d916a1d12eb0a2f5a88",
"detected_licenses": [
"MIT"
],
"directory_id": "c867eb0378c8f1983c36f4dbd4f1251ffc6907b9",
"extension": "h",
"filename": "defs.h",
"fork_events_count": 0,
"gha_created_at": "2020-07-29T05:03:06",
"gha_event_created_at": "2020-07-29T05:03:07",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 283403107,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1993,
"license": "MIT",
"license_type": "permissive",
"path": "/firmware/apollo_fw/defs.h",
"provenance": "stackv2-0069.json.gz:240088",
"repo_name": "ShawK91/ProjectApollo",
"revision_date": "2020-07-30T00:43:36",
"revision_id": "9b37b40f4a5959c3c732d93d093b9584f2ac338d",
"snapshot_id": "c5d0fc93f335c8d20d21986b6e987df6ff7f68ff",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ShawK91/ProjectApollo/9b37b40f4a5959c3c732d93d093b9584f2ac338d/firmware/apollo_fw/defs.h",
"visit_date": "2022-11-25T14:28:15.019223"
}
|
stackv2
|
#ifndef _DEFS_H_
#define _DEFS_H_
#include <stdint.h>
typedef struct
{
uint8_t magic;
uint16_t time_stage_5way;
uint16_t time_stage_2way;
uint16_t time_stage_pause;
uint32_t odometer_hours;
uint8_t debug_mode;
uint16_t checksum;
}
nvm_t;
#define NVM_MAGIC 0xA5
typedef struct
{
uint8_t seq;
uint32_t odometer_hours;
uint32_t millis;
uint32_t fault_code;
}
fault_t;
enum
{
FAULTCODE_NONE = 0x00,
FAULTCODE_START_PLACEHOLDER = 0x01 << 0, // this isn't actually a fault, it's used to pad the LED blinking
FAULTCODE_UNDERVOLTAGE = 0x01 << 1,
FAULTCODE_OVERVOLTAGE = 0x01 << 2,
FAULTCODE_COIL_5WAY_SHORT = 0x01 << 3,
FAULTCODE_COIL_5WAY_OPEN = 0x01 << 4,
FAULTCODE_COIL_2WAY_SHORT = 0x01 << 5,
FAULTCODE_COIL_2WAY_OPEN = 0x01 << 6,
FAULTCODE_OXY_HW_FAIL = 0x01 << 7, // oxygen sensor failed to respond
FAULTCODE_OXY_LOW = 0x01 << 8,
FAULTCODE_FLOW_LOW = 0x01 << 9,
FAULTCODE_PRESSURE_HW_FAIL = 0x01 << 10,
FAULTCODE_PRESSURE_LOW = 0x01 << 11,
FAULTCODE_PRESSURE_HIGH = 0x01 << 12,
FAULTCODE_END = 0x01 << 13,
};
// valve phases, defined in order because the state-machine uses addition to goto next state
enum
{
PHASE_IDLE,
PHASE_5WAY_OFF_2WAY_OFF,
PHASE_5WAY_OFF_2WAY_ON,
PHASE_5WAY_OFF_2WAY_PAUSE, // optional, may be skipped
PHASE_5WAY_ON_2WAY_OFF,
PHASE_5WAY_ON_2WAY_ON,
PHASE_5WAY_ON_2WAY_PAUSE, // optional, may be skipped
PHASE_WRAP, // when this is reached, the state-machine wraps back to the top
PHASE_FAULT,
};
#define TIME_HAS_ELAPSED(now_, stamp_, period_) ((now_) - (stamp_) >= (period_)) // this will account for overflow
// MPR sensor state machine phases
enum
{
MPRPHASE_START,
MPRPHASE_WAIT,
MPRPHASE_READ,
};
enum
{
MPR_MODE_NONE,
MPR_MODE_I2C,
MPR_MODE_SPI,
MPR_MODE_OTHER,
};
#define MPR_STATUS_MASK 0xF7
#define MPR_STATUS_POWERED 0x40
#define MPR_STATUS_ERROR 0x04
#endif
| 2.140625 | 2 |
2024-11-18T21:08:27.077471+00:00
| 2015-04-24T14:37:44 |
b6fca7a8c08aa16ccf6c610403b157833f0c4f70
|
{
"blob_id": "b6fca7a8c08aa16ccf6c610403b157833f0c4f70",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-24T14:37:44",
"content_id": "aaa33fbdd6878c36c1bcffbebc1fa81c9ef888bc",
"detected_licenses": [
"MIT"
],
"directory_id": "1cb49ad8374679d66347f86db21ee85dd4a03cb1",
"extension": "c",
"filename": "higher.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 29701316,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3532,
"license": "MIT",
"license_type": "permissive",
"path": "/chordProgression/higher.c",
"provenance": "stackv2-0069.json.gz:240347",
"repo_name": "lusth-music/jbwolfe",
"revision_date": "2015-04-24T14:37:44",
"revision_id": "4e2567a42d454ef5aba7e724b3b6690bdc5312b5",
"snapshot_id": "6305440e9b2238fe0b89029fa14fba79d7ba7738",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/lusth-music/jbwolfe/4e2567a42d454ef5aba7e724b3b6690bdc5312b5/chordProgression/higher.c",
"visit_date": "2016-09-10T16:56:52.262340"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "/usr/local/include/songlib/util.h"
#include "/usr/local/include/songlib/songlib.h"
#define dir "/usr/local/share/samples/cello/"
#define base "pluck_"
//
//#define dir "/usr/local/share/samples/guitar-electric/"
//#define base "SGM-dis_"
//#define base "lp_"
//#define base "fluid-harm_"
//
//#define dir "/usr/local/share/samples/piano/"
//#define base "bright_"
//
/* change PROGRAM_NAME and PROGRAM_VERSION appropriately */
char *PROGRAM_NAME = "higher";
char *PROGRAM_VERSION = "0.01";
int
main()
{
int instrument;
int octave = 4;
songInit();
instrument = readScale(dir,base);
setTempo(200);
setTime(4,4);
setStride(0.05);
setSustain(0.99995);
setAmplitude(0.4);
openOutput("higher.rra",0,0);
setKey(C);
setMode(IONIAN);
goto here;
/* A 50's Progression */
c(1,H,instrument,octave);
c(6,H,instrument,octave-1);
c(4,H,instrument,octave-1);
c(5,H,instrument,octave-1);
/* Let's end it with a POWER CHORD! */
cpower(1, H, instrument, octave);
cpower2(1, H, instrument, octave);
here:;
int i;
for(i=0;i<2;++i){
//b(1, Q, instrument, octave, "xxx", SX);
cpower2(1, Q, instrument, octave);
b(1, I, instrument, octave, "x--", SX);
b(1, I, instrument, octave, "-x-", SX);
b(1, Q, instrument, octave, "--x", SX);
//b(6, Q, instrument, octave-1, "xxx", SX);
cpower2(6, Q, instrument, octave-1);
b(6, I, instrument, octave-1, "x--", SX);
b(6, I, instrument, octave-1, "-x-", SX);
b(6, Q, instrument, octave-1, "--x", SX);
//b(4, Q, instrument, octave-1, "xxx", SX);
cpower2(4, Q, instrument, octave-1);
b(4, I, instrument, octave-1, "x--", SX);
b(4, I, instrument, octave-1, "-x-", SX);
b(4, Q, instrument, octave-1, "--x", SX);
//b(5, Q, instrument, octave-1, "xxx", SX);
cpower2(5, Q, instrument, octave-1);
b(5, I, instrument, octave-1, "x--", SX);
b(5, I, instrument, octave-1, "-x-", SX);
b(5, Q, instrument, octave-1, "--x", SX);
}
cchord(4, Q, instrument, octave-1, "xxx");
cchord(4, I, instrument, octave-1, "x--");
cchord(4, I, instrument, octave-1, "-x-");
cchord(4, Q, instrument, octave-1, "--x");
cchord(5, Q, instrument, octave-1, "xxx");
cchord(5, I, instrument, octave-1, "x--");
cchord(5, I, instrument, octave-1, "-x-");
cchord(5, Q, instrument, octave-1, "--x");
cchord(6, Q, instrument, octave-1, "xxx");
cchord(6, I, instrument, octave-1, "x--");
cchord(6, I, instrument, octave-1, "-x-");
cchord(6, Q, instrument, octave-1, "--x");
cchord(1, Q, instrument, octave, "xxx");
cchord(1, I, instrument, octave, "x--");
cchord(1, I, instrument, octave, "-x-");
cchord(1, Q, instrument, octave, "--x");
cchord(6, Q, instrument, octave-1, "xxx");
cchord(6, I, instrument, octave-1, "--x");
cchord(6, I, instrument, octave-1, "-x-");
cchord(6, Q, instrument, octave-1, "x--");
cchord(5, Q, instrument, octave-1, "xxx");
cchord(5, I, instrument, octave-1, "--x");
cchord(5, I, instrument, octave-1, "-x-");
cchord(5, Q, instrument, octave-1, "x--");
cchord(4, Q, instrument, octave-1, "xxx");
cchord(4, I, instrument, octave-1, "--x");
cchord(4, I, instrument, octave-1, "-x-");
cchord(4, Q, instrument, octave-1, "x--");
cpower(1, W, instrument, octave);
closeOutput();
return 0;
}
| 2.015625 | 2 |
2024-11-18T22:10:58.306664+00:00
| 2018-07-29T10:53:38 |
a8b289f2b8fca16237223ac8af72516213291259
|
{
"blob_id": "a8b289f2b8fca16237223ac8af72516213291259",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-29T10:53:38",
"content_id": "123f6e910ab63210bfd0b301e82314823e00b277",
"detected_licenses": [
"MIT"
],
"directory_id": "15312b1c83f0a1873f20d8b472edb53e733bf341",
"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": 30434370,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1166,
"license": "MIT",
"license_type": "permissive",
"path": "/src/m25p16_write_test/main.c",
"provenance": "stackv2-0072.json.gz:36241",
"repo_name": "gheja/avr",
"revision_date": "2018-07-29T10:53:38",
"revision_id": "2b0fe031c65915e2b60ca233667cbf80fc290a99",
"snapshot_id": "36779dba1a3647fa19bb87906dc33baaa54c3785",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/gheja/avr/2b0fe031c65915e2b60ca233667cbf80fc290a99/src/m25p16_write_test/main.c",
"visit_date": "2021-01-21T12:46:19.087122"
}
|
stackv2
|
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/eeprom.h>
#include <util/delay.h>
#include "../lib/spi.h"
#include "../lib/m25p16.h"
#define BIT_SET(x,y) x |= _BV(y)
#define BIT_CLEAR(x,y) x &= ~(_BV(y))
#define BIT_TOGGLE(x,y) x ^= _BV(y)
#define BIT_WAVE(x,y) BIT_SET(x,y); _delay_ms(150); BIT_CLEAR(x,y); _delay_ms(150);
#define LED_PORT PORTB
#define LED_DDR DDRB
#define LED_PIN PB0
void static inline led_init()
{
LED_DDR |= (1 << LED_PIN);
}
void static inline led_on()
{
BIT_SET(LED_PORT, LED_PIN);
}
void static inline led_off()
{
BIT_CLEAR(LED_PORT, LED_PIN);
}
void main(void)
{
uint8_t a, i;
led_init();
led_on();
m25p16_init();
m25p16_write_enable();
m25p16_sector_erase(0x00, 0x02, 0x00);
m25p16_wait_for_operation();
m25p16_write_enable();
m25p16_write_begin(0x00, 0x02, 0x00);
m25p16_write_byte(0x01);
m25p16_write_byte(0x55);
m25p16_write_byte(0xaa);
m25p16_write_byte(0x42);
m25p16_write_end();
m25p16_wait_for_operation();
m25p16_read_begin(0x00, 0x02, 0x00);
m25p16_read_byte();
m25p16_read_byte();
m25p16_read_byte();
m25p16_read_byte();
m25p16_read_end();
led_off();
while (1)
{
}
}
| 2.46875 | 2 |
2024-11-18T22:10:58.538564+00:00
| 2017-10-26T21:06:34 |
56988f093ab698125e5cbb3ce54ba237e2c0f2ce
|
{
"blob_id": "56988f093ab698125e5cbb3ce54ba237e2c0f2ce",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-26T21:06:34",
"content_id": "ee4ddafdf9935076d31a93b9d6c804914217c1af",
"detected_licenses": [
"MIT"
],
"directory_id": "c92de3e54ea958f43eeb6f9d28471e9d2c1a7af4",
"extension": "c",
"filename": "net_mon.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 85514254,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2733,
"license": "MIT",
"license_type": "permissive",
"path": "/src/net_mon.c",
"provenance": "stackv2-0072.json.gz:36629",
"repo_name": "ritlew/net_mon",
"revision_date": "2017-10-26T21:06:34",
"revision_id": "ebaa75b117e24728f217cbfca52f375d025744e8",
"snapshot_id": "5d8d82c8f2f2726e99a7b8b4e47835cf7f2c4843",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ritlew/net_mon/ebaa75b117e24728f217cbfca52f375d025744e8/src/net_mon.c",
"visit_date": "2021-01-22T22:12:24.030181"
}
|
stackv2
|
#include <stdlib.h>
#include "ledutil.h"
#include "netutil.h"
// main program
int main(int argc, char * argv[]){
// initalize the monitor
mon_init();
// initalize the display
led_init();
// counter
int i;
// variables to keep track of data
int kbps = 0;
// history of speeds
// range for download speeds
int kbps_range_d[32] = {0};
// range for upload speeds
int kbps_range_u[32] = {0};
// pointer to current time
int kbps_p = 0;
// highest seen download in range
int highest_d = 1;
// highest seen upload in range
int highest_u = 1;
// timer variable
// this will count up to time_before_refresh
// and then loop back to 0
int timer = 0;
// contant for timer to count up to
int time_before_refresh = 7;
// variables for current download, and upload
int d, u;
while (1){
// get new info if timer is at 0
if (timer == 0){
// get current speeds
current_KBps(&d, &u);
// put them in the range
kbps_range_d[kbps_p] = d;
kbps_range_u[kbps_p] = u;
// update pointer
kbps_p = (kbps_p + 1) % 32;
// get new top speeds
highest_d = 1;
highest_u = 1;
// linear find max
for (i = 0; i < 32; i++){
if (highest_d < kbps_range_d[i]){
highest_d = kbps_range_d[i];
}
if (highest_u < kbps_range_u[i]){
highest_u = kbps_range_u[i];
}
}
// reset the screen
clear_screen();
// rebuild the display
for (i = 0; i < 32; i++){
// top row of display acts as a scale,
// the higher the highest upload is, the more pixels that are filled in
// start from right most pixel and work backwords
// every pixel represends 256kbps
if (highest_u > 256*i){
set_pixel(31-i, 0, 1);
}
// same idea as above
if (highest_d > 256*i){
set_pixel(31-i, 8, 1);
}
// main display
// rows 1-7
// every column is its own line, height relative to highest seen upload speed
if (kbps_range_u[(i+kbps_p)%32] > 50){
fill_rectangle(i, 7 - 6*((double)kbps_range_u[(i+kbps_p)%32]/(double)highest_u), i+1,
8, 1);
}
// same idea as above
if (kbps_range_d[(i+kbps_p)%32] > 50){
fill_rectangle(i, 16 - 7*((double)kbps_range_d[(i+kbps_p)%32]/(double)highest_d), i+1,
16, 1);
}
}
}
// increment timer
timer = (timer + 1) % time_before_refresh;
// always refresh the display
refresh();
}
}
| 3.125 | 3 |
2024-11-18T22:10:58.977727+00:00
| 2023-08-23T04:46:46 |
a682bec9c1cbcef62ed855b09b4798e348705f8e
|
{
"blob_id": "a682bec9c1cbcef62ed855b09b4798e348705f8e",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-23T04:46:46",
"content_id": "ccd5670b1dd064bad429f4f864613b661ac8e46d",
"detected_licenses": [
"MIT"
],
"directory_id": "2c73a693c2b3c162eae2ab94f649d8c4494878ba",
"extension": "c",
"filename": "lv_ex_table_1.c",
"fork_events_count": 93,
"gha_created_at": "2019-12-27T08:29:19",
"gha_event_created_at": "2021-12-17T02:19:30",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 230403844,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1350,
"license": "MIT",
"license_type": "permissive",
"path": "/components/lvgl/lv_demos/src/lv_ex_widgets/lv_ex_table/lv_ex_table_1.c",
"provenance": "stackv2-0072.json.gz:36885",
"repo_name": "openLuat/LuatOS",
"revision_date": "2023-08-23T04:46:46",
"revision_id": "4b29d5121ab4f7133630331e8502c526c7856897",
"snapshot_id": "185e1e140aed908434168133571ddcafe98f4e12",
"src_encoding": "UTF-8",
"star_events_count": 378,
"url": "https://raw.githubusercontent.com/openLuat/LuatOS/4b29d5121ab4f7133630331e8502c526c7856897/components/lvgl/lv_demos/src/lv_ex_widgets/lv_ex_table/lv_ex_table_1.c",
"visit_date": "2023-08-23T04:57:23.263539"
}
|
stackv2
|
#include "../../../lv_examples.h"
#if LV_USE_TABLE
void lv_ex_table_1(void)
{
lv_obj_t * table = lv_table_create(lv_scr_act(), NULL);
lv_table_set_col_cnt(table, 2);
lv_table_set_row_cnt(table, 4);
lv_obj_align(table, NULL, LV_ALIGN_CENTER, 0, 0);
/*Make the cells of the first row center aligned */
lv_table_set_cell_align(table, 0, 0, LV_LABEL_ALIGN_CENTER);
lv_table_set_cell_align(table, 0, 1, LV_LABEL_ALIGN_CENTER);
/*Align the price values to the right in the 2nd column*/
lv_table_set_cell_align(table, 1, 1, LV_LABEL_ALIGN_RIGHT);
lv_table_set_cell_align(table, 2, 1, LV_LABEL_ALIGN_RIGHT);
lv_table_set_cell_align(table, 3, 1, LV_LABEL_ALIGN_RIGHT);
lv_table_set_cell_type(table, 0, 0, 2);
lv_table_set_cell_type(table, 0, 1, 2);
/*Fill the first column*/
lv_table_set_cell_value(table, 0, 0, "Name");
lv_table_set_cell_value(table, 1, 0, "Apple");
lv_table_set_cell_value(table, 2, 0, "Banana");
lv_table_set_cell_value(table, 3, 0, "Citron");
/*Fill the second column*/
lv_table_set_cell_value(table, 0, 1, "Price");
lv_table_set_cell_value(table, 1, 1, "$7");
lv_table_set_cell_value(table, 2, 1, "$4");
lv_table_set_cell_value(table, 3, 1, "$6");
lv_table_ext_t * ext = lv_obj_get_ext_attr(table);
ext->row_h[0] = 20;
}
#endif
| 2.609375 | 3 |
2024-11-18T22:10:59.636834+00:00
| 2020-11-05T15:49:17 |
c2908056bb6fd546c22a2cdd7ea2d8876a1bb084
|
{
"blob_id": "c2908056bb6fd546c22a2cdd7ea2d8876a1bb084",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-05T15:49:17",
"content_id": "3159ebe2bdb1b48cb24ffb2812076feea4e6cef7",
"detected_licenses": [
"MIT"
],
"directory_id": "62a7f3b7e884f49d0285bfdf483ef53cec890019",
"extension": "c",
"filename": "rtos.c",
"fork_events_count": 1,
"gha_created_at": "2014-11-27T01:22:32",
"gha_event_created_at": "2017-02-28T22:13:42",
"gha_language": "C",
"gha_license_id": null,
"github_id": 27203641,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 20186,
"license": "MIT",
"license_type": "permissive",
"path": "/rtos/rtos.c",
"provenance": "stackv2-0072.json.gz:37530",
"repo_name": "azsoter/jaeos-devel",
"revision_date": "2020-11-05T15:49:17",
"revision_id": "68eae10d7c6b8134966d073ea832950c1587a483",
"snapshot_id": "4bef1f93baeb0e962499bf5db305d17976a71538",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/azsoter/jaeos-devel/68eae10d7c6b8134966d073ea832950c1587a483/rtos/rtos.c",
"visit_date": "2020-12-24T16:07:36.056282"
}
|
stackv2
|
/*
* Copyright (c) Andras Zsoter 2014-2016.
*
* 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 <stdint.h>
#include <rtos.h>
#include <rtos_internals.h>
volatile RTOS_OS RTOS;
RTOS_RegInt rtos_CreateTask(RTOS_Task *task, void *sp0, unsigned long stackCapacity, void (*f)(void *), void *param)
{
RTOS_RegInt i;
#if defined(RTOS_USE_ASSERTS)
RTOS_ASSERT(0 != task);
#endif
if (0 == task)
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
// sp0 == 0 means that we are initializing a task structure for the 'current thread of execution'.
// In that case no stack initialization will be done.
// Also check for sufficient stack space. RTOS_INITIAL_STACK_DEPT defined in the target specific rtos_types.h is in bytes.
if ((0 != sp0) && ((RTOS_INITIAL_STACK_DEPTH) >= (sizeof(RTOS_StackItem_t) * stackCapacity)))
{
return RTOS_ERROR_FAILED;
}
task->Action = f;
task->Parameter = param;
task->SP0 = sp0;
rtos_TargetInitializeTask(task, stackCapacity);
#if defined(RTOS_SUPPORT_TIMESHARE)
task->IsTimeshared = 0;
task->TicksToRun = RTOS_TIMEOUT_FOREVER;
task->TimeSliceTicks = RTOS_TIMEOUT_FOREVER;
task->Link.Previous = 0;
task->Link.Next = 0;
#endif
return RTOS_OK;
}
// This function needs to be called from a single threaded context.
// Either before the OS has started or from a critical section.
RTOS_RegInt rtos_RegisterTask(RTOS_Task *task, RTOS_TaskPriority priority)
{
#if defined(RTOS_USE_ASSERTS)
RTOS_ASSERT(0 != task);
RTOS_ASSERT(0 == RTOS.TaskList[priority]);
#endif
if (0 != RTOS.TaskList[priority])
{
return RTOS_ERROR_PRIORITY_IN_USE;
}
if (0 == task)
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
task->Priority = priority;
RTOS.TaskList[priority] = task;
#if defined(RTOS_SMP)
rtos_RestrictPriorityToCpus(priority, ~(RTOS_CpuMask)0);
#endif
#if defined(RTOS_SUPPORT_TIMESHARE)
if (task->IsTimeshared)
{
RTOS_TaskSet_AddMember(RTOS.TimeshareTasks, task->Priority);
}
#endif
RTOS_TaskSet_AddMember(RTOS.ReadyToRunTasks, priority);
return RTOS_OK;
}
#if defined(RTOS_TASK_NAME_LENGTH)
// This function can be called during initialization before the RTOS is fully functional.
void RTOS_SetTaskName(RTOS_Task *task, const char *name)
{
RTOS_RegInt i;
char c;
#if defined(RTOS_USE_ASSERTS)
RTOS_ASSERT(0 != task);
#endif
if (0 == task)
{
return;
}
task->TaskName[0] = '\0';
task->TaskName[(RTOS_TASK_NAME_LENGTH) - 1] = '\0';
if (0 != name)
{
// We do not necessarily even have a standard C library, so copy stuff manually.
for (i = 0; i < ((RTOS_TASK_NAME_LENGTH) - 1); i++)
{
c = *name++;
task->TaskName[i] = c;
if (0 == c)
{
break;
}
}
}
}
#endif
// This function can be called during initialization before the RTOS is fully functional.
RTOS_RegInt RTOS_CreateTask(RTOS_Task *task, const char *name, RTOS_TaskPriority priority, void *sp0, unsigned long stackCapacity, void (*f)(), void *param)
{
RTOS_RegInt result;
RTOS_SavedCriticalState(saved_state = 0);
result = rtos_CreateTask(task, sp0, stackCapacity, f, param);
#if defined(RTOS_TASK_NAME_LENGTH)
RTOS_SetTaskName(task, name);
#else
(void)name;
#endif
if (RTOS.IsRunning)
{
RTOS_EnterCriticalSection(saved_state);
}
if (RTOS_OK == result)
{
result = rtos_RegisterTask(task, priority);
}
if (RTOS.IsRunning)
{
RTOS_ExitCriticalSection(saved_state);
}
return result;
}
// -----------------------------------------------------------------------------------
#if !defined(RTOS_SMP)
RTOS_Task *RTOS_GetCurrentTask(void)
{
return RTOS.CurrentTask;
}
#endif
// Stop the calling task and remove it from the system (i.e. 'kill it').
RTOS_RegInt RTOS_KillSelf(void)
{
RTOS_Task *task;
RTOS_TaskPriority priority;
RTOS_SavedCriticalState(saved_state);
#if defined(RTOS_USE_ASSERTS)
RTOS_ASSERT(!RTOS_IsInsideIsr());
RTOS_ASSERT(!RTOS_SchedulerIsLocked());
#endif
if (RTOS_IsInsideIsr())
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
RTOS_EnterCriticalSection(saved_state);
#if defined(RTOS_INCLUDE_SCHEDULER_LOCK)
if (RTOS_SchedulerIsLocked())
{
RTOS_ExitCriticalSection(saved_state);
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
#endif
task = RTOS_CURRENT_TASK();
priority = task->Priority;
// Task is removed from the ready to run set.
// No other sets are touched. The assumption is that the task cannot be sleeping or waiting for some event
// since it is obviously executing otherwise we would not be here.
RTOS_TaskSet_RemoveMember(RTOS.ReadyToRunTasks, priority);
#if defined(RTOS_SUPPORT_TIMESHARE)
// Make sure the task is not in the time share set.
RTOS_TaskSet_RemoveMember(RTOS.TimeshareTasks, priority);
#endif
#if defined(RTOS_SMP)
rtos_RestrictPriorityToCpus(priority, (RTOS_CpuMask)0);
#endif
// Remove task from the list of valid tasks and mark it as killed.
RTOS.TaskList[priority] = 0;
task->Status = RTOS_TASK_STATUS_KILLED;
RTOS_INVOKE_SCHEDULER();
RTOS_ExitCriticalSection(saved_state); // Not reachable, but pacifies GCC.
return RTOS_ERROR_FAILED; // Not actually reachable.
}
void rtos_RunTask(void)
{
volatile RTOS_Task *thisTask;
RTOS_TaskPriority priority;
RTOS_SavedCriticalState(saved_state);
thisTask = RTOS_GetCurrentTask();
// Execute the task's function.
thisTask->Action(thisTask->Parameter);
// If the tasks function has returned just kill the task and try to clean up after it as much as possible.
// There is no real resource management, so the task should first do its own clean up.
RTOS_EnterCriticalSection(saved_state);
RTOS_KillSelf();
// Invoke the scheduler to select a different task to run.
RTOS_INVOKE_SCHEDULER();
// We truly should never get here.
while(1);
RTOS_ExitCriticalSection(saved_state); // Not reachable, but pacifies GCC.
}
#if defined(RTOS_FIND_HIGHEST)
RTOS_TaskPriority RTOS_GetHighestPriorityInSet(RTOS_TaskSet taskSet)
{
return RTOS_FIND_HIGHEST(taskSet);
}
#else
#error RTOS_FIND_HIGHEST must be defined by the target port.
#endif
//RTOS_INLINE RTOS_Task *rtos_TaskFromPriority(RTOS_TaskPriority priority)
//{
// return (priority > RTOS_Priority_Highest) ? 0 : RTOS.TaskList[priority];
//}
// This is an API function wrapper, do not confuse it with the internal (and much faster) macro rtos_TaskFromPriority(PRIORITY).
RTOS_Task *RTOS_TaskFromPriority(RTOS_TaskPriority priority)
{
RTOS_Task *task;
RTOS_SavedCriticalState(saved_state);
RTOS_EnterCriticalSection(saved_state);
task = rtos_TaskFromPriority(priority);
RTOS_ExitCriticalSection(saved_state);
return task;
}
#if !defined(RTOS_SMP)
// The Scheduler must be called from inside an ISR or some similar context depending on the target system.
void rtos_Scheduler(void)
{
RTOS_TaskPriority priority;
RTOS_Task *task;
#if defined(RTOS_SUPPORT_TIMESHARE)
rtos_ManageTimeshared(RTOS.CurrentTask);
#endif
#if defined(RTOS_INCLUDE_SCHEDULER_LOCK)
if (RTOS_SchedulerIsLocked())
{
return;
}
#endif
priority = RTOS_GetHighestPriorityInSet(RTOS.ReadyToRunTasks);
task = rtos_TaskFromPriority(priority);
if (0 != task)
{
RTOS.CurrentTask = task;
}
}
#endif
#if defined(RTOS_INVOKE_YIELD)
#if !defined(RTOS_SMP)
void rtos_SchedulerForYield(void)
{
RTOS_TaskPriority currentPriority;
RTOS_TaskPriority priority;
RTOS_Task *task;
RTOS_TaskSet tasks;
RTOS_TaskSet t;
RTOS_Task *currentTask;
currentTask = RTOS.CurrentTask;
#if defined(RTOS_SUPPORT_TIMESHARE)
rtos_ManageTimeshared(currentTask);
#endif
#if defined(RTOS_INCLUDE_SCHEDULER_LOCK)
if (RTOS_SchedulerIsLocked())
{
return;
}
#endif
currentPriority = currentTask->Priority;
tasks = RTOS.ReadyToRunTasks;
t = tasks;
RTOS_TaskSet_RemoveMember(t, RTOS_Priority_Idle); // Not the idle task.
t = t & ~((~(RTOS_TaskSet)0) << currentPriority); // This makes the assumption that RTOS_TaskSet is some integer type.
priority = RTOS_GetHighestPriorityInSet(t);
task = rtos_TaskFromPriority(priority);
if (0 == task) // If a normal yield did not produce a task just act like a normal scheduler.
{
priority = RTOS_GetHighestPriorityInSet(tasks);
task = rtos_TaskFromPriority(priority);
}
if (0 != task)
{
RTOS.CurrentTask = task;
}
}
#endif
void RTOS_YieldPriority(void)
{
if ((!RTOS_IsInsideIsr()) && (!RTOS_SchedulerIsLocked()))
{
RTOS_INVOKE_YIELD();
}
}
#endif
#if defined(RTOS_INCLUDE_SCHEDULER_LOCK)
RTOS_RegInt RTOS_LockScheduler(void)
{
RTOS_SavedCriticalState(saved_state);
if (RTOS_IsInsideIsr())
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
RTOS_EnterCriticalSection(saved_state);
RTOS.SchedulerLocked++;
RTOS_ExitCriticalSection(saved_state);
return RTOS_OK;
}
RTOS_RegInt RTOS_UnlockScheduler(void)
{
RTOS_SavedCriticalState(saved_state);
if (RTOS_IsInsideIsr())
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
RTOS_EnterCriticalSection(saved_state);
if (0 == RTOS.SchedulerLocked)
{
RTOS_ExitCriticalSection(saved_state);
return RTOS_ERROR_FAILED;
}
else
{
RTOS.SchedulerLocked--;
}
RTOS_ExitCriticalSection(saved_state);
if (0 == RTOS.SchedulerLocked)
{
RTOS_INVOKE_SCHEDULER();
}
return RTOS_OK;
}
#endif
RTOS_Time RTOS_GetTime(void)
{
RTOS_Time time;
RTOS_SavedCriticalState(saved_state);
RTOS_EnterCriticalSection(saved_state);
time = RTOS.Time;
RTOS_ExitCriticalSection(saved_state);
return time;
}
#if 0
void RTOS_SetTime(RTOS_Time time)
{
RTOS_SavedCriticalState(saved_state);
RTOS_EnterCriticalSection(saved_state);
RTOS.Time = time;
RTOS_ExitCriticalSection(saved_state);
}
#endif
#if defined(RTOS_SUPPORT_SLEEP)
RTOS_INLINE void rtos_AddToSleepers(RTOS_Task *task)
{
RTOS.Sleepers[task->Priority] = task;
}
RTOS_INLINE void rtos_RemoveFromSleepers(RTOS_Task *task)
{
RTOS.Sleepers[task->Priority] = 0;
}
#endif
#if defined(RTOS_INCLUDE_DELAY)
// Delay() and DelayUntil().
// The parameter absolute chooses if time is relative to the current time i.e. Delay() or absolute i.e. DelayUntil().
RTOS_RegInt rtos_Delay(RTOS_Time time, RTOS_RegInt absolute)
{
RTOS_RegInt result;
volatile RTOS_Task *thisTask;
RTOS_SavedCriticalState(saved_state);
thisTask = RTOS_GetCurrentTask();
#if defined(RTOS_USE_ASSERTS)
RTOS_ASSERT(!RTOS_IsInsideIsr());
RTOS_ASSERT(!RTOS_SchedulerIsLocked());
RTOS_ASSERT(RTOS_Priority_Idle != thisTask->Priority);
#endif
#if !defined(RTOS_DISABLE_RUNTIME_CHECKS)
if (RTOS_IsInsideIsr())
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
// The Idle task cannot sleep!
if (RTOS_Priority_Idle == thisTask->Priority)
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
#endif
RTOS_EnterCriticalSection(saved_state);
#if !defined(RTOS_DISABLE_RUNTIME_CHECKS)
if (RTOS_SchedulerIsLocked())
{
RTOS_ExitCriticalSection(saved_state);
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
#endif
thisTask->WakeUpTime = absolute ? time : (RTOS.Time + time);
RTOS_TaskSet_RemoveMember(RTOS.ReadyToRunTasks, thisTask->Priority);
thisTask->Status = RTOS_TASK_STATUS_SLEEPING;
#if defined(RTOS_SUPPORT_TIMESHARE)
if (thisTask->IsTimeshared)
{
thisTask->Link.Previous = 0;
thisTask->Link.Next = 0;
}
#endif
rtos_AddToSleepers(thisTask);
RTOS_ExitCriticalSection(saved_state);
RTOS_INVOKE_SCHEDULER();
RTOS_EnterCriticalSection(saved_state);
#if defined( RTOS_INCLUDE_WAKEUP)
result = (RTOS_TASK_STATUS_AWAKENED == thisTask->Status) ? RTOS_ABORTED : RTOS_OK;
#else
result = RTOS_OK;
#endif
thisTask->Status = RTOS_TASK_STATUS_ACTIVE;
RTOS_ExitCriticalSection(saved_state);
return result;
}
RTOS_RegInt RTOS_DelayUntil(RTOS_Time wakeUpTime)
{
return rtos_Delay(wakeUpTime, 1);
}
RTOS_RegInt RTOS_Delay(RTOS_Time ticksToSleep)
{
if (0 == ticksToSleep)
{
return RTOS_OK;
}
return rtos_Delay(ticksToSleep, 0);
}
#endif
#if defined(RTOS_SUPPORT_EVENTS)
void rtos_WaitForEvent(RTOS_EventHandle *event, RTOS_Task *task, RTOS_Time timeout)
{
task->WaitFor = event;
RTOS_TaskSet_AddMember(event->TasksWaiting, task->Priority);
#if defined(RTOS_SUPPORT_TIMESHARE)
if (task->IsTimeshared)
{
rtos_AppendTaskToDLList(&(event->WaitList), task);
}
#endif
RTOS_TaskSet_RemoveMember(RTOS.ReadyToRunTasks, task->Priority);
task->Status = RTOS_TASK_STATUS_WAITING;
if ((0 != timeout) && ((RTOS_TIMEOUT_FOREVER) != timeout))
{
task->WakeUpTime = RTOS.Time + timeout;
rtos_AddToSleepers(task);
}
}
RTOS_INLINE void rtos_RemoveTaskWaiting(RTOS_EventHandle *event, RTOS_Task *task)
{
if (0 == task)
{
return;
}
RTOS_TaskSet_RemoveMember(event->TasksWaiting, task->Priority);
#if defined(RTOS_SUPPORT_TIMESHARE)
rtos_RemoveTaskFromDLList(&(event->WaitList), task);
#endif
task->WaitFor = 0;
}
#if defined(RTOS_SUPPORT_TIMESHARE)
RTOS_INLINE RTOS_Task *rtos_GetFirstWaitingTask(RTOS_EventHandle *event)
{
RTOS_Task *task = 0;
task = rtos_RemoveFirstTaskFromDLList(&(event->WaitList));
return task;
}
#endif
RTOS_RegInt rtos_SignalEvent(RTOS_EventHandle *event)
{
RTOS_TaskPriority priority;
RTOS_Task *task;
priority = RTOS_GetHighestPriorityInSet(event->TasksWaiting);
if (priority <= RTOS_Priority_Highest)
{
#if defined(RTOS_SUPPORT_TIMESHARE)
if (RTOS_TaskSet_IsMember(RTOS.TimeshareTasks, priority))
{
task = rtos_GetFirstWaitingTask(event);
}
else
{
task = rtos_TaskFromPriority(priority);
}
#else
task = rtos_TaskFromPriority(priority);
#endif
if (0 != task)
{
RTOS_TaskSet_RemoveMember(event->TasksWaiting, task->Priority);
task->WaitFor = 0;
rtos_RemoveFromSleepers(task);
RTOS_TaskSet_AddMember(RTOS.ReadyToRunTasks, task->Priority);
task->Status = RTOS_TASK_STATUS_ACTIVE;
return RTOS_OK;
}
}
return RTOS_TIMED_OUT;
}
// Mapping task status after waking up from an event to a return value.
// Should this be moved to a #define macro?
RTOS_RegInt rtos_MapStatusToReturnValue(RTOS_RegInt status)
{
#if defined( RTOS_INCLUDE_WAKEUP)
return (RTOS_TASK_STATUS_TIMED_OUT == status) ? RTOS_TIMED_OUT : ((RTOS_TASK_STATUS_AWAKENED == status) ? RTOS_ABORTED : RTOS_OK);
#else
return (RTOS_TASK_STATUS_TIMED_OUT == status) ? RTOS_TIMED_OUT : RTOS_OK;
#endif
}
#endif
#if defined(RTOS_SUPPORT_EVENTS)
RTOS_RegInt RTOS_CreateEventHandle(RTOS_EventHandle *event)
{
#if defined(RTOS_USE_ASSERTS)
RTOS_ASSERT(0 != event);
#endif
#if !defined(RTOS_DISABLE_RUNTIME_CHECKS)
if (0 == event)
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
#endif
event->TasksWaiting = 0;
#if defined(RTOS_SUPPORT_TIMESHARE)
event->WaitList.Head = 0;
event->WaitList.Tail = 0;
#endif
return RTOS_OK;
}
#endif
#if defined(RTOS_INCLUDE_WAKEUP) || defined(RTOS_INCLUDE_SUSPEND_AND_RESUME)
RTOS_RegInt rtos_WakeupTask(RTOS_Task *task)
{
if (0 == task)
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
if ((RTOS_TASK_STATUS_WAITING != task->Status) && (RTOS_TASK_STATUS_SLEEPING != task->Status))
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
if (0 != task->WaitFor)
{
rtos_RemoveTaskWaiting(task->WaitFor, task);
}
rtos_RemoveFromSleepers(task);
RTOS_TaskSet_AddMember(RTOS.ReadyToRunTasks, task->Priority);
task->Status = RTOS_TASK_STATUS_AWAKENED;
return RTOS_OK;
}
#endif
#if defined(RTOS_INCLUDE_SUSPEND_AND_RESUME)
RTOS_RegInt RTOS_SuspendSelf(void)
{
RTOS_Task *task;
RTOS_TaskPriority priority;
RTOS_SavedCriticalState(saved_state);
#if defined(RTOS_USE_ASSERTS)
RTOS_ASSERT(!RTOS_IsInsideIsr());
RTOS_ASSERT(!RTOS_SchedulerIsLocked());
#endif
#if !defined(RTOS_DISABLE_RUNTIME_CHECKS)
if (RTOS_IsInsideIsr())
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
#endif
RTOS_EnterCriticalSection(saved_state);
if (RTOS_SchedulerIsLocked())
{
RTOS_ExitCriticalSection(saved_state);
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
task = RTOS_CURRENT_TASK();
priority = task->Priority;
RTOS_TaskSet_RemoveMember(RTOS.ReadyToRunTasks, priority);
RTOS_TaskSet_AddMember(RTOS.SuspendedTasks, priority);
task->Status |= RTOS_TASK_STATUS_SUSPENDED_FLAG;
RTOS_ExitCriticalSection(saved_state);
RTOS_INVOKE_SCHEDULER();
return RTOS_OK; // This will only be reached on resume.
}
RTOS_RegInt RTOS_ResumeTask(RTOS_Task *task)
{
RTOS_RegInt result;
RTOS_SavedCriticalState(saved_state);
#if defined(RTOS_USE_ASSERTS)
RTOS_ASSERT(0 != task);
#endif
#if !defined(RTOS_DISABLE_RUNTIME_CHECKS)
if (0 == task)
{
return RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
#endif
RTOS_EnterCriticalSection(saved_state);
if (!RTOS_TaskSet_IsMember(RTOS.SuspendedTasks, task->Priority))
{
result = RTOS_ERROR_OPERATION_NOT_PERMITTED;
}
else
{
RTOS_TaskSet_RemoveMember(RTOS.SuspendedTasks, task->Priority);
RTOS_TaskSet_AddMember(RTOS.ReadyToRunTasks, task->Priority);
task->Status &= ~(RTOS_TASK_STATUS_SUSPENDED_FLAG);
result = RTOS_OK;
}
RTOS_ExitCriticalSection(saved_state);
RTOS_REQUEST_RESCHEDULING();
return result;
}
#endif
static void rtos_TimerTickFunction(void)
{
RTOS_TaskPriority i;
RTOS_Task *task;
RTOS.Time++;
#if defined(RTOS_SUPPORT_SLEEP)
#if defined(RTOS_USE_TIMER_TASK)
RTOS_SavedCriticalState(saved_state);
#endif
// The Idle task should never actually sleep!
// We can start checking at priority 1 instead of 0.
for (i = 1; i <= RTOS_Priority_Highest; i++)
{
#if defined(RTOS_USE_TIMER_TASK)
RTOS_EnterCriticalSection(saved_state);
#endif
task = RTOS.Sleepers[i];
if (0 != task)
{
if (task->WakeUpTime == RTOS.Time)
{
rtos_RemoveFromSleepers(task);
if (0 != task->WaitFor)
{
rtos_RemoveTaskWaiting(task->WaitFor, task);
}
RTOS_TaskSet_AddMember(RTOS.ReadyToRunTasks, i);
task->Status = RTOS_TASK_STATUS_TIMED_OUT;
}
}
#if defined(RTOS_USE_TIMER_TASK)
RTOS_ExitCriticalSection(saved_state);
#endif
}
#endif
}
#if defined(RTOS_USE_TIMER_TASK)
void RTOS_DefaultTimerFunction(void *p)
{
while(1)
{
rtos_TimerTickFunction();
#if defined(RTOS_TIMER_EXTRA_ACTION)
RTOS_TIMER_EXTRA_ACTION();
#endif
RTOS_SuspendSelf();
}
(void)p;
}
void rtos_TimerTick(void)
{
RTOS_Task *task;
task = RTOS.TaskList[RTOS_Priority_Timer];
if (0 != task)
{
RTOS_ResumeTask(task);
}
// Perhaps we need some action for SMP here too.
// Check this when SMP features become more mature.
}
#else
void rtos_TimerTick(void)
{
rtos_TimerTickFunction();
#if defined(RTOS_TIMER_EXTRA_ACTION)
RTOS_TIMER_EXTRA_ACTION();
#endif
#if defined(RTOS_SMP)
rtos_SignalCpus(RTOS_CpuMask_RemoveCpu(RTOS.TimeShareCpus, RTOS_CurrentCpu()));
#endif
}
#endif
void rtos_PrepareToStart(void)
{
#if defined(RTOS_SMP) && defined(RTOS_SUPPORT_TIMESHARE)
RTOS.TimeshareParallelAllowed = (RTOS_TIMESHARE_PARALLEL_MAX);
#endif
}
// The default assert function, if the assert fails just hang the system and go to an infinite loop.
// One will need a debugger to find out what has happened.
void rtos_DefaultAssert(int cond)
{
RTOS_SavedCriticalState(saved_state);
if (!cond)
{
// Make the system dead.
RTOS_EnterCriticalSection(saved_state);
while(1);
RTOS_ExitCriticalSection(saved_state); // Not reachable, but pacifies GCC.
}
}
// End of RTOS Core Functions.
| 2.265625 | 2 |
2024-11-18T22:11:00.733359+00:00
| 2023-07-20T10:07:52 |
fd12e2b8ed9da6b6609832bf5ab29cca491f8ac9
|
{
"blob_id": "fd12e2b8ed9da6b6609832bf5ab29cca491f8ac9",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-20T10:07:52",
"content_id": "571c57271886f3e5873ff9f68eb9f646bda6e22b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "73e6cfe18dd52725f3f3859e81755dfd32a61844",
"extension": "h",
"filename": "logger.h",
"fork_events_count": 6,
"gha_created_at": "2016-10-03T17:17:24",
"gha_event_created_at": "2023-05-01T20:15:00",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 69892828,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6889,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/include/log/logger.h",
"provenance": "stackv2-0072.json.gz:37916",
"repo_name": "IITDBGroup/gprom",
"revision_date": "2023-07-20T10:07:52",
"revision_id": "0d964a8b3ca6d4a5d344bb856626d47c95bac890",
"snapshot_id": "a0c41dda321681e7976299549e039fb845588d73",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/IITDBGroup/gprom/0d964a8b3ca6d4a5d344bb856626d47c95bac890/include/log/logger.h",
"visit_date": "2023-08-31T17:31:52.085716"
}
|
stackv2
|
/*-------------------------------------------------------------------------
*
* logger.h
* Author: Ying Ni yni6@hawk.iit.edu
* This module provides uniform logging for the whole system and exception
* handling capabilities.
*
* XXX_LOG() macros work like printf() in C. The first argument is a
* format string. Additional optional arguments are parameters
* substituted in the format string. For example:
* int t = 5;
* DEBUG_LOG("value of "%s" is %d", "t", t);
* There are six log levels: 0-FATAL, 1-ERROR, 2-WARN, 3-INFO, 4-DEBUG,
* 5-TRACE. Logs of the levels below or equal to the log level value
* set from the command line will be printed. For example, if log level
* is set to 3 by command line, then logs from FATAL to INFO level will
* be printed while logs at DEBUG and TRACE level will not be printed.
* Currently, FATAL causes the application to exit.
*
*-------------------------------------------------------------------------
*/
#ifndef LOGGER_H_
#define LOGGER_H_
#include "common.h"
#include "exception/exception.h"
typedef struct logger_state LoggerState;
typedef enum LogLevel
{
LOG_FATAL = 0,
LOG_ERROR = 1,
LOG_WARN = 2,
LOG_INFO = 3,
LOG_DEBUG = 4,
LOG_TRACE = 5
} LogLevel;
extern void reinitLogger(void);
extern void initLogger(void);
extern void shutdownLogger (void);
extern void setMaxLevel (LogLevel level);
extern void logNodes_(LogLevel level, const char *file, unsigned line,
boolean beatify, char * (*toStringFunc) (void *),
const char *message, ...);
extern void log_(LogLevel level, const char *file, unsigned line,
const char *template, ...);
extern char *formatMes(const char *template, ...);
extern void _debugNode(void *p);
extern void _debugMessage(char *mes);
extern void registerLogCallback (void (*callback) (const char *,const char *,
int,int));
extern LogLevel maxLevel;
/* user has deactivated logging (default) */
#ifdef DISABLE_LOGGING
#define FATAL_LOG(template, ...)
#define ERROR_LOG(template, ...)
#define WARN_LOG(template, ...)
#define INFO_LOG(template, ...)
#define DEBUG_LOG(template, ...)
#define TRACE_LOG(template, ...)
#define GENERIC_LOG(level, file, line, template, ...)
#define INFO_NODE_LOG(message, ...)
#define DEBUG_NODE_LOG(message, ...)
#define TRACE_NODE_LOG(message, ...)
#define ERROR_NODE_BEATIFY_LOG(message, ...)
#define INFO_NODE_BEATIFY_LOG(message, ...)
#define DEBUG_NODE_BEATIFY_LOG(message, ...)
#define INFO_DL_LOG(message, ...)
#define ERROR_OP_LOG(message, ...)
#define INFO_OP_LOG(message, ...)
/* user has activated logging (default) */
#else
#define FATAL_LOG(template, ...) \
do { \
log_(LOG_FATAL, __FILE__, __LINE__, (template), ##__VA_ARGS__); \
THROW(SEVERITY_RECOVERABLE,(template), ##__VA_ARGS__); \
} while (0)
#define ERROR_LOG(template, ...) \
do { \
if (maxLevel >= LOG_ERROR) \
log_(LOG_ERROR, __FILE__, __LINE__, (template), ##__VA_ARGS__); \
} while (0)
#define WARN_LOG(template, ...) \
do { \
if (maxLevel >= LOG_WARN) \
log_(LOG_WARN, __FILE__, __LINE__, (template), ##__VA_ARGS__); \
} while (0)
#define INFO_LOG(template, ...) \
do { \
if (maxLevel >= LOG_INFO) \
log_(LOG_INFO, __FILE__, __LINE__, (template), ##__VA_ARGS__); \
} while (0)
#define DEBUG_LOG(template, ...) \
do { \
if (maxLevel >= LOG_DEBUG) \
log_(LOG_DEBUG, __FILE__, __LINE__, (template), ##__VA_ARGS__); \
} while (0)
#define TRACE_LOG(template, ...) \
do { \
if (maxLevel >= LOG_TRACE) \
log_(LOG_TRACE, __FILE__, __LINE__, (template), ##__VA_ARGS__); \
} while (0)
#define GENERIC_LOG(level, file, line, template, ...) \
do { \
if (maxLevel >= level) \
log_(level, file, line, (template), ##__VA_ARGS__); \
} while (0)
#define NODE_LOG(loglevel,message, ...) \
do { \
if (maxLevel >= loglevel) \
logNodes_(loglevel, __FILE__, __LINE__, FALSE, nodeToString, (message), ##__VA_ARGS__, NULL); \
} while (0)
#define TRACE_NODE_LOG(message, ...) NODE_LOG(LOG_TRACE,message, ##__VA_ARGS__)
#define DEBUG_NODE_LOG(message, ...) NODE_LOG(LOG_DEBUG,message, ##__VA_ARGS__)
#define INFO_NODE_LOG(message, ...) NODE_LOG(LOG_INFO,message, ##__VA_ARGS__)
#define ERROR_NODE_LOG(message, ...) NODE_LOG(LOG_ERROR,message, ##__VA_ARGS__)
#define FATAL_NODE_LOG(message, ...) \
do { \
NODE_LOG(LOG_FATAL,message, ##__VA_ARGS__); \
THROW(SEVERITY_RECOVERABLE,(message), ##__VA_ARGS__); \
} while (0);
#define NODE_BEATIFY_LOG(loglevel,message, ...) \
do { \
if (maxLevel >= loglevel) \
logNodes_(loglevel, __FILE__, __LINE__, TRUE, nodeToString, (message), ##__VA_ARGS__, NULL); \
} while (0)
#define DEBUG_NODE_BEATIFY_LOG(message, ...) NODE_BEATIFY_LOG(LOG_DEBUG,message, ##__VA_ARGS__)
#define INFO_NODE_BEATIFY_LOG(message, ...) NODE_BEATIFY_LOG(LOG_INFO,message, ##__VA_ARGS__)
#define ERROR_NODE_BEATIFY_LOG(message, ...) NODE_BEATIFY_LOG(LOG_ERROR,message, ##__VA_ARGS__)
#define FATAL_NODE_BEATIFY_LOG(message, ...) \
do { \
NODE_BEATIFY_LOG(LOG_FATAL,message, ##__VA_ARGS__); \
THROW(SEVERITY_RECOVERABLE,(message), ##__VA_ARGS__); \
} while (0);
#define DL_LOG(loglevel, message, ...) \
do { \
if (maxLevel >= loglevel) \
logNodes_(loglevel, __FILE__, __LINE__, FALSE, datalogToOverviewString, (message), ##__VA_ARGS__, NULL); \
} while (0)
#define DEBUG_DL_LOG(message, ...) DL_LOG(LOG_DEBUG,message, ##__VA_ARGS__)
#define INFO_DL_LOG(message, ...) DL_LOG(LOG_INFO,message, ##__VA_ARGS__)
#define ERROR_DL_LOG(message, ...) DL_LOG(LOG_ERROR,message, ##__VA_ARGS__)
#define FATAL_DL_LOG(message, ...) \
do { \
DL_LOG(LOG_FATAL,message, ##__VA_ARGS__); \
THROW(SEVERITY_RECOVERABLE,(message), ##__VA_ARGS__); \
} while (0);
#define OP_LOG(loglevel, message, ...) \
do { \
if (maxLevel >= loglevel) \
logNodes_(loglevel, __FILE__, __LINE__, FALSE, operatorToOverviewString, (message), ##__VA_ARGS__, NULL); \
} while (0)
#define DEBUG_OP_LOG(message, ...) OP_LOG(LOG_DEBUG,message, ##__VA_ARGS__)
#define INFO_OP_LOG(message, ...) OP_LOG(LOG_INFO,message, ##__VA_ARGS__)
#define ERROR_OP_LOG(message, ...) OP_LOG(LOG_ERROR,message, ##__VA_ARGS__)
#define FATAL_OP_LOG(message, ...) \
do { \
OP_LOG(LOG_FATAL,message, ##__VA_ARGS__); \
THROW(SEVERITY_RECOVERABLE,(message), ##__VA_ARGS__); \
} while (0);
#define INFO_AND_DEBUG_OP_LOG(_msg, _op) \
do { \
DEBUG_NODE_BEATIFY_LOG(_msg " details:", _op); \
INFO_OP_LOG(_msg " overview:", _op); \
} while(0)
#endif
/* logging activated switch */
/* header */
#endif
| 2.296875 | 2 |
2024-11-18T22:11:03.309265+00:00
| 2020-10-28T23:38:50 |
7d73fdb7cea7bfd8014637927f56f0c4933e0e98
|
{
"blob_id": "7d73fdb7cea7bfd8014637927f56f0c4933e0e98",
"branch_name": "refs/heads/main",
"committer_date": "2020-10-28T23:38:50",
"content_id": "bb16ffc3d0529413388292ffe5eb503f32714bf5",
"detected_licenses": [
"MIT"
],
"directory_id": "a300beb1274418ac741d9e59f870dc01c6ae8726",
"extension": "h",
"filename": "cmem.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": 1260,
"license": "MIT",
"license_type": "permissive",
"path": "/src/cmem.h",
"provenance": "stackv2-0072.json.gz:38303",
"repo_name": "stensalweb/Cosmo",
"revision_date": "2020-10-28T23:38:50",
"revision_id": "a15c8d67a12b94bc1bb15c30ce0e94e17247ff2d",
"snapshot_id": "505729bf702e28423aba9a316e900e1bbc0b7293",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/stensalweb/Cosmo/a15c8d67a12b94bc1bb15c30ce0e94e17247ff2d/src/cmem.h",
"visit_date": "2023-01-04T15:42:29.247104"
}
|
stackv2
|
#ifndef CMEME_C
#define CMEME_C // meme lol
#include "cosmo.h"
#include "cstate.h"
//#define GC_STRESS
//#define GC_DEBUG
// arrays will grow by a factor of 2
#define GROW_FACTOR 2
#define HEAP_GROW_FACTOR 2
#define ARRAY_START 8
#define cosmoM_freearray(state, type, buf, capacity) \
cosmoM_reallocate(state, buf, sizeof(type) *capacity, 0)
#define cosmoM_growarray(state, type, buf, count, capacity) \
if (count >= capacity || buf == NULL) { \
int old = capacity; \
capacity = old *GROW_FACTOR; \
buf = (type*)cosmoM_reallocate(state, buf, sizeof(type) *old, sizeof(type) *capacity); \
}
#define cosmoM_free(state, type, x) \
cosmoM_reallocate(state, x, sizeof(type), 0)
#define cosmoM_isFrozen(state) \
state->freezeGC > 0
#define cosmoM_freezeGC(state) \
state->freezeGC++
#define cosmoM_unfreezeGC(state) \
state->freezeGC--
COSMO_API void *cosmoM_reallocate(CState* state, void *buf, size_t oldSize, size_t newSize);
COSMO_API void cosmoM_collectGarbage(CState* state);
/*
wrapper for cosmoM_reallocate so we can track our memory usage (it's also safer :P)
*/
static inline void *cosmoM_xmalloc(CState *state, size_t sz) {
return cosmoM_reallocate(state, NULL, 0, sz);
}
#endif
| 2.265625 | 2 |
2024-11-18T22:11:03.927152+00:00
| 2020-10-31T20:14:35 |
04dcc5630d8579290781109970c44685e18e587a
|
{
"blob_id": "04dcc5630d8579290781109970c44685e18e587a",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-31T20:14:35",
"content_id": "a87b7fc07fdd9b5e21b627c4eb5ca37ef688b5e1",
"detected_licenses": [
"MIT"
],
"directory_id": "6683de5f08abb3d10a07ee121219ecc93466136e",
"extension": "c",
"filename": "inputParser.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 308958681,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15075,
"license": "MIT",
"license_type": "permissive",
"path": "/src/inputParser.c",
"provenance": "stackv2-0072.json.gz:38815",
"repo_name": "smichniak/gamma",
"revision_date": "2020-10-31T20:14:35",
"revision_id": "b2e87a22fca5495ef0a3a068fcfb7916c03268c6",
"snapshot_id": "6c4fb515588e7cd376c4c4a66b782d715e1b9355",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/smichniak/gamma/b2e87a22fca5495ef0a3a068fcfb7916c03268c6/src/inputParser.c",
"visit_date": "2023-02-08T07:20:42.720613"
}
|
stackv2
|
/** @file
* Implementacja modułu inputParser.h
*
* @author Szymon Michniak <s.michniak@student.uw.edu.pl>
* @date 17.05.2020
*/
#include <inttypes.h>
#include <sys/ioctl.h>
#include "display.h"
#include "inputParser.h"
/** Białe znaki, które oddzialają parametry funckji.
*/
static const char WHITE_CHARS[] = " \t\v\f\r";
/** Ciąg znaków, które oznaczją poprawne funkcje i funkcję pustą.
*/
static const char VALID_FUNCTIONS[] = "BImgbfqp ";
/** Liczba wierszy, którą na ekranie zajmują informacje o graczu.
*/
static const int PLAYER_INFORMATION_HEIGHT = 6;
/**
* @struct result_t
* Struktura przechowująca informacje o wyniku funkcji, która zwraca @p uint64_t.
*/
typedef struct {
uint64_t result_value; ///< Wartość, którą funckja zwróciła
bool valid; ///< @p false, jeśli wywołanie funckji było nieprawidłowe, @p true w przeciwnym przypadku
} result_t;
/** @brief Sprawdza, czy ciąg znaków oznacza poprawną funckję.
* Sprawdza, czy ciąg znaków jest poprwaną funckją gry @p gamma. Funkcja musi być jednoznakowa, i znak
* ten musi być jednym z ustalonych w @p VALID_FUNCTIONS.
* @param[in] function – ciąg znaków do sprawdzenia.
* @return @p true, jeśli funckja jest prawidłowa, @p false w przeciwnym przypadku
*/
static bool valid_function(char* function) {
if (strlen(function) > 1) {
return false;
}
for (uint32_t i = 0; i < strlen(VALID_FUNCTIONS); ++i) {
if (VALID_FUNCTIONS[i] == function[0]) {
return true;
}
}
return false;
}
/** @brief Sprawdza, czy ciąg znaków oznacza poprawnym argumentem funkcji.
* Sprawdza, czy ciąg znaków jest argumentem funkcji gry @p gamma. Argument musi zawierać jednynie
* cryfry i dać się poprawnie skonwertować na typ @p uint32_t. Jeśli @p string jest równy @p NULL,
* to argument jest pusty.
* @param[in] string – ciąg znaków do sprawdzenia.
* @return Struktura opisująca argument funkcji.
*/
static argument_t valid_argument(char* string) {
argument_t argument;
argument.value = 0;
argument.valid = true;
argument.empty = false;
if (string == NULL) {
argument.empty = true;
} else if (!only_digits(string)) {
// Argument może zawierać tylko cyfry, żeby był poprawny
argument.valid = false;
} else {
uint64_t conversion = strtoul(string, NULL, 10);
if (conversion > UINT32_MAX) {
// Wynik większy od UINT32_MAX nie jest poprawny
argument.valid = false;
} else {
argument.value = conversion;
}
}
return argument;
}
/** @brief Wskazuje następnego gracza, który może wykonać ruch.
* Sprawdza kolejych gracz po @p current_player. Zwraca następnego, który może wykonać ruch. Jeśli
* liczba pominiętych graczy jest większa, niż liczba wszystkich graczy, to nikt nie może już wykonać
* ruchu.
* @param[in] g – wskaźnik na strukturę przechowującą stan gry,
* @param[in] current_player – numer gracza, którego tura się skończyła, liczba dodatnia niewiększa od wartości
* @p players z funkcji @ref gamma_new,
* @param[in] players_skipped – liczba pominiętych graczy, przy pierwszym wywołaniu zawsze wynosi 0
* @return Numer następnego gracza, który może wykonać ruch, lub @p 0 jeśli żaden gracz nie może już
* wykonać ruchu.
*/
static uint32_t get_next_player(gamma_t* g, uint32_t current_player, uint64_t players_skipped) {
// Jeśli sprawdziliśmy wszytskich graczy i żaden nie może wykonać ruchu, to zwracamy 0
if (players_skipped > get_players(g)) {
return 0;
}
uint32_t max_player = get_players(g);
// Po ostatnim graczu wracamy do nr 1
uint32_t next_player = (current_player % max_player) + 1;
// Jeśli aktualny gracz nie może wykonać ruchu, sprawdzamy następnego
if (gamma_free_fields(g, next_player) == 0 && !gamma_golden_possible(g, next_player)) {
return get_next_player(g, next_player, players_skipped + 1);
}
return next_player;
}
/** @brief Wykonuje akcje po naciśnięciu strzałki w trybie interaktywnym.
* Sprawdza, czy w trybie interaktywnym została wciśnięta strzałka, jeśli tak,
* to przesuwa kursor odpowiednio.
* @param[in, out] cursor_x_ptr – wskaźnik na współrzędną @p x kursora,
* @param[in, out] cursor_y_ptr – wskaźnik na współrzędną @p y kursora,
* @param[in] max_x – maksymalna współrzędna @p x,
* @param[in] max_y – maksymalna współrzędna @p y,
* @param[in, out] input_char_ptr – wskaźnik na znak z wejścia, który ma być zinterpretowany.
*/
static void parse_arrows(uint32_t* cursor_x_ptr, uint32_t* cursor_y_ptr, uint32_t max_x, uint32_t max_y, int* input_char_ptr) {
*input_char_ptr = getchar();
if (*input_char_ptr == '[') {
*input_char_ptr = getchar();
if (*input_char_ptr == 'A') { // Strzałak w górę
if (*cursor_y_ptr != max_y) {
(*cursor_y_ptr)++;
}
*input_char_ptr = 0;
} else if (*input_char_ptr == 'B') { // Strzałka w dół
if (*cursor_y_ptr != 0) {
(*cursor_y_ptr)--;
}
*input_char_ptr = 0;
} else if (*input_char_ptr == 'C') { // Strzałka w prawo
if (*cursor_x_ptr != max_x) {
(*cursor_x_ptr)++;
}
*input_char_ptr = 0;
} else if (*input_char_ptr == 'D') { // Strzałka w lewo
if (*cursor_x_ptr != 0) {
(*cursor_x_ptr)--;
}
*input_char_ptr = 0;
}
}
}
/** @brief Interpretuje wejście trybu interaktywnego.
* Ustawia tryb wejścia na "raw", zaczyna od gracza nr 1 i ustawia wskaźnik na pole (0, 0). Wywołuje
* funkcje w zależności od wejścia zgodnie ze specyfikacją gry gamma. Przerywa po wykryciu na wejściu
* znaku o kodzie 4 (ctrl + D) lub gdy żaden gracz nie może wykonać ruchu. Wypisuje podsumowanie gry i
* przywraca oryginalne ustawienia terminala.
* @param[in,out] g – wskaźnik na strukturę przechowującą stan gry.
*/
static void interactive_input(gamma_t* g) {
uint32_t cursor_x = 0;
uint32_t cursor_y = 0;
uint32_t max_x = get_width(g) - 1;
uint32_t max_y = get_height(g) - 1;
uint32_t current_player = 1;
bool next_player;
int input_character = 0;
change_terminal_to_raw();
while (current_player != 0) {
next_player = false;
clear();
print_with_highlight(g, cursor_x, cursor_y, 0, current_player);
print_player_info(g, current_player);
// input_character == 0 wtedy, gdy poprzedni wczytany znak został już zinterpretowany
if (input_character == 0) {
input_character = getchar();
}
if (input_character == '\033') { // Początek kodu strzałek
parse_arrows(&cursor_x, &cursor_y, max_x, max_y, &input_character);
} else if (input_character == ' ') {
next_player = gamma_move(g, current_player, cursor_x, cursor_y);
input_character = 0;
} else if (input_character == 'g' || input_character == 'G') {
next_player = gamma_golden_move(g, current_player, cursor_x, cursor_y);
input_character = 0;
} else if (input_character == 'c' || input_character == 'C') {
input_character = 0;
next_player = true;
} else if (input_character == 4) { // Koniec transmisji, gracz = 0 kończy tryb interaktywny
current_player = 0;
} else { // Znak, który nie odpowiada żadnaje komendzie
input_character = 0;
}
if (next_player) {
current_player = get_next_player(g, current_player, 0);
}
}
// Na koniec gry wypisujemy planszę i podsumowanie wyników
clear();
print_with_highlight(g, 0, 0, 0, current_player);
print_results(g);
exit_interactive(0);
}
/** @brief Zwraca domyślną komendę.
* Zwraca strukturę domyślnej komendy. Jest ona poprawna, ma puste argumenty i nie powoduje żadnego działania.
* @return Struktura opisująca domyślną komendę.
*/
static command_t def_command() {
command_t command;
command.function = ' ';
command.is_valid = true;
command.first_argument = valid_argument("");
command.second_argument = valid_argument("");
command.third_argument = valid_argument("");
command.fourth_argument = valid_argument("");
return command;
}
command_t get_command(char* line) {
command_t command = def_command();
// Pomijamy linie puste i zaczynajace się od #
if (line != NULL && line[0] != '#' && line[0] != '\n') {
if (strlen(line) == 0 || isspace(line[0]) || line[strlen(line) - 1] != '\n') {
// Błędne są linie nie kończące się znakiem nowej linii i rozpoczynające się białym znakiem
command.is_valid = false;
} else {
// Usuwamy '\n' z końca linii
line[strlen(line) - 1] = 0;
// Rozdzielamy części miedzy białymi znakami
char* function = strtok(line, WHITE_CHARS);
char* first_arg = strtok(NULL, WHITE_CHARS);
argument_t first_argument = valid_argument(first_arg);
char* second_arg = strtok(NULL, WHITE_CHARS);
argument_t second_argument = valid_argument(second_arg);
char* third_arg = strtok(NULL, WHITE_CHARS);
argument_t third_argument = valid_argument(third_arg);
char* fourth_arg = strtok(NULL, WHITE_CHARS);
argument_t fourth_argument = valid_argument(fourth_arg);
char* rest_of_line = strtok(NULL, WHITE_CHARS);
if (function != NULL) {
if (rest_of_line != NULL || !valid_function(function) || !first_argument.valid ||
!second_argument.valid || !third_argument.valid || !fourth_argument.valid) {
// Prawidłowa linia nie może mieć więcej niż 4 argumenty i każdy musi być poprawny
command.is_valid = false;
} else {
command.function = function[0];
command.first_argument = first_argument;
command.second_argument = second_argument;
command.third_argument = third_argument;
command.fourth_argument = fourth_argument;
}
}
}
}
return command;
}
/** @brief Wywołuje daną komendę w grze danej wskaźnikiem.
* Wywołuje jedną z funkcji {@p m, @p g, @p b, @p f, @p q} i wynik wywołania zapisuje w strukturze, która
* jest zwracana.
* @param[in,out] g_ptr – wskaźnik na wskaźnik na strukturę przechowującą stan gry,
* @param[in] command – struktura opisująca komendę do wywoałnia.
* @return Struktura opisująca wynik wywołania. Parametr poprawności ustawiony na @p true, jeśli udało się
* wyowałać funkcję, @p false w przeciwnym przypadku.
*/
static result_t function_result(gamma_t** g_ptr, command_t command) {
result_t result;
result.valid = true;
if (!command.fourth_argument.empty || !*g_ptr) {
result.valid = false;
} else if (command.function == 'm') { // Zwykly ruch, trzy argumenty
if (command.third_argument.empty) {
result.valid = false;
} else {
result.result_value = gamma_move(*g_ptr, command.first_argument.value, command.second_argument.value,
command.third_argument.value);
}
} else if (command.function == 'g') { // Złoty ruch, trzy argumenty
if (command.third_argument.empty) {
result.valid = false;
} else {
result.result_value = gamma_golden_move(*g_ptr, command.first_argument.value,
command.second_argument.value, command.third_argument.value);
}
} else if (!command.second_argument.empty || command.first_argument.empty) {
result.valid = false;
} else if (command.function == 'b') { // Zajęte pola, jeden argument
result.result_value = gamma_busy_fields(*g_ptr, command.first_argument.value);
} else if (command.function == 'f') { // Wolne pola, jeden argument
result.result_value = gamma_free_fields(*g_ptr, command.first_argument.value);
} else if (command.function == 'q') { // Czy możliwy złoty ruch, jeden argument
result.result_value = gamma_golden_possible(*g_ptr, command.first_argument.value);
}
return result;
}
/** @brief Sprawdza, czy plansza zmieści się na ekranie.
* Sprawdza rozmiary terminala i porównuje je z rozmiarami planszy. Jeśli plansza
* jest zbyt duża, to wypisuje stosowny komunikat
* o błędzie i kończy program z kodem wyjścia @p 1.
* @param[in,out] g – wskaźnik na strukturę przechowującą stan gry.
*/
static void check_terminal_size(gamma_t* g) {
struct winsize window;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &window) == -1) {
exit(1);
}
uint32_t rows = window.ws_row;
uint32_t columns = window.ws_col;
if (get_height(g) + PLAYER_INFORMATION_HEIGHT > rows || get_width(g) > columns) {
fprintf(stderr, "Terminal to small to display the board.\n");
exit(1);
}
}
void execute_command(command_t command, gamma_t** g_ptr, unsigned long long line) {
if (!command.is_valid) {
print_error(line);
} else if (command.function == ' ') { // Pusta komenda, nic nie robi
} else if (command.function == 'B' || command.function == 'I') {
if (*g_ptr) { // Nie możemy zacząć nowej gry, jeśli już jakaś trwa
print_error(line);
} else {
gamma_t* new_gamma = gamma_new(command.first_argument.value, command.second_argument.value,
command.third_argument.value, command.fourth_argument.value);
if (!new_gamma) { // Błędne argumenty lub problemy z alokacją nowej gry
print_error(line);
} else if (command.function == 'B') {
*g_ptr = new_gamma;
printf("OK %llu\n", line);
} else {
*g_ptr = new_gamma;
check_terminal_size(new_gamma);
interactive_input(new_gamma);
}
}
} else if (command.function == 'p') { // Ciąg znaków opisujący planszę, zero argumentów
if (!command.first_argument.empty) {
print_error(line);
} else {
// current_player = 0 oznaczaja string planszy bez podświetlonych pól
print_with_highlight(*g_ptr, 0, 0, line, 0);
}
} else {
result_t result = function_result(g_ptr, command);
if (!result.valid) {
print_error(line);
} else {
printf("%" PRIu64 "\n", result.result_value);
}
}
}
| 2.96875 | 3 |
2024-11-18T22:11:04.651407+00:00
| 2018-07-25T21:54:01 |
3d9bbbc7b5992c5b88466db2acd2a78788de8aa2
|
{
"blob_id": "3d9bbbc7b5992c5b88466db2acd2a78788de8aa2",
"branch_name": "refs/heads/devel",
"committer_date": "2018-07-25T21:54:01",
"content_id": "3c29f952ecf4bb6d79658d4b427fb361672439f7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "67f62674ad3aa8950e990001deed2e17007744f6",
"extension": "c",
"filename": "BThreadWork.c",
"fork_events_count": 1,
"gha_created_at": "2018-10-12T09:42:59",
"gha_event_created_at": "2020-09-02T04:15:20",
"gha_language": "Go",
"gha_license_id": "Apache-2.0",
"github_id": 152728994,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13608,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/github.com/getlantern/lantern-mobile/external/badvpn/threadwork/BThreadWork.c",
"provenance": "stackv2-0072.json.gz:39459",
"repo_name": "Ethan561/lantern",
"revision_date": "2018-07-25T21:54:01",
"revision_id": "f6a98cf108830b0f6a7743d4ba2fe5a2183a311c",
"snapshot_id": "da50b8089b87cf6bb86debb0785c5a884b85d0b7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Ethan561/lantern/f6a98cf108830b0f6a7743d4ba2fe5a2183a311c/src/github.com/getlantern/lantern-mobile/external/badvpn/threadwork/BThreadWork.c",
"visit_date": "2021-07-01T12:42:55.135742"
}
|
stackv2
|
/**
* @file BThreadWork.c
* @author Ambroz Bizjak <ambrop7@gmail.com>
*
* @section LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the author nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#include <stddef.h>
#ifdef BADVPN_THREADWORK_USE_PTHREAD
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#endif
#include <misc/offset.h>
#include <base/BLog.h>
#include <generated/blog_channel_BThreadWork.h>
#include <threadwork/BThreadWork.h>
#ifdef BADVPN_THREADWORK_USE_PTHREAD
static void * dispatcher_thread (struct BThreadWorkDispatcher_thread *t)
{
BThreadWorkDispatcher *o = t->d;
ASSERT_FORCE(pthread_mutex_lock(&o->mutex) == 0)
while (1) {
// exit if requested
if (o->cancel) {
break;
}
if (LinkedList1_IsEmpty(&o->pending_list)) {
// wait for event
ASSERT_FORCE(pthread_cond_wait(&t->new_cond, &o->mutex) == 0)
continue;
}
// grab the work
BThreadWork *w = UPPER_OBJECT(LinkedList1_GetFirst(&o->pending_list), BThreadWork, list_node);
ASSERT(w->state == BTHREADWORK_STATE_PENDING)
LinkedList1_Remove(&o->pending_list, &w->list_node);
t->running_work = w;
w->state = BTHREADWORK_STATE_RUNNING;
// do the work
ASSERT_FORCE(pthread_mutex_unlock(&o->mutex) == 0)
w->work_func(w->work_func_user);
ASSERT_FORCE(pthread_mutex_lock(&o->mutex) == 0)
// release the work
t->running_work = NULL;
LinkedList1_Append(&o->finished_list, &w->list_node);
w->state = BTHREADWORK_STATE_FINISHED;
ASSERT_FORCE(sem_post(&w->finished_sem) == 0)
// write to pipe
uint8_t b = 0;
int res = write(o->pipe[1], &b, sizeof(b));
if (res < 0) {
int error = errno;
ASSERT_FORCE(error == EAGAIN || error == EWOULDBLOCK)
}
}
ASSERT_FORCE(pthread_mutex_unlock(&o->mutex) == 0)
return NULL;
}
static void dispatch_job (BThreadWorkDispatcher *o)
{
ASSERT(o->num_threads > 0)
// lock
ASSERT_FORCE(pthread_mutex_lock(&o->mutex) == 0)
// check for finished job
if (LinkedList1_IsEmpty(&o->finished_list)) {
ASSERT_FORCE(pthread_mutex_unlock(&o->mutex) == 0)
return;
}
// grab finished job
BThreadWork *w = UPPER_OBJECT(LinkedList1_GetFirst(&o->finished_list), BThreadWork, list_node);
ASSERT(w->state == BTHREADWORK_STATE_FINISHED)
LinkedList1_Remove(&o->finished_list, &w->list_node);
// schedule more
if (!LinkedList1_IsEmpty(&o->finished_list)) {
BPending_Set(&o->more_job);
}
// set state forgotten
w->state = BTHREADWORK_STATE_FORGOTTEN;
// unlock
ASSERT_FORCE(pthread_mutex_unlock(&o->mutex) == 0)
// call handler
w->handler_done(w->user);
return;
}
static void pipe_fd_handler (BThreadWorkDispatcher *o, int events)
{
ASSERT(o->num_threads > 0)
DebugObject_Access(&o->d_obj);
// read data from pipe
uint8_t b[64];
int res = read(o->pipe[0], b, sizeof(b));
if (res < 0) {
int error = errno;
ASSERT_FORCE(error == EAGAIN || error == EWOULDBLOCK)
} else {
ASSERT(res > 0)
}
dispatch_job(o);
return;
}
static void more_job_handler (BThreadWorkDispatcher *o)
{
ASSERT(o->num_threads > 0)
DebugObject_Access(&o->d_obj);
dispatch_job(o);
return;
}
static void stop_threads (BThreadWorkDispatcher *o)
{
// set cancelling
ASSERT_FORCE(pthread_mutex_lock(&o->mutex) == 0)
o->cancel = 1;
ASSERT_FORCE(pthread_mutex_unlock(&o->mutex) == 0)
while (o->num_threads > 0) {
struct BThreadWorkDispatcher_thread *t = &o->threads[o->num_threads - 1];
// wake up thread
ASSERT_FORCE(pthread_cond_signal(&t->new_cond) == 0)
// wait for thread to exit
ASSERT_FORCE(pthread_join(t->thread, NULL) == 0)
// free condition variable
ASSERT_FORCE(pthread_cond_destroy(&t->new_cond) == 0)
o->num_threads--;
}
}
#endif
static void work_job_handler (BThreadWork *o)
{
#ifdef BADVPN_THREADWORK_USE_PTHREAD
ASSERT(o->d->num_threads == 0)
#endif
DebugObject_Access(&o->d_obj);
// do the work
o->work_func(o->work_func_user);
// call handler
o->handler_done(o->user);
return;
}
int BThreadWorkDispatcher_Init (BThreadWorkDispatcher *o, BReactor *reactor, int num_threads_hint)
{
// init arguments
o->reactor = reactor;
if (num_threads_hint < 0) {
num_threads_hint = 2;
}
if (num_threads_hint > BTHREADWORK_MAX_THREADS) {
num_threads_hint = BTHREADWORK_MAX_THREADS;
}
#ifdef BADVPN_THREADWORK_USE_PTHREAD
if (num_threads_hint > 0) {
// init pending list
LinkedList1_Init(&o->pending_list);
// init finished list
LinkedList1_Init(&o->finished_list);
// init mutex
if (pthread_mutex_init(&o->mutex, NULL) != 0) {
BLog(BLOG_ERROR, "pthread_mutex_init failed");
goto fail0;
}
// init pipe
if (pipe(o->pipe) < 0) {
BLog(BLOG_ERROR, "pipe failed");
goto fail1;
}
// set read end non-blocking
if (fcntl(o->pipe[0], F_SETFL, O_NONBLOCK) < 0) {
BLog(BLOG_ERROR, "fcntl failed");
goto fail2;
}
// set write end non-blocking
if (fcntl(o->pipe[1], F_SETFL, O_NONBLOCK) < 0) {
BLog(BLOG_ERROR, "fcntl failed");
goto fail2;
}
// init BFileDescriptor
BFileDescriptor_Init(&o->bfd, o->pipe[0], (BFileDescriptor_handler)pipe_fd_handler, o);
if (!BReactor_AddFileDescriptor(o->reactor, &o->bfd)) {
BLog(BLOG_ERROR, "BReactor_AddFileDescriptor failed");
goto fail2;
}
BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, BREACTOR_READ);
// init more job
BPending_Init(&o->more_job, BReactor_PendingGroup(o->reactor), (BPending_handler)more_job_handler, o);
// set not cancelling
o->cancel = 0;
// init threads
o->num_threads = 0;
for (int i = 0; i < num_threads_hint; i++) {
struct BThreadWorkDispatcher_thread *t = &o->threads[i];
// set parent pointer
t->d = o;
// set no running work
t->running_work = NULL;
// init condition variable
if (pthread_cond_init(&t->new_cond, NULL) != 0) {
BLog(BLOG_ERROR, "pthread_cond_init failed");
goto fail3;
}
// init thread
if (pthread_create(&t->thread, NULL, (void * (*) (void *))dispatcher_thread, t) != 0) {
BLog(BLOG_ERROR, "pthread_create failed");
ASSERT_FORCE(pthread_cond_destroy(&t->new_cond) == 0)
goto fail3;
}
o->num_threads++;
}
}
#endif
DebugObject_Init(&o->d_obj);
DebugCounter_Init(&o->d_ctr);
return 1;
#ifdef BADVPN_THREADWORK_USE_PTHREAD
fail3:
stop_threads(o);
BPending_Free(&o->more_job);
BReactor_RemoveFileDescriptor(o->reactor, &o->bfd);
fail2:
ASSERT_FORCE(close(o->pipe[0]) == 0)
ASSERT_FORCE(close(o->pipe[1]) == 0)
fail1:
ASSERT_FORCE(pthread_mutex_destroy(&o->mutex) == 0)
fail0:
return 0;
#endif
}
void BThreadWorkDispatcher_Free (BThreadWorkDispatcher *o)
{
#ifdef BADVPN_THREADWORK_USE_PTHREAD
if (o->num_threads > 0) {
ASSERT(LinkedList1_IsEmpty(&o->pending_list))
for (int i = 0; i < o->num_threads; i++) { ASSERT(!o->threads[i].running_work) }
ASSERT(LinkedList1_IsEmpty(&o->finished_list))
}
#endif
DebugObject_Free(&o->d_obj);
DebugCounter_Free(&o->d_ctr);
#ifdef BADVPN_THREADWORK_USE_PTHREAD
if (o->num_threads > 0) {
// stop threads
stop_threads(o);
// free more job
BPending_Free(&o->more_job);
// free BFileDescriptor
BReactor_RemoveFileDescriptor(o->reactor, &o->bfd);
// free pipe
ASSERT_FORCE(close(o->pipe[0]) == 0)
ASSERT_FORCE(close(o->pipe[1]) == 0)
// free mutex
ASSERT_FORCE(pthread_mutex_destroy(&o->mutex) == 0)
}
#endif
}
int BThreadWorkDispatcher_UsingThreads (BThreadWorkDispatcher *o)
{
#ifdef BADVPN_THREADWORK_USE_PTHREAD
return (o->num_threads > 0);
#else
return 0;
#endif
}
void BThreadWork_Init (BThreadWork *o, BThreadWorkDispatcher *d, BThreadWork_handler_done handler_done, void *user, BThreadWork_work_func work_func, void *work_func_user)
{
DebugObject_Access(&d->d_obj);
// init arguments
o->d = d;
o->handler_done = handler_done;
o->user = user;
o->work_func = work_func;
o->work_func_user = work_func_user;
#ifdef BADVPN_THREADWORK_USE_PTHREAD
if (d->num_threads > 0) {
// set state
o->state = BTHREADWORK_STATE_PENDING;
// init finished semaphore
ASSERT_FORCE(sem_init(&o->finished_sem, 0, 0) == 0)
// post work
ASSERT_FORCE(pthread_mutex_lock(&d->mutex) == 0)
LinkedList1_Append(&d->pending_list, &o->list_node);
for (int i = 0; i < d->num_threads; i++) {
if (!d->threads[i].running_work) {
ASSERT_FORCE(pthread_cond_signal(&d->threads[i].new_cond) == 0)
break;
}
}
ASSERT_FORCE(pthread_mutex_unlock(&d->mutex) == 0)
} else {
#endif
// schedule job
BPending_Init(&o->job, BReactor_PendingGroup(d->reactor), (BPending_handler)work_job_handler, o);
BPending_Set(&o->job);
#ifdef BADVPN_THREADWORK_USE_PTHREAD
}
#endif
DebugObject_Init(&o->d_obj);
DebugCounter_Increment(&d->d_ctr);
}
void BThreadWork_Free (BThreadWork *o)
{
BThreadWorkDispatcher *d = o->d;
DebugObject_Free(&o->d_obj);
DebugCounter_Decrement(&d->d_ctr);
#ifdef BADVPN_THREADWORK_USE_PTHREAD
if (d->num_threads > 0) {
ASSERT_FORCE(pthread_mutex_lock(&d->mutex) == 0)
switch (o->state) {
case BTHREADWORK_STATE_PENDING: {
BLog(BLOG_DEBUG, "remove pending work");
// remove from pending list
LinkedList1_Remove(&d->pending_list, &o->list_node);
} break;
case BTHREADWORK_STATE_RUNNING: {
BLog(BLOG_DEBUG, "remove running work");
// wait for the work to finish running
ASSERT_FORCE(pthread_mutex_unlock(&d->mutex) == 0)
ASSERT_FORCE(sem_wait(&o->finished_sem) == 0)
ASSERT_FORCE(pthread_mutex_lock(&d->mutex) == 0)
ASSERT(o->state == BTHREADWORK_STATE_FINISHED)
// remove from finished list
LinkedList1_Remove(&d->finished_list, &o->list_node);
} break;
case BTHREADWORK_STATE_FINISHED: {
BLog(BLOG_DEBUG, "remove finished work");
// remove from finished list
LinkedList1_Remove(&d->finished_list, &o->list_node);
} break;
case BTHREADWORK_STATE_FORGOTTEN: {
BLog(BLOG_DEBUG, "remove forgotten work");
} break;
default:
ASSERT(0);
}
ASSERT_FORCE(pthread_mutex_unlock(&d->mutex) == 0)
// free finished semaphore
ASSERT_FORCE(sem_destroy(&o->finished_sem) == 0)
} else {
#endif
BPending_Free(&o->job);
#ifdef BADVPN_THREADWORK_USE_PTHREAD
}
#endif
}
| 2.0625 | 2 |
2024-11-18T22:11:04.917881+00:00
| 2018-09-12T01:12:20 |
97279a2f570c9faaef5def73510467e5dc9c974d
|
{
"blob_id": "97279a2f570c9faaef5def73510467e5dc9c974d",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-12T01:12:20",
"content_id": "d1363d9715d0846126122eb7880c8f14cbeb5099",
"detected_licenses": [
"MIT"
],
"directory_id": "0b9c1df516012cee1cee852d3cc62f9f79b664d0",
"extension": "h",
"filename": "config.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 120667683,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1449,
"license": "MIT",
"license_type": "permissive",
"path": "/src/config.h",
"provenance": "stackv2-0072.json.gz:39716",
"repo_name": "97xuzy/http_server",
"revision_date": "2018-09-12T01:12:20",
"revision_id": "5dbf15f5788dfecbcb1a0f519fce095cfb58ec4b",
"snapshot_id": "bcb8da09effeb3e38e751dc90ad562863ece3dba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/97xuzy/http_server/5dbf15f5788dfecbcb1a0f519fce095cfb58ec4b/src/config.h",
"visit_date": "2018-12-09T16:36:44.610308"
}
|
stackv2
|
/*!
Server will not start if configuration file is not found (even a empty one will do).
Main process is responsible for create a global configuration that is stored
in shared meory, each worker process have its own copy of configuration when
spawned (hence copy the global config to local), thus the configuration can
be changed on the fly by respawn worker process.
Global configuration and the shared memory it resides in need to be re-create
every time a new configuration is loaded.
When parsing configuration file, if a config item is not present in the file,
a built-in default value will be used.
*/
#ifndef CONFIG_H
#define CONFIG_H
#include <stdlib.h>
#include <stdbool.h>
#define DEFAULT_CONFIG_FILE_PATH "/var/http_server/config/http_server.conf"
typedef struct config
{
/*!
web_root_path: XXXX
*/
char *web_root_path;
bool logging;
char *log_path;
int log_level;
char *error_page_path;
int worker_num;
} config_t;
config_t* create_global_config(config_t *local);
config_t* copy_global_config_to_local(config_t *global);
int destroy_global_config(config_t *global);
size_t config_size(config_t *config);
/*!
Read configuration file from the given path,
parse the file, and store the configuration in
the config_t struct
*/
int read_config(const char *path, config_t *config);
#endif
| 2.65625 | 3 |
2024-11-18T22:11:05.109006+00:00
| 2018-12-10T19:51:23 |
699ecb08fd922b64f6d840a3f79865abf9c462fd
|
{
"blob_id": "699ecb08fd922b64f6d840a3f79865abf9c462fd",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-10T19:51:23",
"content_id": "9705ef654b4abff1d622c64b5afaf36269ccfb60",
"detected_licenses": [
"MIT"
],
"directory_id": "3a3fd78af4df234666178fca50e650abfd7c9fbb",
"extension": "c",
"filename": "event_loop.c",
"fork_events_count": 5,
"gha_created_at": "2018-05-01T07:44:10",
"gha_event_created_at": "2021-11-16T06:55:55",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 131688423,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7943,
"license": "MIT",
"license_type": "permissive",
"path": "/src/event_loop.c",
"provenance": "stackv2-0072.json.gz:39845",
"repo_name": "parro-it/libui-napi",
"revision_date": "2018-12-10T19:51:23",
"revision_id": "5e32314516a163bc91da36cb709382cbc656e56f",
"snapshot_id": "1589aecdff9351ae6faee36bf3dab3271e71b924",
"src_encoding": "UTF-8",
"star_events_count": 38,
"url": "https://raw.githubusercontent.com/parro-it/libui-napi/5e32314516a163bc91da36cb709382cbc656e56f/src/event_loop.c",
"visit_date": "2021-11-29T12:46:10.622745"
}
|
stackv2
|
#include <assert.h>
#include <stdbool.h>
#include "napi_utils.h"
#include "app.h"
#include "event-loop.h"
static const char *MODULE = "EventLoop";
static uv_barrier_t all_threads_are_waiting;
static uv_barrier_t all_threads_are_awaked;
static napi_ref event_loop_closed_cb_ref = NULL;
static napi_ref event_loop_started_cb_ref = NULL;
static napi_env resolution_env = NULL;
static uv_async_t *keep_alive;
static uv_thread_t thread;
static uv_timer_t main_thread_timer;
/*
wait for pending events
*/
void wait_node_io(int timeout) {
int ret;
LIBUI_NODE_DEBUG_F("--- entering wait with timeout %d", timeout);
do {
ret = waitForNodeEvents(uv_default_loop(), timeout);
} while (ret == -1 && errno == EINTR);
LIBUI_NODE_DEBUG("--- wait done");
}
/*
This function is executed in the
background thread and is responsible for continuosly polling
the node backend for pending events.
When pending node events are found, the main GUI
thread, if it's waiting, is wake up by calling uiLoopWakeup().
*/
static void background_thread(void *arg) {
LIBUI_NODE_DEBUG("--- start background_thread ");
while (!ln_get_main_thread_quitted()) {
LIBUI_NODE_DEBUG("--- wait on all_threads_are_waiting.");
ln_set_background_thread_waiting(true);
// wait for the main thread
// to be blocked waiting for GUI events
uv_barrier_wait(&all_threads_are_waiting);
LIBUI_NODE_DEBUG("--- all_threads_are_waiting passed.");
int timeout = uv_backend_timeout(uv_default_loop());
LIBUI_NODE_DEBUG_F("--- uv_backend_timeout == %d", timeout);
// if timeout == 0, it means there are
// already some callback to execute, so no
// IO wait is necessary.
// If timeout == -1, it means to wait forever.
// When timeout > 0. it means there are one or more timers
// pending, and the first one will expire in
// `timeout` ms
if (timeout != 0) {
LIBUI_NODE_DEBUG("--- wait node io");
wait_node_io(timeout);
LIBUI_NODE_DEBUG("--- done wait node io");
if (ln_get_main_thread_waiting()) {
LIBUI_NODE_DEBUG("--- wake up main thread");
ln_set_background_thread_waiting(false);
uiLoopWakeup();
}
} else {
ln_set_background_thread_waiting(false);
}
// wait for the main thread
// to be unblocked.
uv_barrier_wait(&all_threads_are_awaked);
}
LIBUI_NODE_DEBUG("--- background terminating.");
}
/*
This function run all pending native GUI event in the loop
using libui calls.
It first do a blocking call to uiMainStep that
wait for pending GUI events. This blocking call also exit
when there are pending node events, because uiLoopWakeup
function posts a GUI event
from the background thread for this purpose.
*/
static void main_thread(uv_timer_t *handle) {
enum ln_loop_status status = ln_get_loop_status();
LIBUI_NODE_DEBUG_F("+++ start main_thread with status %d", status);
uv_timer_stop(handle);
if (status == starting) {
assert(event_loop_started_cb_ref != NULL);
LIBUI_NODE_DEBUG("🧐 LOOP STARTED");
napi_ref ref = event_loop_started_cb_ref;
event_loop_started_cb_ref = NULL;
resolve_promise_null(resolution_env, ref, started);
}
LIBUI_NODE_DEBUG("+++ wait on all_threads_are_waiting");
// wait for the background thread
// to be blocked waiting for node events
uv_barrier_wait(&all_threads_are_waiting);
LIBUI_NODE_DEBUG("+++ passed all_threads_are_waiting");
int timeout = uv_backend_timeout(uv_default_loop());
int gui_running = 1;
if (timeout != 0) {
LIBUI_NODE_DEBUG("+++ wait GUI events");
ln_set_main_thread_waiting(true);
LIBUI_NODE_DEBUG("+++ ln_set_main_thread_waiting true");
gui_running = uiMainStep(true);
LIBUI_NODE_DEBUG("+++ uiWaitForEvents done");
ln_set_main_thread_waiting(false);
LIBUI_NODE_DEBUG("+++ ln_set_main_thread_waiting false");
}
if (ln_get_background_thread_waiting()) {
LIBUI_NODE_DEBUG("+++ wake up background thread");
uv_async_send(keep_alive);
}
/* dequeue and run every event pending */
while (gui_running && uiEventsPending()) {
gui_running = uiMainStep(false);
}
LIBUI_NODE_DEBUG("+++ all GUI events worked.");
if (!gui_running && ln_get_loop_status() == stopping) {
ln_set_main_thread_quitted(true);
}
// wait for the background thread
// to be unblocked from waiting for node events
LIBUI_NODE_DEBUG("+++ wait all_threads_are_awaked");
uv_barrier_wait(&all_threads_are_awaked);
LIBUI_NODE_DEBUG("+++ passed all_threads_are_awaked");
LIBUI_NODE_DEBUG_F("+++ libui is running: %d", gui_running);
if (gui_running || ln_get_loop_status() != stopping) {
LIBUI_NODE_DEBUG("+++ schedule next main_thread call.");
uv_timer_start(&main_thread_timer, main_thread, 10, 0);
} else {
// uv_close((uv_handle_t *)&main_thread_timer, NULL);
LIBUI_NODE_DEBUG("+++ main_thread_timer closed");
/* await for the background thread to finish */
LIBUI_NODE_DEBUG("uv_thread_join wait");
uv_thread_join(&thread);
LIBUI_NODE_DEBUG("uv_thread_join done");
/* stop keep alive timer */
uv_close((uv_handle_t *)keep_alive, NULL);
LIBUI_NODE_DEBUG("uv_close keep_alive done");
assert(event_loop_closed_cb_ref != NULL);
LIBUI_NODE_DEBUG("🧐 LOOP STOPPED");
napi_ref ref = event_loop_closed_cb_ref;
event_loop_closed_cb_ref = NULL;
resolve_promise_null(resolution_env, ref, stopped);
LIBUI_NODE_DEBUG("resolved stop promise");
}
}
/* This function start the event loop and exit immediately */
LIBUI_FUNCTION(start) {
INIT_ARGS(1);
ARG_CB_REF(cb_ref, 0);
if (event_loop_closed_cb_ref != NULL) {
napi_throw_error(env, NULL, "Cannot start. A stop loop operation is pending.");
return NULL;
}
if (event_loop_started_cb_ref != NULL) {
napi_throw_error(env, NULL, "Cannot start. A start loop operation is pending.");
return NULL;
}
LIBUI_NODE_DEBUG("🧐 LOOP STARTING");
uv_barrier_init(&all_threads_are_waiting, 2);
uv_barrier_init(&all_threads_are_awaked, 2);
event_loop_started_cb_ref = cb_ref;
resolution_env = env;
ln_set_loop_status(starting);
ln_set_main_thread_waiting(false);
ln_set_background_thread_waiting(false);
ln_set_main_thread_quitted(false);
/* init libui event loop */
uiMainSteps();
LIBUI_NODE_DEBUG("libui loop initialized");
/* start the background thread that check for node evnts pending */
uv_thread_create(&thread, background_thread, NULL);
LIBUI_NODE_DEBUG("background thread started...");
// Add dummy handle for libuv, otherwise libuv would quit when there is
// nothing to do.
keep_alive = malloc(sizeof(uv_async_t));
uv_async_init(uv_default_loop(), keep_alive, NULL);
/* start main_thread timer */
uv_timer_init(uv_default_loop(), &main_thread_timer);
uv_timer_start(&main_thread_timer, main_thread, 1, 0);
LIBUI_NODE_DEBUG("startLoop async started");
return NULL;
}
LIBUI_FUNCTION(stop) {
INIT_ARGS(1);
ARG_CB_REF(cb_ref, 0);
LIBUI_NODE_DEBUG("🧐 LOOP STOPPING");
if (event_loop_closed_cb_ref != NULL) {
napi_throw_error(env, NULL, "Cannot start. A stop loop operation is pending.");
return NULL;
}
if (event_loop_started_cb_ref != NULL) {
napi_throw_error(env, NULL, "Cannot start. A start loop operation is pending.");
return NULL;
}
ln_set_loop_status(stopping);
event_loop_closed_cb_ref = cb_ref;
resolution_env = env;
destroy_all_children(env, visible_windows);
clear_children(env, visible_windows);
visible_windows = create_children_list();
LIBUI_NODE_DEBUG("visible windows cleaned up");
uiQuit();
LIBUI_NODE_DEBUG("uiQuit called");
return NULL;
}
// this function signal background thread
// to stop awaiting node events, allowing it
// to update the list of handles it's
// awaiting on.
LIBUI_FUNCTION(wakeupBackgroundThread) {
if (uv_is_active((const uv_handle_t *)keep_alive)) {
uv_async_send(keep_alive);
}
return NULL;
}
napi_value _libui_init_event_loop(napi_env env, napi_value exports) {
DEFINE_MODULE();
LIBUI_EXPORT(wakeupBackgroundThread);
LIBUI_EXPORT(start);
LIBUI_EXPORT(stop);
return module;
}
| 2.203125 | 2 |
2024-11-18T22:11:05.272108+00:00
| 2019-09-03T15:46:04 |
17207da963a3f9d1e7c08b0ae9883f5a0e6606af
|
{
"blob_id": "17207da963a3f9d1e7c08b0ae9883f5a0e6606af",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-03T15:46:04",
"content_id": "157251df0359694bfabd6e0154eef472ea6628bf",
"detected_licenses": [
"MIT"
],
"directory_id": "4208e9c909deefd4a9ce90484db052213887a4e8",
"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": 206112542,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 490,
"license": "MIT",
"license_type": "permissive",
"path": "/L02/L02Ex9/main.c",
"provenance": "stackv2-0072.json.gz:39973",
"repo_name": "ImGelu/c",
"revision_date": "2019-09-03T15:46:04",
"revision_id": "70d28a48f9bb105cd9ba90c2be34be8fb87abb4f",
"snapshot_id": "28fbe565a576443c14524bbc887b8d016eb53c2c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ImGelu/c/70d28a48f9bb105cd9ba90c2be34be8fb87abb4f/L02/L02Ex9/main.c",
"visit_date": "2020-07-17T22:25:30.033160"
}
|
stackv2
|
/// 3.9. Scrieţi un program care realizează suma, diferenţa, produsul şi împărţirea a două numere reale. Afişarea se va face sub formă tabelară.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, y;
printf("Introduceti x: ");
scanf("%d", &x);
printf("Introduceti y: ");
scanf("%d", &y);
printf("\t x \t y \t x+y \t x-y \t x*y \t x/y \n");
printf("\t %d \t %d \t %d \t %d \t %d \t %lf ", x, y, x+y, x-y, x*y, (float)x/y);
return 0;
}
| 3.625 | 4 |
2024-11-18T22:11:05.499640+00:00
| 2021-02-17T15:36:50 |
97b6f566aaac235416577ed2bdc6e80b9e719fbf
|
{
"blob_id": "97b6f566aaac235416577ed2bdc6e80b9e719fbf",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-17T15:36:50",
"content_id": "705aa50c0007f7acbb94a579569b43554cebff54",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e7cdbc34722df8ef42e2476851f01cfdc610e2b3",
"extension": "c",
"filename": "thread_pool_manage.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 338567009,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5101,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/thread_pool_manage.c",
"provenance": "stackv2-0072.json.gz:40359",
"repo_name": "SuperDan1/Concurrent-Queue-With-Thread-Pool",
"revision_date": "2021-02-17T15:36:50",
"revision_id": "e582db39871f7c92d4c3f7b691388793de0c3d1c",
"snapshot_id": "1cef9ed0b221059da8c0947d3336a2b199eb786d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/SuperDan1/Concurrent-Queue-With-Thread-Pool/e582db39871f7c92d4c3f7b691388793de0c3d1c/src/thread_pool_manage.c",
"visit_date": "2023-03-04T20:58:10.807284"
}
|
stackv2
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "thread_pool_manage.h"
#include "queue.h"
// 标记线程池是否处于可用状态
static int tp_alive = 1;
static ThreadPool pool;
typedef struct Threadworker
{
void *(*process)(void *arg); /*任务回调函数*/
void *arg; /*回调函数的参数*/
} Threadworker;
// tp->thread pool
int32_t TpJobQueueInit()
{
}
/*工作线程函数*/
void *thread_routine(void *arg)
{
ThreadPool *pool = (ThreadPool *)arg;
Threadworker *worker = NULL;
printf("starting thread 0x%lx\n", pthread_self());
while (1)
{
/*线程池要销毁了*/
if (pool->isShutDown)
{
printf("threadid:0x%lx exit.\n", pthread_self());
pthread_exit(NULL);
}
pthread_mutex_lock(&(pool->taskQueue->q_head_lock));
if (IsQueueEmpty(pool->taskQueue))
{
//printf("thread 0x%lx is waiting\n", pthread_self());
//sleep(1);
//pthread_cond_wait(&(pool->queue_ready), &(pool->taskQueue->q_head_lock));
pthread_mutex_unlock(&(pool->taskQueue->q_head_lock));
continue;
}
//printf("%d\n", pool->taskQueue->q_head->next);
popQueue(pool->taskQueue, (void **)&worker);
//printf("%d\n", pool->taskQueue->q_head->next);
pthread_mutex_unlock(&(pool->taskQueue->q_head_lock));
printf("thread 0x%lx is working\n", pthread_self());
(*(worker->process))(worker->arg);
free(worker);
worker = NULL;
printf("thread 0x%lx worked end\n", pthread_self());
}
}
int32_t TpInit(ThreadPool *pool, const uint32_t threadNum)
{
int32_t retVal;
pool->isShutDown = false;
pthread_mutex_init(&(pool->mutex), NULL);
pthread_cond_init(&(pool->queue_ready), NULL);
pool->threadNum = threadNum;
pool->threadIdArray = (pthread_t *)malloc(threadNum * sizeof(pthread_t));
if (unlikely(pool->threadIdArray == NULL))
{
printf("malloc threadIdArray memory failed.\n");
return RETURN_ERROR;
}
pool->taskQueue = (listQueue *)malloc(sizeof(listQueue));
if (unlikely(pool->taskQueue == NULL))
{
free(pool->threadIdArray);
printf("malloc taskQueue memory failed.\n");
return RETURN_ERROR;
}
retVal = initQueue(pool->taskQueue, sizeof(Threadworker));
if (unlikely(retVal != RETURN_OK))
{
printf("init listQueue failed!\n");
return RETURN_ERROR;
}
/*创建工作线程*/
int i = 0;
for (i = 0; i < threadNum; i++)
{
pthread_create(&(pool->threadIdArray[i]), NULL, thread_routine, pool);
}
}
int32_t pool_add_worker(ThreadPool *pool, void *(*process)(void *arg), void *arg)
{
int32_t retVal;
/*构造一个新任务*/
Threadworker *newworker = (Threadworker *)malloc(sizeof(Threadworker));
newworker->process = process;
newworker->arg = arg;
/*将任务加入到等待队列中*/
retVal = pushQueue(pool->taskQueue, newworker);
if (unlikely(retVal != RETURN_OK))
{
printf("add task queue task failed.");
return retVal;
}
// if (pool->taskQueue->size == 0)
// pthread_cond_signal(&(pool->queue_ready));
/*等待队列中有任务了,唤醒一个等待线程;
注意如果所有线程都在忙碌,这句没有任何作用*/
//pthread_cond_signal(&(pool->queue_ready));
return RETURN_OK;
}
void TpDestroy(ThreadPool *pool)
{
int i;
if (pool->isShutDown)
{
return;
//return RETURN_ERROR; /*防止两次调用*/
}
printf("pool destroy now\n");
pool->isShutDown = true;
pthread_cond_broadcast(&(pool->queue_ready));
for (i = 0; i < pool->threadNum; ++i)
{
pthread_join(pool->threadIdArray[i], NULL);
}
pthread_cond_destroy(&(pool->queue_ready));
free(pool->threadIdArray);
free(pool->taskQueue);
}
// //线程函数
// void *tp_thread_func(thread_pool *tp)
// {
// FUNC function;
// void *arg_buf;
// thread_pool_job *job_p;
// while (tp_alive)
// {
// // 线程阻塞,等待信号量
// if (sem_wait(tp->job_queue->quene_sem))
// {
// printf("thread waiting for semaphore....\n");
// exit(1);
// }
// if (tp_alive)
// {
// pthread_mutex_lock(&mutex);
// job_p = tp_get_lastjob(tp);
// if (NULL == job_p)
// {
// pthread_mutex_unlock(&mutex);
// continue;
// }
// function = job_p->function;
// arg_buf = job_p->arg;
// if (tp_delete__lastjob(tp))
// return;
// pthread_mutex_unlock(&mutex);
// //运行指定的线程函数
// printf("consumer...get a job from job quene and run it!\n");
// function(arg_buf);
// free(job_p);
// }
// else
// return;
// }
// return;
// }
| 2.859375 | 3 |
2024-11-18T22:11:06.619564+00:00
| 2019-08-26T14:29:41 |
89208f6b47e6e584fe6302b652842ded1c9ba695
|
{
"blob_id": "89208f6b47e6e584fe6302b652842ded1c9ba695",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-26T14:29:41",
"content_id": "2dd983af442d383d19561170251b4b0548a2d670",
"detected_licenses": [
"MIT"
],
"directory_id": "18ed239634f7acefd44bd6939ecf2e1450ad2c6a",
"extension": "c",
"filename": "preparation.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 204333932,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2571,
"license": "MIT",
"license_type": "permissive",
"path": "/c/preparation.c",
"provenance": "stackv2-0072.json.gz:41131",
"repo_name": "natalijamitic/CrazySnake",
"revision_date": "2019-08-26T14:29:41",
"revision_id": "af1b267182c47693fe0ae9226c09f6d3abc9b3ee",
"snapshot_id": "73308790f4a27fce43d7e771a480fa42fe131357",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/natalijamitic/CrazySnake/af1b267182c47693fe0ae9226c09f6d3abc9b3ee/c/preparation.c",
"visit_date": "2020-07-10T18:19:35.680223"
}
|
stackv2
|
#include "preparation.h"
#include "Demo.h"
void prepare(Options *options, int *row, int *col) {
// Handle to write to the console.
HANDLE wHnd;
HANDLE rHnd;
initscr();
refresh();
getmaxyx(stdscr, *row, *col);
if (*row < 30 || *col < 120) {
*row = 30;
*col = 120;
resize_term(30, 120);
}
int m, n;
m = *row - 2;
n = *col - 22;
wHnd = GetStdHandle(STD_OUTPUT_HANDLE);
rHnd = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleTitle("CRAZY SNAKE");
SMALL_RECT windowSize = { 0, 0, *col, *row };
SetConsoleWindowInfo(wHnd, 1, &windowSize);
load_options(options);
loading2(*row, *col);
if (options->music == ON)
PlaySound(TEXT("IdeZmija.wav"), GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC | SND_LOOP);
else
PlaySound(NULL, NULL, SND_ASYNC);
}
void new_game(Options options, Options *saved_options) {
int score, stop = 0;
int len, total = 0;
short **board = NULL;
Fruit fruit;
Header header;
Move initialmove, currentmove;
score = 0, stop = 0;
initialmove = STOPR;
currentmove = RIGHT;
board = set_game(options.size.row, options.size.col, &header, &fruit);
wclear(stdscr);
wrefresh(stdscr);
len = shortest_path_length(board, header, fruit, options.size.row, options.size.col);
stop = gameplay(board, &header, &fruit, &options, &initialmove, ¤tmove, &score, &len, &total);
save_stop(stop);
wclear(stdscr);
wrefresh(stdscr);
wclear(stdscr);
wrefresh(stdscr);
*saved_options = options;
delete_list(&header);
delete_matrix(&board, options.size.row, options.size.col);
}
void continue_game() {
Fruit fruit;
Header header;
Options saved_options;
Move initialmove, currentmove;
int stop = load_stop(), score;
int len, total;
if (stop != ALIVE) {
print_continue();
return;
}
short **board = loadgame(&saved_options, &initialmove, ¤tmove, &score, &header, &fruit, &len, &total);
wclear(stdscr);
wrefresh(stdscr);
stop = gameplay(board, &header, &fruit, &saved_options, &initialmove, ¤tmove, &score, &len, &total);
save_stop(stop);
wclear(stdscr);
wrefresh(stdscr);
delete_list(&header);
delete_matrix(&board, saved_options.size.row, saved_options.size.col);
}
void demo_game(Options options) {
Fruit fruit;
Header header;
short **board;
int score = 0;
board = set_game(options.size.row, options.size.col, &header, &fruit);
wclear(stdscr);
wrefresh(stdscr);
demo(board, &header, &fruit, &score, &options);
delete_list(&header);
delete_matrix(&board, options.size.row, options.size.row);
}
| 2.28125 | 2 |
2024-11-18T22:11:06.714412+00:00
| 2018-07-05T19:18:43 |
1639682a615b2b366c300ed58811953f957dd06c
|
{
"blob_id": "1639682a615b2b366c300ed58811953f957dd06c",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-05T19:18:43",
"content_id": "d7ab060031609661dec8b2f7d91c0b412d55719d",
"detected_licenses": [
"MIT"
],
"directory_id": "2d8179b0da9816017ad09911af8d30d88b57beee",
"extension": "c",
"filename": "mdl.c",
"fork_events_count": 1,
"gha_created_at": "2019-03-18T12:28:56",
"gha_event_created_at": "2019-03-18T12:28:56",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 176280118,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2647,
"license": "MIT",
"license_type": "permissive",
"path": "/models/initial/mdl.c",
"provenance": "stackv2-0072.json.gz:41259",
"repo_name": "epruyt/SDEverywhere",
"revision_date": "2018-07-05T19:18:43",
"revision_id": "c9ee156e18b19712d159ef59e524697761c28d9c",
"snapshot_id": "ca5c663965fda3c7440682c108d493defea54374",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/epruyt/SDEverywhere/c9ee156e18b19712d159ef59e524697761c28d9c/models/initial/mdl.c",
"visit_date": "2020-04-29T16:56:48.245137"
}
|
stackv2
|
/*(Tue May 03 16:23:57 2016) From initial.mdl - C equations for the model */
#include "simext.c"
static COMPREAL temp0,temp1,temp2,temp3,temp4,temp5,temp6,temp7,temp8
,temp9,temp10,temp11,temp12,temp13,temp14,temp15,temp16,temp17,temp18
,temp19,temp20,temp21,temp22,temp23,temp24,temp25,temp26,temp27,temp28
,temp29,temp30,temp31 ;
static int sumind0,forind0 ;
static int sumind1,forind1 ;
static int sumind2,forind2 ;
static int sumind3,forind3 ;
static int sumind4,forind4 ;
static int sumind5,forind5 ;
static int sumind6,forind6 ;
static int sumind7,forind7 ;
static int simultid ;
#ifndef LINKEXTERN
#endif
unsigned char *mdl_desc()
{
return("(Tue May 03 16:23:57 2016) From initial.mdl") ;
}
/* compute the model rates */
void mdl_func0()
{double temp[10];
VGV->RATE[0] = 1.0 ;/* this is time */
} /* comp_rate */
/* compute the delays */
void mdl_func1()
{double temp[10];
} /* comp_delay */
/* initialize time */
void mdl_func2()
{double temp[10];
vec_arglist_init();
VGV->LEVEL[0] = VGV->LEVEL[3] ;
} /* init_time */
/* initialize time step */
void mdl_func3()
{double temp[10];
/* a constant no need to do anything */
} /* init_tstep */
/* State variable initial value computation*/
void mdl_func4()
{double temp[10];
/* Time */
{
VGV->lastpos = 0 ;
VGV->LEVEL[0] = VGV->LEVEL[3] ;
}
/* x */
{
VGV->lastpos = 9 ;
VGV->LEVEL[9] = VGV->LEVEL[1]*COS(6.280000*VGV->LEVEL[0]/VGV->LEVEL[5
]) ;
}
/* INITIAL x */
{
VGV->lastpos = 4 ;
VGV->LEVEL[4] = VGV->LEVEL[9] ;
}
} /* comp_init */
/* State variable re-initial value computation*/
void mdl_func5()
{double temp[10];
} /* comp_reinit */
/* Active Time Step Equation */
void mdl_func6()
{double temp[10];
} /* comp_tstep */
/* Auxiliary variable equations*/
void mdl_func7()
{double temp[10];
/* x */
{
VGV->lastpos = 9 ;
VGV->LEVEL[9] = VGV->LEVEL[1]*COS(6.280000*VGV->LEVEL[0]/VGV->LEVEL[5
]) ;
}
/* relative x */
{
VGV->lastpos = 6 ;
VGV->LEVEL[6] = VGV->LEVEL[9]/VGV->LEVEL[4] ;
}
/* SAVEPER */
{
VGV->lastpos = 7 ;
VGV->LEVEL[7] = VGV->LEVEL[8] ;
}
} /* comp_aux */
int execute_curloop() {return(0);}
static void vec_arglist_init()
{
}
void VEFCC comp_rate(void)
{
mdl_func0();
}
void VEFCC comp_delay(void)
{
mdl_func1();
}
void VEFCC init_time(void)
{
mdl_func2();
}
void VEFCC init_tstep(void)
{
mdl_func3();
}
void VEFCC comp_init(void)
{
mdl_func4();
}
void VEFCC comp_reinit(void)
{
mdl_func5();
}
void VEFCC comp_tstep(void)
{
mdl_func6();
}
void VEFCC comp_aux(void)
{
mdl_func7();
}
| 2.078125 | 2 |
2024-11-18T22:11:07.127523+00:00
| 2016-06-05T18:21:07 |
3f6fa5658035dc75ddb1f950164412439e95ebd7
|
{
"blob_id": "3f6fa5658035dc75ddb1f950164412439e95ebd7",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-05T18:21:07",
"content_id": "b121d5ace70988f3b2f454361b7beafb556bf88c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "bd9aeb4f90be84f38de103ea02473d8f503efc56",
"extension": "c",
"filename": "mod_miniplate.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 52309300,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1677,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/mod_miniplate.c",
"provenance": "stackv2-0072.json.gz:41387",
"repo_name": "professorsloth/mod_miniplate",
"revision_date": "2016-06-05T18:21:07",
"revision_id": "8debbf3f10db1d635f1548c49ffb6ba7a4e349a0",
"snapshot_id": "43b36674cd572e8d6e1a752db48eff09f35617ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/professorsloth/mod_miniplate/8debbf3f10db1d635f1548c49ffb6ba7a4e349a0/mod_miniplate.c",
"visit_date": "2021-01-19T03:10:06.384887"
}
|
stackv2
|
#include <httpd.h>
#include <http_log.h>
#include <http_core.h>
#include <http_protocol.h>
#include <http_request.h>
#include <apr_strings.h>
#include <string.h>
#include <stdio.h>
#include "miniplate.h"
static int miniplate_handler(request_rec*);
static void register_hooks(apr_pool_t*);
module AP_MODULE_DECLARE_DATA miniplate_module = {
STANDARD20_MODULE_STUFF,
NULL,
NULL,
NULL,
NULL,
NULL,
register_hooks,
};
static int miniplate_handler(request_rec *r)
{
char *base_template_filename = 0;
char *template_content = 0;
int template_length = 0;
char *content_file_content = 0;
int content_file_length = 0;
char* heading = 0;
char* output;
if (!r->handler || strcmp(r->handler, "miniplate")) {
return DECLINED;
}
base_template_filename = get_template_filename(r->filename);
template_length = read_file(base_template_filename, &template_content);
content_file_length = read_file(r->filename, &content_file_content);
heading = find_last_heading(content_file_content);
if (template_length < 1) {
return HTTP_INTERNAL_SERVER_ERROR;
}
if (strcmp(r->parsed_uri.path, BASE_TEMPLATE_NAME) == 0) {
apr_table_add(r->headers_out, "Location", "/");
return HTTP_MOVED_PERMANENTLY;
}
if (content_file_length < 1) {
return HTTP_NO_CONTENT;
}
output = replace_by_keyword("(path)", template_content, r->parsed_uri.path);
output = replace_by_keyword("(heading)", output, heading);
output = replace_by_keyword("(content)", output, content_file_content);
ap_set_content_type(r, "text/html");
ap_rputs(output, r);
return OK;
}
static void register_hooks(apr_pool_t *pool)
{
ap_hook_handler(miniplate_handler, NULL, NULL, APR_HOOK_LAST);
}
| 2.078125 | 2 |
2024-11-18T22:11:08.585271+00:00
| 2018-06-06T14:03:41 |
15d6b7a0ff97eab8c175774413481b5720250c7b
|
{
"blob_id": "15d6b7a0ff97eab8c175774413481b5720250c7b",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-06T14:03:41",
"content_id": "2e815e09bb0baff2894115ed69050bb1a0a37531",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "0126bb0bd15c8555c28bf372a83333d5d1d2750d",
"extension": "c",
"filename": "msg.c",
"fork_events_count": 1,
"gha_created_at": "2013-04-15T17:31:11",
"gha_event_created_at": "2013-11-04T16:01:24",
"gha_language": "C",
"gha_license_id": null,
"github_id": 9454227,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2323,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/msg.c",
"provenance": "stackv2-0072.json.gz:41776",
"repo_name": "LauriM/Gunhack",
"revision_date": "2018-06-06T14:03:41",
"revision_id": "dd1557e68be1fc7368b2b18a4bb8237ce1d20020",
"snapshot_id": "c5fcdcceeee590f5f280ae85022ee667880fc701",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/LauriM/Gunhack/dd1557e68be1fc7368b2b18a4bb8237ce1d20020/src/msg.c",
"visit_date": "2020-05-19T09:18:02.585149"
}
|
stackv2
|
#include "globals.h"
#include "render.h"
#include "msg.h"
#include "player.h"
#include "hud.h"
msg_t *head = NULL;
msg_t *end = NULL;
void msgAdd(char *msg,color_t color){
if(head == NULL){
head = malloc(sizeof(msg_t) + (strlen(msg)+1)*sizeof(char));
head->prev = NULL;
head->next = NULL;
end = head;
head->color = color;
strcpy(head->msg,msg);
head->turn = playerGetInfo()->turn;
return;
}
//End always points to the last node where the new nodes should be linked
msg_t *newMsg = malloc(sizeof(msg_t) + (strlen(msg)+1)*sizeof(char));
end->next = newMsg;
newMsg->prev = end;
newMsg->next = NULL;
strcpy(newMsg->msg,msg);
newMsg->turn = playerGetInfo()->turn;
newMsg->color = color;
end = newMsg;
if(msgGetMsgCount() > MSG_HISTORY_MAX_COUNT){
msgDropHead();
}
}
void msgDropHead(){
msg_t *newHead;
newHead = head->next;
newHead->prev = head->prev;
free(head);
head = newHead;
}
int msgGetMsgCount(){
int count = 0;
msg_t *curr;
curr = head;
while(curr != NULL){
count++;
curr = curr->next;
}
return count;
}
void msgPrintDebugInfo(){
#ifdef DEBUG_LOG_SHOW_INGAME
//If debugging over this is enabled, bailout from this function. It would cause a infinite loop
LOG_WARNING("Disabled DEBUG_LOG_SHOW_INGAME to enabled msgPrintDebugInfo()");
return;
#endif
msg_t *curr;
curr = head;
while(curr != NULL){
LOG_INFO_F("Msg color: %i | %s",curr->color,curr->msg);
curr = curr->next;
}
}
void msgRenderSideView(){
int i = 0;
msg_t *curr;
curr = end;
while(curr != NULL){
setColor(curr->color);
{
char line[100];
snprintf(line,100,"%i : %s",curr->turn,curr->msg);
printxy(82,i,line);
}
setColorOff(curr->color);
curr = curr->prev;
i++;
}
}
void msgShowWindow(){
hudMenuInit();
hudMenuWrite("Message History:");
hudMenuWrite("================");
msg_t *curr;
curr = end;
while(curr != NULL){
setColor(curr->color);
hudMenuWriteF("Turn %i -> %s",curr->turn,curr->msg);
setColorOff(curr->color);
curr = curr->prev;
}
hudMenuFinish();
}
void msgWriteToFile(FILE* file){
msg_t *curr;
curr = end;
int hits = 0;
while(curr != NULL){
fprintf(file,"Turn %i -> %s\n",curr->turn,curr->msg);
curr = curr->prev;
++hits;
if(hits > 15){
return;
}
}
}
extern msg_t* msgGetLastMsg(){
return end;
}
| 2.890625 | 3 |
2024-11-18T22:11:12.728507+00:00
| 2019-04-12T13:23:53 |
e37d20be93afd91a8f10add7e560aa9a7a2627c1
|
{
"blob_id": "e37d20be93afd91a8f10add7e560aa9a7a2627c1",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-12T13:23:53",
"content_id": "e5317ff36bcb1b8b0a25eea0bc4c14366e0063b5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3de8c5bba3edcce5ff851cf3120a4bebf270ac91",
"extension": "c",
"filename": "test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 179712170,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 873,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test.c",
"provenance": "stackv2-0072.json.gz:42548",
"repo_name": "shixiongfei/base64",
"revision_date": "2019-04-12T13:23:53",
"revision_id": "44c95694bc65d0f51494a9a40485eb996a0eaf73",
"snapshot_id": "8d4f78d3b4c69bd0b91356b262810aa3dfb1951b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/shixiongfei/base64/44c95694bc65d0f51494a9a40485eb996a0eaf73/test.c",
"visit_date": "2020-05-05T04:26:29.290057"
}
|
stackv2
|
/*
* test.c
*
* copyright (c) 2019 Xiongfei Shi
*
* author: Xiongfei Shi <jenson.shixf(a)gmail.com>
* license: Apache2.0
*
* https://github.com/shixiongfei/base64
*/
#include <stdio.h>
#include <string.h>
#include "base64.h"
int main(int argc, char *argv[]) {
char text[] = { "Hello World!" };
char encode[64] = { 0 };
char decode[64] = { 0 };
int enclen, declen;
enclen = base64_enclen((int)strlen(text));
printf("Encode evaluate size: %d\n", enclen);
enclen = base64_encode(encode, text, (int)strlen(text));
printf("Encode real size: %d\n", enclen);
declen = base64_declen(enclen);
printf("Decode evaluate size: %d\n", declen);
declen = base64_decode(decode, encode, enclen);
printf("Decode real size: %d\n", declen);
printf("Encode: %s\n", encode);
printf("Decode: %s\n", decode);
}
| 2.734375 | 3 |
2024-11-18T22:11:13.026177+00:00
| 2014-08-04T07:49:10 |
1a93cee5e9fb1c427c96250ff88250d38cdc213d
|
{
"blob_id": "1a93cee5e9fb1c427c96250ff88250d38cdc213d",
"branch_name": "refs/heads/master",
"committer_date": "2014-08-04T07:49:10",
"content_id": "07a6dd98c994c9fef9f1e865ca80b429096b1497",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "6a23d0c2824e6f28c87b48b86f845bc8bec4a99f",
"extension": "c",
"filename": "main.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 17658564,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1796,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0072.json.gz:42933",
"repo_name": "thurday/mos",
"revision_date": "2014-08-04T07:49:10",
"revision_id": "68b44228c60ed5f34cc94abb639e73075a4dff11",
"snapshot_id": "bfcccca70d67212831f3dcc288d52178697b579c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/thurday/mos/68b44228c60ed5f34cc94abb639e73075a4dff11/main.c",
"visit_date": "2021-03-12T23:12:42.544195"
}
|
stackv2
|
#include "types.h"
#include "x86.h"
#include "memlayout.h"
#include "mmu.h"
#define BACKSPACE 0x100
#define CRTPORT 0x3d4
static ushort *crt = (ushort*)P2V(0xb8000); // CGA memory
void* memset(void *dst, int c, uint n)
{
if ((int)dst%4 == 0 && n%4 == 0){
c &= 0xFF;
stosl(dst, (c<<24)|(c<<16)|(c<<8)|c, n/4);
}else{
stosb(dst, c, n);
}
return dst;
}
void* memmove(void *dst, const void *src, uint n)
{
const char *s = src;
char *d = dst;
if(s < d && s + n > d){
s += n;
d += n;
while(n-- > 0){
*--d = *--s;
}
}else{
while(n-- > 0){
*d++ = *s++;
}
}
return dst;
}
static void cgaputc(int c)
{
int pos;
outb(CRTPORT, 14);
pos = inb(CRTPORT+1) << 8;
outb(CRTPORT, 15);
pos |= inb(CRTPORT+1);
if(c == '\n'){
pos += 80 - pos%80;
}else if(c == BACKSPACE){
if(pos > 0){
--pos;
}
}else{
crt[pos++] = (c&0xff) | 0x0700; // black on white
}
if((pos/80) >= 24){ // Scroll up.
memmove(crt, crt+80, sizeof(crt[0])*23*80);
pos -= 80;
memset(crt+pos, 0, sizeof(crt[0])*(24*80 - pos));
}
outb(CRTPORT, 14);
outb(CRTPORT+1, pos>>8);
outb(CRTPORT, 15);
outb(CRTPORT+1, pos);
crt[pos] = ' ' | 0x0700;
}
int main(void)
{
char* buf = "starting mos ...";
char* s = buf;
for(; *s; s++){
cgaputc((*s) & 0xff);
}
while(1)
;
return 0;
}
// Boot page table used in entry.S and entryother.S.
// Page directories (and page tables), must start on a page boundary,
// hence the "__aligned__" attribute.
// Use PTE_PS in page directory entry to enable 4Mbyte pages.
__attribute__((__aligned__(PGSIZE)))
pde_t entrypgdir[NPDENTRIES] = {
// Map VA's [0, 4MB) to PA's [0, 4MB)
[0] = (0) | PTE_P | PTE_W | PTE_PS,
// Map VA's [KERNBASE, KERNBASE+4MB) to PA's [0, 4MB)
[KERNBASE>>PDXSHIFT] = (0) | PTE_P | PTE_W | PTE_PS,
};
| 2.875 | 3 |
2024-11-18T22:11:16.086870+00:00
| 2023-01-27T22:49:21 |
109e0963b707c39a3f4d01909af2059e2616d7ad
|
{
"blob_id": "109e0963b707c39a3f4d01909af2059e2616d7ad",
"branch_name": "refs/heads/main",
"committer_date": "2023-01-27T22:49:29",
"content_id": "43587624f90e0188ccabddc3a0d2d551603c91ba",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "6092c6b6eb94b914757a12707e60339b9bc86f73",
"extension": "c",
"filename": "cbd.c",
"fork_events_count": 1,
"gha_created_at": "2021-03-24T12:48:09",
"gha_event_created_at": "2023-01-09T12:30:13",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 351077384,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2406,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/kem/kyber/kyber1024/avx2/cbd.c",
"provenance": "stackv2-0072.json.gz:43449",
"repo_name": "kriskwiatkowski/pqc",
"revision_date": "2023-01-27T22:49:21",
"revision_id": "e7b5cfe9f8da9d24e25319c8f872133a07d866f2",
"snapshot_id": "d0b3460b1911a9ec56234b2a7ace6be62b80476e",
"src_encoding": "UTF-8",
"star_events_count": 24,
"url": "https://raw.githubusercontent.com/kriskwiatkowski/pqc/e7b5cfe9f8da9d24e25319c8f872133a07d866f2/src/kem/kyber/kyber1024/avx2/cbd.c",
"visit_date": "2023-05-22T14:29:59.105860"
}
|
stackv2
|
#include "cbd.h"
#include "params.h"
#include <immintrin.h>
#include <stdint.h>
/*************************************************
* Name: cbd2
*
* Description: Given an array of uniformly random bytes, compute
* polynomial with coefficients distributed according to
* a centered binomial distribution with parameter eta=2
*
* Arguments: - poly *r: pointer to output polynomial
* - const __m256i *buf: pointer to aligned input byte array
**************************************************/
static void cbd2(poly *restrict r, const __m256i buf[2 * KYBER_N / 128]) {
unsigned int i;
__m256i f0, f1, f2, f3;
const __m256i mask55 = _mm256_set1_epi32(0x55555555);
const __m256i mask33 = _mm256_set1_epi32(0x33333333);
const __m256i mask03 = _mm256_set1_epi32(0x03030303);
const __m256i mask0F = _mm256_set1_epi32(0x0F0F0F0F);
for (i = 0; i < KYBER_N / 64; i++) {
f0 = _mm256_load_si256(&buf[i]);
f1 = _mm256_srli_epi16(f0, 1);
f0 = _mm256_and_si256(mask55, f0);
f1 = _mm256_and_si256(mask55, f1);
f0 = _mm256_add_epi8(f0, f1);
f1 = _mm256_srli_epi16(f0, 2);
f0 = _mm256_and_si256(mask33, f0);
f1 = _mm256_and_si256(mask33, f1);
f0 = _mm256_add_epi8(f0, mask33);
f0 = _mm256_sub_epi8(f0, f1);
f1 = _mm256_srli_epi16(f0, 4);
f0 = _mm256_and_si256(mask0F, f0);
f1 = _mm256_and_si256(mask0F, f1);
f0 = _mm256_sub_epi8(f0, mask03);
f1 = _mm256_sub_epi8(f1, mask03);
f2 = _mm256_unpacklo_epi8(f0, f1);
f3 = _mm256_unpackhi_epi8(f0, f1);
f0 = _mm256_cvtepi8_epi16(_mm256_castsi256_si128(f2));
f1 = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(f2, 1));
f2 = _mm256_cvtepi8_epi16(_mm256_castsi256_si128(f3));
f3 = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(f3, 1));
_mm256_store_si256(&r->vec[4 * i + 0], f0);
_mm256_store_si256(&r->vec[4 * i + 1], f2);
_mm256_store_si256(&r->vec[4 * i + 2], f1);
_mm256_store_si256(&r->vec[4 * i + 3], f3);
}
}
/* buf 32 bytes longer for cbd3 */
void PQCLEAN_KYBER1024_AVX2_poly_cbd_eta1(poly *r, const __m256i buf[KYBER_ETA1 * KYBER_N / 128 + 1]) {
cbd2(r, buf);
}
void PQCLEAN_KYBER1024_AVX2_poly_cbd_eta2(poly *r, const __m256i buf[KYBER_ETA2 * KYBER_N / 128]) {
cbd2(r, buf);
}
| 2.5 | 2 |
2024-11-18T22:11:16.637851+00:00
| 2019-10-25T21:32:55 |
3bdcc95fa3f5a62815ebbb76d479adca6e3b15ca
|
{
"blob_id": "3bdcc95fa3f5a62815ebbb76d479adca6e3b15ca",
"branch_name": "refs/heads/release_60",
"committer_date": "2019-10-28T08:53:38",
"content_id": "3553edea3a5fdb8680feaf2297ab32938ca2c608",
"detected_licenses": [
"NCSA"
],
"directory_id": "6477aa25cab0ea3dfb776ed0ecf6ada7311f0aaa",
"extension": "c",
"filename": "test093.c",
"fork_events_count": 27,
"gha_created_at": "2010-07-22T19:46:09",
"gha_event_created_at": "2019-11-07T20:15:04",
"gha_language": "LLVM",
"gha_license_id": "NOASSERTION",
"github_id": 791823,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 798,
"license": "NCSA",
"license_type": "permissive",
"path": "/projects/llvm-cbe/test/test093.c",
"provenance": "stackv2-0072.json.gz:43705",
"repo_name": "mono/llvm",
"revision_date": "2019-10-25T21:32:55",
"revision_id": "7a8dc89adbe7e123220e070a527e096ee91e66d5",
"snapshot_id": "29b2dc27cdd7865ed40ab423ccbc7bcfd5b94c7b",
"src_encoding": "UTF-8",
"star_events_count": 37,
"url": "https://raw.githubusercontent.com/mono/llvm/7a8dc89adbe7e123220e070a527e096ee91e66d5/projects/llvm-cbe/test/test093.c",
"visit_date": "2023-08-23T09:50:08.043182"
}
|
stackv2
|
//===-- CBackend.cpp - Library for converting LLVM code to C ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===------------------------------------------------------------------------------===//
//
// This code tests to see that the CBE will execute a nested structure properly.
// *TW
//===------------------------------------------------------------------------------===//
struct layer1{
int depth1;
char name1[20];
};
struct layer2{
int depth2;
char name2[20];
struct layer1 layer_data;
}layer2_data;
int main(){
struct layer2 layer2_data = {1, "test", {6, "test2"}};
return layer2_data.layer_data.depth1;
}
| 2.09375 | 2 |
2024-11-18T22:11:16.710423+00:00
| 2021-04-28T18:36:30 |
eba8a7f3bc208c84c6cf252ef05ff8585ecce5eb
|
{
"blob_id": "eba8a7f3bc208c84c6cf252ef05ff8585ecce5eb",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-28T18:36:30",
"content_id": "b80e1062c8d3d61392b8661c078db5570fdbc39c",
"detected_licenses": [
"MIT"
],
"directory_id": "bfa82074cbe9d4f83356087dda364ea5cb127ee2",
"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": 331356521,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3916,
"license": "MIT",
"license_type": "permissive",
"path": "/final/main.c",
"provenance": "stackv2-0072.json.gz:43833",
"repo_name": "ykzzyk/DataStructureAlgorithm",
"revision_date": "2021-04-28T18:36:30",
"revision_id": "75e4e03996d009ba12356e40ee87bc879c609642",
"snapshot_id": "4aa70ed9c94c13bfab54132a2afd1c768c8eb7a8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ykzzyk/DataStructureAlgorithm/75e4e03996d009ba12356e40ee87bc879c609642/final/main.c",
"visit_date": "2023-04-17T05:38:09.904759"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include "stack.h"
#include "link.h"
int priority(char* op){
if (op[0] == '('){
return 0;
}
else if (op[0] == '+' || op[0] == '-'){
return 1;
}
else if (op[0] == '*' || op[0] == '/'){
return 2;
}
return 0;
}
int str_cmp(char input[],char check[])
{
int i,result=1;
for(i=0; input[i]!='\0' || check[i]!='\0'; i++) {
if(input[i] != check[i]) {
result=0;
break;
}
}
return result;
}
LinkNodePtr userInput(){
// (((4+5)/3*5)/5+100/10)-4*3
// 20-((((4+5)/3*5)/5+100/10)-4)*3
// (2+8)/5+3-6*9
char str[100] = "", num[10] = "", temp[1] = "";
int j = 0;
LinkNodePtr list = NULL;
printf("Please type an equation (note: no spaces between the equation):\n");
scanf("%s", str);
for(int i = 0; str[i] != '\0'; i++){
if (isalnum(str[i]) == 0){
if (!str_cmp(num, "")){
insert(&list, num);
memset(num,0,sizeof(num));
j = 0;
}
temp[0] = str[i];
insert(&list, temp);
memset(temp,0,sizeof(temp));
}
else{
num[j] = str[i];
j++;
}
// Check the end condition
if (str[i+1] == '\0'){
if (!str_cmp(num, "")){
insert(&list, num);
memset(num,0,sizeof(num));
j = 0;
}
}
}
return list;
}
int main(void){
StringStackPtr ptr = NULL; // stack
StringStackPtr ptr_e = NULL; // stack
LinkNodePtr list = NULL; // link list
LinkNodePtr head = NULL; // link list
LinkNodePtr output = NULL; // link list
char *data, *op;
char res[10] = "";
// Convert the user's input to link list
list = userInput();
// Infix to postfix conversion
head = list;
while(head != NULL){
// Process the single item in head
data = head->str;
// If the data is not an operator
if (atoi(data) != 0){
insert(&output, data);
}
else if (str_cmp(data, "(")){
push(&ptr, data);
}
else if (str_cmp(data, ")")){
while (!str_cmp(op=pop(&ptr), "("))
{
insert(&output, op);
}
}
else{
while((ptr != NULL) && priority(ptr->str) >= priority(data)){
insert(&output, pop(&ptr));
}
push(&ptr, data);
}
// Update head to next ptr
head = head->nextNode;
}
while(!isStackEmpty(ptr)){
insert(&output, pop(&ptr));
}
// the postfix equation
printf("\nThe postfix equation is:\n");
print_list(output);
head = output;
// Evaluation
while(head != NULL){
// Process the single item in head
data = head->str;
// If the data is not an operator
if (atoi(data) != 0){
push(&ptr_e, data);
}
// If the data is an operator
else{
int b = atoi(pop(&ptr_e));
int a = atoi(pop(&ptr_e));
memset(res,0,sizeof(res));
if (str_cmp(data, "+")){
sprintf(res, "%d", a+b);
}
else if (str_cmp(data, "-")){
sprintf(res, "%d", a-b);
}
else if (str_cmp(data, "*")){
sprintf(res, "%d", a*b);
}
else if (str_cmp(data, "/")){
sprintf(res, "%d", a/b);
}
push(&ptr_e, res);
}
// Update head to next ptr
head = head->nextNode;
}
// The final answer is stored in the top of the stack
printf("\nThe final answer is:\n");
printf("%s\n", pop(&ptr_e));
}
| 3.34375 | 3 |
2024-11-18T22:11:16.895107+00:00
| 2016-06-14T19:36:39 |
472913f32872d99b51de7db39e20f1b5bd744af0
|
{
"blob_id": "472913f32872d99b51de7db39e20f1b5bd744af0",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-14T19:36:39",
"content_id": "54bc91e756d02bc7961996d7308093e9be62a780",
"detected_licenses": [
"MIT"
],
"directory_id": "8b47e8e5283e713643de37f08cd137ada8f63431",
"extension": "c",
"filename": "metropolis.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": 1812,
"license": "MIT",
"license_type": "permissive",
"path": "/metropolis.c",
"provenance": "stackv2-0072.json.gz:44090",
"repo_name": "YashAgarwal/DDP-12D110009",
"revision_date": "2016-06-14T19:36:39",
"revision_id": "e746058a38ba3076e9e391d9a2900719db06fccd",
"snapshot_id": "8245bd3956085367291412e3315c795889ba2733",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/YashAgarwal/DDP-12D110009/e746058a38ba3076e9e391d9a2900719db06fccd/metropolis.c",
"visit_date": "2020-12-28T20:08:37.799014"
}
|
stackv2
|
#include<stdio.h>
#include<stdlib.h>
#include <gsl/gsl_rng.h>
#include<math.h>
//This function takes difference in energy E and a scale factor that is by (default set to 1) and makes a random decission of the jump happening
//it returns 1 for making it happenin
//return 0 for not making it happen
/*int jump_decision(double,double);
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T); */
/*int jump_decision(double E,double scale_factor)
{
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
double u = gsl_rng_uniform (r);
double probablity=exp((-1*E)/scale_factor);
if(probablity>1)
return 1;
else if(probablity>u)
return 1;
else
return 0;
}*/
//driver function to test the code
int main(void)
{
double E=0;
double scale_factor=1;
FILE *fp;
fp=fopen("testing_data_metropolis_code.dat","w");
int i;
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
double u = gsl_rng_uniform (r);
double probablity=exp((-1*E)/scale_factor);
while(E<=1)
{
int count=0;
double probablity=exp((-1*E)/scale_factor);
printf("%le\n",probablity);
for(i=0;i<1000;i++)
{
if(u<probablity)
count++;
u=gsl_rng_uniform(r);
}
fprintf(fp,"%le \t %le \t %le\n",E,((double)count/(double)i),probablity);
E+=0.01;
}
gsl_rng_free(r);
return 0;
}
| 2.6875 | 3 |
2024-11-18T22:11:17.090118+00:00
| 2023-06-20T13:19:19 |
16bde681887601fc47435227c18fecc3c62042ab
|
{
"blob_id": "16bde681887601fc47435227c18fecc3c62042ab",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-20T13:19:19",
"content_id": "bf51af2208cc3ea2b5ce3121088de46f8b1a865c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "a8216d80b80e4cb429086f0f9ac62f91e09498d3",
"extension": "c",
"filename": "vm.c",
"fork_events_count": 223,
"gha_created_at": "2015-03-16T12:05:57",
"gha_event_created_at": "2023-08-29T11:54:14",
"gha_language": "Scheme",
"gha_license_id": "NOASSERTION",
"github_id": 32322244,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 85369,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/vm.c",
"provenance": "stackv2-0072.json.gz:44347",
"repo_name": "ashinn/chibi-scheme",
"revision_date": "2023-06-20T13:19:19",
"revision_id": "67fdb283b667c8f340a5dc7259eaf44825bc90bc",
"snapshot_id": "3e03ee86c0af611f081a38edb12902e4245fb102",
"src_encoding": "UTF-8",
"star_events_count": 1290,
"url": "https://raw.githubusercontent.com/ashinn/chibi-scheme/67fdb283b667c8f340a5dc7259eaf44825bc90bc/vm.c",
"visit_date": "2023-08-24T11:16:42.175821"
}
|
stackv2
|
/* vm.c -- stack-based virtual machine backend */
/* Copyright (c) 2009-2015 Alex Shinn. All rights reserved. */
/* BSD-style license: http://synthcode.com/license.txt */
#if SEXP_USE_NATIVE_X86
#include "opt/x86.c"
#else
/* ... the rest of this file ... */
#include "chibi/eval.h"
#if SEXP_USE_DEBUG_VM > 1
static void sexp_print_stack (sexp ctx, sexp *stack, int top, int fp, sexp out) {
int i;
if (! sexp_oportp(out)) out = sexp_current_error_port(ctx);
for (i=0; i<top; i++) {
sexp_write_char(ctx, ((i==fp) ? '*' : ' '), out);
if (i < 10) sexp_write_char(ctx, '0', out);
sexp_write(ctx, sexp_make_fixnum(i), out);
sexp_write_string(ctx, ": ", out);
sexp_write(ctx, stack[i], out);
sexp_newline(ctx, out);
}
}
#else
#define sexp_print_stack(ctx, stack, top, fp, out)
#endif
#if SEXP_USE_FULL_SOURCE_INFO
static sexp sexp_lookup_source_info (sexp src, int ip) {
int i;
if (src && sexp_procedurep(src))
src = sexp_procedure_source(src);
if (src && sexp_vectorp(src) && sexp_vector_length(src) > 0) {
for (i=1; i<(int)sexp_vector_length(src); i++)
if (sexp_unbox_fixnum(sexp_car(sexp_vector_ref(src, sexp_make_fixnum(i)))) > ip)
return sexp_cdr(sexp_vector_ref(src, sexp_make_fixnum(i-1)));
return sexp_cdr(sexp_vector_ref(src, sexp_make_fixnum(sexp_vector_length(src)-1)));
}
return SEXP_FALSE;
}
#endif
sexp sexp_get_stack_trace (sexp ctx) {
sexp_sint_t i, fp=sexp_context_last_fp(ctx);
sexp self, bc, src, *stack = sexp_stack_data(sexp_context_stack(ctx));
sexp_gc_var2(res, cell);
sexp_gc_preserve2(ctx, res, cell);
res = SEXP_NULL;
for (i=fp; i>4; i=sexp_unbox_fixnum(stack[i+3])) {
self = stack[i+2];
if (self && sexp_procedurep(self)) {
bc = sexp_procedure_code(self);
src = sexp_bytecode_source(bc);
#if SEXP_USE_FULL_SOURCE_INFO
if (src && sexp_vectorp(src))
src = sexp_lookup_source_info(src, sexp_unbox_fixnum(stack[i+3]));
#endif
cell = sexp_cons(ctx, self, src ? src : SEXP_FALSE);
res = sexp_cons(ctx, cell, res);
}
}
res = sexp_nreverse(ctx, res);
sexp_gc_release2(ctx);
return res;
}
void sexp_print_extracted_stack_trace (sexp ctx, sexp trace, sexp out) {
sexp self, bc, src, ls;
if (! sexp_oportp(out))
out = sexp_current_error_port(ctx);
for (ls = trace; sexp_pairp(ls); ls = sexp_cdr(ls)) {
self = sexp_caar(ls);
bc = sexp_procedure_code(self);
src = sexp_cdar(ls);
sexp_write_string(ctx, " called from ", out);
if (sexp_symbolp(sexp_bytecode_name(bc)))
sexp_write(ctx, sexp_bytecode_name(bc), out);
else
sexp_write_string(ctx, "<anonymous>", out);
if (sexp_pairp(src)) {
if (sexp_fixnump(sexp_cdr(src)) && (sexp_cdr(src) >= SEXP_ZERO)) {
sexp_write_string(ctx, " on line ", out);
sexp_write(ctx, sexp_cdr(src), out);
} else {
sexp_write_string(ctx, " bad source line: ", out);
sexp_write(ctx, src, out);
}
if (sexp_stringp(sexp_car(src))) {
sexp_write_string(ctx, " of file ", out);
sexp_write_string(ctx, sexp_string_data(sexp_car(src)), out);
} else {
sexp_write_string(ctx, " bad source file: ", out);
sexp_write(ctx, src, out);
}
}
sexp_write_char(ctx, '\n', out);
}
}
sexp sexp_print_exception_stack_trace_op (sexp ctx, sexp self, sexp_sint_t n, sexp exn, sexp out) {
sexp_assert_type(ctx, sexp_exceptionp, SEXP_EXCEPTION, exn);
sexp_assert_type(ctx, sexp_oportp, SEXP_OPORT, out);
if (sexp_pairp(sexp_exception_stack_trace(exn))) {
sexp_print_extracted_stack_trace(ctx, sexp_exception_stack_trace(exn), out);
}
return SEXP_VOID;
}
void sexp_stack_trace (sexp ctx, sexp out) {
sexp_gc_var1(trace);
sexp_gc_preserve1(ctx, trace);
trace = sexp_get_stack_trace(ctx);
sexp_print_extracted_stack_trace(ctx, trace, out);
sexp_gc_release1(ctx);
}
sexp sexp_stack_trace_op (sexp ctx, sexp self, sexp_sint_t n, sexp out) {
sexp_stack_trace(ctx, out);
return SEXP_VOID;
}
/************************* code generation ****************************/
#if SEXP_USE_ALIGNED_BYTECODE
void sexp_context_align_pos(sexp ctx) {
sexp_uint_t i, pos = sexp_unbox_fixnum(sexp_context_pos(ctx));
sexp_uint_t new_pos = sexp_word_align(pos);
if (new_pos > pos) {
sexp_expand_bcode(ctx, (sexp_sint_t)new_pos - pos);
if (pos > 0)
for (i=pos; i<new_pos; ++i)
sexp_bytecode_data(sexp_context_bc(ctx))[i] =
sexp_bytecode_data(sexp_context_bc(ctx))[pos-1];
sexp_context_pos(ctx) = sexp_make_fixnum(new_pos);
}
}
#endif
static void sexp_inc_context_pos(sexp ctx, sexp_sint_t off) {
sexp_expand_bcode(ctx, off);
sexp_context_pos(ctx) = sexp_fx_add(sexp_context_pos(ctx), sexp_make_fixnum(off));
}
static void sexp_inc_context_depth(sexp ctx, sexp_sint_t off) {
sexp_context_depth(ctx) = sexp_fx_add(sexp_context_depth(ctx), sexp_make_fixnum(off));
if (sexp_unbox_fixnum(sexp_context_depth(ctx))
> sexp_unbox_fixnum(sexp_context_max_depth(ctx)))
sexp_context_max_depth(ctx) = sexp_context_depth(ctx);
}
static void bytecode_preserve (sexp ctx, sexp obj) {
sexp ls = sexp_bytecode_literals(sexp_context_bc(ctx));
if (sexp_pointerp(obj) && !sexp_symbolp(obj)
&& sexp_not(sexp_memq(ctx, obj, ls)))
sexp_push(ctx, sexp_bytecode_literals(sexp_context_bc(ctx)), obj);
}
static void sexp_emit_word (sexp ctx, sexp_uint_t val) {
unsigned char *data;
sexp_context_align_pos(ctx);
sexp_expand_bcode(ctx, sizeof(sexp));
if (sexp_exceptionp(sexp_context_exception(ctx)))
return;
data = sexp_bytecode_data(sexp_context_bc(ctx));
*((sexp_uint_t*)(&(data[sexp_unbox_fixnum(sexp_context_pos(ctx))]))) = val;
sexp_inc_context_pos(ctx, sizeof(sexp));
}
static void sexp_emit_push (sexp ctx, sexp obj) {
sexp_emit(ctx, SEXP_OP_PUSH);
sexp_emit_word(ctx, (sexp_uint_t)obj);
sexp_inc_context_depth(ctx, 1);
bytecode_preserve(ctx, obj);
}
void sexp_emit_return (sexp ctx) {
sexp_emit(ctx, SEXP_OP_RET);
}
static void sexp_push_source (sexp ctx, sexp source) {
#if SEXP_USE_FULL_SOURCE_INFO
sexp src, bc = sexp_context_bc(ctx);
sexp_gc_var1(tmp);
if (source && sexp_pairp(source)) {
src = sexp_bytecode_source(bc);
if (!src) src = sexp_bytecode_source(bc) = SEXP_NULL;
if (!sexp_pairp(src)
|| sexp_unbox_fixnum(sexp_context_pos(ctx)) > sexp_unbox_fixnum(sexp_caar(src))) {
sexp_gc_preserve1(ctx, tmp);
tmp = sexp_cons(ctx, sexp_context_pos(ctx), source);
if (sexp_pairp(tmp)) {
tmp = sexp_cons(ctx, tmp, src);
if (sexp_pairp(tmp)) sexp_bytecode_source(bc) = tmp;
}
sexp_gc_release1(ctx);
}
}
#endif
}
static sexp_sint_t sexp_context_make_label (sexp ctx) {
sexp_sint_t label;
sexp_context_align_pos(ctx);
label = sexp_unbox_fixnum(sexp_context_pos(ctx));
sexp_inc_context_pos(ctx, sizeof(sexp_uint_t));
return label;
}
static void sexp_context_patch_label (sexp ctx, sexp_sint_t label) {
sexp bc = sexp_context_bc(ctx);
unsigned char *data = sexp_bytecode_data(bc)+label;
if (!sexp_exceptionp(sexp_context_exception(ctx)))
*((sexp_sint_t*)data) = sexp_unbox_fixnum(sexp_context_pos(ctx))-label;
}
static void generate_lit (sexp ctx, sexp value) {
sexp_emit_push(ctx, value);
}
static void generate_drop_prev (sexp ctx, sexp prev) {
#if ! SEXP_USE_ALIGNED_BYTECODE
if ((sexp_pairp(prev) && sexp_opcodep(sexp_car(prev))
&& (sexp_opcode_code(sexp_car(prev)) == SEXP_OP_PUSH))
|| sexp_setp(prev) || sexp_litp(prev) || prev == SEXP_VOID)
sexp_inc_context_pos(ctx, -(1 + sizeof(sexp)));
else
#endif
sexp_emit(ctx, SEXP_OP_DROP);
}
static void generate_seq (sexp ctx, sexp name, sexp loc, sexp lam, sexp app) {
sexp head=app, tail=sexp_cdr(app);
sexp_uint_t tailp = sexp_context_tailp(ctx);
sexp_push_source(ctx, sexp_pair_source(app));
sexp_context_tailp(ctx) = 0;
for ( ; sexp_pairp(tail); head=tail, tail=sexp_cdr(tail))
if (sexp_pointerp(sexp_car(head)) && (! sexp_litp(sexp_car(head)))) {
sexp_generate(ctx, name, loc, lam, sexp_car(head));
generate_drop_prev(ctx, sexp_car(head));
sexp_inc_context_depth(ctx, -1);
}
sexp_context_tailp(ctx) = (char)tailp;
sexp_generate(ctx, name, loc, lam, sexp_car(head));
}
static void generate_cnd (sexp ctx, sexp name, sexp loc, sexp lam, sexp cnd) {
sexp_sint_t label1, label2, tailp=sexp_context_tailp(ctx);
sexp_push_source(ctx, sexp_cnd_source(cnd));
sexp_context_tailp(ctx) = 0;
sexp_generate(ctx, name, loc, lam, sexp_cnd_test(cnd));
sexp_context_tailp(ctx) = (char)tailp;
sexp_emit(ctx, SEXP_OP_JUMP_UNLESS);
sexp_inc_context_depth(ctx, -1);
label1 = sexp_context_make_label(ctx);
sexp_generate(ctx, name, loc, lam, sexp_cnd_pass(cnd));
sexp_context_tailp(ctx) = (char)tailp;
sexp_emit(ctx, SEXP_OP_JUMP);
sexp_inc_context_depth(ctx, -1);
label2 = sexp_context_make_label(ctx);
sexp_context_patch_label(ctx, label1);
sexp_generate(ctx, name, loc, lam, sexp_cnd_fail(cnd));
sexp_context_patch_label(ctx, label2);
}
static void generate_non_global_ref (sexp ctx, sexp name, sexp cell,
sexp lambda, sexp fv, int unboxp) {
sexp_uint_t i;
sexp loc = sexp_cdr(cell);
if (loc == lambda && sexp_lambdap(lambda)) {
/* local ref */
sexp_emit(ctx, SEXP_OP_LOCAL_REF);
sexp_emit_word(ctx, sexp_param_index(ctx, lambda, name));
} else {
/* closure ref */
for (i=0; sexp_pairp(fv); fv=sexp_cdr(fv), i++)
if ((name == sexp_ref_name(sexp_car(fv)))
&& (loc == sexp_ref_loc(sexp_car(fv))))
break;
sexp_emit(ctx, SEXP_OP_CLOSURE_REF);
sexp_emit_word(ctx, i);
}
if (unboxp && (sexp_truep(sexp_memq(ctx, name, sexp_lambda_sv(loc)))))
sexp_emit(ctx, SEXP_OP_CDR);
sexp_inc_context_depth(ctx, +1);
}
static void generate_ref (sexp ctx, sexp ref, int unboxp) {
sexp lam;
sexp_push_source(ctx, sexp_ref_source(ref));
if (! sexp_lambdap(sexp_ref_loc(ref))) {
/* global ref */
if (unboxp) {
sexp_emit(ctx, (sexp_cdr(sexp_ref_cell(ref)) == SEXP_UNDEF)
? SEXP_OP_GLOBAL_REF : SEXP_OP_GLOBAL_KNOWN_REF);
sexp_emit_word(ctx, (sexp_uint_t)sexp_ref_cell(ref));
bytecode_preserve(ctx, sexp_ref_cell(ref));
} else
sexp_emit_push(ctx, sexp_ref_cell(ref));
} else {
lam = sexp_context_lambda(ctx);
if (!lam || !sexp_lambdap(lam)) {
sexp_warn(ctx, "variable out of phase: ", sexp_ref_name(ref));
sexp_emit_push(ctx, SEXP_VOID);
} else {
generate_non_global_ref(ctx, sexp_ref_name(ref), sexp_ref_cell(ref),
lam, sexp_lambda_fv(lam), unboxp);
}
}
}
static void generate_set (sexp ctx, sexp set) {
sexp ref = sexp_set_var(set), lambda;
sexp_push_source(ctx, sexp_set_source(set));
/* compile the value */
sexp_context_tailp(ctx) = 0;
if (sexp_lambdap(sexp_set_value(set))) {
sexp_lambda_name(sexp_set_value(set)) = sexp_ref_name(ref);
sexp_generate(ctx, sexp_ref_name(ref), sexp_ref_loc(ref), sexp_set_value(set), sexp_set_value(set));
} else {
sexp_generate(ctx, 0, 0, 0, sexp_set_value(set));
}
if (! sexp_lambdap(sexp_ref_loc(ref))) {
/* global vars are set directly */
if (sexp_cdr(sexp_ref_cell(ref)) == SEXP_UNDEF) {
/* force an undefined variable error if still undef at runtime */
generate_ref(ctx, ref, 1);
sexp_emit(ctx, SEXP_OP_DROP);
}
sexp_emit_push(ctx, sexp_ref_cell(ref));
sexp_emit(ctx, SEXP_OP_SET_CDR);
} else {
lambda = sexp_ref_loc(ref);
if (sexp_truep(sexp_memq(ctx, sexp_ref_name(ref), sexp_lambda_sv(lambda)))) {
/* stack or closure mutable vars are boxed */
generate_ref(ctx, ref, 0);
sexp_emit(ctx, SEXP_OP_SET_CDR);
} else {
/* internally defined variable */
sexp_emit(ctx, SEXP_OP_LOCAL_SET);
sexp_emit_word(ctx, sexp_param_index(ctx, lambda, sexp_ref_name(ref)));
}
}
sexp_emit_push(ctx, SEXP_VOID);
sexp_inc_context_depth(ctx, +1);
}
static void generate_opcode_app (sexp ctx, sexp app) {
sexp op = sexp_car(app);
sexp_sint_t i, num_args, inv_default=0;
sexp_gc_var1(ls);
sexp_gc_preserve1(ctx, ls);
if (sexp_opcode_tail_call_p(op) && !sexp_context_tailp(ctx)) {
sexp_warn(ctx, "tail-call only opcode in non-tail position: ", app);
generate_lit(ctx, SEXP_VOID);
return;
}
num_args = sexp_unbox_fixnum(sexp_length(ctx, sexp_cdr(app)));
sexp_context_tailp(ctx) = 0;
if (sexp_opcode_class(op) != SEXP_OPC_PARAMETER) {
/* maybe push the default for an optional argument */
if ((num_args == sexp_opcode_num_args(op))
&& sexp_opcode_variadic_p(op) && sexp_opcode_data(op)) {
if (sexp_opcode_inverse(op)) {
inv_default = 1;
} else {
if (sexp_opcode_opt_param_p(op) && sexp_opcodep(sexp_opcode_data(op))) {
#if SEXP_USE_GREEN_THREADS
sexp_emit(ctx, SEXP_OP_PARAMETER_REF);
sexp_emit_word(ctx, (sexp_uint_t)sexp_opcode_data(op));
bytecode_preserve(ctx, sexp_opcode_data(op));
#else
sexp_emit_push(ctx, sexp_opcode_data(sexp_opcode_data(op)));
#endif
sexp_emit(ctx, SEXP_OP_CDR);
} else {
sexp_emit_push(ctx, sexp_opcode_data(op));
}
sexp_inc_context_depth(ctx, +1);
num_args++;
}
}
/* push the arguments onto the stack in reverse order */
if (!sexp_opcode_static_param_p(op)) {
ls = ((sexp_opcode_inverse(op)
&& (sexp_opcode_class(op) != SEXP_OPC_ARITHMETIC))
? sexp_cdr(app) : sexp_reverse(ctx, sexp_cdr(app)));
for ( ; sexp_pairp(ls); ls = sexp_cdr(ls)) {
sexp_generate(ctx, 0, 0, 0, sexp_car(ls));
#if SEXP_USE_AUTO_FORCE
if (((sexp_opcode_class(op) != SEXP_OPC_CONSTRUCTOR)
|| sexp_opcode_code(op) == SEXP_OP_MAKE_VECTOR)
&& !(sexp_opcode_class(op) == SEXP_OPC_TYPE_PREDICATE
&& sexp_unbox_fixnum(sexp_opcode_data(op)) == SEXP_PROMISE))
sexp_emit(ctx, SEXP_OP_FORCE);
#endif
}
}
}
/* push the default for inverse opcodes */
if (inv_default) {
sexp_emit_push(ctx, sexp_opcode_data(op));
if (sexp_opcode_opt_param_p(op)) sexp_emit(ctx, SEXP_OP_CDR);
sexp_inc_context_depth(ctx, +1);
num_args++;
}
/* emit the actual operator call */
switch (sexp_opcode_class(op)) {
case SEXP_OPC_ARITHMETIC:
/* fold variadic arithmetic operators */
for (i=num_args-1; i>0; i--)
sexp_emit(ctx, sexp_opcode_code(op));
break;
case SEXP_OPC_ARITHMETIC_CMP:
/* With [<true-value>, x] on the stack, and x boolean, */
/* AND is equivalent to ROT+DROP. Note one AND for every STACK_REF. */
if (num_args > 2) {
sexp_emit(ctx, SEXP_OP_STACK_REF);
sexp_emit_word(ctx, 2);
sexp_emit(ctx, SEXP_OP_STACK_REF);
sexp_emit_word(ctx, 2);
sexp_emit(ctx, sexp_opcode_code(op));
sexp_emit(ctx, SEXP_OP_AND);
for (i=num_args-2; i>0; i--) {
sexp_emit(ctx, SEXP_OP_STACK_REF);
sexp_emit_word(ctx, 3);
sexp_emit(ctx, SEXP_OP_STACK_REF);
sexp_emit_word(ctx, 3);
sexp_emit(ctx, sexp_opcode_code(op));
sexp_emit(ctx, SEXP_OP_AND);
sexp_emit(ctx, SEXP_OP_AND);
}
sexp_emit(ctx, SEXP_OP_AND);
} else
sexp_emit(ctx, sexp_opcode_code(op));
break;
case SEXP_OPC_FOREIGN:
sexp_emit(ctx, sexp_opcode_code(op));
sexp_emit_word(ctx, (sexp_uint_t)op);
bytecode_preserve(ctx, op);
break;
case SEXP_OPC_TYPE_PREDICATE:
case SEXP_OPC_GETTER:
case SEXP_OPC_SETTER:
case SEXP_OPC_CONSTRUCTOR:
sexp_emit(ctx, sexp_opcode_code(op));
if ((sexp_opcode_class(op) != SEXP_OPC_CONSTRUCTOR)
|| sexp_opcode_code(op) == SEXP_OP_MAKE) {
if (sexp_opcode_data(op))
sexp_emit_word(ctx, sexp_unbox_fixnum(sexp_opcode_data(op)));
if (sexp_opcode_data2(op))
sexp_emit_word(ctx, sexp_unbox_fixnum(sexp_opcode_data2(op)));
if (sexp_opcode_data(op) || sexp_opcode_data2(op))
bytecode_preserve(ctx, op);
}
break;
case SEXP_OPC_PARAMETER:
#if SEXP_USE_GREEN_THREADS
if (num_args > 0) {
if (sexp_opcode_data2(op) && sexp_applicablep(sexp_opcode_data2(op))) {
ls = sexp_list2(ctx, sexp_opcode_data2(op), sexp_cadr(app));
sexp_generate(ctx, 0, 0, 0, ls);
} else {
sexp_generate(ctx, 0, 0, 0, sexp_cadr(app));
}
}
sexp_emit(ctx, SEXP_OP_PARAMETER_REF);
sexp_emit_word(ctx, (sexp_uint_t)op);
bytecode_preserve(ctx, op);
#else
if (num_args > 0) sexp_generate(ctx, 0, 0, 0, sexp_cadr(app));
sexp_emit_push(ctx, sexp_opcode_data(op));
#endif
sexp_emit(ctx, ((num_args == 0) ? SEXP_OP_CDR : SEXP_OP_SET_CDR));
if (num_args > 0) sexp_emit_push(ctx, SEXP_VOID);
break;
default:
sexp_emit(ctx, sexp_opcode_code(op));
}
if (sexp_opcode_static_param_p(op))
for (ls=sexp_cdr(app); sexp_pairp(ls); ls=sexp_cdr(ls))
sexp_emit_word(ctx, sexp_unbox_fixnum(sexp_litp(sexp_car(ls)) ?
sexp_lit_value(sexp_car(ls)) :
sexp_car(ls)));
if (sexp_opcode_return_type(op) == SEXP_VOID
&& sexp_opcode_class(op) != SEXP_OPC_FOREIGN)
sexp_emit_push(ctx, SEXP_VOID);
sexp_inc_context_depth(ctx, -(num_args-1));
sexp_gc_release1(ctx);
}
static void generate_general_app (sexp ctx, sexp app) {
sexp_uint_t len = sexp_unbox_fixnum(sexp_length(ctx, sexp_cdr(app))),
tailp = sexp_context_tailp(ctx);
sexp_gc_var1(ls);
sexp_gc_preserve1(ctx, ls);
/* push the arguments onto the stack */
sexp_context_tailp(ctx) = 0;
for (ls=sexp_reverse(ctx, sexp_cdr(app)); sexp_pairp(ls); ls=sexp_cdr(ls))
sexp_generate(ctx, 0, 0, 0, sexp_car(ls));
/* push the operator onto the stack */
sexp_generate(ctx, 0, 0, 0, sexp_car(app));
/* maybe overwrite the current frame */
sexp_emit(ctx, ((tailp && sexp_not(sexp_global(ctx, SEXP_G_NO_TAIL_CALLS_P))) ? SEXP_OP_TAIL_CALL : SEXP_OP_CALL));
sexp_emit_word(ctx, (sexp_uint_t)sexp_make_fixnum(len));
sexp_context_tailp(ctx) = (char)tailp;
sexp_inc_context_depth(ctx, -len);
sexp_gc_release1(ctx);
}
#if SEXP_USE_TAIL_JUMPS
static void generate_tail_jump (sexp ctx, sexp name, sexp loc, sexp lam, sexp app) {
sexp_gc_var3(ls1, ls2, ls3);
sexp_gc_preserve3(ctx, ls1, ls2, ls3);
/* overwrite the arguments that differ */
sexp_context_tailp(ctx) = 0;
for (ls1=sexp_cdr(app), ls2=sexp_lambda_params(lam), ls3=SEXP_NULL;
sexp_pairp(ls1); ls1=sexp_cdr(ls1), ls2=sexp_cdr(ls2)) {
if (!(sexp_refp(sexp_car(ls1))
&& sexp_ref_name(sexp_car(ls1)) == sexp_car(ls2)
&& sexp_ref_loc(sexp_car(ls1)) == lam
&& sexp_not(sexp_memq(ctx, sexp_car(ls2), sexp_lambda_sv(lam))))) {
sexp_generate(ctx, 0, 0, 0, sexp_car(ls1));
ls3 = sexp_cons(ctx, sexp_car(ls2), ls3);
}
}
for (ls1=ls3; sexp_pairp(ls1); ls1=sexp_cdr(ls1)) {
sexp_emit(ctx, SEXP_OP_LOCAL_SET);
sexp_emit_word(ctx, sexp_param_index(ctx, lam, sexp_car(ls1)));
}
/* drop the current result and jump */
sexp_emit(ctx, SEXP_OP_JUMP);
sexp_context_align_pos(ctx);
sexp_emit_word(ctx, (sexp_uint_t) (-sexp_unbox_fixnum(sexp_context_pos(ctx)) +
(sexp_pairp(sexp_lambda_locals(lam))
? 1 + sizeof(sexp) : 0)));
sexp_context_tailp(ctx) = 1;
sexp_gc_release3(ctx);
}
#endif
static void generate_app (sexp ctx, sexp name, sexp loc, sexp lam, sexp app) {
sexp_push_source(ctx, sexp_pair_source(app));
if (sexp_opcodep(sexp_car(app)))
generate_opcode_app(ctx, app);
#if SEXP_USE_TAIL_JUMPS
else if (sexp_context_tailp(ctx) && sexp_refp(sexp_car(app))
&& name == sexp_ref_name(sexp_car(app))
&& loc == sexp_ref_loc(sexp_car(app))
&& (sexp_length(ctx, sexp_cdr(app))
== sexp_length(ctx, sexp_lambda_params(lam))))
generate_tail_jump(ctx, name, loc, lam, app);
#endif
else
generate_general_app(ctx, app);
}
#if SEXP_USE_UNBOXED_LOCALS
static int sexp_internal_definep(sexp ctx, sexp x) {
return sexp_lambdap(sexp_ref_loc(x))
&& sexp_truep(sexp_memq(ctx, sexp_ref_name(x),
sexp_lambda_locals(sexp_ref_loc(x))));
}
static int sexp_mutual_internal_definep(sexp ctx, sexp x, sexp fv) {
return sexp_internal_definep(ctx, x)
&& sexp_ref_loc(x) == sexp_ref_loc(fv) && sexp_internal_definep(ctx, fv)
&& sexp_not(sexp_memq(ctx, sexp_ref_name(fv),
sexp_lambda_sv(sexp_ref_loc(fv))));
}
static int generate_lambda_locals (sexp ctx, sexp name, sexp loc, sexp lam, sexp x) {
sexp ls;
if (sexp_seqp(x)) {
for (ls=sexp_seq_ls(x); sexp_pairp(ls); ls=sexp_cdr(ls))
if (!generate_lambda_locals(ctx, name, loc, lam, sexp_car(ls)))
return 0;
return 1;
} else if (sexp_setp(x) && sexp_internal_definep(ctx, sexp_set_var(x))) {
sexp_generate(ctx, name, loc, lam, x);
sexp_inc_context_pos(ctx, -(1 + sizeof(sexp)));
return 1;
}
return 0;
}
static int generate_lambda_body (sexp ctx, sexp name, sexp loc, sexp lam, sexp x, sexp prev_lam) {
sexp_uint_t k, updatep, tailp;
sexp ls, ref, fv, prev_fv;
if (sexp_exceptionp(sexp_context_exception(ctx)))
return 0;
if (sexp_seqp(x)) {
tailp = sexp_context_tailp(ctx);
sexp_context_tailp(ctx) = 0;
for (ls=sexp_seq_ls(x); sexp_pairp(ls); ls=sexp_cdr(ls)) {
if (sexp_nullp(sexp_cdr(ls))) sexp_context_tailp(ctx) = tailp;
if (!generate_lambda_body(ctx, name, loc, lam, sexp_car(ls), prev_lam)) {
if (sexp_pairp(sexp_cdr(ls))) {
generate_drop_prev(ctx, sexp_car(ls));
for (ls=sexp_cdr(ls); sexp_pairp(ls) && sexp_pairp(sexp_cdr(ls));
ls=sexp_cdr(ls)) {
sexp_generate(ctx, name, loc, lam, sexp_car(ls));
generate_drop_prev(ctx, sexp_car(ls));
}
sexp_context_tailp(ctx) = tailp;
sexp_generate(ctx, name, loc, lam, sexp_car(ls));
}
return 0;
}
}
return 1;
} else if (sexp_setp(x) && sexp_internal_definep(ctx, sexp_set_var(x))) {
updatep = 0;
if (sexp_lambdap(sexp_set_value(x))) {
/* update potentially changed bindings */
fv = sexp_lambda_fv(sexp_set_value(x));
prev_fv = sexp_lambdap(prev_lam) ? sexp_lambda_fv(prev_lam) : SEXP_NULL;
for (k=0; fv && sexp_pairp(fv); fv=sexp_cdr(fv), k++) {
ref = sexp_car(fv);
if (sexp_mutual_internal_definep(ctx, sexp_set_var(x), ref)) {
if (!updatep) {
updatep = 1;
generate_non_global_ref(ctx, sexp_ref_name(sexp_set_var(x)),
sexp_ref_cell(sexp_set_var(x)),
lam, sexp_lambda_fv(lam), 1);
sexp_emit(ctx, SEXP_OP_CLOSURE_VARS);
}
generate_non_global_ref(ctx, sexp_ref_name(ref), sexp_ref_cell(ref),
lam, sexp_lambda_fv(lam), 1);
sexp_emit_push(ctx, sexp_make_fixnum(k));
sexp_emit(ctx, SEXP_OP_STACK_REF);
sexp_emit_word(ctx, 3);
sexp_emit(ctx, SEXP_OP_VECTOR_SET);
sexp_inc_context_depth(ctx, -1);
}
}
}
if (updatep) sexp_emit(ctx, SEXP_OP_DROP);
return 1;
}
sexp_generate(ctx, name, loc, lam, x);
return 0;
}
#endif
static void generate_lambda (sexp ctx, sexp name, sexp loc, sexp lam, sexp lambda) {
sexp ctx2, fv, ls, flags, len, ref, prev_lambda, prev_fv;
sexp_sint_t k;
sexp_gc_var2(tmp, bc);
if (sexp_exceptionp(sexp_context_exception(ctx)))
return;
prev_lambda = sexp_context_lambda(ctx);
prev_fv = sexp_lambdap(prev_lambda) ? sexp_lambda_fv(prev_lambda) : SEXP_NULL;
fv = sexp_lambda_fv(lambda);
ctx2 = sexp_make_eval_context(ctx, sexp_context_stack(ctx), sexp_context_env(ctx), 0, 0);
if (sexp_exceptionp(ctx2)) {
sexp_context_exception(ctx) = ctx2;
return;
}
sexp_context_lambda(ctx2) = lambda;
sexp_gc_preserve2(ctx, tmp, bc);
#if SEXP_USE_FULL_SOURCE_INFO
tmp = sexp_cons(ctx, SEXP_NEG_ONE, sexp_lambda_source(lambda));
tmp = sexp_cons(ctx, tmp, SEXP_NULL);
#else
tmp = sexp_lambda_source(lambda);
#endif
sexp_bytecode_source(sexp_context_bc(ctx2)) = tmp;
tmp = sexp_cons(ctx2, SEXP_ZERO, sexp_lambda_source(lambda));
/* allocate space for local vars */
k = sexp_unbox_fixnum(sexp_length(ctx, sexp_lambda_locals(lambda)));
if (k > 0) {
#if SEXP_USE_RESERVE_OPCODE
sexp_emit(ctx2, SEXP_OP_RESERVE);
sexp_emit_word(ctx2, k);
#else
while (k--) sexp_emit_push(ctx2, SEXP_UNDEF);
#endif
}
/* box mutable vars */
for (ls=sexp_lambda_sv(lambda); sexp_pairp(ls); ls=sexp_cdr(ls)) {
k = sexp_param_index(ctx, lambda, sexp_car(ls));
sexp_emit(ctx2, SEXP_OP_LOCAL_REF);
sexp_emit_word(ctx2, k);
sexp_emit_push(ctx2, sexp_car(ls));
sexp_emit(ctx2, SEXP_OP_CONS);
sexp_emit(ctx2, SEXP_OP_LOCAL_SET);
sexp_emit_word(ctx2, k);
}
if (lam != lambda) loc = 0;
#if SEXP_USE_UNBOXED_LOCALS
sexp_context_tailp(ctx2) = 0;
generate_lambda_locals(ctx2, name, loc, lambda, sexp_lambda_body(lambda));
sexp_context_tailp(ctx2) = 1;
generate_lambda_body(ctx2, name, loc, lambda, sexp_lambda_body(lambda), prev_lambda);
#else
sexp_context_tailp(ctx2) = 1;
sexp_generate(ctx2, name, loc, lam, sexp_lambda_body(lambda));
#endif
flags = sexp_make_fixnum(sexp_not(sexp_listp(ctx, sexp_lambda_params(lambda)))
? (SEXP_PROC_VARIADIC + (sexp_rest_unused_p(lambda)
? SEXP_PROC_UNUSED_REST: 0))
: SEXP_PROC_NONE);
len = sexp_length(ctx2, sexp_lambda_params(lambda));
bc = sexp_complete_bytecode(ctx2);
if (sexp_exceptionp(bc)) {
sexp_context_exception(ctx) = bc;
} else {
sexp_bytecode_name(bc) = sexp_lambda_name(lambda);
if (sexp_nullp(fv)) {
/* shortcut, no free vars */
tmp = sexp_make_vector(ctx2, SEXP_ZERO, SEXP_VOID);
tmp = sexp_make_procedure(ctx2, flags, len, bc, tmp);
bytecode_preserve(ctx, tmp);
generate_lit(ctx, tmp);
} else {
/* push the closed vars */
sexp_emit_push(ctx, SEXP_VOID);
sexp_emit_push(ctx, sexp_length(ctx, fv));
sexp_emit(ctx, SEXP_OP_MAKE_VECTOR);
sexp_inc_context_depth(ctx, -1);
for (k=0; sexp_pairp(fv); fv=sexp_cdr(fv), k++) {
ref = sexp_car(fv);
generate_non_global_ref(ctx, sexp_ref_name(ref), sexp_ref_cell(ref),
prev_lambda, prev_fv, 0);
sexp_emit_push(ctx, sexp_make_fixnum(k));
sexp_emit(ctx, SEXP_OP_STACK_REF);
sexp_emit_word(ctx, 3);
sexp_emit(ctx, SEXP_OP_VECTOR_SET);
sexp_inc_context_depth(ctx, -1);
}
/* push the additional procedure info and make the closure */
sexp_emit(ctx, SEXP_OP_MAKE_PROCEDURE);
sexp_emit_word(ctx, (sexp_uint_t)flags);
sexp_emit_word(ctx, (sexp_uint_t)len);
sexp_emit_word(ctx, (sexp_uint_t)bc);
bytecode_preserve(ctx, bc);
}
}
sexp_gc_release2(ctx);
}
void sexp_generate (sexp ctx, sexp name, sexp loc, sexp lam, sexp x) {
if (sexp_exceptionp(sexp_context_exception(ctx)))
return;
if (sexp_pointerp(x)) {
switch (sexp_pointer_tag(x)) {
case SEXP_PAIR: generate_app(ctx, name, loc, lam, x); break;
case SEXP_LAMBDA: generate_lambda(ctx, name, loc, lam, x); break;
case SEXP_CND: generate_cnd(ctx, name, loc, lam, x); break;
case SEXP_REF: generate_ref(ctx, x, 1); break;
case SEXP_SET: generate_set(ctx, x); break;
case SEXP_SEQ: generate_seq(ctx, name, loc, lam, sexp_seq_ls(x)); break;
case SEXP_LIT: generate_lit(ctx, sexp_lit_value(x)); break;
default: generate_lit(ctx, x);
}
} else {
generate_lit(ctx, x);
}
}
static sexp make_param_list (sexp ctx, sexp_uint_t i) {
sexp_gc_var1(res);
sexp_gc_preserve1(ctx, res);
res = SEXP_NULL;
for ( ; i>0; i--)
res = sexp_cons(ctx, sexp_make_fixnum(i), res);
sexp_gc_release1(ctx);
return res;
}
static sexp make_opcode_procedure (sexp ctx, sexp op, sexp_uint_t i, sexp_sint_t flags) {
int j = i+(flags & SEXP_PROC_VARIADIC);
sexp ls, res, env;
sexp_gc_var6(bc, params, ref, refs, lambda, ctx2);
if (j == sexp_opcode_num_args(op)) { /* return before preserving */
if (sexp_opcode_proc(op)) return sexp_opcode_proc(op);
} else if (j < sexp_opcode_num_args(op)) {
return sexp_compile_error(ctx, "not enough args for opcode", op);
} else if (! sexp_opcode_variadic_p(op)) { /* i > num_args */
return sexp_compile_error(ctx, "too many args for opcode", op);
}
sexp_gc_preserve6(ctx, bc, params, ref, refs, lambda, ctx2);
params = make_param_list(ctx, j);
lambda = sexp_make_lambda(ctx, params);
ctx2 = sexp_make_child_context(ctx, lambda);
env = sexp_extend_env(ctx2, sexp_context_env(ctx), params, lambda);
if (sexp_exceptionp(env)) {
res = env;
} else {
sexp_context_env(ctx2) = env;
for (ls=params, refs=SEXP_NULL; sexp_pairp(ls); ls=sexp_cdr(ls)) {
ref = sexp_make_ref(ctx2, sexp_car(ls), sexp_env_cell(ctx, env, sexp_car(ls), 0));
if (!sexp_exceptionp(ref)) sexp_push(ctx2, refs, ref);
}
if (!sexp_exceptionp(refs))
refs = sexp_reverse(ctx2, refs);
refs = sexp_cons(ctx2, op, refs);
if (sexp_exceptionp(refs)) {
res = refs;
} else {
generate_opcode_app(ctx2, refs);
bc = sexp_complete_bytecode(ctx2);
sexp_bytecode_name(bc) = sexp_opcode_name(op);
res=sexp_make_procedure(ctx2, sexp_make_fixnum(flags), sexp_make_fixnum(i), bc, SEXP_VOID);
if (j == sexp_opcode_num_args(op))
sexp_opcode_proc(op) = res;
}
}
sexp_gc_release6(ctx);
return res;
}
sexp sexp_make_foreign_proc(sexp ctx, const char *name, int num_args, int flags,
const char *fname, sexp_proc1 f) {
sexp_gc_var1(res);
sexp_gc_preserve1(ctx, res);
res = sexp_make_foreign (ctx, name, num_args+((flags & SEXP_PROC_VARIADIC)>0), 0, fname, f, NULL);
if (!sexp_exceptionp(res))
res = make_opcode_procedure (ctx, res, num_args, flags);
sexp_gc_release1(ctx);
return res;
}
sexp sexp_define_foreign_proc_aux (sexp ctx, sexp env, const char *name,int num_args,
int flags, const char *fname, sexp_proc1 f, sexp data) {
sexp_gc_var2(sym, res);
sexp_gc_preserve2(ctx, sym, res);
res = sexp_make_foreign_proc(ctx, name, num_args, flags, fname, f);
if (!sexp_exceptionp(res))
sexp_env_define(ctx, env, sym = sexp_intern(ctx, name, -1), res);
sexp_gc_release2(ctx);
return res;
}
/*********************** the virtual machine **************************/
sexp sexp_make_trampoline (sexp ctx, sexp proc, sexp args) {
return sexp_make_exception(ctx, SEXP_TRAMPOLINE, SEXP_FALSE, args, proc, SEXP_FALSE);
}
#if SEXP_USE_GROW_STACK
static int sexp_grow_stack (sexp ctx, int min_size) {
sexp stack, old_stack = sexp_context_stack(ctx), *from, *to;
int i, size = sexp_stack_length(old_stack), new_size;
new_size = size * 2;
if (new_size < min_size) new_size = min_size;
if (new_size > SEXP_MAX_STACK_SIZE) {
if (size == SEXP_MAX_STACK_SIZE)
return 0;
new_size = SEXP_MAX_STACK_SIZE;
}
stack = sexp_alloc_tagged(ctx, (sexp_sizeof(stack)+sizeof(sexp)*new_size),
SEXP_STACK);
if (!stack || sexp_exceptionp(stack))
return 0;
sexp_stack_length(stack) = new_size;
sexp_stack_top(stack) = sexp_context_top(ctx);
from = sexp_stack_data(old_stack);
to = sexp_stack_data(stack);
for (i=sexp_context_top(ctx)+1; i>=0; i--)
to[i] = from[i];
for (; ctx; ctx=sexp_context_parent(ctx))
if (sexp_context_stack(ctx) == old_stack)
sexp_context_stack(ctx) = stack;
return 1;
}
#else
#define sexp_grow_stack(ctx, min_size) 0
#endif
static sexp sexp_save_stack (sexp ctx, sexp *stack, sexp_uint_t to) {
sexp res, *data;
sexp_uint_t i;
res = sexp_make_vector(ctx, sexp_make_fixnum(to), SEXP_VOID);
data = sexp_vector_data(res);
for (i=0; i<to; i++)
data[i] = stack[i];
return res;
}
static sexp sexp_restore_stack (sexp ctx, sexp saved) {
sexp_uint_t len = sexp_vector_length(saved), i;
sexp *from = sexp_vector_data(saved), *to;
#if SEXP_USE_CHECK_STACK
if ((len+64 >= sexp_stack_length(sexp_context_stack(ctx)))
&& !sexp_grow_stack(ctx, len+64))
return sexp_global(ctx, SEXP_G_OOS_ERROR);
#endif
to = sexp_stack_data(sexp_context_stack(ctx));
for (i=0; i<len; i++)
to[i] = from[i];
sexp_context_top(ctx) = len;
return SEXP_VOID;
}
#define _ARG1 stack[top-1]
#define _ARG2 stack[top-2]
#define _ARG3 stack[top-3]
#define _ARG4 stack[top-4]
#define _ARG5 stack[top-5]
#define _ARG6 stack[top-6]
#define _PUSH(x) (stack[top++]=(x))
#define _POP() (stack[--top])
#if SEXP_USE_ALIGNED_BYTECODE
#define _ALIGN_IP() ip = (unsigned char *)sexp_word_align((sexp_uint_t)ip)
#else
#define _ALIGN_IP()
#endif
#define _WORD0 ((sexp*)ip)[0]
#define _UWORD0 ((sexp_uint_t*)ip)[0]
#define _SWORD0 ((sexp_sint_t*)ip)[0]
#define _WORD1 ((sexp*)ip)[1]
#define _UWORD1 ((sexp_uint_t*)ip)[1]
#define _SWORD1 ((sexp_sint_t*)ip)[1]
#define _WORD2 ((sexp*)ip)[2]
#define sexp_raise(msg, args) \
do {sexp_context_top(ctx) = top+1; \
stack[top] = args; \
stack[top] = sexp_user_exception(ctx, self, msg, stack[top]); \
top++; \
goto call_error_handler;} \
while (0)
#define sexp_check_exception() \
do {if (sexp_exceptionp(_ARG1)) { \
goto call_error_handler;}} \
while (0)
static int sexp_check_type(sexp ctx, sexp a, sexp b) {
int d;
sexp t, v;
if (! sexp_pointerp(a))
return 0;
if (sexp_isa(a, b))
return 1;
t = sexp_object_type(ctx, a);
v = sexp_type_cpl(t);
if (! sexp_vectorp(v))
return 0;
if (b == sexp_type_by_index(ctx, SEXP_OBJECT))
return 1;
d = sexp_type_depth(b);
return (d < (int)sexp_vector_length(v))
&& sexp_vector_ref(v, sexp_make_fixnum(d)) == b;
}
#if SEXP_USE_GREEN_THREADS
#define sexp_fcall_return(x, i) \
if (sexp_exceptionp(x)) { \
if (x == sexp_global(ctx, SEXP_G_IO_BLOCK_ERROR)) { \
fuel = 0; ip--; goto loop; \
} else if (x == sexp_global(ctx, SEXP_G_IO_BLOCK_ONCE_ERROR)) { \
stack[top-i+1] = SEXP_ZERO; \
fuel = 0; ip--; goto loop; \
} else { \
top -= i; \
_ARG1 = x; \
ip += sizeof(sexp); \
goto call_error_handler; \
} \
} else { \
top -= i; \
_ARG1 = x; \
ip += sizeof(sexp); \
}
#else
#define sexp_fcall_return(x, i) \
top -= i; _ARG1 = x; ip += sizeof(sexp); sexp_check_exception();
#endif
#if SEXP_USE_EXTENDED_FCALL
#include "opt/fcall.c"
#endif
#if SEXP_USE_PROFILE_VM
sexp_uint_t profile1[SEXP_OP_NUM_OPCODES];
sexp_uint_t profile2[SEXP_OP_NUM_OPCODES][SEXP_OP_NUM_OPCODES];
sexp sexp_reset_vm_profile (sexp ctx, sexp self, sexp_sint_t n) {
int i, j;
for (i=0; i<SEXP_OP_NUM_OPCODES; i++) {
profile1[i] = 0;
for (j=0; j<SEXP_OP_NUM_OPCODES; j++) profile2[i][j] = 0;
}
return SEXP_VOID;
}
sexp sexp_print_vm_profile (sexp ctx, sexp self, sexp_sint_t n) {
int i, j;
for (i=0; i<SEXP_OP_NUM_OPCODES; i++)
fprintf(stderr, "%s %lu\n", sexp_opcode_names[i], profile1[i]);
for (i=0; i<SEXP_OP_NUM_OPCODES; i++)
for (j=0; j<SEXP_OP_NUM_OPCODES; j++)
fprintf(stderr, "%s %s %lu\n", sexp_opcode_names[i],
sexp_opcode_names[j], profile2[i][j]);
return SEXP_VOID;
}
#endif
#if SEXP_USE_DEBUG_THREADS
static const char* sexp_thread_debug_name(sexp ctx) {
if (sexp_stringp(sexp_context_name(ctx)))
return sexp_string_data(sexp_context_name(ctx));
return "?";
}
static char* sexp_thread_debug_event_type(sexp ctx) {
sexp evt = sexp_context_event(ctx);
return sexp_portp(evt) ? "p" : sexp_contextp(evt) ? "c" : "?";
}
static void* sexp_thread_debug_event(sexp ctx) {
return (void*)sexp_context_event(ctx);
}
#endif
#if SEXP_USE_CHECK_STACK
#define sexp_ensure_stack(n) \
if (top+(n) >= sexp_stack_length(sexp_context_stack(ctx))) { \
sexp_context_top(ctx) = top; \
if (sexp_grow_stack(ctx, (n))) { \
stack = sexp_stack_data(sexp_context_stack(ctx)); \
} else { \
_ARG1 = sexp_global(ctx, SEXP_G_OOS_ERROR); \
goto end_loop; \
} \
}
#else
#define sexp_ensure_stack(n)
#endif
/* used only when no thread scheduler has been loaded */
#if SEXP_USE_POLL_PORT
int sexp_poll_port(sexp ctx, sexp port, int inputp) {
fd_set fds;
struct timeval timeout;
int fd = sexp_port_fileno(port);
if (fd < 0) {
usleep(SEXP_POLL_SLEEP_TIME);
return -1;
}
FD_ZERO(&fds);
FD_SET(fd, &fds);
timeout.tv_sec = 0;
timeout.tv_usec = 10000; /* 10millis */
return select(1, (inputp ? &fds : NULL), (inputp ? NULL : &fds), NULL, &timeout);
}
#endif
sexp sexp_apply (sexp ctx, sexp proc, sexp args) {
unsigned char *ip;
sexp bc, cp, *stack = sexp_stack_data(sexp_context_stack(ctx)), tmp;
sexp_sint_t i, j, k, fp, top = sexp_stack_top(sexp_context_stack(ctx));
#if SEXP_USE_GREEN_THREADS
sexp root_thread = ctx;
sexp_sint_t fuel = sexp_context_refuel(ctx);
#endif
#if SEXP_USE_PROFILE_VM
unsigned char last_op = SEXP_OP_NOOP;
#endif
#if SEXP_USE_BIGNUMS
sexp_lsint_t prod;
#endif
sexp_gc_var3(self, tmp1, tmp2);
sexp_gc_preserve3(ctx, self, tmp1, tmp2);
fp = top - 4;
self = sexp_global(ctx, SEXP_G_FINAL_RESUMER);
bc = sexp_procedure_code(self);
cp = sexp_procedure_vars(self);
ip = sexp_bytecode_data(bc) - sizeof(sexp);
tmp1 = proc, tmp2 = args;
i = sexp_unbox_fixnum(sexp_length(ctx, tmp2));
sexp_ensure_stack(i + 64 + (sexp_procedurep(tmp1) ? sexp_bytecode_max_depth(sexp_procedure_code(tmp1)) : 0));
for (top += i; sexp_pairp(tmp2); tmp2=sexp_cdr(tmp2), top--)
_ARG1 = sexp_car(tmp2);
top += i+1;
goto make_call;
loop:
#if SEXP_USE_GREEN_THREADS
if (--fuel <= 0) {
if (sexp_context_interruptp(ctx)) {
fuel = sexp_context_refuel(ctx);
sexp_context_interruptp(ctx) = 0;
_ARG1 = sexp_global(ctx, SEXP_G_INTERRUPT_ERROR);
goto call_error_handler;
}
tmp1 = sexp_global(ctx, SEXP_G_THREADS_SCHEDULER);
if (sexp_applicablep(tmp1) && sexp_not(sexp_global(ctx, SEXP_G_ATOMIC_P))) {
/* save thread */
sexp_context_top(ctx) = top;
sexp_context_ip(ctx) = ip;
sexp_context_last_fp(ctx) = fp;
sexp_context_proc(ctx) = self;
/* run scheduler */
#if SEXP_USE_DEBUG_THREADS
tmp2 = ctx;
#endif
ctx = sexp_apply1(ctx, tmp1, root_thread);
/* restore thread */
stack = sexp_stack_data(sexp_context_stack(ctx));
top = sexp_context_top(ctx);
fp = sexp_context_last_fp(ctx);
ip = sexp_context_ip(ctx);
self = sexp_context_proc(ctx);
bc = sexp_procedure_code(self);
cp = sexp_procedure_vars(self);
#if SEXP_USE_DEBUG_THREADS
if (ctx != tmp2) {
fprintf(stderr, "****** schedule %p: %p (%s) active:",
root_thread, ctx, sexp_thread_debug_name(ctx));
for (tmp1=sexp_global(ctx, SEXP_G_THREADS_FRONT); sexp_pairp(tmp1); tmp1=sexp_cdr(tmp1))
fprintf(stderr, " %p (%s)", sexp_car(tmp1), sexp_thread_debug_name(sexp_car(tmp1)));
fprintf(stderr, " paused:");
for (tmp1=sexp_global(ctx, SEXP_G_THREADS_PAUSED); sexp_pairp(tmp1); tmp1=sexp_cdr(tmp1))
fprintf(stderr, " %p (%s) [%s %p]", sexp_car(tmp1), sexp_thread_debug_name(sexp_car(tmp1)), sexp_thread_debug_event_type(sexp_car(tmp1)), sexp_thread_debug_event(sexp_car(tmp1)));
fprintf(stderr, " ******\n");
}
#endif
}
fuel = sexp_context_refuel(ctx);
if (fuel <= 0) goto end_loop;
if (sexp_context_waitp(ctx)) {
fuel = 1;
goto loop; /* we were still waiting, try again */
}
}
#endif
#if SEXP_USE_DEBUG_VM
if (sexp_context_tracep(ctx)) {
sexp_print_stack(ctx, stack, top, fp, SEXP_FALSE);
fprintf(stderr, "****** VM %s %s ip: %p stack: %p top: %ld fp: %ld (%ld)\n",
(*ip<=SEXP_OP_NUM_OPCODES) ? sexp_opcode_names[*ip] : "UNKNOWN",
(SEXP_OP_FCALL0 <= *ip && *ip <= SEXP_OP_FCALL4
? sexp_string_data(sexp_opcode_name(((sexp*)(ip+1))[0])) : ""),
ip, stack, top, fp, (fp<1024 ? sexp_unbox_fixnum(stack[fp+3]) : -1));
}
#endif
#if SEXP_USE_PROFILE_VM
profile1[*ip]++;
profile2[last_op][*ip]++;
last_op = *ip;
#endif
switch (*ip++) {
case SEXP_OP_NOOP:
break;
call_error_handler:
if (! sexp_exception_procedure(_ARG1))
sexp_exception_procedure(_ARG1) = self;
#if SEXP_USE_FULL_SOURCE_INFO
if (sexp_not(sexp_exception_source(_ARG1))
&& sexp_procedurep(sexp_exception_procedure(_ARG1))
&& sexp_procedure_source(sexp_exception_procedure(_ARG1)))
sexp_exception_source(_ARG1) = sexp_lookup_source_info(sexp_exception_procedure(_ARG1), (ip-sexp_bytecode_data(bc)));
#endif
case SEXP_OP_RAISE:
sexp_context_top(ctx) = top;
if (sexp_trampolinep(_ARG1)) {
tmp1 = sexp_trampoline_procedure(_ARG1);
tmp2 = sexp_trampoline_args(_ARG1);
if (sexp_trampoline_abortp(_ARG1)) { /* abort - do not catch */
_ARG1 = tmp2;
goto end_loop;
}
top--;
if (sexp_not(tmp1) && sexp_pairp(tmp2)) { /* noop trampoline is */
_PUSH(sexp_car(tmp2)); /* a wrapped exception */
goto loop;
}
goto apply1;
}
tmp1 = sexp_parameter_ref(ctx, sexp_global(ctx, SEXP_G_ERR_HANDLER));
sexp_context_last_fp(ctx) = fp;
if (! sexp_procedurep(tmp1)) {
#if SEXP_USE_GREEN_THREADS
sexp_context_errorp(ctx) = 1;
#endif
if (!sexp_exceptionp(_ARG1)) {
_ARG1 = sexp_make_exception(ctx, SEXP_UNCAUGHT, SEXP_FALSE, _ARG1, self, SEXP_FALSE);
}
sexp_context_top(ctx) = top;
sexp_exception_stack_trace(_ARG1) = sexp_get_stack_trace(ctx);
goto end_loop;
}
stack[top] = SEXP_ONE;
stack[top+1] = sexp_make_fixnum(ip-sexp_bytecode_data(bc));
stack[top+2] = self;
stack[top+3] = sexp_make_fixnum(fp);
top += 4;
self = tmp1;
bc = sexp_procedure_code(self);
ip = sexp_bytecode_data(bc);
cp = sexp_procedure_vars(self);
fp = top-4;
break;
case SEXP_OP_RESUMECC:
sexp_context_top(ctx) = top;
tmp1 = stack[fp-1];
tmp2 = sexp_restore_stack(ctx, sexp_vector_ref(cp, 0));
if (sexp_exceptionp(tmp2)) {_ARG1 = tmp2; goto call_error_handler;}
top = sexp_context_top(ctx);
fp = sexp_unbox_fixnum(_ARG1);
self = _ARG2;
bc = sexp_procedure_code(self);
cp = sexp_procedure_vars(self);
ip = sexp_bytecode_data(bc) + sexp_unbox_fixnum(_ARG3);
top -= 4;
_ARG1 = tmp1;
break;
case SEXP_OP_CALLCC:
stack[top] = SEXP_ONE;
stack[top+1] = sexp_make_fixnum(ip-sexp_bytecode_data(bc));
stack[top+2] = self;
stack[top+3] = sexp_make_fixnum(fp);
tmp1 = _ARG1;
i = 1;
sexp_context_top(ctx) = top;
tmp2 = sexp_make_vector(ctx, SEXP_ONE, SEXP_UNDEF);
sexp_vector_set(tmp2, SEXP_ZERO, sexp_save_stack(ctx, stack, top+4));
_ARG1 = sexp_make_procedure(ctx,
SEXP_ZERO,
SEXP_ONE,
sexp_global(ctx, SEXP_G_RESUMECC_BYTECODE),
tmp2);
top++;
ip -= sizeof(sexp);
goto make_call;
case SEXP_OP_APPLY1:
tmp1 = _ARG1;
tmp2 = _ARG2;
apply1:
tmp = sexp_length(ctx, tmp2);
if (sexp_not(tmp))
sexp_raise("apply: circular list", sexp_list1(ctx, tmp2));
i = sexp_unbox_fixnum(tmp); /* number of params */
sexp_ensure_stack(i + 64 + (sexp_procedurep(tmp1) ? sexp_bytecode_max_depth(sexp_procedure_code(tmp1)) : 0));
k = sexp_unbox_fixnum(stack[fp+3]); /* previous fp */
j = sexp_unbox_fixnum(stack[fp]); /* previous num params */
self = stack[fp+2];
bc = sexp_procedure_code(self);
cp = sexp_procedure_vars(self);
ip = (sexp_bytecode_data(bc)+sexp_unbox_fixnum(stack[fp+1])) - sizeof(sexp);
{
int prev_top = top;
for (top=fp-j+i-1; sexp_pairp(tmp2); tmp2=sexp_cdr(tmp2), top--)
stack[top] = sexp_car(tmp2);
top = fp+i-j+1;
fp = k;
/* if final cdr of tmp2 isn't null, then args list was improper */
if (! sexp_nullp(tmp2)) {
top = prev_top;
sexp_raise("apply: improper args list", sexp_list1(ctx, stack[prev_top-2]));
}
}
goto make_call;
case SEXP_OP_TAIL_CALL:
_ALIGN_IP();
i = sexp_unbox_fixnum(_WORD0); /* number of params */
tmp1 = _ARG1; /* procedure to call */
/* save frame info */
tmp2 = stack[fp+3]; /* previous fp */
j = sexp_unbox_fixnum(stack[fp]); /* previous num params */
self = stack[fp+2];
bc = sexp_procedure_code(self);
cp = sexp_procedure_vars(self);
ip = (sexp_bytecode_data(bc)+sexp_unbox_fixnum(stack[fp+1])) - sizeof(sexp);
/* copy new args into place */
for (k=0; k<i; k++)
stack[fp-j+k] = stack[top-1-i+k];
top = fp+i-j+1;
fp = sexp_unbox_fixnum(tmp2);
goto make_call;
case SEXP_OP_CALL:
_ALIGN_IP();
i = sexp_unbox_fixnum(_WORD0);
tmp1 = _ARG1;
make_call:
sexp_context_top(ctx) = top;
if (sexp_opcodep(tmp1)) {
/* compile non-inlined opcode applications on the fly */
tmp1 = make_opcode_procedure(ctx, tmp1, i, SEXP_PROC_NONE);
if (sexp_exceptionp(tmp1)) {
_ARG1 = tmp1;
goto call_error_handler;
}
}
if (! sexp_procedurep(tmp1))
sexp_raise("non procedure application", sexp_list1(ctx, tmp1));
j = i - sexp_procedure_num_args(tmp1);
if (j < 0)
sexp_raise("not enough args",
sexp_list2(ctx, tmp1, sexp_make_fixnum(i)));
/* ensure there's sufficient stack space before pushing args */
sexp_ensure_stack(sexp_bytecode_max_depth(sexp_procedure_code(tmp1))+64);
if (j > 0) {
if (sexp_procedure_variadic_p(tmp1)) {
if (!sexp_procedure_unused_rest_p(tmp1)) {
stack[top-i-1] = sexp_cons(ctx, stack[top-i-1], SEXP_NULL);
for (k=top-i; k<top-(i-j)-1; k++)
stack[top-i-1] = sexp_cons(ctx, stack[k], stack[top-i-1]);
for ( ; k<top; k++)
stack[k-j+1] = stack[k];
top -= (j-1);
i -= (j-1);
}
} else {
sexp_raise("too many args", sexp_list2(ctx, tmp1, sexp_make_fixnum(i)));
}
} else if (sexp_procedure_variadic_p(tmp1) &&
!sexp_procedure_unused_rest_p(tmp1)) {
/* shift stack, set extra arg to null */
for (k=top; k>=top-i; k--)
stack[k] = stack[k-1];
stack[top-i-1] = SEXP_NULL;
top++;
i++;
}
_ARG1 = sexp_make_fixnum(i);
stack[top] = sexp_make_fixnum(ip+sizeof(sexp)-sexp_bytecode_data(bc));
stack[top+1] = self;
stack[top+2] = sexp_make_fixnum(fp);
top += 3;
self = tmp1;
bc = sexp_procedure_code(self);
ip = sexp_bytecode_data(bc);
cp = sexp_procedure_vars(self);
fp = top-4;
break;
case SEXP_OP_FCALL0:
_ALIGN_IP();
sexp_context_top(ctx) = top;
sexp_context_last_fp(ctx) = fp;
tmp1 = ((sexp_proc1)sexp_opcode_func(_WORD0))(ctx, _WORD0, 0);
sexp_fcall_return(tmp1, -1)
break;
case SEXP_OP_FCALL1:
_ALIGN_IP();
sexp_context_top(ctx) = top;
sexp_context_last_fp(ctx) = fp;
tmp1 = ((sexp_proc2)sexp_opcode_func(_WORD0))(ctx, _WORD0, 1, _ARG1);
sexp_fcall_return(tmp1, 0)
break;
case SEXP_OP_FCALL2:
_ALIGN_IP();
sexp_context_top(ctx) = top;
sexp_context_last_fp(ctx) = fp;
tmp1 = ((sexp_proc3)sexp_opcode_func(_WORD0))(ctx, _WORD0, 2, _ARG1, _ARG2);
sexp_fcall_return(tmp1, 1)
break;
case SEXP_OP_FCALL3:
_ALIGN_IP();
sexp_context_top(ctx) = top;
sexp_context_last_fp(ctx) = fp;
tmp1 = ((sexp_proc4)sexp_opcode_func(_WORD0))(ctx, _WORD0, 3, _ARG1, _ARG2, _ARG3);
sexp_fcall_return(tmp1, 2)
break;
case SEXP_OP_FCALL4:
_ALIGN_IP();
sexp_context_top(ctx) = top;
sexp_context_last_fp(ctx) = fp;
tmp1 = ((sexp_proc5)sexp_opcode_func(_WORD0))(ctx, _WORD0, 4, _ARG1, _ARG2, _ARG3, _ARG4);
sexp_fcall_return(tmp1, 3)
break;
#if SEXP_USE_EXTENDED_FCALL
case SEXP_OP_FCALLN:
_ALIGN_IP();
sexp_context_top(ctx) = top;
sexp_context_last_fp(ctx) = fp;
i = sexp_opcode_num_args(_WORD0) + sexp_opcode_variadic_p(_WORD0);
tmp1 = sexp_fcall(ctx, self, i, _WORD0);
sexp_fcall_return(tmp1, i-1)
break;
#endif
case SEXP_OP_JUMP_UNLESS:
_ALIGN_IP();
if (stack[--top] == SEXP_FALSE)
ip += _SWORD0;
else
ip += sizeof(sexp_sint_t);
break;
case SEXP_OP_JUMP:
_ALIGN_IP();
ip += _SWORD0;
break;
case SEXP_OP_PUSH:
_ALIGN_IP();
_PUSH(_WORD0);
ip += sizeof(sexp);
break;
#if SEXP_USE_RESERVE_OPCODE
case SEXP_OP_RESERVE:
_ALIGN_IP();
for (i=_SWORD0; i > 0; i--)
stack[top++] = SEXP_VOID;
ip += sizeof(sexp);
break;
#endif
case SEXP_OP_DROP:
top--;
break;
case SEXP_OP_GLOBAL_REF:
_ALIGN_IP();
if (sexp_cdr(_WORD0) == SEXP_UNDEF) {
/* handle renamed forward references by doing a final delayed */
/* lookup before throwing an undefined variable error */
if (sexp_synclop(sexp_car(_WORD0))) {
tmp1 = sexp_env_cell(ctx, sexp_synclo_env(sexp_car(_WORD0)), sexp_synclo_expr(sexp_car(_WORD0)), 0);
if (tmp1 != NULL) _WORD0 = tmp1;
}
if (sexp_cdr(_WORD0) == SEXP_UNDEF)
sexp_raise("undefined variable", sexp_list1(ctx, sexp_car(_WORD0)));
}
/* ... FALLTHROUGH ... */
case SEXP_OP_GLOBAL_KNOWN_REF:
_ALIGN_IP();
_PUSH(sexp_cdr(_WORD0));
ip += sizeof(sexp);
break;
#if SEXP_USE_GREEN_THREADS
case SEXP_OP_PARAMETER_REF:
_ALIGN_IP();
sexp_context_top(ctx) = top;
tmp2 = _WORD0;
ip += sizeof(sexp);
for (tmp1=sexp_context_params(ctx); sexp_pairp(tmp1); tmp1=sexp_cdr(tmp1))
if (sexp_caar(tmp1) == tmp2) {
_PUSH(sexp_car(tmp1));
goto loop;
}
_PUSH(sexp_opcode_data(tmp2));
break;
#endif
case SEXP_OP_STACK_REF:
_ALIGN_IP();
stack[top] = stack[top - _SWORD0];
ip += sizeof(sexp);
top++;
break;
case SEXP_OP_LOCAL_REF:
_ALIGN_IP();
stack[top] = stack[fp - 1 - _SWORD0];
ip += sizeof(sexp);
top++;
break;
case SEXP_OP_LOCAL_SET:
_ALIGN_IP();
stack[fp - 1 - _SWORD0] = _POP();
ip += sizeof(sexp);
break;
case SEXP_OP_CLOSURE_REF:
_ALIGN_IP();
_PUSH(sexp_vector_ref(cp, sexp_make_fixnum(_SWORD0)));
ip += sizeof(sexp);
break;
case SEXP_OP_CLOSURE_VARS:
_ARG1 = sexp_procedure_vars(_ARG1);
break;
case SEXP_OP_VECTOR_REF:
if (! sexp_vectorp(_ARG1))
sexp_raise("vector-ref: not a vector", sexp_list1(ctx, _ARG1));
else if (! sexp_fixnump(_ARG2))
sexp_raise("vector-ref: not an integer", sexp_list1(ctx, _ARG2));
i = sexp_unbox_fixnum(_ARG2);
if ((i < 0) || (i >= (sexp_sint_t)sexp_vector_length(_ARG1)))
sexp_raise("vector-ref: index out of range", sexp_list2(ctx, _ARG1, _ARG2));
_ARG2 = sexp_vector_ref(_ARG1, _ARG2);
top--;
break;
case SEXP_OP_VECTOR_SET:
if (! sexp_vectorp(_ARG1))
sexp_raise("vector-set!: not a vector", sexp_list1(ctx, _ARG1));
else if (sexp_immutablep(_ARG1))
sexp_raise("vector-set!: immutable vector", sexp_list1(ctx, _ARG1));
else if (! sexp_fixnump(_ARG2))
sexp_raise("vector-set!: not an integer", sexp_list1(ctx, _ARG2));
i = sexp_unbox_fixnum(_ARG2);
if ((i < 0) || (i >= (sexp_sint_t)sexp_vector_length(_ARG1)))
sexp_raise("vector-set!: index out of range", sexp_list2(ctx, _ARG1, _ARG2));
sexp_vector_set(_ARG1, _ARG2, _ARG3);
top-=3;
break;
case SEXP_OP_VECTOR_LENGTH:
if (! sexp_vectorp(_ARG1))
sexp_raise("vector-length: not a vector", sexp_list1(ctx, _ARG1));
_ARG1 = sexp_make_fixnum(sexp_vector_length(_ARG1));
break;
case SEXP_OP_BYTES_REF:
if (! sexp_bytesp(_ARG1))
sexp_raise("byte-vector-ref: not a byte-vector", sexp_list1(ctx, _ARG1));
if (! sexp_fixnump(_ARG2))
sexp_raise("byte-vector-ref: not an integer", sexp_list1(ctx, _ARG2));
i = sexp_unbox_fixnum(_ARG2);
if ((i < 0) || (i >= (sexp_sint_t)sexp_bytes_length(_ARG1)))
sexp_raise("byte-vector-ref: index out of range", sexp_list2(ctx, _ARG1, _ARG2));
_ARG2 = sexp_bytes_ref(_ARG1, _ARG2);
top--;
break;
case SEXP_OP_STRING_REF:
if (! sexp_stringp(_ARG1))
sexp_raise("string-cursor-ref: not a string", sexp_list1(ctx, _ARG1));
else if (! sexp_string_cursorp(_ARG2))
sexp_raise("string-cursor-ref: not a string-cursor", sexp_list1(ctx, _ARG2));
i = sexp_unbox_string_cursor(_ARG2);
if ((i < 0) || (i >= (sexp_sint_t)sexp_string_size(_ARG1)))
sexp_raise("string-ref: index out of range", sexp_list2(ctx, _ARG1, _ARG2));
_ARG2 = sexp_string_cursor_ref(ctx, _ARG1, _ARG2);
top--;
sexp_check_exception();
break;
case SEXP_OP_BYTES_SET:
if (! sexp_bytesp(_ARG1))
sexp_raise("byte-vector-set!: not a byte-vector", sexp_list1(ctx, _ARG1));
else if (sexp_immutablep(_ARG1))
sexp_raise("byte-vector-set!: immutable byte-vector", sexp_list1(ctx, _ARG1));
else if (! sexp_fixnump(_ARG2))
sexp_raise("byte-vector-set!: not an integer", sexp_list1(ctx, _ARG2));
else if (!(sexp_fixnump(_ARG3) && sexp_unbox_fixnum(_ARG3)>=0
&& sexp_unbox_fixnum(_ARG3)<0x100))
sexp_raise("byte-vector-set!: not an octet", sexp_list1(ctx, _ARG3));
i = sexp_unbox_fixnum(_ARG2);
if ((i < 0) || (i >= (sexp_sint_t)sexp_bytes_length(_ARG1)))
sexp_raise("byte-vector-set!: index out of range", sexp_list2(ctx, _ARG1, _ARG2));
sexp_bytes_set(_ARG1, _ARG2, _ARG3);
top-=3;
break;
#if SEXP_USE_MUTABLE_STRINGS
case SEXP_OP_STRING_SET:
if (! sexp_stringp(_ARG1))
sexp_raise("string-cursor-set!: not a string", sexp_list1(ctx, _ARG1));
else if (sexp_immutablep(_ARG1))
sexp_raise("string-cursor-set!: immutable string", sexp_list1(ctx, _ARG1));
else if (! sexp_string_cursorp(_ARG2))
sexp_raise("string-cursor-set!: not a string-cursor", sexp_list1(ctx, _ARG2));
else if (! sexp_charp(_ARG3))
sexp_raise("string-cursor-set!: not a char", sexp_list1(ctx, _ARG3));
i = sexp_unbox_string_cursor(_ARG2);
if ((i < 0) || (i >= (sexp_sint_t)sexp_string_size(_ARG1)))
sexp_raise("string-cursor-set!: index out of range", sexp_list2(ctx, _ARG1, _ARG2));
sexp_context_top(ctx) = top;
sexp_string_set(ctx, _ARG1, _ARG2, _ARG3);
top-=3;
break;
#endif
#if SEXP_USE_UTF8_STRINGS
case SEXP_OP_STRING_CURSOR_NEXT:
if (! sexp_stringp(_ARG1))
sexp_raise("string-cursor-next: not a string", sexp_list1(ctx, _ARG1));
else if (! sexp_string_cursorp(_ARG2))
sexp_raise("string-cursor-next: not a string-cursor", sexp_list1(ctx, _ARG2));
_ARG2 = sexp_string_cursor_next(_ARG1, _ARG2);
top--;
sexp_check_exception();
break;
case SEXP_OP_STRING_CURSOR_PREV:
if (! sexp_stringp(_ARG1))
sexp_raise("string-cursor-prev: not a string", sexp_list1(ctx, _ARG1));
else if (! sexp_string_cursorp(_ARG2))
sexp_raise("string-cursor-prev: not a string-cursor", sexp_list1(ctx, _ARG2));
_ARG2 = sexp_string_cursor_prev(_ARG1, _ARG2);
top--;
sexp_check_exception();
break;
case SEXP_OP_STRING_CURSOR_END:
if (! sexp_stringp(_ARG1))
sexp_raise("string-cursor-end: not a string", sexp_list1(ctx, _ARG1));
_ARG1 = sexp_make_string_cursor(sexp_string_size(_ARG1));
break;
#endif
case SEXP_OP_BYTES_LENGTH:
if (! sexp_bytesp(_ARG1))
sexp_raise("bytes-length: not a byte-vector", sexp_list1(ctx, _ARG1));
_ARG1 = sexp_make_fixnum(sexp_bytes_length(_ARG1));
break;
case SEXP_OP_STRING_LENGTH:
if (! sexp_stringp(_ARG1))
sexp_raise("string-length: not a string", sexp_list1(ctx, _ARG1));
_ARG1 = sexp_make_fixnum(sexp_string_length(_ARG1));
break;
case SEXP_OP_MAKE_PROCEDURE:
sexp_context_top(ctx) = top;
_ALIGN_IP();
_ARG1 = sexp_make_procedure(ctx, _WORD0, _WORD1, _WORD2, _ARG1);
ip += (3 * sizeof(sexp));
break;
case SEXP_OP_MAKE_VECTOR:
sexp_context_top(ctx) = top;
if (! sexp_fixnump(_ARG1))
sexp_raise("make-vector: not an integer", sexp_list1(ctx, _ARG1));
if (sexp_unbox_fixnum(_ARG1) < 0)
sexp_raise("make-vector: length must be non-negative", sexp_list1(ctx, _ARG1));
_ARG2 = sexp_make_vector(ctx, _ARG1, _ARG2);
top--;
break;
case SEXP_OP_MAKE_EXCEPTION:
sexp_context_top(ctx) = top;
_ARG5 = sexp_make_exception(ctx, _ARG1, _ARG2, _ARG3, _ARG4, _ARG5);
top -= 4;
break;
case SEXP_OP_AND:
_ARG2 = sexp_make_boolean((_ARG1 != SEXP_FALSE) && (_ARG2 != SEXP_FALSE));
top--;
break;
case SEXP_OP_EOFP:
_ARG1 = sexp_make_boolean(_ARG1 == SEXP_EOF); break;
case SEXP_OP_NULLP:
_ARG1 = sexp_make_boolean(sexp_nullp(_ARG1)); break;
case SEXP_OP_FIXNUMP:
_ARG1 = sexp_make_boolean(sexp_fixnump(_ARG1)); break;
case SEXP_OP_SYMBOLP:
_ARG1 = sexp_make_boolean(sexp_symbolp(_ARG1)); break;
case SEXP_OP_CHARP:
_ARG1 = sexp_make_boolean(sexp_charp(_ARG1)); break;
case SEXP_OP_ISA:
tmp1 = _ARG1, tmp2 = _ARG2;
if (! sexp_typep(tmp2)) sexp_raise("is-a?: not a type", tmp2);
top--;
goto do_check_type;
case SEXP_OP_TYPEP:
_ALIGN_IP();
tmp1 = _ARG1, tmp2 = sexp_type_by_index(ctx, _UWORD0);
ip += sizeof(sexp);
do_check_type:
_ARG1 = sexp_make_boolean(sexp_check_type(ctx, tmp1, tmp2));
break;
case SEXP_OP_MAKE:
_ALIGN_IP();
sexp_context_top(ctx) = top;
_PUSH(sexp_alloc_tagged(ctx, _UWORD1, _UWORD0));
/* initialize fields to void */
for (i=(_UWORD1-sexp_sizeof_header)/sizeof(sexp_uint_t) - 1; i>=0; i--)
sexp_slot_set(_ARG1, i, SEXP_VOID);
ip += sizeof(sexp)*2;
break;
case SEXP_OP_SLOT_REF:
_ALIGN_IP();
if (! sexp_check_type(ctx, _ARG1, sexp_type_by_index(ctx, _UWORD0)))
sexp_raise("slot-ref: bad type", sexp_list2(ctx, sexp_type_name_by_index(ctx, _UWORD0), _ARG1));
_ARG1 = sexp_slot_ref(_ARG1, _UWORD1);
ip += sizeof(sexp)*2;
break;
case SEXP_OP_SLOT_SET:
_ALIGN_IP();
if (! sexp_check_type(ctx, _ARG1, sexp_type_by_index(ctx, _UWORD0)))
sexp_raise("slot-set!: bad type", sexp_list2(ctx, sexp_type_name_by_index(ctx, _UWORD0), _ARG1));
else if (sexp_immutablep(_ARG1))
sexp_raise("slot-set!: immutable object", sexp_list1(ctx, _ARG1));
sexp_slot_set(_ARG1, _UWORD1, _ARG2);
ip += sizeof(sexp)*2;
top-=2;
break;
case SEXP_OP_SLOTN_REF:
if (! sexp_typep(_ARG1))
sexp_raise("slotn-ref: not a record type", sexp_list1(ctx, _ARG1));
else if (! sexp_check_type(ctx, _ARG2, _ARG1))
sexp_raise("slotn-ref: bad type", sexp_list1(ctx, _ARG2));
if (! sexp_fixnump(_ARG3))
for (i = 0, tmp1 = sexp_type_slots(_ARG1); sexp_pairp(tmp1); tmp1 = sexp_cdr(tmp1), ++i)
if (sexp_car(tmp1) == _ARG3) { _ARG3 = sexp_make_fixnum(i); break; }
if (! sexp_fixnump(_ARG3))
sexp_raise("slotn-ref: not an integer", sexp_list1(ctx, _ARG3));
if (sexp_vectorp(sexp_type_getters(_ARG1))) {
if (sexp_unbox_fixnum(_ARG3) < 0 || sexp_unbox_fixnum(_ARG3) >= (sexp_sint_t)sexp_vector_length(sexp_type_getters(_ARG1)))
sexp_raise("slotn-ref: slot out of bounds", sexp_list2(ctx, _ARG3, sexp_make_fixnum(sexp_type_field_len_base(_ARG1))));
tmp1 = sexp_vector_ref(sexp_type_getters(_ARG1), _ARG3);
if (sexp_opcodep(tmp1))
_ARG3 = ((sexp_proc2)sexp_opcode_func(tmp1))(ctx, tmp1, 1, _ARG2);
else
sexp_raise("slotn-ref: no getter defined", sexp_list1(ctx, _ARG3));
} else {
if (sexp_unbox_fixnum(_ARG3) < 0 || sexp_unbox_fixnum(_ARG3) >= sexp_type_field_len_base(_ARG1))
sexp_raise("slotn-ref: slot out of bounds", sexp_list2(ctx, _ARG3, sexp_make_fixnum(sexp_type_field_len_base(_ARG1))));
_ARG3 = sexp_slot_ref(_ARG2, sexp_unbox_fixnum(_ARG3));
}
top-=2;
if (!_ARG1) _ARG1 = SEXP_VOID;
else sexp_check_exception();
break;
case SEXP_OP_SLOTN_SET:
if (! sexp_typep(_ARG1))
sexp_raise("slotn-set!: not a record type", sexp_list1(ctx, _ARG1));
else if (! sexp_check_type(ctx, _ARG2, _ARG1))
sexp_raise("slotn-set!: bad type", sexp_list1(ctx, _ARG2));
else if (sexp_immutablep(_ARG2))
sexp_raise("slotn-set!: immutable object", sexp_list1(ctx, _ARG2));
if (! sexp_fixnump(_ARG3))
for (i = 0, tmp1 = sexp_type_slots(_ARG1); sexp_pairp(tmp1); tmp1 = sexp_cdr(tmp1), ++i)
if (sexp_car(tmp1) == _ARG3) { _ARG3 = sexp_make_fixnum(i); break; }
if (! sexp_fixnump(_ARG3))
sexp_raise("slotn-set!: not an integer", sexp_list1(ctx, _ARG3));
if (sexp_vectorp(sexp_type_setters(_ARG1))) {
if (sexp_unbox_fixnum(_ARG3) < 0 || sexp_unbox_fixnum(_ARG3) >= (sexp_sint_t)sexp_vector_length(sexp_type_setters(_ARG1)))
sexp_raise("slotn-set!: slot out of bounds", sexp_list2(ctx, _ARG3, sexp_make_fixnum(sexp_type_field_len_base(_ARG1))));
tmp1 = sexp_vector_ref(sexp_type_setters(_ARG1), _ARG3);
if (sexp_opcodep(tmp1))
_ARG4 = ((sexp_proc3)sexp_opcode_func(tmp1))(ctx, tmp1, 2, _ARG2, _ARG4);
else
sexp_raise("slotn-set!: no setter defined", sexp_list1(ctx, _ARG3));
} else {
if (sexp_unbox_fixnum(_ARG3) < 0 || sexp_unbox_fixnum(_ARG3) >= sexp_type_field_len_base(_ARG1))
sexp_raise("slotn-set!: slot out of bounds", sexp_list2(ctx, _ARG3, sexp_make_fixnum(sexp_type_field_len_base(_ARG1))));
sexp_slot_set(_ARG2, sexp_unbox_fixnum(_ARG3), _ARG4);
}
top-=4;
sexp_check_exception();
break;
case SEXP_OP_CAR:
if (! sexp_pairp(_ARG1))
sexp_raise("car: not a pair", sexp_list1(ctx, _ARG1));
_ARG1 = sexp_car(_ARG1); break;
case SEXP_OP_CDR:
if (! sexp_pairp(_ARG1))
sexp_raise("cdr: not a pair", sexp_list1(ctx, _ARG1));
_ARG1 = sexp_cdr(_ARG1); break;
case SEXP_OP_SET_CAR:
if (! sexp_pairp(_ARG1))
sexp_raise("set-car!: not a pair", sexp_list1(ctx, _ARG1));
else if (sexp_immutablep(_ARG1))
sexp_raise("set-car!: immutable pair", sexp_list1(ctx, _ARG1));
sexp_car(_ARG1) = _ARG2;
top-=2;
break;
case SEXP_OP_SET_CDR:
if (! sexp_pairp(_ARG1))
sexp_raise("set-cdr!: not a pair", sexp_list1(ctx, _ARG1));
else if (sexp_immutablep(_ARG1))
sexp_raise("set-cdr!: immutable pair", sexp_list1(ctx, _ARG1));
sexp_cdr(_ARG1) = _ARG2;
top-=2;
break;
case SEXP_OP_CONS:
sexp_context_top(ctx) = top;
_ARG2 = sexp_cons(ctx, _ARG1, _ARG2);
top--;
break;
case SEXP_OP_ADD:
tmp1 = _ARG1, tmp2 = _ARG2;
sexp_context_top(ctx) = --top;
#if SEXP_USE_BIGNUMS
if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2)) {
j = sexp_unbox_fixnum(tmp1) + sexp_unbox_fixnum(tmp2);
if ((j < SEXP_MIN_FIXNUM) || (j > SEXP_MAX_FIXNUM))
_ARG1 = sexp_add(ctx, tmp1=sexp_fixnum_to_bignum(ctx, tmp1), tmp2);
else
_ARG1 = sexp_make_fixnum(j);
}
else {
_ARG1 = sexp_add(ctx, tmp1, tmp2);
sexp_check_exception();
}
#else
if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2))
_ARG1 = sexp_fx_add(tmp1, tmp2);
#if SEXP_USE_FLONUMS
else if (sexp_flonump(tmp1) && sexp_flonump(tmp2))
_ARG1 = sexp_fp_add(ctx, tmp1, tmp2);
else if (sexp_flonump(tmp1) && sexp_fixnump(tmp2))
_ARG1 = sexp_make_flonum(ctx, sexp_flonum_value(tmp1) + (double)sexp_unbox_fixnum(tmp2));
else if (sexp_fixnump(tmp1) && sexp_flonump(tmp2))
_ARG1 = sexp_make_flonum(ctx, (double)sexp_unbox_fixnum(tmp1) + sexp_flonum_value(tmp2));
#endif
else sexp_raise("+: not a number", sexp_list2(ctx, tmp1, tmp2));
#endif
break;
case SEXP_OP_SUB:
tmp1 = _ARG1, tmp2 = _ARG2;
sexp_context_top(ctx) = --top;
#if SEXP_USE_BIGNUMS
if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2)) {
j = sexp_unbox_fixnum(tmp1) - sexp_unbox_fixnum(tmp2);
if ((j < SEXP_MIN_FIXNUM) || (j > SEXP_MAX_FIXNUM))
_ARG1 = sexp_sub(ctx, tmp1=sexp_fixnum_to_bignum(ctx, tmp1), tmp2);
else
_ARG1 = sexp_make_fixnum(j);
}
else {
_ARG1 = sexp_sub(ctx, tmp1, tmp2);
sexp_check_exception();
}
#else
if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2))
_ARG1 = sexp_fx_sub(tmp1, tmp2);
#if SEXP_USE_FLONUMS
else if (sexp_flonump(tmp1) && sexp_flonump(tmp2))
_ARG1 = sexp_fp_sub(ctx, tmp1, tmp2);
else if (sexp_flonump(tmp1) && sexp_fixnump(tmp2))
_ARG1 = sexp_make_flonum(ctx, sexp_flonum_value(tmp1) - sexp_fixnum_to_double(tmp2));
else if (sexp_fixnump(tmp1) && sexp_flonump(tmp2))
_ARG1 = sexp_make_flonum(ctx, tmp1==SEXP_ZERO ? -sexp_flonum_value(tmp2) : sexp_fixnum_to_double(tmp1)-sexp_flonum_value(tmp2));
#endif
else sexp_raise("-: not a number", sexp_list2(ctx, tmp1, tmp2));
#endif
break;
case SEXP_OP_MUL:
tmp1 = _ARG1, tmp2 = _ARG2;
sexp_context_top(ctx) = --top;
#if SEXP_USE_BIGNUMS
if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2)) {
prod = lsint_mul_sint(lsint_from_sint(sexp_unbox_fixnum(tmp1)), sexp_unbox_fixnum(tmp2));
if (!lsint_is_fixnum(prod))
_ARG1 = sexp_mul(ctx, tmp1=sexp_fixnum_to_bignum(ctx, tmp1), tmp2);
else
_ARG1 = sexp_make_fixnum(lsint_to_sint(prod));
}
else {
_ARG1 = sexp_mul(ctx, tmp1, tmp2);
sexp_check_exception();
}
#else
if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2))
_ARG1 = sexp_fx_mul(tmp1, tmp2);
#if SEXP_USE_FLONUMS
else if (sexp_flonump(tmp1) && sexp_flonump(tmp2))
_ARG1 = sexp_fp_mul(ctx, tmp1, tmp2);
else if (sexp_flonump(tmp1) && sexp_fixnump(tmp2))
_ARG1 = sexp_make_flonum(ctx, sexp_flonum_value(tmp1) * (double)sexp_unbox_fixnum(tmp2));
else if (sexp_fixnump(tmp1) && sexp_flonump(tmp2))
_ARG1 = sexp_make_flonum(ctx, (double)sexp_unbox_fixnum(tmp1) * sexp_flonum_value(tmp2));
#endif
else sexp_raise("*: not a number", sexp_list2(ctx, tmp1, tmp2));
#endif
break;
case SEXP_OP_DIV:
tmp1 = _ARG1, tmp2 = _ARG2;
sexp_context_top(ctx) = --top;
if (tmp2 == SEXP_ZERO) {
#if SEXP_USE_FLONUMS
if (sexp_flonump(tmp1) && sexp_flonum_value(tmp1) == 0.0)
_ARG1 = sexp_make_flonum(ctx, 0.0);
else
#endif
sexp_raise("divide by zero", SEXP_NULL);
} else if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2)) {
#if SEXP_USE_RATIOS
_ARG1 = sexp_make_ratio(ctx, tmp1, tmp2);
_ARG1 = sexp_ratio_normalize(ctx, _ARG1, SEXP_FALSE);
#else
#if SEXP_USE_FLONUMS
tmp1 = sexp_fixnum_to_flonum(ctx, tmp1);
tmp2 = sexp_fixnum_to_flonum(ctx, tmp2);
_ARG1 = sexp_fp_div(ctx, tmp1, tmp2);
if (sexp_flonum_value(_ARG1) == trunc(sexp_flonum_value(_ARG1)))
_ARG1 = sexp_make_fixnum(sexp_flonum_value(_ARG1));
#else
_ARG1 = sexp_fx_div(tmp1, tmp2);
#endif
#endif
}
#if SEXP_USE_BIGNUMS
else {
_ARG1 = sexp_div(ctx, tmp1, tmp2);
sexp_check_exception();
}
#else
#if SEXP_USE_FLONUMS
else if (sexp_flonump(tmp1) && sexp_flonump(tmp2))
_ARG1 = sexp_fp_div(ctx, tmp1, tmp2);
else if (sexp_flonump(tmp1) && sexp_fixnump(tmp2))
_ARG1 = sexp_make_flonum(ctx, sexp_flonum_value(tmp1) / (double)sexp_unbox_fixnum(tmp2));
else if (sexp_fixnump(tmp1) && sexp_flonump(tmp2))
_ARG1 = sexp_make_flonum(ctx, (double)sexp_unbox_fixnum(tmp1) / sexp_flonum_value(tmp2));
#endif
else sexp_raise("/: not a number", sexp_list2(ctx, tmp1, tmp2));
#endif
break;
case SEXP_OP_QUOTIENT:
tmp1 = _ARG1, tmp2 = _ARG2;
sexp_context_top(ctx) = --top;
if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2)) {
if (tmp2 == SEXP_ZERO)
sexp_raise("divide by zero", SEXP_NULL);
_ARG1 = sexp_fx_div(tmp1, tmp2);
}
#if SEXP_USE_BIGNUMS
else {
_ARG1 = sexp_quotient(ctx, tmp1, tmp2);
sexp_check_exception();
}
#else
else sexp_raise("quotient: not an integer", sexp_list2(ctx, _ARG1, tmp2));
#endif
break;
case SEXP_OP_REMAINDER:
tmp1 = _ARG1, tmp2 = _ARG2;
sexp_context_top(ctx) = --top;
if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2)) {
if (tmp2 == SEXP_ZERO)
sexp_raise("divide by zero", SEXP_NULL);
_ARG1 = sexp_fx_rem(tmp1, tmp2);
}
#if SEXP_USE_BIGNUMS
else {
_ARG1 = sexp_remainder(ctx, tmp1, tmp2);
sexp_check_exception();
}
#else
else sexp_raise("remainder: not an integer", sexp_list2(ctx, _ARG1, tmp2));
#endif
break;
case SEXP_OP_LT:
tmp1 = _ARG1, tmp2 = _ARG2;
sexp_context_top(ctx) = --top;
if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2)) {
i = (sexp_sint_t)tmp1 < (sexp_sint_t)tmp2;
#if SEXP_USE_BIGNUMS
_ARG1 = sexp_make_boolean(i);
} else {
_ARG1 = sexp_compare(ctx, tmp1, tmp2);
if (sexp_exceptionp(_ARG1)) {
if (strcmp("can't compare NaN", sexp_string_data(sexp_exception_message(_ARG1))) == 0)
_ARG1 = SEXP_FALSE;
else
goto call_error_handler;
} else {
_ARG1 = sexp_make_boolean(sexp_unbox_fixnum(_ARG1) < 0);
}
}
#else
#if SEXP_USE_FLONUMS
} else if (sexp_flonump(tmp1) && sexp_flonump(tmp2)) {
i = sexp_flonum_value(tmp1) < sexp_flonum_value(tmp2);
} else if (sexp_flonump(tmp1) && sexp_fixnump(tmp2)) {
i = sexp_flonum_value(tmp1) < (double)sexp_unbox_fixnum(tmp2);
} else if (sexp_fixnump(tmp1) && sexp_flonump(tmp2)) {
i = (double)sexp_unbox_fixnum(tmp1) < sexp_flonum_value(tmp2);
#endif
} else sexp_raise("<: not a number", sexp_list2(ctx, tmp1, tmp2));
_ARG1 = sexp_make_boolean(i);
#endif
break;
case SEXP_OP_LE:
tmp1 = _ARG1, tmp2 = _ARG2;
sexp_context_top(ctx) = --top;
if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2)) {
i = (sexp_sint_t)tmp1 <= (sexp_sint_t)tmp2;
#if SEXP_USE_BIGNUMS
_ARG1 = sexp_make_boolean(i);
} else {
_ARG1 = sexp_compare(ctx, tmp1, tmp2);
if (sexp_exceptionp(_ARG1)) {
if (strcmp("can't compare NaN", sexp_string_data(sexp_exception_message(_ARG1))) == 0)
_ARG1 = SEXP_FALSE;
else
goto call_error_handler;
} else {
_ARG1 = sexp_make_boolean(sexp_unbox_fixnum(_ARG1) <= 0);
}
}
#else
#if SEXP_USE_FLONUMS
} else if (sexp_flonump(tmp1) && sexp_flonump(tmp2)) {
i = sexp_flonum_value(tmp1) <= sexp_flonum_value(tmp2);
} else if (sexp_flonump(tmp1) && sexp_fixnump(tmp2)) {
i = sexp_flonum_value(tmp1) <= (double)sexp_unbox_fixnum(tmp2);
} else if (sexp_fixnump(tmp1) && sexp_flonump(tmp2)) {
i = (double)sexp_unbox_fixnum(tmp1) <= sexp_flonum_value(tmp2);
#endif
} else sexp_raise("<=: not a number", sexp_list2(ctx, tmp1, tmp2));
_ARG1 = sexp_make_boolean(i);
#endif
break;
case SEXP_OP_EQN:
tmp1 = _ARG1, tmp2 = _ARG2;
sexp_context_top(ctx) = --top;
if (sexp_fixnump(tmp1) && sexp_fixnump(tmp2)) {
i = tmp1 == tmp2;
#if SEXP_USE_BIGNUMS
_ARG1 = sexp_make_boolean(i);
} else {
#if SEXP_USE_COMPLEX
if (sexp_complexp(tmp1)) {
if (sexp_flonump(sexp_complex_imag(tmp1))
&& sexp_flonum_value(sexp_complex_imag(tmp1)) == 0.0) {
tmp1 = sexp_complex_real(tmp1);
} else if (sexp_complexp(tmp2)) { /* both complex */
_ARG1 = sexp_make_boolean(
(sexp_compare(ctx, sexp_complex_real(tmp1), sexp_complex_real(tmp2))
== SEXP_ZERO)
&& (sexp_compare(ctx, sexp_complex_imag(tmp1), sexp_complex_imag(tmp2))
== SEXP_ZERO));
break;
} else if (sexp_numberp(tmp2)) {
_ARG1 = SEXP_FALSE;
break;
}
}
if (sexp_complexp(tmp2)) {
if (sexp_flonump(sexp_complex_imag(tmp2))
&& sexp_flonum_value(sexp_complex_imag(tmp2)) == 0.0) {
tmp2 = sexp_complex_real(tmp2);
} else if (sexp_numberp(tmp1)) {
_ARG1 = SEXP_FALSE;
break;
}
}
#endif
/* neither is complex */
_ARG1 = sexp_compare(ctx, tmp1, tmp2);
if (sexp_exceptionp(_ARG1)) {
if (strcmp("can't compare NaN", sexp_string_data(sexp_exception_message(_ARG1))) == 0)
_ARG1 = SEXP_FALSE;
else
goto call_error_handler;
} else {
_ARG1 = sexp_make_boolean(_ARG1 == SEXP_ZERO);
}
}
#else
#if SEXP_USE_FLONUMS
} else if (sexp_flonump(tmp1) && sexp_flonump(tmp2)) {
i = sexp_flonum_value(tmp1) == sexp_flonum_value(tmp2);
} else if (sexp_flonump(tmp1) && sexp_fixnump(tmp2)) {
i = sexp_flonum_value(tmp1) == (double)sexp_unbox_fixnum(tmp2);
} else if (sexp_fixnump(tmp1) && sexp_flonump(tmp2)) {
i = (double)sexp_unbox_fixnum(tmp1) == sexp_flonum_value(tmp2);
#endif
} else sexp_raise("=: not a number", sexp_list2(ctx, tmp1, tmp2));
_ARG1 = sexp_make_boolean(i);
#endif
break;
case SEXP_OP_EQ:
_ARG2 = sexp_make_boolean(_ARG1 == _ARG2);
top--;
break;
case SEXP_OP_SCP:
_ARG1 = sexp_make_boolean(sexp_string_cursorp(_ARG1));
break;
case SEXP_OP_SC_LT:
tmp1 = _ARG1, tmp2 = _ARG2;
sexp_context_top(ctx) = --top;
_ARG1 = sexp_make_boolean((sexp_sint_t)tmp1 < (sexp_sint_t)tmp2);
break;
case SEXP_OP_SC_LE:
tmp1 = _ARG1, tmp2 = _ARG2;
sexp_context_top(ctx) = --top;
_ARG1 = sexp_make_boolean((sexp_sint_t)tmp1 <= (sexp_sint_t)tmp2);
break;
case SEXP_OP_CHAR2INT:
if (! sexp_charp(_ARG1))
sexp_raise("char->integer: not a character", sexp_list1(ctx, _ARG1));
_ARG1 = sexp_make_fixnum(sexp_unbox_character(_ARG1));
break;
case SEXP_OP_INT2CHAR:
if (! sexp_fixnump(_ARG1))
sexp_raise("integer->char: not an integer", sexp_list1(ctx, _ARG1));
_ARG1 = sexp_make_character(sexp_unbox_fixnum(_ARG1));
break;
case SEXP_OP_CHAR_UPCASE:
if (! sexp_charp(_ARG1))
sexp_raise("char-upcase: not a character", sexp_list1(ctx, _ARG1));
_ARG1 = sexp_make_character(sexp_toupper(sexp_unbox_character(_ARG1)));
break;
case SEXP_OP_CHAR_DOWNCASE:
if (! sexp_charp(_ARG1))
sexp_raise("char-downcase: not a character", sexp_list1(ctx, _ARG1));
_ARG1 = sexp_make_character(sexp_tolower(sexp_unbox_character(_ARG1)));
break;
case SEXP_OP_WRITE_CHAR:
if (! sexp_charp(_ARG1))
sexp_raise("write-char: not a character", sexp_list1(ctx, _ARG1));
if (! sexp_oportp(_ARG2))
sexp_raise("write-char: not an output-port", sexp_list1(ctx, _ARG2));
sexp_context_top(ctx) = top;
#if SEXP_USE_GREEN_THREADS
errno = 0;
#endif
#if SEXP_USE_UTF8_STRINGS
if (sexp_unbox_character(_ARG1) >= 0x80)
i = sexp_write_utf8_char(ctx, sexp_unbox_character(_ARG1), _ARG2);
else
#endif
i = sexp_write_char(ctx, sexp_unbox_character(_ARG1), _ARG2);
if ((int)i == EOF) {
if (!sexp_port_openp(_ARG2))
sexp_raise("write-char: port is closed", _ARG2);
else
#if SEXP_USE_GREEN_THREADS
if ((sexp_port_stream(_ARG2) ? ferror(sexp_port_stream(_ARG2)) : 1)
&& (errno == EAGAIN)) {
if (sexp_port_stream(_ARG2)) clearerr(sexp_port_stream(_ARG2));
if (sexp_applicablep(sexp_global(ctx, SEXP_G_THREADS_BLOCKER)))
sexp_apply2(ctx, sexp_global(ctx, SEXP_G_THREADS_BLOCKER), _ARG2, SEXP_FALSE);
else
sexp_poll_output(ctx, _ARG2);
fuel = 0;
ip--; /* try again */
goto loop;
} else
#endif
sexp_raise("failed to write char to port", _ARG2);
}
top--;
_ARG1 = SEXP_VOID;
break;
case SEXP_OP_WRITE_STRING:
if (sexp_stringp(_ARG1))
#if SEXP_USE_PACKED_STRINGS
tmp1 = _ARG1;
#else
tmp1 = sexp_string_bytes(_ARG1);
#endif
else if (sexp_bytesp(_ARG1))
tmp1 = _ARG1;
else
sexp_raise("write-string: not a string or bytes", sexp_list1(ctx, _ARG1));
if (_ARG2 == SEXP_TRUE)
_ARG2 = sexp_make_fixnum(sexp_bytes_length(tmp1));
else if (! sexp_fixnump(_ARG2))
sexp_raise("write-string: not an integer", sexp_list1(ctx, _ARG2));
if (sexp_unbox_fixnum(_ARG2) < 0 || sexp_unbox_fixnum(_ARG2) > (sexp_sint_t)sexp_bytes_length(tmp1))
sexp_raise("write-string: not a valid string count", sexp_list2(ctx, tmp1, _ARG2));
if (! sexp_oportp(_ARG3))
sexp_raise("write-string: not an output-port", sexp_list1(ctx, _ARG3));
if (!sexp_port_openp(_ARG3))
sexp_raise("write-string: port is closed", _ARG3);
sexp_context_top(ctx) = top;
#if SEXP_USE_GREEN_THREADS
errno = 0;
#endif
i = sexp_write_string_n(ctx, sexp_bytes_data(tmp1), sexp_unbox_fixnum(_ARG2), _ARG3);
#if SEXP_USE_GREEN_THREADS
if (i < sexp_unbox_fixnum(_ARG2) && errno == EAGAIN) {
if (sexp_port_stream(_ARG3)) clearerr(sexp_port_stream(_ARG3));
/* modify stack in-place so we continue where we left off next time */
if (i > 0) {
_ARG1 = sexp_subbytes(ctx, tmp1, sexp_make_fixnum(i), SEXP_FALSE);
_ARG2 = sexp_make_fixnum(sexp_unbox_fixnum(_ARG2) - i);
}
/* yield if threads are enabled (otherwise busy loop) */
/* TODO: the wait seems necessary on OS X to stop a print loop to ptys */
if (sexp_applicablep(sexp_global(ctx, SEXP_G_THREADS_BLOCKER)))
sexp_apply2(ctx, sexp_global(ctx, SEXP_G_THREADS_BLOCKER), _ARG3, SEXP_FALSE);
else
sexp_poll_output(ctx, _ARG3);
fuel = 0;
ip--; /* try again */
goto loop;
}
#endif
tmp1 = sexp_make_fixnum(i); /* return the number of bytes written */
top-=2;
_ARG1 = tmp1;
break;
case SEXP_OP_READ_CHAR:
if (! sexp_iportp(_ARG1))
sexp_raise("read-char: not an input-port", sexp_list1(ctx, _ARG1));
sexp_context_top(ctx) = top;
#if SEXP_USE_GREEN_THREADS
errno = 0;
#endif
i = sexp_read_char(ctx, _ARG1);
if ((int)i == EOF) {
if (!sexp_port_openp(_ARG1)) {
sexp_raise("read-char: port is closed", _ARG1);
#if SEXP_USE_GREEN_THREADS
} else if ((sexp_port_stream(_ARG1) ? ferror(sexp_port_stream(_ARG1)) : 1)
&& (errno == EAGAIN)) {
if (sexp_port_stream(_ARG1)) clearerr(sexp_port_stream(_ARG1));
/* TODO: block and unblock */
if (sexp_applicablep(sexp_global(ctx, SEXP_G_THREADS_BLOCKER)))
sexp_apply2(ctx, sexp_global(ctx, SEXP_G_THREADS_BLOCKER), _ARG1, SEXP_FALSE);
else
sexp_poll_input(ctx, _ARG1);
fuel = 0;
ip--; /* try again */
#endif
} else {
_ARG1 = SEXP_EOF;
}
#if SEXP_USE_UTF8_STRINGS
} else if (i >= 0x80) {
_ARG1 = sexp_read_utf8_char(ctx, _ARG1, i);
#endif
} else {
if (i == '\n') sexp_port_line(_ARG1)++;
_ARG1 = sexp_make_character(i);
}
sexp_check_exception();
break;
case SEXP_OP_PEEK_CHAR:
if (! sexp_iportp(_ARG1))
sexp_raise("peek-char: not an input-port", sexp_list1(ctx, _ARG1));
sexp_context_top(ctx) = top;
#if SEXP_USE_GREEN_THREADS
errno = 0;
#endif
i = sexp_read_char(ctx, _ARG1);
if ((int)i == EOF) {
if (!sexp_port_openp(_ARG1))
sexp_raise("peek-char: port is closed", _ARG1);
else
#if SEXP_USE_GREEN_THREADS
if ((sexp_port_stream(_ARG1) ? ferror(sexp_port_stream(_ARG1)) : 1)
&& (errno == EAGAIN)) {
if (sexp_port_stream(_ARG1)) clearerr(sexp_port_stream(_ARG1));
if (sexp_applicablep(sexp_global(ctx, SEXP_G_THREADS_BLOCKER)))
sexp_apply2(ctx, sexp_global(ctx, SEXP_G_THREADS_BLOCKER), _ARG1, SEXP_FALSE);
else
sexp_poll_input(ctx, _ARG1);
fuel = 0;
ip--; /* try again */
} else
#endif
_ARG1 = SEXP_EOF;
#if SEXP_USE_UTF8_STRINGS
} else if (i >= 0x80) {
tmp1 = sexp_read_utf8_char(ctx, _ARG1, i);
sexp_push_utf8_char(ctx, sexp_unbox_character(tmp1), _ARG1);
_ARG1 = tmp1;
#endif
} else {
sexp_push_char(ctx, i, _ARG1);
_ARG1 = sexp_make_character(i);
}
sexp_check_exception();
break;
case SEXP_OP_YIELD:
#if SEXP_USE_GREEN_THREADS
fuel = 0;
#endif
break;
case SEXP_OP_FORCE:
#if SEXP_USE_AUTO_FORCE
sexp_context_top(ctx) = top;
while (sexp_promisep(_ARG1)) {
if (sexp_promise_donep(_ARG1)) {
_ARG1 = sexp_promise_value(_ARG1);
} else {
sexp_context_top(ctx) = top;
tmp1 = sexp_apply(ctx, sexp_promise_value(_ARG1), SEXP_NULL);
if (!sexp_promise_donep(_ARG1)) {
sexp_promise_value(_ARG1) = tmp1;
sexp_promise_donep(_ARG1) = 1;
}
_ARG1 = tmp1;
}
}
#endif
break;
case SEXP_OP_RET:
i = sexp_unbox_fixnum(stack[fp]);
stack[fp-i] = _ARG1;
top = fp-i+1;
self = stack[fp+2];
bc = sexp_procedure_code(self);
ip = sexp_bytecode_data(bc) + sexp_unbox_fixnum(stack[fp+1]);
cp = sexp_procedure_vars(self);
fp = sexp_unbox_fixnum(stack[fp+3]);
break;
case SEXP_OP_DONE:
sexp_context_last_fp(ctx) = fp;
goto end_loop;
default:
sexp_raise("unknown opcode", sexp_list1(ctx, sexp_make_fixnum(*(ip-1))));
}
#if SEXP_USE_DEBUG_VM
if (sexp_context_tracep(ctx))
fprintf(stderr, "****** VM => %p (%d)\n", _ARG1,
sexp_pointerp(_ARG1) && sexp_in_heap_p(ctx, _ARG1)
? sexp_pointer_tag(_ARG1) : -1);
#endif
goto loop;
end_loop:
#if SEXP_USE_GREEN_THREADS
sexp_context_result(ctx) = _ARG1;
if (ctx != root_thread) {
if (sexp_context_refuel(root_thread) <= 0) {
/* the root already terminated */
_ARG1 = sexp_context_result(root_thread);
} else {
/* don't return from child threads */
if (sexp_exceptionp(_ARG1)) {
tmp1 = sexp_current_error_port(ctx);
sexp_write_string(ctx, "ERROR in child thread: ", tmp1);
sexp_write(ctx, ctx, tmp1);
sexp_newline(ctx, tmp1);
sexp_print_exception(ctx, _ARG1, tmp1);
}
#if SEXP_USE_DEBUG_THREADS
fprintf(stderr, "****** schedule %p: terminating %p (%s)\n",
root_thread, ctx, sexp_thread_debug_name(ctx));
#endif
sexp_context_refuel(ctx) = fuel = 0;
goto loop;
}
}
#endif
sexp_gc_release3(ctx);
tmp1 = _ARG1;
sexp_context_top(ctx) = --top;
return tmp1;
}
sexp sexp_apply1 (sexp ctx, sexp f, sexp x) {
sexp res;
sexp_gc_var1(args);
if (sexp_opcodep(f) && sexp_opcode_func(f)) {
res = ((sexp_proc2)sexp_opcode_func(f))(ctx, f, 1, x);
} else {
sexp_gc_preserve1(ctx, args);
res = sexp_apply(ctx, f, args=sexp_list1(ctx, x));
sexp_gc_release1(ctx);
}
return res;
}
sexp sexp_apply2 (sexp ctx, sexp f, sexp x, sexp y) {
sexp res;
sexp_gc_var1(args);
if (sexp_opcodep(f) && sexp_opcode_func(f)) {
res = ((sexp_proc3)sexp_opcode_func(f))(ctx, f, 2, x, y);
} else {
sexp_gc_preserve1(ctx, args);
res = sexp_apply(ctx, f, args=sexp_list2(ctx, x, y));
sexp_gc_release1(ctx);
}
return res;
}
sexp sexp_apply3 (sexp ctx, sexp f, sexp x, sexp y, sexp z) {
sexp res;
sexp_gc_var1(args);
if (sexp_opcodep(f) && sexp_opcode_func(f)) {
res = ((sexp_proc4)sexp_opcode_func(f))(ctx, f, 3, x, y, z);
} else {
sexp_gc_preserve1(ctx, args);
res = sexp_apply(ctx, f, args=sexp_list3(ctx, x, y, z));
sexp_gc_release1(ctx);
}
return res;
}
sexp sexp_apply_no_err_handler (sexp ctx, sexp proc, sexp args) {
sexp res, err_cell;
sexp_gc_var2(handler, params);
sexp_gc_preserve2(ctx, handler, params);
#if SEXP_USE_GREEN_THREADS
params = sexp_context_params(ctx);
sexp_context_params(ctx) = SEXP_NULL;
++sexp_context_refuel(ctx);
#endif
err_cell = sexp_global(ctx, SEXP_G_ERR_HANDLER);
err_cell = sexp_opcodep(err_cell) ? sexp_opcode_data(err_cell) : SEXP_FALSE;
handler = sexp_pairp(err_cell) ? sexp_cdr(err_cell) : SEXP_FALSE;
if (sexp_pairp(err_cell)) sexp_cdr(err_cell) = SEXP_FALSE;
res = sexp_apply(ctx, proc, args);
if (sexp_pairp(err_cell)) sexp_cdr(err_cell) = handler;
#if SEXP_USE_GREEN_THREADS
sexp_context_params(ctx) = params;
#endif
sexp_gc_release2(ctx);
return res;
}
#endif
| 2.09375 | 2 |
2024-11-18T22:11:17.227389+00:00
| 2016-02-01T10:35:21 |
ffcf7e5984d7877ef08237ca4c60d347e82921a1
|
{
"blob_id": "ffcf7e5984d7877ef08237ca4c60d347e82921a1",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-01T10:35:21",
"content_id": "a7c54ecdf8a3b713895f075768e281ae220f42eb",
"detected_licenses": [
"MIT"
],
"directory_id": "781bcb6d1b73cb5e515357dd3ca1aed23b9b0058",
"extension": "h",
"filename": "ce.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 50718523,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2242,
"license": "MIT",
"license_type": "permissive",
"path": "/ce.h",
"provenance": "stackv2-0072.json.gz:44606",
"repo_name": "ptahpeteh/ce",
"revision_date": "2016-02-01T10:35:21",
"revision_id": "7cdd864d462c9392787d877edaadb55beb047f9e",
"snapshot_id": "716eb4270d36d4655ab490e9fb6ac1dc85b6d3f9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ptahpeteh/ce/7cdd864d462c9392787d877edaadb55beb047f9e/ce.h",
"visit_date": "2021-01-10T04:41:43.520819"
}
|
stackv2
|
/** Simple nested exceptions for C
author: Rafał Przywara <ptah.peteh@gmail.com>, (c) 2007
license: MIT
usage:
TRY {
...
if (some + thing - goes == wrong) THROW(-1);
...
this_can_throw_too();
...
}
CATCH (ex) {
// ex: exception code passed to THROW(), int
}
FINALLY {
// this gets always executed after try/catch blocks
}
CATCH and FINALLY are obligatory after TRY. TRY blocks can be nested.
Throw value is an int error code other than 0. Passing 0 to THROW() or
throwing exception outside of any TRY block will abort().
Directive USE_EXCEPTIONS; has to be placed somewhere in the global scope.
Compile with -DCE_M for multithread support.
*/
#include <setjmp.h>
#include <stdlib.h>
#ifndef __ce_h__
#define __ce_h__
/// multithread support
#ifdef CE_M
#define CE_TLS _Thread_local
#else
#define CE_TLS
#endif
/** holds info about an exception handler (linked list)
*/
typedef struct ce_exception__ {
jmp_buf env; ///< exception handler environment
struct ce_exception__ *prev; ///< pointer to the previously set handler
} ce_exception_;
/// pointer to the current (most recent) exception handler
extern CE_TLS ce_exception_ *ce_glob_;
/// should be placed spmewhere in the program, only once
#define USE_EXCEPTIONS CE_TLS ce_exception_ *ce_glob_ = NULL
/// throws an exception of code e, e must no be 0
#define THROW(e) if (ce_glob_ && e) longjmp(ce_glob_->env, e); else abort()
/// begins try block
#define TRY void ce_try_(void)
/// begins catch block
#define CATCH(e) void ce_catch_(int e)
/// begins finally block
#define FINALLY auto void ce_finally_(void); { \
ce_exception_ lce_; \
int ec_; \
\
lce_.prev = ce_glob_; \
ce_glob_ = &lce_; \
\
if ((ec_ = setjmp(ce_glob_->env))) { \
int cc_; \
\
if ((cc_ = setjmp(ce_glob_->env))) { \
ce_glob_ = lce_.prev; \
ce_finally_(); \
if (!ce_glob_) abort(); \
longjmp(ce_glob_->env, cc_); \
} else { \
ce_catch_(ec_); \
} \
} else { \
ce_try_(); \
} \
\
ce_glob_ = lce_.prev; \
ce_finally_(); \
} \
void ce_finally_() \
#endif // __ce_h__
| 2.640625 | 3 |
2024-11-18T22:11:18.040321+00:00
| 2015-06-08T00:17:31 |
e2478c0e7dda0c17eb42c0df5be58df90e1d579b
|
{
"blob_id": "e2478c0e7dda0c17eb42c0df5be58df90e1d579b",
"branch_name": "refs/heads/master",
"committer_date": "2015-06-08T00:17:31",
"content_id": "e6b0ada00beace68b07c9dae60f6c04eeb0998e3",
"detected_licenses": [
"MIT"
],
"directory_id": "183224ad43c8071c02fe45546f4235e250051eb3",
"extension": "c",
"filename": "dwmstatus.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 36613515,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5857,
"license": "MIT",
"license_type": "permissive",
"path": "/dwmstatus.c",
"provenance": "stackv2-0072.json.gz:44863",
"repo_name": "Mariappan/dwm",
"revision_date": "2015-06-08T00:17:31",
"revision_id": "bd31eb38b9c3cebd675d631e1ed6023853da842a",
"snapshot_id": "5502daa0ade2212c44a36a692e2fd17c65ada75c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Mariappan/dwm/bd31eb38b9c3cebd675d631e1ed6023853da842a/dwmstatus.c",
"visit_date": "2021-01-10T16:17:25.500819"
}
|
stackv2
|
#define _BSD_SOURCE
#define _GNU_SOURCE
#include <unistd.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <strings.h>
#include <inttypes.h>
#include <sys/time.h>
#include <sys/sysinfo.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <sys/statvfs.h>
#include <X11/Xlib.h>
#include <alsa/asoundlib.h>
#include <alsa/control.h>
#define MB 1048576
#define GB 1073741824
char *tz = "Asia/Kolkata";
static Display *dpy;
char *
smprintf(char *fmt, ...)
{
va_list fmtargs;
char *buf = NULL;
va_start(fmtargs, fmt);
if (vasprintf(&buf, fmt, fmtargs) == -1){
fprintf(stderr, "malloc vasprintf\n");
exit(1);
}
va_end(fmtargs);
return buf;
}
void
settz(char *tzname)
{
setenv("TZ", tzname, 1);
}
char *
mktimes(char *fmt, char *tzname)
{
char buf[129];
time_t tim;
struct tm *timtm;
memset(buf, 0, sizeof(buf));
settz(tzname);
tim = time(NULL);
timtm = localtime(&tim);
if (timtm == NULL) {
perror("localtime");
exit(1);
}
if (!strftime(buf, sizeof(buf)-1, fmt, timtm)) {
fprintf(stderr, "strftime == 0\n");
exit(1);
}
return smprintf(buf);
}
char *
loadavg(void)
{
double avgs[3];
if (getloadavg(avgs, 3) < 0) {
perror("getloadavg");
exit(1);
}
return smprintf("\x03\uf3a4 %.2f", avgs[0]);
}
char *
up() {
struct sysinfo info;
int h,m = 0;
sysinfo(&info);
h = info.uptime/3600;
m = (info.uptime - h*3600 )/60;
return smprintf("\x04\uf108 %dh%dm",h,m);
}
char *
get_volume(void)
{
snd_mixer_t *handle;
snd_mixer_elem_t *elem;
snd_mixer_selem_id_t *s_elem;
snd_mixer_open(&handle, 0);
snd_mixer_attach(handle, "default");
snd_mixer_selem_register(handle, NULL, NULL);
snd_mixer_load(handle);
snd_mixer_selem_id_malloc(&s_elem);
snd_mixer_selem_id_set_name(s_elem, "Master");
elem = snd_mixer_find_selem(handle, s_elem);
if (elem == NULL)
{
snd_mixer_selem_id_free(s_elem);
snd_mixer_close(handle);
exit(EXIT_FAILURE);
}
long int vol, max, min, percent;
snd_mixer_handle_events(handle);
snd_mixer_selem_get_playback_volume_range(elem, &min, &max);
snd_mixer_selem_get_playback_volume(elem, 0, &vol);
percent = (vol * 100) / max;
snd_mixer_selem_id_free(s_elem);
snd_mixer_close(handle);
return smprintf("\x05\uf028 %d",percent);
}
int
parse_netdev(unsigned long long int *receivedabs, unsigned long long int *sentabs)
{
char buf[255];
char *datastart;
static int bufsize;
int rval;
FILE *devfd;
unsigned long long int receivedacc, sentacc;
bufsize = 255;
devfd = fopen("/proc/net/dev", "r");
rval = 1;
// Ignore the first two lines of the file
fgets(buf, bufsize, devfd);
fgets(buf, bufsize, devfd);
while (fgets(buf, bufsize, devfd)) {
if ((datastart = strstr(buf, "lo:")) == NULL) {
datastart = strstr(buf, ":");
// With thanks to the conky project at http://conky.sourceforge.net/
sscanf(datastart + 1, "%llu %*d %*d %*d %*d %*d %*d %*d %llu",\
&receivedacc, &sentacc);
*receivedabs += receivedacc;
*sentabs += sentacc;
rval = 0;
}
}
fclose(devfd);
return rval;
}
void
calculate_speed(char *speedstr, unsigned long long int newval, unsigned long long int oldval)
{
double speed;
speed = (newval - oldval) / 1024.0;
if (speed > 1024.0) {
speed /= 1024.0;
sprintf(speedstr, "%5.3f M", speed);
} else {
sprintf(speedstr, "%5.2f K", speed);
}
}
char *
get_netusage(unsigned long long int *rec, unsigned long long int *sent)
{
unsigned long long int newrec, newsent;
newrec = newsent = 0;
char downspeedstr[15], upspeedstr[15];
static char retstr[42];
int retval;
retval = parse_netdev(&newrec, &newsent);
if (retval) {
fprintf(stdout, "Error when parsing /proc/net/dev file.\n");
exit(1);
}
calculate_speed(downspeedstr, newrec, *rec);
calculate_speed(upspeedstr, newsent, *sent);
sprintf(retstr, "\x01\uf063 %s \x02\uf062 %s", downspeedstr, upspeedstr);
/*sprintf(retstr, "\uf175 %s \uf176 %s", downspeedstr, upspeedstr);*/
*rec = newrec;
*sent = newsent;
return retstr;
}
static char *get_ram()
{
uintmax_t used = 0;
struct sysinfo mem;
sysinfo(&mem);
/*total = (uintmax_t) mem.totalram / MB;*/
used = (uintmax_t) (mem.totalram - mem.freeram -
mem.bufferram - mem.sharedram) / MB;
return smprintf("\uf3a5 %dM", used);
}
void
setstatus(char *str)
{
XStoreName(dpy, DefaultRootWindow(dpy), str);
XSync(dpy, False);
}
int runevery(time_t *ltime, int sec){
/* return 1 if sec elapsed since last run
* else return 0
*/
time_t now = time(NULL);
if ( difftime(now, *ltime ) >= sec)
{
*ltime = now;
return(1);
}
else
return(0);
}
int
main(void)
{
char *status = NULL;
char *tmprs = NULL;
char *avgs = NULL;
time_t count60 = 0;
char *uptm = NULL;
char *vol = NULL;
char *netstats = NULL;
char *ram = NULL;
static unsigned long long int rec, sent;
if (!(dpy = XOpenDisplay(NULL))) {
fprintf(stderr, "dwmstatus: cannot open display.\n");
return 1;
}
parse_netdev(&rec, &sent);
for (;;sleep(1)) {
/* checks every minutes */
if ( runevery(&count60, 60) )
{
free(tmprs);
free(uptm);
tmprs = mktimes("\x06\uf073 %b-%d %I:%M %p", tz);
uptm = up();
free(ram);
ram = get_ram();
}
/* checks every second */
avgs = loadavg();
vol = get_volume();
netstats = get_netusage(&rec, &sent);
status = smprintf("%s%s %s %s%s%s",
netstats, avgs, ram, uptm, vol, tmprs);
setstatus(status);
free(vol);
free(avgs);
free(status);
}
XCloseDisplay(dpy);
return 0;
}
| 2.3125 | 2 |
2024-11-18T22:11:18.871565+00:00
| 2017-07-20T19:23:19 |
7d48e932d763d4824d37a766290dbd980144483a
|
{
"blob_id": "7d48e932d763d4824d37a766290dbd980144483a",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-20T19:23:46",
"content_id": "cac0906b7c4b888c5b7d20b43fbba28d0897f7ef",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2384e8ef1b35fefaa476d46fb77424e8d3263800",
"extension": "c",
"filename": "bukkit_hdr.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": 7986,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/c_src/bukkit_hdr.c",
"provenance": "stackv2-0072.json.gz:45634",
"repo_name": "b20n/bukkit",
"revision_date": "2017-07-20T19:23:19",
"revision_id": "f6434f6f0e776bbd60b90a28b8d1e084faca26ba",
"snapshot_id": "f04c06a6f8bc055995e96bc404b0de8bcc106e58",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/b20n/bukkit/f6434f6f0e776bbd60b90a28b8d1e084faca26ba/c_src/bukkit_hdr.c",
"visit_date": "2021-06-22T15:41:48.546323"
}
|
stackv2
|
#include <errno.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "bukkit_hdr.h"
static int64_t power(int64_t base, int64_t exp)
{
int64_t result = 1;
while (exp) {
result *= base;
exp--;
}
return result;
}
static int32_t get_bucket_index(Hdr *hdr, int64_t value)
{
// Smallest power of 2 containing the value
int32_t pow2ceiling = 64 - __builtin_clzll(value | hdr->sub_bucket_mask);
int32_t magnitude = hdr->unit_magnitude;
int32_t sbhcm = hdr->sub_bucket_half_count_magnitude + 1;
return pow2ceiling - magnitude - sbhcm;
}
static int32_t get_sub_bucket_index(int64_t v, int32_t index, int32_t magnitude)
{
return (int32_t) (v >> (index + magnitude));
}
static int32_t counts_index(Hdr *hdr, int32_t bucket_index, int32_t sub_index)
{
int32_t sbhcm = hdr->sub_bucket_half_count_magnitude;
int32_t bucket_base_index = (bucket_index + 1) << sbhcm;
int32_t offset_in_bucket = sub_index - hdr->sub_bucket_half_count;
return bucket_base_index + offset_in_bucket;
}
static int32_t normalize_index(Hdr *hdr, int32_t index)
{
if (hdr->normalizing_index_offset == 0) {
return index;
}
int32_t normalized_index = index - hdr->normalizing_index_offset;
int32_t adjustment = 0;
if (normalized_index < 0) {
adjustment = hdr->counts_len;
} else if (normalized_index >= hdr->counts_len) {
adjustment = -hdr->counts_len;
}
return normalized_index + adjustment;
}
static int64_t size_of_equivalent_value_range(Hdr *hdr, int64_t value)
{
int32_t bucket_index = get_bucket_index(hdr, value);
int32_t sub_bucket_index = get_sub_bucket_index(
value,
bucket_index,
hdr->unit_magnitude
);
if (sub_bucket_index >= hdr->sub_bucket_count) {
bucket_index++;
}
return INT64_C(1) << (hdr->unit_magnitude + bucket_index);
}
static int64_t value_from_index(int32_t index, int32_t sub_index, int32_t mag)
{
return ((int64_t) sub_index) << (index + mag);
}
static int64_t value_at_index(Hdr *hdr, int32_t index)
{
int32_t bucket_index = (index >> hdr->sub_bucket_half_count_magnitude) - 1;
int32_t sub_bucket_index = (index & (hdr->sub_bucket_half_count - 1));
if (bucket_index < 0) {
bucket_index = 0;
} else {
sub_bucket_index += hdr->sub_bucket_half_count;
}
return value_from_index(bucket_index, sub_bucket_index, hdr->unit_magnitude);
}
static int64_t lowest_equivalent_value(Hdr *hdr, int64_t value)
{
int32_t bucket_index = get_bucket_index(hdr, value);
int32_t sub_bucket_index = get_sub_bucket_index(
value,
bucket_index,
hdr->unit_magnitude
);
return value_from_index(bucket_index, sub_bucket_index, hdr->unit_magnitude);
}
static int64_t highest_eqivalent_value(Hdr *hdr, int64_t value)
{
int64_t ret = lowest_equivalent_value(hdr, value);
ret += size_of_equivalent_value_range(hdr, value);
return ret - 1;
}
static int64_t median_equivalent_value(Hdr *hdr, int64_t value)
{
int64_t ret = lowest_equivalent_value(hdr, value);
ret += (size_of_equivalent_value_range(hdr, value) >> 1);
return ret;
}
int bukkit_hdr_new(int64_t lowest, int64_t highest, int sigfig, Hdr **result)
{
Hdr *hdr = NULL;
hdr = calloc(1, sizeof(Hdr));
if (hdr == NULL) {
return ENOMEM;
}
hdr->lowest_trackable_value = lowest;
hdr->highest_trackable_value = highest;
hdr->significant_figures = sigfig;
int32_t mag = (int32_t) floor(log((double) lowest) / log(2));
hdr->unit_magnitude = mag;
// Largest single resolution value
int64_t lsrv = 2 * power(10, sigfig);
int32_t sbcm = ceil(log((double) lsrv) / log(2));
int32_t sbhcm = ((sbcm > 1) ? sbcm : 1) - 1;
hdr->sub_bucket_half_count_magnitude = sbhcm;
hdr->sub_bucket_count = (int32_t) power(2, sbhcm + 1);
hdr->sub_bucket_half_count = hdr->sub_bucket_count / 2;
hdr->sub_bucket_mask = ((int64_t) hdr->sub_bucket_count - 1) << mag;
hdr->bucket_count = 1;
int64_t smallest_untrackable_value = ((int64_t) hdr->sub_bucket_count) << mag;
while (smallest_untrackable_value <= highest) {
hdr->bucket_count++;
if (smallest_untrackable_value > INT64_MAX / 2) {
break;
}
smallest_untrackable_value <<= 1;
}
hdr->counts_len = (hdr->bucket_count + 1) * (hdr->sub_bucket_count / 2);
hdr->min = INT64_MAX;
hdr->max = 0;
hdr->normalizing_index_offset = 0;
hdr->conversion_ratio = 1.0;
hdr->total_count = 0;
hdr->counts = calloc(hdr->counts_len, sizeof(int64_t));
if (hdr->counts == NULL) {
free(hdr);
return ENOMEM;
}
*result = hdr;
return 0;
}
void bukkit_hdr_free(Hdr *hdr)
{
free(hdr->counts);
free(hdr);
return;
}
int bukkit_hdr_add(Hdr *from, Hdr *to)
{
for (int32_t index = 0; index < from->counts_len; index++) {
int64_t value = value_at_index(from, index);
int64_t count = from->counts[normalize_index(from, index)];
for (int i = 0; i < count; i++) {
if (bukkit_hdr_update(to, value) != 0) {
return 1;
}
}
}
return 0;
}
int bukkit_hdr_update(Hdr *hdr, int64_t value)
{
if (value < hdr->lowest_trackable_value) {
return EINVAL;
}
int32_t mag = hdr->unit_magnitude;
int32_t bucket_index = get_bucket_index(hdr, value);
int32_t sub_bucket_index = get_sub_bucket_index(value, bucket_index, mag);
int32_t index = counts_index(hdr, bucket_index, sub_bucket_index);
if (index < 0 || hdr->counts_len <= index) {
return EINVAL;
}
int32_t normalized_index = normalize_index(hdr, index);
__sync_fetch_and_add(&hdr->counts[normalized_index], 1);
__sync_fetch_and_add(&hdr->total_count, 1);
hdr->counts[normalized_index]++;
hdr->total_count++;
while (hdr->min > value) {
__sync_val_compare_and_swap(&hdr->min, hdr->min, value);
}
while (hdr->max < value) {
__sync_val_compare_and_swap(&hdr->max, hdr->max, value);
}
return 0;
}
int bukkit_hdr_read(Hdr *hdr, HdrRead **result)
{
HdrRead *read = calloc(1, sizeof(HdrRead));
if (read == NULL) {
return ENOMEM;
}
if (hdr->counts[normalize_index(hdr, 0)] > 0) {
read->min = 0;
} else if (hdr->min == INT64_MAX) {
read->min = INT64_MAX;
} else {
read->min = lowest_equivalent_value(hdr, hdr->min);
}
if (hdr->max == 0) {
read->max = 0;
} else {
read->max = highest_eqivalent_value(hdr, hdr->max);
}
read->p50 = bukkit_hdr_percentile(hdr, 50.0);
read->p75 = bukkit_hdr_percentile(hdr, 75.0);
read->p90 = bukkit_hdr_percentile(hdr, 90.0);
read->p99 = bukkit_hdr_percentile(hdr, 99.0);
read->p999 = bukkit_hdr_percentile(hdr, 99.9);
read->mean = bukkit_hdr_mean(hdr);
read->stddev = bukkit_hdr_stddev(hdr);
*result = read;
return 0;
}
void bukkit_hdr_read_free(HdrRead *read)
{
free(read);
return;
}
int64_t bukkit_hdr_percentile(Hdr *hdr, double percentile)
{
percentile = percentile < 100.0 ? percentile : 100.0;
int64_t count = (int64_t) (percentile / 100 * hdr->total_count + 0.5);
int64_t total = 0;
for (int32_t index = 0; index < hdr->counts_len; index++) {
total += hdr->counts[normalize_index(hdr, index)];
if (total > count) {
return highest_eqivalent_value(hdr, value_at_index(hdr, index));
}
}
return 0;
}
double bukkit_hdr_mean(Hdr *hdr)
{
if (hdr->total_count == 0) {
return NAN;
}
int64_t total = 0;
for (int32_t index = 0; index < hdr->counts_len; index++) {
int64_t count = hdr->counts[normalize_index(hdr, index)];
total += count * median_equivalent_value(hdr, value_at_index(hdr, index));
}
return (total * 1.0) / hdr->total_count;
}
double bukkit_hdr_stddev(Hdr *hdr)
{
if (hdr->total_count == 0) {
return NAN;
}
double mean = bukkit_hdr_mean(hdr);
double variance = 0.0;
for (int32_t index = 0; index < hdr->counts_len; index++) {
int64_t value = median_equivalent_value(hdr, value_at_index(hdr, index));
double dev = (value * 1.0) - mean;
variance += (dev * dev) * hdr->counts[normalize_index(hdr, index)];
}
return sqrt(variance / hdr->total_count);
}
| 2.53125 | 3 |
2024-11-18T22:11:18.977433+00:00
| 2015-08-22T06:20:23 |
53547c0825c52a1c76e4654d2d69307580f67112
|
{
"blob_id": "53547c0825c52a1c76e4654d2d69307580f67112",
"branch_name": "refs/heads/master",
"committer_date": "2015-08-22T06:20:23",
"content_id": "d2c739e4c50a0282f8d76bd07c59f4c447673412",
"detected_licenses": [
"MIT"
],
"directory_id": "674baf736031d0c29992b745a7e987471842aad6",
"extension": "h",
"filename": "sc_types.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": 1464,
"license": "MIT",
"license_type": "permissive",
"path": "/ThirdParty/coresocial/h/scoreloop/sc_types.h",
"provenance": "stackv2-0072.json.gz:45762",
"repo_name": "duhone/BumbleTales-1",
"revision_date": "2015-08-22T06:20:23",
"revision_id": "39182d2c28d8d9e16d041774b9f529225effb20d",
"snapshot_id": "d671c8100e13ef49f8e75de8cd39a5f56f40881a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/duhone/BumbleTales-1/39182d2c28d8d9e16d041774b9f529225effb20d/ThirdParty/coresocial/h/scoreloop/sc_types.h",
"visit_date": "2021-01-16T18:48:40.022842"
}
|
stackv2
|
/*-------------------------------------------------------------------------------------*
* Copyright (C) 2012 Scoreloop AG. All rights reserved.
*-------------------------------------------------------------------------------------*/
/**
* @file sc_types.h
* @brief Scoreloop Core - basic types.
*
* @addtogroup SC_Types
* @{
*
* Scoreloop Core - basic types.
*/
#ifndef __SC_TYPES_H__
#define __SC_TYPES_H__
/*-------------------------------------------------------------------------------------*
* Includes
*-------------------------------------------------------------------------------------*/
#include <scoreloop/sc_platform.h>
/*-------------------------------------------------------------------------------------*
* Types
*-------------------------------------------------------------------------------------*/
/** Maximum unsigned integer value. */
#define MAX_UINT ((unsigned int)(0-1))
/** Maximum integer value. */
#define MAX_INT (MAX_UINT/2)
/** Boolean type */
typedef unsigned char SC_Bool_t;
/** Boolean 'false' value. */
#define SC_FALSE 0
/** Boolean 'true' value. */
#define SC_TRUE 1
/** Int64 type */
typedef long long SC_Int64_t;
/** Unsigned Int64 type */
typedef unsigned long long SC_UInt64_t;
/** Float type */
typedef double SC_Float_t;
/** NULL constant */
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
#endif /* __SC_TYPES_H__ */
/*! @} */
| 2.15625 | 2 |
2024-11-18T22:11:19.539927+00:00
| 2021-06-28T08:12:41 |
7c1d8a457cb21837e32edfc3344619a50a9e9964
|
{
"blob_id": "7c1d8a457cb21837e32edfc3344619a50a9e9964",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-28T08:12:41",
"content_id": "9e23e6bfb7aba6d2bda094cc0e0b0d5a49090e30",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ddda55fcfc84ac5cd78cfc5c336a3df0b9096157",
"extension": "c",
"filename": "usr_pin.c",
"fork_events_count": 2,
"gha_created_at": "2021-06-23T16:11:54",
"gha_event_created_at": "2021-06-28T10:08:10",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 379661507,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2552,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/thirdparty/MicroPython/user/machine/driver/OneOS/usr_pin.c",
"provenance": "stackv2-0072.json.gz:45891",
"repo_name": "liu-delong/lu_xing_xiang_one_os",
"revision_date": "2021-06-28T08:12:41",
"revision_id": "0c659cb811792f2e190d5a004a531bab4a9427ad",
"snapshot_id": "701b74fceb82dbb2806518bfb07eb85415fab43a",
"src_encoding": "GB18030",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/liu-delong/lu_xing_xiang_one_os/0c659cb811792f2e190d5a004a531bab4a9427ad/thirdparty/MicroPython/user/machine/driver/OneOS/usr_pin.c",
"visit_date": "2023-06-17T03:02:13.426431"
}
|
stackv2
|
#include "usr_pin.h"
#include <stdlib.h>
#include "py/runtime.h"
#ifdef MICROPY_PY_MACHINE_PIN
#include <drv_gpio.h>
os_base_t gpio_list[] ={
#if defined(GPIOA_BASE)
GPIOA_BASE,
#endif
#if defined(GPIOB_BASE)
GPIOB_BASE,
#endif
#if defined(GPIOC_BASE)
GPIOC_BASE,
#endif
#if defined(GPIOD_BASE)
GPIOD_BASE,
#endif
#if defined(GPIOE_BASE)
GPIOE_BASE,
#endif
#if defined(GPIOF_BASE)
GPIOF_BASE,
#endif
#if defined(GPIOG_BASE)
GPIOG_BASE,
#endif
#if defined(GPIOH_BASE)
GPIOH_BASE,
#endif
};
static int pin_read(void *device, uint32_t offset, void *buf, uint32_t bufsize)
{
return os_pin_read((os_base_t)offset);
}
static int pin_write(void *device, uint32_t offset, void *buf, uint32_t bufsize)
{
os_pin_write((os_base_t)offset, *((os_base_t*)buf));
return 0;
}
static int pin_ctrl(void *device, int cmd, void* arg)
{
os_pin_mode(*((os_base_t*)arg), (os_base_t)cmd);
return 0;
}
static int pin_close(void *device)
{
return 0;
}
/**
*********************************************************************************************************
* 获取gpio的序列号
*
* @description: 这个函数用来获取gpio的序列号。
*
* @param : device: 设备。
*
* mesg: gpio的信息,如['A', 13]
* @returns : gpio 的序列号,(操作系统层的序列号)
*********************************************************************************************************
*/
int mp_pin_get_num(void *device, void *mesg)
{
char *data = (char *)mesg;
int group_index = data[0];
if (group_index > 'H' || group_index < 'A'){
mp_raise_ValueError("[pin_get_num] parameters is wrong! \n");
return -1;
} else {
group_index -= 'A';
}
int index = data[1];
return (os_base_t)((16 * ((gpio_list[group_index] - (os_base_t)GPIOA_BASE) / (0x0400UL))) + index);
}
int mpycall_pin_register(void)
{
device_info_t * pin;
pin = (device_info_t *)malloc(sizeof(device_info_t));
if(NULL == pin)
{
printf("mpycall_pin_register malloc mem failed!");
return -1;
}
pin->owner.name = "pin";
pin->owner.type = DEV_BUS;
pin->ops = (struct operate *)malloc(sizeof(struct operate));
if(NULL == pin->ops)
{
printf("mpycall_pin_register malloc mem failed!");
return -1;
}
pin->ops->read = pin_read;
pin->ops->write = pin_write;
pin->ops->ioctl = pin_ctrl;
pin->ops->close = pin_close;
pin->ops->suspend = mp_pin_get_num;
mpycall_device_add(pin);
return 0;
}
OS_DEVICE_INIT(mpycall_pin_register);
#endif // MICROPY_PY_MACHINE_PIN
| 2.5625 | 3 |
2024-11-18T22:11:19.669711+00:00
| 2022-11-16T11:24:24 |
619c120851eca4e9aa6e8925116bdfadd6232a9a
|
{
"blob_id": "619c120851eca4e9aa6e8925116bdfadd6232a9a",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-16T11:24:24",
"content_id": "3c0d39bf9b1c323b0d91c5734d17f36fa5671426",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "dd1570ea326d0d903cc6d2a0ae27ba26b786fd9b",
"extension": "c",
"filename": "reduce.c",
"fork_events_count": 3,
"gha_created_at": "2016-07-06T12:45:04",
"gha_event_created_at": "2023-02-15T21:56:51",
"gha_language": "Python",
"gha_license_id": "BSD-3-Clause",
"github_id": 62720223,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1413,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/wee_mpi/examples/reduce.c",
"provenance": "stackv2-0072.json.gz:46147",
"repo_name": "EPCCed/wee_archie",
"revision_date": "2022-11-16T11:24:24",
"revision_id": "c9821b92dc532de966b8e28bc11e302ef6736d06",
"snapshot_id": "6e46dc4d7b8907f5a949d36d0278a76d05cdf363",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/EPCCed/wee_archie/c9821b92dc532de966b8e28bc11e302ef6736d06/wee_mpi/examples/reduce.c",
"visit_date": "2023-02-26T01:35:25.110194"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <wee_mpi.h>
int main(int argc, char** argv) {
// initialize the mpi environment
MPI_Init(&argc, &argv);
// get the number of processes
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
// get the rank of the process
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
// get the name of the processor
char processor_name[MPI_MAX_PROCESSOR_NAME]; int name_len;
MPI_Get_processor_name(processor_name, &name_len);
printf("Rank: %d, Proc Name:%s\n", world_rank, processor_name);
float rand_nums[world_size];
for(int i =0; i < world_size; i++) rand_nums[i] = i;
// Sum the numbers locally
float local_sum = 0;
int i;
for (i = 0; i < world_size; i++) {
local_sum += rand_nums[i];
}
// Print the random numbers on each process
printf("Local sum for process %d - %f, avg = %f\n",
world_rank, local_sum, local_sum / world_size);
// Reduce all of the local sums into the global sum
float global_sum;
MPI_Reduce(&local_sum, &global_sum, 1, MPI_FLOAT, MPI_SUM, 0,
MPI_COMM_WORLD);
// Print the result
if (world_rank == 0) {
printf("Total sum = %f, avg = %f\n", global_sum,
global_sum / (world_size * world_size));
}
// Finalize the MPI environment.
MPI_Finalize();
}
| 3.03125 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.