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-18T18:23:02.582785+00:00 | 2015-04-29T17:47:53 | 76d693e0782eee106c87377d52ea40875ecd27b9 | {
"blob_id": "76d693e0782eee106c87377d52ea40875ecd27b9",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-29T17:47:53",
"content_id": "8edfca35eb8b70026fcb86f07f2657b9021f0390",
"detected_licenses": [
"MIT"
],
"directory_id": "6292621a965ef2e5892e142d20d92fde8d00ca08",
"extension": "c",
"filename": "AMS_pressure.c",
"fork_events_count": 2,
"gha_created_at": "2015-04-06T18:57:37",
"gha_event_created_at": "2015-04-06T18:57:38",
"gha_language": null,
"gha_license_id": null,
"github_id": 33499473,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3467,
"license": "MIT",
"license_type": "permissive",
"path": "/FlightCode/sensors/AirData/AMS_pressure.c",
"provenance": "stackv2-0003.json.gz:387855",
"repo_name": "hamid-m/OpenFlight",
"revision_date": "2015-04-29T17:47:53",
"revision_id": "86fbeec8a7725526a97231b69e772246f4f9ea0d",
"snapshot_id": "9f942b7b7f0be4e418683af539fc3bd4aa39e491",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/hamid-m/OpenFlight/86fbeec8a7725526a97231b69e772246f4f9ea0d/FlightCode/sensors/AirData/AMS_pressure.c",
"visit_date": "2021-01-21T03:09:11.678703"
} | stackv2 | /*! \file AMS_pressure.c
* \brief Header file for AMS pressure sensors.
*
* \details This program is designed to read data off 4 AMS pressure sensor units:
* AMS 5812-0003-D (unidirectional 0.3psi differential for airspeed)
* AMS 5812-0003-DB (x2) (bidirectional +-0.3psi differential for alpha and beta)
* AMS 5812-0150-B (barometric sensor for altitude)
* \ingroup airdata_fcns
*
* \author University of Minnesota
* \author Aerospace Engineering and Mechanics
* \copyright Copyright 2011 Regents of the University of Minnesota. All rights reserved.
*
* $Id: AMS_pressure.c 756 2012-01-04 18:51:43Z murch $
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <cyg/io/i2c_mpc5xxx.h>
#include "../../globaldefs.h"
#include "airdata_interface.h"
#include "airdata_constants.h"
#include "AMS_pressure.h"
void init_airdata(){
return;
}
int read_airdata (struct airdata *adData_ptr)
{
int status = 0;
// Read AMS pressure sensors, passing in pointers to air data structure locations
// Thread delay is needed to allow I2C transaction sufficient time to complete.
if(0 == read_AMS_sensor(&AMS5812_0150B,&adData_ptr->Ps,11.0,17.5))
status |= 1;
cyg_thread_delay(1);
if(0 == read_AMS_sensor(&AMS5812_0003D,&adData_ptr->Pd,0.0, 0.3))
status |= 1 << 1;
// These are only on Thor and FASER
cyg_thread_delay(1);
if(0 == read_AMS_sensor(&AMS5812_0003DB_1,&adData_ptr->Pd_aoa,-0.3,0.3))
status |= 1 << 2;
cyg_thread_delay(1);
if(0 == read_AMS_sensor(&AMS5812_0003DB_2,&adData_ptr->Pd_aos,-0.3,0.3))
status |= 1 << 3;
return status;
}
static int read_AMS_sensor(cyg_i2c_device* device,double* pressure_data, double p_min, double p_max)
{
uint8_t DataBuf[4]; //databuffer that stores the binary words output from sensor
uint16_t pressure_counts; // temporary variables
//uint16_t temp_counts;
//Equations for conversion are as follows:
//P = (Digout(p) - Digoutp_min)/Sensp + p_min
//Where Sensp = (Digoutp_max - Digoutp_min)/(p_max - p_min)
//Therein p is current pressure in PSI and p_min and p_max are the specific max and min
//pressure of the respective sensor. The Digoutp_max and Digoutp_min are the 90% and 10%
//values of the 15 bit output word i.e. 0111111111111111_binary = 32767_decimal
//For temperature conversion replace T for p in above equations where T_max 85c and
//T_min = -25c. Temperature is the sensor temperature at the measurement cell and includes
//self heating. This is NOT the actual air temperature.
// Try to read 2 bytes from sensor (just pressure data). Don't update pressure data if 2 bytes are not read.
if (2 == cyg_i2c_rx(device, DataBuf, 2)){
//Combine the two bytes of returned data
pressure_counts = (((uint16_t) (DataBuf[0]&0x7F)) <<8) + (((uint16_t) DataBuf[1])); // data is a 15-bit word. Bitwise AND ensures only 7 bits of upper byte are used.
//temp_counts = (((uint16_t) (DataBuf[2]&0x7F)) <<8) + (((uint16_t) DataBuf[3]));
// Convert counts to engineering units
*pressure_data = (double)((pressure_counts - P_MIN_COUNTS)/((P_MAX_COUNTS-P_MIN_COUNTS)/(p_max-p_min)) + p_min)*PSI_TO_KPA; //pressure in kpa for bi_dir_1
//*temp_data = (double)(temp_counts - P_MIN_COUNTS)/((P_MAX_COUNTS-P_MIN_COUNTS)/110.0) - 25.0; //temperature in celcius
return 1;
}
else{
// printf("\n<read_AMS_sensor>: 4 bytes NOT read!");
return 0;
}
}
| 2.5 | 2 |
2024-11-18T18:23:05.179034+00:00 | 2020-08-16T01:03:26 | 79ad0fb3b834fe1e0cb0528c06b5863a5481c9c3 | {
"blob_id": "79ad0fb3b834fe1e0cb0528c06b5863a5481c9c3",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-16T03:53:56",
"content_id": "9ef6c15406d1bff2096b94b5fb540249bbe4fc55",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "d911ae679ba2e25498390954538796c4921a0d5d",
"extension": "c",
"filename": "tx.c",
"fork_events_count": 4,
"gha_created_at": "2016-05-23T19:02:23",
"gha_event_created_at": "2020-08-16T00:10:04",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 59510611,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2850,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/test/tx.c",
"provenance": "stackv2-0003.json.gz:388501",
"repo_name": "libbitc/libbitc",
"revision_date": "2020-08-16T01:03:26",
"revision_id": "f7b6dca668128f202e82c7549af503516c782f4a",
"snapshot_id": "25de193fbc75ef344a314ef5f29320494849d4ee",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/libbitc/libbitc/f7b6dca668128f202e82c7549af503516c782f4a/test/tx.c",
"visit_date": "2020-12-11T07:52:01.160271"
} | stackv2 | /* Copyright 2012 exMULTI, Inc.
* Distributed under the MIT/X11 software license, see the accompanying
* file COPYING or http://www.opensource.org/licenses/mit-license.php.
*/
#include <bitc/buffer.h> // for const_buffer
#include <bitc/buint.h> // for bu256_equal, bu256_hex, etc
#include <bitc/cstr.h> // for cstring, cstr_free, etc
#include <bitc/key.h> // for bitc_key_static_shutdown
#include <bitc/parr.h> // for parr
#include <bitc/primitives/transaction.h> // for bitc_tx, bitc_txout, etc
#include <bitc/util.h> // for bu_read_file
#include "libtest.h" // for test_filename
#include <cJSON.h> // for cJSON, cJSON_GetObjectItem, etc
#include <assert.h> // for assert
#include <stdbool.h> // for true, bool
#include <stddef.h> // for size_t
#include <stdio.h> // for fprintf, NULL, stderr
#include <stdlib.h> // for free
#include <string.h> // for strcmp, memcmp
static void runtest(const char *json_base_fn, const char *ser_base_fn)
{
char *json_fn = test_filename(json_base_fn);
cJSON *meta = read_json(json_fn);
assert(meta != NULL);
assert((meta->type & 0xFF) == cJSON_Object);
char *ser_fn = test_filename(ser_base_fn);
void *data = NULL;
size_t data_len = 0;
bool rc = bu_read_file(ser_fn, &data, &data_len, 100 * 1024 * 1024);
assert(rc);
const char *hashstr = cJSON_GetObjectItem(meta, "hash")->valuestring;
assert(hashstr != NULL);
unsigned int size = cJSON_GetObjectItem(meta, "size")->valueint;
assert(data_len == size);
struct bitc_tx tx;
bitc_tx_init(&tx);
struct const_buffer buf = { data, data_len };
rc = deser_bitc_tx(&tx, &buf);
assert(rc);
cstring *gs = cstr_new_sz(10000);
ser_bitc_tx(gs, &tx);
if (gs->len != data_len) {
fprintf(stderr, "gs->len %ld, data_len %lu\n",
(long)gs->len, data_len);
assert(gs->len == data_len);
}
assert(memcmp(gs->str, data, data_len) == 0);
bitc_tx_calc_sha256(&tx);
char hexstr[BU256_STRSZ];
bu256_hex(hexstr, &tx.sha256);
if (strcmp(hexstr, hashstr)) {
fprintf(stderr, "tx: wanted hash %s,\n got hash %s\n",
hashstr, hexstr);
assert(!strcmp(hexstr, hashstr));
}
assert(tx.vin->len == 1);
assert(tx.vout->len == 2);
struct bitc_tx tx_copy;
bitc_tx_init(&tx_copy);
bitc_tx_copy(&tx_copy, &tx);
bitc_tx_calc_sha256(&tx_copy);
assert(bu256_equal(&tx_copy.sha256, &tx.sha256) == true);
bitc_tx_free(&tx);
bitc_tx_free(&tx_copy);
cstr_free(gs, true);
free(data);
free(json_fn);
free(ser_fn);
cJSON_Delete(meta);
}
int main (int argc, char *argv[])
{
runtest("data/tx3e0dc3da.json", "data/tx3e0dc3da.ser");
bitc_key_static_shutdown();
return 0;
}
| 2.09375 | 2 |
2024-11-18T18:23:05.274096+00:00 | 2020-03-08T08:29:17 | e31a93e0f90145a440b36a4c7d0cf31c6c2d3c2d | {
"blob_id": "e31a93e0f90145a440b36a4c7d0cf31c6c2d3c2d",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-08T08:29:17",
"content_id": "5e639c03bb84ad1a07c52ef29620c6c71413248b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6c8c11da1d1476062246defad285df20ad4865b1",
"extension": "c",
"filename": "jsr.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 19061446,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1570,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/exec/jsr.c",
"provenance": "stackv2-0003.json.gz:388630",
"repo_name": "chrlns/bean",
"revision_date": "2020-03-08T08:29:17",
"revision_id": "419fbffa4d594347b922d8fb10a3945949a64e97",
"snapshot_id": "af77955a1505163beda90be7045a0200a2aa2e05",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/chrlns/bean/419fbffa4d594347b922d8fb10a3945949a64e97/src/exec/jsr.c",
"visit_date": "2022-04-08T08:33:47.668772"
} | stackv2 | /*
* Bean Java VM
* Copyright (C) 2005-2015 Christian Lins <[email protected]>
*
* 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 <debug.h>
#include <stack.h>
#include <vm.h>
void JSR(Thread *thread, uint32_t offset)
{
Varframe *frame =
(Varframe *) malloc(sizeof(Varframe));
/* At the beginning of this function the thread->InstructionPointer
points to the last branchbyte, so we have to correct this... */
current_frame(thread)->instPtr++;
/* Push the return address onto the stack */
frame->data.ptr = current_frame(thread)->instPtr + offset;
frame->type = JAVATYPE_RETADDR; /* Return address */
Stack_push(&(current_frame(thread)->operandStack), frame);
}
void do_JSR_W(Thread *thread)
{
uint32_t offset;
dbgmsg("JSR_W");
offset = Get4ByteOperand(current_frame(thread));
JSR(thread, offset - 4);
}
void do_JSR(Thread *thread)
{
uint16_t offset;
dbgmsg("JSR");
offset = Get2ByteOperand(current_frame(thread));
JSR(thread, (uint32_t) offset - 2);
}
| 2.375 | 2 |
2024-11-18T18:23:05.485765+00:00 | 2021-04-18T12:50:02 | d513d35604bb951fca72aa6937d57f519d1f3d32 | {
"blob_id": "d513d35604bb951fca72aa6937d57f519d1f3d32",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-18T12:50:02",
"content_id": "7f25839dd8b9f00bb3c81f19c608f19235d3cad7",
"detected_licenses": [
"MIT"
],
"directory_id": "fa252a38c2f9e596c273677a44b6b3f397e34f29",
"extension": "c",
"filename": "common.c",
"fork_events_count": 0,
"gha_created_at": "2021-03-24T05:15:54",
"gha_event_created_at": "2021-03-24T06:36:31",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 350954240,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4350,
"license": "MIT",
"license_type": "permissive",
"path": "/src/common.c",
"provenance": "stackv2-0003.json.gz:388760",
"repo_name": "dgsaf/game-of-life",
"revision_date": "2021-04-18T12:50:02",
"revision_id": "3905c84f28ddff848761b2a1cd9f2118ae6eabd4",
"snapshot_id": "0a5d65f9988f327f39898a150af955d0bd0b35be",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dgsaf/game-of-life/3905c84f28ddff848761b2a1cd9f2118ae6eabd4/src/common.c",
"visit_date": "2023-04-07T21:26:57.147005"
} | stackv2 | /*!
*/
#include "common.h"
void visualise(enum VisualiseType ivisualisetype, int step, int *grid, int n, int m){
if (ivisualisetype == VISUAL_ASCII) visualise_ascii(step, grid, n, m);
if (ivisualisetype == VISUAL_PNG) visualise_png(step, grid, n, m);
else visualise_none(step);
}
/// ascii visualisation
void visualise_ascii(int step, int *grid, int n, int m){
printf("Game of Life\n");
printf("Step %d:\n", step);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
char cell = ' ';
if (grid[i*m + j] == ALIVE) cell = '*';
printf(" %c ", cell);
}
printf("\n");
}
}
void visualise_png(int step, int *grid, int n, int m){
#ifdef USEPNG
char pngname[2000];
sprintf(pngname,"GOL.grid-%d-by-%d.step-%d.png",n,m,step);
bitmap_t gol;
gol.width = n;
gol.height = m;
gol.pixels = calloc (n*m, sizeof (pixel_t));
if (! gol.pixels) {
exit(9);
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
pixel_t * pixel = pixel_at (&gol, i, j);
int state = grid[i*m+j];
if (state == ALIVE) {
pixel->red = (uint8_t)0;
pixel->green = (uint8_t)255;
pixel->blue = (uint8_t)0;
}
else if (state == DEAD) {
pixel->red = (uint8_t)0;
pixel->green = (uint8_t)0;
pixel->blue = (uint8_t)0;
}
else if (state == BORN) {
pixel->red = (uint8_t)0;
pixel->green = (uint8_t)255;
pixel->blue = (uint8_t)255;
}
else if (state == DYING) {
pixel->red = (uint8_t)255;
pixel->green = (uint8_t)0;
pixel->blue = (uint8_t)0;
}
}
}
if (save_png_to_file (&gol, pngname)) {
fprintf (stderr, "Error writing png file %s\n", pngname);
exit(9);
}
free (gol.pixels);
#endif
}
void visualise_none(int step){
printf("Game of Life, Step %d:\n", step);
}
/// generate random IC
void generate_rand_IC(int *grid, int n, int m){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
grid[i*m + j] = (rand() % 100 < 40) ? DEAD : ALIVE;
}
}
}
/// generate some ICs
void generate_IC(enum ICType ic_choice, int *grid, int n, int m){
if (ic_choice == IC_RAND) generate_rand_IC(grid, n, m);
}
/// get some basic timing info
struct timeval init_time(){
struct timeval curtime;
gettimeofday(&curtime, NULL);
return curtime;
}
/// get the elapsed time relative to start, return current wall time
struct timeval get_elapsed_time(struct timeval start){
struct timeval curtime, delta;
gettimeofday(&curtime, NULL);
delta.tv_sec = curtime.tv_sec - start.tv_sec;
delta.tv_usec = curtime.tv_usec - start.tv_usec;
double deltas = delta.tv_sec+delta.tv_usec/1e6;
printf("Elapsed time %f s\n", deltas);
return curtime;
}
/// UI
void getinput(int argc, char **argv, struct Options *opt){
if(argc < 3){
printf("Usage: %s <grid height> <grid width> [<nsteps> <IC type> <Visualisation type> <Rule type> <Neighbour type> <Boundary type> <stats filename> ]\n", argv[0]);
exit(0);
}
// grid size
char statsfilename[2000] = "GOL-stats.txt";
opt->n = atoi(argv[1]), opt->m = atoi(argv[2]);
opt->nsteps = -1;
if (argc >= 4)
opt->nsteps = atoi(argv[3]);
if (argc >= 5)
opt->iictype = atoi(argv[4]);
if (argc >= 6)
opt->ivisualisetype = atoi(argv[5]);
if (argc >= 7)
opt->iruletype = atoi(argv[6]);
if (argc >= 8)
opt->ineighbourtype = atoi(argv[7]);
if (argc >= 9)
opt->iboundarytype = atoi(argv[8]);
if (argc >= 10)
strcpy(statsfilename, argv[9]);
if (opt->n <= 0 || opt->m <= 0) {
printf("Invalid grid size.\n");
exit(1);
}
strcpy(opt->statsfile, statsfilename);
unsigned long long nbytes = sizeof(int) * opt->n * opt->m;
printf("Requesting grid size of (%d,%d), which requires %f GB \n",
opt->n, opt->m, nbytes/1024.0/1024.0/1024.0);
#ifndef USEPNG
if (opt->ivisualisetype == VISUAL_PNG) {
printf("PNG visualisation not enabled at compile time, turning off visualisation from now on.\n");
}
#endif
}
| 2.765625 | 3 |
2024-11-18T18:23:06.096267+00:00 | 2020-02-27T08:08:57 | 8e6a135d56b7c60d1aea2ec2a4323dddfccf1063 | {
"blob_id": "8e6a135d56b7c60d1aea2ec2a4323dddfccf1063",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-27T08:08:57",
"content_id": "3973445429940bb5cfe387883873f34156789ee5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a03530c2d296d90b556a6d9969f230c66712d27b",
"extension": "c",
"filename": "struct_test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 216904791,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 628,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/BCT_TestCasesProject/BCT/workspace_BCT_Testing/CbmcStaticNondeterministic/struct_test.c",
"provenance": "stackv2-0003.json.gz:389406",
"repo_name": "lta-disco-unimib-it/BCT_TOOLSET",
"revision_date": "2020-02-27T08:08:57",
"revision_id": "0eacbed65316a8fc5608161a6396d36dd89f9170",
"snapshot_id": "991b6acc64f9518361ddbef2c67e05be94c2463f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lta-disco-unimib-it/BCT_TOOLSET/0eacbed65316a8fc5608161a6396d36dd89f9170/BCT_TestCasesProject/BCT/workspace_BCT_Testing/CbmcStaticNondeterministic/struct_test.c",
"visit_date": "2020-08-24T21:06:48.610483"
} | stackv2 | //to cover all assertions it is necessary to run "goto-instrument --nonde-static <a.out> <a.instr.goto>"
#include <stdio.h>
struct str {
int x;
char s[10];
};
int global_x;
struct str global_s;
struct str* global_sp;
int func(int x, struct str s, struct str* sp){
int i;
for( i = 0; i < 10; i++ ){
printf("%c.",s.s[i]);
}
printf("\n");
for( i = 0; i < 10; i++ ){
printf("%c.",sp->s[i]);
}
printf("\n");
}
int cbmc_r();
struct str cbmc_s();
int main(){
struct str p;
char a[] = "ABC";
char b[3];
b[0]='A';
b[1]='B';
b[2]='C';
func(0,p,&p);
func(0,global_s,&global_s);
printf( "%d", (a==b) );
}
| 2.8125 | 3 |
2024-11-18T18:23:06.388699+00:00 | 2017-07-20T17:19:19 | 9c82dc0fcecf105057d9da2e85f36e1b23a93115 | {
"blob_id": "9c82dc0fcecf105057d9da2e85f36e1b23a93115",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-20T17:19:19",
"content_id": "337d06eec8a1fbb3ef54ac4f64920049cedc501e",
"detected_licenses": [
"NCSA"
],
"directory_id": "fb53212a449d2db07398694e2f1b404fe1ae8e27",
"extension": "c",
"filename": "get_sign_1.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 93259903,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 809,
"license": "NCSA",
"license_type": "permissive",
"path": "/examples/get_sign/get_sign_1.c",
"provenance": "stackv2-0003.json.gz:389662",
"repo_name": "youfriend20012001/TracerX_Hybrid_WCET",
"revision_date": "2017-07-20T17:19:19",
"revision_id": "44ecc4d186a0a764247a7caedb2c960c92bed2fc",
"snapshot_id": "4c7d0b04ddc50ae018959e18b2106bb88a3c7989",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/youfriend20012001/TracerX_Hybrid_WCET/44ecc4d186a0a764247a7caedb2c960c92bed2fc/examples/get_sign/get_sign_1.c",
"visit_date": "2021-01-23T14:46:58.126973"
} | stackv2 | /*
* First KLEE tutorial: testing a small function
*/
#include <klee/klee.h>
#include <stdio.h>
#include <string.h>
/**
* Compares two digests for equality. Does a simple byte compare.
*
* @param digesta one of the digests to compare.
*
* @param digestb the other digest to compare.
*
* @return true if the digests are equal, false otherwise.
*/
int isEqual(char digesta[], char digestb[]) {
for (int i = 0; i < 2; i++) {
if (digesta[i] != digestb[i]) {
if(digesta[i] > 0)
return 0;
}
}
return 1;
}
int main() {
char key[6];
klee_make_symbolic(&key, sizeof(key), "key");
char attempt[6];
klee_make_symbolic(&attempt, sizeof(attempt), "attempt");
klee_set_taint(1, &key, sizeof(key));
if(attempt[0] > 0)
return isEqual(key,attempt);
else return 1;
}
| 3.015625 | 3 |
2024-11-18T18:23:06.726979+00:00 | 2021-11-14T18:24:03 | b49556d0473872831088feae578948d774210f0d | {
"blob_id": "b49556d0473872831088feae578948d774210f0d",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-14T18:24:38",
"content_id": "8eb8329e28da90632cf1022133e8de5a112e99d6",
"detected_licenses": [],
"directory_id": "9e62727874a55db556dc5c4b1771de872bf21225",
"extension": "c",
"filename": "benchmark-04-event.c",
"fork_events_count": 1,
"gha_created_at": "2017-11-23T06:14:34",
"gha_event_created_at": "2021-01-28T08:25:49",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 111770656,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13398,
"license": "",
"license_type": "permissive",
"path": "/test/benchmark-04-event.c",
"provenance": "stackv2-0003.json.gz:389790",
"repo_name": "SecureIndustries/medusa",
"revision_date": "2021-11-14T18:24:03",
"revision_id": "8cdf200d0fe492f3f912820b8b17218b4a35d8cd",
"snapshot_id": "4017b6ccffc5b62b706363f80ec07317324d78f5",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/SecureIndustries/medusa/8cdf200d0fe492f3f912820b8b17218b4a35d8cd/test/benchmark-04-event.c",
"visit_date": "2023-08-04T15:03:15.672642"
} | stackv2 |
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h>
#include <signal.h>
#include <event2/event.h>
#include <event2/thread.h>
static int g_backend;
static unsigned int g_nloops;
static unsigned int g_nsamples;
static unsigned int g_ntimers;
static unsigned int g_npipes;
static unsigned int g_nactives;
static unsigned int g_nwrites;
static unsigned int g_fired;
static unsigned int g_count;
static unsigned int g_writes;
static unsigned int g_failures;
static int *g_pipes;
static struct event **g_events;
static void io_onevent (evutil_socket_t fd, short events, void *context)
{
uintptr_t id;
unsigned int wid;
unsigned char ch;
ssize_t n;
id = (uintptr_t) context;
wid = id + 1;
if (events & EV_READ) {
if (g_ntimers) {
struct timeval tv;
event_del(g_events[id]);
tv.tv_sec = 10;
tv.tv_usec = drand48() * 1e6;
event_add(g_events[id], &tv);
}
n = read(fd, (char *) &ch, sizeof(ch));
if (n >= 0) {
g_count += 1;
} else {
g_failures++;
}
if (g_writes) {
if (wid >= g_npipes) {
wid -= g_npipes;
}
n = write(g_pipes[2 * wid + 1], "e", 1);
if (n != 1) {
g_failures++;
}
g_writes--;
g_fired++;
}
}
}
static int test_poll (unsigned int poll)
{
int rc;
unsigned int i;
unsigned int j;
unsigned int k;
unsigned int space;
struct timeval event_timeval;
struct event_base *event_base;
struct timeval create_start;
struct timeval create_finish;
struct timeval create_total;
struct timeval destroy_start;
struct timeval destroy_finish;
struct timeval destroy_total;
struct timeval apply_start;
struct timeval apply_finish;
struct timeval apply_total;
struct timeval run_start;
struct timeval run_finish;
struct timeval run_total;
(void) poll;
event_base = NULL;
evthread_use_pthreads();
timerclear(&create_total);
timerclear(&destroy_total);
timerclear(&apply_total);
timerclear(&run_total);
timerclear(&create_start);
timerclear(&destroy_start);
timerclear(&apply_start);
timerclear(&run_start);
timerclear(&create_finish);
timerclear(&destroy_finish);
timerclear(&apply_finish);
timerclear(&run_finish);
for (j = 0; j < g_nloops; j++) {
gettimeofday(&create_start, NULL);
event_base = event_base_new();
if (event_base == NULL) {
goto bail;
}
for (i = 0; i < g_npipes; i++) {
g_events[i] = event_new(event_base, g_pipes[i * 2], EV_READ | EV_PERSIST, io_onevent, (void *) ((uintptr_t) i));
if (g_events[i] == NULL) {
goto bail;
}
if (g_ntimers) {
event_timeval.tv_sec = 10.;
event_timeval.tv_usec = drand48() * 1e6;
rc = event_add(g_events[i], &event_timeval);
if (rc != 0) {
goto bail;
}
} else {
rc = event_add(g_events[i], NULL);
if (rc != 0) {
goto bail;
}
}
}
rc = event_base_loop(event_base, EVLOOP_ONCE | EVLOOP_NONBLOCK);
if (rc < 0) {
goto bail;
}
gettimeofday(&create_finish, NULL);
timersub(&create_finish, &create_start, &create_finish);
timeradd(&create_finish, &create_total, &create_total);
for (k = 0; k < g_nsamples; k++) {
gettimeofday(&apply_start, NULL);
for (i = 0; i < g_npipes; i++) {
event_del(g_events[i]);
if (g_ntimers) {
event_timeval.tv_sec = 10.;
event_timeval.tv_usec = drand48() * 1e6;
rc = event_add(g_events[i], &event_timeval);
if (rc != 0) {
goto bail;
}
} else {
rc = event_add(g_events[i], NULL);
if (rc != 0) {
goto bail;
}
}
}
rc = event_base_loop(event_base, EVLOOP_ONCE | EVLOOP_NONBLOCK);
if (rc < 0) {
goto bail;
}
gettimeofday(&apply_finish, NULL);
timersub(&apply_finish, &apply_start, &apply_finish);
timeradd(&apply_finish, &apply_total, &apply_total);
g_fired = 0;
space = g_npipes / g_nactives;
space = space * 2;
for (i = 0; i < g_nactives; i++, g_fired++) {
(void) write(g_pipes[i * space + 1], "e", 1);
}
g_count = 0;
g_writes = g_nwrites;
gettimeofday(&run_start, NULL);
do {
rc = event_base_loop(event_base, EVLOOP_ONCE | EVLOOP_NONBLOCK);
if (rc < 0) {
goto bail;
}
} while (g_count != g_fired);
gettimeofday(&run_finish, NULL);
timersub(&run_finish, &run_start, &run_finish);
timeradd(&run_finish, &run_total, &run_total);
fprintf(stderr, "%8ld %8ld %8ld %8ld\n",
create_finish.tv_sec * 1000000 + create_finish.tv_usec,
apply_finish.tv_sec * 1000000 + apply_finish.tv_usec,
run_finish.tv_sec * 1000000 + run_finish.tv_usec,
destroy_finish.tv_sec * 1000000 + destroy_finish.tv_usec);
}
gettimeofday(&destroy_start, NULL);
for (i = 0; i < g_npipes; i++) {
event_free(g_events[i]);
}
event_base_free(event_base);
gettimeofday(&destroy_finish, NULL);
timersub(&destroy_finish, &destroy_start, &destroy_finish);
timeradd(&destroy_finish, &destroy_total, &destroy_total);
}
fprintf(stderr, "%8ld %8ld %8ld %8ld %8ld\n",
create_total.tv_sec * 1000000 + create_total.tv_usec,
apply_total.tv_sec * 1000000 + apply_total.tv_usec,
run_total.tv_sec * 1000000 + run_total.tv_usec,
destroy_total.tv_sec * 1000000 + destroy_total.tv_usec,
(create_total.tv_sec * 1000000 + create_total.tv_usec) +
(apply_total.tv_sec * 1000000 + apply_total.tv_usec) +
(run_total.tv_sec * 1000000 + run_total.tv_usec) +
(destroy_total.tv_sec * 1000000 + destroy_total.tv_usec));
fprintf(stderr, "%8ld %8ld %8ld %8ld %8ld\n",
(create_total.tv_sec * 1000000 + create_total.tv_usec) / g_nloops,
(apply_total.tv_sec * 1000000 + apply_total.tv_usec) / (g_nloops * g_nsamples),
(run_total.tv_sec * 1000000 + run_total.tv_usec) / (g_nloops * g_nsamples),
(destroy_total.tv_sec * 1000000 + destroy_total.tv_usec) / g_nloops,
((create_total.tv_sec * 1000000 + create_total.tv_usec) / g_nloops) +
((apply_total.tv_sec * 1000000 + apply_total.tv_usec) / (g_nloops * g_nsamples)) +
((run_total.tv_sec * 1000000 + run_total.tv_usec) / (g_nloops * g_nsamples)) +
((destroy_total.tv_sec * 1000000 + destroy_total.tv_usec) / g_nloops));
return 0;
bail: if (event_base != NULL) {
event_base_free(event_base);
}
return -1;
}
static void alarm_handler (int sig)
{
(void) sig;
abort();
}
int main (int argc, char *argv[])
{
int c;
int rc;
unsigned int i;
srand(time(NULL));
signal(SIGALRM, alarm_handler);
g_backend = -1;
g_nloops = 10;
g_nsamples = 10;
g_pipes = NULL;
g_npipes = 10;
g_nactives = 2;
g_nwrites = g_npipes;
g_ntimers = 0;
while ((c = getopt(argc, argv, "hb:l:s:n:a:w:t:")) != -1) {
switch (c) {
case 'b':
g_backend = atoi(optarg);
break;
case 'l':
g_nloops = atoi(optarg);
break;
case 's':
g_nsamples = atoi(optarg);
break;
case 'n':
g_npipes = atoi(optarg);
break;
case 'a':
g_nactives = atoi(optarg);
break;
case 'w':
g_nwrites = atoi(optarg);
break;
case 't':
g_ntimers = !!atoi(optarg);
break;
case 'h':
fprintf(stderr, "%s [-b backend] [-l loops] [-s samples] [-n pipes] [-a actives] [-w writes] [-t timers]\n", argv[0]);
fprintf(stderr, " -b: poll backend (default: %d)\n", g_backend);
fprintf(stderr, " -l: loop count (default: %d)\n", g_nloops);
fprintf(stderr, " -s: sample count (default: %d)\n", g_nsamples);
fprintf(stderr, " -n: number of pipes (default: %d)\n", g_npipes);
fprintf(stderr, " -a: number of actives (default: %d)\n", g_nactives);
fprintf(stderr, " -w: number of writes (default: %d)\n", g_nwrites);
fprintf(stderr, " -t: enable timers (default: %d)\n", g_ntimers);
return 0;
default:
fprintf(stderr, "unknown param: %c\n", c);
return -1;
}
}
fprintf(stderr, "backend : %d\n", g_backend);
fprintf(stderr, "loops : %d\n", g_nloops);
fprintf(stderr, "samples : %d\n", g_nsamples);
fprintf(stderr, "pipes : %d\n", g_npipes);
fprintf(stderr, "actives : %d\n", g_nactives);
fprintf(stderr, "writes : %d\n", g_nwrites);
fprintf(stderr, "timers : %d\n", g_ntimers);
g_events = malloc(sizeof(struct medusa_io *) * g_npipes);
if (g_events == NULL) {
return -1;
}
g_pipes = malloc(sizeof(int[2]) * g_npipes);
if (g_pipes == NULL) {
return -1;
}
for (i = 0; i < g_npipes; i++) {
#if 0
rc = pipe(&g_pipes[i * 2]);
#else
rc = socketpair(AF_UNIX, SOCK_STREAM, 0, &g_pipes[i * 2]);
#endif
if (rc != 0) {
fprintf(stderr, "can not create pair: %d\n", i);
return -1;
}
}
rc = test_poll(0);
if (rc != 0) {
fprintf(stderr, "fail\n");
return -1;
}
fprintf(stderr, "success\n");
for (i = 0; i < g_npipes; i++) {
close(g_pipes[i * 2]);
close(g_pipes[i * 2 + 1]);
}
free(g_pipes);
free(g_events);
return 0;
}
| 2.125 | 2 |
2024-11-18T18:23:07.141646+00:00 | 2019-07-05T08:05:12 | 67e0dbaf4a250822d7c72fa9b3393d4e17636ad4 | {
"blob_id": "67e0dbaf4a250822d7c72fa9b3393d4e17636ad4",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-05T08:05:12",
"content_id": "a6fa001808c656431a62ece584331f54d4fa6ed2",
"detected_licenses": [
"MIT"
],
"directory_id": "a3504d40b00599157dc33ddc4176bbb082868d54",
"extension": "c",
"filename": "common.c",
"fork_events_count": 0,
"gha_created_at": "2019-07-05T07:40:06",
"gha_event_created_at": "2019-07-05T07:40:07",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 195362833,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1177,
"license": "MIT",
"license_type": "permissive",
"path": "/common.c",
"provenance": "stackv2-0003.json.gz:390304",
"repo_name": "Fykec/rm-protection-c",
"revision_date": "2019-07-05T08:05:12",
"revision_id": "7a0510ef5bb5ef8da0085c8e9322eb6f7e809e78",
"snapshot_id": "c7db39c4518d8af171d91478e03f9e8a49aff2e0",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Fykec/rm-protection-c/7a0510ef5bb5ef8da0085c8e9322eb6f7e809e78/common.c",
"visit_date": "2020-06-15T18:22:08.397921"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include "common.h"
const char *INVALID_PATH_LIST[] = {
".",
"..",
"./",
"../",
NULL
};
char * get_filename(const char *abs_path) {
static char filename[PATH_MAX + 1];
size_t len, i;
len = strlen(abs_path);
strcpy(filename, abs_path);
for(i = len - 1; i >= 0; i--) {
if(filename[i] == '/') {
return &filename[i + 1];
}
}
return filename;
}
char * get_dir(const char *abs_path) {
static char dir[PATH_MAX + 1];
size_t len, i;
len = strlen(abs_path);
strcpy(dir, abs_path);
for(i = len - 1; i >= 0; i--) {
if(dir[i] == '/') {
dir[i + 1] = 0;
break;
}
}
return dir;
}
int read_line(FILE *src, char *str, size_t max_len) {
size_t i;
int ch;
for(i = 0; i < max_len; i++) {
ch = fgetc(src);
if(ch == EOF || ch == '\n') {
str[i] = 0;
break;
}
str[i] = ch;
}
if (i >= max_len) {
// clear stdin buffer
while ((ch = fgetc(src)) != '\n' && ch != EOF) { };
return 0;
}
return 1;
}
| 2.734375 | 3 |
2024-11-18T18:23:07.659178+00:00 | 2017-11-24T07:00:13 | c5ee702e82efe2dfe5849612c159ca063c8df7aa | {
"blob_id": "c5ee702e82efe2dfe5849612c159ca063c8df7aa",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-24T07:00:13",
"content_id": "83f6fe011fd45709a853f4932391eaa2a88f5125",
"detected_licenses": [
"MIT"
],
"directory_id": "f9d507589b873d2cb0ac76059f208983e738cea2",
"extension": "c",
"filename": "Q52.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 111804410,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 441,
"license": "MIT",
"license_type": "permissive",
"path": "/Q52.c",
"provenance": "stackv2-0003.json.gz:390946",
"repo_name": "Ayush-Rawal/ICSP-assignment",
"revision_date": "2017-11-24T07:00:13",
"revision_id": "c4e170fc5950eb654d43fe6eaca6e8156b359855",
"snapshot_id": "892308e785670edd4eae4aab8b45217d10a5bf85",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ayush-Rawal/ICSP-assignment/c4e170fc5950eb654d43fe6eaca6e8156b359855/Q52.c",
"visit_date": "2021-08-19T00:07:24.267855"
} | stackv2 | //Write a program to print the position of the smallest of n numbers using an array
#include<stdio.h>
int main(void)
{
int size,i,small,pos;
printf("Enter array size ");
scanf("%d",&size);
int arr[size];
printf("\nEnter array\n");
for(i=0;i<size;i++){
scanf("%d",&arr[i]);
small=a[pos];
pos=(a[i]<small)?i:a[0];
}
printf"\nSmallest element is: %d and position(index) is %d",a[pos],pos);
return 0;
} | 3.65625 | 4 |
2024-11-18T18:23:08.189762+00:00 | 2015-06-12T17:42:02 | bdd18a8eb4ea801fde072bb01cc1b6aaf9808675 | {
"blob_id": "bdd18a8eb4ea801fde072bb01cc1b6aaf9808675",
"branch_name": "refs/heads/master",
"committer_date": "2015-06-12T17:42:02",
"content_id": "dd60daac07bbcf7046bbdf6b5703b2032addfe16",
"detected_licenses": [
"MIT"
],
"directory_id": "0fc485709afbb18cec1ba63523f368c596ff759f",
"extension": "c",
"filename": "convert-to-word2vec.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32016277,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5816,
"license": "MIT",
"license_type": "permissive",
"path": "/src/c/convert-to-word2vec.c",
"provenance": "stackv2-0003.json.gz:391202",
"repo_name": "mmehdig/word-sense-modeling",
"revision_date": "2015-06-12T17:42:02",
"revision_id": "843078ca0190808d2d764e2626fa9a0d5bfad41b",
"snapshot_id": "3eb9d4de229227d542ec1d100673ac363b691c7b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mmehdig/word-sense-modeling/843078ca0190808d2d764e2626fa9a0d5bfad41b/src/c/convert-to-word2vec.c",
"visit_date": "2021-01-23T13:43:40.633112"
} | stackv2 | //
// convert-to-word2vec.c
//
//
// Created by Mehdi on 2/19/15.
//
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <malloc.h>
#include <ctype.h>
typedef float real;
const long long max_w = 50; // max length of vocabulary entries
const long long max_dimension = 500; // max length of vocabulary entries
int main(int argc, char **argv)
{
FILE *src;
FILE *trg;
char file_name[2000];
long long words, dimensions, a, b, c, vectors, vectors_prog;
unsigned short int max_s, emb_s, s, if_maxout, default_file_format, n;
float *M;
char *vocab;
char word[max_w];
char buffer[3];
float vector[max_dimension];
if (argc < 2) {
printf("Default usage:\n ./convert-to-word2vec FILE\n");
printf("Second file format usage:\n ./convert-to-word2vec FILE 1\n");
printf("FILE:\tThe address of the multiple-word-vector file in text format.\n");
return 0;
}
strcpy(file_name, argv[1]);
default_file_format = 0;
if (argc > 2) default_file_format = atoi(argv[2]);
src = fopen(file_name, "rb");
if (src == NULL) {
printf("Input file not found\n");
return -1;
}
// maxout!! clusterCenter(v)(s) / (1.0 * clusterCount(v)(s)):
// this vector and next vector are the same
if (default_file_format) {
fscanf(src, "%lld", &words);
fscanf(src, "%lld", &dimensions);
if_maxout = 0;
printf("Scan file for senses\n");
vectors = 0;
for (b = 0; b < words; b++) {
a = 0;
while (1) {
word[a] = fgetc(src);
if (feof(src) || (word[a] == ' ')) break;
if ((a < max_w) && (word[a] != '\n')) a++;
}
word[a] = 0;
if (a == 0) continue;
printf("Number of words in progress: %lld / %lld\r", b, words);
fflush(stdout);
// number of embodied senses
fscanf(src, "%hu", &emb_s);
// maximum number of senses per word:
if (max_s < emb_s) max_s = emb_s;
// sense + cluster center
emb_s *= 2;
// number of sense vectors + global sense
for (s = 0; s < emb_s + 1; s++) {
for (c = 0; c < dimensions; c++) fscanf(src, "%f", &vector[c]);
//dummy newline read:
fgetc(src);
// count vectors
vectors++;
}
}
fclose(src);
src = fopen(file_name, "rb");
fscanf(src, "%lld", &words);
fscanf(src, "%lld", &dimensions);
} else {
fscanf(src, "%lld", &words);
fscanf(src, "%lld", &dimensions);
fscanf(src, "%hu", &max_s);
fscanf(src, "%hu", &if_maxout);
if (if_maxout == 0)
max_s = max_s * 2 + 1;
else
max_s = max_s + 1;
vectors = words * max_s;
}
printf("\nNumber words: %lld\n", words);
printf("Maximum number of senses per word: %hu\n", max_s);
printf("Number of dimensions: %lld\n", dimensions);
printf("Maximum number of vectors: %lld\n", vectors);
vocab = (char *)malloc(vectors * max_w * sizeof(char));
M = (float *)malloc(vectors * dimensions * sizeof(float));
if (M == NULL) {
printf("Cannot allocate memory: %lld MB\n", words * dimensions * sizeof(float) / 1048576);
return -1;
}
vectors_prog = 0;
for (b = 0; b < words; b++) {
a = 0;
while (1) {
word[a] = fgetc(src);
if (feof(src) || (word[a] == ' ')) break;
if ((a < max_w) && (word[a] != '\n')) a++;
}
word[a] = 0;
if (a == 0) continue;
printf("Number of words in progress: %lld / %lld %s\r", b, words, word);
fflush(stdout);
fscanf(src, "%hu", &emb_s);
if (if_maxout == 0) {
emb_s *= 2;
}
// number of sense vectors + global sense
for (s = 0; s < emb_s + 1; s++) {
// add the word-sense to vocapulary
strcpy(&vocab[vectors_prog * max_w], word);
for (c = 0; c < dimensions; c++) fscanf(src, "%f", &M[c + vectors_prog * dimensions]);
if (s > 0) {
strcpy(&vocab[vectors_prog * max_w + a], "..");
if (if_maxout == 0) {
// if it's not maxout format then it has cluster centers too. cluster centers should be annotated by a "c"
n = sprintf(buffer, "%d", (s+1)/2);
strcpy(&vocab[vectors_prog * max_w + a + 2], buffer);
if (s %2 == 0) {
vocab[vectors_prog * max_w + a + 2 + n] = 'c';
vocab[vectors_prog * max_w + a + 3 + n] = 0;
}
} else {
n = sprintf(buffer, "%hu", s);
strcpy(&vocab[vectors_prog * max_w + a + 2], buffer);
}
}
//dummy newline read:
fgetc(src);
// next vector!
vectors_prog++;
}
}
fclose(src);
strcat(file_name, ".flat.bin");
printf("\nStoring on \"%s\"\n", file_name);
trg = fopen(file_name, "wb");
fprintf(trg, "%lld %lld\n", vectors, dimensions);
for (b = 0; b < vectors_prog; b++) {
if (vocab[b * max_w] == 0) break;
fprintf(trg, "%s ", &vocab[b * max_w]);
for (c = 0; c < dimensions; c++)
fwrite(&M[b * dimensions + c], sizeof(real), 1, trg);
}
fclose(trg);
return 0;
}
| 2.671875 | 3 |
2024-11-18T18:23:08.514978+00:00 | 2019-02-11T12:59:19 | 1093bca0f6af126b79fba3ef52e0dfc60d8139d0 | {
"blob_id": "1093bca0f6af126b79fba3ef52e0dfc60d8139d0",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-11T12:59:19",
"content_id": "f76e9b7617a46d60ec23c3522ef98ba70455dce3",
"detected_licenses": [
"MIT"
],
"directory_id": "030451c8d5bdf12d9675ef3bfd2c5b1d853f2ea5",
"extension": "c",
"filename": "config.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": 8176,
"license": "MIT",
"license_type": "permissive",
"path": "/src/config.c",
"provenance": "stackv2-0003.json.gz:391716",
"repo_name": "polaco1782/piworld",
"revision_date": "2019-02-11T12:59:19",
"revision_id": "d3dde72001bb1bee2e865f7a97816ddeb05b3a06",
"snapshot_id": "7287b7812fe48afe67c2ffdfa0b55cdac385f2cc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/polaco1782/piworld/d3dde72001bb1bee2e865f7a97816ddeb05b3a06/src/config.c",
"visit_date": "2020-07-07T17:21:25.217164"
} | stackv2 |
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "x11_event_handler.h"
#include "config.h"
#include "pg.h"
#include "util.h"
Config _config;
Config *config = &_config;
void reset_config() {
get_config_path(config->path);
get_default_db_path(config->db_path);
config->fullscreen = FULLSCREEN;
config->port = DEFAULT_PORT;
config->server[0] = '\0';
config->show_chat_text = SHOW_CHAT_TEXT;
config->show_clouds = SHOW_CLOUDS;
config->show_crosshairs = SHOW_CROSSHAIRS;
config->show_info_text = SHOW_INFO_TEXT;
config->show_item = SHOW_ITEM;
config->show_lights = SHOW_LIGHTS;
config->show_plants = SHOW_PLANTS;
config->show_player_names = SHOW_PLAYER_NAMES;
config->show_trees = SHOW_TREES;
config->show_wireframe = SHOW_WIREFRAME;
config->use_cache = USE_CACHE;
config->verbose = 0;
config->view = AUTO_PICK_VIEW_RADIUS;
config->vsync = VSYNC;
strncpy(config->window_title, WINDOW_TITLE, strlen(WINDOW_TITLE));
config->window_x = CENTRE_IN_SCREEN;
config->window_y = CENTRE_IN_SCREEN;
config->window_width = WINDOW_WIDTH;
config->window_height = WINDOW_HEIGHT;
}
void get_config_path(char *path)
{
#ifdef RELEASE
snprintf(path, MAX_PATH_LENGTH, "%s/.piworld", getenv("HOME"));
mkdir(path, 0755);
#else
// Keep the config and world database in the current dir for dev builds
snprintf(path, MAX_PATH_LENGTH, ".");
#endif
}
void get_default_db_path(char *path)
{
snprintf(path, MAX_PATH_LENGTH, "%s/%s", config->path, DB_FILENAME);
}
void get_server_db_cache_path(char *path)
{
snprintf(path, MAX_PATH_LENGTH,
"%s/cache.%s.%d.db", config->path, config->server, config->port);
}
/*
* Return a draw radius that will fit into the current size of GPU RAM.
*/
int get_starting_draw_radius()
{
int gpu_mb = pg_get_gpu_mem_size();
if (gpu_mb < 48) {
// A draw distance of 1 is not enough for the game to be usable, but
// this does at least show something on screen (for low resolutions
// only - higher ones will crash the game with low GPU RAM).
return 1;
} else if (gpu_mb < 64) {
return 2;
} else if (gpu_mb < 128) {
// A GPU RAM size of 64M will result in rendering issues for draw
// distances greater than 3 (with a chunk size of 16).
return 3;
} else {
// For the Raspberry Pi reduce amount to draw to both fit into 128MiB
// of GPU RAM and keep the render speed at a reasonable smoothness.
return 5;
}
}
void parse_startup_config(int argc, char **argv) {
int c;
const char *opt_name;
while (1) {
int option_index = 0;
static struct option long_options[] = {
{"fullscreen", no_argument, 0, 0 },
{"port", required_argument, 0, 0 },
{"server", required_argument, 0, 0 },
{"show-chat-text", required_argument, 0, 0 },
{"show-crosshairs", required_argument, 0, 0 },
{"show-clouds", required_argument, 0, 0 },
{"show-info-text", required_argument, 0, 0 },
{"show-item", required_argument, 0, 0 },
{"show-lights", required_argument, 0, 0 },
{"show-plants", required_argument, 0, 0 },
{"show-player-names", required_argument, 0, 0 },
{"show-trees", required_argument, 0, 0 },
{"show-wireframe", required_argument, 0, 0 },
{"verbose", no_argument, 0, 0 },
{"use-cache", required_argument, 0, 0 },
{"view", required_argument, 0, 0 },
{"vsync", required_argument, 0, 0 },
{"window-size", required_argument, 0, 0 },
{"window-title", required_argument, 0, 0 },
{"window-xy", required_argument, 0, 0 },
{0, 0, 0, 0 }
};
c = getopt_long(argc, argv, "", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
opt_name = long_options[option_index].name;
if (strncmp(opt_name, "fullscreen", 10) == 0) {
config->fullscreen = 1;
} else if (strncmp(opt_name, "port", 4) == 0 &&
sscanf(optarg, "%d", &config->port) == 1) {
} else if (strncmp(opt_name, "show-chat-text", 15) == 0 &&
sscanf(optarg, "%d", &config->show_chat_text) == 1) {
} else if (strncmp(opt_name, "show-crosshairs", 15) == 0 &&
sscanf(optarg, "%d", &config->show_crosshairs) == 1) {
} else if (strncmp(opt_name, "show-clouds", 11) == 0 &&
sscanf(optarg, "%d", &config->show_clouds) == 1) {
} else if (strncmp(opt_name, "show-info-text", 14) == 0 &&
sscanf(optarg, "%d", &config->show_info_text) == 1) {
} else if (strncmp(opt_name, "show-item", 9) == 0 &&
sscanf(optarg, "%d", &config->show_item) == 1) {
} else if (strncmp(opt_name, "show-lights", 11) == 0 &&
sscanf(optarg, "%d", &config->show_lights) == 1) {
} else if (strncmp(opt_name, "show-plants", 11) == 0 &&
sscanf(optarg, "%d", &config->show_plants) == 1) {
} else if (strncmp(opt_name, "show-player-names", 17) == 0 &&
sscanf(optarg, "%d", &config->show_player_names) == 1) {
} else if (strncmp(opt_name, "show-trees", 10) == 0 &&
sscanf(optarg, "%d", &config->show_trees) == 1) {
} else if (strncmp(opt_name, "show-wireframe", 14) == 0 &&
sscanf(optarg, "%d", &config->show_wireframe) == 1) {
} else if (strncmp(opt_name, "use-cache", 9) == 0 &&
sscanf(optarg, "%d", &config->use_cache) == 1) {
} else if (strncmp(opt_name, "verbose", 7) == 0) {
config->verbose = 1;
} else if (strncmp(opt_name, "view", 4) == 0 &&
sscanf(optarg, "%d", &config->view) == 1) {
} else if (strncmp(opt_name, "vsync", 5) == 0 &&
sscanf(optarg, "%d", &config->vsync) == 1) {
} else if (strncmp(opt_name, "window-size", 11) == 0 &&
sscanf(optarg, "%d,%d", &config->window_width,
&config->window_height) == 2) {
} else if (strncmp(opt_name, "window-title", 12) == 0 &&
sscanf(optarg, "%256c", config->window_title) == 1) {
config->window_title[MIN(strlen(optarg),
MAX_TITLE_LENGTH - 1)] = '\0';
} else if (strncmp(opt_name, "window-xy", 9) == 0 &&
sscanf(optarg, "%d,%d", &config->window_x,
&config->window_y) == 2) {
} else if (strncmp(opt_name, "server", 6) == 0 &&
sscanf(optarg, "%256c", config->server) == 1) {
config->server[MIN(strlen(optarg),
MAX_ADDR_LENGTH - 1)] = '\0';
} else {
printf("Bad argument for: --%s: %s\n", opt_name, optarg);
exit(1);
}
break;
case '?':
// Exit on an unrecognised option
exit(1);
break;
default:
printf("?? getopt returned character code 0%o ??\n", c);
exit(1);
}
}
if (optind < argc) {
strncpy(config->db_path, argv[optind++], MAX_PATH_LENGTH);
if (optind < argc) {
// Exit on extra unnamed arguments
printf("unused ARGV-elements: ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
exit(1);
}
}
}
| 2.0625 | 2 |
2024-11-18T18:23:08.601523+00:00 | 2013-04-17T18:42:40 | 9e24d09f22154d6c02db32bf216081a0cf604084 | {
"blob_id": "9e24d09f22154d6c02db32bf216081a0cf604084",
"branch_name": "refs/heads/master",
"committer_date": "2013-04-17T18:42:40",
"content_id": "8b9117d3432c8733ddb1cc18eee264d329b2e2df",
"detected_licenses": [
"MIT"
],
"directory_id": "bb108c3ea7d235e6fee0575181b5988e6b6a64ef",
"extension": "c",
"filename": "xmen.c",
"fork_events_count": 8,
"gha_created_at": "2012-03-23T04:23:01",
"gha_event_created_at": "2013-04-17T18:42:41",
"gha_language": "C",
"gha_license_id": null,
"github_id": 3805274,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7806,
"license": "MIT",
"license_type": "permissive",
"path": "/mame/src/mame/video/xmen.c",
"provenance": "stackv2-0003.json.gz:391847",
"repo_name": "clobber/MAME-OS-X",
"revision_date": "2013-04-17T18:42:40",
"revision_id": "ca11d0e946636bda042b6db55c82113e5722fc08",
"snapshot_id": "3c5e6058b2814754176f3c6dcf1b2963ca804fc3",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/clobber/MAME-OS-X/ca11d0e946636bda042b6db55c82113e5722fc08/mame/src/mame/video/xmen.c",
"visit_date": "2021-01-20T05:31:15.086981"
} | stackv2 | #include "emu.h"
#include "video/konicdev.h"
#include "includes/xmen.h"
/***************************************************************************
Callbacks for the K052109
***************************************************************************/
void xmen_tile_callback( running_machine &machine, int layer, int bank, int *code, int *color, int *flags, int *priority )
{
xmen_state *state = machine.driver_data<xmen_state>();
/* (color & 0x02) is flip y handled internally by the 052109 */
if (layer == 0)
*color = state->m_layer_colorbase[layer] + ((*color & 0xf0) >> 4);
else
*color = state->m_layer_colorbase[layer] + ((*color & 0x7c) >> 2);
}
/***************************************************************************
Callbacks for the K053247
***************************************************************************/
void xmen_sprite_callback( running_machine &machine, int *code, int *color, int *priority_mask )
{
xmen_state *state = machine.driver_data<xmen_state>();
int pri = (*color & 0x00e0) >> 4; /* ??????? */
if (pri <= state->m_layerpri[2])
*priority_mask = 0;
else if (pri > state->m_layerpri[2] && pri <= state->m_layerpri[1])
*priority_mask = 0xf0;
else if (pri > state->m_layerpri[1] && pri <= state->m_layerpri[0])
*priority_mask = 0xf0 | 0xcc;
else
*priority_mask = 0xf0 | 0xcc | 0xaa;
*color = state->m_sprite_colorbase + (*color & 0x001f);
}
/***************************************************************************
Start the video hardware emulation.
***************************************************************************/
VIDEO_START( xmen6p )
{
xmen_state *state = machine.driver_data<xmen_state>();
k053247_get_ram(state->m_k053246, &state->m_k053247_ram);
state->m_screen_left = auto_bitmap_alloc(machine, 64 * 8, 32 * 8, BITMAP_FORMAT_INDEXED16);
state->m_screen_right = auto_bitmap_alloc(machine, 64 * 8, 32 * 8, BITMAP_FORMAT_INDEXED16);
state->save_item(NAME(*state->m_screen_left));
state->save_item(NAME(*state->m_screen_right));
}
/***************************************************************************
Display refresh
***************************************************************************/
SCREEN_UPDATE( xmen )
{
xmen_state *state = screen->machine().driver_data<xmen_state>();
int layer[3], bg_colorbase;
bg_colorbase = k053251_get_palette_index(state->m_k053251, K053251_CI4);
state->m_sprite_colorbase = k053251_get_palette_index(state->m_k053251, K053251_CI1);
state->m_layer_colorbase[0] = k053251_get_palette_index(state->m_k053251, K053251_CI3);
state->m_layer_colorbase[1] = k053251_get_palette_index(state->m_k053251, K053251_CI0);
state->m_layer_colorbase[2] = k053251_get_palette_index(state->m_k053251, K053251_CI2);
k052109_tilemap_update(state->m_k052109);
layer[0] = 0;
state->m_layerpri[0] = k053251_get_priority(state->m_k053251, K053251_CI3);
layer[1] = 1;
state->m_layerpri[1] = k053251_get_priority(state->m_k053251, K053251_CI0);
layer[2] = 2;
state->m_layerpri[2] = k053251_get_priority(state->m_k053251, K053251_CI2);
konami_sortlayers3(layer, state->m_layerpri);
bitmap_fill(screen->machine().priority_bitmap, cliprect, 0);
/* note the '+1' in the background color!!! */
bitmap_fill(bitmap, cliprect, 16 * bg_colorbase + 1);
k052109_tilemap_draw(state->m_k052109, bitmap, cliprect, layer[0], 0, 1);
k052109_tilemap_draw(state->m_k052109, bitmap, cliprect, layer[1], 0, 2);
k052109_tilemap_draw(state->m_k052109, bitmap, cliprect, layer[2], 0, 4);
/* this isn't supported anymore and it is unsure if still needed; keeping here for reference
pdrawgfx_shadow_lowpri = 1; fix shadows of boulders in front of feet */
k053247_sprites_draw(state->m_k053246, bitmap, cliprect);
return 0;
}
SCREEN_UPDATE( xmen6p )
{
xmen_state *state = screen->machine().driver_data<xmen_state>();
int x, y;
if (screen == state->m_lscreen)
for(y = 0; y < 32 * 8; y++)
{
UINT16* line_dest = BITMAP_ADDR16(bitmap, y, 0);
UINT16* line_src = BITMAP_ADDR16(state->m_screen_left, y, 0);
for (x = 12 * 8; x < 52 * 8; x++)
line_dest[x] = line_src[x];
}
else if (screen == state->m_rscreen)
for(y = 0; y < 32 * 8; y++)
{
UINT16* line_dest = BITMAP_ADDR16(bitmap, y, 0);
UINT16* line_src = BITMAP_ADDR16(state->m_screen_right, y, 0);
for (x = 12 * 8; x < 52 * 8; x++)
line_dest[x] = line_src[x];
}
return 0;
}
/* my lefts and rights are mixed up in several places.. */
SCREEN_EOF( xmen6p )
{
xmen_state *state = machine.driver_data<xmen_state>();
int layer[3], bg_colorbase;
bitmap_t * renderbitmap;
rectangle cliprect;
int offset;
state->m_current_frame ^= 0x01;
// const rectangle *visarea = machine.primary_screen->visible_area();
// cliprect.min_x = visarea->min_x;
// cliprect.max_x = visarea->max_x;
// cliprect.min_y = visarea->min_y;
// cliprect.max_y = visarea->max_y;
cliprect.min_x = 0;
cliprect.max_x = 64 * 8 - 1;
cliprect.min_y = 2 * 8;
cliprect.max_y = 30 * 8 - 1;
if (state->m_current_frame & 0x01)
{
/* copy the desired spritelist to the chip */
memcpy(state->m_k053247_ram, state->m_xmen6p_spriteramright, 0x1000);
/* we write the entire content of the tileram to the chip to ensure
everything gets marked as dirty and the desired tilemap is rendered
this is not very efficient!
*/
for (offset = 0; offset < (0xc000 / 2); offset++)
{
// K052109_lsb_w
k052109_w(state->m_k052109, offset, state->m_xmen6p_tilemapright[offset] & 0x00ff);
}
renderbitmap = state->m_screen_right;
}
else
{
/* copy the desired spritelist to the chip */
memcpy(state->m_k053247_ram, state->m_xmen6p_spriteramleft, 0x1000);
/* we write the entire content of the tileram to the chip to ensure
everything gets marked as dirty and the desired tilemap is rendered
this is not very efficient!
*/
for (offset = 0; offset < (0xc000 / 2); offset++)
{
// K052109_lsb_w
k052109_w(state->m_k052109, offset, state->m_xmen6p_tilemapleft[offset] & 0x00ff);
}
renderbitmap = state->m_screen_left;
}
bg_colorbase = k053251_get_palette_index(state->m_k053251, K053251_CI4);
state->m_sprite_colorbase = k053251_get_palette_index(state->m_k053251, K053251_CI1);
state->m_layer_colorbase[0] = k053251_get_palette_index(state->m_k053251, K053251_CI3);
state->m_layer_colorbase[1] = k053251_get_palette_index(state->m_k053251, K053251_CI0);
state->m_layer_colorbase[2] = k053251_get_palette_index(state->m_k053251, K053251_CI2);
k052109_tilemap_update(state->m_k052109);
layer[0] = 0;
state->m_layerpri[0] = k053251_get_priority(state->m_k053251, K053251_CI3);
layer[1] = 1;
state->m_layerpri[1] = k053251_get_priority(state->m_k053251, K053251_CI0);
layer[2] = 2;
state->m_layerpri[2] = k053251_get_priority(state->m_k053251, K053251_CI2);
konami_sortlayers3(layer, state->m_layerpri);
bitmap_fill(machine.priority_bitmap, &cliprect, 0);
/* note the '+1' in the background color!!! */
bitmap_fill(renderbitmap, &cliprect, 16 * bg_colorbase + 1);
k052109_tilemap_draw(state->m_k052109, renderbitmap, &cliprect, layer[0], 0, 1);
k052109_tilemap_draw(state->m_k052109, renderbitmap, &cliprect, layer[1], 0, 2);
k052109_tilemap_draw(state->m_k052109, renderbitmap, &cliprect, layer[2], 0, 4);
/* this isn't supported anymore and it is unsure if still needed; keeping here for reference
pdrawgfx_shadow_lowpri = 1; fix shadows of boulders in front of feet */
k053247_sprites_draw(state->m_k053246, renderbitmap, &cliprect);
}
| 2.078125 | 2 |
2024-11-18T18:23:08.803850+00:00 | 2020-03-02T02:08:08 | eae474dd91bd1a49eb80994ebc54603b3ecad79c | {
"blob_id": "eae474dd91bd1a49eb80994ebc54603b3ecad79c",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-02T02:08:08",
"content_id": "4cdd0473bb4254f803b99ce4010bc3aba03bdcc2",
"detected_licenses": [
"MIT"
],
"directory_id": "4cafcca5bc3542e889d5266daee92bbd1896b6fa",
"extension": "c",
"filename": "patch.c",
"fork_events_count": 18,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 4315621,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3314,
"license": "MIT",
"license_type": "permissive",
"path": "/replay/patch.c",
"provenance": "stackv2-0003.json.gz:392232",
"repo_name": "robertabcd/lol-ob",
"revision_date": "2020-03-02T02:08:08",
"revision_id": "92143e014749daf7e702c7f160a317eb51eca21c",
"snapshot_id": "2ea64fd72a75e09479d022277453692443976e0a",
"src_encoding": "UTF-8",
"star_events_count": 63,
"url": "https://raw.githubusercontent.com/robertabcd/lol-ob/92143e014749daf7e702c7f160a317eb51eca21c/replay/patch.c",
"visit_date": "2021-05-16T03:05:39.662327"
} | stackv2 | /*
* Patch ``League of Legends.exe'' by replacing the public key
* in the executable.
*
* You may generate your own RSA2048 key pair by
* $ openssl genrsa -out my 2048
* $ openssl rsa -in my -pubout > my.pub
*
*
* Robert <robertabcd at gmail.com>
* 2013/6/2
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *lolpub =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1mV8+Ez6EEdQtCYPewmO"
"dhG4ElhApH3AQe1TReKZNHP/uYTQSNE9vAly7W/sXFAJPTUtwXqOeFwMqumzuk3T"
"iXJhQul/zywcBKRawVxgN7qMAdPv7t5AijWh1brDrevdOlwzPwUp24ar96YKDefS"
"73EFnY1xoEqSs1DnkrwKN0Nb8Sjwgs5XrZiLV03U1SlqJD2nHhhLpAAgnKeY6vJN"
"/+H3l/TXfvrbi4b+9GjJkGiahREEvJN2FnKSPofI+gPfA2rXUQTNeSDMYsPhAaV6"
"JPY4iZBpb1//6/p2fTbL1inYDhC5KDuSPPoBHmZFm8gT10jAk1V9fuWeweYAIIve"
"5wIDAQAB";
/* Change this to your public key */
const char *mypub =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp7H6dxiftfx2YVusyjzU"
"Nj2IVycziBlvlKNyak21ofjRH2Ogej/n+M2skuwKshHKqAcApSC9jaF6gaS67Uhc"
"lHp3yHH1OR8jUUL1sZPK69AlElQyfv8XOMPTKq59viG2k1ta9Xq8vZ1bXlvosJIY"
"L0GryBfsyEQc+VGRhzGhrEXgaRiizlHF0rQGd2NAVZ4v8/lp3lQ+7rVRT9ji6qCm"
"BCI+lKEWy/DL7zwaRYV8crgiXll5Y9xYZnmVxag3USvOWmLVVRuLRq9i280iO7pJ"
"jmppXNv4prmmIDyqjgk0ML3GPCrh2Y11o5QPnCT7Dlj+QuYunKGOFJPRawly/0ax"
"QwIDAQAB";
int *build_table(const char *data, int len) {
int *t = (int *) calloc(len, sizeof(int));
int i = 2, m = 0;
while (i < len) {
if (data[i - 1] == data[m])
t[i++] = ++m;
else if (m > 0)
m = t[m];
else
t[i++] = 0;
}
return t;
}
int match(const char *data, int dlen, const char *patt, int plen) {
int *t = build_table(patt, plen);
int i = 0, m = 0;
while (i < dlen) {
if (data[i] == patt[m]) {
i++;
if (++m == plen)
break;
} else if (m > 0) {
m = t[m];
} else {
i++;
}
}
free(t);
return m == plen ? i - m : dlen;
}
int main(int argc, char *argv[]) {
assert(sizeof(lolpub) == sizeof(mypub));
if (argc != 2) {
fprintf(stderr, "Usage: %s <executable>\n", argv[0]);
return 1;
}
FILE *fp;
int size;
char *buffer;
// load the file
if ((fp = fopen(argv[1], "rb")) == NULL) {
perror("Cannot open executable");
return 1;
}
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
if ((buffer = (char *) malloc(size)) == NULL) {
fprintf(stderr, "Cannot allocate memory\n");
return 1;
}
if (fread(buffer, size, 1, fp) != 1) {
fprintf(stderr, "Cannot read file\n");
return 1;
}
fclose(fp);
// find key
int pos = match(buffer, size, lolpub, strlen(lolpub));
if (pos >= size) {
fprintf(stderr, "Cannot find pattern\n");
return 1;
}
printf("Public key at %d\n", pos);
// make a backup
char *backupfn = (char *) malloc(strlen(argv[1]) + 10);
strcpy(backupfn, argv[1]);
strcat(backupfn, ".bak");
if ((fp = fopen(backupfn, "wb")) == NULL) {
fprintf(stderr, "Cannot open backup file for writing\n");
return 1;
}
if (fwrite(buffer, size, 1, fp) != 1) {
fprintf(stderr, "Cannot write to backup file\n");
return 1;
}
fclose(fp);
// replace key
memcpy(buffer + pos, mypub, strlen(lolpub));
// save
if ((fp = fopen(argv[1], "wb")) == NULL) {
fprintf(stderr, "Cannot save patched file\n");
return 1;
}
if (fwrite(buffer, size, 1, fp) != 1) {
fprintf(stderr, "Cannot write to patched file\n");
return 1;
}
fclose(fp);
return 0;
}
| 2.140625 | 2 |
2024-11-18T18:23:09.217679+00:00 | 2015-01-03T15:07:54 | b34df192f0703567c7760f7a9a9c9bc1b3541680 | {
"blob_id": "b34df192f0703567c7760f7a9a9c9bc1b3541680",
"branch_name": "refs/heads/master",
"committer_date": "2015-01-03T15:07:54",
"content_id": "a02f21705cca100e0807af0ea2f3047be47aba35",
"detected_licenses": [
"MIT"
],
"directory_id": "24320d64b13d43325ecff5a42c95df13916690a8",
"extension": "c",
"filename": "fibonacci.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 28746268,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1089,
"license": "MIT",
"license_type": "permissive",
"path": "/math/fibonacci.c",
"provenance": "stackv2-0003.json.gz:392748",
"repo_name": "csitd/c-utils",
"revision_date": "2015-01-03T15:07:54",
"revision_id": "abde33a89a9cb792648230769bb55e3662272a52",
"snapshot_id": "2c21e731ab6db1897f2152d3661c0cede20e17b9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/csitd/c-utils/abde33a89a9cb792648230769bb55e3662272a52/math/fibonacci.c",
"visit_date": "2021-01-10T21:40:27.500379"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
/* C 2014, MIT license, "fibonacci.c" C. Graff */
/* Populate an array with the fibonacci number sequence. */
unsigned long fibonacci(unsigned long);
void print_array(unsigned long *, unsigned long);
int main()
{
unsigned long c = 0;
/* after "94" iterations the fibonacci number is too large for an unsigned int */
unsigned long elements = 94;
unsigned long *numray = malloc(elements * sizeof(unsigned long));
while (c < elements)
numray[c++] = fibonacci(c + 1);
print_array(numray, elements);
return 0;
}
void print_array(unsigned long *a, unsigned long b)
{
unsigned long c;
for (c=0 ; c < b ; c++)
printf("%lu\n", a[c]);
}
unsigned long fibonacci(unsigned long n)
{
unsigned long alpha=0, omega=1, incra=0, c=0;
for ( ; c < n ; c++ ) {
if ( c <= 1 )
{ incra = c; continue; }
incra = alpha + omega;
alpha = omega;
omega = incra;
}
return (incra);
}
| 3.625 | 4 |
2024-11-18T18:23:11.769047+00:00 | 2021-06-23T10:15:18 | a4a4f78c17c5f9e4212230caad41ed64de4f36a0 | {
"blob_id": "a4a4f78c17c5f9e4212230caad41ed64de4f36a0",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-23T10:15:18",
"content_id": "464373bf91df0a4f5d69b8bf7b21d57e65709017",
"detected_licenses": [
"MIT"
],
"directory_id": "741ed13f23e9a655cf2e34ac322fd6f09da8d709",
"extension": "c",
"filename": "file.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 367299492,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9793,
"license": "MIT",
"license_type": "permissive",
"path": "/src/file.c",
"provenance": "stackv2-0003.json.gz:393133",
"repo_name": "bplaat/goldos",
"revision_date": "2021-06-23T10:15:18",
"revision_id": "086f1fdc98ffc25de3f2d221fda21ef55c277f7c",
"snapshot_id": "291f8402eb47771a9910b5e75a35f9cd1c197a5f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/bplaat/goldos/086f1fdc98ffc25de3f2d221fda21ef55c277f7c/src/file.c",
"visit_date": "2023-06-02T19:58:45.934482"
} | stackv2 | #include "file.h"
#include "disk.h"
#include "eeprom.h"
#include <stdlib.h>
#include <string.h>
File files[FILE_SIZE];
int8_t file_open(char *name, uint8_t mode) {
uint16_t block_address = DISK_BLOCK_ALIGN;
while (block_address <= EEPROM_SIZE - 2 - 2) {
uint16_t real_block_address = block_address + 2;
uint16_t block_header = eeprom_read_word(block_address);
uint16_t block_size = block_header & 0x7fff;
if ((block_header & 0x8000) != 0) {
uint8_t file_name_size = eeprom_read_byte(real_block_address);
if (file_name_size != 0) {
char file_name[64];
for (uint8_t i = 0; i < file_name_size; i++) {
file_name[i] = eeprom_read_byte(real_block_address + 1 + i);
}
file_name[file_name_size] = '\0';
if (!strcmp(file_name, name)) {
for (int8_t i = 0; i < FILE_SIZE; i++) {
if (files[i].address == 0) {
files[i].address = real_block_address;
files[i].name_size = file_name_size;
if (mode == FILE_OPEN_MODE_READ) {
files[i].size = eeprom_read_word(real_block_address + 1 + file_name_size);
files[i].position = 0;
}
if (mode == FILE_OPEN_MODE_WRITE) {
files[i].size = 0;
files[i].position = 0;
eeprom_write_word(real_block_address + 1 + file_name_size, files[i].size);
}
if (mode == FILE_OPEN_MODE_APPEND) {
files[i].size = eeprom_read_word(real_block_address + 1 + file_name_size);
files[i].position = files[i].size;
}
return i;
}
}
return - 1;
}
}
}
block_address += 2 + block_size + 2;
}
if (mode == FILE_OPEN_MODE_WRITE || mode == FILE_OPEN_MODE_APPEND) {
for (int8_t i = 0; i < FILE_SIZE; i++) {
if (files[i].address == 0) {
files[i].name_size = strlen(name);
files[i].address = disk_alloc(1 + files[i].name_size + 2);
files[i].size = 0;
files[i].position = 0;
eeprom_write_byte(files[i].address, files[i].name_size);
for (uint8_t j = 0; j < files[i].name_size; j++) {
eeprom_write_byte(files[i].address + 1 + j, name[j]);
}
eeprom_write_word(files[i].address + 1 + files[i].name_size, files[i].size);
return i;
}
}
}
return -1;
}
bool file_name(int8_t file, char *buffer) {
if (file >= 0 && file < FILE_SIZE && files[file].address != 0) {
for (uint8_t i = 0; i < files[file].name_size; i++) {
buffer[i] = eeprom_read_byte(files[file].address + 1 + i);
}
buffer[files[file].name_size] = '\0';
return true;
}
return false;
}
int16_t file_size(int8_t file) {
if (file >= 0 && file < FILE_SIZE && files[file].address != 0) {
return files[file].size;
}
return -1;
}
int16_t file_position(int8_t file) {
if (file >= 0 && file < FILE_SIZE && files[file].address != 0) {
return files[file].position;
}
return -1;
}
bool file_seek(int8_t file, int16_t position) {
if (file >= 0 && file < FILE_SIZE && files[file].address != 0) {
files[file].position = position;
return true;
}
return false;
}
int16_t file_read(int8_t file, uint8_t *buffer, int16_t size) {
if (file >= 0 && file < FILE_SIZE && files[file].address != 0) {
int16_t bytes_read = 0;
while (bytes_read < size && files[file].position < files[file].size) {
buffer[bytes_read++] = eeprom_read_byte(files[file].address + 1 + files[file].name_size + 2 + files[file].position++);
}
return bytes_read;
}
return -1;
}
int16_t file_write(int8_t file, uint8_t *buffer, int16_t size) {
if (file >= 0 && file < FILE_SIZE && files[file].address != 0) {
if (size == -1) size = strlen((char *)buffer);
uint16_t new_size = files[file].size + size;
uint16_t block_size = eeprom_read_word(files[file].address - 2) & 0x7fff;
if (new_size > block_size - 1 - files[file].name_size - 2) {
uint16_t new_block_address = disk_alloc(1 + files[file].name_size + 2 + new_size);
if (new_block_address != 0) {
for (uint16_t i = 0; i < block_size; i++) {
uint8_t byte = eeprom_read_byte(files[file].address + i);
eeprom_write_byte(new_block_address + i, byte);
}
disk_free(files[file].address);
files[file].address = new_block_address;
} else {
return -1;
}
}
files[file].size = new_size;
eeprom_write_word(files[file].address + 1 + files[file].name_size, files[file].size);
int16_t bytes_writen = 0;
while (bytes_writen < size) {
eeprom_write_byte(files[file].address + 1 + files[file].name_size + 2 + files[file].position++, buffer[bytes_writen++]);
}
return bytes_writen;
}
return -1;
}
bool file_close(int8_t file) {
if (file >= 0 && file < FILE_SIZE && files[file].address != 0) {
files[file].address = 0;
return true;
}
return false;
}
bool file_rename(char *old_name, char *new_name) {
uint16_t block_address = DISK_BLOCK_ALIGN;
while (block_address <= EEPROM_SIZE - 2 - 2) {
uint16_t block_header = eeprom_read_word(block_address);
uint16_t block_size = block_header & 0x7fff;
if ((block_header & 0x8000) != 0) {
uint16_t old_block_address = block_address + 2;
uint8_t file_name_size = eeprom_read_byte(old_block_address);
if (file_name_size != 0) {
char file_name[64];
for (uint8_t i = 0; i < file_name_size; i++) {
file_name[i] = eeprom_read_byte(old_block_address + 1 + i);
}
file_name[file_name_size] = '\0';
uint16_t file_size = eeprom_read_word(old_block_address + 1 + file_name_size);
if (!strcmp(file_name, old_name)) {
uint8_t new_file_name_size = strlen(new_name);
uint16_t new_block_address = disk_alloc(1 + new_file_name_size + 2 + file_size);
if (new_block_address != 0) {
for (uint16_t i = 0; i < file_size; i++) {
uint8_t byte = eeprom_read_byte(old_block_address + 1 + file_name_size + 2 + i);
eeprom_write_byte(new_block_address + 1 + new_file_name_size + 2 + i, byte);
}
eeprom_write_byte(new_block_address, new_file_name_size);
for (uint8_t i = 0; i < new_file_name_size; i++) {
eeprom_write_byte(new_block_address + 1 + i, new_name[i]);
}
eeprom_write_word(new_block_address + 1 + new_file_name_size, file_size);
disk_free(old_block_address);
return true;
} else {
return false;
}
}
}
}
block_address += 2 + block_size + 2;
}
return false;
}
bool file_delete(char *name) {
uint16_t block_address = DISK_BLOCK_ALIGN;
while (block_address <= EEPROM_SIZE - 2 - 2) {
uint16_t block_header = eeprom_read_word(block_address);
uint16_t real_block_address = block_address + 2;
uint16_t block_size = block_header & 0x7fff;
if ((block_header & 0x8000) != 0) {
uint8_t file_name_size = eeprom_read_byte(real_block_address);
if (file_name_size != 0) {
char file_name[64];
for (uint8_t i = 0; i < file_name_size; i++) {
file_name[i] = eeprom_read_byte(real_block_address + 1 + i);
}
file_name[file_name_size] = '\0';
if (!strcmp(file_name, name)) {
disk_free(real_block_address);
return true;
}
}
}
block_address += 2 + block_size + 2;
}
return false;
}
bool file_list(char *name, uint16_t *size) {
static uint16_t block_address = DISK_BLOCK_ALIGN;
while (block_address <= EEPROM_SIZE - 2 - 2) {
uint16_t block_header = eeprom_read_word(block_address);
uint16_t real_block_address = block_address + 2;
uint16_t block_size = block_header & 0x7fff;
if ((block_header & 0x8000) != 0) {
uint8_t file_name_size = eeprom_read_byte(real_block_address);
if (file_name_size != 0) {
for (uint8_t i = 0; i < file_name_size; i++) {
name[i] = eeprom_read_byte(real_block_address + 1 + i);
}
name[file_name_size] = '\0';
*size = eeprom_read_word(real_block_address + 1 + file_name_size);
block_address += 2 + block_size + 2;
return true;
}
}
block_address += 2 + block_size + 2;
}
block_address = DISK_BLOCK_ALIGN;
return false;
}
| 2.6875 | 3 |
2024-11-18T18:23:11.835351+00:00 | 2021-01-16T17:47:43 | 56bf6332c5993f84b86cd5db53f04eaafbb5c61f | {
"blob_id": "56bf6332c5993f84b86cd5db53f04eaafbb5c61f",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-16T17:47:43",
"content_id": "b08c3329eff0319f0609f624b4e123194a0f123b",
"detected_licenses": [
"MIT"
],
"directory_id": "105022505b77331ee0c612c5a2c2f33024e92f8e",
"extension": "h",
"filename": "acs.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 302716922,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 871,
"license": "MIT",
"license_type": "permissive",
"path": "/src/acs.h",
"provenance": "stackv2-0003.json.gz:393262",
"repo_name": "JacobLondon/actualcsock",
"revision_date": "2021-01-16T17:47:43",
"revision_id": "9fea82ffdb88b012661b38a6937ae99ef2dd20dc",
"snapshot_id": "896a669df44ea2d2702d2758d3e1316011608b20",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/JacobLondon/actualcsock/9fea82ffdb88b012661b38a6937ae99ef2dd20dc/src/acs.h",
"visit_date": "2023-02-15T17:16:22.171024"
} | stackv2 | #ifndef ACTUAL_C_SOCKETS_H
#define ACTUAL_C_SOCKETS_H
/**
* ACS just blocking TCP client sockets, use something
* easier for servers like Python's socketserver
*
* Works on Windows (Visual C)
* Works on Unix-based
*/
#include <stddef.h> // size_t
struct acs;
enum acs_code {
ACS_OK,
ACS_ERROR,
ACS_RESET,
};
enum acs_code acs_init(void);
void acs_cleanup(void);
/**
* Create an acs struct to connect with, acs_init must have been called
*/
struct acs *acs_new(const char *host, const char *port);
/**
* Delete an acs struct
*/
void acs_del(struct acs *self);
/**
* Send \a bytes of \a buf
*
* \return
* 0 success
* -1 acs_dial error
* -2 send error
*/
enum acs_code acs_send(struct acs *self, char *buf, size_t bytes);
enum acs_code acs_recv(struct acs *self, char *buf, size_t bytes);
#endif // ACTUAL_C_SOCKETS_H
| 2.0625 | 2 |
2024-11-18T18:23:11.897154+00:00 | 2020-06-17T00:52:19 | b03693b2c4024e67c5b343d41bfddaa23f5e2ec2 | {
"blob_id": "b03693b2c4024e67c5b343d41bfddaa23f5e2ec2",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-17T00:52:19",
"content_id": "379ae8910f7871e1eecd54ed85f56e509e958430",
"detected_licenses": [
"MIT"
],
"directory_id": "20af59fadeacfadba09773a5d8a2e121109d2fdc",
"extension": "c",
"filename": "relacionamentosC.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 272843013,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 733,
"license": "MIT",
"license_type": "permissive",
"path": "/Linguagem C/relacionamentosC.c",
"provenance": "stackv2-0003.json.gz:393392",
"repo_name": "marcelofsilveira/ExerciciosC-Atualizado",
"revision_date": "2020-06-17T00:52:19",
"revision_id": "713290dc459cdf6ce2d444067aba12feb2145994",
"snapshot_id": "88f957e95b0415cfbfe8d831f10f4b2e69e32aeb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marcelofsilveira/ExerciciosC-Atualizado/713290dc459cdf6ce2d444067aba12feb2145994/Linguagem C/relacionamentosC.c",
"visit_date": "2022-11-05T17:13:38.950448"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
main () {
int num1, num2;
printf("Informados 2 numeros inteiros, lhe direi qual relacionamento satisfazem: \n");
printf("Digite o primeiro numero inteiro: \n");
scanf("%d", &num1);
printf("Digite o segundo numero inteiro: \n");
scanf("%d", &num2);
if (num1 == num2)
printf("%d eh igual a %d\n", num1, num2);
if (num1 != num2)
printf("%d eh diferente a %d\n", num1, num2);
if (num1 < num2)
printf("%d eh menor a %d\n", num1, num2);
if (num1 > num2)
printf("%d eh maior a %d\n", num1, num2);
if (num1 <= num2)
printf("%d eh menor ou igual a %d\n", num1, num2);
if (num1 >= num2)
printf("%d eh maior ou igual a %d\n", num1, num2);
return 0;
}
| 3.6875 | 4 |
2024-11-18T18:23:11.990100+00:00 | 2019-05-07T15:08:27 | 16968b215424b5f36f707b8e627906e694303024 | {
"blob_id": "16968b215424b5f36f707b8e627906e694303024",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-07T15:08:27",
"content_id": "b0c0c2820cc34ddbd038eca52ebe58b754e19cb1",
"detected_licenses": [
"MIT"
],
"directory_id": "25e76410612348be2a25dd172003f3fb6ec41ab1",
"extension": "c",
"filename": "pbuffer_set_offset.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": 540,
"license": "MIT",
"license_type": "permissive",
"path": "/src/pixelbuffer/pbuffer_set_offset.c",
"provenance": "stackv2-0003.json.gz:393520",
"repo_name": "Excloudx6/BillyScene",
"revision_date": "2019-05-07T15:08:27",
"revision_id": "31d1d8b43d0ae56376d66efa462bef8b5751a5b3",
"snapshot_id": "19542510c972d7ea1989786fa785175be4c2f27a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Excloudx6/BillyScene/31d1d8b43d0ae56376d66efa462bef8b5751a5b3/src/pixelbuffer/pbuffer_set_offset.c",
"visit_date": "2023-03-21T22:06:28.185362"
} | stackv2 | /*
** BillyScene, 2018
** pbuffer_set_offset
** File description:
** bs_pbuffer_set_offset
*/
#include "bs_components.h"
#include "bs_prototypes.h"
#include <stdbool.h>
/**
* @brief Sets the pbuffer's offset
*
* @param pbuffer
* @param offset_x
* @param offset_y
* @return true
* @return false
*/
bool bs_pbuffer_set_offset(bs_pbuffer_t *pbuffer, \
float offset_x, float offset_y)
{
if (pbuffer == NULL) {
return (false);
}
pbuffer->offset.x = offset_x;
pbuffer->offset.y = offset_y;
return (true);
}
| 2.609375 | 3 |
2024-11-18T18:23:13.008396+00:00 | 2015-03-02T07:39:23 | cd58acfff2bd24a2341fa8aae51e87f7a30f47c1 | {
"blob_id": "cd58acfff2bd24a2341fa8aae51e87f7a30f47c1",
"branch_name": "refs/heads/master",
"committer_date": "2015-03-02T07:39:23",
"content_id": "28f5346e4810456a285340e24681d43fa7b1a533",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f37c3546f39d7ebc4236c043e740d68bf826e8c1",
"extension": "c",
"filename": "KplExtensionsLinux.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": 1709,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/build/linux/kpl/KplExtensionsLinux.c",
"provenance": "stackv2-0003.json.gz:393776",
"repo_name": "sandy-slin/kinomajs",
"revision_date": "2015-03-02T07:39:23",
"revision_id": "567b52be74ec1482e0bab2d370781a7188aeb0ab",
"snapshot_id": "f08f60352b63f1d3fad3f6b0e9a5e4bc8025f082",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sandy-slin/kinomajs/567b52be74ec1482e0bab2d370781a7188aeb0ab/build/linux/kpl/KplExtensionsLinux.c",
"visit_date": "2020-12-24T22:21:05.506599"
} | stackv2 | /*
Copyright (C) 2010-2015 Marvell International Ltd.
Copyright (C) 2002-2010 Kinoma, 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.
*/
#define __FSKEXTENSIONS_PRIV__
#include "KplExtensions.h"
#include "FskFiles.h"
#include <dlfcn.h>
FskErr KplLibraryLoad(FskLibrary *libraryOut, const char *path)
{
FskErr err;
FskLibrary library = NULL;
char *nativePath = NULL;
err = FskMemPtrNewClear(sizeof(FskLibraryRecord), (FskMemPtr *)&library);
if (err) goto bail;
err = FskFilePathToNative(path, &nativePath);
if (err) goto bail;
library->module = dlopen(nativePath, RTLD_NOW);
if (NULL == library->module) {
err = kFskErrOperationFailed;
}
bail:
FskMemPtrDispose(nativePath);
if (err) {
KplLibraryUnload(library);
library = NULL;
}
*libraryOut = library;
return err;
}
FskErr KplLibraryUnload(FskLibrary library)
{
if (library) {
if (library->module) {
dlclose(library->module);
}
FskMemPtrDispose(library);
}
return kFskErrNone;
}
FskErr KplLibraryGetSymbolAddress(FskLibrary library, const char *symbol, void **address)
{
*address = dlsym(library->module, symbol);
return (NULL == *address) ? kFskErrUnknownElement : kFskErrNone;
}
| 2 | 2 |
2024-11-18T18:23:13.268678+00:00 | 2023-08-19T19:52:01 | 057d864998c0f747f7e1c0e39600e7a5cf412971 | {
"blob_id": "057d864998c0f747f7e1c0e39600e7a5cf412971",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-24T06:47:43",
"content_id": "40ac3e7dc57a51c01f10e422899e0e2c2b3f37ae",
"detected_licenses": [
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "80cc60b33eb179fe39bad3e0d7208b670d10882a",
"extension": "h",
"filename": "consts.h",
"fork_events_count": 35,
"gha_created_at": "2018-03-19T08:20:10",
"gha_event_created_at": "2023-09-14T13:33:59",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 125824338,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1329,
"license": "BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/include/math/consts.h",
"provenance": "stackv2-0003.json.gz:393907",
"repo_name": "phoenix-rtos/libphoenix",
"revision_date": "2023-08-19T19:52:01",
"revision_id": "90d2bf02d6199d3d8e2325744745d99fc1fcc81f",
"snapshot_id": "2158967e59d1ebf7fe241c54f3ba04017c986c68",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/phoenix-rtos/libphoenix/90d2bf02d6199d3d8e2325744745d99fc1fcc81f/include/math/consts.h",
"visit_date": "2023-08-25T13:15:09.769349"
} | stackv2 | /*
* Phoenix-RTOS
*
* libphoenix
*
* math.h constants
*
* Copyright 2017 Phoenix Systems
* Author: Aleksander Kaminski
*
* This file is part of Phoenix-RTOS.
*
* %LICENSE%
*/
#ifndef _LIBPHOENIX_MATH_CONSTS_H_
#define _LIBPHOENIX_MATH_CONSTS_H_
/* The base of natural logarithms. */
#define M_E 2.7182818284590452354
/* The logarithm to base 2 of M_E. */
#define M_LOG2E 1.4426950408889634074
/* The logarithm to base 10 of M_E. */
#define M_LOG10E 0.43429448190325182765
/* The natural logarithm of 2. */
#define M_LN2 0.69314718055994530942
/* The natural logarithm of 10. */
#define M_LN10 2.30258509299404568402
/* Pi, the ratio of a circle's circumference to its diameter. */
#define M_PI 3.14159265358979323846
/* Pi divided by two. */
#define M_PI_2 1.57079632679489661923
/* Pi divided by four. */
#define M_PI_4 0.78539816339744830962
/* The reciprocal of pi (1/pi) */
#define M_1_PI 0.31830988618379067154
/* Two times the reciprocal of pi. */
#define M_2_PI 0.63661977236758134308
/* Two times the reciprocal of the square root of pi. * */
#define M_2_SQRTPI 1.12837916709551257390
/* The square root of two. */
#define M_SQRT2 1.41421356237309504880
/* The reciprocal of the square root of two (also the square root of 1/2). */
#define M_SQRT1_2 0.70710678118654752440
#endif
| 2.03125 | 2 |
2024-11-18T18:23:13.340358+00:00 | 2022-07-08T09:59:01 | 157bab15e364da28974eef31d67729e7e3fa30f3 | {
"blob_id": "157bab15e364da28974eef31d67729e7e3fa30f3",
"branch_name": "refs/heads/main",
"committer_date": "2022-07-08T09:59:01",
"content_id": "b5dcc4611af54bd0384f1ed538abb0c609253005",
"detected_licenses": [
"MIT"
],
"directory_id": "537eb58d242bc58d27cb07cf3b17db0efcd0b961",
"extension": "h",
"filename": "advanced_macros.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 13664751,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7747,
"license": "MIT",
"license_type": "permissive",
"path": "/old/src/core/util/advanced_macros.h",
"provenance": "stackv2-0003.json.gz:394035",
"repo_name": "dhh1128/intent",
"revision_date": "2022-07-08T09:59:01",
"revision_id": "12c11df9bb748ca71f125eabf65e6a20e9c5ac2f",
"snapshot_id": "abff09c3058e617f66402dc66695a5c032302a90",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/dhh1128/intent/12c11df9bb748ca71f125eabf65e6a20e9c5ac2f/old/src/core/util/advanced_macros.h",
"visit_date": "2022-07-20T23:05:55.378883"
} | stackv2 | #ifndef _427e4537328c4799bdaaf21d8286b211
#define _427e4537328c4799bdaaf21d8286b211
/*
Some things to know about macros:
1. Macros are evaluated at the place where they are called, not where they are
defined. This is why special symbols like __FILE__, __LINE__, and __func__
can have different values each time they appear. You can use this in macros
you write.
2. Arguments to macros generally undergo macro expansion.
3. An exception to rule 2 is those arguments that are preceded by # or ##, or
followed by ##.
4. Another exception to rule 2 is that if a macro is defined to receive args, but
it appears without parens, it is not expanded. This means that a macro that
expands to an expression that includes its own name without parens is not
further expanded.
5. The # operator converts a name/symbol in a macro into its string equivalent.
6. The ## operator allows you to concatenate macro arguments onto identifiers.
*/
/**
* These macros provide a way to convert a numeric macro such as __LINE__
* to a string at compile time. See http://j.mp/1kSzg2l and http://j.mp/1rcwHGg.
*
* Suppose you have this:
* #define MY_FIELD_WIDTH 17
* and you need to get the string "17", e.g., to use in a field width specifier
* for printf.
*
* The stringize() macro will convert its arg to a string. So if you call it with
* MY_FIELD_WIDTH, you'll get "MY_FIELD_WIDTH". You can use this to convert
* variable names and expressions to strings.
*
* The stringize_value_of() macro expands its arg *before* it calls stringize(),
* so it yields the string representation of the *value* of its arg, instead of
* the string representation of the *name* of its arg. So if you call it with
* MY_FIELD_WIDTH, you'll get "17".
*/
#define stringize(x) #x
#define stringize_value_of(x) stringize(x) // use this to stringize __LINE__ or other numeric macro expressions
/**
* These macros provide a way to convert two tokens into a single token. The
* first is straightforward: glue_tokens(a, b) --> ab.
*
* The second, however, is non-obvious. It allows you to use a macro like
* __LINE__ or __COUNTER__ to create a unique token based on a line number or
* a macro invocation count, because the args to the macro are expanded into
* their values, and then glued.
*/
#define glue_tokens(a, b) a ## b
#define glue_token_values(a, b) glue_tokens(a, b)
// IMPL DETAIL: accept any number of args >= 51, but expand to just the 51st one.
#define _get_51st_arg( \
_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, \
_11, _12, _13, _14, _15, _16, _17, _18, _19, _20, \
_21, _22, _23, _24, _25, _26, _27, _28, _29, _30, \
_31, _32, _33, _34, _35, _36, _37, _38, _39, _40, \
_41, _42, _43, _44, _45, _46, _47, _48, _49, _50, N, ...) N
/**
* Count how many args were passed to a variadic macro. Up to 50 args are supported.
*/
#define count_varargs(...) _get_51st_arg( \
"ignored", ##__VA_ARGS__, \
49, 48, 47, 46, 45, 44, 43, 42, 41, 40, \
39, 38, 37, 36, 35, 34, 33, 32, 31, 30, \
29, 28, 27, 26, 25, 24, 23, 22, 21, 20, \
19, 18, 17, 16, 15, 14, 13, 12, 11, 10, \
9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
// IMPL DETAIL: make versions of a for-each macro that are overridden on arg count.
#define _fe_0(_call, ...)
#define _fe_1(_call, x) _call(x)
#define _fe_2(_call, x, ...) _call(x) _fe_1(_call, __VA_ARGS__)
#define _fe_3(_call, x, ...) _call(x) _fe_2(_call, __VA_ARGS__)
#define _fe_4(_call, x, ...) _call(x) _fe_3(_call, __VA_ARGS__)
#define _fe_5(_call, x, ...) _call(x) _fe_4(_call, __VA_ARGS__)
#define _fe_6(_call, x, ...) _call(x) _fe_5(_call, __VA_ARGS__)
#define _fe_7(_call, x, ...) _call(x) _fe_6(_call, __VA_ARGS__)
#define _fe_8(_call, x, ...) _call(x) _fe_7(_call, __VA_ARGS__)
#define _fe_9(_call, x, ...) _call(x) _fe_8(_call, __VA_ARGS__)
#define _fe_10(_call, x, ...) _call(x) _fe_9(_call, __VA_ARGS__)
#define _fe_11(_call, x, ...) _call(x) _fe_10(_call, __VA_ARGS__)
#define _fe_12(_call, x, ...) _call(x) _fe_11(_call, __VA_ARGS__)
#define _fe_13(_call, x, ...) _call(x) _fe_12(_call, __VA_ARGS__)
#define _fe_14(_call, x, ...) _call(x) _fe_13(_call, __VA_ARGS__)
#define _fe_15(_call, x, ...) _call(x) _fe_14(_call, __VA_ARGS__)
#define _fe_16(_call, x, ...) _call(x) _fe_15(_call, __VA_ARGS__)
#define _fe_17(_call, x, ...) _call(x) _fe_16(_call, __VA_ARGS__)
#define _fe_18(_call, x, ...) _call(x) _fe_17(_call, __VA_ARGS__)
#define _fe_19(_call, x, ...) _call(x) _fe_18(_call, __VA_ARGS__)
#define _fe_20(_call, x, ...) _call(x) _fe_19(_call, __VA_ARGS__)
#define _fe_21(_call, x, ...) _call(x) _fe_20(_call, __VA_ARGS__)
#define _fe_22(_call, x, ...) _call(x) _fe_21(_call, __VA_ARGS__)
#define _fe_23(_call, x, ...) _call(x) _fe_22(_call, __VA_ARGS__)
#define _fe_24(_call, x, ...) _call(x) _fe_23(_call, __VA_ARGS__)
#define _fe_25(_call, x, ...) _call(x) _fe_24(_call, __VA_ARGS__)
#define _fe_26(_call, x, ...) _call(x) _fe_25(_call, __VA_ARGS__)
#define _fe_27(_call, x, ...) _call(x) _fe_26(_call, __VA_ARGS__)
#define _fe_28(_call, x, ...) _call(x) _fe_27(_call, __VA_ARGS__)
#define _fe_29(_call, x, ...) _call(x) _fe_28(_call, __VA_ARGS__)
#define _fe_30(_call, x, ...) _call(x) _fe_29(_call, __VA_ARGS__)
#define _fe_31(_call, x, ...) _call(x) _fe_30(_call, __VA_ARGS__)
#define _fe_32(_call, x, ...) _call(x) _fe_31(_call, __VA_ARGS__)
#define _fe_33(_call, x, ...) _call(x) _fe_32(_call, __VA_ARGS__)
#define _fe_34(_call, x, ...) _call(x) _fe_33(_call, __VA_ARGS__)
#define _fe_35(_call, x, ...) _call(x) _fe_34(_call, __VA_ARGS__)
#define _fe_36(_call, x, ...) _call(x) _fe_35(_call, __VA_ARGS__)
#define _fe_37(_call, x, ...) _call(x) _fe_36(_call, __VA_ARGS__)
#define _fe_38(_call, x, ...) _call(x) _fe_37(_call, __VA_ARGS__)
#define _fe_39(_call, x, ...) _call(x) _fe_38(_call, __VA_ARGS__)
#define _fe_40(_call, x, ...) _call(x) _fe_39(_call, __VA_ARGS__)
#define _fe_41(_call, x, ...) _call(x) _fe_40(_call, __VA_ARGS__)
#define _fe_42(_call, x, ...) _call(x) _fe_41(_call, __VA_ARGS__)
#define _fe_43(_call, x, ...) _call(x) _fe_42(_call, __VA_ARGS__)
#define _fe_44(_call, x, ...) _call(x) _fe_43(_call, __VA_ARGS__)
#define _fe_45(_call, x, ...) _call(x) _fe_44(_call, __VA_ARGS__)
#define _fe_46(_call, x, ...) _call(x) _fe_45(_call, __VA_ARGS__)
#define _fe_47(_call, x, ...) _call(x) _fe_46(_call, __VA_ARGS__)
#define _fe_48(_call, x, ...) _call(x) _fe_47(_call, __VA_ARGS__)
#define _fe_49(_call, x, ...) _call(x) _fe_48(_call, __VA_ARGS__)
#define _fe_50(_call, x, ...) _call(x) _fe_49(_call, __VA_ARGS__)
/**
* Provide a for-each construct for variadic macros.
*
* Example usage:
* #define FWD_DECLARE_CLASS(cls) class cls;
* call_macro_x_for_each(FWD_DECLARE_CLASS, Foo, Bar)
*/
#define call_macro_x_for_each(x, ...) \
_get_51st_arg("ignored", ##__VA_ARGS__, \
_fe_49, _fe_48, _fe_47, _fe_46, _fe_45, _fe_44, _fe_43, _fe_42, _fe_41, _fe_40, \
_fe_39, _fe_38, _fe_37, _fe_36, _fe_35, _fe_34, _fe_33, _fe_32, _fe_31, _fe_30, \
_fe_29, _fe_28, _fe_27, _fe_26, _fe_25, _fe_24, _fe_23, _fe_22, _fe_21, _fe_20, \
_fe_19, _fe_18, _fe_17, _fe_16, _fe_15, _fe_14, _fe_13, _fe_12, _fe_11, _fe_10, \
_fe_9, _fe_8, _fe_7, _fe_6, _fe_5, _fe_4, _fe_3, _fe_2, _fe_1, _fe_0)(x, ##__VA_ARGS__)
/**
* Provide a convenient way to place variadic args somewhere other than the
* end of a macro invocation. This is syntatic sugar that provides a variation
* to call_macro_x_for_each; it allows the unbounded list of args to be used
* at the front of a macro, and the predicate applied to each to come at the end.
*
* Example usage:
* with( each(a, b, c), do_something);
*/
#define with(args, pred) call_macro_x_for_each(pred, args)
#define each(...) __VA_ARGS__
#endif // sentry
| 2.59375 | 3 |
2024-11-18T18:23:15.720336+00:00 | 2016-04-30T15:32:22 | 11066385d68df8e403f2ae16398bed2f2ba2ee9e | {
"blob_id": "11066385d68df8e403f2ae16398bed2f2ba2ee9e",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-30T15:32:22",
"content_id": "d1558a62f150f4f1ac54b40020795ac8ccad2ec5",
"detected_licenses": [
"MIT"
],
"directory_id": "9d6a3d2f29cd0b6327f39a687d02f6fb2c807899",
"extension": "c",
"filename": "ffi.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 23512521,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9503,
"license": "MIT",
"license_type": "permissive",
"path": "/ffi.c",
"provenance": "stackv2-0003.json.gz:394806",
"repo_name": "ignorabimus/tinyscheme-ffi",
"revision_date": "2016-04-30T15:32:22",
"revision_id": "7d8e6f34a56f98795498772eb25136b62afd21a8",
"snapshot_id": "19cc179bc85f47301221f86f9820492f119cdaa3",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/ignorabimus/tinyscheme-ffi/7d8e6f34a56f98795498772eb25136b62afd21a8/ffi.c",
"visit_date": "2021-01-21T12:52:42.865700"
} | stackv2 | /* TinyScheme FFI Extension
*/
#include <windows.h>
#include "scheme-private.h"
#include "ffi.h"
typedef struct {
void *proc;
ffi_cif cif;
} ffi_procinfo;
typedef union {
int i;
double r;
char *s;
} ffi_avalue;
static ffi_type *get_ffi_type_ptr(char *ffi_type_str)
{
if (0 == strcmp(ffi_type_str, "void")) {
return &ffi_type_void;
} else if (0 == strcmp(ffi_type_str, "uint8")) {
return &ffi_type_uint8;
} else if (0 == strcmp(ffi_type_str, "sint8")) {
return &ffi_type_sint8;
} else if (0 == strcmp(ffi_type_str, "uint16")) {
return &ffi_type_uint16;
} else if (0 == strcmp(ffi_type_str, "sint16")) {
return &ffi_type_sint16;
} else if (0 == strcmp(ffi_type_str, "uint32")) {
return &ffi_type_uint32;
} else if (0 == strcmp(ffi_type_str, "sint32")) {
return &ffi_type_sint32;
} else if (0 == strcmp(ffi_type_str, "uint64")) {
return &ffi_type_uint64;
} else if (0 == strcmp(ffi_type_str, "sint64")) {
return &ffi_type_sint64;
} else if (0 == strcmp(ffi_type_str, "float")) {
return &ffi_type_float;
} else if (0 == strcmp(ffi_type_str, "double")) {
return &ffi_type_double;
} else if (0 == strcmp(ffi_type_str, "pointer")) {
return &ffi_type_pointer;
} else {
return &ffi_type_void;
}
}
static int get_ffi_type_num(ffi_type *ptype)
{
if (ptype == &ffi_type_void) {
return FFI_TYPE_VOID;
} else if (ptype == &ffi_type_uint8) {
return FFI_TYPE_UINT8;
} else if (ptype == &ffi_type_sint8) {
return FFI_TYPE_SINT8;
} else if (ptype == &ffi_type_uint16) {
return FFI_TYPE_UINT16;
} else if (ptype == &ffi_type_sint16) {
return FFI_TYPE_SINT16;
} else if (ptype == &ffi_type_uint32) {
return FFI_TYPE_UINT32;
} else if (ptype == &ffi_type_sint32) {
return FFI_TYPE_SINT32;
} else if (ptype == &ffi_type_uint64) {
return FFI_TYPE_UINT64;
} else if (ptype == &ffi_type_sint64) {
return FFI_TYPE_SINT64;
} else if (ptype == &ffi_type_float) {
return FFI_TYPE_FLOAT;
} else if (ptype == &ffi_type_double) {
return FFI_TYPE_DOUBLE;
} else if (ptype == &ffi_type_pointer) {
return FFI_TYPE_POINTER;
} else {
return FFI_TYPE_VOID;
}
}
/* ffi-load-lib */
pointer foreign_ffiloadlib(scheme * sc, pointer args)
{
pointer first_arg;
char *varname;
HINSTANCE hinst;
if (args == sc->NIL) {
return sc->F;
}
first_arg = sc->vptr->pair_car(args);
if (!sc->vptr->is_string(first_arg)) {
return sc->F;
}
varname = sc->vptr->string_value(first_arg);
hinst = LoadLibrary(varname);
if (!hinst) {
return sc->F;
}
return sc->vptr->mk_integer(sc, (long)hinst);
}
/* ffi-find-proc */
pointer foreign_ffifindproc(scheme * sc, pointer args)
{
pointer first_arg, second_arg, third_arg, fourth_arg;
HINSTANCE hinst;
ffi_procinfo *p;
if (args == sc->NIL) {
return sc->F;
}
first_arg = sc->vptr->pair_car(args);
if (!sc->vptr->is_integer(first_arg)) {
return sc->F;
}
args = sc->vptr->pair_cdr(args);
second_arg = sc->vptr->pair_car(args);
if (!sc->vptr->is_string(second_arg)) {
return sc->F;
}
args = sc->vptr->pair_cdr(args);
third_arg = sc->vptr->pair_car(args);
if (!sc->vptr->is_list(sc, third_arg)) {
return sc->F;
}
args = sc->vptr->pair_cdr(args);
fourth_arg = sc->vptr->pair_car(args);
if (!sc->vptr->is_string(fourth_arg)) {
return sc->F;
}
hinst = (HINSTANCE)sc->vptr->ivalue(first_arg);
if (!hinst) {
return sc->F;
}
p = (ffi_procinfo *)malloc(sizeof(ffi_procinfo));
if (p) {
char *proc_name;
int list_len;
ffi_type **arg_types;
ffi_type *arg_rtype;
proc_name = sc->vptr->string_value(second_arg);
p->proc = GetProcAddress(hinst, proc_name);
if (!p->proc) {
free(p);
return sc->F;
}
list_len = sc->vptr->list_length(sc, third_arg);
arg_types = (ffi_type **)malloc(sizeof(ffi_type *) * list_len);
if (arg_types) {
int i;
for (i = 0; i < list_len; i++) {
pointer arg = sc->vptr->pair_car(third_arg);
if (!sc->vptr->is_string(arg)) {
free(p);
free(arg_types);
return sc->F;
}
arg_types[i] = get_ffi_type_ptr(sc->vptr->string_value(arg));
third_arg = sc->vptr->pair_cdr(third_arg);
}
arg_rtype = get_ffi_type_ptr(sc->vptr->string_value(fourth_arg));
if (ffi_prep_cif(&p->cif, FFI_DEFAULT_ABI, list_len, arg_rtype, arg_types) == FFI_OK) {
return sc->vptr->mk_integer(sc, (long)p);
}
free(arg_types);
}
free(p);
}
return sc->F;
}
/* ffi-call-proc */
pointer foreign_fficallproc(scheme * sc, pointer args)
{
pointer first_arg, second_arg;
int list_len;
ffi_procinfo *p;
void **values;
ffi_avalue *avalue;
int i;
if (args == sc->NIL) {
return sc->F;
}
first_arg = sc->vptr->pair_car(args);
if (!sc->vptr->is_integer(first_arg)) {
return sc->F;
}
args = sc->vptr->pair_cdr(args);
second_arg = sc->vptr->pair_car(args);
if (!sc->vptr->is_list(sc, second_arg)) {
return sc->F;
}
p = (ffi_procinfo *)sc->vptr->ivalue(first_arg);
if (!p) {
return sc->F;
}
list_len = sc->vptr->list_length(sc, second_arg);
if (list_len != p->cif.nargs) {
return sc->F;
}
values = (void *)malloc(sizeof(void *) * list_len);
if (!values) {
return sc->F;
}
avalue = (ffi_avalue *)malloc(sizeof(ffi_avalue) * list_len);
if (!avalue) {
free(values);
return sc->F;
}
for (i = 0; i < list_len; i++) {
pointer arg = sc->vptr->pair_car(second_arg);
switch (get_ffi_type_num(p->cif.arg_types[i])) {
case FFI_TYPE_UINT8:
case FFI_TYPE_SINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_SINT16:
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT32:
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
avalue[i].i = sc->vptr->ivalue(arg);
break;
case FFI_TYPE_FLOAT:
case FFI_TYPE_DOUBLE:
avalue[i].r = sc->vptr->rvalue(arg);
break;
case FFI_TYPE_POINTER:
avalue[i].s = sc->vptr->string_value(arg);
break;
case FFI_TYPE_VOID:
default:
free(values);
free(avalue);
return sc->F;
}
values[i] = &avalue[i];
second_arg = sc->vptr->pair_cdr(second_arg);
}
switch (get_ffi_type_num(p->cif.rtype)) {
case FFI_TYPE_UINT8:
case FFI_TYPE_SINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_SINT16:
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT32:
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
{
int rvalue;
ffi_call(&p->cif, FFI_FN(p->proc), &rvalue, values);
free(values);
free(avalue);
return sc->vptr->mk_integer(sc, rvalue);
}
case FFI_TYPE_FLOAT:
case FFI_TYPE_DOUBLE:
{
double rvalue;
ffi_call(&p->cif, FFI_FN(p->proc), &rvalue, values);
free(values);
free(avalue);
return sc->vptr->mk_real(sc, rvalue);
}
case FFI_TYPE_POINTER:
{
char *rvalue;
ffi_call(&p->cif, FFI_FN(p->proc), &rvalue, values);
free(values);
free(avalue);
return (pointer)rvalue;
}
case FFI_TYPE_VOID:
free(values);
free(avalue);
return sc->T;
default:
free(values);
free(avalue);
return sc->F;
}
}
/* ffi-free-proc */
pointer foreign_ffifreeproc(scheme * sc, pointer args)
{
pointer first_arg;
ffi_procinfo *p;
if (args == sc->NIL) {
return sc->F;
}
first_arg = sc->vptr->pair_car(args);
if (!sc->vptr->is_integer(first_arg)) {
return sc->F;
}
p = (ffi_procinfo *)sc->vptr->ivalue(first_arg);
if (!p) {
return sc->F;
}
free(p->cif.arg_types);
free(p);
return sc->T;
}
/* ffi-free-lib */
pointer foreign_ffifreelib(scheme * sc, pointer args)
{
pointer first_arg;
HINSTANCE hinst;
if (args == sc->NIL) {
return sc->F;
}
first_arg = sc->vptr->pair_car(args);
if (!sc->vptr->is_integer(first_arg)) {
return sc->F;
}
hinst = (HINSTANCE)sc->vptr->ivalue(first_arg);
if (!hinst) {
return sc->F;
}
if (!FreeLibrary(hinst)) {
return sc->F;
}
return sc->T;
}
/* This function gets called when TinyScheme is loading the extension */
void init_ffi(scheme * sc)
{
sc->vptr->scheme_define(sc, sc->global_env,
sc->vptr->mk_symbol(sc, "ffi-load-lib"),
sc->vptr->mk_foreign_func(sc, foreign_ffiloadlib));
sc->vptr->scheme_define(sc, sc->global_env,
sc->vptr->mk_symbol(sc, "ffi-find-proc"),
sc->vptr->mk_foreign_func(sc, foreign_ffifindproc));
sc->vptr->scheme_define(sc, sc->global_env,
sc->vptr->mk_symbol(sc, "ffi-call-proc"),
sc->vptr->mk_foreign_func(sc, foreign_fficallproc));
sc->vptr->scheme_define(sc, sc->global_env,
sc->vptr->mk_symbol(sc, "ffi-free-proc"),
sc->vptr->mk_foreign_func(sc, foreign_ffifreeproc));
sc->vptr->scheme_define(sc, sc->global_env,
sc->vptr->mk_symbol(sc, "ffi-free-lib"),
sc->vptr->mk_foreign_func(sc, foreign_ffifreelib));
}
| 2.21875 | 2 |
2024-11-18T18:23:15.795384+00:00 | 2016-03-04T20:02:55 | 2ad3082fefb7233bff70946a1da44fb59bea132b | {
"blob_id": "2ad3082fefb7233bff70946a1da44fb59bea132b",
"branch_name": "refs/heads/master",
"committer_date": "2016-03-04T20:02:55",
"content_id": "edab92c09114ce2145449ec668bf83ee379f8d97",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "db201a96cdf02612bf5f7079f0c530095d65832c",
"extension": "c",
"filename": "phonebook_hashfunction.c",
"fork_events_count": 0,
"gha_created_at": "2016-03-02T13:38:08",
"gha_event_created_at": "2016-03-02T13:38:08",
"gha_language": null,
"gha_license_id": null,
"github_id": 52965428,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1706,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/phonebook_hashfunction.c",
"provenance": "stackv2-0003.json.gz:394934",
"repo_name": "O4siang/phonebook",
"revision_date": "2016-03-04T20:02:55",
"revision_id": "33f6e41d040eaeabf31e26e6e9b55d280abfd10e",
"snapshot_id": "e51bdf6f83d83276f4fceb949ff511a9953d28a9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/O4siang/phonebook/33f6e41d040eaeabf31e26e6e9b55d280abfd10e/phonebook_hashfunction.c",
"visit_date": "2020-12-27T09:31:11.301790"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "phonebook_hashfunction.h"
/* FILL YOUR OWN IMPLEMENTATION HERE! */
entry *hash_table[TABLE_SIZE];
void initialize()
{
for(int i=0; i<TABLE_SIZE; i++) {
hash_table[i] = NULL;
}
return ;
}
int TransHashKey(char *lastName,int size)
{
if (!lastName) return 0;
int i, val;
for ( i = 0, val = 0; *lastName != '\0'; i++, lastName++) {
val +=val*i+*lastName;
}
return abs(val % size);
}
entry *findName(char lastName[], entry *pHead)
{
entry *tmp_name;
int index = TransHashKey(lastName, TABLE_SIZE);
tmp_name = hash_table[index];
while (tmp_name != NULL) {
if (strcasecmp(lastName, tmp_name->lastName) == 0)
return tmp_name;
tmp_name = tmp_name->pNext;
}
return NULL;
}
entry *append(char lastName[], entry *e)
{
int index = TransHashKey(lastName,TABLE_SIZE);
entry *newEntry;
entry *curEntry;
// Append
if(hash_table[index]) {
newEntry = hash_table[index];
while(newEntry) {
curEntry = newEntry;
newEntry = newEntry ->pNext;
}
newEntry = (entry *) malloc(sizeof(entry));
strcpy(newEntry->lastName, lastName);
curEntry->pNext = newEntry;
newEntry->pNext = NULL;
return newEntry;
} else {
newEntry = (entry *) malloc(sizeof(entry));
strcpy(newEntry->lastName, lastName);
newEntry->pNext = NULL;
hash_table[index] = newEntry;
return newEntry;
}
e->pNext = (entry *)malloc(sizeof(entry));
e = e->pNext;
strcpy(e->lastName, lastName);
e->pNext = NULL;
return e;
}
| 3.03125 | 3 |
2024-11-18T18:23:16.031081+00:00 | 2023-02-24T02:08:15 | 2e849a1b0a270a08503d5d05acce41760431219e | {
"blob_id": "2e849a1b0a270a08503d5d05acce41760431219e",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-24T02:08:15",
"content_id": "a8ac44fbce62765a3e64226388f76476696c0e63",
"detected_licenses": [
"BSD-3-Clause-Open-MPI"
],
"directory_id": "d5c17a98e78f10baaddf29dd8713e50eef56203c",
"extension": "c",
"filename": "test_reduce.c",
"fork_events_count": 11,
"gha_created_at": "2020-08-10T17:31:17",
"gha_event_created_at": "2023-08-09T20:11:25",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 286538992,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6150,
"license": "BSD-3-Clause-Open-MPI",
"license_type": "permissive",
"path": "/collective-big-count/test_reduce.c",
"provenance": "stackv2-0003.json.gz:395194",
"repo_name": "open-mpi/ompi-tests-public",
"revision_date": "2023-02-24T02:08:15",
"revision_id": "dcc6ec78448000ee2519623134d2595d394feff0",
"snapshot_id": "36f57a5bd16d8d933a9b9f7d4aaaafc91e978d27",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/open-mpi/ompi-tests-public/dcc6ec78448000ee2519623134d2595d394feff0/collective-big-count/test_reduce.c",
"visit_date": "2023-08-26T05:54:40.722349"
} | stackv2 | /*
* Copyright (c) 2021-2022 IBM Corporation. All rights reserved.
*
* $COPYRIGHT$
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <mpi.h>
#include "common.h"
int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking);
int main(int argc, char** argv) {
/*
* Initialize the MPI environment
*/
int ret = 0;
MPI_Init(NULL, NULL);
init_environment(argc, argv);
#ifndef TEST_UNIFORM_COUNT
// Each rank contribues: V_SIZE_INT elements
// Largest buffer is : V_SIZE_INT elements
ret += my_c_test_core(MPI_INT, V_SIZE_INT, true);
ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, true);
if (allow_nonblocked) {
ret += my_c_test_core(MPI_INT, V_SIZE_INT, false);
ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, V_SIZE_DOUBLE_COMPLEX, false);
}
#else
size_t proposed_count;
// Each rank contribues: TEST_UNIFORM_COUNT elements
// Largest buffer is : TEST_UNIFORM_COUNT elements
proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT,
2, 2); // 1 send, 1 recv buffer each
ret += my_c_test_core(MPI_INT, proposed_count, true);
proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT,
2, 2); // 1 send, 1 recv buffer each
ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count, true);
if (allow_nonblocked) {
proposed_count = calc_uniform_count(sizeof(int), TEST_UNIFORM_COUNT,
2, 2); // 1 send, 1 recv buffer each
ret += my_c_test_core(MPI_INT, proposed_count, false);
proposed_count = calc_uniform_count(sizeof(double _Complex), TEST_UNIFORM_COUNT,
2, 2); // 1 send, 1 recv buffer each
ret += my_c_test_core(MPI_C_DOUBLE_COMPLEX, proposed_count, false);
}
#endif
/*
* All done
*/
MPI_Finalize();
return ret;
}
int my_c_test_core(MPI_Datatype dtype, size_t total_num_elements, bool blocking)
{
int ret = 0;
size_t i;
MPI_Request request;
char *mpi_function = blocking ? "MPI_Reduce" : "MPI_Ireduce";
// Actual payload size as divisible by the sizeof(dt)
size_t payload_size_actual;
/*
* Initialize vector
*/
int *my_int_recv_vector = NULL;
int *my_int_send_vector = NULL;
double _Complex *my_dc_recv_vector = NULL;
double _Complex *my_dc_send_vector = NULL;
size_t num_wrong = 0;
assert(MPI_INT == dtype || MPI_C_DOUBLE_COMPLEX == dtype);
assert(total_num_elements <= INT_MAX);
if( MPI_INT == dtype ) {
payload_size_actual = total_num_elements * sizeof(int);
if (world_rank == 0) {
my_int_recv_vector = (int*)safe_malloc(payload_size_actual);
}
my_int_send_vector = (int*)safe_malloc(payload_size_actual);
} else {
payload_size_actual = total_num_elements * sizeof(double _Complex);
if (world_rank == 0) {
my_dc_recv_vector = (double _Complex*)safe_malloc(payload_size_actual);
}
my_dc_send_vector = (double _Complex*)safe_malloc(payload_size_actual);
}
for(i = 0; i < total_num_elements; ++i) {
if( MPI_INT == dtype ) {
my_int_send_vector[i] = 1;
if (world_rank == 0) {
my_int_recv_vector[i] = -1;
}
} else {
my_dc_send_vector[i] = 1.0 - 1.0*I;
if (world_rank == 0) {
my_dc_recv_vector[i] = -1.0 + 1.0*I;
}
}
}
/*
* MPI_Allreduce fails when size of my_int_vector is large
*/
if (world_rank == 0) {
printf("---------------------\nResults from %s(%s x %zu = %zu or %s):\n",
mpi_function, (MPI_INT == dtype ? "int" : "double _Complex"),
total_num_elements, payload_size_actual, human_bytes(payload_size_actual));
}
if (blocking) {
if( MPI_INT == dtype ) {
MPI_Reduce(my_int_send_vector, my_int_recv_vector,
(int)total_num_elements, dtype,
MPI_SUM, 0, MPI_COMM_WORLD);
} else {
MPI_Reduce(my_dc_send_vector, my_dc_recv_vector,
(int)total_num_elements, dtype,
MPI_SUM, 0, MPI_COMM_WORLD);
}
}
else {
if( MPI_INT == dtype ) {
MPI_Ireduce(my_int_send_vector, my_int_recv_vector,
(int)total_num_elements, dtype,
MPI_SUM, 0, MPI_COMM_WORLD, &request);
} else {
MPI_Ireduce(my_dc_send_vector, my_dc_recv_vector,
(int)total_num_elements, dtype,
MPI_SUM, 0, MPI_COMM_WORLD, &request);
}
MPI_Wait(&request, MPI_STATUS_IGNORE);
}
/*
* Check results.
* The exact result = (size*number_of_processes, -size*number_of_processes)
*/
if (world_rank == 0) {
for(i = 0; i < total_num_elements; ++i) {
if( MPI_INT == dtype ) {
if(my_int_recv_vector[i] != world_size) {
++num_wrong;
}
} else {
if(my_dc_recv_vector[i] != 1.0*world_size - 1.0*world_size*I) {
++num_wrong;
}
}
}
if( 0 == num_wrong) {
printf("Rank %2d: PASSED\n", world_rank);
} else {
printf("Rank %2d: ERROR: DI in %14zu of %14zu slots (%6.1f %% wrong)\n", world_rank,
num_wrong, total_num_elements, ((num_wrong * 1.0)/total_num_elements)*100.0);
ret = 1;
}
}
if( NULL != my_int_send_vector ) {
free(my_int_send_vector);
}
if( NULL != my_int_recv_vector ){
free(my_int_recv_vector);
}
if( NULL != my_dc_send_vector ) {
free(my_dc_send_vector);
}
if( NULL != my_dc_recv_vector ){
free(my_dc_recv_vector);
}
fflush(NULL);
MPI_Barrier(MPI_COMM_WORLD);
return ret;
}
| 2.09375 | 2 |
2024-11-18T18:23:16.331161+00:00 | 2021-06-17T22:52:08 | bc634abbcabbc87a60fd42bf3f922fc4a4dff1ac | {
"blob_id": "bc634abbcabbc87a60fd42bf3f922fc4a4dff1ac",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-17T22:52:08",
"content_id": "e10e44e8b3af73472b4b3260c5d88caa28e7c5e3",
"detected_licenses": [
"MIT"
],
"directory_id": "5b395d541284cd05f8a25b83c4c51d8b86c42d79",
"extension": "h",
"filename": "Image_t.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 377925242,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15129,
"license": "MIT",
"license_type": "permissive",
"path": "/sourcecode/src/vx/com/c/image/Image_t.h",
"provenance": "stackv2-0003.json.gz:395587",
"repo_name": "ivarvb/SPIX",
"revision_date": "2021-06-17T22:52:08",
"revision_id": "6c757b69c266f738d66164fa643a09f77721880d",
"snapshot_id": "4bacd23f7349904a88644321f310679c6903ea10",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ivarvb/SPIX/6c757b69c266f738d66164fa643a09f77721880d/sourcecode/src/vx/com/c/image/Image_t.h",
"visit_date": "2023-06-03T22:43:37.227554"
} | stackv2 | /**
*
* Athor: Ivar Vargas Belizario
* Copyright (C) 2021
*
*/
#ifndef IMAGET_H
#define IMAGET_H
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Color3RGB.h"
const int x8[8] = {-1, 0, 1, 0, -1, 1, 1, -1};//for 4 or 8 connectivity
const int y8[8] = { 0, -1, 0, 1, -1, -1, 1, 1};//for 4 or 8 connectivity
// declare types and methods
/* typedef struct Pixel_t Pixel_t;
typedef struct Region_t Region_t; */
typedef struct Image_t Image_t;
void vx_image_free(Image_t *&img);
Image_t* vx_image_create(int width, int height, int fdatai, unsigned char *& fdata);
void vx_image_seg_read(
char filename[],
int width, int height, unsigned long &size_labels, unsigned long *&label,
unsigned long *&next, unsigned long *®ion, unsigned long *®ionsize,
unsigned long *&target, char**& name_targets, unsigned long *size_targets
);
void vx_image_seg_write(
char filename[], char name[], int width, int height,
unsigned long *&label, unsigned long size_labels,
unsigned long *&target, char**& name_targets, unsigned long *size_targets);
void vx_image_seg_width_height(char filename[], int &width, int &height);
void vx_image_fillcolor(Image_t *&img, Color3RGB color);
void vx_image_setcolor(Image_t *&img, int i, Color3RGB color);
Color3RGB vx_image_getcolor(Image_t *&img, int i);
void vx_image_fillgray(Image_t *&img, unsigned char gray);
void vx_image_setgray(Image_t *&img, int i, unsigned char gray);
unsigned char vx_image_getgray(Image_t *&img, int i);
void vx_image_draw_regions_limits(unsigned char *&pixel, unsigned long size_pixels, unsigned long *&label, int width, int height);
void vx_image_draw_regions(unsigned char *&pixel, unsigned long size_pixels, unsigned long *&label, unsigned long size_labels);
void vx_image_update_regions(Image_t *&image);
void vx_image_gray_update_b_in_a(
Image_t *&img_a, unsigned char a, unsigned long la,
Image_t *&img_b, unsigned char b, unsigned long lb
);
void vx_copy(void *destination, void *source, size_t n);
void vx_maketokens(char *line, const char *delim, char **words, int sizetokens);
// types
/* typedef struct Pixel_t{
int i;
int x;
int y;
int label;
Pixel_t *next;
}Pixel_t; */
/* typedef struct Region_t{
Pixel_t *next;
int size;
}Region_t; */
typedef struct Image_t{
int width, height, channels;
unsigned long size_pixels, size_labels;
/* Pixel_t *pixel; */
unsigned char *pixel;
unsigned long *label;
unsigned long *next;
unsigned long *region;
unsigned long *regionsize;
/*
unsigned long *x;
unsigned long *y;
*/
//Region_t *region;
}Image_t;
void vx_image_free(Image_t *&img){
/* if (img->pixel!=NULL){
free(img->pixel);
} */
//free(img->pixel);
free(img->label);
img->label = NULL;
free(img->next);
img->next = NULL;
free(img->region);
img->region = NULL;
free(img->regionsize);
img->regionsize = NULL;
/* free(img->x);
img->x = NULL;
free(img->y);
img->y = NULL; */
free(img);
img = NULL;
}
Image_t* vx_image_create(int width, int height, int fdatai, unsigned char *&fdata){
//Image_t* vx_image_create(int w, int h, int intensity){
clock_t end, start = clock();
Image_t *img = (Image_t*)malloc(sizeof(Image_t));
img->channels = fdatai;
img->width = width;
img->height = height;
img->size_pixels = width*height;
clock_t xstart = clock();
clock_t xend;
//img->pixel = (unsigned char*)malloc(img->size_pixels*img->channels*sizeof(unsigned char));
img->label = (unsigned long*)malloc(img->size_pixels*img->channels*sizeof(unsigned long));
img->next = (unsigned long*)malloc(img->size_pixels*img->channels*sizeof(unsigned long));
img->region = (unsigned long*)malloc(img->size_pixels*img->channels*sizeof(unsigned long));
img->regionsize = (unsigned long*)malloc(img->size_pixels*img->channels*sizeof(unsigned long));
/*
img->x = (unsigned long*)malloc(img->size_pixels*img->channels*sizeof(unsigned long));
img->y = (unsigned long*)malloc(img->size_pixels*img->channels*sizeof(unsigned long));
*/
/* img->pixel = (Pixel_t*)malloc(img->size_pixels*sizeof(Pixel_t));
img->region = (Region_t*)malloc(img->size_pixels*sizeof(Region_t)); */
xend = clock();
printf(" malloc: %f\n", (double)(xend - xstart)/CLOCKS_PER_SEC);
// initializing attributes
int x, y;
unsigned long i;
//unsigned long z = img->size_pixels;
img->pixel = fdata;
for (y=0;y<img->height;++y){
for (x=0;x<img->width;++x){
i=y*img->width+x;
/* for (j=0;j<img->channels;++j){
img->pixel[j*z+i] = fdata[j*z+i];
} */
/*
img->x[i] = x;
img->y[i] = y;
*/
img->next[i] = img->region[0];
img->region[0] = i;
img->label[i] = 0;
}
}
img->size_labels = 1;
img->regionsize[0] = img->size_pixels;
end = clock();
printf("time creiate image: %f\n", (double)(end - start)/CLOCKS_PER_SEC);
return img;
}
void vx_image_fillcolor(Image_t *&img, Color3RGB color){
unsigned long i;
for (i=0; i<img->size_pixels; ++i){
vx_image_setcolor(img, i, color);
}
}
void vx_image_setcolor(Image_t *&img, int i, Color3RGB color){
img->pixel[0*img->size_pixels+i] = color.R;
img->pixel[1*img->size_pixels+i] = color.G;
img->pixel[2*img->size_pixels+i] = color.B;
}
Color3RGB vx_image_getcolor(Image_t *&img, int i){
Color3RGB color;
color.R = img->pixel[0*img->size_pixels+i];
color.G = img->pixel[1*img->size_pixels+i];
color.B = img->pixel[2*img->size_pixels+i];
return color;
}
void vx_image_fillgray(Image_t *&img, unsigned char gray){
unsigned long i;
for (i=0; i<img->size_pixels; ++i){
vx_image_setgray(img, i, gray);
}
}
void vx_image_setgray(Image_t *&img, int i, unsigned char gray){
img->pixel[i] = gray;
}
unsigned char vx_image_getgray(Image_t *&img, int i){
return img->pixel[i];
}
void vx_image_draw_regions(unsigned char *&pixel, unsigned long size_pixels, unsigned long *&label, unsigned long size_labels){
//if(img->channels==3){
//clock_t start = clock();
//clock_t end;
Color3RGB* colors = makecolor(size_labels);
Color3RGB c;
unsigned long i;
for (i=0; i<size_pixels; i++){
c = colors[label[i]];
pixel[0*size_pixels+i] = c.R;
pixel[1*size_pixels+i] = c.G;
pixel[2*size_pixels+i] = c.B;
}
free(colors);
//end = clock();
//printf("time draw regions: %f\n", (double)(end - start)/CLOCKS_PER_SEC);
//}
}
void vx_image_draw_regions_limits(unsigned char *&pixel, unsigned long size_pixels, unsigned long *&label, int width, int height){
//if(img->channels==3){
clock_t start = clock();
clock_t end;
int x, y;
unsigned long i, j;
for(y=1;y<height-1;++y){
for(x=1;x<width-1;++x){
i = y*width+x;
for(j=0;j<4;++j){
j = (y+y8[j])*width+(x+x8[j]);
if(label[i]!=label[j]){
pixel[0*size_pixels+i] = WHITE_D.R;
pixel[1*size_pixels+i] = WHITE_D.G;
pixel[2*size_pixels+i] = WHITE_D.B;
//break;
}
}
}
}
end = clock();
printf("time draw regions limits: %f\n", (double)(end - start)/CLOCKS_PER_SEC);
//}
}
void vx_image_seg_read(
char filename[],
int width, int height, unsigned long &size_labels, unsigned long *&label,
unsigned long *&next, unsigned long *®ion, unsigned long *®ionsize,
unsigned long *&target, char**& name_targets, unsigned long *size_targets
){
clock_t end, start = clock();
// printf("PATHFILE %s\n",filename);
FILE* fp = fopen(filename, "r");
if (fp == NULL) exit(EXIT_FAILURE);
char* line = NULL;
size_t len = 0;
ssize_t read = 0;
char *words[256];
const char *delim = " ";
const char *delim2 = "\n";
int sizetokens = 0;
int r, w, h;
unsigned long i, j, t, c1, c2;
read = getline(&line, &len, fp);
read = getline(&line, &len, fp);
read = getline(&line, &len, fp);
read = getline(&line, &len, fp);
read = getline(&line, &len, fp);
vx_maketokens(line, delim, words, sizetokens);
w = atoi(words[1]);
read = getline(&line, &len, fp);
vx_maketokens(line, delim, words, sizetokens);
h = atoi(words[1]);
assert(w==width && h==height);
width = w;
height = h;
read = getline(&line, &len, fp);
vx_maketokens(line, delim, words, sizetokens);
size_labels = atoi(words[1]);
read = getline(&line, &len, fp);
read = getline(&line, &len, fp);
read = getline(&line, &len, fp);
read = getline(&line, &len, fp);
vx_maketokens(line, delim, words, sizetokens);
*size_targets = atoi(words[1]);
//read target's names
for(i=0; i<*size_targets;++i){
read = getline(&line, &len, fp);
vx_maketokens(line, delim2, words, sizetokens);
strcpy(name_targets[i], line);
}
//read values of targets for each regions
//segmentstargets
read = getline(&line, &len, fp);
for(i=0; i<size_labels;++i){
read = getline(&line, &len, fp);
target[i] = atoi(line);
}
//data
read = getline(&line, &len, fp);
for (i=0; i<size_labels; ++i){
regionsize[i] = 0;
}
while ((read = getline(&line, &len, fp)) != -1) {
vx_maketokens(line, delim, words, sizetokens);
t = atoi(words[0]);
r = atoi(words[1]);
c1 = atoi(words[2]);
c2 = atoi(words[3]);
for (j=c1; j<=c2; ++j){
i = r*width+j;
/*
imgData->x[i] = j;
imgData->y[i] = r;
*/
next[i] = region[t];
region[t] = i;
regionsize[t]++;
label[i] = t;
}
}
fclose(fp);
/* if (line)
free(line); */
end = clock();
printf("time read seg: %f\n", (double)(end - start)/CLOCKS_PER_SEC);
}
void vx_image_seg_write(
char filename[], char name[], int width, int height,
unsigned long *&label, unsigned long size_labels,
unsigned long *&target, char**& name_targets, unsigned long *size_targets
){
clock_t end, start = clock();
FILE* fp = fopen(filename, "w");
if (fp == NULL) exit(EXIT_FAILURE);
int x, y, c1;
unsigned long j;
unsigned long i, la, l;
char bufft[100];
time_t now = time (0);
strftime (bufft, 100, "%Y-%m-%d %H:%M:%S", localtime(&now));
fprintf (fp, "format ascii cr\n");
fprintf (fp, "%s\n", bufft);
//fprintf (fp, "image:%s\n", name);
fprintf (fp, "%s\n", name);
fprintf (fp, "user ?\n");
fprintf (fp, "width %d\n", width);
fprintf (fp, "height %d\n", height);
fprintf (fp, "segments %lu\n", size_labels);
fprintf (fp, "gray 0\n");
fprintf (fp, "invert 0\n");
fprintf (fp, "flipflop 0\n");
fprintf (fp, "targets %ld\n", *size_targets);
for(j=0; j<*size_targets;++j){
fprintf (fp, "%s\n", name_targets[j]);
}
fprintf (fp, "segmentstargets:\n");
for(i=0; i<size_labels;++i){
fprintf (fp, "%ld\n", target[i]);
}
fprintf (fp, "data:\n");
for(y=0; y<height; ++y){
c1 = 0;
// c2 = 0;
la = label[y*width];
for(x=0; x<width; ++x){
i = y*width+x;
l = label[i];
if(la!=l){
fprintf (fp, "%lu %d %d %d\n", la, y, c1, (x-1));
c1=x;
la=l;
}
}
fprintf (fp, "%lu %d %d %d\n", la, y, c1, (width-1));
}
fclose(fp);
end = clock();
printf("time write seg: %f\n", (double)(end - start)/CLOCKS_PER_SEC);
}
void vx_image_seg_width_height(char filename[], int &width, int &height){
FILE* fp = fopen(filename, "r");
if (fp == NULL)
exit(EXIT_FAILURE);
char* line = NULL;
size_t len = 0;
ssize_t read = 0;
char *words[20];
const char *delim = " ";
int sizetokens = 0;
read = getline(&line, &len, fp);
read = getline(&line, &len, fp);
read = getline(&line, &len, fp);
read = getline(&line, &len, fp);
read = getline(&line, &len, fp);
vx_maketokens(line, delim, words, sizetokens);
width = atoi(words[1]);
read = getline(&line, &len, fp);
vx_maketokens(line, delim, words, sizetokens);
height = atoi(words[1]);
read = getline(&line, &len, fp);
vx_maketokens(line, delim, words, sizetokens);
//sizelables = atoi(words[1]);
len = read+1;
fclose(fp);
/* if (line)
free(line); */
}
void vx_image_update_regions(Image_t *&img){
clock_t start = clock();
clock_t end;
unsigned long* aux = (unsigned long*)malloc(img->size_pixels*sizeof(unsigned long));
unsigned long i, j, label;
unsigned long count = 0;
unsigned long dif = -1;
for (i=0; i<img->size_pixels; ++i){
aux[img->label[i]] = dif;
img->next[i] = dif;
//img->region[i].size = 0;
}
for (i=0; i<img->size_pixels; ++i){
/* code */
label = img->label[i];
if (aux[label] == dif){
aux[label] = count;
count++;
}
j = aux[label];
img->next[i] = img->region[j];
img->region[j] = i;
img->regionsize[j]++;
img->label[i] = j;
/* img->pixel[i].next = &*(img->region[j].next);
img->region[j].next = &img->pixel[i];
img->region[j].size++;
img->pixel[i].label = j; */
}
img->size_labels = count;
free(aux);
end = clock();
printf("time update regions: %f\n", (double)(end - start)/CLOCKS_PER_SEC);
}
void vx_image_gray_update_b_in_a(
Image_t *&img_a, unsigned char a, unsigned long la,
Image_t *&img_b, unsigned char b, unsigned long lb
){
clock_t end, start = clock();
unsigned long i, t;
for (i=0; i<img_a->size_pixels; ++i){
img_a->label[i] = 0;
img_a->regionsize[i] = 0;
}
for (i=0; i<img_a->size_pixels; ++i){
if (img_a->pixel[i]==a){
img_a->label[i] = la;
}
if (img_b->pixel[i]==b){
img_a->label[i] = lb;
}
}
for (i=0; i<img_a->size_pixels; ++i){
t = img_a->label[i];
img_a->next[i] = img_a->region[t];
img_a->region[t] = i;
img_a->regionsize[t]++;
}
img_a->size_labels = 3;
end = clock();
printf(" cc time update b in a: %f\n", (double)(end - start)/CLOCKS_PER_SEC);
}
void vx_copy(void *dest, void *source, size_t n){
memcpy (dest, source, n*sizeof(dest));
}
void vx_maketokens(char *line, const char *delim, char **words, int sizetokens){
char *token = strtok(line, delim);
int i = 0;
while (token != NULL) {
words[i] = token;
token = strtok(NULL,delim);
i++;
}
sizetokens = i;
}
#endif | 2.625 | 3 |
2024-11-18T18:23:16.427235+00:00 | 2020-06-25T00:42:38 | f55bd27ac1dcd5fed7ea1bd6e0cd6e4fea5b4c19 | {
"blob_id": "f55bd27ac1dcd5fed7ea1bd6e0cd6e4fea5b4c19",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-25T00:42:38",
"content_id": "105e4e1440478c2229dbd38176fb32befde7e062",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0d620c7ff803827d3a13ed8c7dc6a4e257df8f5f",
"extension": "h",
"filename": "solenoid_test.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": 597,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/controller/integration_tests/solenoid_test.h",
"provenance": "stackv2-0003.json.gz:395716",
"repo_name": "betaprior/VentilatorSoftware",
"revision_date": "2020-06-25T00:42:38",
"revision_id": "7cb87a1bd14079bc6ac67e8cd4795b803405f85a",
"snapshot_id": "c2f5e7850f2e0e56a786480bed6c0d12b9638e40",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/betaprior/VentilatorSoftware/7cb87a1bd14079bc6ac67e8cd4795b803405f85a/controller/integration_tests/solenoid_test.h",
"visit_date": "2022-11-11T00:22:08.150111"
} | stackv2 | // This test switches the binary solenoid between the open and closed position
//
// TODO - This test should be updated because the solenoid is now a proportional
// solenoid with variable positions between 0 and 1 and no longer a
// simple binary solenoid
#include "hal.h"
// test parameters
static constexpr int64_t delay_ms{1000};
void run_test() {
Hal.init();
bool solenoid_state = false;
while (true) {
Hal.PSOL_Value(solenoid_state ? 0.0f : 1.0f);
Hal.delay(milliseconds(delay_ms));
Hal.watchdog_handler();
solenoid_state = !solenoid_state;
}
}
| 2.3125 | 2 |
2024-11-18T18:23:16.485310+00:00 | 2020-11-18T11:54:26 | 6d280ac198369cf434c5f6449ce52bef67603836 | {
"blob_id": "6d280ac198369cf434c5f6449ce52bef67603836",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-18T11:54:26",
"content_id": "9b1b8d5fc39ce938512f820ce880e4057b3565d2",
"detected_licenses": [
"MIT"
],
"directory_id": "56c4a72d42edd231e9518757e43b4c0819f50316",
"extension": "c",
"filename": "firmware.c",
"fork_events_count": 0,
"gha_created_at": "2020-09-30T09:27:47",
"gha_event_created_at": "2020-09-30T09:27:47",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 299870511,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 600,
"license": "MIT",
"license_type": "permissive",
"path": "/software/firmware/firmware.c",
"provenance": "stackv2-0003.json.gz:395846",
"repo_name": "bocherteric/iob-soc",
"revision_date": "2020-11-18T11:54:26",
"revision_id": "7f454de53e608f93726c080559d679c41ff30e13",
"snapshot_id": "62a9f98c2dc4ad3a28b9a9ffc4c7f6a4e84e72f7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bocherteric/iob-soc/7f454de53e608f93726c080559d679c41ff30e13/software/firmware/firmware.c",
"visit_date": "2023-02-01T22:28:11.699568"
} | stackv2 | //#include "stdlib.h"
#include "system.h"
#include "periphs.h"
#include "iob-uart.h"
#include "iob_timer.h"
int main()
{
unsigned long long elapsed;
unsigned int elapsedu;
//timer_reset(TIMER_BASE);
timer_reset(TIMER_BASE);
//init uart
uart_init(UART_BASE,FREQ/BAUD);
uart_printf("\nHello world!\n");
uart_txwait();
//read current timer count, compute elapsed time
elapsed = timer_get_count(TIMER_BASE);
elapsedu = timer_time_us(TIMER_BASE);
uart_printf("\nExecution time: %d clocks in %dus @%dMHz\n\n",
(unsigned int)elapsed, elapsedu, FREQ/1000000);
uart_txwait();
return 0;
}
| 2.359375 | 2 |
2024-11-18T18:23:16.575299+00:00 | 2018-01-25T23:31:39 | 7857fbee99877b340d90211b3f7e9bb46127cff0 | {
"blob_id": "7857fbee99877b340d90211b3f7e9bb46127cff0",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-25T23:31:39",
"content_id": "501ef31feef4a4c59926a1548179d5546046c4cb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "09e13234317c175ee7a403f4a0b379000aa14b17",
"extension": "c",
"filename": "uaf.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": 5555,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Episode3/uaf.c",
"provenance": "stackv2-0003.json.gz:395975",
"repo_name": "gavz/ARM-episodes",
"revision_date": "2018-01-25T23:31:39",
"revision_id": "febbcaff173f86738d20db0d771215360b1deabe",
"snapshot_id": "90ee1e6d353a2ec09f521e3d715da9d4eacfd5e4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gavz/ARM-episodes/febbcaff173f86738d20db0d771215360b1deabe/Episode3/uaf.c",
"visit_date": "2020-03-10T08:34:38.003594"
} | stackv2 | #include <iostream>
#include <cerrno>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#define PORT 4444
#define MAX_NUM 10
using namespace std;
int fd_sock;
static int roulette;
class Note{
protected:
unsigned int note_number;
string note_desc[10];
public:
void insert_note(string ins_note){
if (note_number<10){
note_desc[note_number] = ins_note;
cout << "Note added!" << endl;
note_number++;
}else{
cout << "You can not add more notesd!" << endl;
}
}
void delete_note(){
if(note_number>0){
note_number--;
}else{
note_number=0;
}
if (!note_desc[note_number].empty()){
note_desc[note_number].clear();
cout << "Note deleted!" << endl;
}else{
cout << "No note to delete!" << endl;
}
}
int edit_note(unsigned int new_index, string new_note){
if((new_index<10)&&(!note_desc[new_index].empty())){
note_desc[new_index] = new_note;
cout << "Note modified!" << endl;
}else{
cout << "You can not edit this note" << endl;
}
return 0;
}
virtual int show_all_notes(){
return 0;
}
};
class Edit : public Note{
public:
virtual int show_all_notes(){
unsigned int i;
for(i=0;i<note_number;i++){
cout << note_desc[i] << endl;
}
return 0;
}
};
void stack_pivot(){
asm volatile(
"ldr sp,[r4, #0x0c] \n\t"
"ldr sp, [sp] \n\t"
"pop {lr, pc} \n\t"
);
}
void set_address(){
int *num = new int[12];
int tmp;
cout << "Enter the number" << endl;
cin >> tmp;
num[0]=tmp;
cout << "Number correctly inserted" << endl;
}
void stack_info(){
string str;
printf("Debug informations area \n");
cin >> str;
printf(str.c_str());
}
int note(){
int client_sockfd;
struct sockaddr_in caddr;
socklen_t acclen = sizeof(caddr);
unsigned int index = 0;
unsigned int index_to_edit=0;
string new_note;
string edit_not;
int res, i;
char c, ch;
char *tmp;
string input;
char wel_msg[512] = "Welcome! Enjoy to use this app to manage your notes";
acclen = sizeof(caddr);
Edit *edit_obj = new Edit;
while(1){
if((client_sockfd = accept(fd_sock, (struct sockaddr *) &caddr, &acclen)) < 0 ){
std::cerr << strerror(errno) << std::endl;
exit(1);
}
dup2(client_sockfd, 0);
dup2(client_sockfd, 1);
dup2(client_sockfd, 2);
cout << wel_msg << endl;
while(1){
cout << "1- Insert a note" << endl;
cout << "2- show all notes" << endl;
cout << "3- Edit a note" << endl;
cout << "4- Delete the last note" << endl;
cout << "5- Set your address :)" << endl;
cout << "0- Change the message" << endl;
cout << endl;
std::cin.clear();
cin >> input;
c = input[0];
index = atoi(&c);
switch(index){
case 1:
cout << "Enter the new value: " << endl;
cin >> new_note;
edit_obj->insert_note(new_note);
break;
case 2:
edit_obj->show_all_notes();
break;
case 3:
cout << "Insert the index of the note to modify: " << endl;
cin >> input;
c = input[0];
index_to_edit = atoi(&c);
cout << "Enter the new value: " << endl;
cin >> edit_not;
res = edit_obj->edit_note(index_to_edit, edit_not);
break;
case 4:
edit_obj->delete_note();
cout << "Try to set the roulette number: " << endl;
cin >> roulette;
delete edit_obj;
break;
case 5:
set_address();
break;
case 0:
cout << "Enter the new message: " << endl;
tmp = wel_msg;
i=0;
ch = std::cin.get();
while ((ch = std::cin.get()) != 51 && i<256){
memcpy(tmp, &ch, 256);
tmp = tmp + 1;
i += 1;
}
break;
case 9:
stack_info();
cout << "Debug informations" << endl;
cout << "Address of wel_msg" << "---" << &wel_msg << endl;
cout << "Address of roulette" << "---" << &roulette << endl;
cout << "Well done!" << endl;
break;
default:
cout << "Please select a correct option! " << endl;
break;
}
}
}
close(client_sockfd);
return 0;
}
int main(){
pid_t pid;
int var = 1;
struct sockaddr_in sockaddr;
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
sockaddr.sin_port = htons(PORT);
while(1){
pid = fork();
if ( pid == 0 ){
cout << "Run pid=" << getpid() << endl;
if ((fd_sock = socket(PF_INET, SOCK_STREAM, 0)) < 0){
std::cerr << strerror(errno) << std::endl;
exit(1);
}
if(setsockopt(fd_sock, SOL_SOCKET, SO_REUSEADDR, &var, sizeof(int)) <0) {
std::cerr << strerror(errno) << std::endl;
exit(1);
}
if (bind(fd_sock, (struct sockaddr*) &sockaddr, sizeof(sockaddr)) <0 ){
std::cerr << strerror(errno) << std::endl;
exit(1);
}
if (listen(fd_sock, MAX_NUM) < 0){
std::cerr << strerror(errno) << std::endl;
exit(1);
}
note();
}
else{
wait(NULL);
close(fd_sock);
}
}
return 0;
}
| 2.671875 | 3 |
2024-11-18T18:23:16.823509+00:00 | 2014-11-28T03:35:36 | 02717a464c942a85900e7f5b39aa4825ae3ac8a1 | {
"blob_id": "02717a464c942a85900e7f5b39aa4825ae3ac8a1",
"branch_name": "refs/heads/master",
"committer_date": "2014-11-28T03:35:36",
"content_id": "014bb08f7ef0eb6efcb76c206ae06816f5f2fa65",
"detected_licenses": [
"MIT"
],
"directory_id": "ea74ccc73ca11cc485ebaeab631c949496fc92c4",
"extension": "h",
"filename": "socket_iocp.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": 863,
"license": "MIT",
"license_type": "permissive",
"path": "/skynet-0.2.0-mingw/skynet-src/socket_iocp.h",
"provenance": "stackv2-0003.json.gz:396104",
"repo_name": "horryq/skynet-windows",
"revision_date": "2014-11-28T03:35:36",
"revision_id": "95772f7a6f9ed8927b076a74b1c4dacc5bc6628c",
"snapshot_id": "67c32e72b51763bbafd5f3980032004e52a41e5e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/horryq/skynet-windows/95772f7a6f9ed8927b076a74b1c4dacc5bc6628c/skynet-0.2.0-mingw/skynet-src/socket_iocp.h",
"visit_date": "2017-05-29T17:24:34.260899"
} | stackv2 | #ifndef _SOCKET_IOCP_H_
#define _SOCKET_IOCP_H_
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
typedef HANDLE iocp_fd;
static iocp_fd iocp_create()
{
return CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
}
static int iocp_invalid(iocp_fd fd)
{
return fd == NULL;
}
static void iocp_release(iocp_fd fd)
{
CloseHandle(fd);
}
static int iocp_post_status(iocp_fd fd, DWORD bytes, ULONG_PTR key, OVERLAPPED* ol)
{
int r;
r = PostQueuedCompletionStatus(fd, bytes, key, ol);
return (r==0 ? -1 : 0);
}
static int iocp_get_status(iocp_fd fd, DWORD* bytes, ULONG_PTR* key, OVERLAPPED** ol, DWORD milli_seconds)
{
return GetQueuedCompletionStatus(fd, bytes, key, ol, milli_seconds) ? 0 : -1;
}
static int iocp_add(iocp_fd fd, HANDLE h, ULONG_PTR key)
{
return (CreateIoCompletionPort(h, fd, key, 0) == fd) ? 0 : -1;
}
#endif // _SOCKET_IOCP_H_
| 2.1875 | 2 |
2024-11-18T18:23:17.241833+00:00 | 2020-11-17T03:26:00 | b6b43a2fe017b4c7c5b0476280b413a76cdd464d | {
"blob_id": "b6b43a2fe017b4c7c5b0476280b413a76cdd464d",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-17T03:26:00",
"content_id": "d7f423f9753071dfda588dfc1bd082c179e4fff3",
"detected_licenses": [
"MIT"
],
"directory_id": "8c7fdad65a0a6ae76727a8c4f66496436375baf4",
"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": 270077441,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1154,
"license": "MIT",
"license_type": "permissive",
"path": "/software/main.c",
"provenance": "stackv2-0003.json.gz:396361",
"repo_name": "smpentecost/bbq_controller",
"revision_date": "2020-11-17T03:26:00",
"revision_id": "38ca79c6f0d57298ac6f3119658be08dfa710ce3",
"snapshot_id": "71ae84b873a1bc7f58e362c661e63a5fc39ae39f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/smpentecost/bbq_controller/38ca79c6f0d57298ac6f3119658be08dfa710ce3/software/main.c",
"visit_date": "2023-01-22T08:08:08.305518"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "controller.h"
#include "psql.h"
int main(int argc, char *argv[]){
int damper = 0;
float temp0 = 0.0;
float temp1 = 0.0;
float set_temp = 0;
int *spiHandle0 = malloc(4);
int *spiHandle1 = malloc(4);
if (argc != 2){
fprintf(stderr, "Set temperature required.\n");
return -1;
} else {
set_temp = atof(argv[1]);
fprintf(stdout, "Set temp to %f fahrenheit.\n", set_temp);
}
if (initController(spiHandle0, spiHandle1) != 0) exit(-1);
PGconn *conn = initdb();
sendTemperatures(conn, 150.0, 150.0);
getTemperatures(conn);
exit_nicely(conn);
while (1==1){
temp0 = getTemp(spiHandle0);
temp1 = getTemp(spiHandle1);
fprintf(stdout, "temp0 = %f\n", temp0);
fprintf(stdout, "temp1 = %f\n", temp1);
if (temp0 < set_temp){
if (damper < 100){
damper++;
}
} else if (temp0 > set_temp){
if (damper > 0){
damper--;
}
}
setDamperOpen(damper);
sleep(DAMPERPERIOD);
}
closeHandles(spiHandle0, spiHandle1);
free(spiHandle0);
free(spiHandle1);
return 0;
}
| 2.421875 | 2 |
2024-11-18T18:23:17.537805+00:00 | 2021-01-11T15:58:01 | aa8b6517021f0fcb7b7d4c36bee4339b4e1bcfe8 | {
"blob_id": "aa8b6517021f0fcb7b7d4c36bee4339b4e1bcfe8",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-11T15:58:01",
"content_id": "16317d3e25f60b5346a9e1640b81123e83ef0238",
"detected_licenses": [
"MIT"
],
"directory_id": "0421d5bc16d39030926b9e9a73a7a3e8c30b0361",
"extension": "c",
"filename": "marks and grade.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 280440599,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 364,
"license": "MIT",
"license_type": "permissive",
"path": "/marks and grade.c",
"provenance": "stackv2-0003.json.gz:396619",
"repo_name": "i447/ludo",
"revision_date": "2021-01-11T15:58:01",
"revision_id": "9eaafa446d1640a11467b57fe5c7f212d5fef461",
"snapshot_id": "9ff90765872432fdb7136c4989a80d4a86fc945b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/i447/ludo/9eaafa446d1640a11467b57fe5c7f212d5fef461/marks and grade.c",
"visit_date": "2023-02-15T09:22:33.424677"
} | stackv2 | #include<stdio.h>
int main()
{
int a;
printf("Enter the marks of the student out of 100\n");
scanf("%d",&a);
if(a>=85)
{
printf("Grade A");
}
else if(a>=70)
{
printf("Grade B");
}
else if(a>=55)
{
printf("Grade C");
}
else if(a>=40)
{
printf("Grade D");
}
else
{
printf("Grade F");
}
return 0;
}
| 3.015625 | 3 |
2024-11-18T18:23:17.589172+00:00 | 2021-05-16T18:19:28 | fe600a6d630c115408bf44bca19a93a4bfa14b56 | {
"blob_id": "fe600a6d630c115408bf44bca19a93a4bfa14b56",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-16T18:19:28",
"content_id": "81eabc7355c58401ea84f5c7bc36a0c6626b8cc4",
"detected_licenses": [
"Zlib"
],
"directory_id": "33a32e3dea38e3493e34effad75d9d557426d4ba",
"extension": "c",
"filename": "json.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 345414748,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 23312,
"license": "Zlib",
"license_type": "permissive",
"path": "/src/json.c",
"provenance": "stackv2-0003.json.gz:396747",
"repo_name": "JonCodesThings/jsonlib",
"revision_date": "2021-05-16T18:19:28",
"revision_id": "4f29bd2caa5729675c2dd6dd499a1d541734322a",
"snapshot_id": "db8fe92218265f8fd29a714ccb4e128f39f64c31",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JonCodesThings/jsonlib/4f29bd2caa5729675c2dd6dd499a1d541734322a/src/json.c",
"visit_date": "2023-05-27T04:06:13.527571"
} | stackv2 | #include <include/jsonlib/json.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
// TODO: @Jon
// Big TODO list for this file:
// - Add convenience functions for checking if a JSON struct contains a value of given type
// - Add proper tree searching (possible with some [] operator overloading? Opt-in C++ support would need to be added)
// - Better commentary
// - Way of enforcing precision of floating point string outputs
// - Make C standard library dependencies optional (allow for user-provided alternatives to these functions)
#define JSON_DEFAULT_TOKENS 32
#define JSON_DEFAULT_DIVIDER_STACK_SIZE 4
// NOTE: @Jon
// Tags for JSON nodes
extern const u8 JSON_STRING_TAG = 1 << 0;
extern const u8 JSON_INTEGER_TAG = 1 << 1;
extern const u8 JSON_DECIMAL_TAG = 1 << 2;
extern const u8 JSON_ARRAY_TAG = 1 << 3;
extern const u8 JSON_OBJECT_TAG = 1 << 4;
extern const u8 JSON_BOOLEAN_TAG = 1 << 5;
extern const u8 JSON_NULL_TAG = 1 << 6;
// NOTE: @Jon
// Some useful strings
static const char* const JSONtrueStr = "true";
static const char* const JSONfalseStr = "false";
static const char* const JSONnullStr = "null";
// NOTE: @Jon
// A struct for handling a char * string
typedef struct JSON_STRING_STRUCT
{
char *raw;
u32 length;
u32 capacity;
} JSON_STRING_STRUCT;
// NOTE: @Jon
// JSON Divider Stack for tracking different dividers (e.g. {} or [])
typedef struct JSON_DIVIDER_STACK
{
char *dividerStack;
u32 dividerCount;
u32 dividerCapacity;
} JSON_DIVIDER_STACK;
// NOTE: @Jon
// JSON Token Types
enum JSON_TOKEN_TYPE
{
LEFT_BRACE,
RIGHT_BRACE,
LEFT_SQUARE_BRACKET,
RIGHT_SQUARE_BRACKET,
COLON,
IDENTIFIER,
COMMA,
INTEGER,
FLOAT,
STRING,
JSON_TRUE,
JSON_FALSE,
JSON_NULL,
JSON_EOF,
JSON_ERROR,
JSON_TOKEN_TYPE_COUNT
};
// NOTE: @Jon
// Struct to store token information for the JSON
typedef struct JSON_TOKEN
{
enum JSON_TOKEN_TYPE type; // = JSON_TOKEN_TYPE::JSON_ERROR;
char* identifier; // = NULL;
} JSON_TOKEN;
typedef struct JSON_TOKENS
{
JSON_TOKEN *tokens;
u32 tokenCount;
u32 tokenCapacity;
} JSON_TOKENS;
static JSON_ALLOC allocate = malloc;
static JSON_DEALLOC deallocate = free;
// NOTE: @Jon
// Parses an identifier
static void ParseIdentifier(JSON_TOKEN *token, const char *ident, u32 valueLength)
{
token->type = IDENTIFIER;
token->identifier = (char*)allocate(sizeof(char) * ((size_t)valueLength + 1));
token->identifier[valueLength] = '\0';
memcpy((void*)token->identifier, ident, sizeof(char) * (valueLength));
}
// NOTE: @Jon
// Parses a value
static void ParseValue(JSON_TOKEN *token, const char *value, u32 valueLength)
{
// If the value matches a string
if (value[0] == '"' && value[valueLength] == '"')
{
token->type = STRING;
token->identifier = (char*)allocate(sizeof(char) * (valueLength));
token->identifier[valueLength - 1] = '\0';
memcpy(token->identifier, &value[1], sizeof(char) * (valueLength - 1));
}
// If it starts with a number
else if (isdigit(value[0]) || value[0] == '-')
{
token->identifier = (char*)allocate(sizeof(char) * ((size_t)valueLength + 1));
token->identifier[valueLength] = '\0';
memcpy(token->identifier, value, sizeof(char) * (valueLength));
for (u32 i = 0; i < valueLength; ++i)
{
if (value[i] == '.')
{
token->type = FLOAT;
return;
}
}
token->type = INTEGER;
}
// If it's a boolean value
else if ((value[0] == 't' || value[0] == 'f') && (value[valueLength] == 'e'))
{
if (value[0] == 't')
token->type = JSON_TRUE;
else
token->type = JSON_FALSE;
}
// If it's just null
else if (value[0] == 'n' && value[valueLength] == 'l')
token->type = JSON_NULL;
// Otherwise give up
else
token->type = JSON_ERROR;
}
// NOTE: @Jon
// Adds a value to the JSON node given
void JSONLIB_AddValueJSON(JSON *json, JSON *val)
{
json->valueCount++;
if (val != NULL)
val->parent = json;
// Allocate the memory
JSON **newValueArray = (JSON**)allocate(sizeof(JSON*) * json->valueCount);
assert(newValueArray != NULL);
// Copy over the old array and free the memory
if (json->valueCount - 1 > 0)
memcpy(newValueArray, json->values, sizeof(JSON*) * (json->valueCount - 1));
if (json->values != NULL)
deallocate(json->values);
json->values = newValueArray;
if (val != NULL)
json->values[json->valueCount - 1] = val;
}
static void DividerStackPush(JSON_DIVIDER_STACK *const stack, const char toPush)
{
stack->dividerStack[stack->dividerCount++] = toPush;
}
static char DividerStackPop(JSON_DIVIDER_STACK *const stack)
{
return stack->dividerStack[--stack->dividerCount];
}
// NOTE: @Jon
// Get the closing token to the current divider
static u32 GetCloserOffset(JSON_TOKEN *token, u32 startToken, u32 tokenCount, JSON_DIVIDER_STACK *stack, enum JSON_TOKEN_TYPE opener, enum JSON_TOKEN_TYPE closer)
{
for (u32 i = 0; i < tokenCount; ++i)
{
if (token[i].type == LEFT_BRACE || token[i].type == LEFT_SQUARE_BRACKET)
DividerStackPush(stack, 'S');
else if (token[i].type == RIGHT_BRACE || token[i].type == RIGHT_SQUARE_BRACKET)
DividerStackPop(stack);
if (stack->dividerCount == 0)
return i - startToken;
}
return -1;
}
// NOTE: @Jon
// Convenience function for adding a new value to an array that's being parsed
static void AddValueToArray(JSON** json)
{
JSONLIB_AddValueJSON((*json), NULL);
JSON* newVal = (JSON*)allocate(sizeof(JSON));
newVal->parent = (*json);
assert((*json)->values != NULL);
(*json)->values[(*json)->valueCount - 1] = newVal;
(*json) = newVal;
(*json)->name = NULL;
}
// NOTE: @Jon
// Convenience function for adding a decimal number to a node
static void AddDecimalValue(JSON **json, const char *decimalStr)
{
(*json)->decimal = (f32)atof(decimalStr);
(*json)->tags = 0;
(*json)->tags |= JSON_DECIMAL_TAG;
(*json)->valueCount = 0;
*json = (*json)->parent;
deallocate(decimalStr);
}
// NOTE: @Jon
// Convenience function for adding an integer number to a node
static void AddIntegerValue(JSON **json, const char *integerStr)
{
(*json)->integer = atoi(integerStr);
(*json)->tags = 0;
(*json)->tags |= JSON_INTEGER_TAG;
(*json)->valueCount = 0;
*json = (*json)->parent;
deallocate(integerStr);
}
// NOTE: @Jon
// Convenience function for adding a string to a node
static void AddStringValue(JSON **json, const char *str)
{
(*json)->string = str;
(*json)->tags = 0;
(*json)->tags |= JSON_STRING_TAG;
(*json)->valueCount = 0;
*json = (*json)->parent;
}
// NOTE: @Jon
// Convenience function for adding a boolean value to a node
static void AddBooleanValue(JSON** json, bool boolean)
{
(*json)->boolean = boolean;
(*json)->tags = 0;
(*json)->tags |= JSON_BOOLEAN_TAG;
(*json)->valueCount = 0;
*json = (*json)->parent;
}
// NOTE: @Jon
// Convenience function for adding a null value to a node
static void AddNullValue(JSON** json)
{
(*json)->values = NULL;
(*json)->tags = 0;
(*json)->tags |= JSON_NULL_TAG;
(*json)->valueCount = 0;
*json = (*json)->parent;
}
// NOTE: @Jon
// Function for tokenising the given input string
static JSON_TOKENS* Tokenise(const char* jsonString, u32 stringLength, JSON_DIVIDER_STACK* dividerStack)
{
JSON_TOKENS* container = (JSON_TOKENS*)allocate(sizeof(JSON_TOKENS));
container->tokens = (JSON_TOKEN*)allocate(sizeof(JSON_TOKEN) * JSON_DEFAULT_TOKENS);
container->tokenCount = 0;
container->tokenCapacity = JSON_DEFAULT_TOKENS;
for (u32 i = 0; i < stringLength; ++i)
{
if (container->tokenCount >= container->tokenCapacity)
{
JSON_TOKEN* newTokenAlloc = (JSON_TOKEN*)allocate(sizeof(JSON_TOKEN) * container->tokenCapacity * 2);
assert(newTokenAlloc != NULL);
memcpy(newTokenAlloc, container->tokens, sizeof(JSON_TOKEN) * container->tokenCapacity);
deallocate(container->tokens);
container->tokens = newTokenAlloc;
container->tokenCapacity *= 2;
}
switch (jsonString[i])
{
// NOTE: @Jon
// Fairly standard JSON character handling
case '{':
container->tokens[container->tokenCount++].type = LEFT_BRACE;
dividerStack->dividerStack[dividerStack->dividerCount++] = jsonString[i];
break;
case '}':
container->tokens[container->tokenCount++].type = RIGHT_BRACE;
dividerStack->dividerCount--;
break;
case '[':
container->tokens[container->tokenCount++].type = LEFT_SQUARE_BRACKET;
dividerStack->dividerStack[dividerStack->dividerCount++] = jsonString[i];
break;
case ']':
container->tokens[container->tokenCount++].type = RIGHT_SQUARE_BRACKET;
dividerStack->dividerCount--;
break;
case '"':
if (dividerStack->dividerStack[dividerStack->dividerCount - 1] == '"')
dividerStack->dividerCount--;
else
dividerStack->dividerStack[dividerStack->dividerCount++] = jsonString[i];
break;
case ':':
container->tokens[container->tokenCount++].type = COLON;
break;
case ',':
container->tokens[container->tokenCount++].type = COMMA;
break;
default:
if (container->tokens[container->tokenCount - 1].type == COLON)
{
if (dividerStack->dividerStack[dividerStack->dividerCount - 1] == '"')
{
for (u32 iter = i; iter < stringLength; ++iter)
{
if (jsonString[iter] == '"')
{
// Get the length of the string
u32 length = (iter - i) + 1;
ParseValue(&container->tokens[container->tokenCount++], &jsonString[i - 1], length);
// Stop checking for an identifier
i = iter - 1;
break;
}
}
}
else if (isdigit(jsonString[i]) || jsonString[i] == '-')
{
for (u32 iter = i; iter < stringLength; ++iter)
{
if (jsonString[iter] == ',' || jsonString[iter] == '}')
{
u32 length = iter - i;
ParseValue(&container->tokens[container->tokenCount++], &jsonString[i], length);
i = iter - 1;
break;
}
}
}
else if (jsonString[i] == 'n' || jsonString[i] == 't' || jsonString[i] == 'f')
{
for (u32 iter = i; iter < stringLength; ++iter)
{
if (jsonString[iter] == ',' || jsonString[iter] == '}')
{
u32 length = iter - i;
ParseValue(&container->tokens[container->tokenCount++], &jsonString[i], length - 1);
i = iter - 1;
break;
}
}
}
}
else if ((container->tokens[container->tokenCount - 1].type == COMMA || container->tokens[container->tokenCount - 1].type == LEFT_BRACE || container->tokens[container->tokenCount - 1].type == LEFT_SQUARE_BRACKET))
{
if (dividerStack->dividerStack[dividerStack->dividerCount - 1] == '"')
{
for (u32 iter = i; iter < stringLength; ++iter)
{
if (jsonString[iter] == '"')
{
// Get the length of the string
u32 length = iter - i;
ParseIdentifier(&container->tokens[container->tokenCount++] , &jsonString[i], length);
// printf("%s\n", container->tokens[container->tokenCount].identifier);
// Stop checking for an identifier
i = iter - 1;
break;
}
}
}
bool divstack = false;
if (dividerStack->dividerCount > 1)
divstack = dividerStack->dividerStack[dividerStack->dividerCount - 2] == '[';
if (dividerStack->dividerStack[dividerStack->dividerCount - 1] == '[' || divstack)
{
if (isdigit(jsonString[i]))
{
for (u32 iter = i; iter < stringLength; ++iter)
{
if (jsonString[iter] == ',' || jsonString[iter] == '}' || jsonString[iter] == ']' || jsonString[iter] == '\r' || jsonString[iter] == '\n')
{
u32 length = iter - i;
ParseValue(&container->tokens[container->tokenCount++], &jsonString[i], length);
i = iter - 1;
break;
}
}
}
}
}
break;
}
}
return container;
}
// NOTE: @Jon
// Corrects some problems with the tokenisation process after it has finished running
static bool CorrectTokens(JSON_TOKENS* tokens, JSON_DIVIDER_STACK* dividerStack)
{
for (u32 i = 0; i < dividerStack->dividerCapacity; ++i)
{
dividerStack->dividerStack[i] = ' ';
}
for (u32 i = 0; i < tokens->tokenCount; ++i)
{
JSON_TOKEN* prev = i > 0 ? &tokens->tokens[i - 1] : NULL;
JSON_TOKEN* next = i < tokens->tokenCount - 1 ? &tokens->tokens[i + 1] : NULL;
JSON_TOKEN* current = &tokens->tokens[i];
switch (current->type)
{
default:
break;
case LEFT_BRACE:
DividerStackPush(dividerStack, '{');
break;
case LEFT_SQUARE_BRACKET:
DividerStackPush(dividerStack, '[');
break;
case RIGHT_BRACE:
case RIGHT_SQUARE_BRACKET:
DividerStackPop(dividerStack);
break;
case JSON_ERROR:
return false;
}
if (current->type == IDENTIFIER)
{
if (dividerStack->dividerCount - 1 > 0 && next != NULL)
{
if (dividerStack->dividerStack[dividerStack->dividerCount - 1] == '[' && next->type != COLON)
current->type = STRING;
}
}
}
return true;
}
// NOTE: @Jon
// Internal parsing function
static JSON *ParseJSONInternal(JSON_TOKEN *tokens, u32 tokenCount, JSON_DIVIDER_STACK *stack, const u8 tags, JSON *parent)
{
JSON* json = NULL;
if ((!(tags & JSON_ARRAY_TAG) && !(tags & JSON_OBJECT_TAG)) || parent == NULL)
{
json = (JSON*)allocate(sizeof(JSON));
assert(json != NULL);
json->name = NULL;
json->valueCount = 0;
json->tags = 0;
json->tags |= tags;
json->values = NULL;
json->parent = parent;
}
else
json = parent;
assert(json != NULL);
bool finished = true;
for (u32 i = 1; i < tokenCount - 1; ++i)
{
switch (tokens[i].type)
{
case LEFT_BRACE:
{
u32 offset = GetCloserOffset(&tokens[i], 0, tokenCount - i, stack, LEFT_BRACE, RIGHT_BRACE);
if (offset == -1)
{
finished = false;
break;
}
assert(json != NULL);
if (json->tags & JSON_ARRAY_TAG)
{
JSONLIB_AddValueJSON(json, NULL);
JSON* newVal = (JSON*)allocate(sizeof(JSON));
newVal->parent = json;
assert(json->values != NULL);
json->values[json->valueCount - 1] = newVal;
newVal->name = NULL;
newVal->valueCount = 0;
json = newVal;
}
// Go one layer deeper to parse an object
ParseJSONInternal(&tokens[i], offset + 1, stack, JSON_OBJECT_TAG, json);
i += offset;
json->tags = 0; json->tags |= JSON_OBJECT_TAG;
json = json->parent;
break;
}
case LEFT_SQUARE_BRACKET:
{
u32 offset = GetCloserOffset(&tokens[i], 0, tokenCount - i, stack, LEFT_SQUARE_BRACKET, RIGHT_SQUARE_BRACKET);
if (offset == -1)
{
finished = false;
break;
}
assert(json != NULL);
json->tags = 0; json->tags |= JSON_ARRAY_TAG;
// Go one layer deeper to parse an array
ParseJSONInternal(&tokens[i], offset + 1, stack, JSON_ARRAY_TAG, json);
i += offset;
json = json->parent;
break;
}
case RIGHT_BRACE:
break;
case IDENTIFIER:
{
// Allocate a node for this identifier
JSON *val = (JSON*)allocate(sizeof(JSON));
JSONLIB_AddValueJSON (json, val);
assert(json->values != NULL);
json = val;
json->name = tokens[i].identifier;
json->values = NULL;
json->valueCount = 0;
json->tags = 0;
break;
}
case COLON:
// If we see a colon the next token *should* be a value
break;
case STRING:
{
if (json->tags & JSON_ARRAY_TAG)
AddValueToArray(&json);
// Add a string value to the node
AddStringValue(&json, tokens[i].identifier);
break;
}
case INTEGER:
{
if (json->tags & JSON_ARRAY_TAG)
AddValueToArray(&json);
// Add an integer value to the node
AddIntegerValue(&json, tokens[i].identifier);
break;
}
case FLOAT:
{
if (json->tags & JSON_ARRAY_TAG)
AddValueToArray(&json);
// Add a float value to the node
AddDecimalValue(&json, tokens[i].identifier);
break;
}
case JSON_TRUE:
case JSON_FALSE:
{
if (json->tags & JSON_ARRAY_TAG)
AddValueToArray(&json);
// Add a boolean value to the node
AddBooleanValue(&json, tokens[i].type == JSON_TRUE);
break;
}
case JSON_NULL:
{
if (json->tags & JSON_ARRAY_TAG)
AddValueToArray(&json);
// Add a null value to the node
AddNullValue(&json);
break;
}
}
}
if (finished)
return json;
JSONLIB_FreeJSON(json);
return NULL;
}
// NOTE: @Jon
// Sets the allocation functions for the library to use internally
void JSONLIB_SetAllocator(JSON_ALLOC alloc, JSON_DEALLOC dealloc)
{
allocate = alloc;
deallocate = dealloc;
}
// NOTE: @Jon
// Convenience function for freeing memory
static void FreeTokenAndStackMemory(JSON_TOKENS *tokens, JSON_DIVIDER_STACK *stack)
{
for (u32 i = 0; i < tokens->tokenCount; ++i)
{
if (tokens->tokens[i].identifier != NULL)
deallocate(tokens->tokens[i].identifier);
}
deallocate(tokens->tokens);
deallocate(tokens);
deallocate(stack->dividerStack);
}
// NOTE: @Jon
// Parses a JSON string
JSON *JSONLIB_ParseJSON(const char *jsonString, u32 stringLength)
{
JSON_DIVIDER_STACK stack;
stack.dividerStack = (char*)allocate(sizeof(char) * JSON_DEFAULT_DIVIDER_STACK_SIZE);
stack.dividerCount = 0;
stack.dividerCapacity = JSON_DEFAULT_DIVIDER_STACK_SIZE;
JSON_TOKENS *tokens = Tokenise(jsonString, stringLength, &stack);
if (stack.dividerCount != 0)
{
FreeTokenAndStackMemory(tokens, &stack);
return NULL;
}
if (!CorrectTokens(tokens, &stack))
{
FreeTokenAndStackMemory(tokens, &stack);
return NULL;
}
JSON *json = ParseJSONInternal(tokens->tokens, tokens->tokenCount, &stack, JSON_OBJECT_TAG, NULL);
if (json == NULL)
{
FreeTokenAndStackMemory(tokens, &stack);
return NULL;
}
deallocate(tokens->tokens);
deallocate(tokens);
deallocate(stack.dividerStack);
return json;
}
static const char *DecimalValueToString(char *dest, const f32 decimal, const u32 stringSize)
{
snprintf(dest, sizeof(char) * stringSize, "%f", decimal);
return dest;
}
static const char *IntegerValueToString(char *dest, const i32 integer, const u32 stringSize)
{
snprintf(dest, sizeof(char) * stringSize, "%d", integer);
return dest;
}
static const char *CopyStringValueToString(char *dest, const char *source)
{
memcpy(dest, source, sizeof(char) * strlen(source));
return dest;
}
static const char* BooleanValueToString(char* dest, const bool boolean)
{
const char* copy = boolean ? JSONtrueStr : JSONfalseStr;
u32 len = boolean ? 5 : 6;
memcpy(dest, copy, sizeof(char) * len);
return dest;
}
static const char* NullValueToString(char* dest)
{
memcpy(dest, JSONnullStr, sizeof(char) * 5);
return dest;
}
static char *MakeStringValueString(const char *str)
{
char *memberNameString = (char*)allocate(sizeof(char) * strlen(str) + 3);
memberNameString[0] = memberNameString[strlen(str) + 1] = '\"';
memberNameString[strlen(str) + 2] = '\0';
memcpy(&memberNameString[1], str, sizeof(char) * strlen(str));
return memberNameString;
}
static char *MakeValueString(const JSON *json, const u32 stringSize, JSON_DIVIDER_STACK *stack)
{
// TODO: @Jon
// Gotta not hardcode this
char *valueString = NULL;
if (json->tags & JSON_DECIMAL_TAG || json->tags & JSON_INTEGER_TAG || json->tags & JSON_BOOLEAN_TAG || json->tags & JSON_NULL_TAG)
valueString = (char*)allocate(sizeof(char) * stringSize);
if (json->tags & JSON_DECIMAL_TAG)
DecimalValueToString(valueString, json->decimal, stringSize);
else if (json->tags & JSON_INTEGER_TAG)
IntegerValueToString(valueString, json->integer, stringSize);
else if (json->tags & JSON_BOOLEAN_TAG)
BooleanValueToString(valueString, json->boolean);
else if (json->tags & JSON_NULL_TAG)
NullValueToString(valueString);
else if (json->tags & JSON_STRING_TAG)
valueString = MakeStringValueString(json->string);
return valueString;
}
static bool StringCapacityHelper(JSON_STRING_STRUCT *str, u32 potentialAllocation)
{
if (str->length >= str->capacity || str->length + potentialAllocation >= str->capacity)
{
char *doubled = (char*)allocate(sizeof(char) * str->capacity * 2);
if (doubled == NULL)
return false;
memcpy(doubled, str->raw, sizeof(char) * str->length);
deallocate(str->raw);
str->raw = doubled;
str->capacity *= 2;
}
return true;
}
static JSON_STRING_STRUCT *MakeJSONPrettyNewline(JSON_STRING_STRUCT *str)
{
StringCapacityHelper(str, 1);
str->raw[str->length++] = '\n';
return str;
}
static JSON_STRING_STRUCT *MakeJSONInternal(JSON_STRING_STRUCT *str, JSON_DIVIDER_STACK *stack, const JSON *const json, const bool humanReadable)
{
if (json->name != NULL)
{
if (strlen(json->name) > 0)
{
char* name = MakeStringValueString(json->name);
StringCapacityHelper(str, (u32)strlen(name));
memcpy(&str->raw[str->length], name, sizeof(char) + strlen(name));
str->length += (u32)strlen(name);
StringCapacityHelper(str, 1);
str->raw[str->length++] = ':';
StringCapacityHelper(str, 64);
deallocate(name);
}
}
if (json->tags & JSON_OBJECT_TAG)
{
DividerStackPush(stack, '{');
str->raw[str->length++] = '{';
StringCapacityHelper(str, 0);
}
else if (json-> tags & JSON_ARRAY_TAG)
{
DividerStackPush(stack, '[');
str->raw[str->length++] = '[';
StringCapacityHelper(str, 0);
}
if (json->valueCount > 0)
{
for (u32 i = 0; i < json->valueCount; ++i)
{
MakeJSONInternal(str, stack, json->values[i], humanReadable);
if (i != json->valueCount - 1)
{
StringCapacityHelper(str, 1);
str->raw[str->length++] = ',';
}
if (humanReadable)
MakeJSONPrettyNewline(str);
}
}
else
{
char* valString = MakeValueString(json, 64, stack);
if (valString != NULL)
{
memcpy(&str->raw[str->length], valString, sizeof(char) + strlen(valString));
str->length += (u32)strlen(valString);
deallocate(valString);
}
}
if (json->tags & JSON_OBJECT_TAG)
{
DividerStackPop(stack);
str->raw[str->length++] = '}';
StringCapacityHelper(str, 0);
}
else if (json->tags & JSON_ARRAY_TAG)
{
DividerStackPop(stack);
str->raw[str->length++] = ']';
StringCapacityHelper(str, 0);
}
return str;
}
// NOTE: @Jon
// Makes a JSON string from a given tree input
const char * JSONLIB_MakeJSON(const JSON * const json, const bool humanReadable)
{
JSON_STRING_STRUCT jsonString;
jsonString.capacity = 64;
jsonString.length = 0;
jsonString.raw = (char*)allocate(sizeof(char) * 64);
JSON_DIVIDER_STACK stack;
stack.dividerStack = (char*)allocate(sizeof(char) * JSON_DEFAULT_DIVIDER_STACK_SIZE);
stack.dividerCount = 0;
stack.dividerCapacity = JSON_DEFAULT_DIVIDER_STACK_SIZE;
MakeJSONInternal(&jsonString, &stack, json, humanReadable);
StringCapacityHelper(&jsonString, 1);
jsonString.raw[jsonString.length++] = '\0';
deallocate(stack.dividerStack);
return jsonString.raw;
}
// NOTE: @Jon
// Gets a node from a given tree
JSON *JSONLIB_GetValueJSON(const char *name, u32 nameLength, JSON *json)
{
assert(json != NULL);
for (u32 i = 0; i < json->valueCount; ++i)
{
if (strcmp((*json->values[i]).name, name) == 0)
return json->values[i];
}
return NULL;
}
// NOTE: @Jon
// Frees memory related to a given tree
void JSONLIB_FreeJSON(JSON *json)
{
if (json == NULL)
return;
if (json->parent != NULL)
{
for (u32 i = 0; i < json->parent->valueCount; ++i)
{
if (json->parent->values[i] == json)
{
json->parent->values[i] = NULL;
break;
}
}
}
for (u32 i = 0; i < json->valueCount; ++i)
{
JSONLIB_FreeJSON(json->values[i]);
}
if (json->name)
deallocate((void*)json->name);
if (json->tags & JSON_STRING_TAG)
deallocate((void*)json->string);
if (json->valueCount > 0)
deallocate(json->values);
deallocate(json);
} | 2.625 | 3 |
2024-11-18T18:23:17.782066+00:00 | 2023-08-28T21:30:11 | 2022f7c08d4aaef6333e3f0d6d87f5bdb0dfd556 | {
"blob_id": "2022f7c08d4aaef6333e3f0d6d87f5bdb0dfd556",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-28T21:30:11",
"content_id": "74a32d416a87472277756860368072712872bbd5",
"detected_licenses": [
"MIT"
],
"directory_id": "aed47b5a4ea3af5cbacfc034c1565bd800e9461a",
"extension": "c",
"filename": "Main.c",
"fork_events_count": 53,
"gha_created_at": "2019-10-12T22:33:21",
"gha_event_created_at": "2023-03-02T21:35:56",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 214724629,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 613,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Main.c",
"provenance": "stackv2-0003.json.gz:396876",
"repo_name": "DanielMartensson/CControl",
"revision_date": "2023-08-28T21:30:11",
"revision_id": "25ce62ef3a0d87a55459fc9e7d4e1ee895d89ed9",
"snapshot_id": "a4dcfc13af8ef8266ac83f9ec0690848f5afd1b2",
"src_encoding": "UTF-8",
"star_events_count": 169,
"url": "https://raw.githubusercontent.com/DanielMartensson/CControl/25ce62ef3a0d87a55459fc9e7d4e1ee895d89ed9/src/Main.c",
"visit_date": "2023-08-30T23:53:16.167470"
} | stackv2 | /*
============================================================================
Name : Main.c
Author : <Your Name Here>
Version : 1.0
Copyright : MIT
Description : Initial template
============================================================================
*/
#include "CControl/Headers/Functions.h"
int main() {
clock_t start, end;
float cpu_time_used;
start = clock();
/* Your ANSI C logic here */
end = clock();
cpu_time_used = ((float) (end - start)) / CLOCKS_PER_SEC;
printf("\nTotal speed was %f\n", cpu_time_used);
return EXIT_SUCCESS;
}
| 2.453125 | 2 |
2024-11-18T18:23:18.171595+00:00 | 2019-10-14T05:32:53 | c985dd9e0f204dafe2cfdf80cb4831262b2e50d6 | {
"blob_id": "c985dd9e0f204dafe2cfdf80cb4831262b2e50d6",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-14T05:32:53",
"content_id": "0d0a9ed4cba9386b3e17208aaafebbe02f14485e",
"detected_licenses": [
"MIT"
],
"directory_id": "0c4bd1b977cc714a8a6b2839f51c4247ecfd32b1",
"extension": "c",
"filename": "layer.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": 6643,
"license": "MIT",
"license_type": "permissive",
"path": "/Neural-Networks/AdaptativeNeuralNetwork/src/models/PCFNN/layer.c",
"provenance": "stackv2-0003.json.gz:397004",
"repo_name": "ishine/neuralLOGIC",
"revision_date": "2019-10-14T05:32:53",
"revision_id": "3eb3b9980e7f7a7d87a77ef40b1794fb5137c459",
"snapshot_id": "281d498b40159308815cee6327e6cf79c9426b16",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ishine/neuralLOGIC/3eb3b9980e7f7a7d87a77ef40b1794fb5137c459/Neural-Networks/AdaptativeNeuralNetwork/src/models/PCFNN/layer.c",
"visit_date": "2020-08-14T14:11:54.487922"
} | stackv2 | #include <stdlib.h>
#include "ANN/models/PCFNN/neuron.h"
#include "ANN/tools.h"
#include "ANN/models/PCFNN/layer.h"
struct PCFNN_LAYER *PCFNN_LAYER_new(double(*f_init)(), double(*f_act)(double), double(*f_act_de)(double))
{
struct PCFNN_LAYER *l = malloc(sizeof(struct PCFNN_LAYER));
if (l == NULL) return NULL;
l->size = l->nblinks = l->index = 0;
l->neurons = malloc(sizeof(struct PCFNN_NEURON*) * l->size);
if (l->neurons == NULL)
{ free(l); return NULL; }
l->links = malloc(sizeof(struct PCFNN_LAYER_link*) * l->nblinks);
if (l->links == NULL)
{ free(l->neurons); free(l); return NULL; }
l->f_init = f_init;
l->f_act = f_act;
l->f_act_de = f_act_de;
return l;
}
void PCFNN_LAYER_clear(struct PCFNN_LAYER *l)
{
if (l == NULL) return;
for(size_t i = 0; i < l->size; ++i)
PCFNN_NEURON_clear(l->neurons[i]);
}
void PCFNN_LAYER_free(struct PCFNN_LAYER *l)
{
if (l != NULL)
{
for(size_t i = 0; i < l->size; ++i)
PCFNN_NEURON_free(l->neurons[i]);
for(size_t i = 0; i < l->nblinks; ++i)
{
if (l->links[i] != NULL)
{
if (l->links[i]->from == l)
l->links[i]->to->links[l->links[i]->index_to] = NULL;
else
l->links[i]->from->links[l->links[i]->index_from] = NULL;
free(l->links[i]);
l->links[i] = NULL;
}
}
free(l->neurons);
free(l->links);
free(l);
}
}
int PCFNN_LAYER_addn(struct PCFNN_LAYER *l, size_t size, size_t inputs, double(*f_init)(), double(*f_act)(double), double(*f_act_de)(double))
{
if (f_init == NULL && l->f_init != NULL) f_init = l->f_init;
if (f_act == NULL && l->f_act != NULL) f_act = l->f_act;
if (f_act_de == NULL && l->f_act_de != NULL) f_act_de = l->f_act_de;
if ((size <= 0 && inputs == 0) || f_act_de == NULL || f_act == NULL || f_init == NULL) return 1;
l->size += size;
l->neurons = realloc(l->neurons, sizeof(struct PCFNN_NEURON*) * l->size);
if (l->neurons == NULL) return -1;
for(size_t i = l->size - size; i < l->size; ++i)
{
l->neurons[i] = PCFNN_NEURON_new(inputs, f_init, f_act, f_act_de);
if (l->neurons[i] == NULL) return -1;
}
return 0;
}
struct PCFNN_LAYER *PCFNN_LAYER_new_input(size_t size, double(*f_act)(double), double(*f_act_de)(double))
{
struct PCFNN_LAYER *l = PCFNN_LAYER_new(f_init_input, f_act, f_act_de);
if (l == NULL) return NULL;
if (PCFNN_LAYER_addn(l, size, 0, f_init_input, f_act, f_act_de) != 0)
{ PCFNN_LAYER_free(l); return NULL; }
l->type = PCFNN_LAYER_INPUT;
return l;
}
int PCFNN_LAYER_connect(struct PCFNN_LAYER *from, struct PCFNN_LAYER *to,
size_t size_from, size_t size_to,
size_t offset_from, size_t offset_to,
double(*f_init_to)(), double(*f_act_to)(double), double(*f_act_de_to)(double))
{
if (from == NULL || to == NULL) return 1;
size_t ifrom = from->nblinks;
size_t ito = to->nblinks;
struct PCFNN_LAYER_LINK *link = malloc(sizeof(struct PCFNN_LAYER_LINK));
if (link == NULL) return -1;
++from->nblinks; ++to->nblinks;
from->links = realloc(from->links, sizeof(struct PCFNN_LAYER_LINK*) * from->nblinks);
if (from->links == NULL) { free(link); return -1; }
to->links = realloc(to->links, sizeof(struct PCFNN_LAYER_LINK*) * to->nblinks);
if (to->links == NULL) { free(link); return -1; }
link->from = from;
link->to = to;
link->index_from = ifrom;
link->index_to = ito;
link->size_from = size_from;
link->size_to = size_to;
link->f_init_to = f_init_to;
link->f_act_to = f_act_to;
link->f_act_de_to = f_act_de_to;
link->offset_from = offset_from;
link->offset_to = offset_to;
link->isInit = 0;
from->links[ifrom] = to->links[ito] = link;
return 0;
}
int PCFNN_LAYER_build(struct PCFNN_LAYER *l)
{
size_t nblinks[2]; nblinks[0] = nblinks[1] = 0;
if (l == NULL) return 1;
for(size_t k = 0; k < l->nblinks; ++k)
{
struct PCFNN_LAYER_LINK *link = l->links[k];
if (link == NULL) continue;
if (link->from == l)
++(nblinks[0]);
if (link->to == l && !link->isInit) {
if (link->offset_to > l->size) return 1;
for(size_t i = link->offset_to; i < l->size && i < link->size_to; ++i)
if (link->size_from > l->neurons[i]->size)
PCFNN_NEURON_addinputs(l->neurons[i], link->size_from - l->neurons[i]->size);
if (link->size_to + link->offset_to > l->size)
if (PCFNN_LAYER_addn(l, link->size_to + link->offset_to - l->size, link->size_from, link->f_init_to, link->f_act_to, link->f_act_de_to))
return -1;
link->isInit = 1; ++(nblinks[1]);
}
}
size_t w[l->size];
for(size_t i = 0; i < l->size; ++i)
{
PCFNN_NEURON_build(l->neurons[i]);
w[i] = 0;
}
for(size_t k = 0; k < l->nblinks; ++k)
{
struct PCFNN_LAYER_LINK *link = l->links[k];
if (link != NULL && link->to == l && link->isInit)
for(size_t i = link->offset_to; i < link->size_to + link->offset_to; ++i)
for(size_t j = link->offset_from; j < link->size_from + link->offset_from && w[i] < l->neurons[i]->size; ++j, ++w[i])
l->neurons[i]->inputs[w[i]] = link->from->neurons[j];
}
if (nblinks[0] == 0)
l->type = PCFNN_LAYER_OUTPUT;
else if (nblinks[1] == 0)
l->type = PCFNN_LAYER_INPUT;
else
l->type = PCFNN_LAYER_HIDDEN;
return 0;
}
size_t PCFNN_LAYER_get_ram_usage(struct PCFNN_LAYER *l)
{
if (l == NULL) return 0;
size_t usage = sizeof(struct PCFNN_LAYER);
usage += sizeof(struct PCFNN_NEURON*) * l->size;
for (size_t i = 0; i < l->size; ++i)
usage += PCFNN_NEURON_get_ram_usage(l->neurons[i]);
usage += sizeof(struct PCFNN_LAYER_LINK*) + sizeof(struct PCFNN_LAYER_LINK) * l->nblinks;
return usage;
}
void PCFNN_LAYER_set_lock_state(struct PCFNN_LAYER *l, enum PCFNN_NEURON_LOCK_STATE state, size_t size, size_t offset)
{
if (l == NULL || size + offset > l->size) return;
for (size_t i = offset; i < offset + size; ++i)
PCFNN_NEURON_set_state_lock(l->neurons[i], state);
}
void PCFNN_LAYER_summary(struct PCFNN_LAYER *l, size_t param[2])
{
if (l == NULL || param == NULL) return;
for (size_t i = 0; i < l->size; ++i)
PCFNN_NEURON_summary(l->neurons[i], param);
}
| 2.328125 | 2 |
2024-11-18T18:23:18.254326+00:00 | 2022-05-07T10:33:07 | a85f3fe84d7fd9bb1b9d9a9fe923946a6a7f0d11 | {
"blob_id": "a85f3fe84d7fd9bb1b9d9a9fe923946a6a7f0d11",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-07T10:33:07",
"content_id": "6ad6351027b2172ed7359d5850a0812bebf89649",
"detected_licenses": [
"MIT"
],
"directory_id": "c0ac5ccb734e6d27bc3b6b769e8714fc0ad33a41",
"extension": "c",
"filename": "Logging_frame.c",
"fork_events_count": 12,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 221542786,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7643,
"license": "MIT",
"license_type": "permissive",
"path": "/Optimized ILI9341 Touch LCD/Touch Screen/Frames/Logging_frame.c",
"provenance": "stackv2-0003.json.gz:397132",
"repo_name": "DanielMartensson/STM32-Libraries",
"revision_date": "2022-05-07T10:33:07",
"revision_id": "1e48e522bb8ef4b3a16a4622732246892d80cde9",
"snapshot_id": "5e926954cb47b998e3d067c1bcf2fc614f2b48a5",
"src_encoding": "UTF-8",
"star_events_count": 48,
"url": "https://raw.githubusercontent.com/DanielMartensson/STM32-Libraries/1e48e522bb8ef4b3a16a4622732246892d80cde9/Optimized ILI9341 Touch LCD/Touch Screen/Frames/Logging_frame.c",
"visit_date": "2022-05-30T22:40:17.477783"
} | stackv2 | /*
* Logging_frame.c
*
* Created on: 24 juli 2021
* Author: Daniel Mårtensson
*/
#include "../Touch_screen.h"
#include "../Hardware/ILI9341.h"
#include "../../Functions.h"
void STM32_PLC_LCD_Show_Logging_Frame(J1939 *j1939, uint8_t *frame_id) {
/* Clear the screen , but not the icons */
ILI9341_fill_rect(51, 6, 314, 234, COLOR_NAVY);
/* Write the title */
ILI9341_draw_horizontal_line(50, 30, 265, COLOR_GREEN);
char text[200];
ILI9341_print_text("Logging to a SD card", 55, 10, COLOR_YELLOW, COLOR_NAVY, 1);
/* Check the space */
uint32_t total_space;
uint32_t free_space;
FRESULT status = STM32_PLC_SD_Mont_Card();
if(status == FR_OK) {
STM32_PLC_SD_Check_Space(&total_space, &free_space);
sprintf(text, "Total space:%lu", total_space);
ILI9341_print_text(text, 55, 35, COLOR_YELLOW, COLOR_NAVY, 1);
sprintf(text, "Free space:%lu", free_space);
ILI9341_print_text(text, 55, 45, COLOR_YELLOW, COLOR_NAVY, 1);
} else {
ILI9341_print_text("Error:Could get the space", 55, 35, COLOR_YELLOW, COLOR_NAVY, 1);
sprintf(text, "SD mount error with FatFS code:%i", status);
STM32_PLC_LCD_Show_Information_OK_Dialog(text);
STM32_PLC_LCD_Show_Main_Frame(frame_id, false);
return;
}
/* Star logging button */
uint8_t x1 = 95;
uint8_t y1 = 205;
uint16_t x2 = 260;
uint8_t y2 = 230;
ILI9341_fill_rect(x1, y1, x2, y2, COLOR_GREEN);
ILI9341_hollow_rect(x1, y1, x2, y2, COLOR_BLACK);
ILI9341_print_text("Start logging", 100, 210, COLOR_BLACK, COLOR_GREEN, 2);
/* Logic for request button */
STM32_PLC_LCD_Call_One_Button_Logic(x1, y1, x2, y2);
/* Ask the user if */
if(STM32_PLC_LCD_Show_Question_Yes_No_Dialog("Do you want to log to file?") == 0) {
STM32_PLC_LCD_Show_Main_Frame(frame_id, false);
return;
}
/* You entered choice 1 - Show numpad */
bool minusbutton_show = false;
bool decimalbutton_show = false;
float number_value;
if(STM32_PLC_LCD_Show_Numpad_Frame(decimalbutton_show, minusbutton_show, &number_value, "Enter a log number") == 0) {
STM32_PLC_LCD_Show_Main_Frame(frame_id, false);
return;
}
/* Open a file */
sprintf(text, "%i.CSV", (uint16_t)number_value);
STM32_PLC_SD_Create_New_File_With_Read_Write(text, "", true);
STM32_PLC_SD_Open_Existing_File_With_Write(text);
STM32_PLC_SD_Write_File("ID,Day,Hour,Minute,Second,Millisecond,");
STM32_PLC_SD_Write_File("ADC0,ADC1,ADC2,ADC3,ADC4,ADC5,ADC6,ADC7,ADC8,ADC9,ADC10,ADC11,");
STM32_PLC_SD_Write_File("DADC0,DADC1,DADC2,DADC3,DADC4,");
STM32_PLC_SD_Write_File("I0,I1,I2,I3,I4,I5,I6,I7,");
STM32_PLC_SD_Write_File("E0,E1,");
STM32_PLC_SD_Write_File("IC0,IC1,");
STM32_PLC_SD_Write_File("DAC0,DAC1,DAC2,");
STM32_PLC_SD_Write_File("PWM0,PWM1,PWM2,PWM3,PWM4,PWM5,PWM6,PWM7,PULSE0,PULSE1,PULSE2,PULSE3\n");
/* Sample time */
if(STM32_PLC_LCD_Show_Numpad_Frame(decimalbutton_show, minusbutton_show, &number_value, "Enter sample time between 1 and 65535") == 0) {
STM32_PLC_LCD_Show_Main_Frame(frame_id, false);
return;
}
/* Check */
uint16_t sample_time;
if(number_value < 1)
sample_time = 1;
else if(number_value > 0xFFFF)
sample_time = 0xFFFF;
else
sample_time = (uint16_t) number_value;
/* Show main frame */
STM32_PLC_LCD_Show_Main_Frame(frame_id, false);
/* Clear the screen , but not the icons */
ILI9341_fill_rect(51, 6, 314, 234, COLOR_NAVY);
/* Write the title */
ILI9341_draw_horizontal_line(50, 30, 265, COLOR_GREEN);
ILI9341_print_text("Logging values and time", 55, 10, COLOR_YELLOW, COLOR_NAVY, 1);
/* Stop logging button */
ILI9341_fill_rect(x1, y1, x2, y2, COLOR_RED);
ILI9341_hollow_rect(x1, y1, x2, y2, COLOR_BLACK);
ILI9341_print_text("Stop logging", 105, 210, COLOR_BLACK, COLOR_RED, 2);
/* Do the logging process */
uint16_t milliseconds = 0;
uint8_t seconds = 0;
uint8_t minutes = 0;
uint8_t hours = 0;
uint8_t days = 0;
uint16_t counter = 0;
STM32_PLC_Pulse_Count_Reset();
uint32_t ID = 0; /* This is the primary key for counting how many samples we have */
while (!STM32_PLC_Digital_Input_Get_Stop()) {
/* Execute control program for every cycle */
STM32_PLC_LCD_Execute_Control_Program(j1939);
/* Write line for every sample time */
if(counter >= sample_time) {
ID++;
sprintf(text, "%lu,%i,%i,%i,%i,%i,",
ID,
days,
hours,
minutes,
seconds,
milliseconds);
STM32_PLC_SD_Write_File(text);
sprintf(text, "%0.2f,%0.2f,%0.2f,%0.2f,%0.2f,%0.2f,%0.2f,%0.2f,%0.2f,%0.2f,%0.2f,%0.2f,",
STM32_PLC_Analog_Input_ADC_Get(0),
STM32_PLC_Analog_Input_ADC_Get(1),
STM32_PLC_Analog_Input_ADC_Get(2),
STM32_PLC_Analog_Input_ADC_Get(3),
STM32_PLC_Analog_Input_ADC_Get(4),
STM32_PLC_Analog_Input_ADC_Get(5),
STM32_PLC_Analog_Input_ADC_Get(6),
STM32_PLC_Analog_Input_ADC_Get(7),
STM32_PLC_Analog_Input_ADC_Get(8),
STM32_PLC_Analog_Input_ADC_Get(9),
STM32_PLC_Analog_Input_ADC_Get(10),
STM32_PLC_Analog_Input_ADC_Get(11));
STM32_PLC_SD_Write_File(text);
sprintf(text, "%0.2f,%0.2f,%0.2f,%0.2f,%0.2f,",
STM32_PLC_Analog_Input_DADC_Get(0),
STM32_PLC_Analog_Input_DADC_Get(1),
STM32_PLC_Analog_Input_DADC_Get(2),
STM32_PLC_Analog_Input_DADC_Get(3),
STM32_PLC_Analog_Input_DADC_Get(4));
STM32_PLC_SD_Write_File(text);
sprintf(text, "%i,%i,%i,%i,%i,%i,%i,%i,",
STM32_PLC_Digital_Input_Get(0),
STM32_PLC_Digital_Input_Get(1),
STM32_PLC_Digital_Input_Get(2),
STM32_PLC_Digital_Input_Get(3),
STM32_PLC_Digital_Input_Get(4),
STM32_PLC_Digital_Input_Get(5),
STM32_PLC_Digital_Input_Get(6),
STM32_PLC_Digital_Input_Get(7));
STM32_PLC_SD_Write_File(text);
sprintf(text, "%f,%f,",
STM32_PLC_Encoder_Get(0),
STM32_PLC_Encoder_Get(1));
STM32_PLC_SD_Write_File(text);
sprintf(text, "%f,%f,",
STM32_PLC_Input_Capture_Get(0),
STM32_PLC_Input_Capture_Get(1));
STM32_PLC_SD_Write_File(text);
sprintf(text, "%i,%i,%i,",
STM32_PLC_Analog_Output_Get(0),
STM32_PLC_Analog_Output_Get(1),
STM32_PLC_Analog_Output_Get(2));
STM32_PLC_SD_Write_File(text);
sprintf(text, "%i,%i,%i,%i,%i,%i,%i,%i,",
STM32_PLC_PWM_Get(0),
STM32_PLC_PWM_Get(1),
STM32_PLC_PWM_Get(2),
STM32_PLC_PWM_Get(3),
STM32_PLC_PWM_Get(4),
STM32_PLC_PWM_Get(5),
STM32_PLC_PWM_Get(6),
STM32_PLC_PWM_Get(7));
STM32_PLC_SD_Write_File(text);
sprintf(text, "%lu,%lu,%lu,%lu,\n",
STM32_PLC_Pulse_Count_Get(0),
STM32_PLC_Pulse_Count_Get(1),
STM32_PLC_Pulse_Count_Get(2),
STM32_PLC_Pulse_Count_Get(3));
STM32_PLC_SD_Write_File(text);
/* Reset counter */
counter = 0;
}
/* For every iteration, do count */
counter++;
/* Compute time */
milliseconds++;
if(milliseconds >= 1000){
milliseconds = 0;
seconds++;
}
if(seconds >= 60){
seconds = 0;
minutes++;
}
if(minutes >= 60){
minutes = 0;
hours++;
}
if(hours >= 24) {
hours = 0;
days++;
}
if(days >= 255)
days = 0;
/* One 1 ms is necessary */
HAL_Delay(1);
/* Show plot frame */
STM32_PLC_LCD_Show_Plot_Frame();
/* Check if we want to abort if we press the button */
if (TSC2046_isPressed()) {
TSC2046_GetTouchData();
uint16_t X = lcd.myTsData.X;
uint16_t Y = lcd.myTsData.Y;
if (X >= x1 && X <= x2 && Y >= y1 && Y <= y2) {
ILI9341_hollow_rect(x1, y1, x2, y2, COLOR_MAGENTA);
break;
}
}
}
/* Close file */
STM32_PLC_SD_Close_File();
STM32_PLC_SD_Unmount_Card();
/* This causes that PWM, analog output is OFF - Safety */
STM32_PLC_PWM_Reset();
STM32_PLC_Analog_Output_Reset();
/* Exit */
STM32_PLC_LCD_Show_Main_Frame(frame_id, false);
}
| 2.484375 | 2 |
2024-11-18T18:23:18.568854+00:00 | 2020-11-02T08:53:31 | c82d1d1c66a4d8c222a8b8f64f4b97458b7bf662 | {
"blob_id": "c82d1d1c66a4d8c222a8b8f64f4b97458b7bf662",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-02T08:53:31",
"content_id": "702e2f674f9f07bec9a3476c0c59b8121c0aabdc",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fa7375ba7a73e0ad0b110b967c6062ddda467b07",
"extension": "c",
"filename": "test_harbor.c",
"fork_events_count": 8,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 36478952,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1519,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/win32/test_harbor.c",
"provenance": "stackv2-0003.json.gz:397521",
"repo_name": "lisheng20130930/evnet",
"revision_date": "2020-11-02T08:53:31",
"revision_id": "ab6d084ee878007543edf40269c75082c6da0902",
"snapshot_id": "ba3cfca53cc2528add1aa9809e32149b7459e5a3",
"src_encoding": "UTF-8",
"star_events_count": 23,
"url": "https://raw.githubusercontent.com/lisheng20130930/evnet/ab6d084ee878007543edf40269c75082c6da0902/win32/test_harbor.c",
"visit_date": "2021-01-10T08:48:48.634096"
} | stackv2 | #include "libos.h"
#include "evfunclib.h"
#include "harbor.h"
static int g_msgId = 0;
static bool harbor_msgHandler(void* harbor, int msgType, harborMsg_t *msg)
{
printf("harbor_msgHandler===> MsgType = %d ", msgType);
if(msgType==EMSGTYPE_ERROR){
printf("harbor Error ...errorCode=%d, msgId=%d\r\n",msg->errorcode,msg->msgId);
}else{
printf("harbor recv message ...msgId=%d, response=%s\r\n",msg->msgId,msg->message);
}
return true;
}
int mainXX(int argc, char **argv)
{
evnet_init(3000,500,0);
void *harbor = harbor_start("http://47.110.157.52:8000/pushService",harbor_msgHandler);
unsigned int g_loop = 1;
harbor_send(harbor, ++g_msgId, "{\"cmd\": 5000}",strlen("{\"cmd\": 5000}"));
harbor_send(harbor, ++g_msgId, "{\"cmd\": 5000}",strlen("{\"cmd\": 5000}"));
harbor_send(harbor, ++g_msgId, "{\"cmd\": 5000}",strlen("{\"cmd\": 5000}"));
harbor_send(harbor, ++g_msgId, "{\"cmd\": 5000}",strlen("{\"cmd\": 5000}"));
harbor_send(harbor, ++g_msgId, "{\"cmd\": 5000}",strlen("{\"cmd\": 5000}"));
harbor_send(harbor, ++g_msgId, "{\"cmd\": 5000}",strlen("{\"cmd\": 5000}"));
harbor_send(harbor, ++g_msgId, "{\"cmd\": 5000}",strlen("{\"cmd\": 5000}"));
harbor_send(harbor, ++g_msgId, "{\"cmd\": 5000}",strlen("{\"cmd\": 5000}"));
harbor_send(harbor, ++g_msgId, "{\"cmd\": 5000}",strlen("{\"cmd\": 5000}"));
while(1){
evnet_loop(g_loop);
g_loop++;
}
evnet_uint();
return 0;
} | 2.0625 | 2 |
2024-11-18T18:23:51.501960+00:00 | 2014-10-11T10:30:26 | 2ce287caecf2eea6beec258179de13556e6bc294 | {
"blob_id": "2ce287caecf2eea6beec258179de13556e6bc294",
"branch_name": "refs/heads/master",
"committer_date": "2014-10-11T10:30:26",
"content_id": "7f324200e1312d6cafde6fe31a01791626a5013e",
"detected_licenses": [
"MIT"
],
"directory_id": "31dbbdeee8bb9b996ab713d709fbb7273d3277ce",
"extension": "h",
"filename": "Loader.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": 5265,
"license": "MIT",
"license_type": "permissive",
"path": "/src/BlackBoneDrv/Loader.h",
"provenance": "stackv2-0003.json.gz:398291",
"repo_name": "kkoopa/Blackbone",
"revision_date": "2014-10-11T10:30:26",
"revision_id": "080913094c26ab5aabfb783ae252c718c1a0fdc9",
"snapshot_id": "fe120ab9dc69fd31be6087b00bd3d25251cb5435",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kkoopa/Blackbone/080913094c26ab5aabfb783ae252c718c1a0fdc9/src/BlackBoneDrv/Loader.h",
"visit_date": "2021-01-17T11:33:29.051949"
} | stackv2 | #pragma once
#include "Imports.h"
#include "NativeStructs.h"
// Module type
typedef enum _ModType
{
mt_mod32, // 64 bit module
mt_mod64, // 32 bit module
mt_default, // type is deduced from target process
mt_unknown // Failed to detect type
} ModType;
typedef struct _MODULE_DATA
{
LIST_ENTRY link; // List link
PUCHAR baseAddress; // Base image address in target process
PUCHAR localBase; // Base image address in system space
UNICODE_STRING name; // File name
UNICODE_STRING fullPath; // Full file path
SIZE_T size; // Size of image
ModType type; // Module type
enum MMapFlags flags; // Flags
BOOLEAN manual; // Image is manually mapped
BOOLEAN initialized; // DllMain was already called
} MODULE_DATA, *PMODULE_DATA;
/// <summary>
/// Initialize loader stuff
/// </summary>
/// <param name="pThisModule">Any valid system module</param>
/// <returns>Status code</returns>
NTSTATUS BBInitLdrData( IN PKLDR_DATA_TABLE_ENTRY pThisModule );
/// <summary>
/// Get address of a system module
/// Either 'pName' or 'pAddress' is required to perform search
/// </summary>
/// <param name="pName">Base name of the image (e.g. hal.dll)</param>
/// <param name="pAddress">Address inside module</param>
/// <returns>Found loader entry. NULL if nothing found</returns>
PKLDR_DATA_TABLE_ENTRY BBGetSystemModule( IN PUNICODE_STRING pName, IN PVOID pAddress );
/// <summary>
/// Get module base address by name
/// </summary>
/// <param name="pProcess">Target process</param>
/// <param name="ModuleName">Nodule name to search for</param>
/// <param name="isWow64">If TRUE - search in 32-bit PEB</param>
/// <returns>Found address, NULL if not found</returns>
PVOID BBGetUserModule( IN PEPROCESS pProcess, IN PUNICODE_STRING ModuleName, IN BOOLEAN isWow64 );
/// <summary>
/// Unlink user-mode module from Loader lists
/// </summary>
/// <param name="pProcess">Target process</param>
/// <param name="pBase">Module base</param>
/// <param name="isWow64">If TRUE - unlink from PEB32 Loader, otherwise use PEB64</param>
/// <returns>Status code</returns>
NTSTATUS BBUnlinkFromLoader( IN PEPROCESS pProcess, IN PVOID pBase, IN BOOLEAN isWow64 );
/// <summary>
/// Get exported function address
/// </summary>
/// <param name="pBase">Module base</param>
/// <param name="name_ord">Function name or ordinal</param>
/// <returns>Found address, NULL if not found</returns>
PVOID BBGetModuleExport( IN PVOID pBase, IN PCCHAR name_ord );
/// <summary>
/// Map new user module
/// </summary>
/// <param name="pProcess">Target process</param>
/// <param name="path">Image path</param>
/// <param name="buffer">Image buffer</param>
/// <param name="size">Image buffer size</param>
/// <param name="asImage">Buffer has image memory layout</param>
/// <param name="flags">Mapping flags</param>
/// <param name="pImage">Mapped image data</param>
/// <returns>Status code</returns>
NTSTATUS BBMapUserImage(
IN PEPROCESS pProcess,
IN PUNICODE_STRING path,
IN PVOID buffer, IN ULONG_PTR size,
IN BOOLEAN asImage,
IN INT flags,
OUT PMODULE_DATA pImage
);
NTSTATUS BBResolveReferences( IN PVOID pImageBase, IN BOOLEAN systemImage, IN PEPROCESS pProcess, IN BOOLEAN wow64Image );
/// <summary>
/// Find first thread of the target process
/// </summary>
/// <param name="pid">Target PID.</param>
/// <param name="ppThread">Found thread. Thread object reference count is increased by 1</param>
/// <returns>Status code</returns>
NTSTATUS BBLookupProcessThread( IN HANDLE pid, OUT PETHREAD* ppThread );
/// <summary>
/// Queue user-mode APC to the target thread
/// </summary>
/// <param name="pThread">Target thread</param>
/// <param name="pUserFunc">APC function</param>
/// <param name="Arg1">Argument 1</param>
/// <param name="Arg2">Argument 2</param>
/// <param name="Arg3">Argument 3</param>
/// <param name="bForce">If TRUE - force delivery by issuing special kernel APC</param>
/// <returns>Status code</returns>
NTSTATUS BBQueueUserApc(
IN PETHREAD pThread,
IN PVOID pUserFunc,
IN PVOID Arg1,
IN PVOID Arg2,
IN PVOID Arg3,
BOOLEAN bForce
);
/// <summary>
/// Manually map driver into system space
/// </summary>
/// <param name="pPath">Fully qualified native path to the driver</param>
/// <returns>Status code</returns>
NTSTATUS BBMMapDriver( IN PUNICODE_STRING pPath );
PIMAGE_BASE_RELOCATION
LdrProcessRelocationBlockLongLong(
IN ULONG_PTR VA,
IN ULONG SizeOfBlock,
IN PUSHORT NextOffset,
IN LONGLONG Diff
);
NTSTATUS
LdrRelocateImage (
IN PVOID NewBase,
IN NTSTATUS Success,
IN NTSTATUS Conflict,
IN NTSTATUS Invalid
);
NTSTATUS
LdrRelocateImageWithBias(
IN PVOID NewBase,
IN LONGLONG AdditionalBias,
IN NTSTATUS Success,
IN NTSTATUS Conflict,
IN NTSTATUS Invalid
);
PIMAGE_BASE_RELOCATION
LdrProcessRelocationBlock(
IN ULONG_PTR VA,
IN ULONG SizeOfBlock,
IN PUSHORT NextOffset,
IN LONG_PTR Diff
);
PIMAGE_BASE_RELOCATION
LdrProcessRelocationBlockLongLong(
IN ULONG_PTR VA,
IN ULONG SizeOfBlock,
IN PUSHORT NextOffset,
IN LONGLONG Diff
); | 2.046875 | 2 |
2024-11-18T18:23:51.698830+00:00 | 2023-08-31T05:50:29 | acb4bb4ba731d2b83f6b71703364d9ef4ea03946 | {
"blob_id": "acb4bb4ba731d2b83f6b71703364d9ef4ea03946",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T05:50:29",
"content_id": "928fa58199ba1e0fd29f8455262fbdf813541fd2",
"detected_licenses": [
"MIT"
],
"directory_id": "79d343002bb63a44f8ab0dbac0c9f4ec54078c3a",
"extension": "h",
"filename": "stat.h",
"fork_events_count": 2399,
"gha_created_at": "2015-08-06T00:51:28",
"gha_event_created_at": "2023-09-14T21:09:50",
"gha_language": "Zig",
"gha_license_id": "MIT",
"github_id": 40276274,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 433,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/libc/include/x86_64-linux-musl/bits/stat.h",
"provenance": "stackv2-0003.json.gz:398677",
"repo_name": "ziglang/zig",
"revision_date": "2023-08-31T05:50:29",
"revision_id": "f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c",
"snapshot_id": "4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5",
"src_encoding": "UTF-8",
"star_events_count": 25560,
"url": "https://raw.githubusercontent.com/ziglang/zig/f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c/lib/libc/include/x86_64-linux-musl/bits/stat.h",
"visit_date": "2023-08-31T13:16:45.980913"
} | stackv2 | /* copied from kernel definition, but with padding replaced
* by the corresponding correctly-sized userspace types. */
struct stat {
dev_t st_dev;
ino_t st_ino;
nlink_t st_nlink;
mode_t st_mode;
uid_t st_uid;
gid_t st_gid;
unsigned int __pad0;
dev_t st_rdev;
off_t st_size;
blksize_t st_blksize;
blkcnt_t st_blocks;
struct timespec st_atim;
struct timespec st_mtim;
struct timespec st_ctim;
long __unused[3];
}; | 2.140625 | 2 |
2024-11-18T18:23:51.953295+00:00 | 2019-01-23T19:32:38 | 87f5f962b086fa531f0c1f59b141ff15f510d4df | {
"blob_id": "87f5f962b086fa531f0c1f59b141ff15f510d4df",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-23T19:32:38",
"content_id": "85ddd6be6cc99ec92f451650cc838f16ecba45dd",
"detected_licenses": [
"TCL"
],
"directory_id": "bff941e571161a028114f42607ab59def9dce057",
"extension": "c",
"filename": "lockManagerImpl.c",
"fork_events_count": 0,
"gha_created_at": "2018-07-03T17:20:38",
"gha_event_created_at": "2018-07-03T17:20:39",
"gha_language": null,
"gha_license_id": null,
"github_id": 139615825,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11729,
"license": "TCL",
"license_type": "permissive",
"path": "/src/stasis/experimental/lockManagerImpl.c",
"provenance": "stackv2-0003.json.gz:399062",
"repo_name": "luochen01/stasis",
"revision_date": "2019-01-23T19:32:38",
"revision_id": "2a5f0f1536591ec488c2d9ffed674e8c59eb0cbf",
"snapshot_id": "fd7e86535aaf27e49e4f98d903e3a71efa951091",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/luochen01/stasis/2a5f0f1536591ec488c2d9ffed674e8c59eb0cbf/src/stasis/experimental/lockManagerImpl.c",
"visit_date": "2020-04-17T10:15:33.569118"
} | stackv2 | #include <config.h>
#include <pbl/pbl.h>
#include <stasis/lockManager.h>
#include <stasis/util/latches.h>
#include <stasis/util/hash.h>
#include <sys/time.h>
#include <time.h>
#include <assert.h>
#include <pthread.h>
static pthread_mutex_t stasis_lock_manager_ht_mut = PTHREAD_MUTEX_INITIALIZER;
static int pblHtInsert_r(pblHashTable_t * h, void * key, size_t keylen, void * val) {
pthread_mutex_lock(&stasis_lock_manager_ht_mut);
int ret = pblHtInsert(h, key, keylen, val);
pthread_mutex_unlock(&stasis_lock_manager_ht_mut);
return ret;
}
static void * pblHtLookup_r(pblHashTable_t * h, void * key, size_t keylen) {
pthread_mutex_lock(&stasis_lock_manager_ht_mut);
void * ret = pblHtLookup(h, key, keylen);
pthread_mutex_unlock(&stasis_lock_manager_ht_mut);
return ret;
}
static int pblHtRemove_r(pblHashTable_t * h, void * key, size_t keylen) {
pthread_mutex_lock(&stasis_lock_manager_ht_mut);
int ret = pblHtRemove(h, key, keylen);
pthread_mutex_unlock(&stasis_lock_manager_ht_mut);
return ret;
}
static void * pblHtFirst_r(pblHashTable_t *h) {
pthread_mutex_lock(&stasis_lock_manager_ht_mut);
void * ret = pblHtFirst(h);
pthread_mutex_unlock(&stasis_lock_manager_ht_mut);
return ret;
}
static void * pblHtNext_r(pblHashTable_t *h) {
pthread_mutex_lock(&stasis_lock_manager_ht_mut);
void * ret = pblHtNext(h);
pthread_mutex_unlock(&stasis_lock_manager_ht_mut);
return ret;
}
static void * pblHtCurrentKey_r(pblHashTable_t *h) {
pthread_mutex_lock(&stasis_lock_manager_ht_mut);
void * ret = pblHtCurrentKey(h);
pthread_mutex_unlock(&stasis_lock_manager_ht_mut);
return ret;
}
#define MUTEX_COUNT 32
// These next two correspond to MUTEX count, and are the appropriate values to pass into hash().
#define MUTEX_BITS 5
#define MUTEX_EXT 32
static pthread_mutex_t mutexes[MUTEX_COUNT];
static pthread_mutex_t xid_table_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t * getMutex(byte * dat, int datLen) {
return &mutexes[HASH_ENTRY(fcn)(dat, datLen, MUTEX_BITS, MUTEX_EXT)];
}
static pblHashTable_t * xidLockTable;
static pblHashTable_t * ridLockTable;
typedef struct {
pthread_cond_t writeOK;
pthread_cond_t readOK;
int readers;
int writers;
int waiting;
int active;
} lock;
void lockManagerInitHashed(void) {
int i = 0;
for(i = 0; i < MUTEX_COUNT; i++) {
pthread_mutex_init(&mutexes[i], NULL);
}
xidLockTable = pblHtCreate();
ridLockTable = pblHtCreate();
}
pblHashTable_t * lockManagerBeginTransactionUnlocked(int xid) {
pblHashTable_t * xidLocks = pblHtCreate();
pblHtInsert_r(xidLockTable, &xid, sizeof(int), xidLocks);
return xidLocks;
}
int lockManagerBeginTransaction(int xid) {
pthread_mutex_lock(&xid_table_mutex);
lockManagerBeginTransactionUnlocked(xid);
pthread_mutex_unlock(&xid_table_mutex);
return 0;
}
lock* createLock(byte * dat, int datLen) {
lock * ret = malloc(sizeof(lock));
if(!ret) { return NULL; }
// pthread_mutex_init(&ret->mut, NULL);
pthread_cond_init(&ret->writeOK, NULL);
pthread_cond_init(&ret->readOK, NULL);
ret->active = 0;
ret->readers = 0;
ret->writers = 0;
ret->waiting = 0;
pblHtInsert_r(ridLockTable, dat, datLen, ret);
return ret;
}
void destroyLock(byte * dat, int datLen, lock * l) {
pthread_cond_destroy(&l->writeOK);
pthread_cond_destroy(&l->readOK);
free (l);
pblHtRemove_r(ridLockTable, dat, datLen);
}
#define LM_READLOCK 1
#define LM_WRITELOCK 2
int lockManagerReadLockHashed(int xid, byte * dat, int datLen) {
if(xid == -1) { return 0; }
pthread_mutex_lock(&xid_table_mutex);
pblHashTable_t * xidLocks = pblHtLookup_r(xidLockTable, &xid, sizeof(int));
if(!xidLocks) {
xidLocks = lockManagerBeginTransactionUnlocked(xid);
}
long currentLockLevel = (long)pblHtLookup_r(xidLocks, dat, datLen);
// printf("xid %d read lock (%d)\n", xid, currentLockLevel);
if(currentLockLevel >= LM_READLOCK) {
pthread_mutex_unlock(&xid_table_mutex);
return 0;
}
assert(!currentLockLevel);
pthread_mutex_unlock(&xid_table_mutex);
pthread_mutex_t * mut = getMutex(dat, datLen);
pthread_mutex_lock(mut);
lock * ridLock = pblHtLookup_r(ridLockTable, dat, datLen);
if(!ridLock) {
ridLock = createLock(dat, datLen);
}
ridLock->active++;
if(ridLock->writers || ridLock->waiting) {
struct timeval tv;
int tod_ret = gettimeofday (&tv, NULL);
tv.tv_sec++; // Wait up to one second to obtain a lock before detecting deadlock.
struct timespec ts;
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * 1000;
if(tod_ret != 0) {
perror("Could not get time of day");
return LLADD_INTERNAL_ERROR;
}
do {
int wait_ret = pthread_cond_timedwait(&ridLock->readOK, mut, &ts);
if(wait_ret == ETIMEDOUT) {
ridLock->active--;
pthread_mutex_unlock(mut);
return LLADD_DEADLOCK;
}
} while(ridLock->writers);
}
if(currentLockLevel < LM_READLOCK) {
ridLock->readers++;
pblHtRemove_r(xidLocks, dat, datLen);
pblHtInsert_r(xidLocks, dat, datLen, (void*)LM_READLOCK);
}
ridLock->active--;
pthread_mutex_unlock(mut);
return 0;
}
int lockManagerWriteLockHashed(int xid, byte * dat, int datLen) {
if(xid == -1) { return 0; }
pthread_mutex_lock(&xid_table_mutex);
pblHashTable_t * xidLocks = pblHtLookup_r(xidLockTable, &xid, sizeof(int));
if(!xidLocks) {
xidLocks = lockManagerBeginTransactionUnlocked(xid);
}
long currentLockLevel = (long)pblHtLookup_r(xidLocks, dat, datLen);
// printf("xid %d write lock (%d)\n", xid, currentLockLevel);
int me = 0;
pthread_mutex_unlock(&xid_table_mutex);
if(currentLockLevel >= LM_WRITELOCK) {
return 0;
} else if(currentLockLevel == LM_READLOCK) {
me = 1;
}
pthread_mutex_t * mut = getMutex(dat, datLen);
pthread_mutex_lock(mut);
lock * ridLock = pblHtLookup_r(ridLockTable, dat, datLen);
if(!ridLock) {
ridLock = createLock(dat, datLen);
}
ridLock->active++;
ridLock->waiting++;
if(ridLock->writers || (ridLock->readers - me)) {
struct timeval tv;
int tod_ret = gettimeofday(&tv, NULL);
tv.tv_sec++;
struct timespec ts;
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * 1000;
if(tod_ret != 0) {
perror("Could not get time of day");
return LLADD_INTERNAL_ERROR;
}
while(ridLock->writers || (ridLock->readers - me)) {
int lockret = pthread_cond_timedwait(&ridLock->writeOK, mut, &ts);
if(lockret == ETIMEDOUT) {
ridLock->waiting--;
ridLock->active--;
pthread_mutex_unlock(mut);
return LLADD_DEADLOCK;
}
}
}
ridLock->waiting--;
if(currentLockLevel == 0) {
ridLock->readers++;
ridLock->writers++;
} else if (currentLockLevel == LM_READLOCK) {
ridLock->writers++;
pblHtRemove_r(xidLocks, dat, datLen);
}
if(currentLockLevel != LM_WRITELOCK) {
pblHtInsert_r(xidLocks, dat, datLen, (void*)LM_WRITELOCK);
}
ridLock->active--;
pthread_mutex_unlock(mut);
return 0;
}
static int decrementLock(void * dat, int datLen, int currentLevel) {
// pthread_mutex_unlock(&xid_table_mutex);
pthread_mutex_t * mut = getMutex(dat, datLen);
pthread_mutex_lock(mut);
lock * ridLock = pblHtLookup_r(ridLockTable, dat, datLen);
assert(ridLock);
ridLock->active++;
if(currentLevel == LM_WRITELOCK) {
ridLock->writers--;
ridLock->readers--;
} else if(currentLevel == LM_READLOCK) {
ridLock->readers--;
} else if(currentLevel == 0) {
assert(0); // Someone tried to release a lock they didn't own!
} else {
fprintf(stderr, "Unknown lock type encountered!");
ridLock->active--;
pthread_mutex_unlock(mut);
return LLADD_INTERNAL_ERROR;
}
ridLock->active--;
if(!(ridLock->active || ridLock->waiting || ridLock->readers || ridLock->writers)) {
// printf("destroyed lock");
destroyLock(dat, datLen, ridLock);
} else {
// printf("(%d %d %d %d)", ridLock->active, ridLock->waiting, ridLock->readers, ridLock->writers);
}
pthread_mutex_unlock(mut);
return 0;
}
int lockManagerUnlockHashed(int xid, byte * dat, int datLen) {
if(xid == -1) { return 0; }
// printf("xid %d unlock\n", xid);
pthread_mutex_lock(&xid_table_mutex);
pblHashTable_t * xidLocks = pblHtLookup_r(xidLockTable, &xid, sizeof(int));
if(!xidLocks) {
xidLocks = lockManagerBeginTransactionUnlocked(xid);
}
pthread_mutex_unlock(&xid_table_mutex);
long currentLevel = (long)pblHtLookup_r(xidLocks, dat, datLen);
assert(currentLevel);
pblHtRemove_r(xidLocks, dat, datLen);
decrementLock(dat, datLen, currentLevel);
return 0;
}
int lockManagerCommitHashed(int xid, int datLen) {
if(xid == -1) { return 0; }
pthread_mutex_lock(&xid_table_mutex);
pblHashTable_t * xidLocks = pblHtLookup_r(xidLockTable, &xid, sizeof(int));
pblHtRemove_r(xidLockTable, &xid, sizeof(int));
if(!xidLocks) {
xidLocks = lockManagerBeginTransactionUnlocked(xid);
}
pthread_mutex_unlock(&xid_table_mutex);
long currentLevel;
int ret = 0;
for(currentLevel = (long)pblHtFirst_r(xidLocks); currentLevel; currentLevel = (long)pblHtNext_r(xidLocks)) {
void * currentKey = pblHtCurrentKey_r(xidLocks);
int tmpret = decrementLock(currentKey, datLen, currentLevel);
// Pass any error(s) up to the user.
// (This logic relies on the fact that currently it only returns 0 and LLADD_INTERNAL_ERROR)
if(tmpret) {
ret = tmpret;
}
}
pblHtDelete(xidLocks);
return ret;
}
int lockManagerReadLockRecord(int xid, recordid rid) {
return lockManagerReadLockHashed(xid, (byte*)&rid, sizeof(recordid));
}
int lockManagerWriteLockRecord(int xid, recordid rid) {
return lockManagerWriteLockHashed(xid, (byte*)&rid, sizeof(recordid));
}
int lockManagerUnlockRecord(int xid, recordid rid) {
return lockManagerUnlockHashed(xid, (byte*)&rid, sizeof(recordid));
}
int lockManagerCommitRecords(int xid) {
return lockManagerCommitHashed(xid, sizeof(recordid));
}
int lockManagerReadLockPage(int xid, pageid_t p) {
return lockManagerReadLockHashed(xid, (byte*)&p, sizeof(p));
}
int lockManagerWriteLockPage(int xid, pageid_t p) {
return lockManagerWriteLockHashed(xid, (byte*)&p, sizeof(p));
}
int lockManagerUnlockPage(int xid, pageid_t p) {
return lockManagerUnlockHashed(xid, (byte*)&p, sizeof(p));
}
int lockManagerCommitPages(int xid) {
return lockManagerCommitHashed(xid, sizeof(pageid_t));
}
void setupLockManagerCallbacksPage(void) {
globalLockManager.init = &lockManagerInitHashed;
globalLockManager.readLockPage = &lockManagerReadLockPage;
globalLockManager.writeLockPage = &lockManagerWriteLockPage;
globalLockManager.unlockPage = &lockManagerUnlockPage;
globalLockManager.readLockRecord = NULL;
globalLockManager.writeLockRecord = NULL;
globalLockManager.unlockRecord = NULL;
globalLockManager.commit = &lockManagerCommitPages;
globalLockManager.abort = &lockManagerCommitPages;
globalLockManager.begin = &lockManagerBeginTransaction;
globalLockManager.init();
}
void setupLockManagerCallbacksRecord (void) {
globalLockManager.init = &lockManagerInitHashed;
globalLockManager.readLockPage = NULL;
globalLockManager.writeLockPage = NULL;
globalLockManager.unlockPage = NULL;
globalLockManager.readLockRecord = &lockManagerReadLockRecord;
globalLockManager.writeLockRecord = &lockManagerWriteLockRecord;
globalLockManager.unlockRecord = &lockManagerUnlockRecord;
globalLockManager.commit = &lockManagerCommitRecords;
globalLockManager.abort = &lockManagerCommitRecords;
globalLockManager.begin = &lockManagerBeginTransaction;
globalLockManager.init();
}
| 2.4375 | 2 |
2024-11-18T18:23:52.225411+00:00 | 2017-09-19T20:34:52 | eaf6d86a4d77b11f957d1ab5221e4b92af9a9b7f | {
"blob_id": "eaf6d86a4d77b11f957d1ab5221e4b92af9a9b7f",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-19T20:58:49",
"content_id": "52f6bad4fe7ab99b83d07acfb793bef59cca3b71",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "07419b56df0c85789afe5145adcd0fdfa1ddecd5",
"extension": "h",
"filename": "SkTSAN.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": 2698,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/include/private/SkTSAN.h",
"provenance": "stackv2-0003.json.gz:399447",
"repo_name": "mtMartijn/skia",
"revision_date": "2017-09-19T20:34:52",
"revision_id": "fe69f9a50ac1a6a61c9dda9c28c97599131656ee",
"snapshot_id": "f3e154303cfbe26c2a83e60dca54739f60e33c67",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mtMartijn/skia/fe69f9a50ac1a6a61c9dda9c28c97599131656ee/include/private/SkTSAN.h",
"visit_date": "2021-05-16T09:01:11.111739"
} | stackv2 | /*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkTSAN_DEFINED
#define SkTSAN_DEFINED
#include "SkTypes.h"
#if !defined(__DYNAMIC_ANNOTATIONS_H__)
#if !defined(__has_feature)
#define __has_feature(x) 0
#endif
#if __has_feature(thread_sanitizer)
/* Report that a lock has been created at address "lock". */
#define ANNOTATE_RWLOCK_CREATE(lock) \
AnnotateRWLockCreate(__FILE__, __LINE__, lock)
/* Report that the lock at address "lock" is about to be destroyed. */
#define ANNOTATE_RWLOCK_DESTROY(lock) \
AnnotateRWLockDestroy(__FILE__, __LINE__, lock)
/* Report that the lock at address "lock" has been acquired.
is_w=1 for writer lock, is_w=0 for reader lock. */
#define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \
AnnotateRWLockAcquired(__FILE__, __LINE__, lock, is_w)
/* Report that the lock at address "lock" is about to be released. */
#define ANNOTATE_RWLOCK_RELEASED(lock, is_w) \
AnnotateRWLockReleased(__FILE__, __LINE__, lock, is_w)
#if defined(DYNAMIC_ANNOTATIONS_WANT_ATTRIBUTE_WEAK)
#if defined(__GNUC__)
#define DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK __attribute__((weak))
#else
/* TODO(glider): for Windows support we may want to change this macro in order
to prepend __declspec(selectany) to the annotations' declarations. */
#error weak annotations are not supported for your compiler
#endif
#else
#define DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK
#endif
extern "C" {
void AnnotateRWLockCreate(
const char *file, int line,
const volatile void *lock) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
void AnnotateRWLockDestroy(
const char *file, int line,
const volatile void *lock) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
void AnnotateRWLockAcquired(
const char *file, int line,
const volatile void *lock, long is_w) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
void AnnotateRWLockReleased(
const char *file, int line,
const volatile void *lock, long is_w) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
}
#else
#define ANNOTATE_RWLOCK_CREATE(lock)
#define ANNOTATE_RWLOCK_DESTROY(lock)
#define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w)
#define ANNOTATE_RWLOCK_RELEASED(lock, is_w)
#endif
#endif//!defined(__DYNAMIC_ANNOTATIONS_H__)
#endif//SkTSAN_DEFINED
| 2.078125 | 2 |
2024-11-18T18:23:53.435385+00:00 | 2011-06-10T12:54:05 | ddecd883c4becd017461edef2746552cb20889d3 | {
"blob_id": "ddecd883c4becd017461edef2746552cb20889d3",
"branch_name": "refs/heads/master",
"committer_date": "2011-06-10T12:54:05",
"content_id": "91a5c6c79ea521af08977e0e0b2b17e7feacfc3e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "fa328fd89a419ff2c0947eb08686174622903d14",
"extension": "c",
"filename": "10_correlacion.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1417821,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3743,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/practica10/10_correlacion.c",
"provenance": "stackv2-0003.json.gz:399708",
"repo_name": "aruiz/AAN",
"revision_date": "2011-06-10T12:54:05",
"revision_id": "214ecd6e6cbe51dc28def39c4054a347d4e54b78",
"snapshot_id": "74bc0ed31e7a25ad5b88c3f200c6dc60b152bc33",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aruiz/AAN/214ecd6e6cbe51dc28def39c4054a347d4e54b78/practica10/10_correlacion.c",
"visit_date": "2020-06-06T06:41:35.128842"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include "ami_bmp.h"
#include "float_utils.h"
#include "aan_correlacion.h"
float*
unir_cuatro_imagenes (float *a, float *b, float*c, float *d, int width, int height)
{
int i, j;
float *output = (float*)malloc (sizeof (float) * (width * 2) * (height * 2));
float *tmp = output + (width * 2)*height;
/* Primer cuadrante */
for (i = 0; i < width; i++)
{
for (j=0; j < height; j++)
{
int index = (width*2)*j + i;
output[index] = c[width*j + i];
}
}
/* Segundo cuadrante */
for (i = 0; i < width; i++)
{
for (j=0; j < height; j++)
{
int index = (width*2)*j + i + width;
output[index] = d[width*j + i];
}
}
/* Tercer cuadrante */
for (i = 0; i < width; i++)
{
for (j=0; j < height; j++)
{
int index = (height * width * 2) + (width*2)*j + i;
output[index] = a[width*j + i];
}
}
/* Cuarto cuadrante */
for (i = 0; i < width; i++)
{
for (j=0; j < height; j++)
{
int index = (height * width * 2) + (width*2)*j + i + width;
output[index] = b[width*j + i];
}
}
return output;
}
int
main (int argc, char **argv)
{
int i;
int w1, h1, w2, h2;
unsigned char *red1, *green1, *blue1;
unsigned char *red2, *green2, *blue2;
float *fred1, *fgreen1, *fblue1;
float *fred2, *fgreen2, *fblue2;
float *fred_v, *fgreen_v, *fblue_v;
float *fred_h, *fgreen_h, *fblue_h;
float *fred_resultado,
*fgreen_resultado,
*fblue_resultado;
unsigned char *red_resultado,
*green_resultado,
*blue_resultado;
if (argc < 3)
{
fprintf (stderr, "Usage: %s <BMP file 1> <BMP file 2>\n", argv[0]);
return -1;
}
/* Leemos los ficheros dados como argumentos */
if (ami_read_bmp (argv[1], &red1, &green1, &blue1, &w1, &h1) < 0)
return -1;
if (ami_read_bmp (argv[2], &red2, &green2, &blue2, &w2, &h2) < 0)
return -2;
if (w1 != w2 || h1 != h2)
{
fprintf (stderr, "Las imagenes son de dimensiones distintas");
return -3;
}
fred1 = uchar_to_float (red1, w1*h1);
fgreen1 = uchar_to_float (green1, w1*h1);
fblue1 = uchar_to_float (blue1, w1*h1);
fred2 = uchar_to_float (red2, w2*h2);
fgreen2 = uchar_to_float (green2, w2*h2);
fblue2 = uchar_to_float (blue2, w2*h2);
fred_v = (float*)malloc(sizeof (float) * w1 * h1);
fgreen_v = (float*)malloc(sizeof (float) * w1 * h1);
fblue_v = (float*)malloc(sizeof (float) * w1 * h1);
fred_h = (float*)malloc(sizeof (float) * w1 * h1);
fgreen_h = (float*)malloc(sizeof (float) * w1 * h1);
fblue_h = (float*)malloc(sizeof (float) * w1 * h1);
aan_correlacion (fgreen1, fblue2, w1, h1, fblue_v, fblue_h);
fred_resultado = unir_cuatro_imagenes (fred1, fred2, fblue_v, fblue_h, w1, h1);
fgreen_resultado = unir_cuatro_imagenes (fgreen1, fgreen2, fblue_v, fblue_h, w1, h1);
fblue_resultado = unir_cuatro_imagenes (fblue1, fblue2, fblue_v, fblue_h, w1, h1);
red_resultado = float_to_uchar (fred_resultado, w1*2 * h1*2);
green_resultado = float_to_uchar (fgreen_resultado, w1*2 * h1*2);
blue_resultado = float_to_uchar (fblue_resultado, w1*2 * h1*2);
ami_write_bmp ("movimiento.bmp", red_resultado, green_resultado, blue_resultado, w1*2, h1*2);
/* Liberamos la memoria de los canales */
free (fred1); free (fgreen1); free (fblue1);
free (fred2); free (fgreen2); free (fblue2);
free (fred_v); free (fgreen_v); free (fblue_v);
free (fred_h); free (fgreen_h); free (fblue_h);
free (red1); free (green1); free (blue1);
free (red2); free (green2); free (blue2);
return 0;
}
| 2.796875 | 3 |
2024-11-18T18:23:53.693588+00:00 | 2020-10-22T07:09:55 | 208eae29f695c9061c4072efeace6e5704fa1c40 | {
"blob_id": "208eae29f695c9061c4072efeace6e5704fa1c40",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-22T07:09:55",
"content_id": "3cae4032b9a8c7dd5e2df720b27ddccecb5c29ef",
"detected_licenses": [
"MIT"
],
"directory_id": "be643cafc46704e30c33679a874bcbfd3c19ac8e",
"extension": "c",
"filename": "env_var.c",
"fork_events_count": 0,
"gha_created_at": "2020-09-05T05:42:43",
"gha_event_created_at": "2020-10-22T07:09:57",
"gha_language": "C",
"gha_license_id": null,
"github_id": 293011271,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1043,
"license": "MIT",
"license_type": "permissive",
"path": "/env_var.c",
"provenance": "stackv2-0003.json.gz:399966",
"repo_name": "samruddhishastri/Linux-C-Shell",
"revision_date": "2020-10-22T07:09:55",
"revision_id": "20c76c33b4306c20f93f7fa103869e47132f9521",
"snapshot_id": "a11ddcd5c67e70d534254dfb0cd7dee413af59da",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/samruddhishastri/Linux-C-Shell/20c76c33b4306c20f93f7fa103869e47132f9521/env_var.c",
"visit_date": "2023-01-06T11:52:03.986039"
} | stackv2 | #include"headerfiles/headers.h"
#include"headerfiles/env_var.h"
void setenv_func(char arg[]){
if(strcmp(arg, "setenv")==0){
printf("Invalid number of arguments passed\n");
return;
}
char var[40], val[256];
char *token = strtok(arg, " ");
token = strtok(NULL, " ");
strcpy(var, token);
token = strtok(NULL, " ");
if(token!=NULL){
strcpy(val, token);
token = strtok(NULL, " ");
}
else{
val[0] = '\0';
}
if(token!=NULL){
printf("Invalid number of arguments passed\n");
return;
}
int x = setenv(var, val, 1);
if(x<0){
printf("Error number %d\n", errno);
perror("Setenv:");
}
}
void unsetenv_func(char arg[]){
if(strcmp(arg, "unsetenv")==0){
printf("Invalid number of arguments passed\n");
return;
}
char var[40];
char *token = strtok(arg, " ");
token = strtok(NULL, " ");
strcpy(var, token);
token = strtok(NULL, " ");
if(token!=NULL){
printf("Invalid number of arguments passed");
return;
}
int x = unsetenv(var);
if(x<0){
printf("Error number %d\n", errno);
perror("Unsetenv:");
}
}
| 2.640625 | 3 |
2024-11-18T18:23:53.839269+00:00 | 2019-11-04T09:00:26 | 1ca339d13a8019d583aa6e8950cd67cfe890b2fd | {
"blob_id": "1ca339d13a8019d583aa6e8950cd67cfe890b2fd",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-04T09:25:11",
"content_id": "a856a0f8442c78a365fbc1795eae0357d1285f35",
"detected_licenses": [
"MIT"
],
"directory_id": "4b31b5e8dffcc48975d350d9fc1c5d303902d26e",
"extension": "c",
"filename": "glutil.c",
"fork_events_count": 1,
"gha_created_at": "2019-04-06T13:52:12",
"gha_event_created_at": "2019-11-04T18:02:40",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 179839268,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3199,
"license": "MIT",
"license_type": "permissive",
"path": "/sdl-main/glutil.c",
"provenance": "stackv2-0003.json.gz:400222",
"repo_name": "tkln/glsprite",
"revision_date": "2019-11-04T09:00:26",
"revision_id": "3e971baf5fca2dba5a2708523fe64f874e57d0e5",
"snapshot_id": "bbe41056ffca07103f47f0c5578608072fab236c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tkln/glsprite/3e971baf5fca2dba5a2708523fe64f874e57d0e5/sdl-main/glutil.c",
"visit_date": "2020-05-05T07:49:27.389502"
} | stackv2 | #include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#define GL_GLEXT_PROTOTYPES
#if defined(__APPLE__)
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#else
#include <GL/gl.h>
#include <GL/glext.h>
#endif
#include "glutil.h"
static char *glutil_load_file(const char *path, size_t *sz)
{
struct stat st;
ssize_t read_sz;
char *buf;
int err;
int fd;
fd = open(path, O_RDONLY);
if (fd == -1) {
perror("open");
return NULL;
}
err = fstat(fd, &st);
if (err == -1) {
perror("stat");
buf = NULL;
goto err_close;
}
buf = malloc(st.st_size + 1);
read_sz = read(fd, buf, st.st_size);
if (read_sz != st.st_size) {
perror("read");
free(buf);
buf = NULL;
goto err_close;
}
buf[st.st_size] = '\0';
if (sz)
*sz = st.st_size;
err_close:
close(fd);
return buf;
}
GLuint glutil_compile_shader(const char *const src, GLint *src_len,
GLenum shader_type)
{
GLint compile_status;
GLint info_log_len;
GLuint shader_id;
char *info_log;
shader_id = glCreateShader(shader_type);
if (!shader_id)
return 0;
/*
* The length cast may cause things to overflow into the sign bit, I'll deal
* with it once I see a shader that long. :-)
*/
glShaderSource(shader_id, 1, &src, src_len);
glCompileShader(shader_id);
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compile_status);
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &info_log_len);
if (!compile_status) {
info_log = alloca(info_log_len + 1);
glGetShaderInfoLog(shader_id, info_log_len, &info_log_len, info_log);
fprintf(stderr, "Shader compilation failed:\n%s\n", info_log);
glDeleteShader(shader_id);
shader_id = 0;
}
return shader_id;
}
GLuint glutil_compile_shader_file(const char *path, GLenum shader_type)
{
GLuint shader_id;
size_t src_len;
char *src;
src = glutil_load_file(path, &src_len);
if (!src) {
fprintf(stderr, "Loading shader file \"%s\" failed\n", path);
return 0;
}
shader_id = glutil_compile_shader(src, (GLint *)&src_len, shader_type);
free(src);
return shader_id;
}
GLuint glutil_link_shaders(GLuint shader_prog_id, GLuint shader_id_0, ...)
{
va_list shaders;
GLuint id;
GLint link_status;
GLint info_log_len;
char *info_log;
glAttachShader(shader_prog_id, shader_id_0);
va_start(shaders, shader_id_0);
while ((id = va_arg(shaders, GLuint)))
glAttachShader(shader_prog_id, id);
va_end(shaders);
glLinkProgram(shader_prog_id);
glGetProgramiv(shader_prog_id, GL_LINK_STATUS, &link_status);
glGetProgramiv(shader_prog_id, GL_INFO_LOG_LENGTH, &info_log_len);
if (!link_status) {
info_log = alloca(info_log_len + 1);
glGetProgramInfoLog(shader_prog_id, info_log_len, &info_log_len, info_log);
fprintf(stderr, "Shader linking failed:\n%s\n", info_log);
return 0;
}
return shader_prog_id;
}
| 2.4375 | 2 |
2024-11-18T18:23:54.091734+00:00 | 2020-01-17T08:53:50 | bd79558f96eac2cd42876fe84a2b61e8cc0f07b0 | {
"blob_id": "bd79558f96eac2cd42876fe84a2b61e8cc0f07b0",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-17T08:53:50",
"content_id": "a62fff8fc8da56e0aa79a154d4f80dbb851b0295",
"detected_licenses": [
"MIT"
],
"directory_id": "7c441af6a3f71dd766edfc34919182227cbd8815",
"extension": "c",
"filename": "tomb3.c",
"fork_events_count": 0,
"gha_created_at": "2020-01-17T08:46:06",
"gha_event_created_at": "2023-05-07T19:53:16",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 234507910,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 489,
"license": "MIT",
"license_type": "permissive",
"path": "/mudlib/d/choyin/tomb3.c",
"provenance": "stackv2-0003.json.gz:400478",
"repo_name": "angeluslove/es2",
"revision_date": "2020-01-17T08:53:50",
"revision_id": "9e24d6c0272231214f32699cbac23f4bbace370d",
"snapshot_id": "a0c69e57522cb940346c6805fd85e19cc0bbbad1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/angeluslove/es2/9e24d6c0272231214f32699cbac23f4bbace370d/mudlib/d/choyin/tomb3.c",
"visit_date": "2023-05-26T04:21:12.032453"
} | stackv2 | // Room: /d/choyin/tomb3.c
inherit ROOM;
void create()
{
set("short", "树王坟内部");
set("long", @LONG
这里是树王坟树洞的内部,你在这里可以闻到一股浓郁的檀香,奇
怪的是,这棵大树并不是檀木,却不知这股香味从哪里来?往南的出口
通往树洞的另一端。
LONG
);
set("exits", ([ /* sizeof() == 1 */
"south" : __DIR__"tomb1",
]));
set("objects", ([
__DIR__"obj/chest": 1
]) );
setup();
replace_program(ROOM);
}
| 2.015625 | 2 |
2024-11-18T18:23:54.311779+00:00 | 2019-10-28T01:48:11 | 1e1eb76499855ab38b620dfe86d860b0932e15f6 | {
"blob_id": "1e1eb76499855ab38b620dfe86d860b0932e15f6",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-28T01:48:11",
"content_id": "5c58c7a30d5da03291d3e2650ce80d4fe8399089",
"detected_licenses": [
"MIT"
],
"directory_id": "1d1db577d11bd353da5f3b973a9768aec0c1002e",
"extension": "c",
"filename": "ascii2c.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": 698,
"license": "MIT",
"license_type": "permissive",
"path": "/Virus.Win32.Kpasm/src/kpasm pour tasm/ascii2c.c",
"provenance": "stackv2-0003.json.gz:400735",
"repo_name": "chubbymaggie/Vx-Engines",
"revision_date": "2019-10-28T01:48:11",
"revision_id": "cc04d5c9567395caa83cdada9d1be1845c97dd09",
"snapshot_id": "00589663e143ede95f0c4168cfdcf03ceee90851",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chubbymaggie/Vx-Engines/cc04d5c9567395caa83cdada9d1be1845c97dd09/Virus.Win32.Kpasm/src/kpasm pour tasm/ascii2c.c",
"visit_date": "2020-12-03T22:56:20.185004"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
/*
#include "poly_fonctions.h"
int main()
{
FILE* f=fopen("poly_fonctions.asm","w");
fprintf(f,poly_fonctions);
fclose(f);
}
*/
int main()
{
char ligne[1024];
printf("char* poly_fonctions=\n");
while( fgets(ligne,1024,stdin))
{
printf("\"");
char* p;
for(p=ligne;*p!='\0';p++)
{
switch(*p)
{
case '\t':
printf("\\t");
break;
case '\n':
printf("\\n");
break;
case '\\':
printf("\\\\");
break;
case '\r':
printf("\\r");
break;
case '"':
printf("\\\"");
break;
default:
printf("%c",*p);
}
}
printf("\"\n");
}
printf(";\n");
return(EXIT_SUCCESS);
}
| 2.65625 | 3 |
2024-11-18T18:23:54.474114+00:00 | 2016-04-04T12:40:21 | a8503217bb5b32ead44454fcf267fc04ff07e7aa | {
"blob_id": "a8503217bb5b32ead44454fcf267fc04ff07e7aa",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-04T12:40:21",
"content_id": "a56a156c2dba6d75e6ce20f3667c611158325bd7",
"detected_licenses": [
"MIT"
],
"directory_id": "c6369125c44dbdcf0aa74f7f378327279141afae",
"extension": "c",
"filename": "usbi2c_gpio_read.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 55048712,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 433,
"license": "MIT",
"license_type": "permissive",
"path": "/src/usbi2c_gpio_read.c",
"provenance": "stackv2-0003.json.gz:400864",
"repo_name": "macareux-labs/libusbi2c",
"revision_date": "2016-04-04T12:40:21",
"revision_id": "88c96927b8867c09055abf7a154ea953f1ec67f7",
"snapshot_id": "f2ce539f27ab1221d87df6ef4dbc993de4c86051",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/macareux-labs/libusbi2c/88c96927b8867c09055abf7a154ea953f1ec67f7/src/usbi2c_gpio_read.c",
"visit_date": "2021-01-10T07:45:05.858948"
} | stackv2 | #include <stdio.h>
#include "usbi2c/usbi2c.h"
uint8_t usbi2c_gpio_read ( int usb_handle ) {
unsigned char msg[2] = { 'I', 'P' } ;
if ( usbi2c_raw_write( usb_handle, msg, 2 ) != 2 ) {
fprintf(stderr,"[usbi2c_read_gpio] Error : could not write\n") ;
return 0x00 ;
}
if ( usbi2c_raw_read( usb_handle, msg, 1 ) != 1) {
fprintf(stderr,"[usbi2c_read_gpio] Error : could not read\n") ;
return 0x00 ;
}
return msg[0] ;
}
| 2.375 | 2 |
2024-11-18T18:23:55.156014+00:00 | 2018-04-13T21:37:57 | 5a32b1a81ad617063b976192b162119a2629c5a6 | {
"blob_id": "5a32b1a81ad617063b976192b162119a2629c5a6",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-13T21:37:57",
"content_id": "b6c40aebeff044163c12bc52abe949a7f75c319f",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "be55cc27c60107adbc2ee3f4c6f297d16cb9c2a1",
"extension": "h",
"filename": "socHACKi_debug_macros.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 111345349,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 746,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/C/socHACKi_debug_macros.h",
"provenance": "stackv2-0003.json.gz:401382",
"repo_name": "jsochacki/CoDec_Development",
"revision_date": "2018-04-13T21:37:57",
"revision_id": "a918b235a53eef2d30c0c42dd5bee2238c90b824",
"snapshot_id": "b466b3248ca9b6610a90134e6176781c7a5fbcb6",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/jsochacki/CoDec_Development/a918b235a53eef2d30c0c42dd5bee2238c90b824/C/socHACKi_debug_macros.h",
"visit_date": "2021-09-12T02:33:20.084350"
} | stackv2 | /******************************************************************************/
#ifndef SOCHACKI_DM
#define SOCHACKI_DM
/******************************************************************************/
#include <stdio.h>
#include <math.h>
#include <complex.h>
#define DISPLAYV(x) printf("The variable value is %d \n", (int)x);
#define DISPLAYF(x) printf("The variable value is %f \n", (float)x);
#define DISPLAYD(x) printf("The variable value is %d \n", (double)x);
#define DISPLAYCOMPLEXV(value) printf("%lf + %lfi\n", creal(value), cimag(value));
#define DISPLAY2V(x,y) printf("The variable values are %d and %d \n", (int)x, (int)y);
#define DISPLAYS(x) printf("%s", x);
#define DISPLAYNL printf("\n");
#endif // SOCHACKI_FSP
| 2.1875 | 2 |
2024-11-18T18:23:55.979028+00:00 | 2012-08-09T07:47:01 | 1272055ce38085d125b87f7efc070ebd4455d66d | {
"blob_id": "1272055ce38085d125b87f7efc070ebd4455d66d",
"branch_name": "refs/heads/master",
"committer_date": "2012-08-09T07:47:01",
"content_id": "b7eeaed684ce8e15301ddc8283ae874254bb1878",
"detected_licenses": [
"MIT"
],
"directory_id": "6b6e19cb8b0ae8ec47cdadd2d7ba53c52e06d769",
"extension": "c",
"filename": "Travel.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 5338004,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1505,
"license": "MIT",
"license_type": "permissive",
"path": "/CIS2520/A4/Travel.c",
"provenance": "stackv2-0003.json.gz:401767",
"repo_name": "Bananattack/uoguelph",
"revision_date": "2012-08-09T07:47:01",
"revision_id": "a5c46718ac15a5738eb58a0d75147f928df1dde2",
"snapshot_id": "b0b5a69a7b1ec267017685a9c13a5fdabcc889e3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Bananattack/uoguelph/a5c46718ac15a5738eb58a0d75147f928df1dde2/CIS2520/A4/Travel.c",
"visit_date": "2021-01-01T19:00:43.738084"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include "adt/Graph.h"
#include "adt/List.h"
#include "adt/String.h"
#define BUFFER_SIZE 81
int main()
{
Graph* travelGraph;
FILE* f;
char buffer[BUFFER_SIZE];
char* name;
char* name2;
List* path;
printf("Please enter the file to read from: ");
fgets(buffer, BUFFER_SIZE, stdin);
buffer[strlen(buffer) - 1] = '\0';
f = fopen(buffer, "r");
if(f)
{
travelGraph = GraphRead(f);
if(!travelGraph)
{
printf("Fatal error: Problem occurred when reading '%s'!\n", buffer);
return -1;
}
GraphWrite(travelGraph, stdout);
printf("Name of source airport: ");
fgets(buffer, BUFFER_SIZE, stdin);
name = StringNew(buffer);
name[strlen(name) - 1] = '\0';
printf("Name of destination airport: ");
fgets(buffer, BUFFER_SIZE, stdin);
name2 = StringNew(buffer);
name2[strlen(name2) - 1] = '\0';
path = GraphFindShortestPath(travelGraph, name, name2);
if(path && listHead(path))
{
printf("Route found:\n");
do
{
printf("%s\n", VertexGetName((Vertex*) listGetCurrent(path)) );
} while(listNext(path));
printf("\n");
listDelete(path);
}
else
{
printf("No route found between '%s' and '%s'! (make sure you spelled the airports correctly, and the airports are connected in both directions (if directed graph file))\n", name, name2);
}
StringFree(name);
StringFree(name2);
GraphFree(travelGraph);
}
else
{
printf("Fatal error: Can't read file '%s'!\n", buffer);
}
fclose(f);
return 0;
}
| 2.921875 | 3 |
2024-11-18T18:23:56.539487+00:00 | 2018-03-07T18:49:41 | 5dc7972f80242fe322978a699623bb7dc215cc77 | {
"blob_id": "5dc7972f80242fe322978a699623bb7dc215cc77",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-07T18:49:41",
"content_id": "5105127ff1b47f8c156edc51e252fa2cfe657866",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7ce60e9b000775a8a61843c18edc8dc50d44616b",
"extension": "c",
"filename": "text_values.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 130692135,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11808,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/seabolt/src/bolt/values/text_values.c",
"provenance": "stackv2-0003.json.gz:402151",
"repo_name": "lutovich/seabolt",
"revision_date": "2018-03-07T18:49:41",
"revision_id": "1444a9038e2930658f1e04b83a0c5817654511b0",
"snapshot_id": "a2f03f29e994b24e1342d2967dbbad0fbc4dc071",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lutovich/seabolt/1444a9038e2930658f1e04b83a0c5817654511b0/seabolt/src/bolt/values/text_values.c",
"visit_date": "2020-03-12T15:31:03.196522"
} | stackv2 | /*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* 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 <assert.h>
#include <stdint.h>
#include <string.h>
#include "bolt/mem.h"
#include "bolt/values.h"
#define CHAR_ARRAY_QUOTE '\''
#define STRING_QUOTE '"'
#define CODE_POINT_OPEN_BRACKET '{'
#define CODE_POINT_CLOSE_BRACKET '}'
#define REPLACEMENT_CHARACTER "\xFF\xFD"
#define IS_PRINTABLE_ASCII(ch) ((ch) >= ' ' && (ch) <= '~')
void write_string(FILE * file, const char * data, size_t size)
{
fputc(STRING_QUOTE, file);
for (size_t i = 0; i < size; i++)
{
fputc(data[i], file);
}
fputc(STRING_QUOTE, file);
}
void write_code_point(FILE * file, const uint32_t ch)
{
if (ch < 0x10000)
{
fprintf(file, "U+%c%c%c%c", hex3(&ch, 0), hex2(&ch, 0), hex1(&ch, 0), hex0(&ch, 0));
}
else if (ch < 0x100000)
{
fprintf(file, "U+%c%c%c%c%c", hex4(&ch, 0), hex3(&ch, 0), hex2(&ch, 0), hex1(&ch, 0), hex0(&ch, 0));
}
else if (ch < 0x1000000)
{
fprintf(file, "U+%c%c%c%c%c%c", hex5(&ch, 0), hex4(&ch, 0), hex3(&ch, 0), hex2(&ch, 0), hex1(&ch, 0), hex0(&ch, 0));
}
else
{
fprintf(file, REPLACEMENT_CHARACTER);
}
}
void write_bracketed_code_point(FILE * file, const uint32_t ch)
{
fputc(CODE_POINT_OPEN_BRACKET, file);
write_code_point(file, ch);
fputc(CODE_POINT_CLOSE_BRACKET, file);
}
void BoltValue_to_Char(struct BoltValue * value, uint32_t data)
{
_format(value, BOLT_CHAR, 0, 1, NULL, 0);
value->data.as_uint32[0] = data;
}
uint32_t BoltChar_get(const struct BoltValue * value)
{
return value->data.as_uint32[0];
}
void BoltValue_to_String(struct BoltValue * value, const char * data, int32_t length)
{
size_t data_size = length >= 0 ? sizeof(char) * length : 0;
if (length <= sizeof(value->data) / sizeof(char))
{
// If the string is short, it can fit entirely within the
// BoltValue instance
_format(value, BOLT_STRING, 0, length, NULL, 0);
if (data != NULL)
{
memcpy(value->data.as_char, data, (size_t)(length));
}
}
else if (BoltValue_type(value) == BOLT_STRING)
{
// This is already a UTF-8 string so we can just tweak the value
value->data.extended.as_ptr = BoltMem_adjust(value->data.extended.as_ptr, value->data_size, data_size);
value->data_size = data_size;
value->size = length;
if (data != NULL)
{
memcpy(value->data.extended.as_char, data, data_size);
}
}
else
{
// If all else fails, allocate some new external data space
_format(value, BOLT_STRING, 0, length, data, data_size);
}
}
void BoltValue_to_CharArray(struct BoltValue * value, const uint32_t * data, int32_t length)
{
size_t data_size = length >= 0 ? sizeof(uint32_t) * length : 0;
if (length <= sizeof(value->data) / sizeof(uint32_t))
{
_format(value, BOLT_CHAR_ARRAY, 0, length, NULL, 0);
if (data != NULL)
{
memcpy(value->data.as_uint32, data, data_size);
}
}
else if (BoltValue_type(value) == BOLT_CHAR_ARRAY)
{
value->data.extended.as_ptr = BoltMem_adjust(value->data.extended.as_ptr, value->data_size, data_size);
value->data_size = data_size;
value->size = length;
if (data != NULL)
{
memcpy(value->data.extended.as_uint32, data, data_size);
}
}
else
{
// If all else fails, allocate some new external data space
_format(value, BOLT_CHAR_ARRAY, 0, length, data, data_size);
}
}
void BoltValue_to_StringArray(struct BoltValue * value, int32_t length)
{
_format(value, BOLT_STRING_ARRAY, 0, length, NULL, sizeof_n(struct array_t, length));
for (int i = 0; i < length; i++)
{
value->data.extended.as_array[i].size = 0;
value->data.extended.as_array[i].data.as_ptr = NULL;
}
}
void BoltValue_to_Dictionary(struct BoltValue * value, int32_t length)
{
if (value->type == BOLT_DICTIONARY)
{
_resize(value, length, 2);
}
else
{
size_t unit_size = sizeof(struct BoltValue);
size_t data_size = 2 * unit_size * length;
_recycle(value);
value->data.extended.as_ptr = BoltMem_adjust(value->data.extended.as_ptr, value->data_size, data_size);
value->data_size = data_size;
memset(value->data.extended.as_char, 0, data_size);
_set_type(value, BOLT_DICTIONARY, 0, length);
}
}
char * BoltString_get(struct BoltValue * value)
{
return value->size <= sizeof(value->data) / sizeof(char) ?
value->data.as_char : value->data.extended.as_char;
}
uint32_t * BoltCharArray_get(struct BoltValue * value)
{
return value->size <= sizeof(value->data) / sizeof(uint32_t) ?
value->data.as_uint32 : value->data.extended.as_uint32;
}
char* BoltStringArray_get(struct BoltValue * value, int32_t index)
{
struct array_t string = value->data.extended.as_array[index];
return string.size == 0 ? NULL : string.data.as_char;
}
int32_t BoltStringArray_get_size(struct BoltValue * value, int32_t index)
{
return value->data.extended.as_array[index].size;
}
void BoltStringArray_put(struct BoltValue * value, int32_t index, const char * string, int32_t size)
{
struct array_t* s = &value->data.extended.as_array[index];
s->data.as_ptr = BoltMem_adjust(s->data.as_ptr, (size_t)(s->size), (size_t)(size));
s->size = size;
if (size > 0)
{
memcpy(s->data.as_ptr, string, (size_t)(size));
}
}
struct BoltValue* BoltDictionary_key(struct BoltValue * value, int32_t index)
{
assert(BoltValue_type(value) == BOLT_DICTIONARY);
return &value->data.extended.as_value[2 * index];
}
const char * BoltDictionary_get_key(struct BoltValue * value, int32_t index)
{
assert(BoltValue_type(value) == BOLT_DICTIONARY);
struct BoltValue * key_value = &value->data.extended.as_value[2 * index];
assert(BoltValue_type(key_value) == BOLT_STRING);
return BoltString_get(key_value);
}
int32_t BoltDictionary_get_key_size(struct BoltValue * value, int32_t index)
{
assert(BoltValue_type(value) == BOLT_DICTIONARY);
struct BoltValue * key_value = &value->data.extended.as_value[2 * index];
assert(BoltValue_type(key_value) == BOLT_STRING);
return key_value->size;
}
int BoltDictionary_set_key(struct BoltValue * value, int32_t index, const char * key, size_t key_size)
{
if (key_size <= INT32_MAX)
{
assert(BoltValue_type(value) == BOLT_DICTIONARY);
BoltValue_to_String(&value->data.extended.as_value[2 * index], key, key_size);
return 0;
}
else
{
return -1;
}
}
struct BoltValue* BoltDictionary_value(struct BoltValue * value, int32_t index)
{
assert(BoltValue_type(value) == BOLT_DICTIONARY);
return &value->data.extended.as_value[2 * index + 1];
}
int BoltChar_write(const struct BoltValue * value, FILE * file)
{
assert(BoltValue_type(value) == BOLT_CHAR);
write_code_point(file, BoltChar_get(value));
return 0;
}
int BoltCharArray_write(struct BoltValue * value, FILE * file)
{
assert(BoltValue_type(value) == BOLT_CHAR_ARRAY);
uint32_t * chars = BoltCharArray_get(value);
fputc(CHAR_ARRAY_QUOTE, file);
for (int32_t i = 0; i < value->size; i++)
{
uint32_t ch = chars[i];
if (IS_PRINTABLE_ASCII(ch) && ch != CHAR_ARRAY_QUOTE &&
ch != CODE_POINT_OPEN_BRACKET && ch != CODE_POINT_CLOSE_BRACKET)
{
fputc(ch, file);
}
else
{
write_bracketed_code_point(file, ch);
}
}
fputc(CHAR_ARRAY_QUOTE, file);
return 0;
}
int BoltString_write(struct BoltValue * value, FILE * file)
{
assert(BoltValue_type(value) == BOLT_STRING);
char * data = BoltString_get(value);
fputc(STRING_QUOTE, file);
for (int i = 0; i < value->size; i++)
{
char ch0 = data[i];
if (IS_PRINTABLE_ASCII(ch0) && ch0 != STRING_QUOTE &&
ch0 != CODE_POINT_OPEN_BRACKET && ch0 != CODE_POINT_CLOSE_BRACKET)
{
fputc(ch0, file);
}
else if (ch0 >= 0)
{
write_bracketed_code_point(file, (uint32_t)(ch0));
}
else if ((ch0 & 0b11100000) == 0b11000000)
{
if (i + 1 < value->size)
{
char ch1 = data[++i];
uint32_t ch = ((ch0 & (uint32_t)(0b00011111)) << 6) | (ch1 & (uint32_t)(0b00111111));
write_bracketed_code_point(file, ch);
}
else
{
fprintf(file, REPLACEMENT_CHARACTER);
}
}
else if ((ch0 & 0b11110000) == 0b11100000)
{
if (i + 2 < value->size)
{
char ch1 = data[++i];
char ch2 = data[++i];
uint32_t ch = ((ch0 & (uint32_t)(0b00001111)) << 12) | ((ch1 & (uint32_t)(0b00111111)) << 6) | (ch2 & (uint32_t)(0b00111111));
write_bracketed_code_point(file, ch);
}
else
{
fprintf(file, REPLACEMENT_CHARACTER);
}
}
else if ((ch0 & 0b11111000) == 0b11110000)
{
if (i + 3 < value->size)
{
char ch1 = data[++i];
char ch2 = data[++i];
char ch3 = data[++i];
uint32_t ch = ((ch0 & (uint32_t)(0b00000111)) << 18) | ((ch1 & (uint32_t)(0b00111111)) << 12) | ((ch2 & (uint32_t)(0b00111111)) << 6) | (ch3 & (uint32_t)(0b00111111));
write_bracketed_code_point(file, ch);
}
else
{
fprintf(file, REPLACEMENT_CHARACTER);
}
}
else
{
fprintf(file, REPLACEMENT_CHARACTER);
}
}
fputc(STRING_QUOTE, file);
return 0;
}
int BoltStringArray_write(struct BoltValue * value, FILE * file)
{
assert(BoltValue_type(value) == BOLT_STRING_ARRAY);
fprintf(file, "$[");
for (long i = 0; i < value->size; i++)
{
if (i > 0) { fprintf(file, ", "); }
struct array_t string = value->data.extended.as_array[i];
if (string.size == 0)
{
fprintf(file, "\"\"");
}
else
{
write_string(file, string.data.as_char, (size_t)(string.size));
}
}
fprintf(file, "]");
return 0;
}
int BoltDictionary_write(struct BoltValue * value, FILE * file, int32_t protocol_version)
{
assert(BoltValue_type(value) == BOLT_DICTIONARY);
fprintf(file, "{");
int comma = 0;
for (int i = 0; i < value->size; i++)
{
const char * key = BoltDictionary_get_key(value, i);
if (key != NULL)
{
if (comma) fprintf(file, ", ");
write_string(file, key, (size_t)(BoltDictionary_get_key_size(value, i)));
fprintf(file, ": ");
BoltValue_write(BoltDictionary_value(value, i), file, protocol_version);
comma = 1;
}
}
fprintf(file, "}");
return 0;
}
| 2.375 | 2 |
2024-11-18T18:23:56.672541+00:00 | 2017-06-11T16:19:30 | 64b7778a3467ad801934edce3a4f1d6454a49ed6 | {
"blob_id": "64b7778a3467ad801934edce3a4f1d6454a49ed6",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-11T16:19:30",
"content_id": "595e528d2195d0115cca8d5009b61098bca66c2a",
"detected_licenses": [
"MIT"
],
"directory_id": "fa11231f67efd3f57cbbae3bbea3db649d8ac3ae",
"extension": "c",
"filename": "test_calc.c",
"fork_events_count": 6,
"gha_created_at": "2015-04-23T20:13:07",
"gha_event_created_at": "2015-08-26T20:30:47",
"gha_language": "C",
"gha_license_id": null,
"github_id": 34479087,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6164,
"license": "MIT",
"license_type": "permissive",
"path": "/lib_tests/test_calc.c",
"provenance": "stackv2-0003.json.gz:402409",
"repo_name": "MightyPork/avr-lib",
"revision_date": "2017-06-11T16:19:30",
"revision_id": "94bd7b528343c71d2374feb54bc407e316b28e45",
"snapshot_id": "273032a714878efa8292334337642bdb163285ab",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/MightyPork/avr-lib/94bd7b528343c71d2374feb54bc407e316b28e45/lib_tests/test_calc.c",
"visit_date": "2021-01-11T11:10:09.273108"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#include "lib/calc.h"
void main()
{
printf("== calc.h ==\n");
int i;
int a;
printf("fn: inc_wrap()\n");
{
// normal operation
a = 1;
inc_wrap(a, 0, 15);
assert(a == 2);
// overflow
a = 14;
inc_wrap(a, 0, 15);
assert(a == 0);
}
printf("fn: inc_wrapi()\n");
{
// normal operation
a = 1;
inc_wrapi(a, 0, 15);
assert(a == 2);
// not overflow yet
a = 14;
inc_wrapi(a, 0, 15);
assert(a == 15);
// overflow
a = 15;
inc_wrap(a, 0, 15);
assert(a == 0);
}
printf("fn: dec_wrap()\n");
{
// normal operation
a = 5;
dec_wrap(a, 0, 15);
assert(a == 4);
// underflow
a = 0;
dec_wrap(a, 0, 15);
assert(a == 14);
}
printf("fn: dec_wrapi()\n");
{
// normal operation
a = 5;
dec_wrapi(a, 0, 15);
assert(a == 4);
// underflow
a = 0;
dec_wrapi(a, 0, 15);
assert(a == 15);
}
printf("fn: sbi()\n");
{
a = 0;
sbi(a, 2);
assert(a == 0b100);
}
printf("fn: cbi()\n");
{
a = 0b11111;
cbi(a, 2);
assert(a == 0b11011);
}
printf("fn: read_bit()\n");
{
a = 0b101;
assert(read_bit(a, 0) == 1);
assert(read_bit(a, 1) == 0);
assert(read_bit(a, 2) == 1);
}
printf("fn: bit_is_high()\n");
{
a = 0b101;
assert(bit_is_high(a, 0) == 1);
assert(bit_is_high(a, 1) == 0);
assert(bit_is_high(a, 2) == 1);
}
printf("fn: bit_is_low()\n");
{
a = 0b101;
assert(bit_is_low(a, 0) == 0);
assert(bit_is_low(a, 1) == 1);
assert(bit_is_low(a, 2) == 0);
}
printf("fn: toggle_bit()\n");
{
a = 0;
toggle_bit(a, 2);
assert(a == 0b00100);
toggle_bit(a, 4);
assert(a == 0b10100);
toggle_bit(a, 4);
assert(a == 0b00100);
}
// pointer variants
int* b = &a;
printf("fn: sbi_p()\n");
{
*b = 0;
sbi_p(b, 2);
assert(*b == 0b100);
}
printf("fn: cbi_p()\n");
{
*b = 0b11111;
cbi_p(b, 2);
assert(*b == 0b11011);
}
printf("fn: read_bit_p()\n");
{
*b = 0b101;
assert(read_bit_p(b, 0) == 1);
assert(read_bit_p(b, 1) == 0);
assert(read_bit_p(b, 2) == 1);
}
printf("fn: bit_is_high_p()\n");
{
*b = 0b101;
assert(bit_is_high_p(b, 0) == 1);
assert(bit_is_high_p(b, 1) == 0);
assert(bit_is_high_p(b, 2) == 1);
}
printf("fn: bit_is_low_p()\n");
{
*b = 0b101;
assert(bit_is_low_p(b, 0) == 0);
assert(bit_is_low_p(b, 1) == 1);
assert(bit_is_low_p(b, 2) == 0);
}
printf("fn: toggle_bit_p()\n");
{
*b = 0;
toggle_bit_p(b, 2);
assert(*b == 0b00100);
toggle_bit_p(b, 4);
assert(*b == 0b10100);
toggle_bit_p(b, 4);
assert(*b == 0b00100);
}
// -- nibbles --
printf("fn: write_low_nibble()\n");
{
a = 0xAC;
write_low_nibble(a, 0x5); // shifted 4 left
assert(a == 0xA5);
a = 0xAB;
write_low_nibble(a, 0x65); // shifted 4 left, extra ignored
assert(a == 0xA5);
}
printf("fn: write_high_nibble()\n");
{
a = 0xAC;
write_high_nibble(a, 0x5); // shifted 4 left
assert(a == 0x5C);
a = 0xAB;
write_high_nibble(a, 0x65); // shifted 4 left, extra ignored
assert(a == 0x5B);
}
printf("fn: write_low_nibble_p()\n");
{
*b = 0xAC;
write_low_nibble_p(b, 0x5); // shifted 4 left
assert(*b == 0xA5);
*b = 0xAB;
write_low_nibble_p(b, 0x65); // shifted 4 left, extra ignored
assert(*b == 0xA5);
}
printf("fn: write_high_nibble_p()\n");
{
*b = 0xAC;
write_high_nibble_p(b, 0x5); // shifted 4 left
assert(*b == 0x5C);
*b = 0xAB;
write_high_nibble_p(b, 0x65); // shifted 4 left, extra ignored
assert(*b == 0x5B);
}
printf("fn: in_range()\n");
{
// regular
assert(in_range(10, 10, 15));
assert(in_range(14, 10, 15));
assert(in_range(13, 10, 15));
// under
assert(!in_range(9, 10, 15));
assert(!in_range(0, 10, 15));
// above
assert(!in_range(15, 10, 15));
assert(!in_range(99, 10, 15));
// swapped bounds
// regular
assert(in_range(10, 15, 10));
assert(in_range(14, 15, 10));
assert(in_range(13, 15, 10));
// under
assert(!in_range(9, 15, 10));
assert(!in_range(0, 15, 10));
// above
assert(!in_range(15, 15, 10));
assert(!in_range(99, 15, 10));
}
printf("fn: in_rangei()\n");
{
// regular
assert(in_rangei(10, 10, 15));
assert(in_rangei(15, 10, 15));
assert(in_rangei(13, 10, 15));
// under
assert(!in_rangei(9, 10, 15));
assert(!in_rangei(0, 10, 15));
// above
assert(!in_rangei(16, 10, 15));
assert(!in_rangei(99, 10, 15));
// -- swapped bounds --
// regular
assert(in_rangei(10, 15, 10));
assert(in_rangei(15, 15, 10));
assert(in_rangei(13, 15, 10));
// under
assert(!in_rangei(9, 15, 10));
assert(!in_rangei(0, 15, 10));
// above
assert(!in_rangei(16, 15, 10));
assert(!in_rangei(99, 15, 10));
}
printf("fn: in_range_wrap()\n");
{
// as regular range
// regular
assert(in_range_wrap(10, 10, 15));
assert(in_range_wrap(14, 10, 15));
assert(in_range_wrap(13, 10, 15));
// under
assert(!in_range_wrap(9, 10, 15));
assert(!in_range_wrap(0, 10, 15));
// above
assert(!in_range_wrap(15, 10, 15));
assert(!in_range_wrap(16, 10, 15));
assert(!in_range_wrap(99, 10, 15));
// with wrap (>= 15, < 10)
// regular
assert(!in_range_wrap(10, 15, 10));
assert(!in_range_wrap(14, 15, 10));
assert(!in_range_wrap(13, 15, 10));
// under
assert(in_range_wrap(9, 15, 10));
assert(in_range_wrap(0, 15, 10));
// above
assert(in_range_wrap(16, 15, 10));
assert(in_range_wrap(99, 15, 10));
}
printf("fn: in_range_wrapi()\n");
{
// as regular range
// regular
assert(in_range_wrapi(10, 10, 15));
assert(in_range_wrapi(15, 10, 15));
assert(in_range_wrapi(13, 10, 15));
// under
assert(!in_range_wrapi(9, 10, 15));
assert(!in_range_wrapi(0, 10, 15));
// above
assert(!in_range_wrapi(16, 10, 15));
assert(!in_range_wrapi(99, 10, 15));
// with wrap (>= 15, < 10)
// regular
assert(in_range_wrapi(10, 15, 10));
assert(!in_range_wrapi(14, 15, 10));
assert(!in_range_wrapi(13, 15, 10));
// under
assert(in_range_wrapi(10, 15, 10));
assert(in_range_wrapi(0, 15, 10));
// above
assert(in_range_wrapi(16, 15, 10));
assert(in_range_wrapi(99, 15, 10));
}
printf("== PASSED ==\n");
}
| 2.6875 | 3 |
2024-11-18T18:23:56.732539+00:00 | 2021-07-07T08:56:01 | 1659fc12f06d1910965c3e2c892cdc4bdb75ff85 | {
"blob_id": "1659fc12f06d1910965c3e2c892cdc4bdb75ff85",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-07T08:56:01",
"content_id": "9662c7d1db32860a81d1b2dbeb7efefe8f2d5902",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "98062227c8498a3052c72ab6350743581f73ca7c",
"extension": "c",
"filename": "util.c",
"fork_events_count": 3,
"gha_created_at": "2020-08-24T12:03:28",
"gha_event_created_at": "2021-07-07T08:56:02",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 289916105,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2060,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/h3lib/util.c",
"provenance": "stackv2-0003.json.gz:402539",
"repo_name": "CARV-ICS-FORTH/H3",
"revision_date": "2021-07-07T08:56:01",
"revision_id": "af23aececf1c3fdcc6f2d5cfdc31cef9add4033b",
"snapshot_id": "ec364f2193a9137f1c4bc572b691690daf215072",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/CARV-ICS-FORTH/H3/af23aececf1c3fdcc6f2d5cfdc31cef9add4033b/h3lib/util.c",
"visit_date": "2023-06-11T19:37:58.625621"
} | stackv2 | // Copyright [2019] [FORTH-ICS]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include "util.h"
// http://web.theurbanpenguin.com/adding-color-to-your-output-from-c/
static const char* color[] = {"\033[0;33m", // H3_INFO --> Yellow
"\033[0;32m", // H3_DEBUG --> Green
"\033[1;31m", // H3_ERROR --> Red
"" }; // H3_NumberOfLevels
void _LogActivity(H3_MsgLevel level, const char* function, int lineNumber, const char *format, ...) {
char buffer[H3_HEADER_SIZE + H3_MSG_SIZE];
va_list arg;
// Create header
snprintf(buffer, H3_HEADER_SIZE, "%s%s @ %d - ", color[level], function, lineNumber);
// Create message
va_start(arg, format);
vsnprintf(&buffer[strlen(buffer)], H3_MSG_SIZE - 10, format, arg);
va_end(arg);
// Print the message
printf("%s\033[0m", buffer);
}
// res < 0 A < B
// res = 0 A == B
// res > 0 A > B
int64_t Compare(struct timespec* a, struct timespec* b){
if(a->tv_sec == b->tv_sec)
return a->tv_nsec - b->tv_nsec;
return a->tv_sec - b->tv_sec;
}
struct timespec Posterior(struct timespec* a, struct timespec* b){
return Compare(a,b)>0?*a:*b;
}
struct timespec Anterior(struct timespec* a, struct timespec* b){
return Compare(a,b)<0?*a:*b;
}
void* ReAllocFreeOnFail(void* buffer, size_t size){
void* tmp = realloc(buffer, size);
if(!tmp){
free(buffer);
}
return tmp;
}
| 2.484375 | 2 |
2024-11-18T18:23:56.906235+00:00 | 2020-04-23T15:54:03 | b71e23c4905a1368c149f83e0f97b84c0ea8f5f5 | {
"blob_id": "b71e23c4905a1368c149f83e0f97b84c0ea8f5f5",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-23T15:54:03",
"content_id": "b7fcce5b15025744cb297aff18d62caa5381cd24",
"detected_licenses": [
"MIT"
],
"directory_id": "ee790df9ab183aaaad318eb96a7bd6fa6ce07968",
"extension": "c",
"filename": "squirrelActor.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": 7484,
"license": "MIT",
"license_type": "permissive",
"path": "/src/squirrelActor.c",
"provenance": "stackv2-0003.json.gz:402667",
"repo_name": "raynium/SquirlSim",
"revision_date": "2020-04-23T15:54:03",
"revision_id": "c33aecb47d760d44e3dcc4173b42cde04b8f0916",
"snapshot_id": "22787697e898c9248e810e9dbe1224a2a93a12a5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/raynium/SquirlSim/c33aecb47d760d44e3dcc4173b42cde04b8f0916/src/squirrelActor.c",
"visit_date": "2023-07-12T16:16:07.462979"
} | stackv2 | //
// Created by Ray on 2020/4/7.
//
#include <stdio.h>
#include <mpi.h>
#include "../include/squirrelActor.h"
#include "../include/squirrel-functions.h"
#include "../include/framework.h"
#include "../include/config.h"
#include "../include/actorConfig.h"
static long seed;
int cellWorkers[LENGTH_OF_LAND];
int controllerWorkerPid;
int rank;
float x;
float y;
int state; // 0: does not exist; 1: healthy; 2: sick;
int steps; // The total number of steps
int sickSteps; // The steps after being sick
int pop[LAST_POPULATION_STEPS]; // Last 50 population level
int inf[LAST_INFECTION_STEPS]; // Last 50 infection level
MPI_Status status;
int count;
int position;
int recvBuffer[2];
/** ========= The functions blow from actor framework, they will be called in framework.c ========= **/
int squirrelAsk(int workerPid);
int initialiseSquirrel();
int squirrelWorker();
/** ========= The functions blow belong to this actor ========= **/
int squirlGo();
void reproduce();
float get_avg_inf_level();
float get_avg_pop();
/**
* @brief The function for worker asking message from the master.
* @param[in] workerPid
* The workers' pids.
*
*/
int squirrelAsk(int workerPid){
int SquirlState;
if (sickCount < INITIAL_INFECTION_LEVEL){
SquirlState = SICK;
sickCount++;
} else {
SquirlState = HEALTHY;
}
MPI_Send(&SquirlState, 1, MPI_INT, workerPid, INITIAL_TAG, MPI_COMM_WORLD);
// Tell Squirrels who is controller
MPI_Send(&controllers[0], 1, MPI_INT, workerPid, INITIAL_TAG, MPI_COMM_WORLD);
// Tell Squirrels who are land actors
MPI_Send(cellWorkers, LENGTH_OF_LAND, MPI_INT, workerPid, INITIAL_TAG, MPI_COMM_WORLD);
return workerPid;
}
/**
* @brief The function for worker initialising after recv the message from the master.
*
*/
int initialiseSquirrel(){
int i, parentId;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
seed = -1-rank;
initialiseRNG(&seed);
x = 0;
y = 0;
parentId = getCommandData();
MPI_Probe(parentId, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
if (status.MPI_TAG == 10) { // This means the process was a squirrel but dead. Now restart it.
// This is a redundant identity, will be covered
MPI_Recv(&state, 1, MPI_INT, parentId, IDENTITY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
MPI_Recv(&state, 1, MPI_INT, parentId, INITIAL_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&controllerWorkerPid, 1, MPI_INT, parentId, INITIAL_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&cellWorkers, LENGTH_OF_LAND, MPI_INT, parentId, INITIAL_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
if (parentId == 0) { // This means the squirrel is created by master, therefore, the x and y are randomised
squirrelStep(x, y, &x, &y, &seed);
} else { // This means the squirrel is birthed by a existed squirrel, therefore, inherit parent's x and y
float coord[2];
MPI_Recv(&coord, 2, MPI_FLOAT, parentId, INITIAL_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
x = coord[0];
y = coord[1];
}
steps = 0;
sickSteps = 0;
for (i=0; i<LAST_POPULATION_STEPS; i++)
pop[i] = 0;
for (i=0; i<LAST_INFECTION_STEPS; i++)
inf[i] = 0;
return 0;
}
/**
* @brief The actor work code.
*
*/
int squirrelWorker(){
while (state != NOT_EXIST && state != TERMINATE){
squirlGo();
if (state == NOT_EXIST){
// Tell controller I am dead.
MPI_Send(&state, 1, MPI_INT, controllerWorkerPid, SQUIRREL_CONTROLLER_TAG, MPI_COMM_WORLD);
} else if (state == CATCH_DISEASE) {
// Tell controller I am sick.
MPI_Send(&state, 1, MPI_INT, controllerWorkerPid, SQUIRREL_CONTROLLER_TAG, MPI_COMM_WORLD);
state = SICK;
} else if (state == TERMINATE) {
MPI_Send(&state, 1, MPI_INT, controllerWorkerPid, SQUIRREL_CONTROLLER_TAG, MPI_COMM_WORLD);
}
}
return 0;
}
/**
* @brief The squirrel move and try to catch disease, reproduce and die.
*
*/
int squirlGo() {
squirrelStep(x, y, &x, &y, &seed);
position = getCellFromPosition(x, y);
// Send squirrel state to Land Actor
MPI_Send(&state, 1, MPI_INT, cellWorkers[position], LAND_RECV_TAG, MPI_COMM_WORLD);
// Recv the population and infection level at this position
MPI_Probe(cellWorkers[position], SQUIRREL_RECV_TAG, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_INT, &count);
if (count == 0) {
// Terminate signal, the squirrel should stop
MPI_Recv(NULL, 0, MPI_INT, cellWorkers[position], SQUIRREL_RECV_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
state = TERMINATE;
return 0;
} else {
// The squirrel can proceed
MPI_Recv(recvBuffer, 2, MPI_INT, cellWorkers[position], SQUIRREL_RECV_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// Update population and infection level
pop[steps % LAST_POPULATION_STEPS] = recvBuffer[0];
inf[steps % LAST_INFECTION_STEPS] = recvBuffer[1];
steps++;
if (state == SICK)
sickSteps++;
// The squirrel will catches disease
if (steps > CATCH_DISEASE_STEPS && state == HEALTHY && willCatchDisease(get_avg_inf_level(), &seed))
state = CATCH_DISEASE;
// The squirrel will give birth
if (steps % GIVE_BIRTH_STEPS == 0 && willGiveBirth(get_avg_pop(), &seed))
reproduce();
// The squirrel will die
if (sickSteps > 50 && willDie(&seed))
state = NOT_EXIST;
return 1;
}
}
/**
* @brief The squirrel reproduce need to enquiry the controller, if the
* controller permit then the squirrel can give birth
*
*/
void reproduce(){
/* Create a new process and squirrel */
int childPid, childState, identity;
childState = BORN;
// Enquiry controller whether I can give birth
MPI_Send(&childState, 1, MPI_INT, controllerWorkerPid, SQUIRREL_CONTROLLER_TAG, MPI_COMM_WORLD);
MPI_Recv(&childState, 1, MPI_INT, controllerWorkerPid, SQUIRREL_CONTROLLER_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// If it does not recv the BORN signal, it means the number of squirrels out of limit.
if (childState == HEALTHY) {
childPid = startWorkerProcess();
identity = SQUIRREL_ACTOR;
float coord[2];
coord[0] = x;
coord[1] = y;
MPI_Send(&identity, 1, MPI_INT, childPid, IDENTITY_TAG, MPI_COMM_WORLD);
MPI_Send(&childState, 1, MPI_INT, childPid, INITIAL_TAG, MPI_COMM_WORLD);
// Tell baby squirrel who is controller
MPI_Send(&controllerWorkerPid, 1, MPI_INT, childPid, INITIAL_TAG, MPI_COMM_WORLD);
// Tell baby squirrel who are land actors
MPI_Send(&cellWorkers, LENGTH_OF_LAND, MPI_INT, childPid, INITIAL_TAG, MPI_COMM_WORLD);
MPI_Send(coord, 2, MPI_FLOAT, childPid, INITIAL_TAG, MPI_COMM_WORLD);
}
}
/**
* @brief Get the average infection level
*
*/
float get_avg_inf_level(){
int i;
float avg_inf_level;
avg_inf_level = 0.0;
for (i = 0; i < LAST_INFECTION_STEPS; i++)
avg_inf_level += inf[i];
avg_inf_level /= LAST_INFECTION_STEPS;
return avg_inf_level;
}
/**
* @brief Get the average population influx
*
*/
float get_avg_pop(){
int i;
float avg_pop;
avg_pop = 0.0;
for (i=0; i<LAST_POPULATION_STEPS; i++)
avg_pop += pop[i];
avg_pop /= LAST_POPULATION_STEPS;
return avg_pop;
}
| 2.40625 | 2 |
2024-11-18T18:23:57.002925+00:00 | 2022-08-10T04:24:32 | d69dcc5f3518b272f32afe0918f16d45d931b6c0 | {
"blob_id": "d69dcc5f3518b272f32afe0918f16d45d931b6c0",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-09T00:21:36",
"content_id": "479ce463485dd79990b8e901a29f468dee2d85e8",
"detected_licenses": [
"MIT"
],
"directory_id": "3448fd9bb9c0e6b3b3d2899c028fdefc8870bf15",
"extension": "c",
"filename": "neon.c",
"fork_events_count": 2,
"gha_created_at": "2014-08-08T19:59:17",
"gha_event_created_at": "2023-08-09T00:21:37",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 22769864,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 49534,
"license": "MIT",
"license_type": "permissive",
"path": "/rtl/c/neon.c",
"provenance": "stackv2-0003.json.gz:402796",
"repo_name": "ghewgill/neon-lang",
"revision_date": "2022-08-10T04:24:32",
"revision_id": "4e47db02111fcb057c69c96bb31bf93e50f2a06a",
"snapshot_id": "83a8ed8fa7232ee1e066665fd5d594f80150802d",
"src_encoding": "UTF-8",
"star_events_count": 79,
"url": "https://raw.githubusercontent.com/ghewgill/neon-lang/4e47db02111fcb057c69c96bb31bf93e50f2a06a/rtl/c/neon.c",
"visit_date": "2023-08-19T12:12:14.649588"
} | stackv2 | #include "neon.h"
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef _WIN32
#else
#include <dirent.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#endif
const MethodTable Ne_Boolean_mtable = {
.constructor = (void (*)(void **))Ne_Boolean_constructor,
.destructor = (void (*)(void *))Ne_Boolean_destructor,
.copy = (void (*)(void *, const void *))Ne_Boolean_copy,
.compare = (int (*)(const void *, const void *))Ne_Boolean_compare,
};
const MethodTable Ne_Number_mtable = {
.constructor = (void (*)(void **))Ne_Number_constructor,
.destructor = (void (*)(void *))Ne_Number_destructor,
.copy = (void (*)(void *, const void *))Ne_Number_copy,
.compare = (int (*)(const void *, const void *))Ne_Number_compare,
};
const MethodTable Ne_String_mtable = {
.constructor = (void (*)(void **))Ne_String_constructor,
.destructor = (void (*)(void *))Ne_String_destructor,
.copy = (void (*)(void *, const void *))Ne_String_copy,
.compare = (int (*)(const void *, const void *))Ne_String_compare,
};
const MethodTable Ne_Object_mtable = {
.constructor = (void (*)(void **))Ne_Object_constructor,
.destructor = (void (*)(void *))Ne_Object_destructor,
.copy = (void (*)(void *, const void *))Ne_Object_copy,
.compare = (int (*)(const void *, const void *))Ne_Object_compare,
};
static Ne_Exception Ne_Exception_current;
static const char *Ne_String_null_terminate(const Ne_String *s)
{
// Remove 'const' qualifier.
Ne_String *t = (Ne_String *)s;
t->ptr = realloc(t->ptr, t->len + 1);
t->ptr[t->len] = 0;
// Return normal 'char *' instead of 'unsigned char *'.
return (const char *)t->ptr;
}
void Ne_Boolean_init(Ne_Boolean *bool)
{
*bool = 0;
}
void Ne_Boolean_constructor(Ne_Boolean **bool)
{
*bool = malloc(sizeof(Ne_Boolean));
Ne_Boolean_init(*bool);
}
void Ne_Boolean_destructor(Ne_Boolean *bool)
{
free(bool);
}
void Ne_Boolean_init_copy(Ne_Boolean *dest, const Ne_Boolean *src)
{
*dest = *src;
}
void Ne_Boolean_copy(Ne_Boolean *dest, const Ne_Boolean *src)
{
*dest = *src;
}
void Ne_Boolean_deinit(Ne_Boolean *bool)
{
}
int Ne_Boolean_compare(const Ne_Boolean *a, const Ne_Boolean *b)
{
return *a == *b ? 0 : 1;
}
Ne_Exception *Ne_builtin_boolean__toString(Ne_String *result, const Ne_Boolean *a)
{
Ne_String_init_literal(result, *a ? "TRUE" : "FALSE");
return NULL;
}
void Ne_Number_init(Ne_Number *num)
{
num->dval = 0;
}
void Ne_Number_init_copy(Ne_Number *dest, const Ne_Number *src)
{
dest->dval = src->dval;
}
void Ne_Number_copy(Ne_Number *dest, const Ne_Number *src)
{
dest->dval = src->dval;
}
void Ne_Number_init_literal(Ne_Number *num, double n)
{
num->dval = n;
}
void Ne_Number_constructor(Ne_Number **num)
{
*num = malloc(sizeof(Ne_Number));
Ne_Number_init_literal(*num, 0);
}
void Ne_Number_destructor(Ne_Number *num)
{
free(num);
}
void Ne_Number_deinit(Ne_Number *num)
{
}
int Ne_Number_compare(const Ne_Number *a, const Ne_Number *b)
{
return a->dval == b->dval ? 0 : a->dval > b->dval ? 1 : -1;
}
void Ne_String_init(Ne_String *str)
{
str->ptr = NULL;
str->len = 0;
}
void Ne_String_init_literal(Ne_String *str, const char *s)
{
size_t len = strlen(s);
str->ptr = malloc(len);
memcpy(str->ptr, s, len);
str->len = len;
}
void Ne_String_constructor(Ne_String **str)
{
*str = malloc(sizeof(Ne_String));
Ne_String_init(*str);
}
void Ne_String_destructor(Ne_String *str)
{
Ne_String_deinit(str);
free(str);
}
void Ne_String_init_copy(Ne_String *dest, const Ne_String *src)
{
dest->ptr = malloc(src->len);
memcpy(dest->ptr, src->ptr, src->len);
dest->len = src->len;
}
void Ne_String_copy(Ne_String *dest, const Ne_String *src)
{
Ne_String_deinit(dest);
Ne_String_init_copy(dest, src);
}
void Ne_String_deinit(Ne_String *str)
{
free(str->ptr);
}
int Ne_String_compare(const Ne_String *a, const Ne_String *b)
{
int i = 0;
while (i < a->len && i < b->len) {
if (a->ptr[i] < b->ptr[i]) {
return -1;
} else if (a->ptr[i] > b->ptr[i]) {
return 1;
}
i++;
}
if (i < a->len && i >= b->len) {
return 1;
} else if (i >= a->len && i < b->len) {
return -1;
}
return 0;
}
Ne_Exception *Ne_String_index(Ne_String *dest, const Ne_String *s, const Ne_Number *index)
{
if (index->dval != trunc(index->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "String index not an integer: %g", index->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
int i = (int)index->dval;
if (i < 0) {
char buf[100];
snprintf(buf, sizeof(buf), "String index is negative: %d", i);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (i >= s->len) {
char buf[100];
snprintf(buf, sizeof(buf), "String index exceeds length %d: %d", s->len, i);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
dest->ptr = malloc(1);
*dest->ptr = s->ptr[i];
dest->len = 1;
return NULL;
}
Ne_Exception *Ne_String_range(Ne_String *dest, const Ne_String *s, const Ne_Number *first, Ne_Boolean first_from_end, const Ne_Number *last, Ne_Boolean last_from_end)
{
dest->len = 0;
dest->ptr = NULL;
if (first->dval != trunc(first->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "First index not an integer: %g", first->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (last->dval != trunc(last->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "Last index not an integer: %g", last->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
int f = (int)first->dval;
int l = (int)last->dval;
if (first_from_end) {
f += s->len - 1;
}
if (last_from_end) {
l += s->len - 1;
}
if (l < 0 || f >= s->len || f > l) {
return NULL;
}
if (f < 0) {
f = 0;
}
if (l >= s->len) {
l = s->len - 1;
}
dest->len = l - f + 1;
dest->ptr = malloc(dest->len);
memcpy(dest->ptr, s->ptr + f, dest->len);
return NULL;
}
Ne_Exception *Ne_String_splice(Ne_String *d, const Ne_String *t, const Ne_Number *first, Ne_Boolean first_from_end, const Ne_Number *last, Ne_Boolean last_from_end)
{
if (first->dval != trunc(first->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "First index not an integer: %g", first->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (last->dval != trunc(last->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "Last index not an integer: %g", last->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
int f = (int)first->dval;
int l = (int)last->dval;
if (first_from_end) {
f += d->len - 1;
}
if (last_from_end) {
l += d->len - 1;
}
if (f < 0) {
char buf[100];
snprintf(buf, sizeof(buf), "First index is negative: %d", f);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (l < f-1) {
char buf[100];
snprintf(buf, sizeof(buf), "Last index is less than first %d: %d", f, l);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
int new_len = d->len - (f < d->len ? (l < d->len ? l - f + 1 : d->len - f) : 0) + t->len;
int padding = 0;
if (f > d->len) {
padding = f - d->len;
new_len += padding;
}
if (new_len > d->len) {
d->ptr = realloc(d->ptr, new_len);
}
memmove(&d->ptr[f + padding + t->len], &d->ptr[l + 1], (l < d->len ? d->len - l - 1 : 0));
memset(&d->ptr[d->len], ' ', padding);
memcpy(&d->ptr[f], t->ptr, t->len);
if (new_len < d->len) {
d->ptr = realloc(d->ptr, new_len);
}
d->len = new_len;
return NULL;
}
Ne_Exception *Ne_Number_add(Ne_Number *result, const Ne_Number *a, const Ne_Number *b)
{
result->dval = a->dval + b->dval;
return NULL;
}
Ne_Exception *Ne_Number_subtract(Ne_Number *result, const Ne_Number *a, const Ne_Number *b)
{
result->dval = a->dval - b->dval;
return NULL;
}
Ne_Exception *Ne_Number_multiply(Ne_Number *result, const Ne_Number *a, const Ne_Number *b)
{
result->dval = a->dval * b->dval;
return NULL;
}
Ne_Exception *Ne_Number_divide(Ne_Number *result, const Ne_Number *a, const Ne_Number *b)
{
if (b->dval == 0) {
return Ne_Exception_raise_info_literal("PANIC", "Number divide by zero error: divide");
}
result->dval = a->dval / b->dval;
return NULL;
}
Ne_Exception *Ne_Number_pow(Ne_Number *result, const Ne_Number *a, const Ne_Number *b)
{
result->dval = pow(a->dval, b->dval);
return NULL;
}
Ne_Exception *Ne_Number_mod(Ne_Number *result, const Ne_Number *a, const Ne_Number *b)
{
result->dval = (int)a->dval % (int)b->dval;
return NULL;
}
Ne_Exception *Ne_Number_negate(Ne_Number *result, const Ne_Number *a)
{
result->dval = -a->dval;
return NULL;
}
Ne_Exception *Ne_Number_increment(Ne_Number *a, int delta)
{
a->dval += delta;
return NULL;
}
Ne_String *string_copy(const Ne_String *src)
{
Ne_String *r = malloc(sizeof(Ne_String));
r->ptr = malloc(src->len);
memcpy(r->ptr, src->ptr, src->len);
r->len = src->len;
return r;
}
void Ne_Bytes_init(Ne_Bytes *bytes)
{
bytes->data = NULL;
bytes->len = 0;
}
void Ne_Bytes_init_literal(Ne_Bytes *bytes, const unsigned char *data, int len)
{
bytes->data = malloc(len);
if (data != NULL) {
memcpy(bytes->data, data, len);
}
bytes->len = len;
}
void Ne_Bytes_deinit(Ne_Bytes *bytes)
{
free(bytes->data);
}
void Ne_Bytes_copy(Ne_Bytes *dest, const Ne_Bytes *src)
{
free(dest->data);
dest->data = malloc(src->len);
memcpy(dest->data, src->data, src->len);
dest->len = src->len;
}
int Ne_Bytes_compare(const Ne_Bytes *a, const Ne_Bytes *b)
{
int i = 0;
while (i < a->len && i <= b->len) {
if (a->data[i] < b->data[i]) {
return -1;
} else if (a->data[i] > b->data[i]) {
return 1;
}
i++;
}
if (i < a->len && i >= b->len) {
return 1;
} else if (i >= a->len && i < b->len) {
return -1;
}
return 0;
}
Ne_Exception *Ne_Bytes_index(Ne_Number *dest, const Ne_Bytes *b, const Ne_Number *index)
{
if (index->dval != trunc(index->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "Bytes index not an integer: %g", index->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
int i = (int)index->dval;
if (i < 0) {
char buf[100];
snprintf(buf, sizeof(buf), "Bytes index is negative: %d", i);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (i >= b->len) {
char buf[100];
snprintf(buf, sizeof(buf), "Bytes index exceeds size %d: %d", b->len, i);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
dest->dval = b->data[i];
return NULL;
}
Ne_Exception *Ne_Bytes_range(Ne_Bytes *dest, const Ne_Bytes *b, const Ne_Number *first, Ne_Boolean first_from_end, const Ne_Number *last, Ne_Boolean last_from_end)
{
dest->len = 0;
dest->data = NULL;
if (first->dval != trunc(first->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "First index not an integer: %g", first->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (last->dval != trunc(last->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "Last index not an integer: %g", last->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
int f = (int)first->dval;
int l = (int)last->dval;
if (first_from_end) {
f += b->len - 1;
}
if (last_from_end) {
l += b->len - 1;
}
if (l < 0 || f >= b->len || f > l) {
return NULL;
}
if (f < 0) {
f = 0;
}
if (l >= b->len) {
l = b->len - 1;
}
dest->len = l - f + 1;
dest->data = malloc(dest->len);
memcpy(dest->data, b->data + f, dest->len);
return NULL;
}
Ne_Exception *Ne_Bytes_splice(const Ne_Bytes *src, Ne_Bytes *b, const Ne_Number *first, Ne_Boolean first_from_end, const Ne_Number *last, Ne_Boolean last_from_end)
{
if (first->dval != trunc(first->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "First index not an integer: %g", first->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (last->dval != trunc(last->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "Last index not an integer: %g", last->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
int f = (int)first->dval;
int l = (int)last->dval;
if (first_from_end) {
f += b->len - 1;
}
if (last_from_end) {
l += b->len - 1;
}
if (f < 0) {
char buf[100];
snprintf(buf, sizeof(buf), "First index is negative: %d", f);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (l < f-1) {
char buf[100];
snprintf(buf, sizeof(buf), "Last index is before first %d: %d", f, l);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
int new_len = b->len - (f < b->len ? (l < b->len ? l - f + 1 : b->len - f) : 0) + src->len;
int padding = 0;
if (f > b->len) {
padding = f - b->len;
new_len += padding;
}
if (new_len > b->len) {
b->data = realloc(b->data, new_len);
}
memmove(&b->data[f + padding + src->len], &b->data[l + 1], (l < b->len ? b->len - l - 1 : 0));
memset(&b->data[b->len], 0, padding);
memcpy(&b->data[f], src->data, src->len);
if (new_len < b->len) {
b->data = realloc(b->data, new_len);
}
b->len = new_len;
return NULL;
}
Ne_Exception *Ne_Bytes_store(const Ne_Number *b, Ne_Bytes *s, const Ne_Number *index)
{
if (index->dval != trunc(index->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "Bytes index not an integer: %g", index->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
int i = (int)index->dval;
if (i < 0) {
char buf[100];
snprintf(buf, sizeof(buf), "Bytes index is negative: %d", i);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (i >= s->len) {
char buf[100];
snprintf(buf, sizeof(buf), "Bytes index exceeds size %d: %d", s->len, i);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
s->data[i] = (unsigned char)b->dval;
return NULL;
}
Ne_Exception *Ne_builtin_bytes__append(Ne_Bytes *r, const Ne_Bytes *b)
{
r->data = realloc(r->data, r->len + b->len);
memcpy(&r->data[r->len], b->data, b->len);
r->len += b->len;
return NULL;
}
Ne_Exception *Ne_builtin_bytes__concat(Ne_Bytes *r, const Ne_Bytes *a, const Ne_Bytes *b)
{
r->data = malloc(a->len + b->len);
memcpy(r->data, a->data, a->len);
memcpy(r->data + a->len, b->data, b->len);
r->len = a->len + b->len;
return NULL;
}
Ne_Exception *Ne_global_Bytes__decodeUTF8(Ne_String *r, const Ne_Bytes *bytes)
{
r->ptr = malloc(bytes->len);
memcpy(r->ptr, bytes->data, bytes->len);
r->len = bytes->len;
return NULL;
}
Ne_Exception *Ne_builtin_bytes__size(Ne_Number *r, const Ne_Bytes *bytes)
{
r->dval = bytes->len;
return NULL;
}
Ne_Exception *Ne_builtin_bytes__toArray(Ne_Array *result, const Ne_Bytes *bytes)
{
Ne_Array_init(result, bytes->len, &Ne_Number_mtable);
for (int i = 0; i < bytes->len; i++) {
Ne_Number *p;
Ne_Array_index_int((void **)&p, result, i, 0);
// TODO: Copy the number right into the array instead of using a temporary.
Ne_Number n;
Ne_Number_init_literal(&n, bytes->data[i]);
Ne_Number_copy(p, &n);
Ne_Number_deinit(&n);
}
return NULL;
}
Ne_Exception *Ne_builtin_bytes__toString(Ne_String *result, const Ne_Bytes *bytes)
{
char *buf = malloc(8 + 1 + 1 + 3*bytes->len + 1 + 1);
strcpy(buf, "HEXBYTES \"");
char *p = buf + strlen(buf);
for (int i = 0; i < bytes->len; i++) {
if (i > 0) {
*p++ = ' ';
}
p += sprintf(p, "%02x", bytes->data[i]);
}
*p++ = '"';
*p = 0;
Ne_String_init_literal(result, buf);
free(buf);
return NULL;
}
void Ne_Array_init(Ne_Array *a, int size, const MethodTable *mtable)
{
a->size = size;
a->a = malloc(size * sizeof(void *));
a->mtable = mtable;
for (int i = 0; i < size; i++) {
mtable->constructor(&a->a[i]);
}
}
void Ne_Array_init_copy(Ne_Array *dest, const Ne_Array *src)
{
dest->size = src->size;
dest->a = malloc(dest->size * sizeof(void *));
dest->mtable = src->mtable;
for (int i = 0; i < dest->size; i++) {
dest->mtable->constructor(&dest->a[i]);
dest->mtable->copy(dest->a[i], src->a[i]);
}
}
void Ne_Object_constructor(Ne_Object **obj)
{
*obj = malloc(sizeof(Ne_Object));
Ne_Object_init(*obj);
}
void Ne_Object_init(Ne_Object *obj)
{
obj->type = neNothing;
Ne_Number_init_literal(&obj->num, 0);
Ne_String_init(&obj->str);
}
void Ne_Object_copy(Ne_Object *dest, const Ne_Object *src)
{
Ne_Object_deinit(dest);
dest->type = src->type;
switch (dest->type) {
case neNothing:
break;
case neBoolean:
Ne_Boolean_init_copy(&dest->boo, &src->boo);
break;
case neNumber:
Ne_Number_init_copy(&dest->num, &src->num);
break;
case neString:
Ne_String_init_copy(&dest->str, &src->str);
break;
}
}
void Ne_Object_destructor(Ne_Object *obj)
{
Ne_Object_deinit(obj);
free(obj);
}
void Ne_Object_deinit(Ne_Object *obj)
{
switch (obj->type) {
case neNothing:
break;
case neBoolean:
Ne_Boolean_deinit(&obj->boo);
break;
case neNumber:
Ne_Number_deinit(&obj->num);
break;
case neString:
Ne_String_deinit(&obj->str);
break;
}
obj->type = neNothing;
}
int Ne_Object_compare(const Ne_Object *a, const Ne_Object *b)
{
return a == b ? 0 : 1;
}
Ne_Exception *Ne_builtin_object__getBoolean(Ne_Boolean *r, Ne_Object *obj)
{
if (obj->type != neBoolean) {
return Ne_Exception_raise("DynamicConversionException");
}
Ne_Boolean_init_copy(r, &obj->boo);
return NULL;
}
Ne_Exception *Ne_builtin_object__getNumber(Ne_Number *r, Ne_Object *obj)
{
if (obj->type != neNumber) {
return Ne_Exception_raise("DynamicConversionException");
}
Ne_Number_init_copy(r, &obj->num);
return NULL;
}
Ne_Exception *Ne_builtin_object__getString(Ne_String *r, Ne_Object *obj)
{
if (obj->type != neString) {
return Ne_Exception_raise("DynamicConversionException");
}
Ne_String_init_copy(r, &obj->str);
return NULL;
}
Ne_Exception *Ne_builtin_object__isNull(Ne_Boolean *r, Ne_Object *obj)
{
*r = obj->type == neNothing;
return NULL;
}
Ne_Exception *Ne_builtin_object__makeNull(Ne_Object *obj)
{
Ne_Object_init(obj);
obj->type = neNothing;
return NULL;
}
Ne_Exception *Ne_builtin_object__makeBoolean(Ne_Object *obj, const Ne_Boolean *b)
{
Ne_Object_init(obj);
obj->type = neBoolean;
Ne_Boolean_copy(&obj->boo, b);
return NULL;
}
Ne_Exception *Ne_builtin_object__makeNumber(Ne_Object *obj, const Ne_Number *n)
{
Ne_Object_init(obj);
obj->type = neNumber;
Ne_Number_copy(&obj->num, n);
return NULL;
}
Ne_Exception *Ne_builtin_object__makeString(Ne_Object *obj, const Ne_String *s)
{
Ne_Object_init(obj);
obj->type = neString;
Ne_String_copy(&obj->str, s);
return NULL;
}
Ne_Exception *Ne_builtin_object__toString(Ne_String *result, const Ne_Object *obj)
{
switch (obj->type) {
case neNothing:
Ne_String_init_literal(result, "NIL");
break;
case neNumber: {
char buf[40];
snprintf(buf, sizeof(buf), "%g", obj->num.dval);
Ne_String_init_literal(result, buf);
break;
}
case neString:
Ne_String_init_copy(result, &obj->str);
break;
default: {
char buf[40];
snprintf(buf, sizeof(buf), "[unknown object type %d]", obj->type);
Ne_String_init_literal(result, buf);
break;
}
}
return NULL;
}
void Ne_Array_copy(Ne_Array *dest, const Ne_Array *src)
{
Ne_Array_deinit(dest);
dest->a = malloc(src->size * sizeof(void *));
assert(src->mtable == NULL || src->mtable == dest->mtable);
for (int i = 0; i < src->size; i++) {
dest->mtable->constructor(&dest->a[i]);
dest->mtable->copy(dest->a[i], src->a[i]);
}
dest->size = src->size;
}
void Ne_Array_deinit(Ne_Array *a)
{
for (int i = 0; i < a->size; i++) {
a->mtable->destructor(a->a[i]);
}
free(a->a);
}
int Ne_Array_compare(const Ne_Array *a, const Ne_Array *b)
{
int i = 0;
while (i < a->size && i <= b->size) {
int r = a->mtable->compare(a->a[i], b->a[i]);
if (r != 0) {
return r;
}
i++;
}
if (i < a->size && i >= b->size) {
return 1;
} else if (i >= a->size && i < b->size) {
return -1;
}
return 0;
}
Ne_Exception *Ne_Array_in(Ne_Boolean *result, const Ne_Array *a, void *element)
{
*result = 0;
for (int i = 0; i < a->size; i++) {
if (a->mtable->compare(a->a[i], element) == 0) {
*result = 1;
return NULL;
}
}
return NULL;
}
Ne_Exception *Ne_Array_index_int(void **result, Ne_Array *a, int index, Ne_Boolean always_create)
{
if (index >= a->size) {
if (always_create) {
a->a = realloc(a->a, (index+1) * sizeof(void *));
for (int j = a->size; j < index+1; j++) {
a->mtable->constructor(&a->a[j]);
}
a->size = index+1;
} else {
char buf[100];
snprintf(buf, sizeof(buf), "Array index exceeds size %d: %d", a->size, index);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
}
*result = a->a[index];
return NULL;
}
Ne_Exception *Ne_Array_index(void **result, Ne_Array *a, const Ne_Number *index, Ne_Boolean always_create)
{
if (index->dval != trunc(index->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "Array index not an integer: %g", index->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (index->dval < 0) {
char buf[100];
snprintf(buf, sizeof(buf), "Array index is negative: %g", index->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
return Ne_Array_index_int(result, a, (int)index->dval, always_create);
}
Ne_Exception *Ne_Array_range(Ne_Array *result, const Ne_Array *a, const Ne_Number *first, Ne_Boolean first_from_end, const Ne_Number *last, Ne_Boolean last_from_end)
{
result->size = 0;
result->a = NULL;
result->mtable = a->mtable;
if (first->dval != trunc(first->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "First index not an integer: %g", first->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (last->dval != trunc(last->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "Last index not an integer: %g", last->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
int f = (int)first->dval;
int l = (int)last->dval;
if (first_from_end) {
f += a->size - 1;
}
if (last_from_end) {
l += a->size - 1;
}
if (l < 0 || f >= a->size || f > l) {
return NULL;
}
if (f < 0) {
f = 0;
}
if (l >= a->size) {
l = a->size - 1;
}
result->size = l - f + 1;
result->a = malloc(result->size * sizeof(struct KV));
for (int i = 0; i < result->size; i++) {
result->mtable->constructor(&result->a[i]);
result->mtable->copy(result->a[i], a->a[f+i]);
}
return NULL;
}
Ne_Exception *Ne_Array_splice(const Ne_Array *b, Ne_Array *a, const Ne_Number *first, Ne_Boolean first_from_end, const Ne_Number *last, Ne_Boolean last_from_end)
{
if (first->dval != trunc(first->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "First index not an integer: %g", first->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (last->dval != trunc(last->dval)) {
char buf[100];
snprintf(buf, sizeof(buf), "Last index not an integer: %g", last->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
int f = (int)first->dval;
int l = (int)last->dval;
if (first_from_end) {
f += a->size - 1;
}
if (last_from_end) {
l += a->size - 1;
}
if (l < -1 || f >= a->size || f > l+1) {
return NULL;
}
if (f < 0) {
f = 0;
}
if (l >= a->size) {
l = a->size - 1;
}
int new_size = a->size - (l - f + 1) + b->size;
for (int i = f; i <= l; i++) {
a->mtable->destructor(a->a[i]);
}
a->a = realloc(a->a, new_size * sizeof(void *));
memmove(&a->a[f + b->size], &a->a[l + 1], (a->size - l - 1) * sizeof(void *));
for (int i = 0; i < b->size; i++) {
a->mtable->constructor(&a->a[f + i]);
a->mtable->copy(a->a[f + i], b->a[i]);
}
a->size = new_size;
return NULL;
}
Ne_Exception *Ne_builtin_array__append(Ne_Array *a, const void *element)
{
a->a = realloc(a->a, (a->size+1) * sizeof(void *));
a->mtable->constructor(&a->a[a->size]);
a->mtable->copy(a->a[a->size], element);
a->size++;
return NULL;
}
Ne_Exception *Ne_builtin_array__concat(Ne_Array *dest, const Ne_Array *a, const Ne_Array *b)
{
dest->size = a->size + b->size;
dest->a = malloc(dest->size * sizeof(void *));
dest->mtable = a->mtable;
for (int i = 0; i < a->size; i++) {
dest->mtable->constructor(&dest->a[i]);
dest->mtable->copy(dest->a[i], a->a[i]);
}
for (int i = 0; i < b->size; i++) {
dest->mtable->constructor(&dest->a[a->size+i]);
dest->mtable->copy(dest->a[a->size+i], b->a[i]);
}
return NULL;
}
Ne_Exception *Ne_builtin_array__extend(Ne_Array *dest, const Ne_Array *src)
{
int newsize = dest->size + src->size;
dest->a = realloc(dest->a, newsize * sizeof(void *));
for (int i = 0; i < src->size; i++) {
dest->mtable->constructor(&dest->a[dest->size+i]);
dest->mtable->copy(dest->a[dest->size+i], src->a[i]);
}
dest->size = newsize;
return NULL;
}
Ne_Exception *Ne_builtin_array__find(Ne_Number *result, const Ne_Array *a, void *e)
{
for (int i = 0; i < a->size; i++) {
if (a->mtable->compare(a->a[i], e) == 0) {
Ne_Number_init_literal(result, i);
return NULL;
}
}
return Ne_Exception_raise_info_literal("PANIC", "value not found in array");
}
Ne_Exception *Ne_builtin_array__remove(Ne_Array *a, const Ne_Number *index)
{
int i = (int)index->dval;
if (i < 0) {
char buf[100];
snprintf(buf, sizeof(buf), "Array index is negative: %g", index->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (i >= a->size) {
char buf[100];
snprintf(buf, sizeof(buf), "Array index exceeds size %d: %g", a->size, index->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
a->mtable->destructor(a->a[i]);
memmove(&a->a[i], &a->a[i+1], (a->size-i-1) * sizeof(void *));
a->size--;
return NULL;
}
Ne_Exception *Ne_builtin_array__resize(Ne_Array *a, const Ne_Number *size)
{
int newsize = (int)size->dval;
if (newsize != size->dval) {
char buf[100];
snprintf(buf, sizeof(buf), "Invalid array size: %g", size->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (newsize < a->size) {
for (int i = newsize; i < a->size; i++) {
a->mtable->destructor(a->a[i]);
}
a->a = realloc(a->a, newsize * sizeof(void *));
} else {
a->a = realloc(a->a, newsize * sizeof(void *));
for (int i = a->size; i < newsize; i++) {
a->mtable->constructor(&a->a[i]);
}
}
a->size = newsize;
return NULL;
}
Ne_Exception *Ne_builtin_array__reversed(Ne_Array *dest, const Ne_Array *src)
{
Ne_Array_init(dest, src->size, src->mtable);
for (int i = 0; i < src->size; i++) {
dest->mtable->copy(dest->a[i], src->a[src->size-1-i]);
}
return NULL;
}
Ne_Exception *Ne_builtin_array__size(Ne_Number *result, const Ne_Array *a)
{
Ne_Number_init_literal(result, a->size);
return NULL;
}
Ne_Exception *Ne_builtin_array__toBytes__number(Ne_Bytes *r, const Ne_Array *a)
{
r->data = malloc(a->size);
for (int i = 0; i < a->size; i++) {
double val = ((Ne_Number *)a->a[i])->dval;
if (val >= 0 && val <= 255 && val == trunc(val)) {
r->data[i] = (int)val;
} else {
free(r->data);
char msg[100];
snprintf(msg, sizeof(msg), "Byte value out of range at offset %d: %g", i, val);
return Ne_Exception_raise_info_literal("PANIC", msg);
}
}
r->len = a->size;
return NULL;
}
Ne_Exception *Ne_builtin_array__toString__number(Ne_String *r, const Ne_Array *a)
{
char buf[100];
strcpy(buf, "[");
for (int i = 0; i < a->size; i++) {
if (i > 0) {
strcat(buf, ", ");
}
Ne_Number *n = a->a[i];
snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%g", n->dval);
}
strcat(buf, "]");
Ne_String_init_literal(r, buf);
return NULL;
}
Ne_Exception *Ne_builtin_array__toString__string(Ne_String *r, const Ne_Array *a)
{
char buf[100];
strcpy(buf, "[");
for (int i = 0; i < a->size; i++) {
if (i > 0) {
strcat(buf, ", ");
}
Ne_String *s = a->a[i];
snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\"%.*s\"", s->len, s->ptr);
}
strcat(buf, "]");
Ne_String_init_literal(r, buf);
return NULL;
}
void Ne_Dictionary_init(Ne_Dictionary *d, const MethodTable *mtable)
{
d->size = 0;
d->d = NULL;
d->mtable = mtable;
}
void Ne_Dictionary_copy(Ne_Dictionary *dest, const Ne_Dictionary *src)
{
Ne_Dictionary_deinit(dest);
dest->d = malloc(src->size * sizeof(struct KV));
assert(src->mtable == NULL || src->mtable == dest->mtable);
for (int i = 0; i < src->size; i++) {
Ne_String_init_copy(&dest->d[i].key, &src->d[i].key);
dest->mtable->constructor(&dest->d[i].value);
dest->mtable->copy(dest->d[i].value, src->d[i].value);
}
dest->size = src->size;
}
void Ne_Dictionary_deinit(Ne_Dictionary *d)
{
for (int i = 0; i < d->size; i++) {
Ne_String_deinit(&d->d[i].key);
d->mtable->destructor(d->d[i].value);
}
free(d->d);
}
int Ne_Dictionary_compare(const Ne_Dictionary *a, const Ne_Dictionary *b)
{
assert(a->mtable == b->mtable);
if (a->size < b->size) {
return -1;
}
if (a->size > b->size) {
return 1;
}
for (int i = 0; i < a->size; i++) {
int found = 0;
for (int j = 0; j < b->size; j++) {
if (Ne_String_compare(&a->d[i].key, &b->d[j].key) == 0) {
int r = a->mtable->compare(a->d[i].value, b->d[j].value);
if (r != 0) {
return r;
}
found = 1;
break;
}
}
if (!found) {
return 1;
}
}
return 0;
}
static int dictionary_find(const Ne_Dictionary *d, const Ne_String *key, int *index)
{
int lo = 0;
int hi = d->size;
while (lo < hi) {
int m = (lo + hi) / 2;
int c = Ne_String_compare(key, &d->d[m].key);
if (c == 0) {
*index = m;
return 1;
}
if (c < 0) {
hi = m;
} else {
lo = m + 1;
}
}
*index = lo;
return 0;
}
Ne_Exception *Ne_Dictionary_in(Ne_Boolean *result, const Ne_Dictionary *d, const Ne_String *key)
{
int i;
*result = dictionary_find(d, key, &i);
return NULL;
}
Ne_Exception *Ne_Dictionary_index(void **result, Ne_Dictionary *d, const Ne_String *index, Ne_Boolean always_create)
{
int i;
int found = dictionary_find(d, index, &i);
if (found) {
*result = d->d[i].value;
return NULL;
}
if (!always_create) {
char buf[100];
snprintf(buf, sizeof(buf), "Dictionary key not found: %.*s", index->len, index->ptr);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
d->d = realloc(d->d, (d->size+1) * sizeof(struct KV));
memmove(&d->d[i+1], &d->d[i], (d->size-i) * sizeof(struct KV));
d->size++;
Ne_String_init_copy(&d->d[i].key, index);
d->mtable->constructor(&d->d[i].value);
*result = d->d[i].value;
return NULL;
}
Ne_Exception *Ne_builtin_dictionary__keys(Ne_Array *result, const Ne_Dictionary *d)
{
Ne_Array_init(result, d->size, &Ne_String_mtable);
for (int i = 0; i < d->size; i++) {
Ne_String *s;
Ne_Array_index_int((void **)&s, result, i, 0);
Ne_String_copy(s, &d->d[i].key);
}
return NULL;
}
Ne_Exception *Ne_builtin_dictionary__remove(Ne_Dictionary *d, const Ne_String *key)
{
int i;
int found = dictionary_find(d, key, &i);
if (found) {
Ne_String_deinit(&d->d[i].key);
d->mtable->destructor(d->d[i].value);
memmove(&d->d[i], &d->d[i+1], (d->size-i-1) * sizeof(struct KV));
d->size--;
return NULL;
}
return NULL;
}
Ne_Exception *Ne_builtin_dictionary__toString__string(Ne_String *r, const Ne_Dictionary *d)
{
char buf[1000];
strcpy(buf, "{");
for (int i = 0; i < d->size; i++) {
if (i > 0) {
strcat(buf, ", ");
}
snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%.*s", d->d[i].key.len, d->d[i].key.ptr);
strcat(buf, ": ");
Ne_String *s = d->d[i].value;
snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%.*s", s->len, s->ptr);
}
strcat(buf, "}");
Ne_String_init_literal(r, buf);
return NULL;
}
Ne_Exception *Ne_global_num(Ne_Number *result, const Ne_String *s)
{
const char *t = Ne_String_null_terminate(s);
result->dval = atof(t);
return NULL;
}
Ne_Exception *Ne_builtin_number__toString(Ne_String *result, const Ne_Number *n)
{
char buf[20];
snprintf(buf, sizeof(buf), "%g", n->dval);
Ne_String_init_literal(result, buf);
return NULL;
}
Ne_Exception *Ne_builtin_pointer__toString(Ne_String *r, const void *p)
{
char buf[20];
snprintf(buf, sizeof(buf), "%p", p);
Ne_String_init_literal(r, buf);
return NULL;
}
Ne_Exception *Ne_global_print(const Ne_Object *obj)
{
Ne_String s;
if (Ne_builtin_object__toString(&s, obj)) {
return Ne_Exception_propagate();
}
printf("%.*s\n", s.len, s.ptr);
Ne_String_deinit(&s);
return NULL;
}
Ne_Exception *Ne_global_str(Ne_String *result, const Ne_Number *n)
{
char buf[20];
snprintf(buf, sizeof(buf), "%g", n->dval);
Ne_String_init_literal(result, buf);
return NULL;
}
Ne_Exception *Ne_builtin_string__append(Ne_String *dest, const Ne_String *s)
{
dest->ptr = realloc(dest->ptr, dest->len + s->len);
memcpy(dest->ptr + dest->len, s->ptr, s->len);
dest->len += s->len;
return NULL;
}
Ne_Exception *Ne_builtin_string__concat(Ne_String *dest, const Ne_String *a, const Ne_String *b)
{
dest->len = a->len + b->len;
dest->ptr = malloc(dest->len);
memcpy(dest->ptr, a->ptr, a->len);
memcpy(dest->ptr+a->len, b->ptr, b->len);
return NULL;
}
Ne_Exception *Ne_builtin_string__length(Ne_Number *result, const Ne_String *str)
{
result->dval = str->len;
return NULL;
}
Ne_Exception *Ne_builtin_string__encodeUTF8(Ne_Bytes *result, const Ne_String *str)
{
result->data = malloc(str->len);
memcpy(result->data, str->ptr, str->len);
result->len = str->len;
return NULL;
}
Ne_Exception *Ne_Exception_raise(const char *name)
{
Ne_Exception_current.name = name;
Ne_Object_init(&Ne_Exception_current.info);
return &Ne_Exception_current;
}
Ne_Exception *Ne_Exception_raise_info(const char *name, const Ne_Object *info)
{
Ne_Exception_current.name = name;
Ne_Object_copy(&Ne_Exception_current.info, info);
return &Ne_Exception_current;
}
Ne_Exception *Ne_Exception_raise_info_literal(const char *name, const char *info)
{
Ne_Exception_current.name = name;
Ne_String s;
Ne_String_init_literal(&s, info);
Ne_builtin_object__makeString(&Ne_Exception_current.info, &s);
Ne_String_deinit(&s);
return &Ne_Exception_current;
}
void Ne_Exception_clear()
{
Ne_Exception_current.name = NULL;
Ne_Object_deinit(&Ne_Exception_current.info);
}
int Ne_Exception_trap(const char *name)
{
int len = strlen(name);
return strncmp(Ne_Exception_current.name, name, len) == 0 && (Ne_Exception_current.name[len] == 0 || Ne_Exception_current.name[len] == '.');
}
Ne_Exception *Ne_Exception_propagate()
{
return &Ne_Exception_current;
}
void Ne_Exception_unhandled()
{
Ne_String detail;
Ne_builtin_object__toString(&detail, &Ne_Exception_current.info);
fprintf(stderr, "Unhandled exception %s (%.*s)\n", Ne_Exception_current.name, detail.len, detail.ptr);
Ne_Exception_clear();
exit(1);
}
Ne_Exception *Ne_binary_xorBytes(Ne_Bytes *r, Ne_Bytes *x, Ne_Bytes *y)
{
if (x->len != y->len) {
return Ne_Exception_raise_info_literal("PANIC", "Lengths of operands are not the same");
}
Ne_Bytes_init_literal(r, NULL, x->len);
for (int i = 0; i < x->len; i++) {
r->data[i] = x->data[i] ^ y->data[i];
}
return NULL;
}
Ne_Exception *Ne_file__CONSTANT_Separator(Ne_String *result)
{
#ifdef _WIN32
Ne_String_init_literal(result, "\\");
#else
Ne_String_init_literal(result, "/");
#endif
return NULL;
}
Ne_Exception *Ne_file_delete(const Ne_String *filename)
{
#ifdef _WIN32
abort();
#else
remove((const char *)filename->ptr);
#endif
return NULL;
}
Ne_Exception *Ne_file_files(Ne_Array *result, const Ne_String *path)
{
Ne_Array_init(result, 0, &Ne_String_mtable);
#ifdef _WIN32
abort();
#else
DIR *d = opendir((const char *)path->ptr);
if (d != NULL) {
for (;;) {
struct dirent *de = readdir(d);
if (de == NULL) {
break;
}
Ne_String name;
Ne_String_init_literal(&name, de->d_name);
Ne_builtin_array__append(result, &name);
Ne_String_deinit(&name);
}
closedir(d);
}
#endif
return NULL;
}
Ne_Exception *Ne_file_isDirectory(Ne_Boolean *result, const Ne_String *path)
{
Ne_Boolean_init(result);
#ifdef _WIN32
abort();
#else
struct stat st;
*result = stat((const char *)path->ptr, &st) == 0 && S_ISDIR(st.st_mode);
#endif
return NULL;
}
Ne_Exception *Ne_file_readLines(Ne_Array *result, const Ne_String *filename)
{
Ne_Array_init(result, 0, &Ne_String_mtable);
FILE *f = fopen((const char *)filename->ptr, "r");
if (f != NULL) {
// TODO: handle long lines.
char buf[10000];
while (fgets(buf, sizeof(buf), f) != NULL) {
Ne_String s;
Ne_String_init_literal(&s, buf);
Ne_builtin_array__append(result, &s);
Ne_String_deinit(&s);
}
fclose(f);
}
return NULL;
}
Ne_Exception *Ne_file_removeEmptyDirectory(const Ne_String *path)
{
#ifdef _WIN32
abort();
#else
rmdir((const char *)path->ptr);
#endif
return NULL;
}
Ne_Exception *Ne_math__CONSTANT_PRECISION_DIGITS(Ne_Number *result)
{
result->dval = 15;
return NULL;
}
Ne_Exception *Ne_math_abs(Ne_Number *result, const Ne_Number *x)
{
result->dval = fabs(x->dval);
return NULL;
}
Ne_Exception *Ne_math_acos(Ne_Number *result, const Ne_Number *x)
{
result->dval = acos(x->dval);
return NULL;
}
Ne_Exception *Ne_math_acosh(Ne_Number *result, const Ne_Number *x)
{
result->dval = acosh(x->dval);
return NULL;
}
Ne_Exception *Ne_math_asin(Ne_Number *result, const Ne_Number *x)
{
result->dval = asin(x->dval);
return NULL;
}
Ne_Exception *Ne_math_asinh(Ne_Number *result, const Ne_Number *x)
{
result->dval = asinh(x->dval);
return NULL;
}
Ne_Exception *Ne_math_atan(Ne_Number *result, const Ne_Number *x)
{
result->dval = atan(x->dval);
return NULL;
}
Ne_Exception *Ne_math_atanh(Ne_Number *result, const Ne_Number *x)
{
result->dval = atanh(x->dval);
return NULL;
}
Ne_Exception *Ne_math_atan2(Ne_Number *result, const Ne_Number *y, const Ne_Number *x)
{
result->dval = atan2(y->dval, x->dval);
return NULL;
}
Ne_Exception *Ne_math_cbrt(Ne_Number *result, const Ne_Number *x)
{
result->dval = cbrt(x->dval);
return NULL;
}
Ne_Exception *Ne_math_ceil(Ne_Number *result, const Ne_Number *x)
{
result->dval = ceil(x->dval);
return NULL;
}
Ne_Exception *Ne_math_cos(Ne_Number *result, const Ne_Number *x)
{
result->dval = cos(x->dval);
return NULL;
}
Ne_Exception *Ne_math_cosh(Ne_Number *result, const Ne_Number *x)
{
result->dval = cosh(x->dval);
return NULL;
}
Ne_Exception *Ne_math_erf(Ne_Number *result, const Ne_Number *x)
{
result->dval = erf(x->dval);
return NULL;
}
Ne_Exception *Ne_math_erfc(Ne_Number *result, const Ne_Number *x)
{
result->dval = erfc(x->dval);
return NULL;
}
Ne_Exception *Ne_math_exp(Ne_Number *result, const Ne_Number *x)
{
result->dval = exp(x->dval);
return NULL;
}
Ne_Exception *Ne_math_exp2(Ne_Number *result, const Ne_Number *x)
{
result->dval = exp2(x->dval);
return NULL;
}
Ne_Exception *Ne_math_expm1(Ne_Number *result, const Ne_Number *x)
{
result->dval = expm1(x->dval);
return NULL;
}
Ne_Exception *Ne_math_floor(Ne_Number *result, const Ne_Number *x)
{
result->dval = floor(x->dval);
return NULL;
}
Ne_Exception *Ne_math_frexp(Ne_Number *result, const Ne_Number *x, Ne_Number *exp)
{
int iexp;
result->dval = frexp(x->dval, &iexp);
exp->dval = iexp;
return NULL;
}
Ne_Exception *Ne_math_hypot(Ne_Number *result, const Ne_Number *x, const Ne_Number *y)
{
result->dval = hypot(x->dval, y->dval);
return NULL;
}
Ne_Exception *Ne_math_intdiv(Ne_Number *result, const Ne_Number *x, const Ne_Number *y)
{
result->dval = trunc(x->dval / y->dval);
return NULL;
}
Ne_Exception *Ne_math_ldexp(Ne_Number *result, const Ne_Number *x, const Ne_Number *exp)
{
result->dval = ldexp(x->dval, exp->dval);
return NULL;
}
Ne_Exception *Ne_math_lgamma(Ne_Number *result, const Ne_Number *x)
{
result->dval = lgamma(x->dval);
return NULL;
}
Ne_Exception *Ne_math_log(Ne_Number *result, const Ne_Number *x)
{
result->dval = log(x->dval);
return NULL;
}
Ne_Exception *Ne_math_log10(Ne_Number *result, const Ne_Number *x)
{
result->dval = log10(x->dval);
return NULL;
}
Ne_Exception *Ne_math_log1p(Ne_Number *result, const Ne_Number *x)
{
result->dval = log1p(x->dval);
return NULL;
}
Ne_Exception *Ne_math_log2(Ne_Number *result, const Ne_Number *x)
{
result->dval = log2(x->dval);
return NULL;
}
Ne_Exception *Ne_math_max(Ne_Number *result, const Ne_Number *a, const Ne_Number *b)
{
result->dval = a->dval > b->dval ? a->dval : b->dval;
return NULL;
}
Ne_Exception *Ne_math_min(Ne_Number *result, const Ne_Number *a, const Ne_Number *b)
{
result->dval = a->dval < b->dval ? a->dval : b->dval;
return NULL;
}
Ne_Exception *Ne_math_nearbyint(Ne_Number *result, const Ne_Number *x)
{
result->dval = nearbyint(x->dval);
return NULL;
}
Ne_Exception *Ne_math_odd(Ne_Boolean *result, const Ne_Number *x)
{
int i = (int)trunc(x->dval);
if (i != x->dval) {
return Ne_Exception_raise_info_literal("PANIC", "odd() requires integer");
}
*result = (int)trunc(x->dval) & 1;
return NULL;
}
Ne_Exception *Ne_math_powmod(Ne_Number *result, const Ne_Number *b, const Ne_Number *e, const Ne_Number *m)
{
result->dval = (int)pow(b->dval, e->dval) % (int)m->dval;
return NULL;
}
Ne_Exception *Ne_math_round(Ne_Number *result, const Ne_Number *places, const Ne_Number *value)
{
double f = pow(10, places->dval);
result->dval = round(value->dval * f) / f;
return NULL;
}
Ne_Exception *Ne_math_sign(Ne_Number *result, const Ne_Number *x)
{
result->dval = x->dval > 0 ? 1 : x->dval < 0 ? -1 : 0;
return NULL;
}
Ne_Exception *Ne_math_sin(Ne_Number *result, const Ne_Number *x)
{
result->dval = sin(x->dval);
return NULL;
}
Ne_Exception *Ne_math_sinh(Ne_Number *result, const Ne_Number *x)
{
result->dval = sinh(x->dval);
return NULL;
}
Ne_Exception *Ne_math_sqrt(Ne_Number *result, const Ne_Number *x)
{
result->dval = sqrt(x->dval);
return NULL;
}
Ne_Exception *Ne_math_tan(Ne_Number *result, const Ne_Number *x)
{
result->dval = tan(x->dval);
return NULL;
}
Ne_Exception *Ne_math_tanh(Ne_Number *result, const Ne_Number *x)
{
result->dval = tanh(x->dval);
return NULL;
}
Ne_Exception *Ne_math_tgamma(Ne_Number *result, const Ne_Number *x)
{
result->dval = tgamma(x->dval);
return NULL;
}
Ne_Exception *Ne_math_trunc(Ne_Number *result, const Ne_Number *x)
{
result->dval = trunc(x->dval);
return NULL;
}
Ne_Exception *Ne_random_bytes(Ne_Bytes *result, const Ne_Number *n)
{
result->len = (int)n->dval;
result->data = malloc(result->len);
for (int i = 0; i < result->len; i++) {
result->data[i] = (unsigned char)rand();
}
return NULL;
}
Ne_Exception *Ne_random_uint32(Ne_Number *result)
{
result->dval = (uint32_t)rand();
return NULL;
}
Ne_Exception *Ne_runtime_debugEnabled(Ne_Boolean *r)
{
*r = 0;
return NULL;
}
Ne_Exception *Ne_runtime_isModuleImported(Ne_Boolean *r, Ne_String *module)
{
*r = 1;
return NULL;
}
Ne_Exception *Ne_string_find(Ne_Number *result, const Ne_String *s, const Ne_String *t)
{
if (s->len < t->len) {
result->dval = -1;
return NULL;
}
int i = 0;
while (i <= s->len - t->len) {
int j = 0;
while (j < t->len && s->ptr[i] == t->ptr[j]) {
j++;
}
if (j >= t->len) {
result->dval = i;
return NULL;
}
i++;
}
result->dval = -1;
return NULL;
}
Ne_Exception *Ne_string_fromCodePoint(Ne_String *result, const Ne_Number *n)
{
result->ptr = malloc(1);
*result->ptr = (unsigned char)n->dval;
result->len = 1;
return NULL;
}
Ne_Exception *Ne_string_lower(Ne_String *result, const Ne_String *s)
{
result->ptr = malloc(s->len);
for (int i = 0; i < s->len; i++) {
result->ptr[i] = tolower(s->ptr[i]);
}
result->len = s->len;
return NULL;
}
Ne_Exception *Ne_string_toCodePoint(Ne_Number *result, const Ne_String *s)
{
result->dval = s->ptr[0];
return NULL;
}
Ne_Exception *Ne_string_trimCharacters(Ne_String *result, const Ne_String *s, const Ne_String *trimLeadingChars, const Ne_String *trimTrailingChars)
{
Ne_String_init_copy(result, s);
return NULL;
}
Ne_Array sys_x24args;
void Ne_sys__init(int argc, const char *argv[])
{
Ne_Array_init(&sys_x24args, argc, &Ne_String_mtable);
for (int i = 0; i < argc; i++) {
Ne_String s;
Ne_String_init_literal(&s, argv[i]);
Ne_String *x;
Ne_Array_index_int((void **)&x, &sys_x24args, i, 0);
Ne_String_copy(x, &s);
Ne_String_deinit(&s);
}
}
Ne_Exception *Ne_sys_exit(const Ne_Number *n)
{
int i = (int)trunc(n->dval);
if (i != n->dval) {
char buf[50];
snprintf(buf, sizeof(buf), "sys.exit invalid parameter: %g", n->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
if (i < 0 || i > 255) {
char buf[50];
snprintf(buf, sizeof(buf), "sys.exit invalid parameter: %g", n->dval);
return Ne_Exception_raise_info_literal("PANIC", buf);
}
exit(i);
}
void *textio_x24stderr;
Ne_Exception *Ne_textio_writeLine(void *f, const Ne_String *s)
{
fprintf(stderr, "%.*s\n", s->len, s->ptr);
return NULL;
}
Ne_Exception *Ne_time_now(Ne_Number *result)
{
#ifdef _WIN32
result->dval = time(NULL);
#else
struct timeval tv;
gettimeofday(&tv, NULL);
result->dval = tv.tv_sec + tv.tv_usec / 1000000.0;
#endif
return NULL;
}
Ne_Exception *Ne_time_tick(Ne_Number *result)
{
#ifdef _WIN32
result->dval = time(NULL);
#else
struct timeval tv;
gettimeofday(&tv, NULL);
result->dval = tv.tv_sec + tv.tv_usec / 1000000.0;
#endif
return NULL;
}
| 2.625 | 3 |
2024-11-18T18:24:04.858718+00:00 | 2019-10-16T09:54:38 | bb130e5b5b3e2a2a985aac6aefa522de3e479627 | {
"blob_id": "bb130e5b5b3e2a2a985aac6aefa522de3e479627",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-16T09:54:38",
"content_id": "76f41de0bb168dadcc7a38bf5e543b215731b522",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "f2974f1d6323c9fc117f947c85dadc7a3d1b5b04",
"extension": "h",
"filename": "closure.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 202197789,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3508,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/rts/closure.h",
"provenance": "stackv2-0003.json.gz:403441",
"repo_name": "mniip/nanohc",
"revision_date": "2019-10-16T09:54:38",
"revision_id": "162660d7447b370a26b6ad79f816a41a00aa5bd9",
"snapshot_id": "e9e9235f6d1cbac61b6e2a020fd4051cb9e8f143",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mniip/nanohc/162660d7447b370a26b6ad79f816a41a00aa5bd9/rts/closure.h",
"visit_date": "2020-07-04T07:05:08.931860"
} | stackv2 | #ifndef CLOSURE_H_
#define CLOSURE_H_
#include <stddef.h>
enum closure_tag {
CLOSURE_NULL = 0x00,
CLOSURE_PRIM,
CLOSURE_CONSTR,
CLOSURE_THUNK
};
typedef unsigned char variant;
typedef unsigned char gc_data;
typedef unsigned short int arity;
/* A heap-allocated closure, managed by the GC */
typedef struct closure {
char tag;
gc_data gc;
union {
/* tag = CLOSURE_PRIM, an evaluated primitive datatype value
* prim points to an arbitrarily sized allocation owned by the closure
*/
struct {
void *data;
size_t size;
} prim;
/* tag = CLOSURE_CONSTR, an evaluated algebraic datatype value */
struct {
/* Variant of the constructor */
variant var;
/* How many arguments is the constructor missing, if partially
* applied. 0 means it's fully applied.
*/
arity want_arity;
/* A NULL-terminated list of fields of the constructor, allocation
* owned by the closure.
*/
struct closure **fields;
} constr;
/* tag = CLOSURE_THUNK, either a thunk or a lambda */
struct {
/* How many arguments is the thunk missing. 0 means it's a thunk not
* in WHNF. >0 means it's a lambda in WHNF.
*/
arity want_arity;
/* A NULL-terminated list of the values that the closure is closed
* over, allocation owned by the closure.
*/
struct closure **env;
/* Entry "code" */
struct entry *entry;
} thunk;
} u;
} closure;
enum entry_tag {
ENTRY_PRIM = 0x01,
ENTRY_REF,
ENTRY_SELECT,
ENTRY_APPLY,
ENTRY_CASE,
ENTRY_LETREC,
ENTRY_LAM
};
/* A bitmask specifying a subset of the environment to be passed to the child
* entry code.
*/
typedef unsigned char *env_mask;
typedef struct masked_entry {
/* Pointer never shared */
env_mask mask;
struct entry *entry;
} masked_entry;
/* Entry code for a thunk or function, instructions on how to replace the
* closure with an evaluated version of itself. Managed by the GC.
*/
typedef struct entry {
char tag;
gc_data gc;
union {
/* tag = ENTRY_PRIM, apply a primitive function */
int (*prim)(closure *self);
/* tag = ENTRY_REF, refer to another closure */
closure *ref;
/* tag = ENTRY_SELECT, select a closure from the environemnt by index */
arity select_idx;
/* tag = ENTRY_APPLY, apply a function to a thunk */
struct {
/* How to construct the function */
masked_entry fun;
/* How to construct the argument */
masked_entry arg;
} apply;
/* tag = ENTRY_CASE, perform case analysis of expression and return
* one of possible branches.
*/
struct {
/* How to construct the scrutinee */
masked_entry scrutinee;
/* A NULL-terminated list of case branches, as many as as there are
* variants of the matched datatype.
*/
masked_entry *branches;
} caseof;
/* tag = ENTRY_LETREC, add some closures to the environment */
struct {
/* How to construct the body once other closures have been bound */
masked_entry body;
/* A NULL-terminated list of bindings. */
masked_entry *bindings;
} letrec;
/* tag = ENTRY_LAM, a lambda, request an additional argument */
struct {
/* How to construct the body once applied to an argument */
struct entry *body;
} lambda;
} u;
} entry;
/* Deallocate all data in a closure (so that it can be replaced with new data)
*/
extern void erase_closure(closure *);
/* Deallocate all data in an entry */
extern void erase_entry(entry *);
/* Replace all data of one closure by that of another */
extern void copy_closure(closure *dest, closure *src);
#endif
| 2.71875 | 3 |
2024-11-18T18:24:04.933518+00:00 | 2020-06-22T14:47:03 | 5699cc0dcbeb79089d454e7eb8e3eecdd98f6554 | {
"blob_id": "5699cc0dcbeb79089d454e7eb8e3eecdd98f6554",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-22T14:47:03",
"content_id": "9f0365d541ab0cb1cc6b12b1493737d3ba891a70",
"detected_licenses": [
"curl",
"MIT"
],
"directory_id": "47e01d5c0854b886afe16c7b8139cac08ed096ae",
"extension": "c",
"filename": "order.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": 3011,
"license": "curl,MIT",
"license_type": "permissive",
"path": "/oms-sdk/c/model/order.c",
"provenance": "stackv2-0003.json.gz:403571",
"repo_name": "MEDiCODEDEV/coinapi-sdk",
"revision_date": "2020-06-22T14:47:03",
"revision_id": "9b9a8cf07d3ae2a136a8d3c95094176d88bb9e6a",
"snapshot_id": "19baf5cc3b0be538e4689342992c325742afbd58",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MEDiCODEDEV/coinapi-sdk/9b9a8cf07d3ae2a136a8d3c95094176d88bb9e6a/oms-sdk/c/model/order.c",
"visit_date": "2022-11-08T19:52:34.333690"
} | stackv2 | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "order.h"
order_t *order_create(
char *type,
char *exchange_name,
list_t *data
) {
order_t *order_local_var = malloc(sizeof(order_t));
if (!order_local_var) {
return NULL;
}
order_local_var->type = type;
order_local_var->exchange_name = exchange_name;
order_local_var->data = data;
return order_local_var;
}
void order_free(order_t *order) {
if(NULL == order){
return ;
}
listEntry_t *listEntry;
free(order->type);
free(order->exchange_name);
list_ForEach(listEntry, order->data) {
order_data_free(listEntry->data);
}
list_free(order->data);
free(order);
}
cJSON *order_convertToJSON(order_t *order) {
cJSON *item = cJSON_CreateObject();
// order->type
if(order->type) {
if(cJSON_AddStringToObject(item, "type", order->type) == NULL) {
goto fail; //String
}
}
// order->exchange_name
if(order->exchange_name) {
if(cJSON_AddStringToObject(item, "exchange_name", order->exchange_name) == NULL) {
goto fail; //String
}
}
// order->data
if(order->data) {
cJSON *data = cJSON_AddArrayToObject(item, "data");
if(data == NULL) {
goto fail; //nonprimitive container
}
listEntry_t *dataListEntry;
if (order->data) {
list_ForEach(dataListEntry, order->data) {
cJSON *itemLocal = order_data_convertToJSON(dataListEntry->data);
if(itemLocal == NULL) {
goto fail;
}
cJSON_AddItemToArray(data, itemLocal);
}
}
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
order_t *order_parseFromJSON(cJSON *orderJSON){
order_t *order_local_var = NULL;
// order->type
cJSON *type = cJSON_GetObjectItemCaseSensitive(orderJSON, "type");
if (type) {
if(!cJSON_IsString(type))
{
goto end; //String
}
}
// order->exchange_name
cJSON *exchange_name = cJSON_GetObjectItemCaseSensitive(orderJSON, "exchange_name");
if (exchange_name) {
if(!cJSON_IsString(exchange_name))
{
goto end; //String
}
}
// order->data
cJSON *data = cJSON_GetObjectItemCaseSensitive(orderJSON, "data");
list_t *dataList;
if (data) {
cJSON *data_local_nonprimitive;
if(!cJSON_IsArray(data)){
goto end; //nonprimitive container
}
dataList = list_create();
cJSON_ArrayForEach(data_local_nonprimitive,data )
{
if(!cJSON_IsObject(data_local_nonprimitive)){
goto end;
}
order_data_t *dataItem = order_data_parseFromJSON(data_local_nonprimitive);
list_addElement(dataList, dataItem);
}
}
order_local_var = order_create (
type ? strdup(type->valuestring) : NULL,
exchange_name ? strdup(exchange_name->valuestring) : NULL,
data ? dataList : NULL
);
return order_local_var;
end:
return NULL;
}
| 2.71875 | 3 |
2024-11-18T18:24:05.106843+00:00 | 2019-03-15T06:18:52 | 8bcbb05a191ea60cbae8105f019e7835cf2c38b2 | {
"blob_id": "8bcbb05a191ea60cbae8105f019e7835cf2c38b2",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-15T06:18:52",
"content_id": "f4437324582b29b6f12ff9e92e428bcb484a4678",
"detected_licenses": [
"MIT"
],
"directory_id": "90a0676dc1b7a13234caea959a0ed1a788e9d29b",
"extension": "c",
"filename": "prog2.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 162555249,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 300,
"license": "MIT",
"license_type": "permissive",
"path": "/LAB 9/prog2.c",
"provenance": "stackv2-0003.json.gz:403829",
"repo_name": "nikhilnayak98/CSE3041",
"revision_date": "2019-03-15T06:18:52",
"revision_id": "3e4b356e396340ac3743af9e12eb660ae523b9e0",
"snapshot_id": "c7e0688174d5da6956f3417da4905f1f2edb80f8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/nikhilnayak98/CSE3041/3e4b356e396340ac3743af9e12eb660ae523b9e0/LAB 9/prog2.c",
"visit_date": "2020-04-12T14:32:08.804731"
} | stackv2 | /*
*Name: Nikhil Ranjan Nayak
*Regd No: 1641012040
*Desc: print iter, 3 times
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int pid, pid2;
pid = fork();
if(pid)
{
pid2 = fork();
printf("iter\n");
}
else
{
printf("iter\n");
pid2 = fork();
}
return 0;
}
| 2.4375 | 2 |
2024-11-18T18:24:05.175072+00:00 | 2013-01-25T07:41:50 | 4569c32fc42dcb9b69e0f24bae7ab607861d7706 | {
"blob_id": "4569c32fc42dcb9b69e0f24bae7ab607861d7706",
"branch_name": "refs/heads/master",
"committer_date": "2013-01-25T07:41:50",
"content_id": "7c7987399f66bc640f4ad25907d7d9fde07c408e",
"detected_licenses": [
"ISC"
],
"directory_id": "24c3907cce46626a085adae19c81a7346ff5510e",
"extension": "c",
"filename": "Clock.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": 8576,
"license": "ISC",
"license_type": "permissive",
"path": "/Source/Clock.c",
"provenance": "stackv2-0003.json.gz:403958",
"repo_name": "dalalsunil1986/Synergy-OS",
"revision_date": "2013-01-25T07:41:50",
"revision_id": "5af8bac06d2678e311016752005f83589d2d07a8",
"snapshot_id": "d5459c62878f184a416b37b65d0de1725f59906c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dalalsunil1986/Synergy-OS/5af8bac06d2678e311016752005f83589d2d07a8/Source/Clock.c",
"visit_date": "2021-12-15T00:52:22.533777"
} | stackv2 | /*
Clock.c - Time/Date and Timer Functions.
*
* Basically it uses the RTC to load initial data, and then the PIT (or HP-clock) to update that.
*/
#include <portIO.h>
#include <Clock.h>
#include <vgaConsole.h>
#include <memoryManager.h>
#include <interrupts.h>
time_t clock_systemClock;
clock_timerRequest* clock_timerRequestsList = (clock_timerRequest*) 0x00;
int clock_daysPerMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
clock_timerRequest* clock_addOneShotRequest(time_t* requestedTime, void (*funcToCall)(void))
{
clock_timerRequest* request = memoryManager_allocate(sizeof(clock_timerRequest));
request->seconds = requestedTime->seconds;
request->milliSeconds = requestedTime->milliSeconds;
request->funcToCall = funcToCall;
request->isRepeatTimer = 0;
//Add to queue.
//Do magic to try and find where to place this in the list.
if(!clock_timerRequestsList)
{
request->next = (clock_timerRequest*) 0x00;
clock_timerRequestsList = request;
} else {
//Add it to the front of the list. We'll figure out sorting it later.
request->next = clock_timerRequestsList;
clock_timerRequestsList = request;
}
return(request);
}
clock_timerRequest* clock_addRepeatRequest(uint64 secGap, uint16 milGap, void (*funcToCall)(void))
{
clock_timerRequest* request = memoryManager_allocate(sizeof(clock_timerRequest));
request->seconds = clock_systemClock.seconds + secGap;
request->milliSeconds = clock_systemClock.milliSeconds + milGap;
request->funcToCall = funcToCall;
request->isRepeatTimer = 1;
request->repeatSecondsToAdd = secGap;
request->repeatMilliSecondsToAdd = milGap;
//Add to queue.
//Do magic to try and find where to place this in the list.
if(!clock_timerRequestsList)
{
request->next = (clock_timerRequest*) 0x00;
clock_timerRequestsList = request;
} else {
//Add it to the front of the list. We'll figure out sorting it later.
request->next = clock_timerRequestsList;
clock_timerRequestsList = request;
}
vgaConsole_printf("Added repeat timer. \n");
return(request);
}
void clock_deleteTimerRequest(clock_timerRequest* request)
{
clock_timerRequest* current = clock_timerRequestsList;
clock_timerRequest* oldCurrent = 0;
if(current==request)
{ //Deals with head-of-list issues.
clock_timerRequestsList = current->next;
memoryManager_free(current);
current = 0; //So we don't continue on to the next section and try to delete things twice and make a huge mess of the entire system.
}
while(current)
{
//Perform check.
if(current==request)
{
//Remove it from the list.
clock_timerRequest* temp = current;
oldCurrent->next = current->next;
current = oldCurrent->next;
memoryManager_free(temp);
} else {
oldCurrent = current;
current = current->next;
}
}
}
void clock_setHertz(unsigned int Hertz)
{
/*
SYNOPSIS: Sets the divisor of the channel 0 clock.
INPUT: Requested frequency.
OUTPUT: None.
NOTES: None.
*/
int Divisor;
Divisor = 1193180 / Hertz;
writeByte(0x43, 0x36); //Set command byte.
writeByte(0x40, Divisor & 0xFF); //LSB
writeByte(0x40, Divisor >> 8); //MSB
}
/**
* \brief Handles the clock-tick message produced by the programmable interrupt timer (PIT).
*/
void clock_handler_PIC(uint32 arbitraryNumber)
{
arbitraryNumber++; //To stop GCC complaining about unsused variable. Does nothing.
clock_systemClock.milliSeconds++;
if(clock_systemClock.milliSeconds%CLOCK_HERTZ==0)
{
clock_systemClock.seconds++;
clock_systemClock.milliSeconds = 0;
}
//There are a list of things that need to be notified on clockticks... visit them here.
clock_timerRequest* current = clock_timerRequestsList;
clock_timerRequest* oldCurrent = 0;
while(current)
{
//Perform check.
if((current->seconds==clock_systemClock.seconds)&&(current->milliSeconds==clock_systemClock.milliSeconds))
{
//We have a shot!
void (*foo)();
foo = current->funcToCall;
(*foo)(); //Call the function.
//vgaConsole_printf("Shot! %h.%h",current->seconds,current->milliSeconds);
if(current->isRepeatTimer)
{
//Reset to give it another go.
current->seconds = current->seconds + current->repeatSecondsToAdd;
current->milliSeconds = current->milliSeconds + current->repeatMilliSecondsToAdd;
if(current->milliSeconds>=1000)
{
current->seconds++;
current->milliSeconds = current->milliSeconds-1000;
}
oldCurrent = current;
current = current->next;
} else {
//Remove it from the list.
clock_timerRequest* temp = current;
oldCurrent->next = current->next;
current = oldCurrent->next;
memoryManager_free(temp);
}
} else {
oldCurrent = current;
current = current->next;
}
//vgaConsole_printf("list: %h.%h\n",current,oldCurrent);
}
}
void clock_init()
{
clock_setHertz(CLOCK_HERTZ);
clock_systemClock.seconds = 0;
clock_systemClock.milliSeconds = 0;
interrupts_addHandler(0x20,0,(*clock_handler_PIC));
//We now proceed to get an approx. fix on time from the RTC. This will
//be recalculated once we have a better fix from a network time server.
uint8 statusB = clock_getRTCRegister(0x0B);
//Read seconds.
if(statusB & 0x04)
{
clock_systemClock.seconds += clock_getRTCRegister(0x00);
} else {
clock_systemClock.seconds += clock_convertBCDtoNormal(clock_getRTCRegister(0x00));
}
//Read minutes.
if(statusB & 0x04)
{
clock_systemClock.seconds += SECONDS_PER_MINUTE * clock_getRTCRegister(0x02);
} else {
clock_systemClock.seconds += SECONDS_PER_MINUTE * clock_convertBCDtoNormal(clock_getRTCRegister(0x02));
}
//Read hours.
if(statusB & 0x02)
{
//24-hour mode.
if(statusB & 0x04)
{
clock_systemClock.seconds += SECONDS_PER_HOUR * (clock_getRTCRegister(0x04)+(CLOCK_UTC_OFFSET));
} else {
clock_systemClock.seconds += SECONDS_PER_HOUR * (clock_convertBCDtoNormal(clock_getRTCRegister(0x04))+(CLOCK_UTC_OFFSET));
}
} else {
//12-hour mode.
int temp = clock_getRTCRegister(0x04);
int ampm = temp & 0x80;
if(ampm) //Mask the 0x80 bit out.
temp = temp & 0x7F;
if(!(statusB & 0x04))
temp = clock_convertBCDtoNormal(temp);
if(temp == 12)
temp = 0;
if(ampm)
temp = temp + 12;
clock_systemClock.seconds += SECONDS_PER_HOUR * (temp+(CLOCK_UTC_OFFSET));
}
//Read days.
if(statusB & 0x04)
{
clock_systemClock.seconds += SECONDS_PER_DAY * clock_getRTCRegister(0x07);
} else {
clock_systemClock.seconds += SECONDS_PER_DAY * clock_convertBCDtoNormal(clock_getRTCRegister(0x07));
}
//Read months.
int month;
int totaldays = 0;
if(statusB & 0x04)
{
month = clock_getRTCRegister(0x07) - 1; //Comes out of clock as 1-12. We need 0-11.
} else {
month = clock_convertBCDtoNormal(clock_getRTCRegister(0x07)) - 1;
}
//We now need to add up all the other days in the preceeding months.
for(int i =0; i<month;i++)
{
totaldays += clock_daysPerMonth[month];
}
clock_systemClock.seconds += SECONDS_PER_DAY * totaldays;
//Read years. This register gives us number of years since last century (2000) so we can just add straight on.
//We really should check the century, but we don't.
int year;
if(statusB & 0x04)
{
year = clock_getRTCRegister(0x09);
} else {
year = clock_convertBCDtoNormal(clock_getRTCRegister(0x09));
}
clock_systemClock.seconds += SECONDS_PER_YEAR * year;
//Now add in any leap days from feb.
//The Gregorian leap year rules are that if a year is a multiple of 4 then it's a leap year, unless it happens to be a new century and it can't be divided by 400. <-- from OSDev wiki.
int numberOfLeapYearDays = 0;
numberOfLeapYearDays = (year/4)+1; //This works until 2100.
clock_systemClock.seconds += SECONDS_PER_DAY * numberOfLeapYearDays;
}
void clock_shutdown()
{
//Give back time to the RTC for next time.
//TODO.
}
unsigned long clock_uptime()
{
return (clock_systemClock.seconds);
}
uint8 clock_convertBCDtoNormal(uint8 value)
{
value = ((value / 16) * 10) + (value & 0x0F);
return(value);
}
uint8 clock_getRTCRegister(uint8 chosenRegister)
{
uint8 data = 0;
interrupts_disableInterrupts();
writeByte(0x70,chosenRegister);
//DELAY HERE.
data = readByte(0x71);
interrupts_enableInterrupts();
return(data);
}
| 2.984375 | 3 |
2024-11-18T18:24:06.136944+00:00 | 2019-01-15T20:57:37 | 850aa92c8703b26628a161c8b0c29eeb2b517e9b | {
"blob_id": "850aa92c8703b26628a161c8b0c29eeb2b517e9b",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-15T20:57:37",
"content_id": "e0853f2f0d0d29e623021e5f90b620b447eddc98",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "ee1dd0f4b511492a23fe42654df490a02fcfc6c4",
"extension": "c",
"filename": "libresistance.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 165921624,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 812,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/libresistance-0.0/src/libresistance.c",
"provenance": "stackv2-0003.json.gz:404088",
"repo_name": "mercurio1983/debpackage_linum",
"revision_date": "2019-01-15T20:57:37",
"revision_id": "f4165e3426d7d0e1c7700dc9680f20f9e77cf20b",
"snapshot_id": "31149e4b7d04b1cba6b7cf58f5e6b7cfdec82b3c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mercurio1983/debpackage_linum/f4165e3426d7d0e1c7700dc9680f20f9e77cf20b/libresistance-0.0/src/libresistance.c",
"visit_date": "2020-04-16T21:20:18.940112"
} | stackv2 | /*libresistance.c beräkna ersättningsresistansen*/
float calc_resistance(int count, char conn, float *array){
/*kolla nollpekare*/
if(!array){
return -1;
}
float sum=0;
if (conn=='S'){
/*seriel*/
for(int i=0; i<count;i++){
sum+=array[i];
}
}else if(conn=='P'){
/*parallell*/
for (int i=0; i<count; i++){
/*kontrollera så att ingen är noll vid parallell*/
if(array[i]==0)
return -1;
sum+=1/array[i];
}
sum=1/sum;
}else{
/*varken S || P*/
return -1;
}
return sum;
}
| 2.984375 | 3 |
2024-11-18T18:24:06.215597+00:00 | 2021-03-17T15:02:13 | 99a90cc25fad0f78ad6843823ccd21caa3ca19fb | {
"blob_id": "99a90cc25fad0f78ad6843823ccd21caa3ca19fb",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-17T15:02:13",
"content_id": "54a184a16a9700a8b3e66a8c241716d75032cc33",
"detected_licenses": [
"MIT"
],
"directory_id": "4554aaf38b71c3cec6636bf2060d647c86acb945",
"extension": "c",
"filename": "Console.c",
"fork_events_count": 0,
"gha_created_at": "2021-02-28T08:57:01",
"gha_event_created_at": "2021-03-10T01:45:09",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 343060526,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 103,
"license": "MIT",
"license_type": "permissive",
"path": "/Console.c",
"provenance": "stackv2-0003.json.gz:404217",
"repo_name": "clean-code-craft-tcq-1/functional-c-sembooooo",
"revision_date": "2021-03-17T15:02:13",
"revision_id": "dd95ddad863924887a0ba5679bf346b729379ad9",
"snapshot_id": "e0b3a0d22d52f71c3771c3eeb244779a7bca49ee",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/clean-code-craft-tcq-1/functional-c-sembooooo/dd95ddad863924887a0ba5679bf346b729379ad9/Console.c",
"visit_date": "2023-03-21T17:05:11.966356"
} | stackv2 |
#include <stdio.h>
void printonConsole(char* str1, char* str2)
{
printf("%s %s\n",str1,str2);
} | 2.21875 | 2 |
2024-11-18T18:24:06.846791+00:00 | 2021-08-20T06:00:20 | 78faf0093ac578137c13d582c5f60fcbb85804f5 | {
"blob_id": "78faf0093ac578137c13d582c5f60fcbb85804f5",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-20T06:00:20",
"content_id": "8db5ee899d1bbad0f1072aa9ebfbbab6194b23ed",
"detected_licenses": [
"BSD-3-Clause",
"MIT"
],
"directory_id": "c51c388018c899f40e6cc7b3832dc29b9e91371f",
"extension": "h",
"filename": "agnes.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 398147978,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1249,
"license": "BSD-3-Clause,MIT",
"license_type": "permissive",
"path": "/src/agnes/agnes.h",
"provenance": "stackv2-0003.json.gz:404345",
"repo_name": "ordelore/nes_emu",
"revision_date": "2021-08-20T06:00:20",
"revision_id": "6ee405c526f6fe70a12255d64246085dbe279eaf",
"snapshot_id": "783c8d3bf3d6b69eb47fbbed90ca4d7e57de12c4",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/ordelore/nes_emu/6ee405c526f6fe70a12255d64246085dbe279eaf/src/agnes/agnes.h",
"visit_date": "2023-07-08T04:45:21.594732"
} | stackv2 | #ifndef agnes_h
#define agnes_h
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
enum {
AGNES_SCREEN_WIDTH = 256,
AGNES_SCREEN_HEIGHT = 240
};
typedef struct {
bool a;
bool b;
bool select;
bool start;
bool up;
bool down;
bool left;
bool right;
} agnes_input_t;
typedef struct {
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
} agnes_color_t;
typedef struct agnes agnes_t;
typedef struct agnes_state agnes_state_t;
agnes_t* agnes_make(void);
void agnes_destroy(agnes_t *agn);
bool agnes_load_ines_data(agnes_t *agnes, void *data, size_t data_size);
void agnes_set_input(agnes_t *agnes, const agnes_input_t *input_1, const agnes_input_t *input_2);
size_t agnes_state_size(void);
void agnes_dump_state(const agnes_t *agnes, agnes_state_t *out_res);
bool agnes_restore_state(agnes_t *agnes, const agnes_state_t *state);
bool agnes_tick(agnes_t *agnes, bool *out_new_frame);
bool agnes_next_frame(agnes_t *agnes);
agnes_color_t agnes_get_screen_pixel(const agnes_t *agnes, int x, int y);
uint8_t agnes_get_screen_index(const agnes_t *agnes, int x, int y);
agnes_color_t *get_gcolors(void);
#ifdef __cplusplus
}
#endif
#endif /* agnes_h */
| 2.0625 | 2 |
2024-11-18T18:24:07.173611+00:00 | 2023-05-01T15:31:36 | 292278ac40c3c1a65fbd65ea60c69c7f6cae4ad6 | {
"blob_id": "292278ac40c3c1a65fbd65ea60c69c7f6cae4ad6",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-09T19:35:52",
"content_id": "6693fa63c75fea5807ceef055a009dec27e8b1ba",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c18899835bd2df05ad1fe3a4478fe4f22277d6eb",
"extension": "c",
"filename": "wrap_veclib_c.c",
"fork_events_count": 3,
"gha_created_at": "2017-07-16T22:26:20",
"gha_event_created_at": "2023-05-12T13:55:01",
"gha_language": "Python",
"gha_license_id": null,
"github_id": 97414929,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2145,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/Modules/scipy-0.13.0b1/scipy-0.13.0b1/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/wrap_veclib_c.c",
"provenance": "stackv2-0003.json.gz:404861",
"repo_name": "darlinghq/darling-python_modules",
"revision_date": "2023-05-01T15:31:36",
"revision_id": "4ac56d2fd778358ba9ed2a7b6512ea882dd71ed3",
"snapshot_id": "a6c838dc19564e5643620fe8bd0f6582a46c795f",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/darlinghq/darling-python_modules/4ac56d2fd778358ba9ed2a7b6512ea882dd71ed3/Modules/scipy-0.13.0b1/scipy-0.13.0b1/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/wrap_veclib_c.c",
"visit_date": "2023-05-25T10:04:34.889044"
} | stackv2 | #include <Accelerate/Accelerate.h>
#define WRAP_F77(a) a##_
/* This intermediate C-file is necessary also for the Fortran wrapper:
- The cblas_* functions cannot be called from Fortran directly
as they do not take all of their arguments as pointers
(as is done in Fortran).
- It would in principle be possible to make a wrapper directly between
Fortran as for Lapack. However, apparently some versions of
MacOSX have a bug in the FORTRAN interface to SDOT
(). In addition, the cblas seems to be the only standard officially
endorsed by Apple.
*/
float WRAP_F77(acc_sdot)(const int *N, const float *X, const int *incX,
const float *Y, const int *incY)
{
return cblas_sdot(*N, X, *incX, Y, *incY);
}
float WRAP_F77(acc_sdsdot)(const int *N, const float *alpha,
const float *X, const int *incX,
const float *Y, const int *incY)
{
return cblas_sdsdot(*N, *alpha, X, *incX, Y, *incY);
}
float WRAP_F77(acc_sasum)(const int *N, const float *X, const int *incX)
{
return cblas_sasum(*N, X, *incX);
}
float WRAP_F77(acc_snrm2)(const int *N, const float *X, const int *incX)
{
return cblas_snrm2(*N, X, *incX);
}
float WRAP_F77(acc_scasum)(const int *N, const void *X, const int *incX)
{
return cblas_scasum(*N, X, *incX);
}
float WRAP_F77(acc_scnrm2)(const int *N, const void *X, const int *incX)
{
return cblas_scnrm2(*N, X, *incX);
}
void WRAP_F77(acc_cdotc_sub)(const int *N, const void *X, const int *incX,
const void *Y, const int *incY, void *dotc)
{
cblas_cdotc_sub(*N, X, *incX, Y, *incY, dotc);
}
void WRAP_F77(acc_cdotu_sub)(const int *N, const void *X, const int *incX,
const void *Y, const int *incY, void *dotu)
{
cblas_cdotu_sub(*N, X, *incX, Y, *incY, dotu);
}
void WRAP_F77(acc_zdotc_sub)(const int *N, const void *X, const int *incX,
const void *Y, const int *incY, void *dotc)
{
cblas_zdotc_sub(*N, X, *incX, Y, *incY, dotc);
}
void WRAP_F77(acc_zdotu_sub)(const int *N, const void *X, const int *incX,
const void *Y, const int *incY, void *dotu)
{
cblas_zdotu_sub(*N, X, *incX, Y, *incY, dotu);
}
| 2.0625 | 2 |
2024-11-18T18:24:07.349095+00:00 | 2020-12-26T16:37:01 | e28c1483d027c54e2f0278d7ff6d2fbc8ba170f6 | {
"blob_id": "e28c1483d027c54e2f0278d7ff6d2fbc8ba170f6",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-26T16:37:01",
"content_id": "a578453b7f754bf17ccf4a39d18c04f2de320e85",
"detected_licenses": [
"MIT"
],
"directory_id": "3264e4aac8a52f95a68ffcf11496f70dc93c2dae",
"extension": "h",
"filename": "cv_array_tool.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 221822236,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 661,
"license": "MIT",
"license_type": "permissive",
"path": "/cv_algo/cv_array_tool.h",
"provenance": "stackv2-0003.json.gz:404989",
"repo_name": "fboucher9/cave",
"revision_date": "2020-12-26T16:37:01",
"revision_id": "07167530d104f2d61465ba3577e6f8c2bfa45225",
"snapshot_id": "495730b34cd64562c69028683ae3da78f90d3c3b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fboucher9/cave/07167530d104f2d61465ba3577e6f8c2bfa45225/cv_algo/cv_array_tool.h",
"visit_date": "2021-07-09T05:08:06.960289"
} | stackv2 | /* See LICENSE for license details */
#ifndef cv_array_tool_h_
#define cv_array_tool_h_
/*
Module: cv_array_tool.h
Description: Collection of tools related to arrays.
*/
#include <cv_algo/cv_array.h>
#include <cv_misc/cv_bool.h>
#define cv_array_text_initializer_(name) \
cv_array_initializer_(name, name + sizeof(name))
cv_bool cv_array_compare(
cv_array const * p_left,
cv_array const * p_right);
void cv_array_zero(
cv_array const * p_this);
void cv_array_fill(
cv_array const * p_this,
unsigned char c_value);
void cv_array_copy(
cv_array const * p_dst,
cv_array const * p_src);
#endif /* #ifndef cv_array_tool_h_ */
| 2.109375 | 2 |
2024-11-18T18:24:07.413673+00:00 | 2023-07-04T02:38:52 | f1820d9e791c1e3fb7a63df0b31cac473a8743de | {
"blob_id": "f1820d9e791c1e3fb7a63df0b31cac473a8743de",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-04T02:38:52",
"content_id": "a01be1d60a54fd4d1d4824606bd34b6e2c914592",
"detected_licenses": [
"MIT"
],
"directory_id": "9923d63fc48c0fcc786c7d09789cbdebbd700f0a",
"extension": "h",
"filename": "ef_cfg.h",
"fork_events_count": 1136,
"gha_created_at": "2015-05-09T03:25:54",
"gha_event_created_at": "2023-07-04T02:38:53",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 35313328,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5002,
"license": "MIT",
"license_type": "permissive",
"path": "/demo/os/rt-thread/stm32f10x/components/easyflash/inc/ef_cfg.h",
"provenance": "stackv2-0003.json.gz:405119",
"repo_name": "armink/EasyLogger",
"revision_date": "2023-07-04T02:38:52",
"revision_id": "8585ed801d8ae57af6f2bc41ada8107a0eca44de",
"snapshot_id": "87e92bcf83c405c8d4c6885eb0de0f017a68ac3d",
"src_encoding": "UTF-8",
"star_events_count": 3279,
"url": "https://raw.githubusercontent.com/armink/EasyLogger/8585ed801d8ae57af6f2bc41ada8107a0eca44de/demo/os/rt-thread/stm32f10x/components/easyflash/inc/ef_cfg.h",
"visit_date": "2023-07-09T17:47:58.713944"
} | stackv2 | /*
* This file is part of the EasyFlash Library.
*
* Copyright (c) 2015, Armink, <[email protected]>
*
* 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.
*
* Function: It is the configure head file for this library.
* Created on: 2015-07-14
*/
#ifndef EF_CFG_H_
#define EF_CFG_H_
#include <stm32f10x_conf.h>
/* using ENV function */
#define EF_USING_ENV
/* using wear leveling mode for ENV */
/* #define EF_ENV_USING_WL_MODE */
/* using power fail safeguard mode for ENV */
/* #define EF_ENV_USING_PFS_MODE */
/* using IAP function */
#define EF_USING_IAP
/* using save log function */
#define EF_USING_LOG
/* page size for stm32 flash */
#if defined(STM32F10X_LD) || defined(STM32F10X_LD_VL) || defined (STM32F10X_MD) || defined (STM32F10X_MD_VL)
#define PAGE_SIZE 1024
#else
#define PAGE_SIZE 2048
#endif
/* the minimum size of flash erasure */
#define EF_ERASE_MIN_SIZE PAGE_SIZE /* it is one page for STM3210x */
/**
*
* This all Backup Area Flash storage index. All used flash area configure is under here.
* |----------------------------| Storage Size
* | Environment variables area | ENV area size @see ENV_AREA_SIZE
* | 1.system section | ENV_SYSTEM_SIZE
* | 2:data section | ENV_AREA_SIZE - ENV_SYSTEM_SIZE
* |----------------------------|
* | Saved log area | Log area size @see LOG_AREA_SIZE
* |----------------------------|
* |(IAP)Downloaded application | IAP already downloaded application, unfixed size
* |----------------------------|
*
* @note all area size must be aligned with EF_ERASE_MIN_SIZE
* @note EasyFlash will use ram to buffered the ENV. At some time flash's EF_ERASE_MIN_SIZE is so big,
* and you want use ENV size is less than it. So you must defined ENV_USER_SETTING_SIZE for ENV.
* @note ENV area size has some limitations in different modes.
* 1.Normal mode: no more limitations
* 2.Wear leveling mode: system section will used an flash section and the data section will used at least 2 flash sections
* 3.Power fail safeguard mode: ENV area will has an backup. It is twice as normal mode.
* 4.wear leveling and power fail safeguard mode: The required capacity will be 2 times the total capacity in wear leveling mode.
* For example:
* The EF_ERASE_MIN_SIZE is 128K and the ENV_USER_SETTING_SIZE: 2K. The ENV_AREA_SIZE in different mode you can define
* 1.Normal mode: 1*EF_ERASE_MIN_SIZE
* 2.Wear leveling mode: 3*EF_ERASE_MIN_SIZE (It has 2 data section to store ENV. So ENV can erase at least 200,000 times)
* 3.Power fail safeguard mode: 2*EF_ERASE_MIN_SIZE
* 4.Wear leveling and power fail safeguard mode: 6*EF_ERASE_MIN_SIZE
* @note the log area size must be more than twice of EF_ERASE_MIN_SIZE
*/
/* backup area start address */
#define EF_START_ADDR (FLASH_BASE + 80 * 1024) /* from the chip position: 80KB */
/* the user setting size of ENV, must be word alignment */
#define ENV_USER_SETTING_SIZE (2 * 1024)
#ifndef EF_ENV_USING_PFS_MODE
#ifndef EF_ENV_USING_WL_MODE
/* ENV area total bytes size in normal mode. */
#define ENV_AREA_SIZE (1 * EF_ERASE_MIN_SIZE) /* 2K */
#else
/* ENV area total bytes size in wear leveling mode. */
#define ENV_AREA_SIZE (4 * EF_ERASE_MIN_SIZE) /* 8K */
#endif
#else
#ifndef EF_ENV_USING_WL_MODE
/* ENV area total bytes size in power fail safeguard mode. */
#define ENV_AREA_SIZE (2 * EF_ERASE_MIN_SIZE) /* 4K */
#else
/* ENV area total bytes size in wear leveling and power fail safeguard mode. */
#define ENV_AREA_SIZE (8 * EF_ERASE_MIN_SIZE) /* 16K */
#endif
#endif
/* saved log area size */
#define LOG_AREA_SIZE (10 * EF_ERASE_MIN_SIZE) /* 20K */
/* print debug information of flash */
#define PRINT_DEBUG
#endif /* EF_CFG_H_ */
| 2.140625 | 2 |
2024-11-18T18:24:07.498143+00:00 | 2022-11-06T22:46:23 | 6bbbc23b8b9f612b840166dfc7c35b3e332030db | {
"blob_id": "6bbbc23b8b9f612b840166dfc7c35b3e332030db",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-06T22:46:23",
"content_id": "01672ff502e4cae4b943a666e0c6c0ddc73a0360",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c4116c2e8c411a9ab01065144e0e105f99f95313",
"extension": "c",
"filename": "hists.C",
"fork_events_count": 61,
"gha_created_at": "2013-09-26T20:14:27",
"gha_event_created_at": "2021-10-30T14:54:45",
"gha_language": "C++",
"gha_license_id": "BSD-3-Clause",
"github_id": 13133237,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 17726,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/examples/VDC/hists.C",
"provenance": "stackv2-0003.json.gz:405247",
"repo_name": "JeffersonLab/analyzer",
"revision_date": "2022-11-06T22:46:23",
"revision_id": "a0613dcafa9efe42f759f5321cd0f8d2c633ba2f",
"snapshot_id": "aba8b4ce90b549b345daa81e731e44b0d704354b",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/JeffersonLab/analyzer/a0613dcafa9efe42f759f5321cd0f8d2c633ba2f/examples/VDC/hists.C",
"visit_date": "2023-06-17T00:26:31.368749"
} | stackv2 | {
#include <TStyle.h>
const int kBUFLEN = 150;
// open trees
TFile *f = new TFile("/data/proc_data.root");
TTree *t = (TTree *)f->Get("TL");
Int_t new_nentries, old_nentries, nentries;
nentries = (Int_t)t->GetEntries();
char input[kBUFLEN];
cout<<"Which graphs do you want to see?"<<endl;
cout<<" (s)imple comparisons"<<endl;
cout<<" (t)wo-d comparisons"<<endl;
cout<<" (c)ross correlations"<<endl;
cout<<" (d)ifferences"<<endl;
cout<<" rotated sim(p)le comparisons"<<endl;
cout<<" rotated t(w)o-d comparisons"<<endl;
cout<<" rotated cr(o)ss correlations"<<endl;
cout<<" rotated diff(e)rences"<<endl;
cout<<" ta(r)get values"<<endl;
cout<<" t(a)rget two-d"<<endl;
cout<<" tar(g)et cross-correlations"<<endl;
cout<<" target di(f)erences"<<endl;
input[0] = '\0';
fgets(input, kBUFLEN, stdin);
switch(input[0])
{
// simple comparisons
case 's':
case 'S':
c1 = new TCanvas("c1", "X");
t->Draw("CL_TR_x", "abs(CL_TR_x+0.25)<0.5");
c1->Update();
t->SetLineColor(kRed);
t->Draw("FL_TR_x", "abs(FL_TR_x+0.25)<0.5", "same");
t->SetLineColor(kBlack);
c1->Update();
c2 = new TCanvas("c2", "Y");
t->Draw("CL_TR_y", "abs(CL_TR_y)<0.15");
c2->Update();
t->SetLineColor(kRed);
t->Draw("FL_TR_y", "abs(FL_TR_y)<0.15", "same");
t->SetLineColor(kBlack);
c2->Update();
c3 = new TCanvas("c3", "Theta");
t->Draw("CL_TR_th", "abs(CL_TR_th+0.05)<0.1");
c3->Update();
t->SetLineColor(kRed);
t->Draw("FL_TR_th", "abs(FL_TR_th+0.05)<0.1", "same");
t->SetLineColor(kBlack);
c3->Update();
c4 = new TCanvas("c4", "Phi");
t->Draw("CL_TR_ph", "abs(CL_TR_ph)<0.15");
c4->Update();
t->SetLineColor(kRed);
t->Draw("FL_TR_ph", "abs(FL_TR_ph)<0.15", "same");
t->SetLineColor(kBlack);
c4->Update();
break;
// 2d comparisons
case 't':
case 'T':
c9 = new TCanvas("c9", "New X v Y");
t->Draw("CL_TR_y:CL_TR_x",
"abs(CL_TR_x+0.4)<0.3&&abs(CL_TR_y)<0.05");
c10 = new TCanvas("c10", "Old X v Y");
t->Draw("FL_TR_y:FL_TR_x",
"abs(FL_TR_x+0.4)<0.3&&abs(FL_TR_y)<0.05");
c11 = new TCanvas("c11", "New Theta v Phi");
t->Draw("CL_TR_ph:CL_TR_th",
"abs(CL_TR_th+0.05)<0.06&&abs(CL_TR_ph)<.05");
c12 = new TCanvas("c12", "Old Theta v Phi");
t->Draw("FL_TR_ph:FL_TR_th",
"abs(FL_TR_th+0.05)<0.06&&abs(FL_TR_ph)<.05");
c13 = new TCanvas("c13", "New X v Theta");
t->Draw("CL_TR_th:CL_TR_x",
"abs(CL_TR_x+0.4)<0.3&&abs(CL_TR_th+0.05)<0.1");
c14 = new TCanvas("c14", "Old X v Theta");
t->Draw("FL_TR_th:FL_TR_x",
"abs(FL_TR_x+0.4)<0.3&&abs(FL_TR_th+0.05)<0.1");
c15 = new TCanvas("c15", "New Y v Phi");
t->Draw("CL_TR_ph:CL_TR_y",
"abs(CL_TR_ph)<0.05&&abs(CL_TR_y)<0.05");
c16 = new TCanvas("c16", "Old Y v Phi");
t->Draw("FL_TR_ph:FL_TR_y",
"abs(FL_TR_ph)<0.05&&abs(FL_TR_y)<0.05");
break;
// cross correlations
case 'c':
case 'C':
c20 = new TCanvas("c20", "New X v Old X");
t->Draw("FL_TR_x:CL_TR_x", "abs(FL_TR_x+0.25)<0.5&&abs(CL_TR_x+0.25)<0.5");
c20->Update();
c21 = new TCanvas("c21", "New Y v Old Y");
t->Draw("FL_TR_y:CL_TR_y", "abs(FL_TR_y)<0.15&&abs(CL_TR_y)<0.15");
c21->Update();
c22 = new TCanvas("c22", "New Theta v Old Theta");
t->Draw("FL_TR_th:CL_TR_th", "abs(CL_TR_th+0.05)<0.1&&abs(FL_TR_th+0.05)<0.1");
c22->Update();
c23 = new TCanvas("c23", "New Phi v Old Phi");
t->Draw("FL_TR_ph:CL_TR_ph", "abs(FL_TR_ph)<0.15&&abs(CL_TR_ph)<0.15");
c23->Update();
break;
// differences
case 'd':
case 'D':
c30 = new TCanvas("c30", "New X - Old X");
t->Draw("CL_TR_x-FL_TR_x", "(CL_TR_x-FL_TR_x)>-0.005&&(CL_TR_x-FL_TR_x)<0.005");
TH1F *xdhist = (TH1F*)gPad->GetPrimitive("htemp");
xdhist->Fit("gaus");
TF1 *xf = xdhist->GetFunction("gaus");
cout<<"chi-squared = "<<xf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<xf->GetChisquare()/(float)(xf->GetNDF())<<endl;
cout<<"mean value = "<<xdhist->GetMean()<<endl;
cout<<"RMS value = "<<xdhist->GetRMS()<<endl;
c30->Update();
c31 = new TCanvas("c31", "New Y - Old Y");
t->Draw("CL_TR_y-FL_TR_y", "(CL_TR_y-FL_TR_y)>-0.005&&(CL_TR_y-FL_TR_y)<0.005");
TH1F *ydhist = (TH1F*)gPad->GetPrimitive("htemp");
ydhist->Fit("gaus");
TF1 *yf = ydhist->GetFunction("gaus");
cout<<"chi-squared = "<<yf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<yf->GetChisquare()/(float)(yf->GetNDF())<<endl;
cout<<"mean value = "<<ydhist->GetMean()<<endl;
cout<<"RMS value = "<<ydhist->GetRMS()<<endl;
c31->Update();
c32 = new TCanvas("c32", "New Theta - Old Theta");
t->Draw("CL_TR_th-FL_TR_th", "(CL_TR_th-FL_TR_th)>-0.01&&(CL_TR_th-FL_TR_th)<0.01");
TH1F *tdhist = (TH1F*)gPad->GetPrimitive("htemp");
tdhist->Fit("gaus");
TF1 *tf = tdhist->GetFunction("gaus");
cout<<"chi-squared = "<<tf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<tf->GetChisquare()/(float)(tf->GetNDF())<<endl;
cout<<"mean value = "<<tdhist->GetMean()<<endl;
cout<<"RMS value = "<<tdhist->GetRMS()<<endl;
c32->Update();
c33 = new TCanvas("c33", "New Phi - Old Phi");
t->Draw("CL_TR_ph-FL_TR_ph", "(CL_TR_ph-FL_TR_ph)>-0.01&&(CL_TR_ph-FL_TR_ph)<0.01");
TH1F *pdhist = (TH1F*)gPad->GetPrimitive("htemp");
pdhist->Fit("gaus");
TF1 *pf = pdhist->GetFunction("gaus");
cout<<"chi-squared = "<<pf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<pf->GetChisquare()/(float)(pf->GetNDF())<<endl;
cout<<"mean value = "<<pdhist->GetMean()<<endl;
cout<<"RMS value = "<<pdhist->GetRMS()<<endl;
c33->Update();
break;
// target histograms
case 'r':
case 'R':
c51 = new TCanvas("c51", "delta");
t->Draw("CL_TG_dp", "abs(CL_TG_dp+0.025)<0.025");
c51->Update();
t->SetLineColor(kRed);
t->Draw("FL_TG_dp", "abs(FL_TG_dp+0.025)<0.025", "same");
t->SetLineColor(kBlack);
c51->Update();
c52 = new TCanvas("c52", "Y");
t->Draw("CL_TG_y", "abs(CL_TG_y)<0.06");
c52->Update();
t->SetLineColor(kRed);
t->Draw("FL_TG_y", "abs(FL_TG_y)<0.06", "same");
t->SetLineColor(kBlack);
c52->Update();
c53 = new TCanvas("c53", "Theta");
t->Draw("CL_TG_th", "abs(CL_TG_th+0.05)<0.2");
c53->Update();
t->SetLineColor(kRed);
t->Draw("FL_TG_th", "abs(FL_TG_th+0.05)<0.2", "same");
t->SetLineColor(kBlack);
c53->Update();
c54 = new TCanvas("c4", "Phi");
t->Draw("CL_TG_ph", "abs(CL_TG_ph)<0.1");
c54->Update();
t->SetLineColor(kRed);
t->Draw("FL_TG_ph", "abs(FL_TG_ph)<0.1", "same");
t->SetLineColor(kBlack);
c54->Update();
break;
case 'g':
case 'G':
c250 = new TCanvas("c250", "New Delta v. Old Delta");
t->Draw("FL_TG_dp:CL_TG_dp", "abs(CL_TG_dp+0.025)<0.025&&abs(FL_TG_dp+0.025)<0.025");
c250->Update();
c251 = new TCanvas("c251", "New Y v. Old Y");
t->Draw("FL_TG_y:CL_TG_y", "abs(CL_TG_y)<0.06&&abs(FL_TG_y)<0.06");
c251->Update();
c252 = new TCanvas("c252", "New Theta v. Old Theta");
t->Draw("FL_TG_th:CL_TG_th", "abs(CL_TG_th+0.05)<0.2&&abs(FL_TG_th+0.05)<0.2");
c252->Update();
c253 = new TCanvas("c253", "New Phi v. Old Phi");
t->Draw("FL_TG_ph:CL_TG_ph", "abs(CL_TG_ph)<0.1&&abs(FL_TG_ph)<0.1");
c253->Update();
break;
case 'a':
case 'A':
c55 = new TCanvas("c55", "Target Theta v. Phi");
c55->Divide(1,2);
c55->cd(1);
t->Draw("CL_TG_th:CL_TG_ph", "abs(CL_TG_th)<0.1&&abs(CL_TG_ph)<0.1");
c55->cd(2);
t->Draw("FL_TG_th:FL_TG_ph", "abs(FL_TG_th)<0.1&&abs(FL_TG_ph)<0.1");
c55->Update();
c56 = new TCanvas("c56", "Target Theta v. Phi - Peak 0");
c56->Divide(1,2);
c56->cd(1);
t->Draw("CL_TG_th:CL_TG_ph",
"abs(CL_TG_th)<0.1&&abs(CL_TG_ph)<0.1&&abs(CL_TG_y)<0.003");
c56->cd(2);
t->Draw("FL_TG_th:FL_TG_ph",
"abs(FL_TG_th)<0.1&&abs(FL_TG_ph)<0.1&&abs(FL_TG_y)<0.003");
c56->Update();
c57 = new TCanvas("c57", "Target Theta v. Phi - Peak 1");
c57->Divide(1,2);
c57->cd(1);
t->Draw("CL_TG_th:CL_TG_ph",
"abs(CL_TG_th)<0.1&&abs(CL_TG_ph)<0.1&&abs(CL_TG_y+1*0.0125)<0.003");
c57->cd(2);
t->Draw("FL_TG_th:FL_TG_ph",
"abs(FL_TG_th)<0.1&&abs(FL_TG_ph)<0.1&&abs(FL_TG_y+1*0.0125)<0.003");
c57->Update();
c58 = new TCanvas("c58", "Target Theta v. Phi - Peak 2");
c58->Divide(1,2);
c58->cd(1);
t->Draw("CL_TG_th:CL_TG_ph",
"abs(CL_TG_th)<0.1&&abs(CL_TG_ph)<0.1&&abs(CL_TG_y+2*0.0125)<0.003");
c58->cd(2);
t->Draw("FL_TG_th:FL_TG_ph",
"abs(FL_TG_th)<0.1&&abs(FL_TG_ph)<0.1&&abs(FL_TG_y+2*0.0125)<0.003");
c58->Update();
c59 = new TCanvas("c59", "Target Theta v. Phi - Peak 3");
c59->Divide(1,2);
c59->cd(1);
t->Draw("CL_TG_th:CL_TG_ph",
"abs(CL_TG_th)<0.1&&abs(CL_TG_ph)<0.1&&abs(CL_TG_y+3*0.0125)<0.003");
c59->cd(2);
t->Draw("FL_TG_th:FL_TG_ph",
"abs(FL_TG_th)<0.1&&abs(FL_TG_ph)<0.1&&abs(FL_TG_y+3*0.0125)<0.003");
c59->Update();
c100 = new TCanvas("c100", "Target Theta v. Phi - Peak 4");
c100->Divide(1,2);
c100->cd(1);
t->Draw("CL_TG_th:CL_TG_ph",
"abs(CL_TG_th)<0.1&&abs(CL_TG_ph)<0.1&&abs(CL_TG_y+4*0.0125)<0.003");
c100->cd(2);
t->Draw("FL_TG_th:FL_TG_ph",
"abs(FL_TG_th)<0.1&&abs(FL_TG_ph)<0.1&&abs(FL_TG_y+4*0.0125)<0.003");
c100->Update();
c101 = new TCanvas("c100", "Target Theta v. Phi - Peak -1");
c101->Divide(1,2);
c101->cd(1);
t->Draw("CL_TG_th:CL_TG_ph",
"abs(CL_TG_th)<0.1&&abs(CL_TG_ph)<0.1&&abs(CL_TG_y-1*0.0125)<0.003");
c101->cd(2);
t->Draw("FL_TG_th:FL_TG_ph",
"abs(FL_TG_th)<0.1&&abs(FL_TG_ph)<0.1&&abs(FL_TG_y-1*0.0125)<0.003");
c101->Update();
c102 = new TCanvas("c102", "Target Theta v. Phi - Peak -2");
c102->Divide(1,2);
c102->cd(1);
t->Draw("CL_TG_th:CL_TG_ph",
"abs(CL_TG_th)<0.1&&abs(CL_TG_ph)<0.1&&abs(CL_TG_y-2*0.0125)<0.003");
c102->cd(2);
t->Draw("FL_TG_th:FL_TG_ph",
"abs(FL_TG_th)<0.1&&abs(FL_TG_ph)<0.1&&abs(FL_TG_y-2*0.0125)<0.003");
c102->Update();
c103 = new TCanvas("c103", "Target Theta v. Phi - Peak -3");
c103->Divide(1,2);
c103->cd(1);
t->Draw("CL_TG_th:CL_TG_ph",
"abs(CL_TG_th)<0.1&&abs(CL_TG_ph)<0.1&&abs(CL_TG_y-3*0.0125)<0.003");
c103->cd(2);
t->Draw("FL_TG_th:FL_TG_ph",
"abs(FL_TG_th)<0.1&&abs(FL_TG_ph)<0.1&&abs(FL_TG_y-3*0.0125)<0.003");
c103->Update();
c104 = new TCanvas("c104", "Target Theta v. Phi - Peak -4");
c104->Divide(1,2);
c104->cd(1);
t->Draw("CL_TG_th:CL_TG_ph",
"abs(CL_TG_th)<0.1&&abs(CL_TG_ph)<0.1&&abs(CL_TG_y-4*0.0125)<0.003");
c104->cd(2);
t->Draw("FL_TG_th:FL_TG_ph",
"abs(FL_TG_th)<0.1&&abs(FL_TG_ph)<0.1&&abs(FL_TG_y-4*0.0125)<0.003");
c104->Update();
c105 = new TCanvas("c105", "Target Theta v. Delta");
c105->Divide(1,2);
c105->cd(1);
t->Draw("CL_TG_dp:CL_TG_ph", "abs(CL_TG_ph)<0.05&&abs(CL_TG_dp+0.025)<0.025");
c105->cd(2);
t->Draw("FL_TG_dp:FL_TG_ph", "abs(FL_TG_ph)<0.05&&abs(FL_TG_dp+0.025)<0.025");
c105->Update();
c106 = new TCanvas("c106", "Target Theta v. Delta - Peak 0");
c106->Divide(1,2);
c106->cd(1);
t->Draw("CL_TG_dp:CL_TG_ph",
"abs(CL_TG_ph)<0.05&&abs(CL_TG_dp+0.025)<0.025&&abs(CL_TG_y)<0.003");
c106->cd(2);
t->Draw("FL_TG_dp:FL_TG_ph",
"abs(FL_TG_ph)<0.05&&abs(FL_TG_dp+0.025)<0.025&&abs(CL_TG_y)<0.003");
c106->Update();
break;
case 'f':
case 'F':
/* delta diff for each peak */
c60 = new TCanvas("c60", "New delta - Old delta");
t->Draw("CL_TG_dp-FL_TG_dp",
"(CL_TG_dp-FL_TG_dp)>-0.01&&(CL_TG_dp-FL_TG_dp)<0.01");
TH1F *xdhist = (TH1F*)gPad->GetPrimitive("htemp");
xdhist->Fit("gaus");
TF1 *xf = xdhist->GetFunction("gaus");
cout<<"chi-squared = "<<xf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<xf->GetChisquare()/(float)(xf->GetNDF())<<endl;
cout<<"mean value = "<<xdhist->GetMean()<<endl;
cout<<"RMS value = "<<xdhist->GetRMS()<<endl;
c60->Update();
c61 = new TCanvas("c61", "New Target Y - Old Target Y");
t->Draw("CL_TG_y-FL_TG_y", "(CL_TG_y-FL_TG_y)>-0.02&&(CL_TG_y-FL_TG_y)<0.02");
TH1F *ydhist = (TH1F*)gPad->GetPrimitive("htemp");
ydhist->Fit("gaus");
TF1 *yf = ydhist->GetFunction("gaus");
cout<<"chi-squared = "<<yf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<yf->GetChisquare()/(float)(yf->GetNDF())<<endl;
cout<<"mean value = "<<ydhist->GetMean()<<endl;
cout<<"RMS value = "<<ydhist->GetRMS()<<endl;
c61->Update();
c62 = new TCanvas("c62", "New Target Theta - Old Target Theta");
t->Draw("CL_TG_th-FL_TG_th",
"(CL_TG_th-FL_TG_th)>-0.05&&(CL_TG_th-FL_TG_th)<0.05");
TH1F *tdhist = (TH1F*)gPad->GetPrimitive("htemp");
tdhist->Fit("gaus");
TF1 *tf = tdhist->GetFunction("gaus");
cout<<"chi-squared = "<<tf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<tf->GetChisquare()/(float)(tf->GetNDF())<<endl;
cout<<"mean value = "<<tdhist->GetMean()<<endl;
cout<<"RMS value = "<<tdhist->GetRMS()<<endl;
c62->Update();
c63 = new TCanvas("c63", "New Target Phi - Old Target Phi");
t->Draw("CL_TG_ph-FL_TG_ph",
"(CL_TG_ph-FL_TG_ph)>-0.01&&(CL_TG_ph-FL_TG_ph)<0.01");
TH1F *pdhist = (TH1F*)gPad->GetPrimitive("htemp");
pdhist->Fit("gaus");
TF1 *pf = pdhist->GetFunction("gaus");
cout<<"chi-squared = "<<pf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<pf->GetChisquare()/(float)(pf->GetNDF())<<endl;
cout<<"mean value = "<<pdhist->GetMean()<<endl;
cout<<"RMS value = "<<pdhist->GetRMS()<<endl;
c63->Update();
break;
// rotated simple comparisons
case 'p':
case 'P':
c71 = new TCanvas("c71", "X");
t->Draw("CL_TR_rx", "abs(CL_TR_rx+0.25)<0.5");
c71->Update();
t->SetLineColor(kRed);
t->Draw("FL_TR_rx", "abs(FL_TR_rx+0.25)<0.5", "same");
t->SetLineColor(kBlack);
c71->Update();
c72 = new TCanvas("c72", "Y");
t->Draw("CL_TR_ry", "abs(CL_TR_ry)<0.15");
c72->Update();
t->SetLineColor(kRed);
t->Draw("FL_TR_ry", "abs(FL_TR_ry)<0.15", "same");
t->SetLineColor(kBlack);
c72->Update();
c73 = new TCanvas("c73", "Theta");
t->Draw("CL_TR_rth", "abs(CL_TR_rth+0.05)<0.1");
c73->Update();
t->SetLineColor(kRed);
t->Draw("FL_TR_rth", "abs(FL_TR_rth+0.05)<0.1", "same");
t->SetLineColor(kBlack);
c73->Update();
c74 = new TCanvas("c74", "Phi");
t->Draw("CL_TR_rph", "abs(CL_TR_rph)<0.15");
c74->Update();
t->SetLineColor(kRed);
t->Draw("FL_TR_rph", "abs(FL_TR_rph)<0.15", "same");
t->SetLineColor(kBlack);
c74->Update();
break;
// rotated 2d comparisons
case 'w':
case 'W':
c89 = new TCanvas("c89", "New X v Y");
t->Draw("CL_TR_ry:CL_TR_rx",
"abs(CL_TR_rx+0.4)<0.3&&abs(CL_TR_ry)<0.05");
c80 = new TCanvas("c80", "Old X v Y");
t->Draw("FL_TR_ry:FL_TR_rx",
"abs(FL_TR_rx+0.4)<0.3&&abs(FL_TR_ry)<0.05");
c81 = new TCanvas("c81", "New Theta v Phi");
t->Draw("CL_TR_rph:CL_TR_rth",
"abs(CL_TR_rth+0.05)<0.06&&abs(CL_TR_rph)<.05");
c82 = new TCanvas("c82", "Old Theta v Phi");
t->Draw("FL_TR_rph:FL_TR_rth",
"abs(FL_TR_rth+0.05)<0.06&&abs(FL_TR_rph)<.05");
c83 = new TCanvas("c83", "New X v Theta");
t->Draw("CL_TR_rth:CL_TR_rx",
"abs(CL_TR_rx+0.4)<0.3&&abs(CL_TR_rth+0.05)<0.1");
c84 = new TCanvas("c84", "Old X v Theta");
t->Draw("FL_TR_rth:FL_TR_rx",
"abs(FL_TR_rx+0.4)<0.3&&abs(FL_TR_rth+0.05)<0.1");
c85 = new TCanvas("c85", "New Y v Phi");
t->Draw("CL_TR_rph:CL_TR_ry",
"abs(CL_TR_rph)<0.05&&abs(CL_TR_ry)<0.05");
c86 = new TCanvas("c86", "Old Y v Phi");
t->Draw("FL_TR_rph:FL_TR_ry",
"abs(FL_TR_rph)<0.05&&abs(FL_TR_ry)<0.05");
break;
// rotated cross correlations
case 'o':
case 'O':
c90 = new TCanvas("c20", "New X v Old X");
t->Draw("FL_TR_rx:CL_TR_rx", "abs(FL_TR_rx+0.25)<0.5&&abs(CL_TR_rx+0.25)<0.5");
c20->Update();
c91 = new TCanvas("c21", "New Y v Old Y");
t->Draw("FL_TR_ry:CL_TR_ry", "abs(FL_TR_ry)<0.15&&abs(CL_TR_ry)<0.15");
c21->Update();
c92 = new TCanvas("c22", "New Theta v Old Theta");
t->Draw("FL_TR_rth:CL_TR_rth", "abs(CL_TR_rth+0.05)<0.1&&abs(FL_TR_rth+0.05)<0.1");
c22->Update();
c93 = new TCanvas("c23", "New Phi v Old Phi");
t->Draw("FL_TR_rph:CL_TR_rph", "abs(FL_TR_rph)<0.15&&abs(CL_TR_rph)<0.15");
c93->Update();
break;
// differences
case 'e':
case 'E':
c94 = new TCanvas("c94", "New X - Old X");
t->Draw("CL_TR_rx-FL_TR_rx", "(CL_TR_rx-FL_TR_rx)>-0.005&&(CL_TR_rx-FL_TR_rx)<0.005");
TH1F *xdhist = (TH1F*)gPad->GetPrimitive("htemp");
xdhist->Fit("gaus");
TF1 *xf = xdhist->GetFunction("gaus");
cout<<"chi-squared = "<<xf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<xf->GetChisquare()/(float)(xf->GetNDF())<<endl;
cout<<"mean value = "<<xdhist->GetMean()<<endl;
cout<<"RMS value = "<<xdhist->GetRMS()<<endl;
c94->Update();
c95 = new TCanvas("c95", "New Y - Old Y");
t->Draw("CL_TR_ry-FL_TR_ry", "(CL_TR_ry-FL_TR_ry)>-0.005&&(CL_TR_ry-FL_TR_ry)<0.005");
TH1F *ydhist = (TH1F*)gPad->GetPrimitive("htemp");
ydhist->Fit("gaus");
TF1 *yf = ydhist->GetFunction("gaus");
cout<<"chi-squared = "<<yf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<yf->GetChisquare()/(float)(yf->GetNDF())<<endl;
cout<<"mean value = "<<ydhist->GetMean()<<endl;
cout<<"RMS value = "<<ydhist->GetRMS()<<endl;
c95->Update();
c96 = new TCanvas("c96", "New Theta - Old Theta");
t->Draw("CL_TR_rth-FL_TR_rth",
"(CL_TR_rth-FL_TR_rth)>-0.02&&(CL_TR_rth-FL_TR_rth)<0.02");
TH1F *tdhist = (TH1F*)gPad->GetPrimitive("htemp");
tdhist->Fit("gaus");
TF1 *tf = tdhist->GetFunction("gaus");
cout<<"chi-squared = "<<tf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<tf->GetChisquare()/(float)(tf->GetNDF())<<endl;
cout<<"mean value = "<<tdhist->GetMean()<<endl;
cout<<"RMS value = "<<tdhist->GetRMS()<<endl;
c96->Update();
c97 = new TCanvas("c97", "New Phi - Old Phi");
t->Draw("CL_TR_rph-FL_TR_rph",
"(CL_TR_rph-FL_TR_rph)>-0.01&&(CL_TR_rph-FL_TR_rph)<0.01");
TH1F *pdhist = (TH1F*)gPad->GetPrimitive("htemp");
pdhist->Fit("gaus");
TF1 *pf = pdhist->GetFunction("gaus");
cout<<"chi-squared = "<<pf->GetChisquare()<<endl;
cout<<"reduced chi-squared = "
<<pf->GetChisquare()/(float)(pf->GetNDF())<<endl;
cout<<"mean value = "<<pdhist->GetMean()<<endl;
cout<<"RMS value = "<<pdhist->GetRMS()<<endl;
c97->Update();
break;
}
// cleanup
delete f;
}
| 2.359375 | 2 |
2024-11-18T18:24:07.581610+00:00 | 2019-08-28T12:12:40 | a98bba29913d478454ff6b709e8e4d49b44b000f | {
"blob_id": "a98bba29913d478454ff6b709e8e4d49b44b000f",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-28T12:12:40",
"content_id": "792e18d255f2a3f09ab165be8383c4c0a6c8c936",
"detected_licenses": [
"MIT"
],
"directory_id": "276806db8ea591a8da004a073dc9e2bbe870f8f4",
"extension": "c",
"filename": "std_funcs_os_anonymizer.c",
"fork_events_count": 0,
"gha_created_at": "2019-08-28T11:27:47",
"gha_event_created_at": "2019-08-28T13:27:48",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 204915720,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7663,
"license": "MIT",
"license_type": "permissive",
"path": "/src/generics/std_funcs_os_anonymizer.c",
"provenance": "stackv2-0003.json.gz:405375",
"repo_name": "leopardb/mhl-tool",
"revision_date": "2019-08-28T12:12:40",
"revision_id": "63d6bfb8b03702b0f9263153fba0b8903bbd0b93",
"snapshot_id": "099189d0b4d795129639cf3ebaa738e6d91e3274",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/leopardb/mhl-tool/63d6bfb8b03702b0f9263153fba0b8903bbd0b93/src/generics/std_funcs_os_anonymizer.c",
"visit_date": "2020-07-12T21:52:58.576925"
} | stackv2 | /*
The MIT License (MIT)
Copyright (c) 2016 Pomfort GmbH
https://github.com/pomfort/mhl-tool
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
* @file: std_funcs_os_anonymizer.c
*
* Definitions of generic functions have different
* implementation of different OS.
*
*/
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <generics/os_check.h>
#ifdef WIN
#include <ctype.h>
#include <malloc.h>
#include <sys/types.h>
#elif defined MAC_OS_X
#include <wctype.h>
#endif
#include <generics/std_funcs_os_anonymizer.h>
#ifdef WIN
/*
* OS specific version of "strcasestr". strcasestr is GNU specific function.
*/
char* mhlosi_strcasestr(const char* haystack, const char* needle)
{
// This implementation is unoptimal.
// May be it make sense to find more optimal implementation.
errno_t err;
char* haystack_lw;
char* needle_lw;
char* needle_lw_p;
off_t needle_distance;
char* res;
haystack_lw = _strdup(haystack);
if (haystack_lw == NULL)
{
return NULL;
}
needle_lw = _strdup(needle);
if (needle_lw == NULL)
{
free(haystack_lw);
return NULL;
}
//
err = _strlwr_s(haystack_lw, strlen(haystack_lw));
if (err != 0)
{
free(haystack_lw);
free(needle_lw);
return NULL;
}
err = _strlwr_s(needle_lw, strlen(needle_lw));
if (err != 0)
{
free(haystack_lw);
free(needle_lw);
return NULL;
}
//
needle_lw_p = strstr(haystack_lw, needle_lw);
if (needle_lw_p == NULL)
{
free(haystack_lw);
free(needle_lw);
return NULL;
}
needle_distance = needle_lw_p - haystack_lw;
free(haystack_lw);
free(needle_lw);
res = (char*) haystack + needle_distance;
return res;
}
#else
/*
* OS specific version of "strcasestr". strcasestr is GNU specific function.
*/
char* mhlosi_strcasestr(const char* haystack, const char* needle)
{
return strcasestr(haystack, needle);
}
#endif
char* mhlosi_strdup(const char* s)
{
#ifdef WIN
return _strdup(s);
#else
return strdup(s);
#endif
}
/*
* OS specific version of "strcasecmp".
*/
int mhlosi_strcasecmp(const char* s1, const char* s2)
{
#ifdef WIN
return _stricmp(s1, s2);
#else
return strcasecmp(s1, s2);
#endif
}
/*
* OS specific version of "strncasecmp".
*/
int mhlosi_strncasecmp(const char* s1, const char* s2, size_t n)
{
#ifdef WIN
return _strnicmp(s1, s2, n);
#else
return strncasecmp(s1, s2, n);
#endif
}
/*
* OS specific version of "strtoull".
*/
unsigned long long mhlosi_strtoull(const char *nptr, char **endptr, int base)
{
#ifdef WIN
return (unsigned long long) _strtoui64(nptr, endptr, base);
#else
return strtoull(nptr, endptr, base);
#endif
}
//
//
//
/*
* OS specific version of "strdup".
* strdup POSIX function is deprecated since Visual C++ 2005.
*/
wchar_t* mhlosi_wstrdup(const wchar_t* s)
{
#if defined WIN
return _wcsdup(s);
#elif defined MAC_OS_X
wchar_t* ws_dup;
size_t ws_sz = wcslen(s);
ws_dup = (wchar_t*) calloc(ws_sz + 1, sizeof(wchar_t));
if (ws_dup == NULL)
{
return NULL;
}
wcsncpy(ws_dup, s, ws_sz);
return ws_dup;
#else
return wcsdup(s);
#endif
}
/*
* strdup POSIX function is deprecated since Visual C++ 2005.
*/
wchar_t* mhlosi_wstrndup(const wchar_t* s, size_t s_sz)
{
wchar_t* ws_dup;
size_t real_s_sz = 0;
real_s_sz = wcslen(s);
real_s_sz = real_s_sz > s_sz ? s_sz : real_s_sz;
ws_dup = calloc(real_s_sz + 1, sizeof(wchar_t));
if (ws_dup == 0)
{
return 0; // no memeory
}
wcsncpy(ws_dup, s, real_s_sz);
// ending L'\0' already set by calloc
return ws_dup;
}
/*
* OS specific version of "strcasecmp". strcasecmp is GNU specific function.
*/
int mhlosi_wstrcmp(const wchar_t* s1, const wchar_t* s2)
{
return wcscmp(s1, s2);
}
/*
* OS specific version of "strcasecmp". strcasecmp is GNU specific function.
*/
int mhlosi_wstrncmp(const wchar_t* s1, const wchar_t* s2, size_t n)
{
return wcsncmp(s1, s2, n);
}
/*
* OS specific version of "strcasecmp". strcasecmp is GNU specific function.
*/
#ifdef MAC_OS_X
int mhlosi_wstrncasecmp(const wchar_t* ws1, const wchar_t* ws2, size_t wsz)
{
wchar_t* s1_lower;
wchar_t* s2_lower;
int results;
int index;
s1_lower = (wchar_t*)malloc(sizeof(wchar_t) * wcslen(ws1));
s2_lower = (wchar_t*)malloc(sizeof(wchar_t) * wcslen(ws2));
wcscpy(s1_lower, ws1);
wcscpy(s2_lower, ws2);
index = 0;
while (s1_lower[index] != '\0')
{
s1_lower[index] = towlower(s1_lower[index]);
index++;
}
index = 0;
while (s2_lower[index] != '\0')
{
s2_lower[index] = towlower(s2_lower[index]);
index++;
}
results = wcsncmp(s1_lower, s2_lower, wsz);
free(s1_lower);
free(s2_lower);
return results;
}
#else
int mhlosi_wstrncasecmp(const wchar_t* ws1, const wchar_t* ws2, size_t wsz)
{
#ifdef WIN
return _wcsnicmp(ws1, ws2, wsz);
#else
return wcsncasecmp(ws1, ws2, wsz);
#endif
}
#endif
/*
* OS specific version of "strcasecmp". strcasecmp is GNU specific function.
*/
#ifdef MAC_OS_X
int mhlosi_wstrcasecmp(const wchar_t* ws1, const wchar_t* ws2)
{
wchar_t* s1_lower;
wchar_t* s2_lower;
int results;
int index;
s1_lower = (wchar_t*)malloc(sizeof(wchar_t) * wcslen(ws1));
s2_lower = (wchar_t*)malloc(sizeof(wchar_t) * wcslen(ws2));
wcscpy(s1_lower, ws1);
wcscpy(s2_lower, ws2);
index = 0;
while (s1_lower[index] != '\0')
{
s1_lower[index] = towlower(s1_lower[index]);
index++;
}
index = 0;
while (s2_lower[index] != '\0')
{
s2_lower[index] = towlower(s2_lower[index]);
index++;
}
results = wcscmp(s1_lower, s2_lower);
free(s1_lower);
free(s2_lower);
return results;
}
#else
int mhlosi_wstrcasecmp(const wchar_t* s1, const wchar_t* s2)
{
#ifdef WIN
return _wcsicmp(s1, s2);
#else
return wcscasecmp(s1, s2);
#endif
}
#endif
/*
* OS specific version of "strcasestr". strcasestr is GNU specific function.
*/
wchar_t* mhlosi_wstrstr(const wchar_t* haystack, const wchar_t* needle)
{
return (wchar_t*) wcsstr(haystack, needle);
}
/*
* OS specific and safe version of wcscat.
* Appends at least n wchars from str to dst.
* NOTE: buffer with dst string should have enough space for appended n wchars!
*
* Returns pointer to destination string. 0 means error.
*/
wchar_t*
mhlosi_wstrncat(const wchar_t* src, wchar_t* dst, size_t count)
{
size_t i;
size_t dst_sz;
if (src == 0 || dst == 0 || count == 0)
{
return 0;
}
dst_sz = wcslen(dst);
for (i = 0; i < count && src[i] != L'\0'; ++i)
{
dst[dst_sz + i] = src[i];
}
dst[dst_sz + i] = L'\0';
return dst;
}
| 2.296875 | 2 |
2024-11-18T18:24:07.654829+00:00 | 2012-07-05T06:20:54 | 91c767df88d437bdf62d27f59d4185c25f04cf2c | {
"blob_id": "91c767df88d437bdf62d27f59d4185c25f04cf2c",
"branch_name": "HEAD",
"committer_date": "2012-07-05T06:20:54",
"content_id": "f645242f995dbc6bf6eb39122dad2dbdf123cc33",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "b4b36c26891cb94f6ca1c9d05c013443f91a4739",
"extension": "h",
"filename": "fs.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 4156239,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4509,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/fs/fs.h",
"provenance": "stackv2-0003.json.gz:405504",
"repo_name": "capel/brazos",
"revision_date": "2012-07-05T06:20:54",
"revision_id": "553f9d1d7f2c6e852d5e1f24e844d569115897cc",
"snapshot_id": "9bb72a0c25dd7afd65f3d4a10baa2b1beb575a61",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/capel/brazos/553f9d1d7f2c6e852d5e1f24e844d569115897cc/fs/fs.h",
"visit_date": "2016-09-11T14:59:56.369866"
} | stackv2 | #ifndef FS_H
#define FS_H
#define NAME_LEN 8
#define PATH_LEN 32
#define MAX_ARGS 32
#include <stdlib.h>
#include <stdbool.h>
#include <dir.h>
typedef struct Block Block;
typedef const char Link;
typedef struct Directory Directory;
typedef struct Entry Entry;
typedef struct File File;
typedef struct Node Node;
typedef struct fs_state fs_state;
Directory* dir_ctor(Block * b);
File* file_ctor(int size, Block** blocks, int num_args);
Link* link_ctor(const char* path);
Block* block_ctor(int bid);
Entry* entry_ctor(const char* path, Node* n);
#define STYPE_STDIN 0
#define STYPE_STDOUT 1
#define STYPE_BLOCK 3
File* stdin_ctor();
File* stdout_ctor();
// Should be called using DTOR()
void dir_dtor(Directory* d);
void link_dtor(Link* l);
void block_dtor(Block* b);
void entry_dtor(Entry* e);
void file_dtor(File* f);
void node_dtor(Node* n);
char* dir_serialize(Directory* n);
char* link_serialize(Link* n);
char* block_serialize(Block* n);
char* entry_serialize(Entry* n);
char* file_serialize(File* n);
char* node_serialize(Node* n);
#define DTOR(o) do { if (o) _Generic((o), \
Directory*: dir_dtor, \
Link*: link_dtor, \
Block*: block_dtor, \
Node*: node_dtor, \
Entry*: entry_dtor) \
(o); } while(0)
Node* dir2Node(Directory* d);
Node* link2Node(Link* l);
Node* file2Node(File* f);
bool is_dir(Node* n);
bool is_link(Node* n);
bool is_file(Node* n);
Directory* get_dir(Node *n);
File* get_file(Node *n);
Link* get_link(Node *n);
int node_type(Node* n);
#define NODE(o) _Generic((o), \
Directory*: dir2Node, \
Link*: link2Node, \
File*: file2Node)(o)
Node* walk(const char * path);
Node* root();
int bid_alloc(void);
#define SUCCESS 0
#define E_EXISTS -50
#define E_NOTFOUND -51
#define E_FULL -52
#define E_INVAL -53
#define E_CANT -54
#define E_BADFD -55
// Adds a node to the directory with the specified name.
// It takes ownership of the Node.
// Returns:
// E_FULL: No space left in directory
// E_EXISTS: A node with that name already exists
// SUCCESS
int dir_add(Directory* dir, const char* name, Node* n);
// Removes the node with the name from the directory.
// It then destroys the node. If this is not the intended behavior,
// use dir_move to transfer ownership.
// Returns
// E_NOTFOUND: No node by that name was found
// SUCCESS
int dir_remove(Directory* dir, const char* name);
// Transfers ownership of the node with the given name from src to dst.
// E_NOTFOUND: No node by that name was found in src
// Returns
// E_FULL: No space left in dst
// E_EXISTS: A node with that name already exists in dst
// SUCCESS
int dir_move(Directory* src, Directory* dst, const char* name);
// Looks up a name in dir, and returns a node it finds.
// Returns NULL if nothing was found.
// Returns Node* on success
Node* dir_lookup(Directory* dir, const char* name);
int dir_stat(Directory* dir, int pos, struct _stat_entry* out);
#define Read(b, pos, buf, nbytes) (_Generic((b), \
File*: file_read, \
Block*: block_read, \
Link*: link_read,\
Node*: node_read))(b, pos, buf, nbytes)
#define Write(b, pos, buf, nbytes) (_Generic((b), \
File*: file_write, \
Block*: block_write, \
Link*: link_write,\
Node*: node_write))(b, pos, buf, nbytes)
#define Sync(o) (_Generic((o), \
File*: file_sync, \
Block*: block_sync, \
Directory*: dir_sync,\
Link*: link_sync,\
Node*: node_sync))(o)
#define Size(o) (_Generic((o), \
File*: file_size, \
Block*: block_size, \
Directory*: dir_size,\
Link*: link_size,\
Node*: node_size))(o)
int file_read(File* b, size_t pos, void *buf, size_t nbytes);
int dir_read(Directory* d, size_t pos, void *buf, size_t nbytes);
int link_read(Link* b, size_t pos, void *buf, size_t nbytes);
int block_read(Block* b, size_t pos, void *buf, size_t nbytes);
int node_read(Node* b, size_t pos, void *buf, size_t nbytes);
int block_write(Block* b, size_t pos, const void *buf, size_t nbytes);
int file_write(File* b, size_t pos, const void *buf, size_t nbytes);
int link_write(Link* b, size_t pos, const void *buf, size_t nbytes);
int node_write(Node* b, size_t pos, const void *buf, size_t nbytes);
// always fails
int dir_write(Directory* b, size_t pos, const void *buf, size_t nbytes);
int dir_sync(Directory* d);
int block_sync(Block* b);
int file_sync(File* b);
int link_sync(Link* b);
int node_sync(Node* b);
int dir_size(Directory* d);
int block_size(Block* b);
int file_size(File* b);
int link_size(Link* b);
int node_size(Node* b);
#endif
| 2.453125 | 2 |
2024-11-18T18:24:08.486553+00:00 | 2020-01-15T04:24:36 | fa7de3c83ec4cd1296bb41e9892bba0bb912a197 | {
"blob_id": "fa7de3c83ec4cd1296bb41e9892bba0bb912a197",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-15T04:24:36",
"content_id": "6a1e432a01898e6d68421be9ad329f28bed59be1",
"detected_licenses": [
"MIT"
],
"directory_id": "3d6c5aebfd9dcbd4c2f0c9e7031ab7eb88e9be46",
"extension": "c",
"filename": "adapter_example.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 230332219,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4054,
"license": "MIT",
"license_type": "permissive",
"path": "/src/adapter_example.c",
"provenance": "stackv2-0003.json.gz:405892",
"repo_name": "Berbardo/VL53L1_Example",
"revision_date": "2020-01-15T04:24:36",
"revision_id": "55ce7cfe60e8ad8d74e28ea169230b39d1673c08",
"snapshot_id": "c3ddee348c5ae08ca4e9f6a77559c1654b509905",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Berbardo/VL53L1_Example/55ce7cfe60e8ad8d74e28ea169230b39d1673c08/src/adapter_example.c",
"visit_date": "2020-11-30T06:29:15.690913"
} | stackv2 | /**
* @file adapter_example.c
*
* @brief Adapter example code for VL53L1 ToF sensors.
*
* @author Lucas Schneider <[email protected]>
* @author Bernardo Coutinho <[email protected]>
*
* @date 01/2020
*/
#include <stdbool.h>
#include <stdint.h>
#include "adapter_example.h"
#include "vl53l1.h"
#include "mcu.h"
#include "main.h"
#include "i2c.h"
/*****************************************
* Private Constants
*****************************************/
#define VL53L1_DEFAULT_COMM_SPEED_KHZ 100
#define TIMING_BUDGET_US 50000
#define INIT_RESET_SLEEP_TIME_MS 10
#define MAX_RANGE_MM 4000
/*****************************************
* Private Variables
*****************************************/
static VL53L1_Dev_t sensors[] = {
{ // 0
.comms_speed_khz = VL53L1_DEFAULT_COMM_SPEED_KHZ,
.I2cHandle = &TARGET_I2C_HANDLE,
.xshut_port = FIRST_SENSOR_GPIOx,
.xshut_pin = FIRST_SENSOR_GPIO_PIN
},
{ // 1
.comms_speed_khz = VL53L1_DEFAULT_COMM_SPEED_KHZ,
.I2cHandle = &TARGET_I2C_HANDLE,
.xshut_port = SECOND_SENSOR_GPIOx,
.xshut_pin = SECOND_SENSOR_GPIO_PIN
},
{ // 2
.comms_speed_khz = VL53L1_DEFAULT_COMM_SPEED_KHZ,
.I2cHandle = &TARGET_I2C_HANDLE,
.xshut_port = THIRD_SENSOR_GPIOx,
.xshut_pin = THIRD_SENSOR_GPIO_PIN
}
};
static VL53L1_RangingMeasurementData_t sensors_measurement[DS_AMOUNT];
static VL53L1_CalibrationData_t sensors_calibration[DS_AMOUNT];
static uint16_t actual_range[] = {MAX_RANGE_MM, MAX_RANGE_MM, MAX_RANGE_MM};
static const uint8_t used_sensors[] = {1, 0, 1};
static const uint8_t i2c_addresses[] = {0x30, 0x34, 0x38};
__attribute__((used)) static uint8_t sensors_status[] = {0, 0, 0};
static const VL53L1_DistanceModes sensor_distance_mode[] = {VL53L1_DISTANCEMODE_MEDIUM, VL53L1_DISTANCEMODE_MEDIUM, VL53L1_DISTANCEMODE_MEDIUM};
static const uint32_t sensor_timing_budget_us[] = {TIMING_BUDGET_US, TIMING_BUDGET_US, TIMING_BUDGET_US};
/*****************************************
* Public Functions Bodies Definitions
*****************************************/
uint8_t distance_sensors_adapter_init(void) {
TARGET_I2C_INIT();
VL53L1_Error global_status = VL53L1_ERROR_NONE;
// desabilita todos, independente de quantos vai usar
for (int i = 0; i < DS_AMOUNT; i++) {
vl53l1_turn_off(&(sensors[i]));
}
mcu_sleep(INIT_RESET_SLEEP_TIME_MS);
for (int i = 0; i < DS_AMOUNT; i++) {
if (!used_sensors[i]) {
continue;
}
VL53L1_Error status = VL53L1_ERROR_NONE;
VL53L1_Dev_t* p_device = &(sensors[i]);
vl53l1_set_default_config(p_device);
p_device->distance_mode = sensor_distance_mode[i];
p_device->timing_budget_us = sensor_timing_budget_us[i];
vl53l1_turn_on(p_device);
if (status == VL53L1_ERROR_NONE) {
status = VL53L1_SetDeviceAddress(p_device, i2c_addresses[i]);
}
if (status == VL53L1_ERROR_NONE) {
p_device->I2cDevAddr = i2c_addresses[i];
status = vl53l1_init(p_device, &sensors_calibration[i]);
}
if (status == VL53L1_ERROR_NONE) {
p_device->present = 1;
p_device->calibrated = 1;
}
global_status |= status;
}
if (global_status == VL53L1_ERROR_NONE) {
return 0;
}
return 1;
}
uint8_t distance_sensors_adapter_update(void) {
uint8_t status = 0;
for (int i = 0; i < DS_AMOUNT; i++) {
if (!used_sensors[i]) {
continue;
}
sensors_status[i] =
vl53l1_update_reading(&(sensors[i]), &(sensors_measurement[i]), &(actual_range[i]), MAX_RANGE_MM);
if (sensors_status[i] != 0) {
status |= 1 << (i + 1);
}
}
return status;
}
uint16_t distance_sensors_adapter_get(distance_sensor_position_t sensor) {
if ((sensors[(int) sensor]).present) {
return actual_range[(int) sensor];
}
return -1;
}
| 2.171875 | 2 |
2024-11-18T18:24:08.869265+00:00 | 2019-10-11T11:19:42 | 0f6d347a506d29fecde20c901374a65ffd0887af | {
"blob_id": "0f6d347a506d29fecde20c901374a65ffd0887af",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-11T11:19:42",
"content_id": "74c933a7b7e9a178212c68dcd3fe6c9c52f30aa8",
"detected_licenses": [
"BSD-2-Clause",
"CC0-1.0"
],
"directory_id": "d33a52804719c2c6dd276dc5aee0aa6db23ffe35",
"extension": "c",
"filename": "screen.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 4356996,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13373,
"license": "BSD-2-Clause,CC0-1.0",
"license_type": "permissive",
"path": "/firmware/src/screen.c",
"provenance": "stackv2-0003.json.gz:406406",
"repo_name": "hairymnstr/oggbox",
"revision_date": "2019-10-11T11:19:42",
"revision_id": "6628aab0a7282a490fe611a49dad5456a3789205",
"snapshot_id": "43156b85f284f50a5bcc2bce14a22c7fe653783e",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/hairymnstr/oggbox/6628aab0a7282a490fe611a49dad5456a3789205/firmware/src/screen.c",
"visit_date": "2020-03-31T11:54:26.967387"
} | stackv2 | /*
* This file is part of the oggbox project.
*
* Copyright (C) 2012 Nathan Dumont <[email protected]>
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/f1/bkp.h>
#include <libopencm3/stm32/timer.h>
#include <libopencm3/stm32/spi.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "screen.h"
#include "config.h"
extern const char *font[];
extern const char *font_portrait[];
unsigned char frame_buffer[128*64/8];
// unsigned char frame_buffer[132*8];
int frame_cursor = 0;
void lcdCommand(unsigned char cmd) {
// int i;
//while(lcdStatus() & LCD_BUSY) {__asm__("nop\n\t");}
//gpio_set_mode(LCD_DATA_PORT, GPIO_MODE_OUTPUT_10_MHZ,
// GPIO_CNF_OUTPUT_PUSHPULL, LCD_DATA_MASK);
//gpio_clear(LCD_DATA_PORT, LCD_DATA_MASK);
//gpio_set(LCD_DATA_PORT, cmd);
// write mode = low
//gpio_clear(LCD_RW_PORT, LCD_RW_PIN);
// command mode = low
gpio_clear(LCD_DC_PORT, LCD_DC_PIN);
gpio_clear(LCD_CS_PORT, LCD_CS_PIN);
//gpio_set(LCD_E_PORT, LCD_E_PIN);
spi_send(LCD_SPI, cmd);
// for(i=0;i<100;i++) {__asm__("nop\n\t");}
while(!(SPI_SR(LCD_SPI) & SPI_SR_TXE));
while((SPI_SR(LCD_SPI) & SPI_SR_BSY));
//gpio_clear(LCD_E_PORT, LCD_E_PIN);
gpio_set(LCD_CS_PORT, LCD_CS_PIN);
//gpio_set_mode(LCD_DATA_PORT, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, LCD_DATA_MASK);
}
void lcdData(unsigned char d) {
// int i;
//while(lcdStatus() & LCD_BUSY) {__asm__("nop\n\t");}
//gpio_set_mode(LCD_DATA_PORT, GPIO_MODE_OUTPUT_10_MHZ,
// GPIO_CNF_OUTPUT_PUSHPULL, LCD_DATA_MASK);
//gpio_clear(LCD_DATA_PORT, LCD_DATA_MASK);
//gpio_set(LCD_DATA_PORT, d);
// write mode = low
//gpio_clear(LCD_RW_PORT, LCD_RW_PIN);
// data mode = high
gpio_set(LCD_DC_PORT, LCD_DC_PIN);
gpio_clear(LCD_CS_PORT, LCD_CS_PIN);
//gpio_set(LCD_E_PORT, LCD_E_PIN);
spi_send(LCD_SPI, d);
while(!(SPI_SR(LCD_SPI) & SPI_SR_TXE));
// for(i=0;i<100;i++) {__asm__("nop\n\t");}
while((SPI_SR(LCD_SPI) & SPI_SR_BSY));
//gpio_clear(LCD_E_PORT, LCD_E_PIN);
gpio_set(LCD_CS_PORT, LCD_CS_PIN);
//gpio_set_mode(LCD_DATA_PORT, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, LCD_DATA_MASK);
}
// unsigned char lcdStatus() {
// unsigned char rv;
// int i;
// gpio_set(LCD_RW_PORT, LCD_RW_PIN);
// gpio_clear(LCD_DC_PORT, LCD_DC_PIN);
//
// gpio_clear(LCD_CS_PORT, LCD_CS_PIN);
// gpio_set(LCD_E_PORT, LCD_E_PIN);
//
// for(i=0;i<100;i++) {__asm__("nop\n\t");}
//
// rv = gpio_port_read(LCD_DATA_PORT) & LCD_DATA_MASK;
// gpio_clear(LCD_E_PORT, LCD_E_PIN);
// gpio_set(LCD_CS_PORT, LCD_CS_PIN);
// return rv;
// }
void screen_init() {
volatile int i;
// hardware layout specific optimisations here
// if you change the pinout these need to be changed
rcc_periph_clock_enable(RCC_SPI3);
//rcc_peripheral_enable_clock(&RCC_APB1ENR, RCC_APB1ENR_SPI3EN);
gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ,
GPIO_CNF_OUTPUT_PUSHPULL,
LCD_RST_PIN | LCD_CS_PIN | LCD_DC_PIN);
gpio_set_mode(LCD_BL_PORT, GPIO_MODE_OUTPUT_2_MHZ,
GPIO_CNF_OUTPUT_PUSHPULL, LCD_BL_PIN);
gpio_set_mode(LCD_MOSI_PORT, GPIO_MODE_OUTPUT_50_MHZ,
GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, LCD_MOSI_PIN);
gpio_set_mode(LCD_SCK_PORT, GPIO_MODE_OUTPUT_50_MHZ,
GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, LCD_SCK_PIN);
gpio_clear(LCD_RST_PORT, LCD_RST_PIN);
gpio_set(LCD_CS_PORT, LCD_CS_PIN);
gpio_set(LCD_DC_PORT, LCD_DC_PIN);
gpio_clear(LCD_BL_PORT, LCD_BL_PIN);
/* Set up the serial port */
/* configure the SPI peripheral */
spi_set_unidirectional_mode(LCD_SPI); /* we want to send only */
spi_disable_crc(LCD_SPI); /* no CRC for this slave */
spi_set_dff_8bit(LCD_SPI); /* 8-bit dataword-length */
spi_set_full_duplex_mode(LCD_SPI); /* otherwise it's read only */
spi_enable_software_slave_management(LCD_SPI); /* we want to handle the CS signal in software */
spi_set_nss_high(LCD_SPI);
spi_set_baudrate_prescaler(LCD_SPI, SPI_CR1_BR_FPCLK_DIV_4);
spi_set_master_mode(LCD_SPI); /* we want to control everything and generate the clock -> master */
spi_set_clock_polarity_1(LCD_SPI); /* sck idle state high */
spi_set_clock_phase_1(LCD_SPI); /* bit is taken on the second (rising edge) of sck */
spi_disable_ss_output(LCD_SPI);
spi_enable(LCD_SPI);
for(i=0;i<10000;i++);
gpio_set(LCD_RST_PORT, LCD_RST_PIN);
for(i=0;i<10000;i++);
lcdCommand(LCD_BIAS_SEVENTH);
lcdCommand(LCD_DIRECTION_FWD);
lcdCommand(LCD_COMMON_FWD);
lcdCommand(LCD_VREG_SET);
lcdCommand(LCD_CONTRAST_HI);
lcdCommand(LCD_CONTRAST_LO(lcd_get_contrast()));
lcdCommand(LCD_POWER_SETUP);
lcdCommand(LCD_DISPLAY_ON);
}
int screen_shutdown() {
gpio_clear(LCD_RST_PORT, LCD_RST_PIN);
gpio_clear(LCD_BL_PORT, LCD_BL_PIN);
spi_disable(LCD_SPI);
return 0;
}
void screen_backlight(unsigned short on) {
if(on) {
gpio_set(LCD_BL_PORT, LCD_BL_PIN);
} else {
gpio_clear(LCD_BL_PORT, LCD_BL_PIN);
}
}
void lcd_set_contrast(unsigned char contrast) {
contrast = contrast & 0x3F;
BKP_DR1 = contrast;
lcdCommand(LCD_CONTRAST_HI);
lcdCommand(LCD_CONTRAST_LO(contrast));
}
unsigned char lcd_get_contrast() {
unsigned char con;
con = BKP_DR1;
if(con == 0) {
con = 32;
}
return con;
}
// void lcdClear() {
// int i, j;
//
// for(i=0;i<8;i++) {
// lcdCommand(LCD_PAGE_SET(i));
// lcdCommand(LCD_COLUMN_SET_HI(0));
// lcdCommand(LCD_COLUMN_SET_LO(0));
// for(j=0;j<128;j++) {
// lcdData(0x00);
// }
// }
// lcdCommand(LCD_PAGE_SET(0));
// lcdCommand(LCD_COLUMN_SET_HI(0));
// lcdCommand(LCD_COLUMN_SET_LO(0));
// }
//
// void lcdPrint(char *msg, char line) {
// int i, j;
// for(i=0;i<21;i++) {
// if(msg[i] == 0) {
// break;
// }
// lcdCommand(LCD_PAGE_SET(7-line));
// lcdCommand(LCD_COLUMN_SET_HI(i*6));
// lcdCommand(LCD_COLUMN_SET_LO(i*6));
// for(j=0;j<6;j++) {
// lcdData(font[msg[i]][j]);
// }
// }
// }
// void lcdBlit(uint8_t *img, unsigned char rows, unsigned char cols, unsigned char x, unsigned char y) {
// lcdBlitPortrait(img, rows, cols, x, y);
// }
// void lcdBlitPortrait(uint8_t *img, unsigned char rows, unsigned char cols,
// unsigned char x, unsigned char y) {
// int j;
// lcdCommand(LCD_PAGE_SET(x/8));
// lcdCommand(LCD_COLUMN_SET_HI(4 + y));
// lcdCommand(LCD_COLUMN_SET_LO(4 + y));
// for(j=0;j<8;j++) {
// lcdData(img[j]);
// }
// }
void frameCharAt(uint8_t x, uint8_t y, char c) {
int i;
y &= 7;
for(i=0;i<FONT_WIDTH;i++) {
if(x + i < SCREEN_WIDTH) {
frame_buffer[y*SCREEN_WIDTH+x+i] = font[(unsigned char)c][i];
}
}
}
void frame_char_at_portrait(int x, int y, char c) {
uint8_t oldval;
int i;
int shift;
int xb;
// x = width (64 pixels)
// y = height (128 pixels)
if((x > 63) || (x < -5) || (y > 127) || (y < -7)) { // don't write out of the frame buffer
return;
}
shift = x % 8;
if(shift < 0)
shift += 8;
xb = x/8;
if(x < 0)
xb--;
for(i=0;i<8;i++) {
if(y + i > 127) {
return; // don't leave the frame
}
if(y + i >= 0) {
if(shift < 2) {
// all bits are in the same byte
oldval = frame_buffer[(7 - xb) * SCREEN_WIDTH + y + i + SCREEN_OFFSET];
oldval &= ~(0x3f << shift);
oldval |= (font_portrait[(unsigned char)c][i] & 0x3f) << shift;
frame_buffer[(7 - xb) * SCREEN_WIDTH + y + i + SCREEN_OFFSET] = oldval;
} else {
// character spans two pages
if(xb >= 0) {
oldval = frame_buffer[(7 - xb) * SCREEN_WIDTH + y + i + SCREEN_OFFSET];
oldval &= ~(0x3f << shift);
oldval |= (font_portrait[(unsigned char)c][i] & 0x3f) << shift;
frame_buffer[(7 - xb) * SCREEN_WIDTH + y + i + SCREEN_OFFSET] = oldval;
}
if(xb < 7) {
oldval = frame_buffer[(7 - xb - 1) * SCREEN_WIDTH + y + i + SCREEN_OFFSET];
oldval &= ~(0x3f >> (8 - shift));
oldval |= (font_portrait[(unsigned char)c][i] & 0x3f) >> (8 - shift);
frame_buffer[(7 - xb - 1) * SCREEN_WIDTH + y + i + SCREEN_OFFSET] = oldval;
}
}
}
}
}
void frame_clear() {
int i;
frame_cursor = 0;
for(i=0;i<SCREEN_WIDTH * (SCREEN_HEIGHT/8);i++) {
frame_buffer[i] = 0;
}
}
// void framePrint(const char *msg) {
// //
// }
void frame_print_at(int x, int y, const char *msg) {
while(*msg) {
frame_char_at_portrait(x,y,*msg++);
x += 6;
}
}
// void frame_print_at(uint8_t x, uint8_t y, const char *msg) {
// y = y / 8;
//
// while(*msg) {
// frameCharAt(x,y,*msg);
// x += FONT_WIDTH;
// msg++;
// }
// }
void frame_bar_display(uint8_t x, uint8_t y, uint8_t len, uint8_t percent) {
int i, filled;
y = y >> 3;
if((len + x) > SCREEN_WIDTH) {
len = SCREEN_WIDTH - x;
}
filled = len;
filled *= percent;
filled /= 100;
for(i=0;i<filled;i++) {
// if(i < filled) {
frame_buffer[y*SCREEN_WIDTH+x+i] = 0x7e;
// } else {
// frame_buffer[y*SCREEN_WIDTH+x+i] = 0x00;
// }
}
}
void frame_vline_at(uint8_t x, uint8_t y, uint8_t len) {
int row;
row = y/8;
frame_buffer[row*SCREEN_WIDTH+x] = (1 << (y %8)) - 1;
len -= (y % 8);
while(len > 8) {
row++;
frame_buffer[row*SCREEN_WIDTH+x] = 0xff;
len -= 8;
}
if(len > 0) {
row++;
frame_buffer[row*SCREEN_WIDTH+x] = 0xff ^ ((1 << (y %8)) - 1);
}
}
// void frame_show() {
// int i;
// lcdCommand(LCD_PAGE_SET(0));
// lcdCommand(LCD_COLUMN_SET_HI(0));
// lcdCommand(LCD_COLUMN_SET_LO(0));
// for(i=0;i<(8 * 132);i++) {
// lcdData(frame_buffer[i]);
// }
// }
void frame_show() {
int i, j;
for(i=0;i<8;i++) {
lcdCommand(LCD_PAGE_SET(i));
lcdCommand(LCD_COLUMN_SET_HI(0));
lcdCommand(LCD_COLUMN_SET_LO(4));
for(j=0;j<128;j++) {
lcdData(frame_buffer[(7-i)*SCREEN_WIDTH+j]);
}
}
}
void lcd_splash(const char *image[]) {
int i, j;
for(i=0;i<8;i++) {
lcdCommand(LCD_PAGE_SET(i));
lcdCommand(LCD_COLUMN_SET_HI(0));
lcdCommand(LCD_COLUMN_SET_LO(4));
for(j=0;j<128;j++) {
lcdData(image[(7-i)][j]);
}
}
lcdCommand(LCD_PAGE_SET(0));
lcdCommand(LCD_COLUMN_SET_HI(0));
lcdCommand(LCD_COLUMN_SET_LO(4));
}
void frame_draw_h_line(int x, int y, int l, int line_type) {
int i;
int d;
if(l == 0) {
return;
}
if(l < 0) {
x = x + l;
l = l * -1;
}
l--; // for a 10 pixel line we count from 0 to 9 pixels
if((x > 63) || (x + l < 0)) {
return;
}
if((y > 127) || (y < 0)) {
return;
}
if(!((line_type==FILL_TYPE_BLACK) ||
(line_type==FILL_TYPE_WHITE) ||
(line_type==FILL_TYPE_INVERT))) {
return;
}
if(x < 0) {
l += x;
x = 0;
}
if(x + l > 63) {
l = 63 - x;
}
// right. Now we're happy to actually draw a line
for(i=x/8;i<(x+l)/8+1;i++) {
d = 0xff;
if((i*8) < x) {
d = (0xff << (x % 8)) & d;
}
if(((i+1)*8) >= (x+l)) {
d = (0xff >> (7 - ((x+l) % 8))) & d;
}
if(line_type == FILL_TYPE_BLACK) {
frame_buffer[y + ((7 - i) * 128)] |= d;
} else if(line_type == FILL_TYPE_WHITE) {
frame_buffer[y + ((7 - i) * 128)] &= (d ^ 0xff);
} else {
frame_buffer[y + ((7 - i) * 128)] ^= d;
}
}
}
void frame_draw_v_line(int x, int y, int l, int line_type) {
int i;
int d;
if(l == 0) {
return;
}
if(l < 0) {
y = y + l;
l *= -1;
}
l--;
if((x > 63) || (x < 0)) {
return;
}
if((y > 127) || ((y + l) < 0)) {
return;
}
if(!((line_type==FILL_TYPE_BLACK) ||
(line_type==FILL_TYPE_WHITE) ||
(line_type==FILL_TYPE_INVERT))) {
return;
}
if(y < 0) {
l += y;
y = 0;
}
if((y + l) > 127) {
l = (127 - y);
}
d = 1 << (x % 8);
for(i=y;i<y+l;i++) {
if(line_type == FILL_TYPE_BLACK) {
frame_buffer[i + ((7 - (x % 8)) * 128)] |= d;
} else if(line_type == FILL_TYPE_WHITE) {
frame_buffer[i + ((7 - (x % 8)) * 128)] &= (d ^ 0xff);
} else {
frame_buffer[i + ((7 - (x % 8)) * 128)] ^= d;
}
}
}
void frame_draw_rect(int x, int y, int width, int height, int fill, int line_type) {
int i;
if(line_type != FILL_TYPE_NONE) {
frame_draw_h_line(x, y, width, line_type);
frame_draw_h_line(x, y+height-1, width, line_type);
frame_draw_v_line(x, y+1, height-1, line_type);
frame_draw_v_line(x+width-1, y+1, height-1, line_type);
}
if(fill != FILL_TYPE_NONE) {
for(i=y+1;i<y+(height-1);i++) {
frame_draw_h_line(x+1, i, width-2, fill);
}
}
}
| 2.0625 | 2 |
2024-11-18T18:24:08.988598+00:00 | 2021-04-04T21:05:55 | c823491f0e9603f0b5c385869945b529013c82d9 | {
"blob_id": "c823491f0e9603f0b5c385869945b529013c82d9",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-04T21:05:55",
"content_id": "20a847e1e5925fb472615a7c626890cf6e0799cd",
"detected_licenses": [
"MIT"
],
"directory_id": "cb57a4a4d960ae6bacee27cb701620597dcf979e",
"extension": "h",
"filename": "ks_treemapnode.h",
"fork_events_count": 0,
"gha_created_at": "2019-06-16T15:37:18",
"gha_event_created_at": "2019-12-09T23:18:07",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 192208014,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6323,
"license": "MIT",
"license_type": "permissive",
"path": "/include/ks_treemapnode.h",
"provenance": "stackv2-0003.json.gz:406534",
"repo_name": "krglaws/KyleStructs",
"revision_date": "2021-04-04T21:05:55",
"revision_id": "90d0a1d6e953ae6104085eecbd42f09e649e2210",
"snapshot_id": "c7f9f5edc2285ace2cf5122fd44c24a33775d003",
"src_encoding": "UTF-8",
"star_events_count": 25,
"url": "https://raw.githubusercontent.com/krglaws/KyleStructs/90d0a1d6e953ae6104085eecbd42f09e649e2210/include/ks_treemapnode.h",
"visit_date": "2021-06-17T08:28:24.134811"
} | stackv2 | #ifndef _KS_TREEMAPNODE_H_
#define _KS_TREEMAPNODE_H_
/* ------------------------------------
* ks_treemapnode_new():
* Creates a new ks_treemapnode.
*
* Inputs:
* ks_datacont* key - the key
* ks_datacont* value - the value
*
* Returns:
* ks_treemapnode* tmn - (NULL) if either of the parameters is NULL.
* - a ks_treemapnode containing 'key' and 'value'.
*/
ks_treemapnode* ks_treemapnode_new(const ks_datacont* key, const ks_datacont* value);
/* ----------------------------------
* ks_treemapnode_delete():
* Deletes a ks_treemapnode and its 'key' and 'value' members.
*
* Inputs:
* ks_treemapnode* tmn - the ks_treemapnode to be deleted
*
* Returns:
* void
*/
void ks_treemapnode_delete(ks_treemapnode* tmn);
/* ----------------------------------
* ks_treemapnode_copy():
* Creates a copy of a treemapnode* and its ks_datacont*.
*
* Inputs:
* ks_treempanode* tmn - the ks_treemapnode to be copied.
*
* Returns:
* ks_treemapnode* - a copy of the ks_treemapnode*.
*
* Notes:
* ks_treemapnode_copy() only copies the ks_treemapnode itself
* and its ks_datacont, but not any other connected ks_treemapnodes.
*/
ks_treemapnode* ks_treemapnode_copy(const ks_treemapnode* tmn);
/* -----------------------------------
* ks_treemapnode_delete_all():
* Deletes a ks_treemapnode, its 'key' and 'value' members, and recursively
* deletes its 'right' and 'left' members.
*
* Inputs:
* ks_treemapnode* tmn - the ks_treemapnode being deleted.
*
* Returns:
* void
*/
void ks_treemapnode_delete_all(ks_treemapnode* tmn);
/* ----------------------------------
* ks_treemapnode_copy_all():
* Creates a copy of a treemapnode*, its ks_datacont*, and any
* connected ks_treemapnodes.
*
* Inputs:
* ks_treempanode* tmn - the ks_treemapnode to be copied.
*
* Returns:
* ks_treemapnode* - a copy of the ks_treemapnode*.
*/
ks_treemapnode* ks_treemapnode_copy_all(const ks_treemapnode* tmn);
/* ----------------------------------
* ks_treemapnode_add():
* Add a key/value pair to a ks_treemapnode tree.
*
* Inputs:
* ks_treemapnode* tmn - the treemap to be added to
* ks_datacont* key - the key
* ks_datacont* value - the value that the key maps to
*
* Returns:
* int result - (-1) if any params are NULL.
* - (0) pair added successfully
* - (1) already contains pair, old key and value replaced.
*
* Notes:
* If the key-value pair is successfully added to the ks_treemapnode (0), the user code
* must not delete or modify 'key' or 'value', otherwise undefined behavior could
* ensue. If a key with the same value was already present (1), the old key and value
* have been deleted and replaced by the new key and value. If the pair was not added
* to the ks_treemapnode (-1), the user code is responsible for deleting both when they are
* no longer needed.
*/
int ks_treemapnode_add(ks_treemapnode* tmn, const ks_datacont* key, const ks_datacont* value);
/* ---------------------------
* ks_treemapnode_remove():
* Find key/value pair and delete it.
*
* Inputs:
* ks_treemapnode** tmn - the ks_treemapnode to be operated on
* ks_datacont* key - the key to be removed
*
* Returns:
* int result - (-1) if either param is NULL, or 'key' could not be found.
* - (0) pair removed successfully.
*
* Notes:
* Because the key-value pair that is being removed could be located in the root node,
* 'tmn' must be passed as a nested pointer so that it can be set to a different node,
* or NULL if there are no nodes left after the removal. Also: 'key' is not consumed by
* this procedure, it is only used to locate another ks_datacont containing the same data.
*/
int ks_treemapnode_remove(ks_treemapnode** tmn, const ks_datacont* key);
/* ---------------------------
* ks_treemapnode_get():
* Get the value from a ks_treemapnode by key.
*
* Inputs:
* ks_treemapnode* tmn - the ks_treemapnode to be operated on.
* ks_datacont* key - the key used to retrieve a value.
*
* Returns:
* ks_datacont* value - (NULL) if either param is NULL, or if 'key' could not be found.
* - the value mapped to by the key.
*
* Notes:
* The ks_datacont returned by this function is a pointer to the original contained within
* the treemap, so it should not be deleted or modified by client code. Also:
* 'key' is not consumed by this procedure, it is only used to locate another ks_datacont
* containing the same data.
*/
ks_datacont* ks_treemapnode_get(const ks_treemapnode* tmn, const ks_datacont* key);
/* --------------------------
* ks_treemapnode_get_key():
* Retrieves a key located at a specified index within the ks_treemapnode.
*
* Inputs:
* ks_treemapnode* tmn - the ks_treemapnode being retrieved from.
* int index - the index of the key being retrieved. Negative values
* will wrap around.
*
* Returns:
* ks_datacont* key - (NULL) if 'index' is OOB, or if 'tmn' is NULL.
* - the key located at 'index'.
* Notes:
* The ks_datacont returned by this function is a pointer to the original contained within
* the list, so it should not be deleted or modified by client code.
*/
ks_datacont* ks_treemapnode_get_key(const ks_treemapnode* tmn, int index);
/* ----------------------------
* ks_treemapnode_count():
* Count the number of key/value pairs stored within a ks_treemapnode.
*
* Inputs:
* ks_treemapnode* tmn - the ks_treemapnode to be operated on.
*
* Returns:
* unsigned int - >= (0) the number of pairs found in the ks_treemapnode, (0) if 'tmn' is NULL.
*/
unsigned int ks_treemapnode_count(const ks_treemapnode* tmn);
/* --------------------------
* ks_treemapnode_height():
* Calculate the maximum height of a ks_treemapnode tree.
*
* Inputs:
* ks_treemapnode* tmn - the ks_treemapnode to be operated on.
*
* Returns:
* unsigned int - >= (0) the height of the tree, (0) if 'tmn' is NULL.
*/
unsigned int ks_treemapnode_height(const ks_treemapnode* tmn);
/* --------------------------
* ks_treemapnode_balance():
* Balances a ks_treemapnode* tree to ensure optimal performance.
*
* Inputs:
* ks_treemapnode* tmn - the root of the ks_treemapnode being balanced.
*
* Returns:
* ks_treemapnode* - a balanced treemapnode*.
*/
ks_treemapnode* ks_treemapnode_balance(ks_treemapnode* tmn);
#endif
| 2.53125 | 3 |
2024-11-18T18:24:09.051145+00:00 | 2016-02-18T10:48:55 | 299ceff9665f97df3a7f2e257dc43d539ca76f39 | {
"blob_id": "299ceff9665f97df3a7f2e257dc43d539ca76f39",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-18T10:48:55",
"content_id": "d122b7f21f29b2aaf08d1854ed0fdcb0f0078482",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "74ca0502be3ea74703928bfa458e87a4335866f9",
"extension": "c",
"filename": "symtab.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 52000870,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1472,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/isode-8.0/others/quipu/uips/sd/symtab.c",
"provenance": "stackv2-0003.json.gz:406666",
"repo_name": "Kampbell/ISODE",
"revision_date": "2016-02-18T10:48:55",
"revision_id": "affd47713e792f7797150f237b10764577e5e067",
"snapshot_id": "a80682dab1ee293a2711a687fc10660aae546933",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/Kampbell/ISODE/affd47713e792f7797150f237b10764577e5e067/isode-8.0/others/quipu/uips/sd/symtab.c",
"visit_date": "2021-01-10T15:56:44.788906"
} | stackv2 |
#ifndef lint
static char *rcsid = "$Header: /xtel/isode/isode/others/quipu/uips/sd/RCS/symtab.c,v 9.0 1992/06/16 12:45:08 isode Rel $";
#endif
/*
* $Header: /xtel/isode/isode/others/quipu/uips/sd/RCS/symtab.c,v 9.0 1992/06/16 12:45:08 isode Rel $
*
* $Log: symtab.c,v $
* Revision 9.0 1992/06/16 12:45:08 isode
* Release 8.0
*
*/
#include "general.h"
#include "symtab.h"
put_symbol_value(table, name, val)
table_entry table;
char *name;
char *val;
{
if (!name) return;
while(table && strcmp(name, table->name)) {
table = table->next;
}
if (table) {
free(table->val);
if (val) {
table->val =
(char *) malloc((unsigned) strlen(val) + 1);
(void) strcpy(table->val, val);
} else
table->val = (char *) 0;
} else {
table = (table_entry) malloc(sizeof(table_entry));
table->next = NULLSYM;
table->name = (char *) malloc((unsigned) strlen(name) + 1);
(void) strcpy(table->name, name);
if (val) {
table->val =
(char *) malloc((unsigned) strlen(val) + 1);
(void) strcpy(table->val, val);
} else
table->val = 0;
}
}
char *
get_symbol_value(table, name)
table_entry table;
char *name;
{
while(table && strcmp(name, table->name)) table = table->next;
if (table)
return table->val;
return (char *) 0;
}
free_table(table)
table_entry table;
{
table_entry entry;
while(table) {
if (table->val)
free(table->val);
free(table->name);
entry = table;
table = table->next;
free((char *) entry);
}
}
| 2.28125 | 2 |
2024-11-18T18:24:09.495628+00:00 | 2019-03-01T05:16:46 | 48fc1c453ed05a6d776de8079bfc9bf111860932 | {
"blob_id": "48fc1c453ed05a6d776de8079bfc9bf111860932",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-01T05:16:46",
"content_id": "cc06d2136603e14d3116a84a06789636e37bac31",
"detected_licenses": [
"MIT"
],
"directory_id": "5a17a3d150c4773318d397a46878d2fd74c0671f",
"extension": "c",
"filename": "wuji.c",
"fork_events_count": 0,
"gha_created_at": "2018-12-26T11:38:10",
"gha_event_created_at": "2018-12-26T11:38:10",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 163173406,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2784,
"license": "MIT",
"license_type": "permissive",
"path": "/nitan/kungfu/skill/lingshe-zhangfa/wuji.c",
"provenance": "stackv2-0003.json.gz:406923",
"repo_name": "cantona/NT6",
"revision_date": "2019-03-01T05:16:46",
"revision_id": "073f4d491b3cfe6bfbe02fbad12db8983c1b9201",
"snapshot_id": "e9adc7308619b614990fa64456c294fad5f07d61",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cantona/NT6/073f4d491b3cfe6bfbe02fbad12db8983c1b9201/nitan/kungfu/skill/lingshe-zhangfa/wuji.c",
"visit_date": "2020-04-15T21:16:28.817947"
} | stackv2 | // This program is a part of NITAN MudLIB
// wuji.c 橫行無忌
#include <ansi.h>
#include <combat.h>
inherit F_SSERVER;
string name() { return "橫行無忌"; }
int perform(object me, object target)
{
object weapon;
string msg;
int ap, dp;
int damage;
if (! target)
{
me->clean_up_enemy();
target = me->select_opponent();
}
if (! target || ! me->is_fighting(target))
return notify_fail("「橫行無忌」只能對戰鬥中的對手使用。\n");
if( !objectp(weapon=query_temp("weapon", me)) ||
query("skill_type", weapon) != "staff" )
return notify_fail("運用「橫行無忌」必須手中持杖!\n");
if ((int)me->query_skill("force") < 200)
return notify_fail("你的內功火候不夠,難以運用使用「橫行無忌」!\n");
if( query("neili", me)<300 )
return notify_fail("你現在的真氣不夠,無法使用「橫行無忌」!\n");
if ((int)me->query_skill("lingshe-zhangfa", 1) < 150)
return notify_fail("你的靈蛇杖法還不到家,無法使用「橫行無忌」!\n");
if (me->query_skill_mapped("staff") != "lingshe-zhangfa")
return notify_fail("你沒有激發靈蛇杖法,無法使用「橫行無忌」!\n");
if (! living(target))
return notify_fail("對方都已經這樣了,用不着這麼費力吧?\n");
msg = HIY "$N" HIY "一聲冷笑,手中的" + weapon->name() + HIY "忽然變得"
"如同活物一般,時上時下,忽左忽右,不知攻向$n" HIY "何處!\n" NOR;
ap = attack_power(me, "staff");
dp = defense_power(target, "parry");
if (ap / 2 + random(ap) > dp)
{
damage = damage_power(me, "staff");
addn("neili", -200, me);
msg += COMBAT_D->do_damage(me, target, WEAPON_ATTACK, damage, 55,
HIR "$n" HIR "實在無法捕做到$P"
HIR "的實招,接連擋空,連中數招,"
"登時吐了一口鮮血!\n" NOR);
me->start_busy(2);
if (! target->is_busy())
target->start_busy(1);
} else
{
msg += CYN "$n" CYN "奮力招架,總算抵擋住了$P"
CYN "的攻擊!\n" NOR;
addn("neili", -80, me);
me->start_busy(3);
if (! target->is_busy())
target->start_busy(1);
}
message_combatd(msg, me, target);
return 1;
}
| 2.125 | 2 |
2024-11-18T18:24:09.584062+00:00 | 2020-07-17T08:12:10 | 694e7e56834075b754d4ff150ca42bdd9b86fcb4 | {
"blob_id": "694e7e56834075b754d4ff150ca42bdd9b86fcb4",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-17T08:12:10",
"content_id": "5e0f94bb317ceb5aed312586c9f0a06e20bf46cb",
"detected_licenses": [
"Unlicense"
],
"directory_id": "db4c734b6f00ac1dd39d5bb6cf6db0910add4e3f",
"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": 255977183,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14964,
"license": "Unlicense",
"license_type": "permissive",
"path": "/5/main.c",
"provenance": "stackv2-0003.json.gz:407052",
"repo_name": "BenKarcher/Computer_Physik",
"revision_date": "2020-07-17T08:12:10",
"revision_id": "26b3a73c6d5d6e5e6bdd4a79cfdb248f80d28503",
"snapshot_id": "3bf4b6f9b8995cd918385e6c6fcbc8f980704bac",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BenKarcher/Computer_Physik/26b3a73c6d5d6e5e6bdd4a79cfdb248f80d28503/5/main.c",
"visit_date": "2022-11-18T18:47:19.351307"
} | stackv2 | //gcc main.c -lm -o main -Wall -Wextra -g -O3
//./main
//to make plots call plot.sh this calls gnuplot and ffmpeg
//Ben Karcher, Anika Hoverath
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
// um zu schauen, ob der Ordner existiert
extern int errno;
struct stat st = {0};
//ffmpeg -i time%02d.png -vf scale="trunc(iw/2)*2:trunc(ih/2)*2" -c:v libx264 -profile:v high -pix_fmt yuv420p -g 25 -r 25 output.mp4
//derive a function in its second argument
//used to find local minima of u2
double derive(double (*f)(double, double), double x, double t, double h)
{
return (f(t, x + h) - f(t, x - h)) / (2 * h);
}
//finds local extrema of a function between x1 and x2
//used to find local minima of u2
double findExtrema(double x1, double x2, double t, double (*func)(double, double))
{
// x1,x2
double f1 = derive(func, x1, t, 0.001);
double xn;
while (fabs(x1 - x2) > 1e-5)
{
xn = (x1 + x2) / 2;
if (f1 * derive(func, xn, t, 0.001) > 0)
{
x1 = xn;
}
else
{
x2 = xn;
}
}
return (x1 + x2) / 2;
}
//safely accesses an array of given length returns 0 if out of bounds
double edge(double *arr, long idx, long length)
{
return (idx < 0 || idx >= length) ? 0 : arr[idx];
}
// calculates next value at point j
double step(double *u0, double *u1, double j, double h, double d, long len)
{
double a = (edge(u1, j + 1, len) + edge(u1, j, len) + edge(u1, j - 1, len)) * (edge(u1, j + 1, len) - edge(u1, j - 1, len)) / 6.0 / h;
double b = (edge(u1, j + 2, len) - 2.0 * edge(u1, j + 1, len) + 2.0 * edge(u1, j - 1, len) - edge(u1, j - 2, len)) / 2.0 / (h * h * h);
return ((6.0 * a - b) * 2 * d) + edge(u0, j, len);
}
//the start condition for N waves
double uN(double x, double N)
{
return -N * (N + 1) / (cosh(x) * cosh(x));
}
// exact solution for N=1
double u_1(double t, double x)
{
return -2 / (cosh(x - 4 * t) * cosh(x - 4 * t));
}
// exact solution for N=2
double u_2(double t, double x)
{
return -12. * (3. + 4. * cosh(2. * x - 8. * t) + cosh(4. * x - 64. * t)) / pow(3. * cosh(x - 28. * t) + cosh(3. * x - 36. * t), 2.);
}
int main(void)
{
double hWerte[] = {0.4, 0.2, 0.1, 0.05}; // Die hs
double xmin = -30;
double xmax = 30;
double tmin = -1;
double tmax = 1;
double N = 2.0;
char str[50]; // string for name of file
double *u0, *u1, *un; // arrays of points only to are malloced un is for swaping
unsigned int numFrames = 100; // number of frames in a video
unsigned int frameCount = 0; // current frame number
// create files to save plots
sprintf(str, "plots/"); //file for all plots
if (stat(str, &st) == -1)
{
mkdir(str, 0700);
}
FILE *timePlot;
sprintf(str, "plots/plotExact/"); //file for exact solution
if (stat(str, &st) == -1)
{
mkdir(str, 0700);
}
double h = 0.1;
long xn = ceil(fabs(xmin - xmax) / h);
// problem 1
for (long tc = 0; tc < numFrames; tc++)
{
double t = tmin + (tmax - tmin) * tc / (numFrames - 1);
sprintf(str, "plots/plotExact/time%02u", frameCount);
timePlot = fopen(str, "w");
frameCount++;
for (long xc = 0; xc < xn; xc++)
{
double x = xc * h + xmin;
fprintf(timePlot, "%lf %lf\n", x, u_2(t, x));
}
fclose(timePlot);
}
double min1 = findExtrema(0., 15., 1., u_2);
double min2 = findExtrema(15., 30., 1., u_2);
printf("Solitionengeschwindigkeit: %lf, %lf\n", min1, min2);
// problem 2
sprintf(str, "plots/plotExactN1/");
printf("%s\n", str);
if (stat(str, &st) == -1)
{
mkdir(str, 0700);
}
for (long tc = 0; tc < numFrames; tc++)
{
double t = tmin + (tmax - tmin) * tc / (numFrames - 1);
sprintf(str, "plots/plotExactN1/time%02u", frameCount);
timePlot = fopen(str, "w");
frameCount++;
for (long xc = 0; xc < xn; xc++)
{
double x = xc * h + xmin;
fprintf(timePlot, "%lf %lf\n", x, u_1(t, x));
}
fclose(timePlot);
}
tmin = 0;
numFrames = 250;
N = 1.;
// Numeric calculation
for (int hCount = 0; hCount < sizeof(hWerte) / sizeof(hWerte[0]); hCount++)
{
sprintf(str, "plots/plotN1%02d/", hCount);
printf("%s\n", str);
if (stat(str, &st) == -1)
{
mkdir(str, 0700);
}
frameCount = 0;
sprintf(str, "plots/plotN1%02d/time%02ld", hCount, (long)0);
timePlot = fopen(str, "w");
if (timePlot == NULL)
exit(EXIT_FAILURE);
frameCount++;
double h = hWerte[hCount];
double d = 1. / 2.6 * h * h * h;
long xn = ceil(fabs(xmin - xmax) / h);
long tn = ceil(fabs(tmin - tmax) / d);
u0 = (double *)malloc(sizeof(double) * xn);
u1 = (double *)malloc(sizeof(double) * xn);
//instantiate array using uN
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = uN(xmin + xc * h, N);
fprintf(timePlot, "%lf %lf\n", xc * h + xmin, u0[xc]);
}
for (long xc = 0; xc < xn; xc++)//set u1 using formula as derived in pdf
{
u1[xc] = (step(u0, u0, xc, h, d, xn) + u0[xc]) / 2.0;
}
//iterate over each time step
for (long tc = 2; tc < tn; tc++)
{
if (tn * frameCount < tc * numFrames)//determines when to draw a new frame
{
sprintf(str, "plots/plotN1%02d/time%02u", hCount, frameCount);//file name
fclose(timePlot);
timePlot = fopen(str, "w");
frameCount++;
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = step(u0, u1, xc, h, d, xn);
fprintf(timePlot, "%lf %lf\n", xc * h + xmin, u0[xc]);
}
}
else
{//does step without writing to file
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = u(u0, u1, xc, h, d, xn);
}
}
//swaps arrays because next u is writen into u0 each step
un = u0;
u0 = u1;
u1 = un;
}
// free memory
fclose(timePlot);
free(u0);
free(u1);
}
N = 2.;
tmin = 0;
numFrames = 250;
//same code as above but for n=2
for (int hCount = 0; hCount < sizeof(hWerte) / sizeof(hWerte[0]); hCount++)
{
sprintf(str, "plots/plot%02d/", hCount);
printf("%s\n", str);
if (stat(str, &st) == -1)
{
mkdir(str, 0700);
}
frameCount = 0;
sprintf(str, "plots/plot%02d/time%02ld", hCount, (long)0);
timePlot = fopen(str, "w");
if (timePlot == NULL)
exit(EXIT_FAILURE);
frameCount++;
double h = hWerte[hCount];
double d = 1. / 2.6 * h * h * h;
long xn = ceil(fabs(xmin - xmax) / h);
long tn = ceil(fabs(tmin - tmax) / d);
u0 = (double *)malloc(sizeof(double) * xn);
u1 = (double *)malloc(sizeof(double) * xn);
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = uN(xmin + xc * h, N);
fprintf(timePlot, "%lf %lf\n", xc * h + xmin, u0[xc]);
}
for (long xc = 0; xc < xn; xc++)
{
u1[xc] = (step(u0, u0, xc, h, d, xn) + u0[xc]) / 2.0;
}
for (long tc = 2; tc < tn; tc++)
{
if (tn * frameCount < tc * numFrames)
{
sprintf(str, "plots/plot%02d/time%02u", hCount, frameCount);
fclose(timePlot);
timePlot = fopen(str, "w");
frameCount++;
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = step(u0, u1, xc, h, d, xn);
fprintf(timePlot, "%lf %lf\n", xc * h + xmin, u0[xc]);
}
}
else
{
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = step(u0, u1, xc, h, d, xn);
}
}
un = u0;
u0 = u1;
u1 = un;
}
fclose(timePlot);
free(u0);
free(u1);
}
// Heatmap for 2
printf("berechne heatMap für Aufgabe 2 N=1...\n");
sprintf(str, "plots/heatMapN1");
timePlot = fopen(str, "w");
N = 1.0;
xmin = -30.0;
xmax = 30.0;
tmin = 0;
tmax = 1;
double (*fExact)(double, double) = u_2;
int maxSize = (xmax - xmin) / 0.05 + 1;
u0 = (double *)malloc(sizeof(double) * maxSize);
u1 = (double *)malloc(sizeof(double) * maxSize);
for (double h = 0.05; h <= 0.4; h += 0.003)
{
for (double d = 0.00003; d < 0.00025; d += 0.0000025)
{
long xn = ceil(fabs(xmin - xmax) / h);
long tn = ceil(fabs(tmin - tmax) / d);
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = uN(xmin + xc * h, N);
}
for (long xc = 0; xc < xn; xc++)
{
u1[xc] = (step(u0, u0, xc, h, d, xn) + u0[xc]) / 2.0;
}
double error = 0;
for (long tc = 2; tc < tn; tc++)
{
double t = tmin + d * tc;
for (long xc = 0; xc < xn; xc++)
{
double x = xmin + h * xc;
double uNum = step(u0, u1, xc, h, d, xn);
u0[xc] = uNum;
double uExct = fExact(t, x);
error += fabs(uNum - uExct) / xn / tn;
}
un = u0;
u0 = u1;
u1 = un;
}
fprintf(timePlot, "%lf ", isnan(error) ? 1000. : error);
}
fprintf(timePlot, "\n");
}
N = 2.0;
printf("berechne heatMap für Aufgabe 2 N=2...\n");
sprintf(str, "plots/heatMapN2");
timePlot = fopen(str, "w");
for (double h = 0.05; h <= 0.4; h += 0.003)
{
for (double d = 0.00003; d < 0.00025; d += 0.0000025)
{
long xn = ceil(fabs(xmin - xmax) / h);
long tn = ceil(fabs(tmin - tmax) / d);
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = uN(xmin + xc * h, N);
}
for (long xc = 0; xc < xn; xc++)
{
u1[xc] = (step(u0, u0, xc, h, d, xn) + u0[xc]) / 2.0;
}
double error = 0;
for (long tc = 2; tc < tn; tc++)
{
double t = tmin + d * tc;
for (long xc = 0; xc < xn; xc++)
{
double x = xmin + h * xc;
double uNum = step(u0, u1, xc, h, d, xn);
u0[xc] = uNum;
double uExct = fExact(t, x);
error += fabs(uNum - uExct) / xn / tn;
}
un = u0;
u0 = u1;
u1 = un;
}
fprintf(timePlot, "%lf ", isnan(error) ? 1000. : error);
}
fprintf(timePlot, "\n");
}
fclose(timePlot);
free(u0);
free(u1);
// Problem 3
printf("Aufgabe 3\n");
tmin = 0;
numFrames = 250;
N = 3.;
xmax = 45;
sprintf(str, "plots/plotN3/");
printf("%s\n", str);
if (stat(str, &st) == -1)
{
mkdir(str, 0700);
}
frameCount = 0;
sprintf(str, "plots/plotN3/time%02ld", (long)0);
timePlot = fopen(str, "w");
if (timePlot == NULL)
exit(EXIT_FAILURE);
frameCount++;
h = 0.05;
double d = 1. / 2.6 * h * h * h;
xn = ceil(fabs(xmin - xmax) / h);
long tn = ceil(fabs(tmin - tmax) / d);
u0 = (double *)malloc(sizeof(double) * xn);
u1 = (double *)malloc(sizeof(double) * xn);
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = uN(xmin + xc * h, N);
fprintf(timePlot, "%lf %lf\n", xc * h + xmin, u0[xc]);
}
for (long xc = 0; xc < xn; xc++)
{
u1[xc] = (step(u0, u0, xc, h, d, xn) + u0[xc]) / 2.0;
}
for (long tc = 2; tc < tn; tc++)
{
if (tn * frameCount < tc * numFrames)
{
sprintf(str, "plots/plotN3/time%02u", frameCount);
fclose(timePlot);
timePlot = fopen(str, "w");
frameCount++;
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = step(u0, u1, xc, h, d, xn);
fprintf(timePlot, "%lf %lf\n", xc * h + xmin, u0[xc]);
}
}
else
{
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = step(u0, u1, xc, h, d, xn);
}
}
un = u0;
u0 = u1;
u1 = un;
}
fclose(timePlot);
free(u0);
free(u1);
// Problem 4
printf("Aufgabe 4\n");
numFrames = 250;
for (N = 1.; N < 2.; N += 0.1)
{
sprintf(str, "plots/plotN%02.1f/", N);
printf("%s\n", str);
if (stat(str, &st) == -1)
{
mkdir(str, 0700);
}
frameCount = 0;
sprintf(str, "plots/plotN%02.1f/time%02ld", N, (long)0);
timePlot = fopen(str, "w");
if (timePlot == NULL)
exit(EXIT_FAILURE);
frameCount++;
double h = 0.05;
double d = 1. / 2.6 * h * h * h;
long xn = ceil(fabs(xmin - xmax) / h);
long tn = ceil(fabs(tmin - tmax) / d);
u0 = (double *)malloc(sizeof(double) * xn);
u1 = (double *)malloc(sizeof(double) * xn);
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = uN(xmin + xc * h, N);
fprintf(timePlot, "%lf %lf\n", xc * h + xmin, u0[xc]);
}
for (long xc = 0; xc < xn; xc++)
{
u1[xc] = (step(u0, u0, xc, h, d, xn) + u0[xc]) / 2.0;
}
for (long tc = 2; tc < tn; tc++)
{
if (tn * frameCount < tc * numFrames)
{
sprintf(str, "plots/plotN%02.1f/time%02u", N, frameCount);
fclose(timePlot);
timePlot = fopen(str, "w");
frameCount++;
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = step(u0, u1, xc, h, d, xn);
fprintf(timePlot, "%lf %lf\n", xc * h + xmin, u0[xc]);
}
}
else
{
for (long xc = 0; xc < xn; xc++)
{
u0[xc] = step(u0, u1, xc, h, d, xn);
}
}
un = u0;
u0 = u1;
u1 = un;
}
fclose(timePlot);
free(u0);
free(u1);
}
return 0;
}
| 2.671875 | 3 |
2024-11-18T18:24:09.645182+00:00 | 2019-03-31T22:58:04 | b653619300bda0608ec9b58e99ea14f848990045 | {
"blob_id": "b653619300bda0608ec9b58e99ea14f848990045",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-31T22:58:04",
"content_id": "fd806838e91ea45537babbf44218c9794e82f66c",
"detected_licenses": [
"MIT"
],
"directory_id": "0a66ccdab25d7a08d66a5b925e1803bf1f71e6e7",
"extension": "c",
"filename": "padfile.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 169133226,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1738,
"license": "MIT",
"license_type": "permissive",
"path": "/extras/padfile.c",
"provenance": "stackv2-0003.json.gz:407181",
"repo_name": "cadel560x/SHA256",
"revision_date": "2019-03-31T22:58:04",
"revision_id": "33355ff6ba7dfa3c397c8238da9b501c2c4af54e",
"snapshot_id": "a2b145de47cb35dbd44980e59813744b38431a71",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cadel560x/SHA256/33355ff6ba7dfa3c397c8238da9b501c2c4af54e/extras/padfile.c",
"visit_date": "2020-04-20T22:14:30.865139"
} | stackv2 | #include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
union msgblock {
uint8_t e[64];
uint32_t t[16];
uint64_t s[8];
};
enum status {READ, PAD0, PAD1, FINISH};
int main(int argc, char *argv[]) {
union msgblock M;
uint64_t nobits = 0;
uint64_t nobytes;
enum status S = READ;
FILE *f;
// Check for input files
if (argc == 1) {
fprintf(stderr, "Error: No input files\n");
fprintf(stderr, "usage: %s [FILE]...\n", argv[0]);
exit(1);
}
// Iterates over input files
for (int j = 1; j < argc; j++ ) {
f = fopen(argv[j], "r");
// File check
if ( f == NULL ) {
fprintf(stderr, "Error: %s\n", strerror(errno));
exit(2);
}
// Starts reading current input file pointed by 'f' pointer
S = READ;
while (S == READ) {
nobytes = fread(M.e, 1, 64, f);
printf("Read %2llu bytes\n", nobytes);
nobits = nobits + (nobytes * 8);
if (nobytes < 56 ) {
printf("I've found a block with less than 55 bytes!\n");
M.e[nobytes] = 0x80;
while (nobytes < 56) {
nobytes = nobytes + 1;
M.e[nobytes] = 0x00;
} // end loop
M.s[7] = nobits;
S = FINISH;
}
else if (nobytes < 64) {
S = PAD0;
M.e[nobytes] = 0x80;
while (nobytes < 64) {
nobytes = nobytes + 1;
M.e[nobytes] = 0x00;
} // end loop
}
else if (feof(f)) {
S = PAD1;
} // end if-else if
} // end loop
fclose(f);
if (S == PAD0 || S == PAD1) {
for (int i = 0; i < 56; i++) {
M.e[i] = 0x00;
}
M.s[7] = nobits;
} // end if
if (S == PAD1) {
M.e[0] = 0x80;
}
for (int i = 0; i < 64; i++) {
printf("%x ", M.e[i]);
}
printf("\n\n");
} // end loop
return 0;
} // end main
| 3.046875 | 3 |
2024-11-18T18:24:09.946685+00:00 | 2017-05-10T09:50:21 | 388475176ce9170e902353d01bc2db432038bdcd | {
"blob_id": "388475176ce9170e902353d01bc2db432038bdcd",
"branch_name": "refs/heads/arm",
"committer_date": "2017-05-10T14:22:48",
"content_id": "49875b9b4d6aaf19567a2eb4af029b5c53d60377",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6af50a4b5b928211880dd9f1c6ce92c2afea828b",
"extension": "c",
"filename": "isr_tables.c",
"fork_events_count": 0,
"gha_created_at": "2016-12-16T09:52:08",
"gha_event_created_at": "2020-02-04T19:16:46",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 76642373,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1854,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/arch/common/isr_tables.c",
"provenance": "stackv2-0003.json.gz:407438",
"repo_name": "erwango/zephyr",
"revision_date": "2017-05-10T09:50:21",
"revision_id": "162f4574c781ae17d3fecfd4ac10df111e90ae3c",
"snapshot_id": "1c7aa447f613de76439291ba9dde1e4dc7c5786e",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/erwango/zephyr/162f4574c781ae17d3fecfd4ac10df111e90ae3c/arch/common/isr_tables.c",
"visit_date": "2023-08-11T10:29:20.031948"
} | stackv2 | /*
* Copyright (c) 2017 Intel Corporation.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <toolchain.h>
#include <sections.h>
#include <sw_isr_table.h>
#include <arch/cpu.h>
#if defined(CONFIG_GEN_SW_ISR_TABLE) && defined(CONFIG_GEN_IRQ_VECTOR_TABLE)
#define ISR_WRAPPER (&_isr_wrapper)
#else
#define ISR_WRAPPER NULL
#endif
/* There is an additional member at the end populated by the linker script
* which indicates the number of interrupts specified
*/
struct int_list_header {
void *spurious_ptr;
void *handler_ptr;
u32_t table_size;
u32_t offset;
};
/* These values are not included in the resulting binary, but instead form the
* header of the initList section, which is used by gen_isr_tables.py to create
* the vector and sw isr tables,
*/
_GENERIC_SECTION(.irq_info) struct int_list_header _iheader = {
.spurious_ptr = &_irq_spurious,
.handler_ptr = ISR_WRAPPER,
.table_size = IRQ_TABLE_SIZE,
.offset = CONFIG_GEN_IRQ_START_VECTOR,
};
/* These are placeholder tables. They will be replaced by the real tables
* generated by gen_isr_tables.py.
*/
/* Some arches don't use a vector table, they have a common exception entry
* point for all interrupts. Don't generate a table in this case.
*/
#ifdef CONFIG_GEN_IRQ_VECTOR_TABLE
u32_t __irq_vector_table _irq_vector_table[IRQ_TABLE_SIZE] = {
[0 ...(IRQ_TABLE_SIZE - 1)] = 0xabababab,
};
#endif
/* If there are no interrupts at all, or all interrupts are of the 'direct'
* type and bypass the _sw_isr_table, then do not generate one.
*/
#ifdef CONFIG_GEN_SW_ISR_TABLE
struct _isr_table_entry __sw_isr_table _sw_isr_table[IRQ_TABLE_SIZE] = {
[0 ...(IRQ_TABLE_SIZE - 1)] = {(void *)0xcdcdcdcd, (void *)0xcdcdcdcd},
};
#endif
/* Linker needs this */
GEN_ABS_SYM_BEGIN(isr_tables_syms)
GEN_ABSOLUTE_SYM(__ISR_LIST_SIZEOF, sizeof(struct _isr_list));
GEN_ABS_SYM_END
| 2.078125 | 2 |
2024-11-18T18:24:10.219490+00:00 | 2020-06-21T16:05:45 | 989a24882c11447cb7872d05da984b7e4bfc52d0 | {
"blob_id": "989a24882c11447cb7872d05da984b7e4bfc52d0",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-21T16:05:45",
"content_id": "a6e56774e354c924642e3ea9d94f0583b9cb5641",
"detected_licenses": [
"MIT"
],
"directory_id": "469cd4318c9a59ddeca9e47948959bcfafc1f7d4",
"extension": "h",
"filename": "node.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 262583659,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2929,
"license": "MIT",
"license_type": "permissive",
"path": "/include/node.h",
"provenance": "stackv2-0003.json.gz:407695",
"repo_name": "idodra/Compile-project",
"revision_date": "2020-06-21T16:05:45",
"revision_id": "d5e9aa8748f869409b4dc0cf331273d052ed5fe6",
"snapshot_id": "8af4ef41b0f3ce9d7a60d047e3cc4172cfa520a9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/idodra/Compile-project/d5e9aa8748f869409b4dc0cf331273d052ed5fe6/include/node.h",
"visit_date": "2022-11-05T17:30:30.023136"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NODE_MAX 2000
enum TreeNodeType {Add, Sub, Mul, Fdiv, Idiv, Mod, Eq, Com, Par, Tref, Sref, Index, Intv, Floatv};
union TreeNodeVal {
int Int;
float Float;
char *String;
};
struct TreeNode {
TreeNodeVal val;
TreeNodeType type;
TreeNode *left, *right;
};
int node_num = 0;
TreeNode *TreeRoot = NULL;
TreeNode nodes[NODE_MAX];
// void ValCopy(TreeNodeVal &dest, const TreeNodeVal &src, const TreeNodeType &t) {
// if (t == Intv) {
// dest.Int = src.Int;
// }
// else if (t == Floatv) {
// dest.Float = src.Float;
// }
// else {
// dest.String = strdup(src.String);
// }
// }
bool ValEqual(const TreeNodeVal &val1, const TreeNodeVal &val2, const TreeNodeType &t) {
if (t == Intv) {
return (val1.Int == val2.Int);
}
else if (t == Floatv) {
return (val1.Float == val2.Float);
}
else {
return (strcmp(val1.String, val2.String) == 0);
}
}
TreeNode* find_valnode(const TreeNodeType &t, const TreeNode *left, const TreeNode *right, const TreeNodeVal &val) {
for (int i = 0; i < node_num; ++i) {
if (nodes[i].type == t && nodes[i].left == left && nodes[i].right == right && ValEqual(nodes[i].val, val, t)) {
return nodes+i;
}
}
return NULL;
}
TreeNode* new_valnode(const TreeNodeType &t, TreeNode *left, TreeNode *right, const TreeNodeVal &val) {
if (t != Intv && t != Floatv && t != Index && t != Tref && t != Sref) {
return NULL;
}
TreeNode* node = find_valnode(t, left, right, val);
if (node == NULL) {
nodes[node_num].type = t;
nodes[node_num].left = left;
nodes[node_num].right = right;
if (t == Intv) {
nodes[node_num].val.Int = val.Int;
}
else if (t == Floatv) {
nodes[node_num].val.Float = val.Float;
}
else {
nodes[node_num].val.String = strdup(val.String);
}
node = nodes+node_num;
node_num++;
}
return node;
}
TreeNode* find_node(const TreeNodeType &t, const TreeNode *left, const TreeNode *right) {
for (int i = 0; i < node_num; ++i) {
if (nodes[i].type == t && nodes[i].left == left && nodes[i].right == right) {
return nodes+i;
}
}
return NULL;
}
TreeNode* new_node(const TreeNodeType &t, TreeNode *left, TreeNode *right) {
if (t == Intv || t == Floatv || t == Index || t == Tref || t == Sref) {
return NULL;
}
TreeNode* node = find_node(t, left, right);
if (node == NULL) {
nodes[node_num].type = t;
nodes[node_num].left = left;
nodes[node_num].right = right;
node = nodes+node_num;
node_num++;
}
return node;
}
void free_node(TreeNode *node) {
if (node->type == Index || node->type == Tref || node->type == Sref) {
if (node->val.String != NULL) {
free(node->val.String);
node->val.String = NULL;
}
}
if (node->left != NULL) {
free_node(node->left);
}
if (node->right != NULL) {
free_node(node->right);
}
}
void free_tree(TreeNode *root) {
if (root != NULL) {
free_node(root);
}
node_num = 0;
TreeRoot = NULL;
}
| 3.046875 | 3 |
2024-11-18T18:24:10.594184+00:00 | 2022-03-19T10:01:09 | 6126a9963df388ed07111bb80cd3111c43ef4215 | {
"blob_id": "6126a9963df388ed07111bb80cd3111c43ef4215",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-19T10:01:09",
"content_id": "13f7f7827c056479b5f799c2475a9b340668fa48",
"detected_licenses": [
"MIT"
],
"directory_id": "7573bc088286370865a424fb77a0b726010752ec",
"extension": "c",
"filename": "echoclient.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 238354204,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2974,
"license": "MIT",
"license_type": "permissive",
"path": "/echoserv/echoclient.c",
"provenance": "stackv2-0003.json.gz:408209",
"repo_name": "iceice/glacier",
"revision_date": "2022-03-19T10:01:09",
"revision_id": "779082cc197f753fb2feff63ac8fbe3f5512828c",
"snapshot_id": "21f0fcd55d9172416f6b55b1bf741d824841bfa7",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/iceice/glacier/779082cc197f753fb2feff63ac8fbe3f5512828c/echoserv/echoclient.c",
"visit_date": "2022-05-02T23:39:09.868309"
} | stackv2 | /*
ECHOCLIENT.C
==========
(c) Yansong Li, 2020
Email: [email protected]
Simple TCP/IP echo client.
*/
#include <sys/socket.h> /* socket definitions */
#include <sys/types.h> /* socket types */
#include <arpa/inet.h> /* inet (3) funtions */
#include <unistd.h> /* misc. UNIX functions */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "helper.h" /* our own helper functions */
/* Global constants */
#define ECHO_PORT (2020)
#define MAX_LINE (1000)
char *Fgets(char *ptr, int n, FILE *stream)
{
char *rptr;
if (((rptr = fgets(ptr, n, stream)) == NULL) && ferror(stream))
return rptr;
}
int main(int argc, char *argv[])
{
int clientfd; /* client socket */
char *buffer[MAX_LINE]; /* character buffer */
char *endptr; /* for strtol() */
short int port; /* port number */
// struct in_addr host; /* host address */
struct sockaddr_in servaddr; /* socket address structure */
/* Get host address and port from the command line */
if (argc == 3)
{
// change network to int
// if (inet_aton("127.0.0.1", &host) != 1)
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) < 0)
{
fprintf(stderr, "ECHOCLIENT: Invalid host address.\n");
exit(EXIT_FAILURE);
}
// change string port to int
port = strtol(argv[2], &endptr, 0);
if (*endptr)
{
fprintf(stderr, "ECHOCLIENT: Invalid port number.\n");
exit(EXIT_FAILURE);
}
}
else
{
fprintf(stderr, "ECHOCLIENT: usage: %s <host> <port>\n", argv[0]);
exit(EXIT_FAILURE);
}
/* Create the client socket */
if ((clientfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
fprintf(stderr, "ECHOCLIENT: Error creating listening socket.\n");
exit(EXIT_FAILURE);
}
/* Set all bytes in socket address structure to
zero, and fill in the relevant data members */
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
// /* Connect our socket address to the client socket */
if (connect(clientfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
{
fprintf(stderr, "ECHOCLIENT: Error calling connect()\n");
exit(EXIT_FAILURE);
}
while (fgets(buffer, MAX_LINE, stdin) != NULL)
{
/* Retrieve an input line from the connected socket
then simply write it back to the same socket. */
Writeline(clientfd, buffer, strlen(buffer));
Readline(clientfd, buffer, MAX_LINE-1);
fputs(buffer, stdout);
}
close(clientfd);
exit(0);
} | 3.078125 | 3 |
2024-11-18T18:24:10.684592+00:00 | 2018-11-04T16:36:23 | f594505ae7d7937e2cd49118dad171ba920d637d | {
"blob_id": "f594505ae7d7937e2cd49118dad171ba920d637d",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-04T16:36:23",
"content_id": "a50df0be3cd2f4f1d8d568f7e679dff0b68ae0c9",
"detected_licenses": [
"MIT"
],
"directory_id": "9ea64a07241d1cb6e743ca641b890572452edc43",
"extension": "c",
"filename": "FIxedSizeMemory.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 129050171,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3390,
"license": "MIT",
"license_type": "permissive",
"path": "/Operating_System_lab/Memory_Management/FIxedSizeMemory.c",
"provenance": "stackv2-0003.json.gz:408337",
"repo_name": "dashan124/ITLabs",
"revision_date": "2018-11-04T16:36:23",
"revision_id": "e465ef910d475e1dc3983ca44d623fee9b569061",
"snapshot_id": "751056fd4f2e88b38388d892dd53c98ca1f1e659",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dashan124/ITLabs/e465ef910d475e1dc3983ca44d623fee9b569061/Operating_System_lab/Memory_Management/FIxedSizeMemory.c",
"visit_date": "2020-03-10T00:38:12.758630"
} | stackv2 | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
void BestFITmem(int m,int block[],int n,int process[]){
int allocation[n]; //declaring a array for allocation status
int arblock[m];//blocka is for the memory
for(int x=0;x<m;x++){
arblock[x]=block[x];
}
int arprocess[n];
for(int u=0;u<n;u++){
arprocess[u]=process[u];
}
memset(allocation,-1,sizeof(allocation));
for(int i=0;i<n;i++){
int best=-1; //best fit is basically find a block with min size >=rquired size
for(int j=0;j<m;j++){
if(arblock[j]>=arprocess[i]){
if(best==-1){
best=j;
}
else if(arblock[best]>arblock[j]){
best=j;
}
}
}
if(best!=-1){
allocation[i]=best;
arblock[best]=arblock[best]-arprocess[i];
}
}
printf("BESTFIt\n");
printf("\n process No. \t Process Size\t Block No.\n");
for(int r=0;r<n;r++){
printf(" %d\t\t%d\t\t",r+1,arprocess[r] );
if(allocation[r]!=-1){
printf("%d",allocation[r]+1);
}
else{
printf("Not allocated");
}
printf("\n");
}
}
void FirstFitmem(int m,int block[],int n,int process[]){
int allocation[n];
int block1[m];
for(int y=0;y<m;y++){
block1[y]=block[y];
}
int process1[n];
for(int c=0;c<n;c++){
process1[c]=process[c];
}
memset(allocation,-1,sizeof(allocation));
//whichever having size >=process size comes first allocate it
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(block1[j]>=process1[i]){
allocation[i]=j;
block1[j]-=process1[i];
break;
}
}
}
printf("FIRSTFIT\n");
printf("\n process No. \t Process Size\t Block No.\n");
for(int r=0;r<n;r++){
printf(" %d\t\t%d\t\t",r+1,process1[r] );
if(allocation[r]!=-1){
printf("%d",allocation[r]+1);
}
else{
printf("Not allocated");
}
printf("\n");
}
}
void WORSTFITmem(int m,int block[],int n,int process[]){
int allocation[n];
int copyblock[m];
int copyprocess[n];
//find a bigger block for any process
for(int i=0;i<m;i++){
copyblock[i]=block[i];
}
for(int j=0;j<n;j++){
copyprocess[j]=block[j];
}
memset(allocation,-1,sizeof(allocation));
for(int i=0;i<n;i++){
int worst=-1;
for(int j=0;j<m;j++){
if(copyblock[j]>=copyprocess[i]){
if(worst==-1){
worst=j;
}
else if(copyblock[worst]<copyblock[j]){
worst=j;
}
}
}
if(worst!=-1){
allocation[i]=worst;
copyblock[worst]=copyblock[worst]-copyprocess[i];
}
}
printf("\n process No. \t Process Size\t Block No.\n");
for(int r=0;r<n;r++){
printf(" %d\t\t%d\t\t",r+1,copyprocess[r] );
if(allocation[r]!=-1){
printf("%d",allocation[r]+1);
}
else{
printf("Not allocated");
}
printf("\n");
}
}
int main(){
int memblock;
printf("Enter the no of memory blocks\n");
scanf("%d",&memblock);
int memw[memblock];
int i;
printf("Enter the sizes of the memory %d blocks \n",memblock);
for(i=0;i<memblock;i++){
scanf("%d",&memw[i]);
}
int proce;
printf("Enter the no of processes\n");
scanf("%d",&proce);
int process[proce];
int j;
for(j=0;j<proce;j++){
scanf("%d",&process[j]);
}
BestFITmem(memblock,memw,proce,process);
WORSTFITmem(memblock,memw,proce,process);
FirstFitmem(memblock,memw,proce,process);
return 0;
}
| 3.0625 | 3 |
2024-11-18T18:24:12.018166+00:00 | 2015-07-03T13:34:15 | 5216d826c5db217903d0c082b0e85d8538c1af16 | {
"blob_id": "5216d826c5db217903d0c082b0e85d8538c1af16",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-03T13:34:15",
"content_id": "f93c9a60e61964d1da7783bb063d1746b38372ad",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3305da8141f013c39e44b36601c7df12f4aa16bc",
"extension": "c",
"filename": "ksi_verify.c",
"fork_events_count": 1,
"gha_created_at": "2015-05-20T07:37:51",
"gha_event_created_at": "2015-07-03T13:34:15",
"gha_language": "C",
"gha_license_id": null,
"github_id": 35933291,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4598,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/example/ksi_verify.c",
"provenance": "stackv2-0003.json.gz:408727",
"repo_name": "rgerhards/libksi",
"revision_date": "2015-07-03T13:34:15",
"revision_id": "b1ac0346395b4f52ec42a050bf33ac223f194443",
"snapshot_id": "94ee7205f44ad6367420298687d9f699c33bba47",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/rgerhards/libksi/b1ac0346395b4f52ec42a050bf33ac223f194443/src/example/ksi_verify.c",
"visit_date": "2016-09-06T03:27:06.750365"
} | stackv2 | /*
* Copyright 2013-2015 Guardtime, Inc.
*
* This file is part of the Guardtime client SDK.
*
* 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, CONDITIONS, OR OTHER LICENSES OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
* "Guardtime" and "KSI" are trademarks or registered trademarks of
* Guardtime, Inc., and no license to trademarks is granted; Guardtime
* reserves and retains all trademark rights.
*/
#include <stdio.h>
#include <string.h>
#include <ksi/ksi.h>
int main(int argc, char **argv) {
int res = KSI_UNKNOWN_ERROR;
KSI_CTX *ksi = NULL;
KSI_Signature *sig = NULL;
KSI_DataHash *hsh = NULL;
KSI_DataHasher *hsr = NULL;
FILE *in = NULL;
unsigned char buf[1024];
unsigned buf_len;
const KSI_VerificationResult *info = NULL;
FILE *logFile = NULL;
/* Init context. */
res = KSI_CTX_new(&ksi);
if (res != KSI_OK) {
fprintf(stderr, "Unable to init KSI context.\n");
goto cleanup;
}
logFile = fopen("ksi_verify.log", "w");
if (logFile == NULL) {
fprintf(stderr, "Unable to open log file.\n");
}
KSI_CTX_setLoggerCallback(ksi, KSI_LOG_StreamLogger, logFile);
KSI_CTX_setLogLevel(ksi, KSI_LOG_DEBUG);
KSI_LOG_info(ksi, "Using KSI version: '%s'", KSI_getVersion());
/* Check parameters. */
if (argc != 5) {
fprintf(stderr, "Usage\n"
" %s <data file | -> <signature> <extender url> <pub-file url | ->\n", argv[0]);
goto cleanup;
}
res = KSI_CTX_setExtender(ksi, argv[3], "anon", "anon");
if (res != KSI_OK) {
fprintf(stderr, "Unable to set extender parameters.\n");
goto cleanup;
}
if (strncmp("-", argv[4], 1)) {
/* Set the publications file url. */
res = KSI_CTX_setPublicationUrl(ksi, argv[4]);
if (res != KSI_OK) {
fprintf(stderr, "Unable to set publications file url.\n");
goto cleanup;
}
}
printf("Reading signature... ");
/* Read the signature. */
res = KSI_Signature_fromFile(ksi, argv[2], &sig);
if (res != KSI_OK) {
printf("failed (%s)\n", KSI_getErrorString(res));
goto cleanup;
}
printf("ok\n");
/* Create hasher. */
res = KSI_Signature_createDataHasher(sig, &hsr);
if (res != KSI_OK) {
fprintf(stderr, "Unable to create data hasher.\n");
goto cleanup;
}
if (strcmp(argv[1], "-")) {
in = fopen(argv[1], "rb");
if (in == NULL) {
fprintf(stderr, "Unable to open data file '%s'.\n", argv[1]);
goto cleanup;
}
/* Calculate the hash of the document. */
while (!feof(in)) {
buf_len = (unsigned)fread(buf, 1, sizeof(buf), in);
res = KSI_DataHasher_add(hsr, buf, buf_len);
if (res != KSI_OK) {
fprintf(stderr, "Unable hash the document.\n");
goto cleanup;
}
}
/* Finalize the hash computation. */
res = KSI_DataHasher_close(hsr, &hsh);
if (res != KSI_OK) {
fprintf(stderr, "Failed to close the hashing process.\n");
goto cleanup;
}
printf("Verifying document hash... ");
res = KSI_Signature_verifyDataHash(sig, ksi, hsh);
} else {
printf("Verifiyng signature...");
res = KSI_Signature_verify(sig, ksi);
}
switch (res) {
case KSI_OK:
printf("ok\n");
break;
case KSI_VERIFICATION_FAILURE:
printf("failed\n");
break;
default:
printf("failed (%s)\n", KSI_getErrorString(res));
goto cleanup;
}
res = KSI_Signature_getVerificationResult(sig, &info);
if (res != KSI_OK) goto cleanup;
if (info != NULL) {
size_t i;
printf("Verification info:\n");
for (i = 0; i < KSI_VerificationResult_getStepResultCount(info); i++) {
const KSI_VerificationStepResult *result = NULL;
const char *desc = NULL;
res = KSI_VerificationResult_getStepResult(info, i, &result);
if (res != KSI_OK) goto cleanup;
printf("\t0x%02x:\t%s", KSI_VerificationStepResult_getStep(result), KSI_VerificationStepResult_isSuccess(result) ? "OK" : "FAIL");
desc = KSI_VerificationStepResult_getDescription(result);
if (desc && *desc) {
printf(" (%s)", desc);
}
printf("\n");
}
}
res = KSI_OK;
cleanup:
if (logFile != NULL) fclose(logFile);
if (res != KSI_OK && ksi != NULL) {
KSI_ERR_statusDump(ksi, stderr);
}
if (in != NULL) fclose(in);
KSI_Signature_free(sig);
KSI_DataHasher_free(hsr);
KSI_DataHash_free(hsh);
KSI_CTX_free(ksi);
return res;
}
| 2.03125 | 2 |
2024-11-18T18:24:12.550723+00:00 | 2023-03-27T18:49:02 | 4b47ed77bba5e5d386a240884b7ab3481db5d4f3 | {
"blob_id": "4b47ed77bba5e5d386a240884b7ab3481db5d4f3",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-27T18:49:02",
"content_id": "18cd1622b7aa067ca774448e3808caa8f4112eaf",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ed21cc9eab214a4582bf68267a7f94547ae0fcd3",
"extension": "c",
"filename": "file1.c",
"fork_events_count": 17,
"gha_created_at": "2017-07-20T16:45:43",
"gha_event_created_at": "2023-05-22T19:52:58",
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 97858019,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 145,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/docsbuild/file1.c",
"provenance": "stackv2-0003.json.gz:409499",
"repo_name": "att/MkTechDocs",
"revision_date": "2023-03-27T18:49:02",
"revision_id": "660b558e9212aae8b2e6afa27a1f6412a6ebd82b",
"snapshot_id": "602a003cf83556463227531d7a4e7cd43946d5b8",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/att/MkTechDocs/660b558e9212aae8b2e6afa27a1f6412a6ebd82b/docsbuild/file1.c",
"visit_date": "2023-06-08T20:28:35.360526"
} | stackv2 | #include <stdio.h>
#include "file1.h"
int main(int argc, char **argv)
{
printf("Size of SOMETHING is: %lu\n", sizeof(SOMETHING));
return 0;
}
| 2.09375 | 2 |
2024-11-18T18:24:12.652546+00:00 | 2016-09-07T15:40:23 | 6ebe0b7a363bcdc9d09b952d9754213fcaa09275 | {
"blob_id": "6ebe0b7a363bcdc9d09b952d9754213fcaa09275",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-07T15:40:23",
"content_id": "f4d2d895dc9e08d84780aa4177b19cf43360d4a5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b76aa6cffa0a5ba2137ca8e12f3ba7a4cf3b5125",
"extension": "h",
"filename": "OMPCACell.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 67615697,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7814,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/project_openmp/OMPCACell.h",
"provenance": "stackv2-0003.json.gz:409629",
"repo_name": "HPC4HEP/HybCellularAutomaton",
"revision_date": "2016-09-07T15:40:23",
"revision_id": "7b777c7f6e329a906e968de3cc763aa7d7cc8613",
"snapshot_id": "28f995e1ff588a5896767b63afe90dd6d0ab9e2c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/HPC4HEP/HybCellularAutomaton/7b777c7f6e329a906e968de3cc763aa7d7cc8613/project_openmp/OMPCACell.h",
"visit_date": "2020-04-17T22:33:07.165508"
} | stackv2 | /** \file OMPCACell.h*/
#ifndef OMP_CACELL_H_
#define OMP_CACELL_H_
#include "OMPHitsAndDoublets.h"
#include "OMPSimpleVector.h"
#include "OMPResultVector.h"
#include "OMPMixedList.h"
#include <math.h>
const int numberOfLayers = 4;
//! The Cellular Automaton cell
/** Keeps all the relevant info for compatibility checks.
*/
typedef struct OMPCACell
{
unsigned int theInnerHitId; /**< integer index of inner hit in its layer*/
unsigned int theOuterHitId; /**< integer index of outer hit in its layer*/
int theDoubletId; /**< integer index of doublets in the layer pair structure*/
int theLayerIdInFourLayers; /**< the id of the layer*/
float theInnerX; /**< x value of inner hit*/
float theOuterX; /**< x value of outer hit*/
float theInnerY; /**< y value of inner hit*/
float theOuterY; /**< y value of outer hit*/
float theInnerZ; /**< z value of inner hit*/
float theOuterZ; /**< z value of outer hit*/
float theInnerR; /**< r value of inner hit*/
float theOuterR; /**< r value of outer hit*/
} OMPCACell;
//! Initialize the values of the cell.
/** The cells correspond 1-1 to a given doublet.
\param this The cell in question
\param doublets The structure of the layer pair
\param layerId The layer in which the doublet resides
\param innerHitId The identifier of the inner hit in its layer
\param outerHitId The identifier of the outer hit in its layer
*/
void init(OMPCACell* this, const OMPLayerDoublets* doublets, int layerId, int doubletId, int innerHitId, int outerHitId) {
this->theInnerHitId = innerHitId;
this->theOuterHitId = outerHitId;
this->theDoubletId = doubletId;
this->theLayerIdInFourLayers = layerId;
this->theInnerX = doublets->layers[0].p[3*(doublets->indices[2 * doubletId])];
this->theOuterX = doublets->layers[1].p[3*(doublets->indices[2 * doubletId + 1])];
this->theInnerY = doublets->layers[0].p[1+3*(doublets->indices[2 * doubletId])];
this->theOuterY = doublets->layers[1].p[1+3*(doublets->indices[2 * doubletId + 1])];
this->theInnerZ = doublets->layers[0].p[2+3*(doublets->indices[2 * doubletId])];
this->theOuterZ = doublets->layers[1].p[2+3*(doublets->indices[2 * doubletId + 1])];
this->theInnerR = hypot(this->theInnerX, this->theInnerY);
this->theOuterR = hypot(this->theOuterX, this->theOuterY);
}
/** Get x value of inner hit. Provides an abstaction
* for getting the value.
\param this Pointer to the cell in question
*/
float get_inner_x(const OMPCACell* this) {
return this->theInnerX;
}
/** Get x value of outer hit. Provides an abstaction
* for getting the value.
\param this Pointer to the cell in question
*/
float get_outer_x(const OMPCACell* this) {
return this->theOuterX;
}
/** Get y value of inner hit. Provides an abstaction
* for getting the value.
\param this Pointer to the cell in question
*/
float get_inner_y(const OMPCACell* this) {
return this->theInnerY;
}
/** Get y value of outer hit. Provides an abstaction
* for getting the value.
\param this Pointer to the cell in question
*/
float get_outer_y(const OMPCACell* this) {
return this->theOuterY;
}
/** Get z value of inner hit. Provides an abstaction
* for getting the value.
\param this Pointer to the cell in question
*/
float get_inner_z(const OMPCACell* this) {
return this->theInnerZ;
}
/** Get z value of outer hit. Provides an abstaction
* for getting the value.
\param this Pointer to the cell in question
*/
float get_outer_z(const OMPCACell* this) {
return this->theOuterZ;
}
/** Get r value of inner hit. Provides an abstaction
* for getting the value.
\param this Pointer to the cell in question
*/
float get_inner_r(const OMPCACell* this) {
return this->theInnerR;
}
/** Get r value of outer hit. Provides an abstaction
* for getting the value.
\param this Pointer to the cell in question
*/
float get_outer_r(const OMPCACell* this) {
return this->theOuterR;
}
/** Get id of inner hit. Provides an abstaction
* for getting the value.
\param this Pointer to the cell in question
*/
unsigned int get_inner_hit_id(const OMPCACell* this) {
return this->theInnerHitId;
}
/** Get id of outer hit. Provides an abstaction
* for getting the value.
\param this Pointer to the cell in question
*/
unsigned int get_outer_hit_id(const OMPCACell* this) {
return this->theOuterHitId;
}
void print_cell(const OMPCACell* this) {
printf(
"\n printing cell: %d, on layer: %d, innerHitId: %d, outerHitId: %d, innerradius %f, outerRadius %f ",
this->theDoubletId, this->theLayerIdInFourLayers, this->theInnerHitId,
this->theOuterHitId, this->theInnerR, this->theOuterR);
}
int are_aligned_RZ(const OMPCACell* this, const OMPCACell* otherCell, const float ptmin, const float thetaCut) {
float r1 = get_inner_r(otherCell);
float z1 = get_inner_z(otherCell);
float distance_13_squared = (r1 - this->theOuterR) * (r1 - this->theOuterR) + (z1 - this->theOuterZ) * (z1 - this->theOuterZ);
float tan_12_13_half = fabs(z1 * (this->theInnerR - this->theOuterR) + this->theInnerZ * (this->theOuterR - r1) + this->theOuterZ * (r1 - this->theInnerR)) / distance_13_squared;
return tan_12_13_half * ptmin <= thetaCut;
}
int have_similar_curvature(const OMPCACell* this, const OMPCACell* otherCell, const float region_origin_x, const float region_origin_y, const float region_origin_radius, const float phiCut) {
float x1 = get_inner_x(otherCell);
float y1 = get_inner_y(otherCell);
float x2 = get_inner_x(this);
float y2 = get_inner_y(this);
float x3 = get_outer_x(this);
float y3 = get_outer_y(this);
float precision = 0.5f;
float offset = x2 * x2 + y2 * y2;
float bc = (x1 * x1 + y1 * y1 - offset) / 2.f;
float cd = (offset - x3 * x3 - y3 * y3) / 2.f;
float det = (x1 - x2) * (y2 - y3) - (x2 - x3) * (y1 - y2);
//points are aligned
if (fabs(det) < precision)
return 1;
float idet = 1.f / det;
float x_center = (bc * (y2 - y3) - cd * (y1 - y2)) * idet;
float y_center = (cd * (x1 - x2) - bc * (x2 - x3)) * idet;
float radius = sqrt((x2 - x_center) * (x2 - x_center)+ (y2 - y_center) * (y2 - y_center));
float centers_distance_squared = (x_center - region_origin_x) * (x_center - region_origin_x) + (y_center - region_origin_y) * (y_center - region_origin_y);
float minimumOfIntesectionRange = (radius - region_origin_radius) * (radius - region_origin_radius) - phiCut;
if (centers_distance_squared >= minimumOfIntesectionRange)
{
float maximumOfIntesectionRange = (radius + region_origin_radius)
* (radius + region_origin_radius) + phiCut;
return centers_distance_squared <= maximumOfIntesectionRange;
}
else
{
return 0;
}
}
/** Get boolean value (as integer) of compatibility predicate. Receives 2 cells and checks if they are compatible in respect with the parameters provides.
\param this The integer index of the outer cell doublet in the layer pair
\param innerCell The integer index of the inner cell doublet in the layer pair
*/
int check_alignment_and_tag(const OMPCACell* this, const OMPCACell* innerCell, const float ptmin, const float region_origin_x, const float region_origin_y, const float region_origin_radius, const float thetaCut, const float phiCut) {
return (are_aligned_RZ(this, innerCell, ptmin, thetaCut) && have_similar_curvature(this, innerCell, region_origin_x, region_origin_y, region_origin_radius, phiCut));
}
#endif /*CACELL_H_ */
| 2.53125 | 3 |
2024-11-18T18:24:14.335937+00:00 | 2021-10-25T02:02:29 | 49f561257db3a81ba29aeb7321e49c958a47a988 | {
"blob_id": "49f561257db3a81ba29aeb7321e49c958a47a988",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-25T02:02:29",
"content_id": "454a33a569da4209cedec3c3a8696698cab16f78",
"detected_licenses": [
"MIT"
],
"directory_id": "abda7fa9bab285f213ad89e66e19b89602691a9e",
"extension": "c",
"filename": "If.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": 3117,
"license": "MIT",
"license_type": "permissive",
"path": "/src/default/If.c",
"provenance": "stackv2-0003.json.gz:410914",
"repo_name": "skoomn/libonnx",
"revision_date": "2021-10-25T02:02:29",
"revision_id": "973f440d639027030f3c67d6f233b1a467daa232",
"snapshot_id": "ae77dcc1f27db4a038dcfd32575a51b1ede32e37",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skoomn/libonnx/973f440d639027030f3c67d6f233b1a467daa232/src/default/If.c",
"visit_date": "2023-08-28T16:21:56.480106"
} | stackv2 | #include <onnx.h>
struct operator_pdata_t {
struct onnx_graph_t * else_branch;
struct onnx_graph_t * then_branch;
};
static int If_init(struct onnx_node_t * n)
{
struct operator_pdata_t * pdat;
if((n->ninput == 1) && (n->noutput >= 1))
{
pdat = malloc(sizeof(struct operator_pdata_t));
if(pdat)
{
pdat->else_branch = onnx_graph_alloc(n->ctx, onnx_attribute_read_graph(n, "else_branch", NULL));
pdat->then_branch = onnx_graph_alloc(n->ctx, onnx_attribute_read_graph(n, "then_branch", NULL));
if(!pdat->else_branch || !pdat->then_branch)
{
if(pdat->else_branch)
onnx_graph_free(pdat->else_branch);
if(pdat->then_branch)
onnx_graph_free(pdat->then_branch);
free(pdat);
return 0;
}
n->priv = pdat;
return 1;
}
}
return 0;
}
static int If_exit(struct onnx_node_t * n)
{
struct operator_pdata_t * pdat = (struct operator_pdata_t *)n->priv;
if(pdat)
{
if(pdat->else_branch)
onnx_graph_free(pdat->else_branch);
if(pdat->then_branch)
onnx_graph_free(pdat->then_branch);
free(pdat);
}
return 1;
}
static int If_reshape(struct onnx_node_t * n)
{
struct operator_pdata_t * pdat = (struct operator_pdata_t *)n->priv;
struct onnx_tensor_t * x = n->inputs[0];
uint8_t * px = (uint8_t *)x->datas;
struct onnx_graph_t * g;
struct onnx_node_t * t;
int i;
if(px[0])
g = pdat->then_branch;
else
g = pdat->else_branch;
if(g->nlen > 0)
{
for(i = 0; i < g->nlen; i++)
{
t = &g->nodes[i];
t->reshape(t);
}
if(t)
{
for(i = 0; i < min(t->noutput, n->noutput); i++)
{
struct onnx_tensor_t * a = t->outputs[i];
struct onnx_tensor_t * b = n->outputs[i];
onnx_tensor_reshape_identity(b, a, a->type);
}
}
}
return 1;
}
static void If_operator(struct onnx_node_t * n)
{
struct operator_pdata_t * pdat = (struct operator_pdata_t *)n->priv;
struct onnx_tensor_t * x = n->inputs[0];
uint8_t * px = (uint8_t *)x->datas;
struct onnx_graph_t * g;
struct onnx_node_t * t;
int i;
if(px[0])
g = pdat->then_branch;
else
g = pdat->else_branch;
if(g->nlen > 0)
{
for(i = 0; i < g->nlen; i++)
{
t = &g->nodes[i];
t->operator(t);
}
if(t)
{
for(i = 0; i < min(t->noutput, n->noutput); i++)
{
struct onnx_tensor_t * a = t->outputs[i];
struct onnx_tensor_t * b = n->outputs[i];
if(x->type == ONNX_TENSOR_TYPE_STRING)
{
char ** pa = (char **)a->datas;
char ** pb = (char **)b->datas;
for(size_t o = 0; o < b->ndata; o++)
{
if(pb[o])
free(pb[o]);
pb[o] = strdup(pa[o]);
}
}
else
{
memcpy(b->datas, a->datas, a->ndata * onnx_tensor_type_sizeof(a->type));
}
}
}
}
}
void resolver_default_op_If(struct onnx_node_t * n)
{
if(n->opset >= 13)
{
n->init = If_init;
n->exit = If_exit;
n->reshape = If_reshape;
n->operator = If_operator;
}
else if(n->opset >= 11)
{
n->init = If_init;
n->exit = If_exit;
n->reshape = If_reshape;
n->operator = If_operator;
}
else if(n->opset >= 1)
{
n->init = If_init;
n->exit = If_exit;
n->reshape = If_reshape;
n->operator = If_operator;
}
}
| 2.375 | 2 |
2024-11-18T18:24:15.405399+00:00 | 2015-07-27T11:01:02 | 19dcfc860ed0a53f410d7fc69d433102b25848ef | {
"blob_id": "19dcfc860ed0a53f410d7fc69d433102b25848ef",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-27T11:01:02",
"content_id": "59723e22779bdb53b32081551a07b2e38d91a971",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8b9da90133c658ed0a92f3e0b43c63ee84728f44",
"extension": "c",
"filename": "userintr.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 36775757,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1846,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/examples/userintr.c",
"provenance": "stackv2-0003.json.gz:411430",
"repo_name": "megoldsby/microcsp",
"revision_date": "2015-07-27T11:01:02",
"revision_id": "b896f568bb78b9e1574ec41ca448c9ee2f62aa03",
"snapshot_id": "b8fa896b0b3889be302a31aafa39d185bda72712",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/megoldsby/microcsp/b896f568bb78b9e1574ec41ca448c9ee2f62aa03/src/examples/userintr.c",
"visit_date": "2021-01-10T07:34:59.064214"
} | stackv2 |
/**
* Two processes, one sending interrupts, one receiving them.
*/
#include "microcsp.h"
#include <stdio.h>
#define ONE_SEC 1000000000ULL
Channel chan[2];
PROCESS(Proc1)
Guard guards[2];
int intr0;
int intr1;
ENDPROC
void Proc1_rtc(void *local)
{
enum { INTR0=0, INTR1 };
Proc1 *proc1 = (Proc1 *)local;
if (initial()) {
init_alt(&proc1->guards[0], 2);
activate(&proc1->guards[0]);
activate(&proc1->guards[1]);
connect_interrupt_to_channel(in(&chan[0]), 0);
init_chanin_guard_for_interrupt(
&proc1->guards[0], in(&chan[0]), &proc1->intr0);
connect_interrupt_to_channel(in(&chan[1]), 1);
init_chanin_guard_for_interrupt(
&proc1->guards[1], in(&chan[1]), &proc1->intr1);
} else {
printf("boing!\n");
switch(selected()) {
case INTR0:
printf("INTR0 received by Proc1, intr0=%d\n", proc1->intr0);
break;
case INTR1:
printf("INTR1 received by Proc1, intr1=%d\n", proc1->intr1);
break;
}
}
}
PROCESS(Proc2)
Guard guards[1];
Timeout timeout;
uint8_t which;
ENDPROC
void Proc2_rtc(void *local)
{
Proc2 *proc2 = (Proc2 *)local;
if (initial()) {
init_alt(&proc2->guards[0], 2);
activate(&proc2->guards[0]);
init_timeout_guard(&proc2->guards[0], &proc2->timeout, Now()+ONE_SEC);
proc2->which = 0;
} else {
send_software_interrupt(proc2->which);
proc2->which = (proc2->which + 1) % 2;
init_timeout_guard(&proc2->guards[0], &proc2->timeout, Now()+ONE_SEC);
}
}
int main(int argc, char **argv)
{
initialize(32768);
Proc1 local1;
START(Proc1, &local1, 1);
Proc2 local2;
START(Proc2, &local2, 2);
run();
}
| 2.8125 | 3 |
2024-11-18T18:24:15.738565+00:00 | 2018-07-12T06:52:23 | e1666abcb71da89d52bd9f9aa53523ed6fbd5d54 | {
"blob_id": "e1666abcb71da89d52bd9f9aa53523ed6fbd5d54",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-12T06:52:23",
"content_id": "983d482be5a4bfee602f2619b67f0c2c5e8fef91",
"detected_licenses": [
"MIT"
],
"directory_id": "1988106dc94e0915bc8b80c194931891b0f4bf21",
"extension": "c",
"filename": "datagram2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 140673275,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1580,
"license": "MIT",
"license_type": "permissive",
"path": "/datagram2.c",
"provenance": "stackv2-0003.json.gz:411818",
"repo_name": "nachliel/winsock-tutorials",
"revision_date": "2018-07-12T06:52:23",
"revision_id": "6b7d3457734ac5e7a24aeb2f1ee6304b1900aa0d",
"snapshot_id": "85b42393c9c8ee111fa8c31f548307d9675214e6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nachliel/winsock-tutorials/6b7d3457734ac5e7a24aeb2f1ee6304b1900aa0d/datagram2.c",
"visit_date": "2020-03-22T21:16:32.813976"
} | stackv2 | /*
** datagram client.
*/
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
#define BUFFLEN 1024
#define PORT 41234
void main()
{
WSADATA wsaData;
struct sockaddr_in clientAddr;
int iResult, sockfd, clientLen, i = 0;
char string[BUFFLEN];
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
/*Create Client socket*/
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("socket failed:");
exit(0);
}
/* Clear Client structure */
memset((char *)&clientAddr, 0, sizeof(struct sockaddr_in));
clientAddr.sin_family = AF_INET; //For IPV4 internet protocol
clientAddr.sin_port = htons(PORT); //Assign port number on which server listening
clientAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //Assign server machine address
clientLen = sizeof(clientAddr);
/* Send data to server */
while (1)
{
printf("Enter any string\n");
scanf_s("%s", string);
/* Send string/data to server */
if (sendto(sockfd, string, BUFFLEN, 0, (struct sockaddr_in *)&clientAddr, clientLen) == -1)
{
perror("sendto failed:");
exit(1);
}
}
closesocket(sockfd);
WSACleanup();
} | 2.65625 | 3 |
2024-11-18T18:24:15.874778+00:00 | 2021-07-27T11:20:26 | ff1341c0cc4b5d0c0646a6bc220ec6dc810badec | {
"blob_id": "ff1341c0cc4b5d0c0646a6bc220ec6dc810badec",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-27T11:20:26",
"content_id": "85a2875b6df205ea4a3ac031af32fdb55da2f4a1",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "b6724a4bec9e678a3689ad7bcc9da263e1ec2f31",
"extension": "c",
"filename": "cswap.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": 9209,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/tests/thirdparty/cswap.c",
"provenance": "stackv2-0003.json.gz:411948",
"repo_name": "naveenpardeep/oshmpi",
"revision_date": "2021-07-27T11:20:26",
"revision_id": "31dd851630ef5639b7d72c4e8ba4d6172a35b7ec",
"snapshot_id": "95850b4fa52bf80202313cdafaa54fc7e6089e90",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/naveenpardeep/oshmpi/31dd851630ef5639b7d72c4e8ba4d6172a35b7ec/tests/thirdparty/cswap.c",
"visit_date": "2023-06-25T00:13:10.575447"
} | stackv2 | /*
* exercise:
* shmem_*_cswap()
* shmem_*_fadd()
* shmem_*_finc()
*/
#include <shmem.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define Vprintf if (Verbose) printf
static int *src_int;
static long *src_long;
static long long *src_llong;
static int dst_int, itmp;
static long dst_long, ltmp;
static long long dst_llong, lltmp;
static int loops = 5;
int
main(int argc, char* argv[])
{
int me, num_pes, l, pe;
int Verbose = 0;
start_pes(0);
me = _my_pe();
num_pes = _num_pes();
for (l = 0 ; l < loops ; ++l) {
if ((src_int = shmalloc(sizeof(int))) == NULL) {
printf("PE-%d int shmalloc() failed?\n", me);
exit(1);
}
*src_int = 4;
dst_int = itmp = 0;
if ((src_long = shmalloc(sizeof(long))) == NULL) {
printf("PE-%d long shmalloc() failed?\n", me);
exit(1);
}
*src_long = 8;
dst_long = ltmp = 0;
if ((src_llong = shmalloc(sizeof(long long))) == NULL) {
printf("PE-%d long long shmalloc() failed?\n", me);
exit(1);
}
*src_llong = 16;
dst_llong = lltmp = 0;
//printf("PE-%d malloc()s done.\n",me);
shmem_barrier_all();
if ( me == 0 ) {
/* integer swap */
itmp = shmem_int_g(src_int,1);
Vprintf("PE-0 Initial Conditions(int) local %d rem(%d)\n",
dst_int,itmp);
dst_int = shmem_int_cswap(src_int,*src_int,0,1);
if (dst_int != 4) {
printf("PE-%d dst_int %d != 4?\n",me,dst_int);
exit(1);
}
/* verify remote data */
itmp = shmem_int_g(src_int,1);
if (itmp != 0) {
printf("PE-%d rem %d != 0?\n",me,itmp);
exit(1);
}
Vprintf("PE-0 1st int_cswap done: local %d rem(%d)\n",dst_int,itmp);
dst_int = shmem_int_cswap(src_int,0,dst_int,1);
if (dst_int != 0) {
printf("PE-%d dst_int %d != 0?\n",me,dst_int);
exit(1);
}
/* verify remote data */
itmp = shmem_int_g(src_int,1);
if (itmp != 4) {
printf("PE-%d rem %d != 4?\n",me,itmp);
exit(1);
}
Vprintf("PE-0 2nd int_swap done: local %d rem(%d)\n",dst_int,itmp);
/* cswap() should not swap as cond(0) != remote(4) */
dst_int = shmem_int_cswap(src_int,0,0,1);
if (dst_int != 4) {
printf("PE-%d int no-swap returned dst_int %d != 4?\n",
me,dst_int);
exit(1);
}
/* verify previous cswap() did not swap */
itmp = shmem_int_g(src_int,1);
if (itmp != 4) {
printf("PE-%d failed cond int_cswap() swapped? rem(%d) != 4?\n",
me,itmp);
exit(1);
}
/* long swap */
ltmp = shmem_long_g(src_long,1);
Vprintf("PE-0 Initial Conditions(long) local %ld rem(%ld)\n",
dst_long,ltmp);
dst_long = shmem_long_cswap(src_long,*src_long,0,1);
if (dst_long != 8) {
printf("PE-%d dst_long %ld != 8?\n",me,dst_long);
exit(1);
}
/* verify remote data */
ltmp = shmem_long_g(src_long,1);
if (ltmp != 0) {
printf("PE-%d long rem(%ld) != 0?\n",me,ltmp);
exit(1);
}
Vprintf("PE-0 1st long_cswap done: local %ld rem(%ld)\n",
dst_long,ltmp);
dst_long = shmem_long_cswap(src_long,0,dst_long,1);
if (dst_long != 0) {
printf("PE-%d dst_long %ld != 0?\n",me,dst_long);
exit(1);
}
/* verify remote data */
ltmp = shmem_long_g(src_long,1);
if (ltmp != 8) {
printf("PE-%d long rem(%ld) != 8?\n",me,ltmp);
exit(1);
}
Vprintf("PE-0 2nd long_swap done: local %ld rem(%ld)\n",
dst_long,ltmp);
/* cswap() should not swap as cond(0) != remote(8) */
dst_long = shmem_long_cswap(src_long,0,0,1);
if (dst_long != 8) {
printf("PE-%d long no-swap returned dst_long %ld != 8?\n",
me,dst_long);
exit(1);
}
/* verify previous cswap() did not swap */
ltmp = shmem_long_g(src_long,1);
if (ltmp != 8) {
printf("PE-%d failed cond long_cswap() swapped? rem(%ld) != 8?\n",
me,ltmp);
exit(1);
}
/* long long swap */
lltmp = shmem_longlong_g(src_llong,1);
Vprintf("PE-0 Initial Conditions(long long) local %lld rem(%lld)\n",
dst_llong,lltmp);
dst_llong = shmem_longlong_cswap(src_llong,*src_llong,0,1);
if (dst_llong != 16) {
printf("PE-%d dst_llong %lld != 16?\n",me,dst_llong);
exit(1);
}
/* verify remote data */
lltmp = shmem_longlong_g(src_llong,1);
if (lltmp != 0) {
printf("PE-%d longlong rem(%lld) != 0?\n",me,lltmp);
exit(1);
}
Vprintf("PE-0 1st longlong_cswap done: local %lld rem(%lld)\n",
dst_llong, lltmp);
dst_llong = shmem_longlong_cswap(src_llong,0,dst_llong,1);
if (dst_llong != 0) {
printf("PE-%d dst_llong %lld != 0?\n",me,dst_llong);
exit(1);
}
/* verify remote data */
lltmp = shmem_longlong_g(src_llong,1);
if (lltmp != 16) {
printf("PE-%d long long rem(%lld) != 16?\n",me,lltmp);
exit(1);
}
Vprintf("PE-0 2nd longlong_swap done: local %lld rem(%lld)\n",
dst_llong,lltmp);
/* cswap() should not swap as cond(0) != remote(8) */
dst_llong = shmem_longlong_cswap(src_llong,0,0,1);
if (dst_llong != 16) {
printf("PE-%d longlong no-swap returned dst_llong %lld != 16?\n",
me,dst_llong);
exit(1);
}
/* verify previous cswap() did not swap */
lltmp = shmem_longlong_g(src_llong,1);
if (lltmp != 16) {
printf("PE-0 failed cond longlong_cswap() swapped? rem(%lld) != 16?\n",
lltmp);
exit(1);
}
}
else {
if (!shmem_addr_accessible(src_int,0)) {
printf("PE-%d local src_int %p not accessible from PE-%d?\n",
me, (void*)src_int, 0);
exit(1);
}
if (!shmem_addr_accessible(src_long,0)) {
printf("PE-%d local src_long %p not accessible from PE-%d?\n",
me, (void*)src_long, 0);
exit(1);
}
if (!shmem_addr_accessible(src_llong,0)) {
printf("PE-%d local src_llong %p not accessible from PE-%d?\n",
me, (void*)src_llong, 0);
exit(1);
}
}
shmem_barrier_all();
/* shmem_*fadd() exercise */
if (me == 0) {
itmp = 0;
ltmp = 0;
lltmp = 0;
*src_int = 0;
*src_long = 0;
*src_llong = 0;
}
shmem_barrier_all();
(void)shmem_int_fadd( &itmp, me+1, 0 );
(void)shmem_long_fadd( <mp, me+1, 0 );
(void)shmem_longlong_fadd( &lltmp, me+1, 0 );
shmem_barrier_all();
if (me == 0) {
int tot;
for(pe=0,tot=0; pe < num_pes; pe++)
tot += pe+1;
if ( itmp != tot )
printf("fadd() total %d != expected %d?\n",itmp,tot);
if ( ltmp != (long)tot )
printf("fadd() total %ld != expected %d?\n",ltmp,tot);
if ( lltmp != (long long)tot )
printf("fadd() total %lld != expected %d?\n",lltmp,tot);
}
shmem_barrier_all();
(void)shmem_int_finc(src_int,0);
(void)shmem_long_finc(src_long,0);
(void)shmem_longlong_finc(src_llong,0);
shmem_barrier_all();
if (me == 0) {
int tot = num_pes;
if ( *src_int != tot )
printf("finc() total %d != expected %d?\n",*src_int,tot);
if ( *src_long != (long)tot )
printf("finc() total %ld != expected %d?\n",*src_long,tot);
if ( *src_llong != (long long)tot )
printf("finc() total %lld != expected %d?\n",*src_llong,tot);
}
shmem_barrier_all();
shfree(src_int);
shfree(src_long);
shfree(src_llong);
}
if (Verbose)
fprintf(stderr,"[%d] exit\n",_my_pe());
return 0;
}
| 2.828125 | 3 |
2024-11-18T18:24:16.283963+00:00 | 2021-03-08T16:06:16 | 442835d95c5d7ccdeeb14cac5dcffb09a2616218 | {
"blob_id": "442835d95c5d7ccdeeb14cac5dcffb09a2616218",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-08T16:06:16",
"content_id": "c01c6e7463c21f14e832cb90f4adb25657be3871",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "8378d108402f81850a6fa6dca0f4ba1c8f0aeead",
"extension": "c",
"filename": "game.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 345679417,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16554,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/game.c",
"provenance": "stackv2-0003.json.gz:412333",
"repo_name": "jonaro00/NyanPongBall",
"revision_date": "2021-03-08T16:06:16",
"revision_id": "97f91b495b8397e884b7a5de8e0dee7df6b6d09a",
"snapshot_id": "cfd1ae5c16b61f9b14ae5a2f30328b02f5148bb2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jonaro00/NyanPongBall/97f91b495b8397e884b7a5de8e0dee7df6b6d09a/game.c",
"visit_date": "2023-03-22T14:38:36.734869"
} | stackv2 |
#include <stdint.h>
#include <pic32mx.h>
#include "game.h"
// Time-keeping
uint32_t ticks = -1; // Ticks since power on
int cooldown = 0; // Used for state transitions
uint32_t tick_start = 1; // used for random seed
uint32_t level_started; // time where current level started
// Special modes and debugging
uint8_t DEBUG_MODE = 0;
int *DEBUG_ADDR = &ticks;
int debug_dummy;
// Poll switch 4 for cheat mode
uint8_t cheat_mode(){
return getsw() & BTN4; // Switch 4 up = cheat mode is on
}
// Game states
#define START 0
#define MENU 1
#define GAME 2
#define GAMEOVER 3
uint8_t game_state = START, prev_game_state = START;
// Level tracking
uint8_t levels_completed, level_progress, level_type, level_transition;
int8_t current_level;
uint16_t score_req[] = {0,15,30,50,70,100,150,200,250,300,400,500,600,700,800,900,1000,2000,3000};
// Menu values
#define MENU_MAIN 0
#define MENU_SCORES 1
#define MENU_GAMEOVER 2
uint8_t menu_page = MENU_MAIN, prev_menu_page = MENU_MAIN;
char menu_choices[][CHAR_SPACES] = {
// MENU_MAIN
"4-A Scores\n3-W \n2-S \n1-D Play",
// MENU_SCORES
"4-A Back\n3-W Up\n2-S Down\n1-D Play",
// MENU_GAMEOVER
"4-A Left\n3-W Skip\n2-S Enter\n1-D Right",
};
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.!_-#$";
char name[] = "AAA";
int name_pos;
int scrollwheel_offset; // The current position of the potentiometer
void set_scrollwheel_offset(){
scrollwheel_offset = getpot()/32 - indexOf(name[name_pos], alphabet);
}
char *scoreboard;
int scoreboard_scroll, scoreboard_scroll_max;
// In-game score counter
int score;
float scoreY, scoreX;
char score_str[15] = "Score: ";
// Player
AnimUnit nyan;
#define NYAN_FLY_SPEED 0.6 // Fly speed in pong
#define NYAN_ACC_Y 0.125 // Gravity in dodgeball
// Pong units
AnimUnit ball;
#define BALL_MAX_SPEED_Y 1.2
float ball_prev_dy = -1, ball_prev_dx = -1;
// Dodgeball units
#define MAX_BALLS 6
AnimUnit balls[MAX_BALLS];
uint8_t n_balls;
Unit bullet;
// ### INTERRUPTS ### //
void interrupt_handler(){
// TIMER -- main clock
if(IFS(0) & 0x100){ // check timer interrupt bit (8)
IFS(0) &= ~0x100; // clear the interrupt flag bit
main_tick();
}
// SW1 - Toggle debug mode
else if(IFS(0) & 0x80){ // check interrupt bit
IFS(0) &= ~0x80; // clear int bit
DEBUG_MODE = DEBUG_MODE == 0 ? 1 : 0;
}
// SW4 - Toggle cheat mode
// else if(IFS(0) & 0x80000){
// IFS(0) &= ~0x80000;
// CHEAT_MODE = CHEAT_MODE == 0 ? 1 : 0;
// }
}
// Gets run as often as possible
void loop(){
// this turned out to be pretty useless
}
// Game logic every frame
void main_tick(){
ticks++;
// Get buttons pressed since last tick
getbtns();
// Start screen
if(game_state == START){
if(is_clicked(BTN4|BTN3|BTN2|BTN1)){ // wait for any button press
game_state = MENU;
tick_start = ticks;
}
screen_fill(1); // screen white
screen_draw_box(2,2,SCREEN_HEIGHT-4,SCREEN_WIDTH-4,0); // black box in middle
screen_display_string(6,23,"Nyan Pong Ball"); // title
screen_display_string(21,60,"by jonaro00"); // subtitle
screen_render();
return;
}
// Debug pause check
if(DEBUG_MODE && !is_clicked(BTN1)) return;
// Has game state changed?
uint8_t game_state_changed = prev_game_state != game_state;
prev_game_state = game_state;
// Has menu page changed?
uint8_t menu_page_changed = prev_menu_page != menu_page || game_state_changed;
prev_menu_page = menu_page;
switch(game_state){
case MENU:
switch(menu_page){
case MENU_MAIN:
if(is_clicked(BTN4)){menu_page = MENU_SCORES; return;}
if(is_clicked(BTN1)){game_state = GAME; return;}
if(menu_page_changed) menu_main_init();
menu_main_tick();
break;
case MENU_SCORES:
if(is_clicked(BTN4)){menu_page = MENU_MAIN; return;}
if(is_clicked(BTN1)){game_state = GAME; return;}
if(menu_page_changed) menu_scores_init();
if(is_pressed(BTN3)) scoreboard_scroll = max(scoreboard_scroll-1, 0);
if(is_pressed(BTN2)) scoreboard_scroll = min(scoreboard_scroll+1, scoreboard_scroll_max);
menu_scores_tick();
break;
case MENU_GAMEOVER:
if(is_clicked(BTN3)){menu_page = MENU_MAIN; return;}
if(is_clicked(BTN2)){add_Score(init_Score(name, score)); menu_page = MENU_MAIN; return;}
if(menu_page_changed) menu_gameover_init();
if(is_clicked(BTN4)){name_pos = floorMod(name_pos-1, 3); set_scrollwheel_offset();}
if(is_clicked(BTN1)){name_pos = floorMod(name_pos+1, 3); set_scrollwheel_offset();}
menu_gameover_tick();
break;
default:
break;
}
// Print menu choices
screen_display_string(0, 0, menu_choices[menu_page]);
break;
case GAME:
if(game_state_changed) game_init();
game_tick();
break;
case GAMEOVER:
if(game_state_changed) gameover_init();
gameover_tick();
break;
default:
screen_display_string(0,0,"Achievement unlocked:");
screen_display_string(8,0,"How did we get here?");
break;
}
// Debug info goes on top of everything else
if(DEBUG_MODE) print_debug(DEBUG_ADDR);
// Render the frame
screen_render();
}
// New game initialization
void game_init(){
// Initial values for every game
score = 0;
current_level = -1;
levels_completed = 0;
level_transition = 0;
// generate random backgrounds
init_bg();
// start at Pong level
level_type0_init();
}
// Game logic every tick. Manages points & levels.
void game_tick(){
if(getsw() & BTN3 && ticks % 5 == 0) score++; // Switch 3 up = free points
//# LEVEL PROGRESSION #//
level_progress = 8*(score-score_req[current_level])/(score_req[current_level+1]-score_req[current_level]);
PORTE = (0xff << 8-level_progress) & 0xff; // LEDS show progress towards next level
if(level_transition && ticks / 10 % 2 == 0) // LEDS flash while waiting for next level to start
PORTEINV = 0xff;
if(score >= score_req[current_level+1] && !level_transition){ // score for next level is achieved.
cooldown = 60; // 1s wait time
level_transition = 1; // initiate move to next level
levels_completed = (uint8_t)min(current_level+1, sizeof score_req);
}
//# MOVEMENT, COLLISIONS, GAMESTATE #//
if(!level_type) level_type0_update();
else level_type1_update();
//# GRAPHICS #//
// Score counter is drawn regardless of level_type
insert(itoaconv(score), score_str, 7, 1);
screen_display_string(scoreY, scoreX, score_str);
// Level-specific objects
if(!level_type) level_type0_draw();
else level_type1_draw();
// Player is drawn regardless of level_type
draw_AnimUnit(&nyan);
}
// ### PONG LEVEL ### //
// Pong initialization
void level_type0_init(){
// Set level-specific values
level_type = 0;
current_level++;
cooldown = 20;
scoreY = 12; scoreX = 50;
// Set up units for current level
init_AnimUnit(&ball,16,25,0.8F,1.7F+current_level*0.1F,0,0,11,11,&t_ball[0][0][0],1,BALL_FRAMES,32);
init_AnimUnit(&nyan,14,0,0,0,0,0,14,23,&t_nyancat[0][0][0],1,NYANCAT_FRAMES,4);
}
// Pong update cycle
void level_type0_update(){
// Check for transition to next level
if(ball.x > SCREEN_WIDTH+80 && level_transition){
if(cooldown-- == 0){
level_transition = 0;
level_type1_init();
return;
}
}
// Background
update_star_bg();
// Player controls
if(is_pressed(BTN3)) // press W (fly up)
nyan.y = max(nyan.y-NYAN_FLY_SPEED, 0);
if(is_pressed(BTN2)) // press S (fly down)
nyan.y = min(nyan.y+NYAN_FLY_SPEED, SCREEN_HEIGHT-nyan.h);
if(is_clicked(BTN4)) // click A (turn left)
nyan.xdir = -1;
if(is_clicked(BTN1)) // click D (turn right)
nyan.xdir = 1;
// Initial wait before the ball is served
if(!level_transition){
if(cooldown > 0){
cooldown--;
return;
}
}
// Ball movement
if (ball.y < 1) ball.dy = abs(ball.dy); // top wall bounce
else if(ball.y+ball.h >= SCREEN_HEIGHT-1) ball.dy = -abs(ball.dy); // bot wall bounce
float yd = (ball.y+(ball.h-1)/2)-(nyan.y+(nyan.h-1)/2); // difference between ball center and nyan center
if(ball.x+ball.w > SCREEN_WIDTH-1 && !level_transition) ball.dx = -abs(ball.dx); // right wall bounce
else if(abs(ball.x - (nyan.x+nyan.w-3)) < 2 && // ball x at nyan nose
abs(yd) < nyan.h/2 && // ball center within nyan y
ball.dx < 0) // ball going left
{ // Ball & nyan collision
ball.dx = -ball.dx; // dx is flipped
float mdy = 0; // modification to dy
if(!((ball.dy < 0 && yd <= 1) || (ball.dy > 0 && yd >= -1))) // ball hit on closer side
mdy = yd / 3;
else if((ball.dy < 0 && yd <= -2) || (ball.dy > 0 && yd >= 2)) // ball hit on further side
mdy = yd / 5;
ball.dy = bound(-BALL_MAX_SPEED_Y, ball.dy+mdy, BALL_MAX_SPEED_Y); // Add mdy and constrain to max speed
score++;
}
// change spin direction and speed
if(sign(ball_prev_dy) != sign(ball.dy) || sign(ball_prev_dx) != sign(ball.dx)){
ball.xdir = ixor(ball.dy, ball.dx);
ball.period = 48-40*abs(ball.dy/BALL_MAX_SPEED_Y);
}
ball_prev_dy = ball.dy; ball_prev_dx = ball.dx;
move_Unit(&ball);
// Death condition
if(ball.x < -40){
if(cheat_mode()) ball.x += 170;
else{
game_state = GAMEOVER;
return;
}
}
}
// Pong draw routine
void level_type0_draw(){
// Background
draw_star_bg();
// Walls
screen_draw_box(0,30,1,SCREEN_WIDTH-30,1);
screen_draw_box(SCREEN_HEIGHT-1,30,1,SCREEN_WIDTH-30,1);
if(!level_transition)
screen_draw_box(0,SCREEN_WIDTH-1,SCREEN_HEIGHT,1,1);
// Ball
draw_AnimUnit(&ball);
}
// ### DODGEBALL LEVEL ### //
// Dodgeball initialization
void level_type1_init(){
// Level-specific values
level_type = 1;
current_level++;
level_started = ticks;
n_balls = min(3+current_level/2, MAX_BALLS);
cooldown = 20;
scoreY = 0; scoreX = 0;
// Deactivate leftovers from previous levels
uint8_t i;
for(i = 0; i < MAX_BALLS; i++)
balls[i].active = 0;
bullet.active = 0;
// Set player
init_AnimUnit(&nyan,SCREEN_HEIGHT-15,(SCREEN_WIDTH-23)/2,0,0,0.125F,0,14,23,&t_nyancat[0][0][0],1,NYANCAT_FRAMES,4);
}
// Dodgeball update cycle
void level_type1_update(){
// Death check
if(!nyan.alive && !unit_on_screen(&nyan)){
game_state = GAMEOVER;
return;
}
// Background
update_rain_bg();
// Transition check
uint8_t i;
for(i = 0; i < n_balls; i++)
if(balls[i].active)
break;
// if no balls are active and transition is ongoing, run countdown towards next level
if(i == n_balls && level_transition){
if(cooldown-- == 0){
level_transition = 0;
level_type0_init();
return;
}
}
// Player controls
if(is_clicked(BTN3)) // click W (jump)
if(nyan.y == SCREEN_HEIGHT-nyan.h-1)
nyan.dy = -2.2F;
if(is_clicked(BTN2)) // click S (fast fall)
nyan.dy = 1.3F;
if(is_clicked(BTN4)) // click A (turn left / shoot)
if(nyan.xdir == 1)
nyan.xdir = -1;
else if(!bullet.active)
init_Unit(&bullet, nyan.y+5, nyan.x-5, 0, -0.5F, 0, -0.1F, 7, 8, &t_bullet[0][0], -1);
if(is_clicked(BTN1)) // click D (turn right / shoot)
if(nyan.xdir == -1)
nyan.xdir = 1;
else if(!bullet.active)
init_Unit(&bullet, nyan.y+5, nyan.x+nyan.w-3, 0, 0.5F, 0, 0.1F, 7, 8, &t_bullet[0][0], 1);
// MOVE NYAN & BULLET
move_Unit(&nyan);
nyan.y = min(nyan.y, SCREEN_HEIGHT-nyan.h-1);
move_Unit(&bullet);
// MOVEMENT, DEATH & COLLISIONS FOR ALL BALLS
for(i = 0; i < n_balls; i++){
AnimUnit * b = &balls[i];
if(!b->active) continue;
move_Unit(b);
// Is ball OOB and dead/past the stage?
if(!unit_on_screen(b)){
if(!b->alive || ((b->x < 0 && b->dx < 0) || (b->x > 0 && b->dx > 0))){
b->active = 0;
}
}
// COLLISIONS
// dead balls are skipped for collisions
if(!b->alive) continue;
// Nyan touches ball
if(collides(&nyan, b)){
if(nyan.y+nyan.h-1 - b->y < 3 && nyan.alive){ // Nyan jumped on ball
nyan.dy = min(nyan.dy, -1);
b->ay = 0.25F;
b->alive = 0;
score++;
}
else if(!cheat_mode()){ // Death
nyan.alive = 0;
nyan.dy = -2; nyan.ay = 0;
nyan.dx = sign(b->dx)*3;
return;
}
}
// Bullet hits ball
else if(collides(&bullet, b) && bullet.active){
b->dy = -1.5F;
b->dx = bullet.dx * 1.3F;
b->alive = 0;
bullet.active = 0;
score++;
}
}
// Bullet OOB
if(bullet.active && !unit_on_screen(&bullet))
bullet.active = 0;
// OBJECT SPAWNING
if(!level_transition){ // Don't spawn when next level score is achieved
if(cooldown > 0){ // Start of level peace period
cooldown--;
return;
}
if((ticks-level_started) % 14 == 13){ // frequency of spawn chances
if(random() < 0.2F){ // chance of spawn
// spawn position
int bxdir = random() < 0.55F ? -1 : 1;
float h = random() < 0.75F ? SCREEN_HEIGHT-12 : 3;
// spawn one if slot availible
for(i = 0; i < n_balls; i++){
if(!balls[i].active){
init_AnimUnit(&balls[i],h,bxdir==1?-11:SCREEN_WIDTH,0,bxdir*(0.4F+current_level*0.1F),0,0,11,11,&t_ball[0][0][0],bxdir,BALL_FRAMES,10);
break;
}
}
}
}
}
}
// Dodgeball draw routine
void level_type1_draw(){
// Background
draw_rain_bg();
// Ground
screen_draw_box(SCREEN_HEIGHT-1,0,1,SCREEN_WIDTH,1);
// Balls
uint8_t i;
for(i = 0; i < n_balls; i++)
draw_AnimUnit(&balls[i]);
// Bullet
draw_Unit(&bullet);
}
// MENU PAGES VALUES & UPDATES
void gameover_init(){
cooldown = 70; // Time to display gameover screen
PORTECLR = 0xff; // Shut off LEDs
}
void gameover_tick(){
screen_display_string(10, 30, "Game over!");
if(cooldown--) return;
game_state = MENU;
menu_page = MENU_GAMEOVER;
}
void menu_main_init(){
init_AnimUnit(&ball,20,89,0,0,0,0,11,11,&t_ball[0][0][0],1,BALL_FRAMES,8);
init_AnimUnit(&nyan,17,64,0,0,0,0,14,23,&t_nyancat[0][0][0],1,NYANCAT_FRAMES,4);
}
void menu_main_tick(){
screen_draw_box(0,61,SCREEN_HEIGHT,1,1);
screen_display_string(0, 67, "Nyan");
screen_display_string(10, 87, "Pong");
screen_display_string(20, 107, "Ball");
draw_AnimUnit(&ball);
draw_AnimUnit(&nyan);
}
void menu_scores_init(){
scoreboard = get_scores_page();
scoreboard_scroll = 0;
scoreboard_scroll_max = max(0, (get_scores_len()-4)*8);
}
void menu_scores_tick(){
screen_draw_box(0,50,SCREEN_HEIGHT,1,1);
screen_display_string(-scoreboard_scroll, 52, scoreboard);
}
void menu_gameover_init(){
name_pos = 0; // selected character
set_scrollwheel_offset();
}
void menu_gameover_tick(){
screen_draw_box(0,56,SCREEN_HEIGHT,1,1);
screen_display_string(0, 59, score_str);
screen_display_string(8, 59, "Enter name:");
name[name_pos] = alphabet[floorMod(getpot()/32 - scrollwheel_offset, 32)];
screen_display_string(20, 82, name);
screen_draw_box(28,82+name_pos*6,1,6,1); // selected character underline marker
}
| 2.421875 | 2 |
2024-11-18T18:24:17.258855+00:00 | 2015-08-20T22:21:19 | aea39ef0c4b0f66c4f7cb3b5d77ff81d5cf73596 | {
"blob_id": "aea39ef0c4b0f66c4f7cb3b5d77ff81d5cf73596",
"branch_name": "refs/heads/master",
"committer_date": "2015-08-20T22:21:19",
"content_id": "dbb467d39952a23c3079e078cfe38888616449b0",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "76819d7ec89b0d59cc54c0e554ed176f6668ffa2",
"extension": "c",
"filename": "st_scenes.c",
"fork_events_count": 0,
"gha_created_at": "2015-02-02T15:34:03",
"gha_event_created_at": "2015-02-02T15:34:06",
"gha_language": "C",
"gha_license_id": null,
"github_id": 30193672,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11971,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/test/suite/st_scenes.c",
"provenance": "stackv2-0003.json.gz:413620",
"repo_name": "clibs/sophia",
"revision_date": "2015-08-20T22:21:19",
"revision_id": "2b66cc065e96d8a7971056e87b617395b2961ca6",
"snapshot_id": "8099ecff20e791c2b03d5c7cae9c39fee9d89cc9",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/clibs/sophia/2b66cc065e96d8a7971056e87b617395b2961ca6/test/suite/st_scenes.c",
"visit_date": "2021-01-16T22:43:19.753961"
} | stackv2 |
/*
* sophia database
* sphia.org
*
* Copyright (c) Dmitry Simonenko
* BSD License
*/
#include <sophia.h>
#include <libss.h>
#include <libsf.h>
#include <libsr.h>
#include <libsv.h>
#include <libso.h>
#include <libst.h>
void st_scene_rmrf(stscene *s ssunused)
{
rmrf(st_r.conf->sophia_dir);
rmrf(st_r.conf->backup_dir);
rmrf(st_r.conf->log_dir);
rmrf(st_r.conf->db_dir);
}
void st_scene_test(stscene *s ssunused)
{
if (st_r.verbose) {
fprintf(st_r.output, ".test");
fflush(st_r.output);
}
st_r.test->function();
st_r.stat_test++;
if (st_r.conf->report) {
int percent = (st_r.stat_test * 100.0) / st_r.suite.total;
if (percent == st_r.report)
return;
st_r.report = percent;
fprintf(stdout, "complete %02d%% (%d tests out of %d)\n",
percent,
st_r.stat_test,
st_r.suite.total);
}
}
void st_scene_pass(stscene *s ssunused)
{
fprintf(st_r.output, ": ok\n");
fflush(st_r.output);
}
void st_scene_init(stscene *s ssunused)
{
st_listinit(&st_r.gc, 1);
ss_aopen(&st_r.a, &ss_stda);
sr_schemeinit(&st_r.scheme);
memset(&st_r.injection, 0, sizeof(st_r.injection));
sr_errorinit(&st_r.error);
sr_seqinit(&st_r.seq);
st_r.crc = ss_crc32c_function();
st_r.fmt = SF_KV;
st_r.fmt_storage = SF_SRAW;
st_r.compression = NULL;
memset(&st_r.r, 0, sizeof(st_r.r));
st_r.key_start = 8;
st_r.key_end = 32;
st_r.value_start = 4;
st_r.value_end = 4;
}
void st_scene_scheme_u32(stscene *s ssunused)
{
srkey *part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key") == 0 );
t( sr_keyset(part, &st_r.a, "u32") == 0 );
}
void st_scene_rt(stscene *s ssunused)
{
sr_init(&st_r.r, &st_r.error, &st_r.a,
NULL, /* quota */
&st_r.seq,
st_r.fmt,
st_r.fmt_storage,
NULL, /* update */
&st_r.scheme,
&st_r.injection,
st_r.crc,
st_r.compression);
st_generator_init(&st_r.g, &st_r.r,
st_r.key_start,
st_r.key_end,
st_r.value_start,
st_r.value_end);
}
void st_scene_gc(stscene *s ssunused)
{
st_listfree(&st_r.gc, &st_r.a);
ss_aclose(&st_r.a);
sr_errorfree(&st_r.error);
sr_seqfree(&st_r.seq);
sr_schemefree(&st_r.scheme, &st_r.a);
}
void st_scene_env(stscene *s ssunused)
{
if (st_r.verbose) {
fprintf(st_r.output, ".env");
fflush(st_r.output);
}
t( st_r.env == NULL );
t( st_r.db == NULL );
void *env = sp_env();
t( env != NULL );
st_r.env = env;
t( sp_setstring(env, "sophia.path", st_r.conf->sophia_dir, 0) == 0 );
t( sp_setint(env, "scheduler.threads", 0) == 0 );
t( sp_setint(env, "compaction.page_checksum", 1) == 0 );
t( sp_setint(env, "log.enable", 1) == 0 );
t( sp_setstring(env, "log.path", st_r.conf->log_dir, 0) == 0 );
t( sp_setint(env, "log.sync", 0) == 0 );
t( sp_setint(env, "log.rotate_sync", 0) == 0 );
t( sp_setstring(env, "db", "test", 0) == 0 );
t( sp_setstring(env, "db.test.path", st_r.conf->db_dir, 0) == 0 );
t( sp_setstring(env, "db.test.format", "kv", 0) == 0 );
t( sp_setint(env, "db.test.sync", 0) == 0 );
t( sp_setint(env, "db.test.mmap", 0) == 0 );
t( sp_setstring(env, "db.test.compression", "none", 0) == 0 );
t( sp_setstring(env, "db.test.index.key", "u32", 0) == 0 );
st_r.db = sp_getobject(env, "db.test");
t( st_r.db != NULL );
}
void st_scene_branch_wm_1(stscene *s ssunused)
{
t( sp_setint(st_r.env, "compaction.0.branch_wm", 1) == 0 );
}
void st_scene_thread_5(stscene *s ssunused)
{
if (st_r.verbose) {
fprintf(st_r.output, ".thread_5");
fflush(st_r.output);
}
t( sp_setint(st_r.env, "scheduler.threads", 5) == 0 );
}
void st_scene_open(stscene *s ssunused)
{
if (st_r.verbose) {
fprintf(st_r.output, ".open");
fflush(st_r.output);
}
t( sp_open(st_r.env) == 0 );
}
void st_scene_destroy(stscene *s ssunused)
{
if (st_r.verbose) {
fprintf(st_r.output, ".destroy");
fflush(st_r.output);
}
t( st_r.env != NULL );
t( sp_destroy(st_r.env) == 0 );
st_r.env = NULL;
st_r.db = NULL;
}
void st_scene_truncate(stscene *s ssunused)
{
if (st_r.verbose) {
fprintf(st_r.output, ".truncate");
fflush(st_r.output);
}
void *c = sp_cursor(st_r.env);
t( c != NULL );
void *o = sp_object(st_r.db);
t( o != NULL );
t( sp_setstring(o, "order", ">=", 0) == 0 );
while ((o = sp_get(c, o))) {
void *k = sp_object(st_r.db);
t( k != NULL );
int valuesize;
void *value = sp_getstring(o, "value", &valuesize);
sp_setstring(k, "value", value, valuesize);
int i = 0;
while (i < st_r.r.scheme->count) {
int keysize;
void *key = sp_getstring(o, st_r.r.scheme->parts[i].name, &keysize);
sp_setstring(k, st_r.r.scheme->parts[i].name, key, keysize);
i++;
}
t( sp_delete(st_r.db, k) == 0 );
}
t( sp_destroy(c) == 0 );
}
void st_scene_recover(stscene *s ssunused)
{
fprintf(st_r.output, "\n (recover) ");
fflush(st_r.output);
}
void st_scene_phase_compaction(stscene *s)
{
st_r.phase_compaction_scene = s->state;
st_r.phase_compaction = 0;
if (st_r.verbose == 0)
return;
switch (s->state) {
case 0:
fprintf(st_r.output, ".in_memory");
fflush(st_r.output);
break;
case 1:
fprintf(st_r.output, ".branch");
fflush(st_r.output);
break;
case 2:
fprintf(st_r.output, ".compact");
fflush(st_r.output);
break;
case 3:
fprintf(st_r.output, ".logrotate_gc");
fflush(st_r.output);
break;
case 4:
fprintf(st_r.output, ".branch_compact");
fflush(st_r.output);
break;
default: assert(0);
}
}
void st_scene_phase_scheme_int(stscene *s)
{
srkey *part;
switch (s->state) {
case 0:
if (st_r.verbose) {
fprintf(st_r.output, ".scheme_u32");
fflush(st_r.output);
}
part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key") == 0 );
t( sr_keyset(part, &st_r.a, "u32") == 0 );
t( sp_setstring(st_r.env, "db.test.index.key", "u32", 0) == 0 );
break;
case 1:
if (st_r.verbose) {
fprintf(st_r.output, ".scheme_u64");
fflush(st_r.output);
}
part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key") == 0 );
t( sr_keyset(part, &st_r.a, "u64") == 0 );
t( sp_setstring(st_r.env, "db.test.index.key", "u64", 0) == 0 );
break;
case 2:
if (st_r.verbose) {
fprintf(st_r.output, ".scheme_u32_u32");
fflush(st_r.output);
}
part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key") == 0 );
t( sr_keyset(part, &st_r.a, "u32") == 0 );
part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key_b") == 0 );
t( sr_keyset(part, &st_r.a, "u32") == 0 );
t( sp_setstring(st_r.env, "db.test.index.key", "u32", 0) == 0 );
t( sp_setstring(st_r.env, "db.test.index", "key_b", 0) == 0 );
t( sp_setstring(st_r.env, "db.test.index.key_b", "u32", 0) == 0 );
break;
default: assert(0);
}
}
void st_scene_phase_scheme(stscene *s)
{
srkey *part;
switch (s->state) {
case 0:
if (st_r.verbose) {
fprintf(st_r.output, ".scheme_u32");
fflush(st_r.output);
}
part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key") == 0 );
t( sr_keyset(part, &st_r.a, "u32") == 0 );
t( sp_setstring(st_r.env, "db.test.index.key", "u32", 0) == 0 );
break;
case 1:
if (st_r.verbose) {
fprintf(st_r.output, ".scheme_u64");
fflush(st_r.output);
}
part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key") == 0 );
t( sr_keyset(part, &st_r.a, "u64") == 0 );
t( sp_setstring(st_r.env, "db.test.index.key", "u64", 0) == 0 );
break;
case 2:
if (st_r.verbose) {
fprintf(st_r.output, ".scheme_string");
fflush(st_r.output);
}
part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key") == 0 );
t( sr_keyset(part, &st_r.a, "string") == 0 );
t( sp_setstring(st_r.env, "db.test.index.key", "string", 0) == 0 );
break;
case 3:
if (st_r.verbose) {
fprintf(st_r.output, ".scheme_u32_u32");
fflush(st_r.output);
}
part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key") == 0 );
t( sr_keyset(part, &st_r.a, "u32") == 0 );
part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key_b") == 0 );
t( sr_keyset(part, &st_r.a, "u32") == 0 );
t( sp_setstring(st_r.env, "db.test.index.key", "u32", 0) == 0 );
t( sp_setstring(st_r.env, "db.test.index", "key_b", 0) == 0 );
t( sp_setstring(st_r.env, "db.test.index.key_b", "u32", 0) == 0 );
break;
case 4:
if (st_r.verbose) {
fprintf(st_r.output, ".scheme_string_u32");
fflush(st_r.output);
}
part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key") == 0 );
t( sr_keyset(part, &st_r.a, "string") == 0 );
part = sr_schemeadd(&st_r.scheme, &st_r.a);
t( sr_keysetname(part, &st_r.a, "key_b") == 0 );
t( sr_keyset(part, &st_r.a, "u32") == 0 );
t( sp_setstring(st_r.env, "db.test.index.key", "string", 0) == 0 );
t( sp_setstring(st_r.env, "db.test.index", "key_b", 0) == 0 );
t( sp_setstring(st_r.env, "db.test.index.key_b", "u32", 0) == 0 );
break;
default: assert(0);
}
}
void st_scene_phase_format(stscene *s)
{
switch (s->state) {
case 0:
if (st_r.verbose) {
fprintf(st_r.output, ".fmt_kv");
fflush(st_r.output);
}
st_r.fmt = SF_KV;
t( sp_setstring(st_r.env, "db.test.format", "kv", 0) == 0 );
break;
case 1:
if (st_r.verbose) {
fprintf(st_r.output, ".fmt_doc");
fflush(st_r.output);
}
st_r.fmt = SF_DOCUMENT;
t( sp_setstring(st_r.env, "db.test.format", "document", 0) == 0 );
break;
default: assert(0);
}
}
void st_scene_phase_storage(stscene *s)
{
if (st_r.fmt == SF_DOCUMENT)
s->statemax = 3;
switch (s->state) {
case 0:
if (st_r.verbose) {
fprintf(st_r.output, ".storage_default");
fflush(st_r.output);
}
break;
case 1:
if (st_r.verbose) {
fprintf(st_r.output, ".storage_compression");
fflush(st_r.output);
}
t( sp_setstring(st_r.env, "db.test.compression", "lz4", 0) == 0 );
break;
case 2:
if (st_r.verbose) {
fprintf(st_r.output, ".storage_mmap");
fflush(st_r.output);
}
t( sp_setint(st_r.env, "db.test.mmap", 1) == 0 );
break;
case 3:
if (st_r.verbose) {
fprintf(st_r.output, ".storage_mmap_compression");
fflush(st_r.output);
}
t( sp_setint(st_r.env, "db.test.mmap", 1) == 0 );
t( sp_setstring(st_r.env, "db.test.compression", "lz4", 0) == 0 );
break;
case 4:
if (st_r.verbose) {
fprintf(st_r.output, ".storage_compression_key");
fflush(st_r.output);
}
t( sp_setint(st_r.env, "db.test.compression_key", 1) == 0 );
break;
case 5:
if (st_r.verbose) {
fprintf(st_r.output, ".storage_mmap_compression_key");
fflush(st_r.output);
}
t( sp_setint(st_r.env, "db.test.mmap", 1) == 0 );
t( sp_setint(st_r.env, "db.test.compression_key", 1) == 0 );
break;
case 6:
if (st_r.verbose) {
fprintf(st_r.output, ".storage_compression_compression_key");
fflush(st_r.output);
}
t( sp_setstring(st_r.env, "db.test.compression", "lz4", 0) == 0 );
t( sp_setint(st_r.env, "db.test.compression_key", 1) == 0 );
break;
case 7:
if (st_r.verbose) {
fprintf(st_r.output, ".storage_mmap_compression_compression_key");
fflush(st_r.output);
}
t( sp_setint(st_r.env, "db.test.mmap", 1) == 0 );
t( sp_setstring(st_r.env, "db.test.compression", "lz4", 0) == 0 );
t( sp_setint(st_r.env, "db.test.compression_key", 1) == 0 );
break;
default: assert(0);
}
}
void st_scene_phase_size(stscene *s)
{
switch (s->state) {
case 0:
if (st_r.verbose) {
fprintf(st_r.output, ".size_8byte");
fflush(st_r.output);
}
st_r.value_start = 8;
st_r.value_end = 8;
break;
case 1:
if (st_r.verbose) {
fprintf(st_r.output, ".size_1Kb");
fflush(st_r.output);
}
st_r.value_start = 1024;
st_r.value_end = 1024;
break;
case 2:
if (st_r.verbose) {
fprintf(st_r.output, ".size_512Kb");
fflush(st_r.output);
}
st_r.value_start = 512 * 1024;
st_r.value_end = 512 * 1024;
break;
default: assert(0);
}
}
| 2.078125 | 2 |
2024-11-18T18:24:17.324270+00:00 | 2016-11-01T13:16:44 | 657b7516e00060f4a99816fbe73fc18eb684ac31 | {
"blob_id": "657b7516e00060f4a99816fbe73fc18eb684ac31",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-01T13:16:44",
"content_id": "a1f0e604d401e2c957bf935ce302180fef08147c",
"detected_licenses": [
"NCSA"
],
"directory_id": "b5a214062f140389527479802d98d414d8e41dc6",
"extension": "c",
"filename": "constructor-attribute.c",
"fork_events_count": 5,
"gha_created_at": "2016-11-01T14:32:02",
"gha_event_created_at": "2020-04-30T11:36:08",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 72544381,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 606,
"license": "NCSA",
"license_type": "permissive",
"path": "/test/CodeGen/constructor-attribute.c",
"provenance": "stackv2-0003.json.gz:413750",
"repo_name": "Codeon-GmbH/mulle-clang",
"revision_date": "2016-11-01T13:16:44",
"revision_id": "2f6104867287dececb46e8d93dd9246aad47c282",
"snapshot_id": "f050d6d8fb64689a1e4b039c4a6513823de9b430",
"src_encoding": "UTF-8",
"star_events_count": 29,
"url": "https://raw.githubusercontent.com/Codeon-GmbH/mulle-clang/2f6104867287dececb46e8d93dd9246aad47c282/test/CodeGen/constructor-attribute.c",
"visit_date": "2021-07-18T07:45:29.083064"
} | stackv2 | // RUN: %clang_cc1 -emit-llvm -o %t %s
// RUN: grep -e "global_ctors.*@A" %t
// RUN: grep -e "global_dtors.*@B" %t
// RUN: grep -e "global_ctors.*@C" %t
// RUN: grep -e "global_dtors.*@D" %t
int printf(const char *, ...);
void A() __attribute__((constructor));
void B() __attribute__((destructor));
void A() {
printf("A\n");
}
void B() {
printf("B\n");
}
static void C() __attribute__((constructor));
static void D() __attribute__((destructor));
static int foo() {
return 10;
}
static void C() {
printf("A: %d\n", foo());
}
static void D() {
printf("B\n");
}
int main() {
return 0;
}
| 2.25 | 2 |
2024-11-18T18:56:25.119186+00:00 | 2015-04-28T05:49:07 | 29859e4aaaa01efb1147592dfcf3e6009c1d1b32 | {
"blob_id": "29859e4aaaa01efb1147592dfcf3e6009c1d1b32",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-28T05:49:07",
"content_id": "e12c694e49cf673f78e7bdf59c1fa4ca5951ce9b",
"detected_licenses": [
"MIT"
],
"directory_id": "2e45e8daa35300424b4007be2251dfeddb0d2afa",
"extension": "c",
"filename": "exec.c",
"fork_events_count": 1,
"gha_created_at": "2015-04-18T04:19:42",
"gha_event_created_at": "2020-03-07T09:55:58",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 34152105,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9174,
"license": "MIT",
"license_type": "permissive",
"path": "/linux-0.11-devel-040923/fs/exec.c",
"provenance": "stackv2-0004.json.gz:19239",
"repo_name": "huangbop/skywalker",
"revision_date": "2015-04-28T05:49:07",
"revision_id": "31d6d990ddfe8533c66614038174381f16015bdf",
"snapshot_id": "34f2eea9bcb5874541b56ba9fe591081a6c98b47",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/huangbop/skywalker/31d6d990ddfe8533c66614038174381f16015bdf/linux-0.11-devel-040923/fs/exec.c",
"visit_date": "2021-01-01T19:52:36.062806"
} | stackv2 | /*
* linux/fs/exec.c
*
* (C) 1991 Linus Torvalds
*/
/*
* #!-checking implemented by tytso.
*/
/*
* Demand-loading implemented 01.12.91 - no need to read anything but
* the header into memory. The inode of the executable is put into
* "current->executable", and page faults do the actual loading. Clean.
*
* Once more I can proudly say that linux stood up to being changed: it
* was less than 2 hours work to get demand-loading completely implemented.
*/
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <a.out.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <asm/segment.h>
extern int sys_exit(int exit_code);
extern int sys_close(int fd);
/*
* MAX_ARG_PAGES defines the number of pages allocated for arguments
* and envelope for the new program. 32 should suffice, this gives
* a maximum env+arg of 128kB !
*/
#define MAX_ARG_PAGES 32
int sys_uselib()
{
return -ENOSYS;
}
/*
* create_tables() parses the env- and arg-strings in new user
* memory and creates the pointer tables from them, and puts their
* addresses on the "stack", returning the new stack pointer value.
*/
static unsigned long * create_tables(char * p,int argc,int envc)
{
unsigned long *argv,*envp;
unsigned long * sp;
sp = (unsigned long *) (0xfffffffc & (unsigned long) p);
sp -= envc+1;
envp = sp;
sp -= argc+1;
argv = sp;
put_fs_long((unsigned long)envp,--sp);
put_fs_long((unsigned long)argv,--sp);
put_fs_long((unsigned long)argc,--sp);
while (argc-->0) {
put_fs_long((unsigned long) p,argv++);
while (get_fs_byte(p++)) /* nothing */ ;
}
put_fs_long(0,argv);
while (envc-->0) {
put_fs_long((unsigned long) p,envp++);
while (get_fs_byte(p++)) /* nothing */ ;
}
put_fs_long(0,envp);
return sp;
}
/*
* count() counts the number of arguments/envelopes
*/
static int count(char ** argv)
{
int i=0;
char ** tmp;
if (tmp = argv)
while (get_fs_long((unsigned long *) (tmp++)))
i++;
return i;
}
/*
* 'copy_string()' copies argument/envelope strings from user
* memory to free pages in kernel mem. These are in a format ready
* to be put directly into the top of new user memory.
*
* Modified by TYT, 11/24/91 to add the from_kmem argument, which specifies
* whether the string and the string array are from user or kernel segments:
*
* from_kmem argv * argv **
* 0 user space user space
* 1 kernel space user space
* 2 kernel space kernel space
*
* We do this by playing games with the fs segment register. Since it
* it is expensive to load a segment register, we try to avoid calling
* set_fs() unless we absolutely have to.
*/
static unsigned long copy_strings(int argc,char ** argv,unsigned long *page,
unsigned long p, int from_kmem)
{
char *tmp, *pag;
int len, offset = 0;
unsigned long old_fs, new_fs;
if (!p)
return 0; /* bullet-proofing */
new_fs = get_ds();
old_fs = get_fs();
if (from_kmem==2)
set_fs(new_fs);
while (argc-- > 0) {
if (from_kmem == 1)
set_fs(new_fs);
if (!(tmp = (char *)get_fs_long(((unsigned long *)argv)+argc)))
panic("argc is wrong");
if (from_kmem == 1)
set_fs(old_fs);
len=0; /* remember zero-padding */
do {
len++;
} while (get_fs_byte(tmp++));
if (p-len < 0) { /* this shouldn't happen - 128kB */
set_fs(old_fs);
return 0;
}
while (len) {
--p; --tmp; --len;
if (--offset < 0) {
offset = p % PAGE_SIZE;
if (from_kmem==2)
set_fs(old_fs);
if (!(pag = (char *) page[p/PAGE_SIZE]) &&
!(pag = (char *) page[p/PAGE_SIZE] =
(unsigned long *) get_free_page()))
return 0;
if (from_kmem==2)
set_fs(new_fs);
}
*(pag + offset) = get_fs_byte(tmp);
}
}
if (from_kmem==2)
set_fs(old_fs);
return p;
}
static unsigned long change_ldt(unsigned long text_size,unsigned long * page)
{
unsigned long code_limit,data_limit,code_base,data_base;
int i;
code_limit = text_size+PAGE_SIZE -1;
code_limit &= 0xFFFFF000;
data_limit = 0x4000000;
code_base = get_base(current->ldt[1]);
data_base = code_base;
set_base(current->ldt[1],code_base);
set_limit(current->ldt[1],code_limit);
set_base(current->ldt[2],data_base);
set_limit(current->ldt[2],data_limit);
/* make sure fs points to the NEW data segment */
__asm__("pushl $0x17\n\tpop %%fs"::);
data_base += data_limit;
for (i=MAX_ARG_PAGES-1 ; i>=0 ; i--) {
data_base -= PAGE_SIZE;
if (page[i])
put_page(page[i],data_base);
}
return data_limit;
}
/*
* 'do_execve()' executes a new program.
*/
int do_execve(unsigned long * eip,long tmp,char * filename,
char ** argv, char ** envp)
{
struct m_inode * inode;
struct buffer_head * bh;
struct exec ex;
unsigned long page[MAX_ARG_PAGES];
int i,argc,envc;
int e_uid, e_gid;
int retval;
int sh_bang = 0;
unsigned long p=PAGE_SIZE*MAX_ARG_PAGES-4;
if ((0xffff & eip[1]) != 0x000f)
panic("execve called from supervisor mode");
for (i=0 ; i<MAX_ARG_PAGES ; i++) /* clear page-table */
page[i]=0;
if (!(inode=namei(filename))) /* get executables inode */
return -ENOENT;
argc = count(argv);
envc = count(envp);
restart_interp:
if (!S_ISREG(inode->i_mode)) { /* must be regular file */
retval = -EACCES;
goto exec_error2;
}
i = inode->i_mode;
e_uid = (i & S_ISUID) ? inode->i_uid : current->euid;
e_gid = (i & S_ISGID) ? inode->i_gid : current->egid;
if (current->euid == inode->i_uid)
i >>= 6;
else if (current->egid == inode->i_gid)
i >>= 3;
if (!(i & 1) &&
!((inode->i_mode & 0111) && suser())) {
retval = -ENOEXEC;
goto exec_error2;
}
if (!(bh = bread(inode->i_dev,inode->i_zone[0]))) {
retval = -EACCES;
goto exec_error2;
}
ex = *((struct exec *) bh->b_data); /* read exec-header */
if ((bh->b_data[0] == '#') && (bh->b_data[1] == '!') && (!sh_bang)) {
/*
* This section does the #! interpretation.
* Sorta complicated, but hopefully it will work. -TYT
*/
char buf[1023], *cp, *interp, *i_name, *i_arg;
unsigned long old_fs;
strncpy(buf, bh->b_data+2, 1022);
brelse(bh);
iput(inode);
buf[1022] = '\0';
if (cp = strchr(buf, '\n')) {
*cp = '\0';
for (cp = buf; (*cp == ' ') || (*cp == '\t'); cp++);
}
if (!cp || *cp == '\0') {
retval = -ENOEXEC; /* No interpreter name found */
goto exec_error1;
}
interp = i_name = cp;
i_arg = 0;
for ( ; *cp && (*cp != ' ') && (*cp != '\t'); cp++) {
if (*cp == '/')
i_name = cp+1;
}
if (*cp) {
*cp++ = '\0';
i_arg = cp;
}
/*
* OK, we've parsed out the interpreter name and
* (optional) argument.
*/
if (sh_bang++ == 0) {
p = copy_strings(envc, envp, page, p, 0);
p = copy_strings(--argc, argv+1, page, p, 0);
}
/*
* Splice in (1) the interpreter's name for argv[0]
* (2) (optional) argument to interpreter
* (3) filename of shell script
*
* This is done in reverse order, because of how the
* user environment and arguments are stored.
*/
p = copy_strings(1, &filename, page, p, 1);
argc++;
if (i_arg) {
p = copy_strings(1, &i_arg, page, p, 2);
argc++;
}
p = copy_strings(1, &i_name, page, p, 2);
argc++;
if (!p) {
retval = -ENOMEM;
goto exec_error1;
}
/*
* OK, now restart the process with the interpreter's inode.
*/
old_fs = get_fs();
set_fs(get_ds());
if (!(inode=namei(interp))) { /* get executables inode */
set_fs(old_fs);
retval = -ENOENT;
goto exec_error1;
}
set_fs(old_fs);
goto restart_interp;
}
brelse(bh);
if (N_MAGIC(ex) != ZMAGIC || ex.a_trsize || ex.a_drsize ||
ex.a_text+ex.a_data+ex.a_bss>0x3000000 ||
inode->i_size < ex.a_text+ex.a_data+ex.a_syms+N_TXTOFF(ex)) {
retval = -ENOEXEC;
goto exec_error2;
}
if (N_TXTOFF(ex) != BLOCK_SIZE) {
printk("%s: N_TXTOFF != BLOCK_SIZE. See a.out.h.", filename);
retval = -ENOEXEC;
goto exec_error2;
}
if (!sh_bang) {
p = copy_strings(envc,envp,page,p,0);
p = copy_strings(argc,argv,page,p,0);
if (!p) {
retval = -ENOMEM;
goto exec_error2;
}
}
/* OK, This is the point of no return */
if (current->executable)
iput(current->executable);
current->executable = inode;
for (i=0 ; i<32 ; i++)
current->sigaction[i].sa_handler = NULL;
for (i=0 ; i<NR_OPEN ; i++)
if ((current->close_on_exec>>i)&1)
sys_close(i);
current->close_on_exec = 0;
free_page_tables(get_base(current->ldt[1]),get_limit(0x0f));
free_page_tables(get_base(current->ldt[2]),get_limit(0x17));
if (last_task_used_math == current)
last_task_used_math = NULL;
current->used_math = 0;
p += change_ldt(ex.a_text,page)-MAX_ARG_PAGES*PAGE_SIZE;
p = (unsigned long) create_tables((char *)p,argc,envc);
current->brk = ex.a_bss +
(current->end_data = ex.a_data +
(current->end_code = ex.a_text));
current->start_stack = p & 0xfffff000;
current->euid = e_uid;
current->egid = e_gid;
i = ex.a_text+ex.a_data;
while (i&0xfff)
put_fs_byte(0,(char *) (i++));
eip[0] = ex.a_entry; /* eip, magic happens :-) */
eip[3] = p; /* stack pointer */
return 0;
exec_error2:
iput(inode);
exec_error1:
for (i=0 ; i<MAX_ARG_PAGES ; i++)
free_page(page[i]);
return(retval);
}
| 2.359375 | 2 |
2024-11-18T18:56:30.628145+00:00 | 2021-02-11T16:29:38 | f35e15ec0cc33fc60189417fb71ddadf011f5ed7 | {
"blob_id": "f35e15ec0cc33fc60189417fb71ddadf011f5ed7",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-11T16:29:38",
"content_id": "8f1f7f4ab116253f5187c70302185c43f19323d7",
"detected_licenses": [
"MIT"
],
"directory_id": "754012bf855a43cbc46889479dd61e311faf86a8",
"extension": "c",
"filename": "binary.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 338084077,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 418,
"license": "MIT",
"license_type": "permissive",
"path": "/datastruct/ch4_tree/binary.c",
"provenance": "stackv2-0004.json.gz:20137",
"repo_name": "shankusu2017/data_structures_algorithm",
"revision_date": "2021-02-11T16:29:38",
"revision_id": "70381e2df0ab4ce585ce472537180610244d3bb5",
"snapshot_id": "8de858c75e5679067304c6388dafad876b225003",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/shankusu2017/data_structures_algorithm/70381e2df0ab4ce585ce472537180610244d3bb5/datastruct/ch4_tree/binary.c",
"visit_date": "2023-03-02T08:14:04.465661"
} | stackv2 | typedef struct TreeNode *PtrNode;
typedef struct PtrNode Tree;
typedef int ElementType;
struct TreeNode
{
ElementType element;
Tree left;
Tree right;
};
//2叉数搜索算法
static PtrNode find(Tree tree, int x)
{
if (!tree)
return NULL;
if (x < tree->element)
find(tree->left, x);
else if (x > tree->element)
find(tree->right, x);
else
return tree;
}
| 2.75 | 3 |
2024-11-18T18:56:30.707042+00:00 | 2016-05-24T20:16:19 | 35b72b9d75a726c921aabadd2fc556177c7f4a9d | {
"blob_id": "35b72b9d75a726c921aabadd2fc556177c7f4a9d",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-24T20:16:19",
"content_id": "672445e29f45b6461732902f72611fc421a9ce65",
"detected_licenses": [
"MIT"
],
"directory_id": "3deec92ca33109f6556488c0d32c1b6178066b7e",
"extension": "c",
"filename": "avbin_open_filename.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 25474303,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 952,
"license": "MIT",
"license_type": "permissive",
"path": "/Stage/Externals/matlab-avbin/avbin_open_filename.c",
"provenance": "stackv2-0004.json.gz:20265",
"repo_name": "SchwartzNU/DataAcquisition",
"revision_date": "2016-05-24T20:16:19",
"revision_id": "47d728c34bd9db1787bbb3f7805aff60484104d0",
"snapshot_id": "2fa1749de3550c4145f03959b638d2d2d711ce5a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SchwartzNU/DataAcquisition/47d728c34bd9db1787bbb3f7805aff60484104d0/Stage/Externals/matlab-avbin/avbin_open_filename.c",
"visit_date": "2021-01-10T15:37:21.746443"
} | stackv2 | #include <mex.h>
#include "avbin.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
size_t filenameLen;
char *filename;
AVbinFile *file;
mxArray *fileAddr;
if (nrhs != 1)
{
mexErrMsgIdAndTxt("avbin:usage", "Usage: file = avbin_open_filename(filename)");
return;
}
filenameLen = mxGetN(prhs[0]) * sizeof(mxChar) + 1;
filename = mxMalloc(filenameLen);
mxGetString(prhs[0], filename, (mwSize)filenameLen);
file = avbin_open_filename(filename);
if (file == NULL)
{
mexErrMsgIdAndTxt("avbin:failed", "The file could not be opened, or is not of a recognized file format");
return;
}
fileAddr = mxCreateNumericMatrix(1, 1, mxUINT64_CLASS, mxREAL);
*((uint64_t *)mxGetData(fileAddr)) = (uint64_t)file;
plhs[0] = fileAddr;
mxFree(filename);
} | 2.078125 | 2 |
2024-11-18T18:56:31.227799+00:00 | 2021-10-24T23:47:49 | 428fc77724309610efd29c4acfa2f5db5c1c88cb | {
"blob_id": "428fc77724309610efd29c4acfa2f5db5c1c88cb",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-24T23:47:49",
"content_id": "c9e50c056adb0cb5168ea96a7b98aed16604af86",
"detected_licenses": [
"MIT"
],
"directory_id": "d9143039fbfc35f37c70e956c31fa51a900ef46a",
"extension": "c",
"filename": "job.c",
"fork_events_count": 9,
"gha_created_at": "2014-02-03T19:47:03",
"gha_event_created_at": "2021-04-09T21:05:16",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 16490830,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4685,
"license": "MIT",
"license_type": "permissive",
"path": "/src/tegradrm/uapi_v2/job.c",
"provenance": "stackv2-0004.json.gz:20649",
"repo_name": "grate-driver/xf86-video-opentegra",
"revision_date": "2021-10-24T23:47:49",
"revision_id": "9be4b4aa7c81b9b43496e8621954a0f4b343f3b1",
"snapshot_id": "06da2c162b1b315827ebf637c8065350d9be943e",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/grate-driver/xf86-video-opentegra/9be4b4aa7c81b9b43496e8621954a0f4b343f3b1/src/tegradrm/uapi_v2/job.c",
"visit_date": "2021-12-27T18:48:07.079518"
} | stackv2 |
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <xf86drm.h>
#include "private.h"
int drm_tegra_job_new_v2(struct drm_tegra_job_v2 **jobp,
struct drm_tegra *drm,
unsigned int num_bos_expected,
unsigned int num_words_expected)
{
struct drm_tegra_job_v2 *job;
void *bo_table;
void *start;
int err;
if (!jobp || !drm)
return -EINVAL;
job = calloc(1, sizeof(*job));
if (!job)
return -ENOMEM;
if (num_words_expected < 64)
num_words_expected = 64;
err = posix_memalign(&start, 64,
sizeof(*job->start) * num_words_expected);
if (err)
goto err_free_job;
if (num_bos_expected < 8)
num_bos_expected = 8;
if (num_bos_expected > DRM_TEGRA_BO_TABLE_MAX_ENTRIES_NUM)
goto err_free_words;
err = posix_memalign(&bo_table, 64,
sizeof(*job->bo_table) * num_bos_expected);
if (err)
goto err_free_words;
job->num_bos_max = num_bos_expected;
job->num_words = num_words_expected;
job->bo_table = bo_table;
job->start = start;
job->ptr = start;
job->drm = drm;
*jobp = job;
return 0;
err_free_words:
free(start);
err_free_job:
free(job);
return err;
}
int drm_tegra_job_resize_v2(struct drm_tegra_job_v2 *job,
unsigned int num_words,
unsigned int num_bos,
bool reallocate)
{
unsigned int offset;
void *new_bo_table;
void *new_start;
size_t size;
int err;
if (!job)
return -EINVAL;
if (num_words != job->num_words) {
offset = (unsigned int)(job->ptr - job->start);
err = posix_memalign(&new_start, 64,
sizeof(*job->start) * num_words);
if (err)
return err;
if (reallocate) {
if (num_words < job->num_words)
size = sizeof(*job->start) * num_words;
else
size = sizeof(*job->start) * job->num_words;
memcpy(new_start, job->start, size);
}
free(job->start);
job->num_words = num_words;
job->start = new_start;
job->ptr = new_start;
job->ptr += offset;
}
if (num_bos != job->num_bos_max) {
if (num_bos > DRM_TEGRA_BO_TABLE_MAX_ENTRIES_NUM)
return -EINVAL;
err = posix_memalign(&new_bo_table, 64,
sizeof(*job->bo_table) * num_bos);
if (err)
return err;
if (reallocate) {
if (num_bos < job->num_bos_max)
size = sizeof(*job->bo_table) * num_bos;
else
size = sizeof(*job->bo_table) * job->num_bos_max;
memcpy(new_bo_table, job->bo_table, size);
}
free(job->bo_table);
job->bo_table = new_bo_table;
job->num_bos_max = num_bos;
}
return 0;
}
int drm_tegra_job_reset_v2(struct drm_tegra_job_v2 *job)
{
if (!job)
return -EINVAL;
job->num_bos = 0;
job->ptr = job->start;
return 0;
}
int drm_tegra_job_free_v2(struct drm_tegra_job_v2 *job)
{
if (!job)
return -EINVAL;
free(job->bo_table);
free(job->start);
free(job);
return 0;
}
int drm_tegra_job_push_reloc_v2(struct drm_tegra_job_v2 *job,
struct drm_tegra_bo *target,
unsigned long offset,
uint32_t drm_bo_table_flags)
{
struct drm_tegra_cmdstream_reloc reloc;
unsigned int i;
int err;
if (!job)
return -EINVAL;
for (i = 0; i < job->num_bos; i++) {
if (job->bo_table[i].handle == target->handle) {
if (drm_bo_table_flags & DRM_TEGRA_BO_TABLE_WRITE)
job->bo_table[i].flags |= DRM_TEGRA_BO_TABLE_WRITE;
if (!(drm_bo_table_flags & DRM_TEGRA_BO_TABLE_EXPLICIT_FENCE))
job->bo_table[i].flags &= ~DRM_TEGRA_BO_TABLE_EXPLICIT_FENCE;
break;
}
}
if (i == job->num_bos) {
if (job->num_bos == job->num_bos_max) {
err = drm_tegra_job_resize_v2(
job, job->num_words, job->num_bos_max + 8, true);
if (err)
return err;
}
job->bo_table[i].handle = target->handle;
job->bo_table[i].flags = drm_bo_table_flags;
job->num_bos++;
}
reloc.bo_index = i;
reloc.bo_offset = target->offset + offset;
offset = (unsigned long)(job->ptr - job->start);
if (offset == job->num_words) {
err = drm_tegra_job_resize_v2(
job, job->num_words + 256, job->num_bos_max, true);
if (err)
return err;
}
*job->ptr++ = reloc.u_data;
return 0;
}
int drm_tegra_job_submit_v2(struct drm_tegra_job_v2 *job,
uint32_t syncobj_handle_in,
uint32_t syncobj_handle_out,
uint64_t pipes_mask)
{
struct drm_tegra_submit_v2 args;
if (!job)
return -EINVAL;
args.in_fence = syncobj_handle_in;
args.out_fence = syncobj_handle_out;
args.cmdstream_ptr = (uintptr_t)job->start;
args.bo_table_ptr = (uintptr_t)job->bo_table;
args.num_cmdstream_words = (uint32_t)(job->ptr - job->start);
args.num_bos = job->num_bos;
args.pipes = pipes_mask;
args.uapi_ver = 0;
args.flags = 0;
return drmCommandWriteRead(job->drm->fd, DRM_TEGRA_SUBMIT_V2,
&args, sizeof(args));
}
| 2.484375 | 2 |
2024-11-18T18:56:34.685829+00:00 | 2020-04-24T23:20:40 | 556477462478a1685521a984fbbcdc1b53e722b6 | {
"blob_id": "556477462478a1685521a984fbbcdc1b53e722b6",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-24T23:20:40",
"content_id": "e82fb0ac0e304306803d8f0231254a31c2cb82bb",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "48c2d779adc3ec016b996d1bb03c5f9b2605bb3f",
"extension": "c",
"filename": "cham.c",
"fork_events_count": 0,
"gha_created_at": "2020-04-29T11:44:55",
"gha_event_created_at": "2020-04-29T11:44:56",
"gha_language": null,
"gha_license_id": null,
"github_id": 259910011,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2483,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/cryptarm/cham/cham.c",
"provenance": "stackv2-0004.json.gz:20905",
"repo_name": "wqweto/tinycrypt",
"revision_date": "2020-04-24T23:20:40",
"revision_id": "b6100cf07b7355643085dda326c13dcfcc804077",
"snapshot_id": "6aa72dab0fc553de87f7d925dd075fbc4347211b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/wqweto/tinycrypt/b6100cf07b7355643085dda326c13dcfcc804077/cryptarm/cham/cham.c",
"visit_date": "2022-04-24T00:13:25.536111"
} | stackv2 | /**
Copyright (C) 2018 Odzhan. All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY AUTHORS "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 "cham.h"
void cham(void *key, void *data)
{
int i;
uint32_t x0, x1, x2, x3, k0, k1, k2, t0;
uint32_t rk[2*KW];
uint32_t *x, *k;
k = (uint32_t*)key;
x = (uint32_t*)data;
// derive round keys from 128-bit key
for (i=0; i<KW; i++) {
k0 = k[i];
k1 = ROTR32(k0, 31);
k2 = ROTR32(k0, 24);
k0 ^= k1;
rk[i] = k0 ^ k2;
k2 = ROTR32(k2, 29);
k0 ^= k2;
rk[(i+KW)^1] = k0;
}
// load 128-bit plain text
x0 = x[0]; x1 = x[1];
x2 = x[2]; x3 = x[3];
// perform encryption
for (i=0; i<R; i++)
{
k0 = x3; // backup x3
x0^= i; // xor by round number
// execution depends on (i % 2)
x3 = rk[i & 7];
x3^= (i & 1) ? ROTR32(x1, 24) : ROTR32(x1, 31);
x3+= x0;
x3 = (i & 1) ? ROTR32(x3, 31) : ROTR32(x3, 24);
// swap
x0 = x1; x1 = x2; x2 = k0;
}
x[0] = x0; x[1] = x1;
x[2] = x2; x[3] = x3;
}
| 2.203125 | 2 |
2024-11-18T18:56:34.760291+00:00 | 2017-01-11T12:08:13 | 7648dbf60560d028060aa3ec40dce625d5ddda76 | {
"blob_id": "7648dbf60560d028060aa3ec40dce625d5ddda76",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-11T12:08:13",
"content_id": "a7cb25900a0b61a8957857e44c8a57975d060706",
"detected_licenses": [
"MIT"
],
"directory_id": "91a558a151f75599d25bde706e84a316e116254d",
"extension": "c",
"filename": "ws_utils.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 77800010,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7258,
"license": "MIT",
"license_type": "permissive",
"path": "/ws_utils.c",
"provenance": "stackv2-0004.json.gz:21033",
"repo_name": "overflowerror/Serwer",
"revision_date": "2017-01-11T12:08:13",
"revision_id": "17b03c4c005075eb23a44776950bc401b97a818f",
"snapshot_id": "06d48e5423edbcabc0a75faa4ad4f73d123186ee",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/overflowerror/Serwer/17b03c4c005075eb23a44776950bc401b97a818f/ws_utils.c",
"visit_date": "2021-01-12T04:48:25.305670"
} | stackv2 | #include "serwer.h"
#include "ws_error.h"
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
method_t ws_method(const char* string) {
if (strcmp(string, "OPTIONS") == 0)
return OPTIONS;
else if (strcmp(string, "GET") == 0)
return GET;
else if (strcmp(string, "HEAD") == 0)
return HEAD;
else if (strcmp(string, "POST") == 0)
return POST;
else if (strcmp(string, "PUT") == 0)
return PUT;
else if (strcmp(string, "DELETE") == 0)
return DELETE;
else if (strcmp(string, "TRACE") == 0)
return TRACE;
else if (strcmp(string, "CONNECT") == 0)
return CONNECT;
else
return -1; // unknown method
}
const char* ws_method_string(method_t method) {
switch(method) {
case OPTIONS:
return "OPTIONS";
case GET:
return "GET";
case HEAD:
return "HEAD";
case POST:
return "POST";
case PUT:
return "PUT";
case DELETE:
return "DELETE";
case TRACE:
return "TRACE";
case CONNECT:
return "CONNECT";
default:
return "unknown method";
}
}
const char* ws_code_reason(int code) {
switch(code) {
case 100:
return "Continue";
case 101:
return "Switching Protocols";
case 200:
return "OK";
case 201:
return "Created";
case 202:
return "Accepted";
case 203:
return "Non-Authoritative Information";
case 204:
return "No Content";
case 205:
return "Reset Content";
case 206:
return "Partial Content";
case 300:
return "Multible Choices";
case 301:
return "Moved Permanently";
case 302:
return "Found";
case 303:
return "See Other";
case 304:
return "Not Modified";
case 305:
return "Use Proxy";
case 307:
return "Temporary Redirect";
case 400:
return "Bad Request";
case 401:
return "Unauthorized";
case 402:
return "Payment Required";
case 403:
return "Forbidden";
case 404:
return "Not Found";
case 405:
return "Method Not Allowed";
case 406:
return "Not Acceptable";
case 407:
return "Proxy Authentication Required";
case 408:
return "Request Time-out";
case 409:
return "Conflict";
case 410:
return "Gone";
case 411:
return "Length Required";
case 412:
return "Precondition Failed";
case 413:
return "Request Entify Too Large";
case 414:
return "Request-URI Too Large";
case 415:
return "Unsupported Media Type";
case 416:
return "Requested range not satisfiable";
case 417:
return "Expectation Failed";
case 500:
return "Internal Server Error";
case 501:
return "Not Implemented";
case 502:
return "Bad Gateway";
case 503:
return "Service Unavailable";
case 504:
return "Gateway Time-out";
case 505:
return "HTTP Version not supported";
default:
return "Unknown extension code";
}
}
bool ws_host_match(const char* host, const char* match) {
// only two possible positions for wildcard: begin and end
int lenh = strlen(host);
int lenm = strlen(match);
if (lenm > lenh)
return false;
bool wildcard = false;
int wnext = -1;
int found = -1;
int h = 0, m = 0;
for (; m < lenm && h < lenh; m++, h++) {
if (match[m] == '*') {
wildcard = true;
wnext = m + 1;
found = -1;
// current host char matches automatically
continue;
}
if (wildcard) {
if (found == -1) {
if (match[m] != host[h])
m--;
else
found = h;
} else {
if (match[m] != host[h]) {
// found was negated; reset cursor positions
m = wnext;
h = found + 1;
found = -1;
}
}
} else {
if (match[m] != host[h])
return false;
}
}
// TODO server:80 and server:80* do not match.
// if not whole match string matches, return false
if (m != lenm)
return false;
return true;
}
bool ws_path_match(const char* path, const char* match) {
int lenp = strlen(path);
int lenm = strlen(match);
if (lenm > lenp)
return false;
bool wildcard = false;
int wnext = -1;
int found = -1;
int p = 0, m = 0;
for (; m < lenm && p < lenp; m++, p++) {
if (match[m] == '*') {
wildcard = true;
wnext = m + 1;
found = -1;
// current host char matches automatically
continue;
}
if (wildcard) {
if (found < 0) {
if (match[m] != path[p])
m--;
else
found = p;
} else {
if (match[m] != path[p]) {
// found was negated; reset cursor positions
m = wnext;
p = found + 1;
found = -1;
}
}
// if directory end
if (path[p] == '/') {
// found is here only true if match[m] = path[p] = '/'
if (found >= 0) {
wildcard = false;
} else {
return false;
}
}
} else {
if (match[m] != path[p])
return false;
}
}
// TODO /hello and /hello* do not match.
// if not whole match string used, return false
if (m != lenm)
return false;
return true;
}
int ws_request_parse(char* buffer, const char** path, method_t* method) {
char lbuffer[9];
int position = 0;
int state = 0;
size_t len = strlen(buffer);
for(size_t i = 0; i < len; i++) {
switch(state) {
case 0: // method
if (buffer[i] != ' ') {
lbuffer[position++] = buffer[i];
if (position > 7)
return -1; // method name too long
} else {
state++;
lbuffer[position] = '\0';
*method = ws_method(lbuffer);
if (*method < 0)
return -2; // unknown method
}
break;
case 1: // path begin
if (buffer[i] == ' ' || buffer[i] == '\r')
return -3; // malformed;
*path = buffer + i;
state++;
break;
case 2: // path
if (buffer[i] == ' ') {
buffer[i] = '\0';
position = 0;
state++;
}
break;
case 3: // version
if (buffer[i] != '\r') {
lbuffer[position++] = buffer[i];
if (position > 8)
return -4; // version too long
} else {
lbuffer[position] = '\0';
// we just support HTTP 1.0 and 1.1
if (!strcmp(lbuffer, "HTTP/1.0"))
return 0;
if (!strcmp(lbuffer, "HTTP/1.1"))
return 0;
return -5;
}
break;
default:
assert(false);
}
}
return 0;
}
char* ws_host_find(const char** path, headers_t headers) {
char* host = NULL;
for (int i = 0; i < headers.nrfields; i++) {
header_t header = headers.fields[i];
if (strcmp(header.key, "Host") == 0) {
host = malloc(strlen(header.value) + 1);
if (host == NULL) {
ws_error.type = ERRNO;
ws_error.no = errno;
return NULL;
}
memcpy(host, header.value, strlen(header.value) + 1);
return host;
}
}
if (strlen(*path) <= strlen("http://"))
return host;
if ((*path)[0] == '/')
return host;
bool setHost = false;
if (host == NULL) {
setHost = true;
host = malloc(strlen(*path) + 1);
if (host == NULL) {
ws_error.type = ERRNO;
ws_error.no = errno;
return NULL;
}
}
int hposition = 0;
int nrslash = 0;
size_t len = strlen(*path);
for (size_t i = 0; i < len; i++) {
if (nrslash < 2) {
// http://
} else if (nrslash < 3) {
if (setHost) {
host[hposition++] = (*path)[i];
/*if ((*path)[i] == ':') {
host[hposition - 1] = '\0';
setHost = false;
}*/
}
} else {
// rebase path
*path = *path + i;
break;
}
if ((*path)[i] == '/')
nrslash++;
}
if (setHost) {
host[hposition] = '\0';
host = realloc(host, strlen(host) + 1);
if (host == NULL) {
ws_error.type = ERRNO;
ws_error.no = errno;
return NULL;
}
}
return host;
}
| 2.015625 | 2 |
2024-11-18T18:56:35.005416+00:00 | 2020-02-11T23:20:52 | 6c0e2d67f235299983089c1b0f967bcaa2870d13 | {
"blob_id": "6c0e2d67f235299983089c1b0f967bcaa2870d13",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-11T23:20:52",
"content_id": "bce6b502b902b2aa7e7971a4234dd3e906e38791",
"detected_licenses": [
"MIT"
],
"directory_id": "59a5ca26151808d863979d806379fba99cde9c3b",
"extension": "c",
"filename": "DEBUG.C",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 11710742,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2464,
"license": "MIT",
"license_type": "permissive",
"path": "/FRMWRKS/C/C/DEBUG.C",
"provenance": "stackv2-0004.json.gz:21289",
"repo_name": "chrisoldwood/WIN16",
"revision_date": "2020-02-11T23:20:52",
"revision_id": "c30f5e3b872ee2dc06e3f5fdafd96236b47d2fd2",
"snapshot_id": "9f0456c2abf573e486cedae4171702cefd3ee1ec",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/chrisoldwood/WIN16/c30f5e3b872ee2dc06e3f5fdafd96236b47d2fd2/FRMWRKS/C/C/DEBUG.C",
"visit_date": "2021-01-23T03:53:15.891401"
} | stackv2 | /*****************************************************************************
** (C) Chris Wood 1995.
**
** DEBUG.C - Debugging utilities.
**
******************************************************************************
*/
#include <windows.h>
#include "apptypes.h"
/* Check build type. */
#ifdef DEBUG
/**** Defines & Global variables. *******************************************/
/* Configure the display of assert messages.*/
#define ASSERT_AS_DBMSG /* Output as a debug message.*/
#undef ASSERT_AS_MSGBOX /* Output to a message box. */
extern BYTE szAppName[]; /* The application name. */
extern HWND hAppWnd; /* The main window. */
/******************************************************************************
** My simple assert function. This will cause a debug break if the value is
** not okay and display a simple message.
*/
VOID FAR MyAssert(LPSTR lpszModule, WORD wLineNum, BOOL bExpr)
{
BYTE szMsg[128]; /* The full message. */
/* Check the exporession. */
if(!bExpr)
{
/* Copy the module and line number into the message. */
wsprintf((LPSTR) szMsg, (LPSTR) "ASSERT Failed: Module %s Line %d\n",
lpszModule, wLineNum);
/* Display message. */
#ifdef ASSERT_AS_DBMSG
OutputDebugString((LPSTR) szMsg);
#else /* ASSERT_AS_MSGBOX. */
MessageBox(hAppWnd, (LPSTR) szMsg, (LPSTR) szAppName, MB_OK | MB_ICONEXCLAMATION);
#endif
/* Force a break. */
DebugBreak();
}
}
/******************************************************************************
** My extended assert function. This will also cause a debug break if the value
** is not okay but allow a more flexible message.
*/
VOID FAR MyAssertEx(LPSTR lpszModule, WORD wLineNum, BOOL bExpr, LPSTR lpszType)
{
BYTE szMsg[128]; /* The full message. */
/* Check the exporession. */
if(!bExpr)
{
/* Copy the type, module and line number into the message. */
wsprintf((LPSTR) szMsg, (LPSTR) "%s Failed: Module %s Line %d\n",
lpszType, lpszModule, wLineNum);
/* Display message. */
#ifdef ASSERT_AS_DBMSG
OutputDebugString((LPSTR) szMsg);
#else /* ASSERT_AS_MSGBOX. */
MessageBox(hAppWnd, (LPSTR) szMsg, (LPSTR) szAppName, MB_OK | MB_ICONEXCLAMATION);
#endif
/* Force a break. */
DebugBreak();
}
}
#endif /* DEBUG. */
| 2.46875 | 2 |
2024-11-18T18:56:35.132666+00:00 | 2022-11-25T14:31:40 | a0c90b36448e8aa8a008301057277ecd2402c487 | {
"blob_id": "a0c90b36448e8aa8a008301057277ecd2402c487",
"branch_name": "refs/heads/main",
"committer_date": "2022-11-25T14:31:40",
"content_id": "8dda9fa9e8525f8c08cb97613c88233a2a7d5cc6",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c6bbd226758134f7057e381234b14ab0e5f19410",
"extension": "c",
"filename": "poly.c",
"fork_events_count": 0,
"gha_created_at": "2020-06-16T04:28:36",
"gha_event_created_at": "2022-11-25T14:31:42",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 272609398,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2655,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/pj/poly.c",
"provenance": "stackv2-0004.json.gz:21417",
"repo_name": "kattkieru/Animator-Pro",
"revision_date": "2022-11-25T14:31:40",
"revision_id": "5a7a58a3386a6430a59b64432d31dc556c56315b",
"snapshot_id": "441328d06cae6b7175b0260f4ea1c425b36625e9",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/kattkieru/Animator-Pro/5a7a58a3386a6430a59b64432d31dc556c56315b/src/pj/poly.c",
"visit_date": "2023-08-05T04:34:00.462730"
} | stackv2 |
#include <limits.h>
#include "errcodes.h"
#include "imath.h"
#include "memory.h"
#include "poly.h"
#include "rectang.h"
void reverse_poly(Poly *p)
{
LLpoint *olist, *newlist, *next;
int pcount;
pcount = p->pt_count;
olist = p->clipped_list; /* 1st point will stay the same... */
newlist = NULL;
while (--pcount >= 0)
{
next = olist->next;
olist->next = newlist;
newlist = olist;
olist = next;
}
p->clipped_list->next = newlist; /* put in the ring link */
}
Errcode poly_to_vertices(Poly *poly, Boolean closed,
Short_xyz **pvertices)
/* Convert a Polygon in circular linked list form to one that's an
* array of x/y/z values. If poly is closed, duplicate the first point
* as the last point */
{
Short_xyz *v;
LLpoint *pts = poly->clipped_list;
int pcount = poly->pt_count+closed;
if ((*pvertices = v = pj_malloc(pcount*sizeof(*v))) == NULL)
return(Err_no_memory);
while (--pcount >= 0)
{
v->x = pts->x;
v->y = pts->y;
v->z = pts->z;
pts = pts->next;
v += 1;
}
return(Success);
}
void poly_ave_3d(Poly *p, Short_xyz *v)
{
long lx,ly,lz;
int count = p->pt_count;
int i = count;
LLpoint *s = p->clipped_list;
lx = ly = lz = 0;
while (--i >= 0)
{
lx += s->x;
ly += s->y;
lz += s->z;
s = s->next;
}
v->x = lx/count;
v->y = ly/count;
v->z = lz/count;
}
int calc_zpoly(Short_xyz *s, Short_xy *d,
int count, int xcen, int ycen, int ground_z)
/* Transform 3-d pointlist into 2-d pointlist doing perspective
calculations the cheap way */
{
int x, y, z;
#define TOOBIG 10000
while (--count >= 0)
{
z = s->z + ground_z;
if (z < 1)
return(Err_overflow);
x = d->x = sscale_by(s->x-xcen, ground_z, z) + xcen;
y = d->y = sscale_by(s->y-ycen, ground_z, z) + ycen;
if (x < -TOOBIG || x > TOOBIG || y < -TOOBIG || y > TOOBIG)
return(Err_overflow);
d += 1;
s += 1;
}
return(0);
#undef TOOBIG
}
void poly_to_3d(Poly *sp, Short_xyz *d)
/* convert a poly with linked list to an array of points */
{
int count = sp->pt_count;
LLpoint *pt = sp->clipped_list;
while (--count>=0)
{
*d++ = *((Short_xyz *)&pt->x);
pt = pt->next;
}
}
void poly_bounds(Poly *p, Cliprect *cr)
{
int count = p->pt_count;
LLpoint *pt = p->clipped_list;
cr->MaxY = cr->MaxX = SHRT_MIN;
cr->x = cr->y = SHRT_MAX;
while (--count>=0)
{
if(pt->x < cr->x)
cr->x = pt->x;
if(pt->x > cr->MaxX)
cr->MaxX = pt->x;
if(pt->y < cr->y)
cr->y = pt->y;
if(pt->y > cr->MaxY)
cr->MaxY = pt->y;
pt = pt->next;
}
/* cause cliprects are 1 beyond */
++cr->MaxX;
++cr->MaxY;
}
| 2.5625 | 3 |
2024-11-18T18:56:35.336620+00:00 | 2017-06-21T02:58:20 | c92046b46448718d1e24f78366ec2545cb4a9dfe | {
"blob_id": "c92046b46448718d1e24f78366ec2545cb4a9dfe",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-21T02:58:20",
"content_id": "f8dcc3e1cb1c39b180ec78e69f7c50cec88fa4bd",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "a14e7948e4138e46693ddb77c8f27ea5abb821fb",
"extension": "c",
"filename": "sp_extbug_signal.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 42516252,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2358,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/extbug/sp_extbug_signal.c",
"provenance": "stackv2-0004.json.gz:21546",
"repo_name": "museless/Muse-Spider",
"revision_date": "2017-06-21T02:58:20",
"revision_id": "b20cdffbc4e6513069e24478a6be308a3dffa338",
"snapshot_id": "7ef03ccfa85fe667138f83f6463064589ca2bf2e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/museless/Muse-Spider/b20cdffbc4e6513069e24478a6be308a3dffa338/src/extbug/sp_extbug_signal.c",
"visit_date": "2021-01-22T23:43:45.107786"
} | stackv2 | /*------------------------------------------
Source file content Five part
Part Zero: Include
Part One: Local data
Part Two: Local function
Part Three: Define
Part Four: Signal handle
--------------------------------------------*/
/*------------------------------------------
Part Zero: Include
--------------------------------------------*/
#include "spinc.h"
#include "spmpool.h"
#include "spnet.h"
#include "spdb.h"
#include "mpctl.h"
#include "spextb.h"
#include "speglobal.h"
/*------------------------------------------
Part One: Local data
--------------------------------------------*/
static pmut_t sigIntLock = PTHREAD_MUTEX_INITIALIZER;
static pmut_t sigSegLock = PTHREAD_MUTEX_INITIALIZER;
/*------------------------------------------
Part Two: Local function
--------------------------------------------*/
/* Part Four */
static void exbug_signal_handler(int nSignal);
/*------------------------------------------
Part Four: Signal handle
1. exbug_signal_init
2. exbug_signal_handler
--------------------------------------------*/
/*-----exbug_signal_init-----*/
int exbug_signal_init(void)
{
struct sigaction sigStru;
sigset_t sigMask;
/* for signal int */
sigemptyset(&sigMask);
sigaddset(&sigMask, SIGINT);
sigStru.sa_handler = exbug_signal_handler;
sigStru.sa_mask = sigMask;
sigStru.sa_flags = 0;
if(sigaction(SIGINT, &sigStru, NULL) == FUN_RUN_FAIL) {
perror("Extbug---> exbug_signal_init - sigaction - SIGINT");
return FUN_RUN_END;
}
/* for signal segv */
sigdelset(&sigMask, SIGINT);
sigStru.sa_mask = sigMask;
if(sigaction(SIGSEGV, &sigStru, NULL) == FUN_RUN_FAIL) {
perror("otbug_init_signal - sigaction - SIGSEGV");
return FUN_RUN_END;
}
return FUN_RUN_OK;
}
/*-----exbug_signal_handler-----*/
static void exbug_signal_handler(int nSignal)
{
int nTimes = 0;
if(nSignal == SIGINT) {
pthread_mutex_lock(&sigIntLock);
printf("Extbug---> inside SIGINT...\n");
while(nTimes++ < nExbugPthead && !mato_sub_and_test(&pthreadCtlLock, 0))
sleep(TAKE_A_SEC);
exbug_paper_sync();
exbug_data_sync();
mgc_all_clean(exbGarCol);
mgc_one_clean(&extResCol);
printf("Extbug---> quitting...\n");
exit(FUN_RUN_FAIL);
}
if(nSignal == SIGSEGV) {
pthread_mutex_lock(&sigSegLock);
printf("Extbug---> caught SIGSEGV\n");
exbug_sig_error(PTHREAD_ERROR);
}
}
| 2.28125 | 2 |
2024-11-18T18:56:35.534891+00:00 | 2020-07-24T20:58:46 | b599775e4b120ae07e7d16483ab5727ff36edbe7 | {
"blob_id": "b599775e4b120ae07e7d16483ab5727ff36edbe7",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-24T20:58:46",
"content_id": "36e9b2cda1deb48b13f68e85c4a485d5bee2004a",
"detected_licenses": [
"BSD-3-Clause",
"OpenSSL",
"BSD-2-Clause"
],
"directory_id": "428c9a5dbc28098c2c71b6a7020d8c98ff27b537",
"extension": "c",
"filename": "dyn_buffer_test.c",
"fork_events_count": 0,
"gha_created_at": "2020-05-14T15:04:34",
"gha_event_created_at": "2020-05-14T15:04:34",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 263946890,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1497,
"license": "BSD-3-Clause,OpenSSL,BSD-2-Clause",
"license_type": "permissive",
"path": "/test/dyn_buffer_test.c",
"provenance": "stackv2-0004.json.gz:21802",
"repo_name": "pjulien/libmtev",
"revision_date": "2020-07-24T20:58:46",
"revision_id": "863b98e4d1a3f584226ff4408c77fbbaa2ea767e",
"snapshot_id": "cf4f0f934ba80fa382f90d2310b19520008db4b2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pjulien/libmtev/863b98e4d1a3f584226ff4408c77fbbaa2ea767e/test/dyn_buffer_test.c",
"visit_date": "2022-11-20T06:28:27.835089"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <assert.h>
#include <mtev_dyn_buffer.h>
int chkmem(mtev_dyn_buffer_t *buff, size_t len, char exp) {
const char *cp;
const char *ptr = mtev_dyn_buffer_data(buff);
for(cp = ptr; cp < ptr+len; cp++) if(*cp != exp) return 0;
return 1;
}
int main(int argc, char *argv[]) {
int a = 12345;
int b = 54321;
mtev_dyn_buffer_t buff;
mtev_dyn_buffer_init(&buff);
assert(mtev_dyn_buffer_size(&buff) > 1892);
memset(mtev_dyn_buffer_write_pointer(&buff), 1, 1892);
mtev_dyn_buffer_advance(&buff, 1892);
assert(chkmem(&buff, 1892, 1));
mtev_dyn_buffer_reset(&buff);
memset(mtev_dyn_buffer_write_pointer(&buff), 2, 1892);
mtev_dyn_buffer_advance(&buff, 1892);
assert(chkmem(&buff, 1892, 2));
mtev_dyn_buffer_ensure(&buff, 100000);
assert(chkmem(&buff, 1892, 2));
assert(mtev_dyn_buffer_size(&buff) >= 100000);
mtev_dyn_buffer_reset(&buff);
memset(mtev_dyn_buffer_write_pointer(&buff), 3, 100000);
mtev_dyn_buffer_advance(&buff, 100000);
assert(chkmem(&buff, 100000, 3));
assert(a == 12345);
assert(b == 54321);
mtev_dyn_buffer_destroy(&buff);
mtev_dyn_buffer_t b2;
mtev_dyn_buffer_init(&b2);
char c = 34;
for (int i = 0; i < 8192; i++) {
/* trigger a growth from static space to heap space halfway through */
mtev_dyn_buffer_add(&b2, &c, 1);
}
assert(chkmem(&b2, 8192, 34));
assert(mtev_dyn_buffer_used(&b2) == 8192);
assert(mtev_dyn_buffer_size(&b2) >= 8192);
return 0;
}
| 2.90625 | 3 |
2024-11-18T18:56:35.802133+00:00 | 2021-06-05T11:16:40 | cf03311db2d48e48c7fe8aa97ccd0156631cf533 | {
"blob_id": "cf03311db2d48e48c7fe8aa97ccd0156631cf533",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-05T11:16:40",
"content_id": "0d788f2ee99ea7650e691b972c1e8799d7a97271",
"detected_licenses": [
"MIT"
],
"directory_id": "d7e06cd1c05160f91da9261fd9e15330f08f3d88",
"extension": "c",
"filename": "test006.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 360976861,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1092,
"license": "MIT",
"license_type": "permissive",
"path": "/C_Pentest/Learning/test006.c",
"provenance": "stackv2-0004.json.gz:22186",
"repo_name": "Felipesco/Pentest-Studies",
"revision_date": "2021-06-05T11:16:40",
"revision_id": "845b6fd1740e44bff453ab68dee7813091a37197",
"snapshot_id": "668c5e489ab9b99f82faf0fd11ee5006d4342fb0",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/Felipesco/Pentest-Studies/845b6fd1740e44bff453ab68dee7813091a37197/C_Pentest/Learning/test006.c",
"visit_date": "2023-05-15T01:28:44.230636"
} | stackv2 | // PortScan
// $ man 7 ip ===> Manual de implementação do Protocolo IP
// $ man socket ===> Manual do Socket
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
int main(int argc, char *argv[]){
int meuSocket;
int conecta;
int porta;
int inicio = 0;
int final = 65335; // Todas as portas
char *destino;
destino = argv[1];
struct sockaddr_in alvo;
for(porta=inicio; porta<final; porta++){
meuSocket = socket(AF_INET, SOCK_STREAM, 0);
alvo.sin_family = AF_INET;
alvo.sin_port = htons(porta);
alvo.sin_addr.s_addr = inet_addr(destino);
conecta = connect(meuSocket, (struct sockaddr *)&alvo, sizeof alvo);
if(conecta == 0){
printf("Porta %d - Status: ABERTA! \n", porta);
close(meuSocket);
close(conecta);
}else{
close(meuSocket);
close(conecta);
}
}
// Tinha dado um Erro... Eu tinha esquecido de importar a biblioteca #include <netdb.h>
return 0;
} | 3.109375 | 3 |
2024-11-18T18:56:35.999243+00:00 | 2020-05-03T22:30:35 | 690e357ab00e4f226e1258f1c49787e51476accb | {
"blob_id": "690e357ab00e4f226e1258f1c49787e51476accb",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-03T22:30:35",
"content_id": "52b7cea14e02c6f4fbb330c9221f9ac8e1d1d639",
"detected_licenses": [
"MIT"
],
"directory_id": "f8796ff5df371af6d2be9da667367e02b34195c5",
"extension": "h",
"filename": "arena.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 259772726,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1714,
"license": "MIT",
"license_type": "permissive",
"path": "/src/arena.h",
"provenance": "stackv2-0004.json.gz:22442",
"repo_name": "wtwhite/xmp",
"revision_date": "2020-05-03T22:30:35",
"revision_id": "e0faf9079d980c169c70b8ce2f079f32e88c8cbe",
"snapshot_id": "83edae8ca11eca80273e4ceea746a57e70cf7810",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wtwhite/xmp/e0faf9079d980c169c70b8ce2f079f32e88c8cbe/src/arena.h",
"visit_date": "2022-06-07T06:25:48.367040"
} | stackv2 | #ifndef __ARENA_H
#define __ARENA_H
// A simple arena data structure for performing LIFO memory allocations quickly.
// ArenaInit() calls ALIGNED_MALLOC(), so provided that all allocations are multiples
// of BYTESPERBLOCK, all returned memory blocks are aligned.
#include <stdlib.h> // For size_t
#include <assert.h>
#include <stdint.h> // Needed for uintptr_t
#include <string.h>
#include "switches.h" // Needed for BYTESPERBLOCK
#include "alignedalloc.h" // Needed for ALIGNED_MALLOC(), ALIGNED_FREE()
struct arena {
unsigned char *cur;
unsigned char *base;
size_t size;
};
// An external configuration process should #define INLINE to be either "inline" (if it is supported)
// or blank (in the increasingly unlikely event that it is not).
static INLINE void ArenaCreate(struct arena *a, size_t size) {
assert(size % BYTESPERBLOCK == 0);
ALIGNED_MALLOC(a->base, size);
assert((uintptr_t) a->base % BYTESPERBLOCK == 0);
a->cur = a->base;
a->size = size;
}
static INLINE void ArenaDestroy(struct arena *a) {
ALIGNED_FREE(a->base);
}
static INLINE void *ArenaAllocate(struct arena *a, size_t size) {
unsigned char *p = a->cur;
assert(size % BYTESPERBLOCK == 0);
assert(a->cur + size <= a->base + a->size);
a->cur += size;
#ifdef DEBUG
// Mimic MS's debug allocation strategy
memset(p, 0xCD, size);
#endif // DEBUG
return p;
}
static INLINE void *ArenaGetPos(struct arena *a) {
return a->cur;
}
static INLINE void ArenaSetPos(struct arena *a, void *p) {
assert((unsigned char *) p >= a->base && (unsigned char *) p <= a->base + a->size);
assert((uintptr_t) p % BYTESPERBLOCK == 0);
a->cur = p;
}
#endif // #include guard
| 2.75 | 3 |
2024-11-18T18:56:36.144655+00:00 | 2015-11-16T09:39:42 | 2f74b215fdaf274d8e898745296ff520e7c9e175 | {
"blob_id": "2f74b215fdaf274d8e898745296ff520e7c9e175",
"branch_name": "refs/heads/master",
"committer_date": "2015-11-16T09:39:42",
"content_id": "cacf0048bc8260c6516d12f31838b753403d116d",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "e3b5a899c0c6683cd5440100ed2f1aa80ca94bf9",
"extension": "c",
"filename": "freq_scheduler.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 35454177,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13458,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/lib/src/freq_scheduler.c",
"provenance": "stackv2-0004.json.gz:22570",
"repo_name": "plafl/aduana",
"revision_date": "2015-11-16T09:39:42",
"revision_id": "b14bb32f9b92393db241733f94d06a286525a3c1",
"snapshot_id": "b494adce6312f63402fa5311ffee45bff1d665a1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/plafl/aduana/b14bb32f9b92393db241733f94d06a286525a3c1/lib/src/freq_scheduler.c",
"visit_date": "2021-01-17T08:11:10.170863"
} | stackv2 | #define _POSIX_C_SOURCE 200809L
#define _BSD_SOURCE 1
#define _GNU_SOURCE 1
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#ifdef __APPLE__
#include <malloc/malloc.h>
#else
#include <malloc.h>
#endif
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include "freq_scheduler.h"
#include "txn_manager.h"
#include "util.h"
#include "scheduler.h"
static void
freq_scheduler_set_error(FreqScheduler *sch, int code, const char *message) {
error_set(sch->error, code, message);
}
static void
freq_scheduler_add_error(FreqScheduler *sch, const char *message) {
error_add(sch->error, message);
}
FreqSchedulerError
freq_scheduler_new(FreqScheduler **sch, PageDB *db, const char *path) {
FreqScheduler *p = *sch = malloc(sizeof(*p));
if (p == 0)
return freq_scheduler_error_memory;
p->error = error_new();
if (p->error == 0) {
free(p);
return freq_scheduler_error_memory;
}
p->page_db = db;
p->persist = FREQ_SCHEDULER_DEFAULT_PERSIST;
p->margin = -1.0; // disabled
p->max_n_crawls = 0;
// create directory if not present yet
char *error = 0;
p->path = path? strdup(path): concat(db->path, "freqs", '_');
if (!p->path)
error = "building scheduler path";
else
error = make_dir(p->path);
if (error != 0) {
freq_scheduler_set_error(p, freq_scheduler_error_invalid_path, __func__);
freq_scheduler_add_error(p, error);
return p->error->code;
}
if (txn_manager_new(&p->txn_manager, 0) != 0) {
freq_scheduler_set_error(p, freq_scheduler_error_internal, __func__);
freq_scheduler_add_error(p, p->txn_manager?
p->txn_manager->error->message:
"NULL");
return p->error->code;
}
int rc;
// initialize LMDB on the directory
if ((rc = mdb_env_create(&p->txn_manager->env) != 0))
error = "creating environment";
else if ((rc = mdb_env_set_mapsize(p->txn_manager->env,
FREQ_SCHEDULER_DEFAULT_SIZE)) != 0)
error = "setting map size";
else if ((rc = mdb_env_set_maxdbs(p->txn_manager->env, 1)) != 0)
error = "setting number of databases";
else if ((rc = mdb_env_open(
p->txn_manager->env,
p->path,
MDB_NOTLS | MDB_NOSYNC, 0664) != 0))
error = "opening environment";
if (error != 0) {
freq_scheduler_set_error(p, freq_scheduler_error_internal, __func__);
freq_scheduler_add_error(p, error);
freq_scheduler_add_error(p, mdb_strerror(rc));
return p->error->code;
}
return p->error->code;
}
FreqSchedulerError
freq_scheduler_cursor_open(FreqScheduler *sch, MDB_cursor **cursor) {
char *error1 = 0;
char *error2 = 0;
MDB_txn *txn = 0;
if (txn_manager_begin(sch->txn_manager, 0, &txn) != 0) {
error1 = "starting transaction";
error2 = sch->txn_manager->error->message;
goto on_error;
}
MDB_dbi dbi;
int mdb_rc =
mdb_dbi_open(txn, "schedule", MDB_CREATE, &dbi) ||
mdb_set_compare(txn, dbi, schedule_entry_mdb_cmp_asc) ||
mdb_cursor_open(txn, dbi, cursor);
if (mdb_rc != 0) {
*cursor = 0;
error1 = "opening cursor";
error2 = mdb_strerror(mdb_rc);
}
return sch->error->code;
on_error:
if (txn != 0)
txn_manager_abort(sch->txn_manager, txn);
freq_scheduler_set_error(sch, freq_scheduler_error_internal, __func__);
freq_scheduler_add_error(sch, error1);
freq_scheduler_add_error(sch, error2);
return sch->error->code;
}
FreqSchedulerError
freq_scheduler_cursor_commit(FreqScheduler *sch, MDB_cursor *cursor) {
MDB_txn *txn = mdb_cursor_txn(cursor);
if (txn_manager_commit(sch->txn_manager, txn) != 0) {
if (txn != 0)
txn_manager_abort(sch->txn_manager, txn);
freq_scheduler_set_error(sch, freq_scheduler_error_internal, __func__);
freq_scheduler_add_error(sch, "commiting schedule transaction");
freq_scheduler_add_error(sch, sch->txn_manager->error->message);
}
return sch->error->code;
}
void
freq_scheduler_cursor_abort(FreqScheduler *sch, MDB_cursor *cursor) {
if (cursor) {
txn_manager_abort(sch->txn_manager, mdb_cursor_txn(cursor));
}
}
FreqSchedulerError
freq_scheduler_cursor_write(FreqScheduler *sch,
MDB_cursor *cursor,
uint64_t hash,
float freq) {
if (freq <= 0)
return 0;
ScheduleKey sk = {
.score = 0,
.hash = hash
};
MDB_val key = {
.mv_size = sizeof(sk),
.mv_data = &sk,
};
MDB_val val = {
.mv_size = sizeof(float),
.mv_data = &freq,
};
int mdb_rc;
if ((mdb_rc = mdb_cursor_put(cursor, &key, &val, 0)) != 0) {
freq_scheduler_set_error(sch, freq_scheduler_error_internal, __func__);
freq_scheduler_add_error(sch, "adding page to schedule");
freq_scheduler_add_error(sch, mdb_strerror(mdb_rc));
}
return sch->error->code;
}
FreqSchedulerError
freq_scheduler_load_simple(FreqScheduler *sch,
float freq_default,
float freq_scale) {
char *error1 = 0;
char *error2 = 0;
MDB_cursor *cursor = 0;
HashInfoStream *st;
if (hashinfo_stream_new(&st, sch->page_db) != 0) {
error1 = "creating stream";
error2 = st? sch->page_db->error->message: "NULL";
goto on_error;
}
if (freq_scheduler_cursor_open(sch, &cursor) != 0)
goto on_error;
StreamState ss;
uint64_t hash;
PageInfo *pi;
while ((ss = hashinfo_stream_next(st, &hash, &pi)) == stream_state_next) {
if ((pi->n_crawls > 0) &&
((sch->max_n_crawls == 0) || (pi->n_crawls < sch->max_n_crawls)) &&
!page_info_is_seed(pi)){
float freq = freq_default;
if (freq_scale > 0) {
float rate = page_info_rate(pi);
if (rate > 0) {
freq = freq_scale * rate;
}
}
if (freq_scheduler_cursor_write(sch, cursor, hash, freq) != 0)
goto on_error;
}
page_info_delete(pi);
}
if (ss != stream_state_end) {
error1 = "incorrect stream state";
error2 = 0;
hashinfo_stream_delete(st);
goto on_error;
}
hashinfo_stream_delete(st);
if (freq_scheduler_cursor_commit(sch, cursor) != 0)
goto on_error;
return sch->error->code;
on_error:
freq_scheduler_cursor_abort(sch, cursor);
freq_scheduler_set_error(sch, freq_scheduler_error_internal, __func__);
freq_scheduler_add_error(sch, error1);
freq_scheduler_add_error(sch, error2);
return sch->error->code;
}
FreqSchedulerError
freq_scheduler_load_mmap(FreqScheduler *sch, MMapArray *freqs) {
char *error1 = 0;
char *error2 = 0;
MDB_cursor *cursor = 0;
if (txn_manager_expand(
sch->txn_manager,
2*freqs->n_elements*freqs->element_size) != 0) {
error1 = "resizing database";
error2 = sch->txn_manager->error->message;
goto on_error;
}
if (freq_scheduler_cursor_open(sch, &cursor) != 0)
goto on_error;
for (size_t i=0; i<freqs->n_elements; ++i) {
PageFreq *f = mmap_array_idx(freqs, i);
ScheduleKey sk = {
.score = 1.0/f->freq,
.hash = f->hash
};
MDB_val key = {
.mv_size = sizeof(sk),
.mv_data = &sk,
};
MDB_val val = {
.mv_size = sizeof(float),
.mv_data = &f->freq,
};
int mdb_rc;
if ((mdb_rc = mdb_cursor_put(cursor, &key, &val, 0)) != 0) {
error1 = "adding page to schedule";
error2 = mdb_strerror(mdb_rc);
goto on_error;
}
}
if (freq_scheduler_cursor_commit(sch, cursor) != 0)
goto on_error;
return sch->error->code;
on_error:
freq_scheduler_cursor_abort(sch, cursor);
freq_scheduler_set_error(sch, freq_scheduler_error_internal, __func__);
freq_scheduler_add_error(sch, error1);
freq_scheduler_add_error(sch, error2);
return sch->error->code;
}
FreqSchedulerError
freq_scheduler_request(FreqScheduler *sch,
size_t max_requests,
PageRequest **request) {
char *error1 = 0;
char *error2 = 0;
MDB_cursor *cursor = 0;
if (freq_scheduler_cursor_open(sch, &cursor) != 0)
goto on_error;
PageRequest *req = *request = page_request_new(max_requests);
if (!req) {
error1 = "allocating memory";
goto on_error;
}
int interrupt_requests = 0;
while ((req->n_urls < max_requests) && !interrupt_requests) {
MDB_val key;
MDB_val val;
ScheduleKey sk;
float freq;
int mdb_rc;
int crawl = 0;
switch (mdb_rc = mdb_cursor_get(cursor, &key, &val, MDB_FIRST)) {
case 0:
// copy data before deleting cursor
sk = *(ScheduleKey*)key.mv_data;
freq = *(float*)val.mv_data;
PageInfo *pi = 0;
if (page_db_get_info(sch->page_db, sk.hash, &pi) != 0) {
error1 = "retrieving PageInfo from PageDB";
error2 = sch->page_db->error->message;
goto on_error;
}
if (pi) {
if (sch->margin >= 0) {
double elapsed = difftime(time(0), 0) - pi->last_crawl;
if (elapsed < 1.0/(freq*(1.0 + sch->margin)))
interrupt_requests = 1;
}
crawl = (sch->max_n_crawls == 0) || (pi->n_crawls < sch->max_n_crawls);
}
if (!interrupt_requests) {
if ((mdb_rc = mdb_cursor_del(cursor, 0)) != 0) {
error1 = "deleting head of schedule";
error2 = mdb_strerror(mdb_rc);
goto on_error;
}
if (crawl) {
if (page_request_add_url(req, pi->url) != 0) {
error1 = "adding url to request";
goto on_error;
}
sk.score += 1.0/freq;
val.mv_data = &freq;
key.mv_data = &sk;
if ((mdb_rc = mdb_cursor_put(cursor, &key, &val, 0)) != 0) {
error1 = "moving element inside schedule";
error2 = mdb_strerror(mdb_rc);
goto on_error;
}
}
}
page_info_delete(pi);
break;
case MDB_NOTFOUND: // no more pages left
interrupt_requests = 1;
break;
default:
error1 = "getting head of schedule";
error2 = mdb_strerror(mdb_rc);
goto on_error;
}
}
if (freq_scheduler_cursor_commit(sch, cursor) != 0)
goto on_error;
return sch->error->code;
on_error:
freq_scheduler_cursor_abort(sch, cursor);
freq_scheduler_set_error(sch, freq_scheduler_error_internal, __func__);
freq_scheduler_add_error(sch, error1);
freq_scheduler_add_error(sch, error2);
return sch->error->code;
}
FreqSchedulerError
freq_scheduler_add(FreqScheduler *sch, const CrawledPage *page) {
if (page_db_add(sch->page_db, page, 0) != 0) {
freq_scheduler_set_error(sch, freq_scheduler_error_internal, __func__);
freq_scheduler_add_error(sch, "adding crawled page");
freq_scheduler_add_error(sch, sch->page_db->error->message);
}
return sch->error->code;
}
void
freq_scheduler_delete(FreqScheduler *sch) {
mdb_env_close(sch->txn_manager->env);
(void)txn_manager_delete(sch->txn_manager);
if (!sch->persist) {
char *data = build_path(sch->path, "data.mdb");
char *lock = build_path(sch->path, "lock.mdb");
remove(data);
remove(lock);
free(data);
free(lock);
remove(sch->path);
}
free(sch->path);
error_delete(sch->error);
free(sch);
}
FreqSchedulerError
freq_scheduler_dump(FreqScheduler *sch, FILE *output) {
MDB_cursor *cursor;
if (freq_scheduler_cursor_open(sch, &cursor) != 0)
return sch->error->code;
int end = 0;
MDB_cursor_op cursor_op = MDB_FIRST;
do {
int mdb_rc;
MDB_val key;
MDB_val val;
ScheduleKey *key_data;
float *val_data;
switch (mdb_rc = mdb_cursor_get(cursor, &key, &val, cursor_op)) {
case 0:
key_data = (ScheduleKey*)key.mv_data;
val_data = (float*)val.mv_data;
fprintf(output, "%.2e %016"PRIx64" %.2e\n",
key_data->score, key_data->hash, *val_data);
break;
case MDB_NOTFOUND:
end = 1;
break;
default:
freq_scheduler_set_error(sch, freq_scheduler_error_internal, __func__);
freq_scheduler_add_error(sch, "iterating over database");
freq_scheduler_add_error(sch, mdb_strerror(mdb_rc));
end = 1;
break;
}
cursor_op = MDB_NEXT;
} while (!end);
freq_scheduler_cursor_abort(sch, cursor);
return sch->error->code;
}
#if (defined TEST) && TEST
#include "test_freq_scheduler.c"
#endif // TEST
| 2.015625 | 2 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.