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:56:36.249700+00:00 | 2023-08-10T13:42:17 | f65e1c2fd857bd82cb11d3ba6779e3a6d2ca595d | {
"blob_id": "f65e1c2fd857bd82cb11d3ba6779e3a6d2ca595d",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-10T13:42:17",
"content_id": "6d813d831e253cb81bee256889e9de55bce4c8be",
"detected_licenses": [
"MIT"
],
"directory_id": "6ff85b80c6fe1b3ad5416a304b93551a5e80de10",
"extension": "c",
"filename": "LoopVariable.c",
"fork_events_count": 136,
"gha_created_at": "2017-01-11T11:19:24",
"gha_event_created_at": "2023-01-28T12:10:01",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 78631930,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2550,
"license": "MIT",
"license_type": "permissive",
"path": "/C/Algorithm/LoopVariable.c",
"provenance": "stackv2-0004.json.gz:22698",
"repo_name": "maniero/SOpt",
"revision_date": "2023-08-10T13:42:17",
"revision_id": "5d17e1a9cbf115eaea6d30af2079d0c92ffff7a3",
"snapshot_id": "c600cc2333e0a47ce013be3516bbb8080502ff2a",
"src_encoding": "UTF-8",
"star_events_count": 1002,
"url": "https://raw.githubusercontent.com/maniero/SOpt/5d17e1a9cbf115eaea6d30af2079d0c92ffff7a3/C/Algorithm/LoopVariable.c",
"visit_date": "2023-08-10T16:48:46.058739"
} | stackv2 | #include <stdio.h>
int main() {
struct pessoas {
int codTC; //codigo do consumidor para falar se é 1-Residencial 2-Comercial 3-Industrial
int num; //numero do consumidor (vou colocar o numero referente ao cod para nao confundir)
float kwh; //Quilowatt-hora
};
struct pessoas consumidor[16];
float total, totalT, consumo1, consumo2;
int i = 0;
printf("\nExercício desenvolvido considerando a tarifa do CIP - Contribuição Municipal\n");
do {
printf("\nTipo de consumidor, digite:\n1 - Residencial\n2 - Comercial\n3 - Industrial: ");
scanf("%i", &consumidor[i].codTC);
fflush(stdin);
if (consumidor[i].codTC == 1) {
printf("\nResidencial");
printf("\n\nDigite o numero do consumidor: ");
scanf("%i", &consumidor[i].num);
printf("\nDigite a quantidade de kWh consumidos durante o mes: ");
scanf("%f", &consumidor[i].kwh);
//O total do valor sem tarifa, ou seja o custo total para cada consumidor;
total = consumidor[i].kwh * 0.3;
//O total do valor com tarifa, ou seja o total + tarifas
totalT = total + 5.17;
consumo1 = consumidor[i].kwh;
} else if (consumidor[i].codTC == 2) {
printf("\nComercial");
printf("\n\nDigite o numero do consumidor: ");
scanf("%i", &consumidor[i].num);
printf("\nDigite a quantidade de kWh consumidos durante o mes: ");
scanf("%f", &consumidor[i].kwh);
total = consumidor[i].kwh * 0.5;
//O total do valor com tarifa, ou seja o total + tarifas
totalT = total + 5.17;
consumo2 = consumidor[i].kwh;
} else if (consumidor[i].codTC == 3) {
printf("\nIndustrial");
printf("\n\nDigite o numero do consumidor: ");
scanf("%i", &consumidor[i].num);
printf("\nDigite a quantidade de kWh consumidos durante o mes: ");
scanf("%f", &consumidor[i].kwh);
total = consumidor[i].kwh * 0.7;
//O total do valor com tarifa, ou seja o total + tarifas
totalT = total + 5.17;
}
float media = consumo1 + consumo2 / 2;
printf("\nO total de consumo e %.2f\n", total);
printf("\nO custo total e %.2f\n", totalT);
printf("\nA media de consumo dos consumidores 1 e 2 e %.2f\n", media);
i++;
} while (consumidor[i - 1].num != 0);
}
//https://pt.stackoverflow.com/q/87889/101
| 3.03125 | 3 |
2024-11-18T18:56:40.257385+00:00 | 2017-06-24T13:26:05 | 367ac395b1ebf5d8a3d478c6cdb7e99c0cdc7c01 | {
"blob_id": "367ac395b1ebf5d8a3d478c6cdb7e99c0cdc7c01",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-24T13:26:05",
"content_id": "099fad75e6a90ac7226e8775070db236bd225af9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "80d20f56dcf8e7660360562e0668c1a61fde9841",
"extension": "c",
"filename": "test.wrapping.c",
"fork_events_count": 8,
"gha_created_at": "2017-05-22T14:14:47",
"gha_event_created_at": "2020-02-02T18:52:07",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 92061529,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1547,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/moxie/test/test.wrapping.c",
"provenance": "stackv2-0004.json.gz:22954",
"repo_name": "LedgerHQ/bolos-enclave",
"revision_date": "2017-06-24T13:26:05",
"revision_id": "573464ed783540704137b1cdc6dfd82c02c825ad",
"snapshot_id": "57011c7a20a41583bd55b1abddbb06587f61406c",
"src_encoding": "UTF-8",
"star_events_count": 37,
"url": "https://raw.githubusercontent.com/LedgerHQ/bolos-enclave/573464ed783540704137b1cdc6dfd82c02c825ad/moxie/test/test.wrapping.c",
"visit_date": "2021-01-21T18:34:33.801096"
} | stackv2 | /*
*******************************************************************************
* BOLOS TEE Samples
* (c) 2016, 2017 Ledger
*
* 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 <stdlib.h>
#include <stdint.h>
#include "bolos.h"
int main(int argc, char **argv) {
unsigned char data[500];
unsigned char data2[500];
bls_copy_input_parameters(data, 0, 3);
int scope = data[0];
if ((data[1] != 0x00) || (data[2] != 0x00)) {
int size = (data[1] << 8) | data[2];
bls_copy_input_parameters(data, 3, size);
int result = bls_unwrap(scope, data, size, data2, sizeof(data2));
if (result == 0) {
bls_debug("Unwrap fail\n");
}
else {
bls_set_return(data2, result);
}
}
else {
int i;
for (i=0; i<10; i++) {
data[i] = i;
}
int result = bls_wrap(scope, data, 10, data2, sizeof(data2));
if (result == 0) {
bls_debug("Wrap fail\n");
}
else {
bls_set_return(data2, result);
}
}
}
| 2.328125 | 2 |
2024-11-18T18:56:40.319547+00:00 | 2014-04-23T02:13:25 | 62407892cac709a6068b0c990a7f250816e630a0 | {
"blob_id": "62407892cac709a6068b0c990a7f250816e630a0",
"branch_name": "refs/heads/master",
"committer_date": "2014-04-23T02:13:25",
"content_id": "77ec511958759075de9c44c633fac98c851f522f",
"detected_licenses": [
"MIT"
],
"directory_id": "3093432c54b7b5c26fa7588bd3c337e3431ee726",
"extension": "c",
"filename": "wk5_n1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 16112155,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 946,
"license": "MIT",
"license_type": "permissive",
"path": "/set3/wk5_n1.c",
"provenance": "stackv2-0004.json.gz:23082",
"repo_name": "NanoSmasher/aps106-problems",
"revision_date": "2014-04-23T02:13:25",
"revision_id": "8007b9bcb9c52a33803c5efe7c7ec3d43fde46c5",
"snapshot_id": "3055585c1eef8a8295118568804ece899a603dd4",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/NanoSmasher/aps106-problems/8007b9bcb9c52a33803c5efe7c7ec3d43fde46c5/set3/wk5_n1.c",
"visit_date": "2021-01-20T04:33:16.633856"
} | stackv2 | #include <stdio.h>
int main(){
/*
The following short questions have all appeared on old midterms and finals:
(a) Convert the hexadecimal number ABCD to a binary number.
(b) Consider the following four non-decimal numbers, where the subscripts indicate the base of each number:
A8_16 251_8 2222_4 10100111_2.
Which number is the smallest, and which is the largest?
(c) What is the binary representation of a, where a = 27_16 - 27_8 ?
(d) What is the octal (base 8) representation of the hexadecimal value B38?
*/
printf("a) ABCD_16 = 43981 = 101010111100111_2 ");
printf("\n\n\n\n");
printf("A8_16 = 168");
printf("251_8 = 169");
printf("2222_4 = 170 < largest");
printf("10100111_2 = 167 < smallest");
printf("\n\n\n\n");
printf("a = 27_16 - 27_8 = 16 = 1000_2");
printf("\n\n\n\n");
printf("B38_16 = 5470_8");
printf("\n\n\n\n");
return 0;
}
| 3.21875 | 3 |
2024-11-18T18:56:40.391551+00:00 | 2018-05-15T05:33:54 | a03a289f5ececfd1cb92e7429c7395b8f62b5fd5 | {
"blob_id": "a03a289f5ececfd1cb92e7429c7395b8f62b5fd5",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-15T05:33:54",
"content_id": "5da1b5ab8e72e4eb8fc9f5d8c24b4678fa94e28b",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "96a178dd7db1f6d677d28344c9fa580fcec5ef35",
"extension": "c",
"filename": "lib_ser.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 131357389,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5360,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/lib_ser.c",
"provenance": "stackv2-0004.json.gz:23210",
"repo_name": "dereksnyder42v2/diet-fi",
"revision_date": "2018-05-15T05:33:54",
"revision_id": "ae609112f1e73f65fa53390831f253bac722e07a",
"snapshot_id": "fdff5b8a430a83c5e5a67bae3735e5fbb0104829",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dereksnyder42v2/diet-fi/ae609112f1e73f65fa53390831f253bac722e07a/lib_ser.c",
"visit_date": "2020-03-14T00:28:33.725335"
} | stackv2 | #include <stdio.h> /* Standard I/O definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
/* Lots of credit to Michael R. Sweet for his writeup.
* A lot of this is directly or slightly indirectly his code, adapted for my uses.
* http://www.cmrr.umn.edu/~strupp/serial.html#2_1
*
* Derek Snyder
* Fri 27 Apr 20:53:06 EDT 2018
*/
/* Common baud rates
* B9600
* B19200
* B115200
*/
#define BAUDRT B9600
/* Common char size and parity bit setups
* 8N1 No parity
* 7E1 Even parity
* 7O1 Odd parity
* 7S1 Space parity/ no parity
*/
#define _8N1 0
#define _7E1 1
#define _7O1 2
#define _7S1 3
#define PARITY _8N1
const long vdisable = _POSIX_VDISABLE;
/* Params
* (str) name of serial port, in /dev/
* Returns
* (int) file descriptor of port
*/
int
open_port(void* port_name)
{
int fd; // File descriptor for port
/* O_RDWR read/write mode
* O_NOCTTY tells UNIX that this program doesn't want to be the
* 'controlling terminal' for this port. Otherwise,
* keyboard abort signals (&c.) could affect process.
* O_NDELAY tells UNIX that the program doesn't care what state
* DCD ('Data Carrier Detect') line is in
* <--> in other words, what state the other end of
* the port is in
*/
//fd = open(PORT, O_RDWR | O_NOCTTY | O_NDELAY);
fd = open(port_name, O_RDWR | O_NOCTTY );
if (fd == -1)
{
// Couldn't open port
perror("open_port(): Unable to open PORT - ");
}
else
{
/* set third argument to 0 for blocking read() calls,
* or set to "FNDELAY" for nonblocking */
fcntl(fd, F_SETFL, 0);
struct termios options;
/* Get current port configuration */
tcgetattr(fd, &options);
/* Set baud rate to definition (I and O respectively) */
cfsetispeed(&options, BAUDRT);
cfsetospeed(&options, BAUDRT);
/* Raw output */
options.c_oflag &= ~OPOST;
/* Set control options with c_cflag member.
* These should be set as so pretty much always...
* CLOCAL local line; don't change port owner
* CREAD enable receiver
*/
options.c_cflag |= (CLOCAL | CREAD);
/* Mask character size bits; gotta do this before setting */
options.c_cflag &= ~CSIZE;
/* Now set parity based on #def */
if (PARITY == _8N1)
{
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag |= CS8;
}
else if (PARITY == _7E1)
{
options.c_cflag |= PARENB;
options.c_cflag &= ~PARODD;
options.c_cflag &= ~CSTOPB;
options.c_cflag |= CS7;
}
else if (PARITY == _7O1)
{
options.c_cflag |= PARENB;
options.c_cflag |= PARODD;
options.c_cflag &= ~CSTOPB;
options.c_cflag |= CS7;
}
else if (PARITY == _7S1)
{
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag |= CS8;
}
/* Types of input setup:
* Canonical input is line-oriented; characters are put in a buffer and only sent when
* CR or NL is received
* Raw input is unprocessed. Whatever goes in, goes out.
*/
//options.c_lflag |= (ICANON | ECHO | ECHOE); // canonical
options.c_lflag &= !(ICANON | ECHO | ECHOE | ISIG); // raw
/* Disabling special characters, preserving actual bytes in TX/RX
* TODO
options.c_cc[VDISCARD] = vdisable;
options.c_cc[VDSUSP] = vdisable;
options.c_cc[VEOF] = vdisable;
options.c_cc[VEOL] = vdisable;
options.c_cc[VEOL2] = vdisable;
options.c_cc[VERASE] = vdisable;
//options.c_cc[VERASE2] = vdisable; // BSD only
options.c_cc[VINTR] = vdisable;
options.c_cc[VKILL] = vdisable;
//options.c_cc[VINTR] = vdisable;
//options.c_cc[VINTR] = vdisable;
//options.c_cc[VINTR] = vdisable;
//options.c_cc[VINTR] = vdisable;
*/
// TODO
/* Input parity checking
*
*/
// TODO
/* Software flow control
*
*/
// TODO
/* Output options
*
*/
/* Now set new options.
* TCSANOW means do it now, instead of waiting for input
* output operations to finish
* TCSADRAIN wait until IO operations finish
* TCSAFLUSH flush IO buffers and make changes
*/
tcsetattr(fd, TCSAFLUSH, &options);
}
return (fd);
}
/* Params
* (int) fd file descriptor of port
* (*void) buffer base pointer to write to
* (size_t)count max number of Bytes to write into buffer
* Returns
* (int) number of Bytes read from port
*/
int
read_port(int fd, void* buf, size_t count)
{
int bytes_read = read(fd, buf, count);
if (bytes_read < 0)
perror("Error: in read_port(): -");
return bytes_read;
}
/* Params
* (int) fd file descriptor of port
* (ptr) buf pointer to what to write
* (size_t)count max number of bytes to write
* Returns
* (int) number of bytes written, or -1 if error occurred
*/
int
write_port(int fd, void* buf, size_t count)
{
int n = write(fd, buf, count);
if (n < 0)
{
;
/* TODO find a better way to handle write_port errors.
* getting a lot of "resource busy" errors etc.
*/
perror("write_port(): Unable to write to PORT -");
}
return (n);
}
/* Params
* (int) fd file descriptor of port
* Returns
* (int) "0" on success, "-1" on failure
*/
int
close_port(int fd)
{
return (close(fd));
}
| 2.671875 | 3 |
2024-11-18T18:56:40.569893+00:00 | 2017-10-17T16:23:07 | 29b0744feabc40f8562645aac14c3a8bea125714 | {
"blob_id": "29b0744feabc40f8562645aac14c3a8bea125714",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-17T16:23:07",
"content_id": "3b3abe6d4bb9561c26a31314ebab04a8f62f4579",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "eb913ec065018dda4aa49a64930aff35faa08f93",
"extension": "c",
"filename": "main.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 100621568,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 473,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/SelectionSort/main.c",
"provenance": "stackv2-0004.json.gz:23466",
"repo_name": "zaqueumoura/APA",
"revision_date": "2017-10-17T16:23:07",
"revision_id": "55b10d40648a8f33592cb2e79084adc2aa11d445",
"snapshot_id": "1664c09305ff83cfd259f5dae59aa07d134b579a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zaqueumoura/APA/55b10d40648a8f33592cb2e79084adc2aa11d445/SelectionSort/main.c",
"visit_date": "2021-07-14T03:08:58.610781"
} | stackv2 | #include <stdio.h>
#include "selection_sort.h"
void imprimeVetor(int vetor[], int max){
int i = 0;
for (i = 0; i < max; i++) {
printf ("%d ",vetor[i]);
}
printf ("\n");
}
int main () {
int max, i;
printf("Digite o tamanho do vetor\n");
scanf ("%d",&max);
int vetor[max];
for (i = 0; i < max; i++) {
printf("Digite os numeros do vetor\n");
scanf ("%d",&vetor[i]);
}
selection_sort (vetor, max);
imprimeVetor(vetor, max);
} | 3.203125 | 3 |
2024-11-18T18:56:41.395059+00:00 | 2020-06-27T04:01:46 | d8d73e2ecad6d23c6756741b84032f34023720d3 | {
"blob_id": "d8d73e2ecad6d23c6756741b84032f34023720d3",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-27T04:01:46",
"content_id": "5e8d522a9633acd18e334725ae3724a987df3773",
"detected_licenses": [
"Unlicense"
],
"directory_id": "2615a03ef8330c5880b5c9ddefd2462f80ae8333",
"extension": "c",
"filename": "pregunta3.c",
"fork_events_count": 0,
"gha_created_at": "2020-03-01T06:14:33",
"gha_event_created_at": "2020-06-27T04:00:24",
"gha_language": "C",
"gha_license_id": "Unlicense",
"github_id": 244097526,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 554,
"license": "Unlicense",
"license_type": "permissive",
"path": "/Laboratorios/Laboratorio1/pregunta3.c",
"provenance": "stackv2-0004.json.gz:24106",
"repo_name": "Shompi/datastructures",
"revision_date": "2020-06-27T04:01:46",
"revision_id": "e72f9caed622e64f4b472011b6b3773e7057588f",
"snapshot_id": "cc3c3d725fba7feffd97155233f178e13fba1766",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Shompi/datastructures/e72f9caed622e64f4b472011b6b3773e7057588f/Laboratorios/Laboratorio1/pregunta3.c",
"visit_date": "2021-02-08T02:17:29.047679"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
void factorial(int *n, int *r)
{
for (*n = *n; *n > 1; *n = *n - 1)
{
*r = *r * *n;
}
}
int main()
{
/*
Implementar una función que calcule el factorial
de un número
*/
int numero;
int resultado = 1;
do
{
printf("Ingrese un numero positivo para calcular su factorial: ");
scanf("%i", &numero);
if (numero < 0)
printf("\nEl numero ingresado no es valido.\n");
} while (numero < 0);
factorial(&numero, &resultado);
printf("\nEl resultado es: %i", resultado);
} | 3.859375 | 4 |
2024-11-18T18:56:41.937575+00:00 | 2022-01-30T10:10:17 | 5430da2a76eee26332c5e05f2acce35ad6570855 | {
"blob_id": "5430da2a76eee26332c5e05f2acce35ad6570855",
"branch_name": "refs/heads/master",
"committer_date": "2022-01-30T10:10:17",
"content_id": "d8217ad1835850be262c6d8ee24fa8229f07e40d",
"detected_licenses": [
"MIT"
],
"directory_id": "2996465417a4b4c930844ee5fcde6d38379b2576",
"extension": "h",
"filename": "isotp_defines.h",
"fork_events_count": 70,
"gha_created_at": "2018-10-09T06:53:18",
"gha_event_created_at": "2023-06-01T13:28:21",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 152202150,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6198,
"license": "MIT",
"license_type": "permissive",
"path": "/isotp_defines.h",
"provenance": "stackv2-0004.json.gz:24619",
"repo_name": "lishen2/isotp-c",
"revision_date": "2022-01-30T10:10:17",
"revision_id": "5593428d95af10dde1e565cebcda16089fc74857",
"snapshot_id": "219ed2c948bd2499634d57826238dc39e6d5bca7",
"src_encoding": "UTF-8",
"star_events_count": 149,
"url": "https://raw.githubusercontent.com/lishen2/isotp-c/5593428d95af10dde1e565cebcda16089fc74857/isotp_defines.h",
"visit_date": "2023-06-07T22:36:31.723920"
} | stackv2 | #ifndef __ISOTP_TYPES__
#define __ISOTP_TYPES__
/**************************************************************
* compiler specific defines
*************************************************************/
#ifdef __GNUC__
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define ISOTP_BYTE_ORDER_LITTLE_ENDIAN
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#else
#error "unsupported byte ordering"
#endif
#endif
/**************************************************************
* OS specific defines
*************************************************************/
#ifdef _WIN32
#define snprintf _snprintf
#endif
#ifdef _WIN32
#define ISOTP_BYTE_ORDER_LITTLE_ENDIAN
#define __builtin_bswap8 _byteswap_uint8
#define __builtin_bswap16 _byteswap_uint16
#define __builtin_bswap32 _byteswap_uint32
#define __builtin_bswap64 _byteswap_uint64
#endif
/**************************************************************
* internal used defines
*************************************************************/
#define ISOTP_RET_OK 0
#define ISOTP_RET_ERROR -1
#define ISOTP_RET_INPROGRESS -2
#define ISOTP_RET_OVERFLOW -3
#define ISOTP_RET_WRONG_SN -4
#define ISOTP_RET_NO_DATA -5
#define ISOTP_RET_TIMEOUT -6
#define ISOTP_RET_LENGTH -7
/* return logic true if 'a' is after 'b' */
#define IsoTpTimeAfter(a,b) ((int32_t)((int32_t)(b) - (int32_t)(a)) < 0)
/* invalid bs */
#define ISOTP_INVALID_BS 0xFFFF
/* ISOTP sender status */
typedef enum {
ISOTP_SEND_STATUS_IDLE,
ISOTP_SEND_STATUS_INPROGRESS,
ISOTP_SEND_STATUS_ERROR,
} IsoTpSendStatusTypes;
/* ISOTP receiver status */
typedef enum {
ISOTP_RECEIVE_STATUS_IDLE,
ISOTP_RECEIVE_STATUS_INPROGRESS,
ISOTP_RECEIVE_STATUS_FULL,
} IsoTpReceiveStatusTypes;
/* can fram defination */
#if defined(ISOTP_BYTE_ORDER_LITTLE_ENDIAN)
typedef struct {
uint8_t reserve_1:4;
uint8_t type:4;
uint8_t reserve_2[7];
} IsoTpPciType;
typedef struct {
uint8_t SF_DL:4;
uint8_t type:4;
uint8_t data[7];
} IsoTpSingleFrame;
typedef struct {
uint8_t FF_DL_high:4;
uint8_t type:4;
uint8_t FF_DL_low;
uint8_t data[6];
} IsoTpFirstFrame;
typedef struct {
uint8_t SN:4;
uint8_t type:4;
uint8_t data[7];
} IsoTpConsecutiveFrame;
typedef struct {
uint8_t FS:4;
uint8_t type:4;
uint8_t BS;
uint8_t STmin;
uint8_t reserve[5];
} IsoTpFlowControl;
#else
typedef struct {
uint8_t type:4;
uint8_t reserve_1:4;
uint8_t reserve_2[7];
} IsoTpPciType;
/*
* single frame
* +-------------------------+-----+
* | byte #0 | ... |
* +-------------------------+-----+
* | nibble #0 | nibble #1 | ... |
* +-------------+-----------+ ... +
* | PCIType = 0 | SF_DL | ... |
* +-------------+-----------+-----+
*/
typedef struct {
uint8_t type:4;
uint8_t SF_DL:4;
uint8_t data[7];
} IsoTpSingleFrame;
/*
* first frame
* +-------------------------+-----------------------+-----+
* | byte #0 | byte #1 | ... |
* +-------------------------+-----------+-----------+-----+
* | nibble #0 | nibble #1 | nibble #2 | nibble #3 | ... |
* +-------------+-----------+-----------+-----------+-----+
* | PCIType = 1 | FF_DL | ... |
* +-------------+-----------+-----------------------+-----+
*/
typedef struct {
uint8_t type:4;
uint8_t FF_DL_high:4;
uint8_t FF_DL_low;
uint8_t data[6];
} IsoTpFirstFrame;
/*
* consecutive frame
* +-------------------------+-----+
* | byte #0 | ... |
* +-------------------------+-----+
* | nibble #0 | nibble #1 | ... |
* +-------------+-----------+ ... +
* | PCIType = 0 | SN | ... |
* +-------------+-----------+-----+
*/
typedef struct {
uint8_t type:4;
uint8_t SN:4;
uint8_t data[7];
} IsoTpConsecutiveFrame;
/*
* flow control frame
* +-------------------------+-----------------------+-----------------------+-----+
* | byte #0 | byte #1 | byte #2 | ... |
* +-------------------------+-----------+-----------+-----------+-----------+-----+
* | nibble #0 | nibble #1 | nibble #2 | nibble #3 | nibble #4 | nibble #5 | ... |
* +-------------+-----------+-----------+-----------+-----------+-----------+-----+
* | PCIType = 1 | FS | BS | STmin | ... |
* +-------------+-----------+-----------------------+-----------------------+-----+
*/
typedef struct {
uint8_t type:4;
uint8_t FS:4;
uint8_t BS;
uint8_t STmin;
uint8_t reserve[5];
} IsoTpFlowControl;
#endif
typedef struct {
uint8_t ptr[8];
} IsoTpDataArray;
typedef struct {
union {
IsoTpPciType common;
IsoTpSingleFrame single_frame;
IsoTpFirstFrame first_frame;
IsoTpConsecutiveFrame consecutive_frame;
IsoTpFlowControl flow_control;
IsoTpDataArray data_array;
} as;
} IsoTpCanMessage;
/**************************************************************
* protocol specific defines
*************************************************************/
/* Private: Protocol Control Information (PCI) types, for identifying each frame of an ISO-TP message.
*/
typedef enum {
ISOTP_PCI_TYPE_SINGLE = 0x0,
ISOTP_PCI_TYPE_FIRST_FRAME = 0x1,
TSOTP_PCI_TYPE_CONSECUTIVE_FRAME = 0x2,
ISOTP_PCI_TYPE_FLOW_CONTROL_FRAME = 0x3
} IsoTpProtocolControlInformation;
/* Private: Protocol Control Information (PCI) flow control identifiers.
*/
typedef enum {
PCI_FLOW_STATUS_CONTINUE = 0x0,
PCI_FLOW_STATUS_WAIT = 0x1,
PCI_FLOW_STATUS_OVERFLOW = 0x2
} IsoTpFlowStatus;
/* Private: network layer resault code.
*/
#define ISOTP_PROTOCOL_RESULT_OK 0
#define ISOTP_PROTOCOL_RESULT_TIMEOUT_A -1
#define ISOTP_PROTOCOL_RESULT_TIMEOUT_BS -2
#define ISOTP_PROTOCOL_RESULT_TIMEOUT_CR -3
#define ISOTP_PROTOCOL_RESULT_WRONG_SN -4
#define ISOTP_PROTOCOL_RESULT_INVALID_FS -5
#define ISOTP_PROTOCOL_RESULT_UNEXP_PDU -6
#define ISOTP_PROTOCOL_RESULT_WFT_OVRN -7
#define ISOTP_PROTOCOL_RESULT_BUFFER_OVFLW -8
#define ISOTP_PROTOCOL_RESULT_ERROR -9
#endif
| 2.015625 | 2 |
2024-11-18T18:56:42.019422+00:00 | 2018-01-25T17:10:39 | 271519341479f1c73c3092c9e3b565b2d96d3c67 | {
"blob_id": "271519341479f1c73c3092c9e3b565b2d96d3c67",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-25T17:10:39",
"content_id": "7b0a65108db612cf05460a41a2a5beb645f4c526",
"detected_licenses": [
"MIT"
],
"directory_id": "ed59c963efe92f5d82ff78dd9efc1993179a4787",
"extension": "c",
"filename": "distanciaMatrizes.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44780318,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1014,
"license": "MIT",
"license_type": "permissive",
"path": "/distanciaMatrizes.c",
"provenance": "stackv2-0004.json.gz:24747",
"repo_name": "HosanaUFRRJ2014/transformada-Discreta-do-Cosseno-TDC-e-Transformada-Inversa-TIC-",
"revision_date": "2018-01-25T17:10:39",
"revision_id": "61abae751139e50a1a8dcee30deba1f69088585a",
"snapshot_id": "df07ffc564739ea8c2c5933650992a8426efad89",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/HosanaUFRRJ2014/transformada-Discreta-do-Cosseno-TDC-e-Transformada-Inversa-TIC-/61abae751139e50a1a8dcee30deba1f69088585a/distanciaMatrizes.c",
"visit_date": "2021-01-10T17:52:21.535310"
} | stackv2 | #include "stdio.h"
#include "math.h"
/*Matriz Original é a dada pelo usuario(conjuntovetor)
e a matriz comprimida é a que veio da TDC (matriz da transformada)*/
/*A distancia entre matrizes é calculada pelo valor máximo(em módulo) da diferença
entre os valores de matrizOriginal e a matrizComprimida.
Em outras palavras, será feita a diferença de cada valor i, j das matrizes
esse valor será posto em módulo. O maior módulo encontrado será a distancia entre as
matrizes.
*/
void distanciaMatrizes(int DIM, float matrizOriginal[][DIM], float matrizComprimida[][DIM])
{
int linha, coluna;
float distancia = 0;
float diferenca = 0; //guarda a diferenca entre cada elemento das matrizes
for (linha = 0; linha < DIM; linha++)
{
for (coluna = 0; coluna < DIM; coluna++)
{
diferenca = matrizOriginal[linha][coluna] - matrizComprimida[linha][coluna];
diferenca = sqrt(pow(diferenca,2));
if(diferenca > distancia)
distancia = diferenca;
}
}
printf("%f\n",distancia);
}
| 3.140625 | 3 |
2024-11-18T18:56:42.102418+00:00 | 2020-04-26T20:10:59 | e93bf707931fe975d18d4ba3fd5613183721b836 | {
"blob_id": "e93bf707931fe975d18d4ba3fd5613183721b836",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-26T20:10:59",
"content_id": "834137088f9540120aa3e487af9b74b4ef9a570b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c20eab49ff6ee454db60d18d98c16191c67544b7",
"extension": "h",
"filename": "preamble.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 255118481,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 942,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/crc-receiver/src/preamble.h",
"provenance": "stackv2-0004.json.gz:24875",
"repo_name": "napicella/arduino-crc",
"revision_date": "2020-04-26T20:10:59",
"revision_id": "198ac159862e3ee448bb85e32e982b16b8ce7ef1",
"snapshot_id": "d616fb19e1ca2a4a167c1f3eb75de012388c4fa3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/napicella/arduino-crc/198ac159862e3ee448bb85e32e982b16b8ce7ef1/crc-receiver/src/preamble.h",
"visit_date": "2022-05-31T18:52:05.808411"
} | stackv2 | #include <Arduino.h>
volatile bool expected = true;
const int preambleBitsLength = 8;
volatile int preambleBitsToReceive = preambleBitsLength;
bool detectPreamble(int pin) {
if (preambleBitsToReceive == 0) {
return true;
}
bool data = digitalRead(pin);
if (data == expected) {
preambleBitsToReceive--;
expected = !expected;
} else if (data == HIGH) {
preambleBitsToReceive = preambleBitsLength - 1;
expected = false;
} else if (data == LOW) {
preambleBitsToReceive = preambleBitsLength;
expected = true;
}
return false;
}
const int endPreambleBit = 5;
volatile int endPreambleBitToReceive = endPreambleBit;
bool detectEnd(int pin) {
if (endPreambleBitToReceive == 0) {
return true;
}
bool data = digitalRead(pin);
if (data) {
endPreambleBitToReceive--;
return endPreambleBitToReceive == 0;
} else {
endPreambleBitToReceive = endPreambleBit;
return false;
}
} | 2.796875 | 3 |
2024-11-18T18:56:42.250780+00:00 | 2022-10-02T23:20:09 | 21741b3b3504c58bd238fb0932feb2f05fd2d106 | {
"blob_id": "21741b3b3504c58bd238fb0932feb2f05fd2d106",
"branch_name": "refs/heads/main",
"committer_date": "2022-10-02T23:20:09",
"content_id": "51c171c48e842f1646203f0b32cf9cfffa43dbbc",
"detected_licenses": [
"MIT"
],
"directory_id": "5c1328a271a8607e59be87244068ab46fd24c893",
"extension": "c",
"filename": "19-Remove-Nth-Node-From-End-of-List.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 514034071,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 677,
"license": "MIT",
"license_type": "permissive",
"path": "/c/19-Remove-Nth-Node-From-End-of-List.c",
"provenance": "stackv2-0004.json.gz:25131",
"repo_name": "ErdemOzgen/leetcode",
"revision_date": "2022-10-02T23:20:09",
"revision_id": "c50d6fa482a608a2556e92e6f629e9c29089efd6",
"snapshot_id": "32d0f2fae605caf33655db38d8dc701062dd773c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ErdemOzgen/leetcode/c50d6fa482a608a2556e92e6f629e9c29089efd6/c/19-Remove-Nth-Node-From-End-of-List.c",
"visit_date": "2022-11-06T06:22:10.322894"
} | stackv2 | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
if (head->next == NULL) {
return head->next;
}
struct ListNode* slow = head;
struct ListNode* fast = head;
while (n--) {
fast = fast->next;
}
if (fast != NULL) {
while (fast->next != NULL) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
}
else {
slow->val = slow->next->val;
slow->next = slow->next->next;
}
return head;
} | 3.0625 | 3 |
2024-11-18T18:56:42.825525+00:00 | 2020-05-11T23:49:53 | 06a7ae7076618584623db2e573a915bf71c1c7f2 | {
"blob_id": "06a7ae7076618584623db2e573a915bf71c1c7f2",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-11T23:49:53",
"content_id": "68ca1a14ece846ce2bb6968aaecea9626ca5f92a",
"detected_licenses": [
"MIT"
],
"directory_id": "95a44a0ed483cc608132321310dd6ba2387d7b9e",
"extension": "c",
"filename": "16.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 249592266,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1076,
"license": "MIT",
"license_type": "permissive",
"path": "/src/06/16.c",
"provenance": "stackv2-0004.json.gz:25643",
"repo_name": "kgoettler/c-primer-plus",
"revision_date": "2020-05-11T23:49:53",
"revision_id": "0ed507465629942c5fb8766c4d42b5dbb7b45757",
"snapshot_id": "0579ea81b797ad86f264e65d31d6d04a4ef90bdf",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/kgoettler/c-primer-plus/0ed507465629942c5fb8766c4d42b5dbb7b45757/src/06/16.c",
"visit_date": "2021-04-19T07:46:43.864269"
} | stackv2 | /*
* Daphne invests $100 at 10% simple interest. (That is, every year, the
* investment earns an interest equal to 10% of the original investment.)
* Deirdre invests $100 at 5% interest compounded annually. (That is, interest
* is 5% of the current balance, including previous addition of interest.) Write
* a program that finds how many years it takes for the value of Deirdre’s
* investment to exceed the value of Daphne’s investment. Also show the two
* values at that time.
*/
#include <stdio.h>
int main (void)
{
float deirdre_p = 100, daphne_p = 100;
float deirdre_r = 0.05, daphne_r = 0.10;
float deirdre_bal = deirdre_p;
float daphne_bal = daphne_p;
int years = 0;
while (deirdre_bal <= daphne_bal)
{
// Simple interest for Daphne
daphne_bal += daphne_p * daphne_r;
// Compound interest for Deirdre
deirdre_bal *= (1.0 + deirdre_r);
years++;
}
printf("Years: %d\n", years);
printf("Daphne: %.2f\n", daphne_bal);
printf("Deirdre: %.2f\n", deirdre_bal);
return 0;
}
| 3.734375 | 4 |
2024-11-18T18:56:42.981554+00:00 | 2019-05-07T23:15:00 | 54215e67a5cc505c13f3c8852f7eeaa38495896f | {
"blob_id": "54215e67a5cc505c13f3c8852f7eeaa38495896f",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-07T23:15:00",
"content_id": "db869c1749565857b846705e21bc28b513891d60",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "af668c07e6877363d706aa002b48b3c87d4f3d42",
"extension": "c",
"filename": "ATL_pcol2blk.c",
"fork_events_count": 0,
"gha_created_at": "2019-05-07T23:06:54",
"gha_event_created_at": "2019-05-07T23:06:55",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 185490601,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3729,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/src/blas/pklevel3/gpmm/ATL_pcol2blk.c",
"provenance": "stackv2-0004.json.gz:25771",
"repo_name": "kevleyski/math-atlas",
"revision_date": "2019-05-07T23:15:00",
"revision_id": "cc36aa7e0362c577739ac507378068882834825e",
"snapshot_id": "20f30d4f039aafc00811a61a1c65087b2b0739e5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kevleyski/math-atlas/cc36aa7e0362c577739ac507378068882834825e/src/blas/pklevel3/gpmm/ATL_pcol2blk.c",
"visit_date": "2020-05-20T09:05:20.638100"
} | stackv2 | /*
* Automatically Tuned Linear Algebra Software v3.10.3
* (C) Copyright 2003 R. Clint Whaley
*
* 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 ATLAS group or the names of its contributers may
* not be used to endorse or promote products derived from this
* software without specific written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ATLAS GROUP OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "atlas_pkblas.h"
void Mjoin(Mjoin(PATL,pcol2blk),NM)
(const int M, const int N, const TYPE alpha, const TYPE *A, int lda,
const int ldainc, TYPE *V)
/*
* Given a packed matrix A, copies N columns starting at A into
* block-major column panel
* ldainc = 0 : General
* ldainc = 1 : Upper
* ldainc = -1 : Lower
* NOTE: specialize to alpha cases after it works!
*/
{
const int kb = Mmin(M,NB);
const int nrb = M / kb, mr = M - nrb*kb;
int i, ib, j, J;
const int NN = N*kb;
TYPE *v = V + nrb*NN;
if (ldainc)
{
if (ldainc == -1) lda--;
ATL_assert(N <= NB);
for (j=0; j != N; j++)
{
for (ib=nrb; ib; ib--)
{
for (i=0; i < kb; i++) V[i] = ATL_MulByALPHA(A[i]);
V += NN;
A += kb;
}
if (mr)
{
for (i=0; i < mr; i++) v[i] = ATL_MulByALPHA(A[i]);
v += mr;
}
V += kb - nrb*NN;
A += lda - nrb*kb;
lda += ldainc;
}
}
else Mjoin(Mjoin(PATL,col2blk),NM)(M, N, A, lda, V, alpha);
}
#ifdef ALPHA1
void Mjoin(PATL,pcol2blkF)
(const int M, const int N, const SCALAR alpha, const TYPE *A, int lda,
const int ldainc, TYPE *V)
/*
* Copies entire MxN matrix to block major format
*/
{
int j, jb;
const int incV = ATL_MulByNB(M);
const enum PACK_UPLO UA = (ldainc == 1) ? PackUpper :
( (lda == -1) ? PackLower : PackGen );
void (*col2blk)(const int M, const int N, const SCALAR alpha, const TYPE *A,
int lda, const int ldainc, TYPE *V);
if (ldainc)
{
if (alpha == ATL_rone) col2blk = Mjoin(PATL,pcol2blk_a1);
else col2blk = Mjoin(PATL,pcol2blk_aX);
for (j=0; j < N; j += NB)
{
jb = N-j;
jb = Mmin(jb, NB);
col2blk(M, jb, alpha, A+MindexP(UA,0,j,lda), Mpld(UA,j,lda), ldainc,V);
V += incV;
}
}
else if (alpha == ATL_rone)
Mjoin(PATL,col2blk2_a1)(M, N, A, lda, V, alpha);
else
Mjoin(PATL,col2blk2_aX)(M, N, A, lda, V, alpha);
}
#endif
| 2.078125 | 2 |
2024-11-18T18:56:43.601118+00:00 | 2018-11-12T01:54:10 | 6b3c1534c615476e05ee16039f3e77d05f75b461 | {
"blob_id": "6b3c1534c615476e05ee16039f3e77d05f75b461",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-12T01:54:10",
"content_id": "ade660642ecb7d8cf10220111a546429a73feed8",
"detected_licenses": [
"MIT"
],
"directory_id": "35f0288c6311f56b37443edc2c8c76cbd8ecd53e",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2018-11-12T01:55:17",
"gha_event_created_at": "2018-11-12T01:55:18",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 157141959,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11450,
"license": "MIT",
"license_type": "permissive",
"path": "/第六届决赛-电压测量与互补 PWM 信号输出 第二版(全部实现)/USER/main.c",
"provenance": "stackv2-0004.json.gz:26027",
"repo_name": "ranxiaolang/lanqiao-competition-code",
"revision_date": "2018-11-12T01:54:10",
"revision_id": "54cd6feacb399a7e498eb143aa3582e52149435c",
"snapshot_id": "03b5aa7304aa1495a90d13d6a78a0b960d24bd4d",
"src_encoding": "GB18030",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ranxiaolang/lanqiao-competition-code/54cd6feacb399a7e498eb143aa3582e52149435c/第六届决赛-电压测量与互补 PWM 信号输出 第二版(全部实现)/USER/main.c",
"visit_date": "2020-04-05T19:35:45.428907"
} | stackv2 | /*第六届决赛试题——互补输出*/
/*实现全部内容,无bug,*/
/*作者:龚子然*/
#include "stm32f10x.h"
#include <stdio.h>
#include "lcd.h"
#include "LED.h"
#include "i2c.h"
#include "gong.h"
u8 string[20];
u8 SignalPA9=0,PB14=0;
u8 shezhi=0;
u8 qiehuan=0;
u8 i=0;
u8 open=0;
u8 status=1;
u16 run = 0xffff;
float temp1;
float temp2;
float pulse1;
float pulse2;
float CCR2_Val=550.0;
float period=999.0;
u8 f;
u32 TimingDelay = 0;
float ADC_VALUE;
void TIM1_Configuration(uint16_t period,uint16_t CCR2_Val);
void TIM1_cmd(void);
void TIM1_dcmd(void);
void PA9_Display(void);
void PB14_Display(void);
void Period_Display(void);
void Delay_Ms(u32 nTime);
void KEY_Scan(void);
void AD_Read(void);
void LCD_Init(void);
void LED_RUN(u16 run);
int main(void)
{
SysTick_Config(SystemCoreClock/1000);
LCD_Init();
GPIO_Int();
i2c_init();
Delay_Ms(10);
if(IIC_Read(0x40)!=30)
{
Delay_Ms(10);
IIC_Write(0x11,1);
Delay_Ms(10);
IIC_Write(0x40,30);
}
Delay_Ms(10);
f=IIC_Read(0x11);
TIM1_Configuration(period,CCR2_Val);
TIM1_cmd();
// sprintf((char*)string,"%s%d","period:",f);
// LCD_DisplayStringLine(Line9,string);
while (1)
{
KEY_Scan();
if(shezhi==0)
{
AD_Read();
if(open==0)
{
PA9_Display();
PB14_Display();
Period_Display();
}
}
}
}
void AD_Read(void){
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
ADC_VALUE = ADC_GetConversionValue(ADC1)*3.3/0xFFF;
sprintf((char*)string,"%s%.2fV "," Votage:",ADC_VALUE);
LCD_DisplayStringLine(Line3,string);
switch(f)//频率转换
{
case 1:
period=999.0;
break;
case 2:
period=499.0;
break;
case 3:
period=333.0;
break;
case 4:
period=250.0;
break;
case 5:
period=199.0;
break;
case 6:
period=166.0;
break;
case 7:
period=141.0;
break;
case 8:
period=124.0;
break;
case 9:
period=110.0;
break;
case 10:
period=99.0;
break;
default:
break;
}
// switch((int)period)
// {
// case 999:
// f=1;
// break;
// case 499:
// f=2;
// break;
// case 333:
// f=3;
// break;
// case 250:
// f=4;
// break;
// case 199:
// f=5;
// break;
// case 166:
// f=6;
// break;
// case 141:
// f=7;
// break;
// case 124:
// f=8;
// break;
// case 110:
// f=9;
// break;
// case 99:
// f=10;
// break;
//
// default:
// break;
// }
CCR2_Val=(ADC_VALUE/3.3)*(period+1);
}
void PA9_Display(void)//PA9输出
{
temp1=CCR2_Val/(period+1);
pulse1=temp1*100;
TIM1_Configuration(period,temp1*1000);
TIM1_cmd();
sprintf((char*)string, "%s%.0f%% ","Signal:PA9:",pulse1);
LCD_DisplayStringLine(Line5, (unsigned char *)string);
}
void PB14_Display(void)//PB14输出
{
temp2=1.0-CCR2_Val/(period+1);
pulse2=temp2*100;
sprintf((char*)string, "%s%.0f%% ","Signal:PB14:",pulse2);
LCD_DisplayStringLine(Line6, (unsigned char *)string);
}
void Period_Display(void)//频率变换显示
{
TIM1_Configuration(period,CCR2_Val);
TIM1_cmd();
sprintf((char*)string, "%s%dKHz "," ",f);
LCD_DisplayStringLine(Line7, (unsigned char *)string);
}
void LED_RUN(u16 run)
{
GPIO_SetBits(GPIOC,run);
GPIO_SetBits(GPIOD,GPIO_Pin_2);
GPIO_ResetBits(GPIOD,GPIO_Pin_2);
}
void TIM1_cmd(void)
{
TIM_Cmd(TIM1,ENABLE);
TIM_CtrlPWMOutputs(TIM1, ENABLE);
}
void TIM1_dcmd(void)
{
TIM_CtrlPWMOutputs(TIM1, DISABLE);
TIM_Cmd(TIM1,DISABLE);
}
void KEY_Scan(void)
{
if(RB1==0) //切换状态
{
Delay_Ms(10);
if(RB1==0)
{
if(shezhi==0)
{
if(open==0)
{
open=1;
LCD_DisplayStringLine(Line4,(unsigned char*)" Status: OFF ");
status=0;
run = run |0x0100;
LED_RUN(run);
TIM1_dcmd();
}
else if(open==1)
{
open=0;
LCD_DisplayStringLine(Line4,(unsigned char*)" Status: ON ");
status=1;
run = run & 0xfeff;
LED_RUN(run);
TIM1_cmd();
}
}
}
while(!RB1);
}
if(RB2==0) //进入设置页面
{
Delay_Ms(10);
if(RB2==0)
{
if(shezhi==0)
{
shezhi=1;
LCD_SetBackColor(Blue);
LCD_SetTextColor(White);
LCD_DisplayStringLine(Line0,(unsigned char*)" ");
LCD_DisplayStringLine(Line1,(unsigned char*)" ");
LCD_DisplayStringLine(Line2,(unsigned char*)" ");
LCD_DisplayStringLine(Line3, (unsigned char*)" Para Setup ");
LCD_DisplayStringLine(Line4,(unsigned char*)" ");
sprintf((char*)string, " %s%dKHz ","Frq: ",f);
LCD_DisplayStringLine(Line5, (unsigned char *)string);
LCD_DisplayStringLine(Line6, (unsigned char *)" ");
LCD_DisplayStringLine(Line7, (unsigned char *)" ");
LCD_DisplayStringLine(Line9,(unsigned char*)" 2");
}
else if(shezhi==1)
{
shezhi=0;
LCD_SetBackColor(Blue);
LCD_SetTextColor(White);
LCD_DisplayStringLine(Line0,(unsigned char*)" ");
LCD_DisplayStringLine(Line1,(unsigned char*)" Paras Interface ");
LCD_DisplayStringLine(Line2,(unsigned char*)" ");
sprintf((char*)string,"%s%.2fV "," Votage:",ADC_VALUE);
LCD_DisplayStringLine(Line3,string);
PA9_Display();
PB14_Display();
Period_Display();
LCD_DisplayStringLine(Line8,(unsigned char*)" ");
LCD_DisplayStringLine(Line9,(unsigned char*)" 1");
if(status==1)
{
LCD_DisplayStringLine(Line4,(unsigned char*)" Status: ON ");
}
else if(status==0)
{
LCD_DisplayStringLine(Line4,(unsigned char*)" Status: OFF ");
}
}
}
while(!RB2);
}
if(RB3==0) //调整频率并保存设置
{
Delay_Ms(10);
if(RB3==0)
{
if(shezhi==1)
{
if(f<10)
{
f=f+1;
sprintf((char*)string, " %s%dKHz ","Frq: ",f);
LCD_DisplayStringLine(Line5, (unsigned char *)string);
IIC_Write(0x11,f);
Delay_Ms(10);
}
else
{
sprintf((char*)string, " %s%dKHz ","Frq: ",f);
LCD_DisplayStringLine(Line5, (unsigned char *)string);
IIC_Write(0x11,f);
Delay_Ms(10);
}
}
}
while(!RB3);
}
if(RB4==0)
{
Delay_Ms(10);
if(RB4==0)
{
}
while(!RB4);
}
}
void LCD_Init(void)
{
STM3210B_LCD_Init();
LCD_Clear(Blue);
LCD_SetBackColor(Blue);
LCD_SetTextColor(White);
LCD_DisplayStringLine(Line0,(unsigned char*)" ");
LCD_DisplayStringLine(Line1,(unsigned char*)" Paras Interface ");
LCD_DisplayStringLine(Line2,(unsigned char*)" ");
LCD_DisplayStringLine(Line3,(unsigned char*)" Votage: ");
LCD_DisplayStringLine(Line4,(unsigned char*)" Status: ON ");
LCD_DisplayStringLine(Line5,(unsigned char*)" Signal:PA9: ");
LCD_DisplayStringLine(Line6,(unsigned char*)" PB14: ");
LCD_DisplayStringLine(Line7,(unsigned char*)" 1KHz ");
LCD_DisplayStringLine(Line8,(unsigned char*)" ");
LCD_DisplayStringLine(Line9,(unsigned char*)" 1");
}
void Delay_Ms(u32 nTime)
{
TimingDelay = nTime;
while(TimingDelay != 0);
}
void TIM1_Configuration(uint16_t period,uint16_t CCR2_Val)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_BDTRInitTypeDef TIM_BDTRInitStructure;
/******PWM电平跳变值**********/
// uint16_t CCR2_Val=500;
/******第一部分 时基初始化**********/
TIM_DeInit(TIM1); //重设为缺省值
/*TIM1时钟配置*/
TIM_TimeBaseStructure.TIM_Period = period;//装载值
TIM_TimeBaseStructure.TIM_Prescaler = 71; //预分频(时钟分频)
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置了时钟分割 不懂得不管
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; //周期计数器值 不懂得不管
TIM_TimeBaseInit(TIM1,&TIM_TimeBaseStructure); //初始化TIMx的时间基数单位
/******第二部分 输出模式初始化**********/
/* Channel 1 Configuration in PWM mode 通道一的PWM */
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //PWM模式2
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //正向通道有效 PA8
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable; //反向通道也有效 PB13
/******第三部分 装载跳变值**********/
TIM_OCInitStructure.TIM_Pulse = CCR2_Val; //占空时间 CCR2_Val
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable; //使能该通道输出
//下面几个参数是高级定时器才会用到,通用定时器不用配置
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High; //互补端的极性
TIM_OCInitStructure.TIM_OutputNState=TIM_OutputNState_Enable;//使能互补端输出
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset; //空闲状态下的非工作状态 不管
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset; //先不管
TIM_OC2Init(TIM1,&TIM_OCInitStructure); //数初始化外设TIMx通道1这里2.0库为TIM_OCInit
TIM_OC2PreloadConfig(TIM1,TIM_OCPreload_Enable);//使能预装载寄存器
/******死区和刹车功能配置,高级定时器才有的,通用定时器不用配置******/
TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Disable;//运行模式下输出选择
TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Disable;//空闲模式下输出选择
TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_OFF; //锁定设置
TIM_BDTRInitStructure.TIM_DeadTime = 50; //死区时间设置
TIM_BDTRInitStructure.TIM_Break = TIM_Break_Enable; //刹车功能使能
TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_Low;//刹车输入极性
TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Enable;//自动输出使能
TIM_BDTRConfig(TIM1,&TIM_BDTRInitStructure);
TIM_ARRPreloadConfig(TIM1,ENABLE); //使能重装载寄存器
/* TIM1 counter enable开定时器 */
// TIM_Cmd(TIM1,ENABLE);
/* TIM1 Main Output Enable 使能TIM1外设的主输出*/
// TIM_CtrlPWMOutputs(TIM1, ENABLE); //pwm输出使能,一定要记得打开
/*TIM_OC1PreloadConfig(),TIM_ARRPreloadConfig();这两个函数控制的是ccr1和arr的预装载使能,
使能和失能的区别就是:使能的时候这两个寄存器的读写需要等待有更新事件发生时才能被改变
(比如计数溢出就是更新时间)。
失能的时候可以直接进行读写而没有延迟。
另外在运行当中想要改变pwm的频率和占空比调用:TIM_SetAutoreload()
TIM_SetCompare1()这两个函数就可以了。*/
}
| 2.546875 | 3 |
2024-11-18T18:56:43.791011+00:00 | 2019-01-05T12:42:27 | f477bbfa07c8defec4c60813a9f108ebea3bbc83 | {
"blob_id": "f477bbfa07c8defec4c60813a9f108ebea3bbc83",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-05T12:42:27",
"content_id": "05aab09dc13a82231d46f78ee739a77e697e5844",
"detected_licenses": [
"MIT"
],
"directory_id": "6c698f413d5231a108c117c42d5b5e3fd4b72eb0",
"extension": "c",
"filename": "clone_test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 164213110,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 614,
"license": "MIT",
"license_type": "permissive",
"path": "/test/clone_test.c",
"provenance": "stackv2-0004.json.gz:26283",
"repo_name": "jamesljlster/CSV_DataProc",
"revision_date": "2019-01-05T12:42:27",
"revision_id": "d0baed1c5647644abd1c3f7a21acec20f23ea274",
"snapshot_id": "3ebba297bedc64c1aa035a651df3120293b7f484",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jamesljlster/CSV_DataProc/d0baed1c5647644abd1c3f7a21acec20f23ea274/test/clone_test.c",
"visit_date": "2020-04-14T23:43:05.365438"
} | stackv2 | #include <stdio.h>
#include <csv_dataproc.h>
int main(int argc, char* argv[])
{
int iResult;
csv_t csv;
csv_t clone;
if(argc < 2)
{
printf("Assign a csv file to run a program\n");
return -1;
}
iResult = csv_read(&csv, argv[1]);
if(iResult != CSV_NO_ERROR)
{
printf("csv_read() failed with error: %d\n", iResult);
return -1;
}
iResult = csv_clone(&clone, csv);
if(iResult != CSV_NO_ERROR)
{
printf("csv_clone() failed with error: %d\n", iResult);
return -1;
}
printf("Original CSV:\n");
csv_print(csv);
printf("Clone CSV:\n");
csv_print(clone);
csv_delete(csv);
return 0;
}
| 2.734375 | 3 |
2024-11-18T18:56:48.433397+00:00 | 2019-01-05T22:46:08 | c4f8e5b4603567bcd45ff48593b4b06c4d5f549c | {
"blob_id": "c4f8e5b4603567bcd45ff48593b4b06c4d5f549c",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-05T22:46:08",
"content_id": "fd5f3da67514353c5529a52e3e5e25c3d1fedcc4",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "ef55d0e2d4797533783573377b4ae75d48313928",
"extension": "c",
"filename": "fo-property-character.c",
"fork_events_count": 9,
"gha_created_at": "2012-10-24T19:42:14",
"gha_event_created_at": "2021-10-21T20:54:59",
"gha_language": "C",
"gha_license_id": null,
"github_id": 6376377,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6215,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/xmlroff/libfo/property/fo-property-character.c",
"provenance": "stackv2-0004.json.gz:26923",
"repo_name": "xmlroff/xmlroff",
"revision_date": "2019-01-05T22:46:08",
"revision_id": "0e407a385a5fc63c1faf1f0ac62e4468491543d7",
"snapshot_id": "fefab307345ddd8ffcb3872c256969e4dd88936a",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/xmlroff/xmlroff/0e407a385a5fc63c1faf1f0ac62e4468491543d7/xmlroff/libfo/property/fo-property-character.c",
"visit_date": "2021-10-25T17:15:52.256578"
} | stackv2 | /* Fo
* fo-property-character.c: 'character' property
*
* Copyright (C) 2001 Sun Microsystems
* Copyright (C) 2007 Menteith Consulting Ltd
*
* See COPYING for the status of this software.
*/
#include <string.h>
#include "fo-utils.h"
#include "fo-context.h"
#include "datatype/fo-datatype.h"
#include "property/fo-property-private.h"
#include "property/fo-property-font-size.h"
#include "property/fo-property-character.h"
#include "property/fo-property-util.h"
/* character */
/* Inherited: FALSE */
/* Shorthand: FALSE */
/* <character> */
/* Initial value: N/A, value is required */
struct _FoPropertyCharacter
{
FoProperty parent_instance;
};
struct _FoPropertyCharacterClass
{
FoPropertyClass parent_class;
};
static void fo_property_character_init (FoPropertyCharacter *property_character);
static void fo_property_character_class_init (FoPropertyCharacterClass *klass);
static void fo_property_character_finalize (GObject *object);
static FoDatatype* fo_property_character_validate (FoDatatype *datatype,
FoContext *context,
GError **error);
static const gchar class_name[] = "character";
static gpointer parent_class;
/**
* fo_property_character_get_type:
*
* Register the #FoPropertyCharacter type if not already registered and
* return its #GType value.
*
* Return value: #GType of #FoPropertyCharacter.
**/
GType
fo_property_character_get_type (void)
{
static GType object_type = 0;
if (!object_type)
{
static const GTypeInfo object_info =
{
sizeof (FoPropertyCharacterClass),
NULL, /* base_init */
NULL, /* base_finalize */
(GClassInitFunc) fo_property_character_class_init,
NULL, /* class_finalize */
NULL, /* class_data */
sizeof (FoPropertyCharacter),
0, /* n_preallocs */
(GInstanceInitFunc) fo_property_character_init,
NULL /* value_table */
};
object_type = g_type_register_static (FO_TYPE_PROPERTY,
class_name,
&object_info, 0);
}
return object_type;
}
/**
* fo_property_character_init:
* @character: #FoPropertyCharacter object to initialise.
*
* Implements #GInstanceInitFunc for #FoPropertyCharacter.
**/
void
fo_property_character_init (FoPropertyCharacter *character)
{
FO_PROPERTY (character)->value =
NULL;
}
/**
* fo_property_character_class_init:
* @klass: #FoPropertyCharacterClass object to initialise.
*
* Implements #GClassInitFunc for #FoPropertyCharacterClass.
**/
void
fo_property_character_class_init (FoPropertyCharacterClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
FoPropertyClass *property_class = FO_PROPERTY_CLASS (klass);
parent_class = g_type_class_peek_parent (klass);
object_class->finalize = fo_property_character_finalize;
property_class->is_inherited = FALSE;
property_class->is_shorthand = FALSE;
property_class->resolve_enum =
fo_property_util_resolve_no_enum;
property_class->validate =
fo_property_character_validate;
property_class->get_initial =
fo_property_character_get_initial;
}
/**
* fo_property_character_finalize:
* @object: #FoPropertyCharacter object to finalize.
*
* Implements #GObjectFinalizeFunc for #FoPropertyCharacter.
**/
void
fo_property_character_finalize (GObject *object)
{
FoPropertyCharacter *character;
character = FO_PROPERTY_CHARACTER (object);
G_OBJECT_CLASS (parent_class)->finalize (object);
}
/**
* fo_property_character_new:
*
* Creates a new #FoPropertyCharacter initialized to default value.
*
* Return value: the new #FoPropertyCharacter.
**/
FoProperty*
fo_property_character_new (void)
{
FoProperty* character;
character =
FO_PROPERTY (g_object_new (fo_property_character_get_type (),
NULL));
return character;
}
/**
* fo_property_character_validate:
* @datatype: #FoDatatype to be validated against allowed datatypes and
* values for current property.
* @context: #FoContext object from which to possibly inherit values.
* @error: Information about any error that has occurred.
*
* Validates @datatype against allowed values. Returns @datatype, a
* replacement datatype value, or NULL if validation failed.
*
* Return value: Valid datatype value or NULL.
**/
FoDatatype*
fo_property_character_validate (FoDatatype *datatype,
FoContext *context,
GError **error)
{
FoDatatype *new_datatype;
g_return_val_if_fail (datatype != NULL, NULL);
g_return_val_if_fail (FO_IS_DATATYPE (datatype), NULL);
g_return_val_if_fail (context != NULL, NULL);
g_return_val_if_fail (FO_IS_CONTEXT (context), NULL);
g_return_val_if_fail (error == NULL || *error == NULL, NULL);
if (FO_IS_CHAR (datatype))
{
return datatype;
}
else if (FO_IS_NAME (datatype))
{
new_datatype = fo_char_new_with_value (fo_name_get_value (datatype));
g_object_unref (datatype);
return (new_datatype);
}
else if (FO_IS_STRING (datatype))
{
new_datatype = fo_char_new_with_value (fo_string_get_value (datatype));
g_object_unref (datatype);
return (new_datatype);
}
else
{
gchar *datatype_sprintf = fo_object_sprintf (datatype);
g_set_error (error,
FO_FO_ERROR,
FO_FO_ERROR_DATATYPE,
_(fo_fo_error_messages[FO_FO_ERROR_DATATYPE]),
class_name,
datatype_sprintf,
g_type_name (G_TYPE_FROM_INSTANCE (datatype)));
g_object_unref (datatype);
g_free (datatype_sprintf);
return NULL;
}
}
/**
* fo_property_character_get_initial:
*
* Get an instance of the property with the correct initial value.
*
* Return value: An instance of the property.
**/
FoProperty*
fo_property_character_get_initial (void)
{
static FoProperty *character = NULL;
if (character == NULL)
{
character =
fo_property_character_new ();
}
return character;
}
| 2.046875 | 2 |
2024-11-18T18:56:48.919667+00:00 | 2019-07-18T02:47:19 | 48278c5b3cfce125908f6e7f66310e0af0e6efd0 | {
"blob_id": "48278c5b3cfce125908f6e7f66310e0af0e6efd0",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-18T02:47:39",
"content_id": "ebf0901dd341686f0a6a85501761f28998e3eed9",
"detected_licenses": [
"Unlicense"
],
"directory_id": "ea2bfabfd7f97dc64c4ef6dd9d9d27f3c271bdab",
"extension": "c",
"filename": "test_convert_from_trace.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 16342224,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2884,
"license": "Unlicense",
"license_type": "permissive",
"path": "/flint/nmod_poly_extra/test/test_convert_from_trace.c",
"provenance": "stackv2-0004.json.gz:27308",
"repo_name": "defeo/ff_compositum",
"revision_date": "2019-07-18T02:47:19",
"revision_id": "6c30bdb5f1979843585d469b82833639e438a2cb",
"snapshot_id": "b995e7d245c6c22084a1a29646643222403e8535",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/defeo/ff_compositum/6c30bdb5f1979843585d469b82833639e438a2cb/flint/nmod_poly_extra/test/test_convert_from_trace.c",
"visit_date": "2020-12-09T20:27:10.783551"
} | stackv2 | #include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <flint/nmod_poly.h>
#include "util.h"
#include "sage_output.h"
#include "nmod_poly_extra.h"
/*------------------------------------------------------------*/
/* if opt = 1, runs a check */
/* else, runs timings */
/*------------------------------------------------------------*/
void check(int opt){
long i;
flint_rand_t state;
flint_randinit(state);
mp_limb_t n = 65537;
for (i = 1; i < 17; i+=1){
nmod_poly_t P;
nmod_poly_init(P, n);
nmod_poly_rand_dense_monic(P, state, i);
nmod_poly_t S;
nmod_poly_init(S, n);
nmod_poly_inverse_reverse_main(S, P);
nmod_poly_t iP, dP;
nmod_poly_init(iP, n);
nmod_poly_init(dP, n);
nmod_poly_derivative(dP, P);
nmod_poly_invmod(iP, dP, P);
nmod_poly_clear(dP);
mp_ptr trace_vec;
trace_vec = _nmod_vec_init(i);
nmod_poly_to_newton_sums(trace_vec, P, i);
nmod_poly_t A;
nmod_poly_init(A, n);
nmod_poly_rand_dense(A, state, i);
mp_ptr A_trace;
A_trace = _nmod_vec_init(i);
nmod_poly_tmulmod(A_trace, trace_vec, A, P, S);
nmod_poly_t A2;
nmod_poly_init(A2, n);
if (opt == 1){
nmod_poly_convert_from_trace(A2, A_trace, P, iP);
sage_output_init(P->mod);
sage_output_assign_vec(A_trace, i, "Atrace");
sage_output_assign_poly(P, "P");
sage_output_assign_poly(A, "A");
sage_output_assign_poly(A2, "A2");
printf("A == A2\n");
}
else{
double t, u;
long j;
t = util_gettime();
for (j = 0; j < 10000; j++)
nmod_poly_convert_from_trace(A2, A_trace, P, iP);
t = util_gettime() - t;
nmod_poly_t tmp1, tmp2, tmp3;
nmod_poly_init(tmp1, n);
nmod_poly_init(tmp2, n);
nmod_poly_init(tmp3, n);
nmod_poly_rand_dense(tmp1, state, i);
nmod_poly_rand_dense(tmp2, state, i);
u = util_gettime();
for (j = 0; j < 10000; j++)
nmod_poly_mul(tmp3, tmp1, tmp2);
u = util_gettime() - u;
nmod_poly_clear(tmp1);
nmod_poly_clear(tmp2);
nmod_poly_clear(tmp3);
printf("%lu %f %f\n", i, t, u);
}
nmod_poly_clear(P);
nmod_poly_clear(iP);
nmod_poly_clear(S);
nmod_poly_clear(A);
nmod_poly_clear(A2);
_nmod_vec_clear(trace_vec);
_nmod_vec_clear(A_trace);
}
flint_randclear(state);
}
/*------------------------------------------------------------*/
/* main just calls check() */
/* if not argument is given, runs timings */
/* if the argument 1 is given, runs check */
/*------------------------------------------------------------*/
int main(int argc, char **argv){
int opt = 0;
if (argc > 1)
opt = atoi(argv[1]);
check(opt);
return 0;
}
| 2.359375 | 2 |
2024-11-18T18:56:49.443897+00:00 | 2018-08-20T22:13:29 | 097ef690957107168d131f646e07877ccbd44415 | {
"blob_id": "097ef690957107168d131f646e07877ccbd44415",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-20T22:13:29",
"content_id": "a3608063602ba89924de2f9f6d8812ba64df7464",
"detected_licenses": [
"MIT"
],
"directory_id": "516ab413666082045660623f1664dba9c9727fca",
"extension": "h",
"filename": "debug.h",
"fork_events_count": 0,
"gha_created_at": "2018-08-20T21:26:46",
"gha_event_created_at": "2018-08-20T21:26:46",
"gha_language": null,
"gha_license_id": null,
"github_id": 145472185,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 502,
"license": "MIT",
"license_type": "permissive",
"path": "/src/debug.h",
"provenance": "stackv2-0004.json.gz:27565",
"repo_name": "jakeajames/noncereboot11",
"revision_date": "2018-08-20T22:13:29",
"revision_id": "7ac862124169bb78f1d743c13567541a3e244546",
"snapshot_id": "fd6ad9751f02db514ba98eed0694a84a50ee266e",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/jakeajames/noncereboot11/7ac862124169bb78f1d743c13567541a3e244546/src/debug.h",
"visit_date": "2020-03-26T22:35:59.762741"
} | stackv2 | #include <stdio.h>
#pragma once
enum verboselevel {
lvlNONE,
lvlERROR,
lvlINFO,
lvlDEBUG,
};
extern int loglevel;
#define RAWLOG(fmt, args...)\
fprintf(stderr, fmt, ##args);
#define INFO(fmt, args...)\
if (loglevel >= lvlINFO) { \
RAWLOG("[INF]" fmt "\n", ##args);\
}
#define DEBUG(fmt, args...)\
if (loglevel >= lvlDEBUG) { \
RAWLOG("[DBG] " fmt "\n", ##args);\
}
#define ERROR(fmt, args...)\
if (loglevel >= lvlERROR) { \
RAWLOG("[ERR] " fmt "\n", ##args);\
}
| 2.15625 | 2 |
2024-11-18T18:56:49.596206+00:00 | 2021-10-12T14:59:02 | c13a2acb213cdd56a5bf5567c448f1e10cc6a88a | {
"blob_id": "c13a2acb213cdd56a5bf5567c448f1e10cc6a88a",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-12T14:59:02",
"content_id": "c368637724c0bb67b686e9736748d37ebbaeb6a6",
"detected_licenses": [
"MIT"
],
"directory_id": "af9ecd36a89c6236640fa7333f3aef20cda420f1",
"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": 148581577,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 628,
"license": "MIT",
"license_type": "permissive",
"path": "/dynamic_programming/fibonacci.c",
"provenance": "stackv2-0004.json.gz:27821",
"repo_name": "poyichou/algorithm_note",
"revision_date": "2021-10-12T14:59:02",
"revision_id": "faf3bcecb594fe9e062bb9c177ae8c62c63b19b6",
"snapshot_id": "91970a13c3986fd75e838d84b7ee95a06ce1d113",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/poyichou/algorithm_note/faf3bcecb594fe9e062bb9c177ae8c62c63b19b6/dynamic_programming/fibonacci.c",
"visit_date": "2021-10-14T06:54:28.705915"
} | stackv2 | /*
fibonacci sequence
*/
#include <stdio.h>
#include <stdlib.h>
static int *table;
int fibonacci(int idx) {
if (idx == 0) return 0;
else if (idx == 1) return 1;
else {
if (table[idx - 2] == -1) {
table[idx - 2] = fibonacci(idx - 2);
}
if (table[idx - 1] == -1) {
table[idx - 1] = fibonacci(idx - 1);
}
return table[idx - 1] + table[idx - 2];
}
}
int main() {
int idx;
printf("enter idx of fibonacci:");
scanf("%d", &idx);
table = malloc(sizeof(int) * (idx + 1));
for (int i = 0; i < idx + 1; i++) {
table[i] = -1;
}
printf("fibonacci[%d] is %d\n", idx, fibonacci(idx));
free(table);
return 0;
}
| 3.703125 | 4 |
2024-11-18T18:56:49.833264+00:00 | 2021-03-17T02:56:52 | 34152213c61f1480fa6a28c110714710e7a3709a | {
"blob_id": "34152213c61f1480fa6a28c110714710e7a3709a",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-17T02:56:52",
"content_id": "0cbe2cf3b7cb542e9d1410c567ba30c9b1ff1979",
"detected_licenses": [
"MIT"
],
"directory_id": "91a471cb831df97d200574d5016ad24b0b84a8ca",
"extension": "c",
"filename": "jr_tar.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 336133285,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 27236,
"license": "MIT",
"license_type": "permissive",
"path": "/libjr/io/jr_tar.c",
"provenance": "stackv2-0004.json.gz:28205",
"repo_name": "frankjas/srcjr",
"revision_date": "2021-03-17T02:56:52",
"revision_id": "4c0da568b899f120abfbe6e17c3a8277946c6d09",
"snapshot_id": "fe3a3a4f0d0c70167ed427514851c4e21cafe5c4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/frankjas/srcjr/4c0da568b899f120abfbe6e17c3a8277946c6d09/libjr/io/jr_tar.c",
"visit_date": "2023-03-14T15:43:39.668774"
} | stackv2 | #define _POSIX_SOURCE 1
#include "ezport.h"
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include "jr/malloc.h"
#include "jr/error.h"
#include "jr/tar.h"
#include "jr/syscalls.h"
jr_int jr_TarEntryInitFromRfp (tar_entry_ptr, rfp, error_buf)
jr_TarEntryType * tar_entry_ptr ;
FILE * rfp ;
char * error_buf ;
{
jr_int header_offset;
jr_int data_offset;
jr_int status;
header_offset = ftell (rfp) ;
status = jr_TarEntryInitFromFifoRfp (tar_entry_ptr, rfp, error_buf);
data_offset = ftell(rfp) ;
jr_TarEntrySetHeaderOffset (tar_entry_ptr, header_offset);
jr_TarEntrySetDataOffset (tar_entry_ptr, data_offset);
if (status > 0) {
status = 0;
}
return status;
}
jr_int jr_TarEntryInitFromFifoRfp (tar_entry_ptr, rfp, error_buf)
jr_TarEntryType * tar_entry_ptr ;
FILE * rfp ;
char * error_buf ;
{
jr_int magic_length;
jr_int num_items;
long tmp_value;
jr_int status;
char tmp_buf [16]; /* must hold mtime, size fields */
jr_TarEntryInit (tar_entry_ptr);
num_items = fread (
jr_TarEntryHeaderPtr (tar_entry_ptr),
sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)),
1, rfp
);
if (num_items != 1) {
if (feof (rfp)) {
jr_esprintf (error_buf, "couldn't read: end-of-file");
status = jr_TAR_EOF_ERROR;
}
else {
jr_esprintf (error_buf, "couldn't read: %s", strerror (errno));
status = jr_TAR_INTERNAL_ERROR;
}
goto return_status;
}
if (jr_TAR_BLOCK_SIZE < sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr))) {
jr_esprintf (error_buf, "jr_TAR_BLOCK_SIZE (%d) < sizeof (jr_TarHeaderStruct) (%d)",
jr_TAR_BLOCK_SIZE, (jr_int) sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr))
);
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
if (sizeof (tmp_buf) < jr_TAR_BLOCK_SIZE - sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr))) {
jr_esprintf (error_buf, "couldn't align input: tmp_buf too small, should be at least %d bytes",
jr_TAR_BLOCK_SIZE - (jr_int) sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr))
);
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
num_items = fread (
tmp_buf,
jr_TAR_BLOCK_SIZE - sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)),
1, rfp
);
if (num_items != 1 && !feof (rfp)) {
jr_esprintf (error_buf, "couldn't read: %s", strerror (errno));
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
if ( jr_TarEntryHeaderName (tar_entry_ptr)[0] == 0
&& jr_TarEntryPrefix (tar_entry_ptr)[0] == 0) {
/*
* This is the case which will be encountered
* in the first of the 2 NULL blocks at the end
* of a tar file.
*/
jr_esprintf (error_buf, "couldn't read: null tar block");
status = jr_TAR_EOF_ERROR;
goto return_status;
}
magic_length = strlen (TMAGIC);
if (strncmp (jr_TarEntryHeaderMagic (tar_entry_ptr), TMAGIC, magic_length) != 0) {
if ( jr_TarEntryHeaderMagic (tar_entry_ptr)[magic_length] != 0
&& jr_TarEntryHeaderMagic (tar_entry_ptr)[magic_length] != ' ') {
jr_esprintf (error_buf, "%.128s: bad magic field", jr_TarEntryHeaderName( tar_entry_ptr));
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
switch (jr_TarEntryHeaderTypeFlag (tar_entry_ptr)) {
case LNKTYPE :
case SYMTYPE :
case DIRTYPE :
case BLKTYPE :
case CHRTYPE :
case FIFOTYPE : {
jr_TarEntrySetSizeInt (tar_entry_ptr, 0);
jr_TarEntrySetNumBlocks (tar_entry_ptr, 0);
break ;
}
default :
case REGTYPE :
case AREGTYPE :
case CONTTYPE : {
strncpy (
tmp_buf, jr_TarEntryHeaderSize (tar_entry_ptr),
sizeof (jr_TarEntryHeaderSize (tar_entry_ptr))
);
tmp_buf [sizeof (jr_TarEntryHeaderSize (tar_entry_ptr))] = 0;
num_items = sscanf (tmp_buf, " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'size' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetSizeInt (tar_entry_ptr, tmp_value);
tmp_value = (jr_TarEntrySize (tar_entry_ptr) + (jr_TAR_BLOCK_SIZE-1));
tmp_value /= jr_TAR_BLOCK_SIZE ;
jr_TarEntrySetNumBlocks (tar_entry_ptr, tmp_value);
break ;
}
}
num_items = sscanf (jr_TarEntryHeaderMode (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'mode' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetModeInt (tar_entry_ptr, tmp_value);
num_items = sscanf (jr_TarEntryHeaderUID (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'uid' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetUIDInt (tar_entry_ptr, tmp_value);
num_items = sscanf (jr_TarEntryHeaderGID (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'gid' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetGIDInt (tar_entry_ptr, tmp_value);
strncpy (
tmp_buf, jr_TarEntryHeaderMTime (tar_entry_ptr),
sizeof (jr_TarEntryHeaderMTime (tar_entry_ptr))
);
tmp_buf [sizeof (jr_TarEntryHeaderMTime (tar_entry_ptr))] = 0;
num_items = sscanf (tmp_buf, " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'mtime' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetMTimeInt (tar_entry_ptr, tmp_value);
num_items = sscanf (jr_TarEntryHeaderDevMajor (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
if (jr_TarEntryHeaderDevMajor (tar_entry_ptr) [0] != 0) {
jr_esprintf (error_buf, "couldn't parse 'devmajor' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
else {
jr_TarEntrySetDevMajorInt (tar_entry_ptr, tmp_value);
}
num_items = sscanf (jr_TarEntryHeaderDevMinor (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
if (jr_TarEntryHeaderDevMinor (tar_entry_ptr) [0] != 0) {
jr_esprintf (error_buf, "couldn't parse 'devminor' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
else {
jr_TarEntrySetDevMinorInt (tar_entry_ptr, tmp_value);
}
num_items = sscanf (jr_TarEntryHeaderChkSum (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'chksum' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetChkSumInt (tar_entry_ptr, tmp_value);
status = jr_TAR_BLOCK_SIZE;
return_status : {
if (status != 0) {
jr_TarEntryUndo (tar_entry_ptr);
}
}
return status;
}
jr_int jr_TarEntryReadData (tar_entry_ptr, rfp, opt_data_ref, error_buf)
jr_TarEntryType * tar_entry_ptr ;
FILE * rfp ;
void ** opt_data_ref;
char * error_buf ;
{
struct stat stat_info[1];
void * data_ptr = 0;
jr_int num_items;
jr_int is_fifo_rfp = 0;
jr_int align_bytes = 0;
unsigned jr_int k;
jr_int status;
if (opt_data_ref) {
data_ptr = jr_malloc (jr_TarEntrySize (tar_entry_ptr) + 1) ;
/*
* add 1 since we want to make a string out of it
* added 3/1/94
*/
if (data_ptr == 0) {
jr_esprintf (error_buf, "couldn't allocate %ld bytes for data (header offset %ld)",
(long) jr_TarEntrySize (tar_entry_ptr),
(long) jr_TarEntryHeaderOffset (tar_entry_ptr)
) ;
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
if (jr_TarEntrySize (tar_entry_ptr) > 0) {
if (data_ptr) {
num_items = fread (data_ptr, jr_TarEntrySize (tar_entry_ptr), 1, rfp) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't read %ld bytes for (data header block %ld) : %s",
(long) jr_TarEntrySize (tar_entry_ptr),
(long) jr_TarEntryHeaderOffset (tar_entry_ptr),
strerror(errno)
) ;
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
else {
status = fstat (fileno (rfp), stat_info);
if (status != 0) {
jr_esprintf (error_buf, "couldn't fstat() input: %s",
strerror(errno)
) ;
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
is_fifo_rfp = S_ISFIFO (stat_info->st_mode);
if (is_fifo_rfp) {
for (k=0; k < jr_TarEntrySize (tar_entry_ptr); k++) {
if (getc (rfp) == EOF) {
break;
}
}
}
else {
fseek (rfp, jr_TarEntrySize (tar_entry_ptr), SEEK_CUR) ;
}
}
align_bytes = jr_TarFilePtrAlignFifoRead (rfp, jr_TarEntrySize (tar_entry_ptr));
}
if (opt_data_ref) {
((char *) data_ptr) [jr_TarEntrySize (tar_entry_ptr)] = 0;
*opt_data_ref = data_ptr;
data_ptr = 0;
}
status = jr_TarEntrySize (tar_entry_ptr) + align_bytes;
return_status : {
if (data_ptr) {
jr_free (data_ptr);
}
}
return status;
}
jr_int jr_TarEntryCopyData (tar_entry_ptr, rfp, wfp, error_buf)
jr_TarEntryType * tar_entry_ptr ;
FILE * rfp ;
FILE * wfp ;
char * error_buf ;
{
unsigned jr_int k;
jr_int c;
jr_int align_bytes = 0;
jr_int status;
if (jr_TarEntrySize (tar_entry_ptr) > 0) {
for (k=0; k < jr_TarEntrySize (tar_entry_ptr); k++) {
if ((c = getc (rfp)) == EOF) {
jr_esprintf (error_buf, "unexpected EOF after byte %d", k);
status = jr_TAR_EOF_ERROR;
goto return_status;
}
putc (c, wfp);
}
align_bytes = jr_TarFilePtrAlignFifoWrite (wfp, jr_TarEntrySize (tar_entry_ptr));
align_bytes = jr_TarFilePtrAlignFifoRead (rfp, jr_TarEntrySize (tar_entry_ptr));
}
status = jr_TarEntrySize (tar_entry_ptr) + align_bytes;
return_status : {
}
return status;
}
jr_int jr_TarEntryWriteSegment (
jr_TarEntryType * tar_entry_ptr ,
unsigned jr_int total_data_size,
const void * opt_data_ptr,
FILE * opt_data_rfp,
unsigned jr_int curr_data_size,
FILE * wfp,
char * error_buf)
{
char tmp_buf [16]; /* must hold mtime, size fields */
jr_int num_items;
jr_int status;
/*
* This function writes out the 512 byte tar header
* followed by the data and seeks to the next 512 block boundary
* after the data has been written.
* The tar header data will be adjusted to match the new size
* argument passed in, and a new checksum will be calculated.
*/
switch (jr_TarEntryTypeFlag (tar_entry_ptr)) {
case DIRTYPE :
case LNKTYPE :
case SYMTYPE : {
total_data_size = 0;
break;
}
}
jr_TarEntrySetSize (tar_entry_ptr, total_data_size);
jr_TarEntryMakePosixConformant (tar_entry_ptr);
num_items = fwrite (
jr_TarEntryHeaderPtr (tar_entry_ptr),
sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)),
1, wfp
);
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't write tar header: %s", strerror (errno));
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
if (sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)) > jr_TAR_BLOCK_SIZE) {
jr_esprintf (error_buf, "sizeof (jr_TarHeaderStruct) (%d) > jr_TAR_BLOCK_SIZE (%d)",
(jr_int) sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)), jr_TAR_BLOCK_SIZE
);
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
if (jr_TAR_BLOCK_SIZE - sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)) > sizeof (tmp_buf)) {
jr_esprintf (error_buf, "couldn't align input: tmp_buf too small, should be at least %d bytes",
jr_TAR_BLOCK_SIZE - (jr_int) sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr))
);
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
memset (tmp_buf, 0, sizeof (tmp_buf));
num_items = fwrite (
tmp_buf,
jr_TAR_BLOCK_SIZE - sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)),
1, wfp
);
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't write tar header alignment: %s", strerror (errno));
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
if (curr_data_size > 0) {
if (opt_data_ptr) {
num_items = fwrite (opt_data_ptr, curr_data_size, 1, wfp);
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't write data: %s", strerror (errno));
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
else if (opt_data_rfp) {
/*
* Fill with null if no data or not enough data.
*/
jr_int c = 0;
unsigned jr_int k;
for (k=0; k < curr_data_size; k++) {
if (opt_data_rfp) {
c = getc (opt_data_rfp);
if (c == EOF) {
c = 0;
}
}
putc (c, wfp);
}
}
if (opt_data_ptr || opt_data_rfp) {
if (curr_data_size == total_data_size) {
jr_TarFilePtrAlignFifoWrite (wfp, curr_data_size);
}
}
}
status = 0;
return_status : {
}
return status;
}
void jr_TarEntrySetIsDir (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
jr_TarEntrySetTypeFlag (tar_entry_ptr, DIRTYPE);
}
void jr_TarEntrySetIsFile (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
jr_TarEntrySetTypeFlag (tar_entry_ptr, REGTYPE);
}
void jr_TarEntrySetCustomType (tar_entry_ptr, type_value)
jr_TarEntryType * tar_entry_ptr;
jr_int type_value;
{
jr_TarEntrySetTypeFlag (tar_entry_ptr, type_value);
}
void jr_TarEntrySetIsSymLink (tar_entry_ptr, link_name)
jr_TarEntryType * tar_entry_ptr;
const char * link_name;
{
jr_TarEntrySetTypeFlag (tar_entry_ptr, SYMTYPE);
strncpy (
jr_TarEntryHeaderLinkName (tar_entry_ptr),
link_name,
sizeof (jr_TarEntryHeaderLinkName (tar_entry_ptr)) - 1
);
}
void jr_TarEntrySetUserInfo (tar_entry_ptr, uid, opt_uname, gid, opt_gname)
jr_TarEntryType * tar_entry_ptr;
jr_int uid;
const char * opt_uname;
jr_int gid;
const char * opt_gname;
{
jr_TarEntrySetUID (tar_entry_ptr, uid);
jr_TarEntrySetGID (tar_entry_ptr, gid);
if (opt_uname) {
strncpy (
jr_TarEntryHeaderUName (tar_entry_ptr),
opt_uname,
sizeof (jr_TarEntryHeaderUName (tar_entry_ptr)) - 1
);
}
if (opt_gname) {
strncpy (
jr_TarEntryHeaderGName (tar_entry_ptr),
opt_gname,
sizeof (jr_TarEntryHeaderGName (tar_entry_ptr)) - 1
);
}
}
void jr_TarEntrySetPathInfo (tar_entry_ptr, pathname, is_dir, mode, mtime)
jr_TarEntryType * tar_entry_ptr ;
const char * pathname ;
jr_int is_dir;
jr_int mode;
jr_int mtime;
{
jr_int pathname_length = strlen (pathname);
jr_int tar_pathname_length = pathname_length;
jr_int has_trailing_slash = 0;
if (is_dir && pathname_length > 0) {
if (pathname [pathname_length - 1] != '/') {
has_trailing_slash = 0;
tar_pathname_length ++;
}
}
if ( tar_pathname_length
> (jr_int) (sizeof(jr_TarEntryHeaderName (tar_entry_ptr))
+ sizeof(jr_TarEntryHeaderPrefix (tar_entry_ptr)))) {
/*
* Path name too long. Is caller's responsibility to check.
*/
return;
}
if (is_dir) {
jr_TarEntrySetIsDir (tar_entry_ptr);
}
else {
jr_TarEntrySetIsFile (tar_entry_ptr);
}
jr_TarEntrySetMode (tar_entry_ptr, mode);
jr_TarEntrySetMTime (tar_entry_ptr, mtime);
if (tar_pathname_length > (jr_int) sizeof(jr_TarEntryHeaderName (tar_entry_ptr))) {
const char * cp ;
jr_int prefix_length = tar_pathname_length;
for (cp = pathname + pathname_length; cp >= pathname; cp--) {
if (*cp == '/') {
prefix_length = cp - pathname + 1;
if (prefix_length <= (jr_int) sizeof(jr_TarEntryHeaderPrefix (tar_entry_ptr))) {
break ;
}
}
}
if ( (*cp == '/') && (cp != pathname)
&& tar_pathname_length - prefix_length
<= (jr_int) sizeof (jr_TarEntryHeaderName (tar_entry_ptr))) {
strncpy (
jr_TarEntryHeaderPrefix (tar_entry_ptr),
pathname,
prefix_length
);
if (prefix_length < (jr_int) sizeof(jr_TarEntryHeaderPrefix (tar_entry_ptr))) {
/*
** 9/11/06: if it has no null, use trailing '/' instead, otherwise no null?
** 12/31/06: use "null required if null fits" rule?
** ToDo: verify with standard.
*/
jr_TarEntryHeaderPrefix (tar_entry_ptr)[prefix_length] = 0;
}
strncpy (
jr_TarEntryHeaderName (tar_entry_ptr),
cp + 1,
sizeof (jr_TarEntryHeaderName (tar_entry_ptr))
);
if (is_dir && !has_trailing_slash) {
jr_TarEntryHeaderName (tar_entry_ptr)[pathname_length - prefix_length] = '/';
}
/*
* Use tar_pathname_length since we've added the trailing slash if it's a dir.
*/
if ( tar_pathname_length - prefix_length
< (jr_int) sizeof(jr_TarEntryHeaderName (tar_entry_ptr))) {
jr_TarEntryHeaderName (tar_entry_ptr)[tar_pathname_length - prefix_length] = 0;
/*
* Null required if the null fits.
*/
}
}
else {
/*
* Path name too long. Is caller's responsibility to check.
*/
jr_TarEntryHeaderName (tar_entry_ptr)[0] = 0;
}
}
else {
strncpy (
jr_TarEntryHeaderName (tar_entry_ptr),
pathname,
sizeof (jr_TarEntryHeaderName (tar_entry_ptr))
);
memset (
jr_TarEntryHeaderPrefix (tar_entry_ptr),
0,
sizeof (jr_TarEntryHeaderPrefix (tar_entry_ptr))
);
if (is_dir && !has_trailing_slash) {
jr_TarEntryHeaderName (tar_entry_ptr)[pathname_length] = '/';
}
/*
* Use tar_pathname_length since we've added the trailing slash if it's a dir.
*/
if (tar_pathname_length < (jr_int) sizeof(jr_TarEntryHeaderName (tar_entry_ptr))) {
jr_TarEntryHeaderName (tar_entry_ptr)[tar_pathname_length] = 0;
}
}
}
void jr_TarEntryInit (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
memset (tar_entry_ptr, 0, sizeof (*tar_entry_ptr));
}
void jr_TarEntryUndo (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
}
void jr_TarEntrySetMode (tar_entry_ptr, mode_int)
jr_TarEntryType * tar_entry_ptr;
jr_int mode_int;
{
if (mode_int < 0) {
mode_int = 0;
}
jr_TarEntrySetModeInt (tar_entry_ptr, mode_int);
if ((unsigned) mode_int < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderMode (tar_entry_ptr) ,"%07o", (unsigned) mode_int) ;
}
}
void jr_TarEntrySetUID (tar_entry_ptr, uid_int)
jr_TarEntryType * tar_entry_ptr;
jr_int uid_int;
{
if (uid_int < 0) {
uid_int = jr_USHRT_MAX; /* 1/5/07: Unix id for "nobody"? */
}
jr_TarEntrySetUIDInt (tar_entry_ptr, uid_int);
if ((unsigned) uid_int < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderUID (tar_entry_ptr) ,"%07o", (unsigned) uid_int) ;
}
}
void jr_TarEntrySetGID (tar_entry_ptr, gid_int)
jr_TarEntryType * tar_entry_ptr;
jr_int gid_int;
{
if (gid_int < 0) {
gid_int = jr_USHRT_MAX; /* 1/5/07: Unix id for "nobody"? */
}
jr_TarEntrySetGIDInt (tar_entry_ptr, gid_int);
if ((unsigned) gid_int < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderGID (tar_entry_ptr) ,"%07o", (unsigned) gid_int) ;
}
}
void jr_TarEntrySetSize (tar_entry_ptr, size_int)
jr_TarEntryType * tar_entry_ptr;
unsigned jr_int size_int;
{
jr_TarEntrySetSizeInt (tar_entry_ptr, size_int);
if (size_int < jr_TAR_MAX_12_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderSize (tar_entry_ptr) ,"%011o", size_int) ;
}
else {
sprintf (jr_TarEntryHeaderSize (tar_entry_ptr) ,"%011o", jr_TAR_MAX_12_BYTE_ASCII_OCTAL) ;
}
}
void jr_TarEntrySetMTime (tar_entry_ptr, mtime_int)
jr_TarEntryType * tar_entry_ptr;
jr_int mtime_int;
{
if (mtime_int < 0) {
mtime_int = 0;
}
jr_TarEntrySetMTimeInt (tar_entry_ptr, mtime_int);
if ((unsigned) mtime_int < jr_TAR_MAX_12_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderMTime (tar_entry_ptr) ,"%011o", (unsigned) mtime_int) ;
}
}
void jr_TarEntrySetDevMajor (tar_entry_ptr, dev_major)
jr_TarEntryType * tar_entry_ptr;
jr_int dev_major;
{
if (dev_major < 0) {
dev_major = 0;
}
jr_TarEntrySetDevMajorInt (tar_entry_ptr, dev_major);
if ((unsigned) dev_major < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderDevMajor (tar_entry_ptr) ,"%07o", (unsigned) dev_major) ;
}
}
void jr_TarEntrySetDevMinor (tar_entry_ptr, dev_minor)
jr_TarEntryType * tar_entry_ptr;
jr_int dev_minor;
{
if (dev_minor < 0) {
dev_minor = 0;
}
jr_TarEntrySetDevMinorInt (tar_entry_ptr, dev_minor);
if ((unsigned) dev_minor < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderDevMinor (tar_entry_ptr) ,"%07o", (unsigned) dev_minor) ;
}
}
void jr_TarEntrySetMagic (tar_entry_ptr, magic_string)
jr_TarEntryType * tar_entry_ptr;
const char * magic_string;
{
sprintf (jr_TarEntryHeaderMagic (tar_entry_ptr), "%.*s",
(jr_int) sizeof(jr_TarEntryHeaderMagic (tar_entry_ptr))-1,
TMAGIC
) ;
}
void jr_TarEntrySetVersion (tar_entry_ptr, magic_string)
jr_TarEntryType * tar_entry_ptr;
const char * magic_string;
{
jr_TarHeaderStruct * tar_header_ptr = jr_TarEntryHeaderPtr (tar_entry_ptr);
tar_header_ptr->version [0] = '0';
tar_header_ptr->version [1] = '0';
/*
* No null in this field.
*/
}
static unsigned long SumByteString(string, nbytes)
unsigned char * string ;
jr_int nbytes ;
{
unsigned long sum = 0L;
jr_int i;
for (i=0; i < nbytes; i++) {
sum += string[i] ;
}
return(sum) ;
}
void jr_TarEntryInitCheckSum (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
jr_TarHeaderStruct * thp = jr_TarEntryHeaderPtr (tar_entry_ptr);
jr_int chksum_val = 0;
chksum_val += SumByteString (jr_TarHeaderName (thp), sizeof(jr_TarHeaderName (thp))) ;
chksum_val += SumByteString (jr_TarHeaderMode (thp), sizeof(jr_TarHeaderMode (thp))) ;
chksum_val += SumByteString (jr_TarHeaderUID (thp), sizeof(jr_TarHeaderUID (thp))) ;
chksum_val += SumByteString (jr_TarHeaderGID (thp), sizeof(jr_TarHeaderGID (thp))) ;
chksum_val += SumByteString (jr_TarHeaderSize (thp), sizeof(jr_TarHeaderSize (thp))) ;
chksum_val += SumByteString (jr_TarHeaderMTime (thp), sizeof(jr_TarHeaderMTime (thp))) ;
chksum_val += SumByteString (" ", sizeof(jr_TarHeaderChkSum (thp))) ;
chksum_val += SumByteString (&jr_TarHeaderTypeFlag (thp), sizeof(thp->typeflag)) ;
chksum_val += SumByteString (jr_TarHeaderLinkName (thp), sizeof(jr_TarHeaderLinkName (thp))) ;
chksum_val += SumByteString (jr_TarHeaderMagic (thp), sizeof(jr_TarHeaderMagic (thp))) ;
chksum_val += SumByteString (jr_TarHeaderVersion (thp), sizeof(jr_TarHeaderVersion (thp))) ;
chksum_val += SumByteString (jr_TarHeaderUName (thp), sizeof(jr_TarHeaderUName (thp))) ;
chksum_val += SumByteString (jr_TarHeaderGName (thp), sizeof(jr_TarHeaderGName (thp))) ;
chksum_val += SumByteString (jr_TarHeaderDevMajor (thp), sizeof(jr_TarHeaderDevMajor (thp))) ;
chksum_val += SumByteString (jr_TarHeaderDevMinor (thp), sizeof(jr_TarHeaderDevMinor (thp))) ;
chksum_val += SumByteString (jr_TarHeaderPrefix (thp), sizeof(jr_TarHeaderPrefix (thp))) ;
jr_TarEntrySetChkSumInt (tar_entry_ptr, chksum_val);
if ((unsigned) chksum_val < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf(jr_TarHeaderChkSum (thp), "%07o", (unsigned) chksum_val) ;
}
else {
/*
* max. check sum : 512 * 256 == 131072 < 2079151 == MAX_7_BYTE_ASCII_OCTAL
*/
}
}
void jr_TarEntryMakePosixConformant (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
jr_TarEntrySetMagic (tar_entry_ptr, TMAGIC);
jr_TarEntrySetVersion (tar_entry_ptr, TVERSION);
jr_TarEntryInitCheckSum (tar_entry_ptr);
}
const char *jr_TarEntryMakeFullPath (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
jr_int prefix_length = strlen (jr_TarEntryPrefix (tar_entry_ptr));
jr_int name_length = strlen (jr_TarEntryName (tar_entry_ptr));
jr_int path_length = prefix_length + 1 + name_length;
char * path_string;
path_string = jr_malloc (path_length + 1);
if (jr_TarEntryPrefix (tar_entry_ptr)[0]) {
if (jr_TarEntryPrefix(tar_entry_ptr)[prefix_length - 1] == '/') {
sprintf (path_string, "%s%s",
jr_TarEntryPrefix (tar_entry_ptr), jr_TarEntryName (tar_entry_ptr)
);
}
else {
sprintf (path_string, "%s/%s",
jr_TarEntryPrefix (tar_entry_ptr), jr_TarEntryName (tar_entry_ptr)
);
}
}
else {
sprintf (path_string, "%s", jr_TarEntryName (tar_entry_ptr));
}
return path_string;
}
void jr_TarFilePtrAlign (fp)
FILE * fp;
{
unsigned jr_int absolute_offset ;
unsigned jr_int offset_within_block ;
absolute_offset = ftell(fp) ;
offset_within_block = (absolute_offset % jr_TAR_BLOCK_SIZE) ;
if (offset_within_block != 0) {
absolute_offset += jr_TAR_BLOCK_SIZE - offset_within_block ;
fseek(fp, absolute_offset, SEEK_SET) ;
}
}
jr_int jr_TarFilePtrAlignFifoRead (rfp, num_bytes_moved)
FILE * rfp;
unsigned jr_int num_bytes_moved;
{
unsigned jr_int offset_within_block ;
unsigned jr_int bytes_to_block_end = 0;
unsigned jr_int k;
offset_within_block = (num_bytes_moved % jr_TAR_BLOCK_SIZE) ;
if (offset_within_block != 0) {
bytes_to_block_end = jr_TAR_BLOCK_SIZE - offset_within_block;
for (k=0; k < bytes_to_block_end; k++) {
if (getc (rfp) == EOF) {
break;
}
}
}
return bytes_to_block_end;
}
jr_int jr_TarFilePtrAlignFifoWrite (wfp, num_bytes_moved)
FILE * wfp;
unsigned jr_int num_bytes_moved;
{
unsigned jr_int offset_within_block ;
unsigned jr_int bytes_to_block_end = 0;
unsigned jr_int k;
offset_within_block = (num_bytes_moved % jr_TAR_BLOCK_SIZE) ;
if (offset_within_block != 0) {
bytes_to_block_end = jr_TAR_BLOCK_SIZE - offset_within_block;
for (k=0; k < bytes_to_block_end; k++) {
putc (0, wfp);
}
}
return bytes_to_block_end;
}
jr_int jr_TarFileWriteEOF (wfp, error_buf)
FILE * wfp;
char * error_buf;
{
jr_int num_items;
jr_int k;
char null_buf [jr_TAR_BLOCK_SIZE];
/*
* 6/15/2004: two null blocks signify the end of a tar file
* according to /usr/include/tar.h on Linux.
*/
memset (null_buf, 0, jr_TAR_BLOCK_SIZE);
for (k=0; k < 2; k++) {
num_items = fwrite (null_buf, jr_TAR_BLOCK_SIZE, 1, wfp);
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't write null tar header: %s", strerror (errno));
return jr_TAR_INTERNAL_ERROR;
}
}
return 0;
}
const char * jr_TarTypeFlagToString(type_flag)
jr_int type_flag;
{
char * type_desc ;
switch (type_flag) {
case LNKTYPE : type_desc = "hard-link" ; break ;
case SYMTYPE : type_desc = "symb-link" ; break ;
case DIRTYPE : type_desc = "directory" ; break ;
case BLKTYPE : type_desc = "blck-spec" ; break ;
case CHRTYPE : type_desc = "char-spec" ; break ;
case FIFOTYPE : type_desc = "fifo-spec" ; break ;
case REGTYPE : type_desc = "file" ; break;
case AREGTYPE : type_desc = "file" ; break;
case CONTTYPE : type_desc = "cont-spec" ; break ;
default : type_desc = "UNKNOWN" ; break ;
}
return(type_desc) ;
}
unsigned jr_int jr_TarModeToPerms (
jr_int tar_mode)
{
unsigned jr_int perm_flags = 0;
if (tar_mode & TSUID) {
perm_flags |= jr_PERM_S_OWNER;
}
if (tar_mode & TSGID) {
perm_flags |= jr_PERM_S_GROUP;
}
if (tar_mode & TUREAD) {
perm_flags |= jr_PERM_R_OWNER;
}
if (tar_mode & TUWRITE) {
perm_flags |= jr_PERM_W_OWNER;
}
if (tar_mode & TUEXEC) {
perm_flags |= jr_PERM_X_OWNER;
}
if (tar_mode & TGREAD) {
perm_flags |= jr_PERM_R_GROUP;
}
if (tar_mode & TGWRITE) {
perm_flags |= jr_PERM_W_GROUP;
}
if (tar_mode & TGEXEC) {
perm_flags |= jr_PERM_X_GROUP;
}
if (tar_mode & TOREAD) {
perm_flags |= jr_PERM_R_OTHER;
}
if (tar_mode & TOWRITE) {
perm_flags |= jr_PERM_W_OTHER;
}
if (tar_mode & TOEXEC) {
perm_flags |= jr_PERM_X_OTHER;
}
return perm_flags;
}
| 2.125 | 2 |
2024-11-18T18:56:50.021386+00:00 | 2018-12-08T20:48:18 | 099a61fa99e84fee79c19754f75c310e452c0d40 | {
"blob_id": "099a61fa99e84fee79c19754f75c310e452c0d40",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-08T20:48:18",
"content_id": "5be2992f760448eac9ccbf196415718adbafa00c",
"detected_licenses": [
"MIT"
],
"directory_id": "ed129d9dd401a002aa1337d02d3013a9ebc830fb",
"extension": "c",
"filename": "SPI.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 160977160,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1124,
"license": "MIT",
"license_type": "permissive",
"path": "/SPI.c",
"provenance": "stackv2-0004.json.gz:28462",
"repo_name": "MHessen/Safe_Security",
"revision_date": "2018-12-08T20:48:18",
"revision_id": "55a40d7a53246bdaad43283f3528a1705dcb4489",
"snapshot_id": "d5e0696542d61a87b0a1e419210595a6bd4a2aad",
"src_encoding": "WINDOWS-1252",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MHessen/Safe_Security/55a40d7a53246bdaad43283f3528a1705dcb4489/SPI.c",
"visit_date": "2020-04-10T10:50:23.250659"
} | stackv2 | /*
* SPI.c
*
* Created on: ??þ/??þ/????
* Author: DR . radwa hussein
*/
#include "Types.h"
#include "Registers.h"
#include "DIO.h"
#include "SPI.h"
#define get_bit(Register,Pin) ((Register >> Pin) & 1)
#define Enable 1
#define Disable 0
#define Master Disable
#define Slave Enable
#define Mode_S 0
enum Mode {SelectMaster , SelectSlave , Select=Mode_S};
void SPI_vidInit (void)
{
#if ( Master == Enable )
{
{//Master
DIO_vidSetBitDirction(1,4,1) ; // SS o/p
DIO_vidSetBitDirction(1,7,1) ; // clk o/p
DIO_vidSetBitDirction(1,5,1) ; // MISO o/p
DIO_vidSetBitDirction(1,6,0) ; // MOSI i/p
SPCR = 0b01010001 ; // Master
}
}
#endif
#if ( Slave == Enable )
{
void SPI_vidInit (void)
{//Slave
DIO_vidSetBitDirction(1,4,0) ; // SS o/p
DIO_vidSetBitDirction(1,7,0) ; // clk o/p
DIO_vidSetBitDirction(1,5,0) ; // MISO o/p
DIO_vidSetBitDirction(1,6,1) ; // MOSI i/p
SPCR = 0b01010001 ; // Master
}
}
#endif
}
u8 SPI_u8TranRec (u8 Data)
{
SPDR = Data ;
while ( 0 == ( get_bit(SPSR,7) ) ) ;
return SPDR ;
}
| 2.515625 | 3 |
2024-11-18T18:56:50.738400+00:00 | 2020-07-19T13:55:57 | c70993502d60678103fa09e13e94de606d2c9807 | {
"blob_id": "c70993502d60678103fa09e13e94de606d2c9807",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-19T13:55:57",
"content_id": "e2d012ffab9575b7940a07a38c7985ac864cd792",
"detected_licenses": [
"MIT"
],
"directory_id": "ead3406a38a51ed0df9144178fe7416a3bb87985",
"extension": "h",
"filename": "board.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 279995452,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 660,
"license": "MIT",
"license_type": "permissive",
"path": "/src/board.h",
"provenance": "stackv2-0004.json.gz:28974",
"repo_name": "guidanoli/chess99",
"revision_date": "2020-07-19T13:55:57",
"revision_id": "595bd566013a29acaa595f31284f91da861803da",
"snapshot_id": "3fc7c14ca9cc1c55f625c60738d1acf20cea1639",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/guidanoli/chess99/595bd566013a29acaa595f31284f91da861803da/src/board.h",
"visit_date": "2022-11-17T07:00:21.634539"
} | stackv2 | #ifndef BOARD_H
#define BOARD_H
#include <stdio.h>
#include "types.h"
typedef struct Board Board;
// Create new board
// In case of error, returns NULL
Board* Board_new();
// Obtain piece in a given square
Piece* Board_at(Board* board, Square sq);
Piece const* Board_at_const(Board const* board, Square sq);
// Serialize board
void Board_save(Board const* board, FILE* fp);
// Deserialize board
// In case of error, returns NULL
Board* Board_load(FILE *fp);
// Print board to file
void Board_print(Board const* board, FILE* fp);
// Delete board
void Board_delete(Board* board);
// Check if board is valid
int Board_check(Board const* board);
#endif
| 2.046875 | 2 |
2024-11-18T18:56:50.981328+00:00 | 2021-03-15T22:45:19 | 969afd890efa12d40d9688833ce6d66cb560e141 | {
"blob_id": "969afd890efa12d40d9688833ce6d66cb560e141",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-15T22:45:19",
"content_id": "2e06c765084f9ca425e8a13ebc2ed39c3e007ecf",
"detected_licenses": [
"Unlicense"
],
"directory_id": "21344769ca2bd11dcdd8f4831d6da5e0cd705df6",
"extension": "c",
"filename": "traveling_salesman.c",
"fork_events_count": 1,
"gha_created_at": "2018-05-28T16:46:17",
"gha_event_created_at": "2021-03-15T22:45:19",
"gha_language": "C",
"gha_license_id": "Unlicense",
"github_id": 135186701,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3702,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/traveling_salesman/traveling_salesman.c",
"provenance": "stackv2-0004.json.gz:29360",
"repo_name": "dalealleshouse/algorithms",
"revision_date": "2021-03-15T22:45:19",
"revision_id": "9ceac5692e657ff0f26e27ba9864cc58f70f2764",
"snapshot_id": "83f8acca49b7adeac468f378fe3311fd4d6e35f4",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dalealleshouse/algorithms/9ceac5692e657ff0f26e27ba9864cc58f70f2764/src/traveling_salesman/traveling_salesman.c",
"visit_date": "2021-06-09T00:46:32.352766"
} | stackv2 | #include "./traveling_salesman.h"
#include <math.h>
#include <stdlib.h>
#include "common_math.h"
static double squared_dist(const point* p1, const point* p2) {
return ((p2->x - p1->x) * (p2->x - p1->x)) +
((p2->y - p1->y) * (p2->y - p1->y));
}
static double _dist(const point* p1, const point* p2) {
return sqrt(squared_dist(p1, p2));
}
ResultCode dist(const point* p1, const point* p2, double* result) {
if (p1 == NULL || p2 == NULL || result == NULL) return kNullParameter;
*result = _dist(p1, p2);
return kSuccess;
}
ResultCode adjacencyMatrix(const city* cities, const size_t n,
double** matrix) {
if (cities == NULL || matrix == NULL) return kNullParameter;
if (*matrix != NULL) return kOutputPointerIsNotNull;
double* result = malloc(sizeof(double) * n * n);
if (result == NULL) return kFailedMemoryAllocation;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
dist(&cities[i].coordinates, &cities[j].coordinates, &result[i * n + j]);
}
}
*matrix = result;
return kSuccess;
}
ResultCode TravelingSalesman(size_t n, double graph[n][n],
double* shortest_path) {
if (graph == NULL || shortest_path == NULL) return kNullParameter;
if (n < 2) return kArgumentOutOfRange;
unsigned int size = 1 << (n - 1);
double* pBest = malloc(sizeof(double) * size * n);
double(*best)[n] = (double(*)[n])pBest;
for (size_t i = 0; i < size; i++) {
for (size_t j = 0; j < n; j++) {
best[i][j] = INFINITY;
}
}
for (size_t visited = 1; visited < (size); ++visited) {
for (size_t last = 0; last < (n - 1); ++last) {
// last visited vertex must be one of the visited vertices
if (!(visited & 1 << last)) continue;
// try all possibilities for the previous vertex,
// pick the best among them
if (visited == 1 << last) {
// previous vertex must have been N-1
best[visited][last] = graph[n - 1][last];
} else {
// previous vertex was one of the other ones in "visited"
size_t prev_visited = visited ^ 1 << last;
for (size_t prev = 0; prev < n - 1; ++prev) {
if (!(prev_visited & 1 << prev)) continue;
best[visited][last] =
MinDouble(2, best[visited][last],
graph[last][prev] + best[prev_visited][prev]);
}
}
}
}
double answer = INFINITY;
for (size_t last = 0; last < n - 1; ++last) {
answer = MinDouble(2, answer, graph[last][n - 1] + best[(size - 1)][last]);
}
free(best);
*shortest_path = answer;
return kSuccess;
}
static city* find_closest(city* cities, size_t n, city* the_city) {
city* result = NULL;
double shortest_dist = INFINITY;
for (size_t i = 0; i < n; i++) {
if (cities[i].visted) continue;
double dist = squared_dist(&the_city->coordinates, &cities[i].coordinates);
if (dist < shortest_dist) {
result = &cities[i];
shortest_dist = dist;
}
}
return result;
}
ResultCode TravelingSalesmanApprox(size_t n, city* cities,
double* shortest_path) {
if (cities == NULL || shortest_path == NULL) return kNullParameter;
if (n < 2) return kArgumentOutOfRange;
city* here_now = &cities[0];
here_now->visted = true;
double dist_so_far = 0;
for (size_t i = 1; i < n; i++) {
city* closest = find_closest(cities, n, here_now);
dist_so_far += _dist(&closest->coordinates, &here_now->coordinates);
closest->visted = true;
here_now = closest;
}
dist_so_far += _dist(&cities[0].coordinates, &here_now->coordinates);
*shortest_path = dist_so_far;
return kSuccess;
}
| 2.828125 | 3 |
2024-11-18T18:56:51.916737+00:00 | 2019-03-05T15:36:04 | c0b6094687948f945449ac136dd781154d0ae82e | {
"blob_id": "c0b6094687948f945449ac136dd781154d0ae82e",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-05T15:36:04",
"content_id": "e975530419c94e25ca106e3cc48fd31f87095787",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "a55c5e52744a2ca3612245fd31081a168f5e4f74",
"extension": "h",
"filename": "lorasc.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": 4054,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/preconditioners/lorasc.h",
"provenance": "stackv2-0004.json.gz:30001",
"repo_name": "HesslerY/preAlps",
"revision_date": "2019-03-05T15:36:04",
"revision_id": "8e59028f6f5bbc3e4c362ac16776b88b8a38fb83",
"snapshot_id": "07198c97eb2cd0a8526469e0f335b385329540cc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/HesslerY/preAlps/8e59028f6f5bbc3e4c362ac16776b88b8a38fb83/src/preconditioners/lorasc.h",
"visit_date": "2021-10-21T18:10:05.413723"
} | stackv2 | /*
============================================================================
Name : lorasc.h
Author : Simplice Donfack
Version : 0.1
Description : Preconditioner based on Schur complement
Date : Sept 20, 2017
============================================================================
*/
#ifndef LORASC_H
#define LORASC_H
#include <mpi.h>
#include <cplm_matcsr.h>
#include <cplm_matdense.h>
#include "preAlps_solver.h"
/*Structure of the preconditioner*/
typedef struct{
/* User input*/
double deflation_tol; /* The deflation tolerance (default: 10^-2)*/
int nrhs; /* The number of rhs on which lorasc will be applied. This is required internally for the analysis. Default value: 1 */
/* Computed during the build but accessible by the user */
//int *partCount; /* array of size P (idxRowCount[i] indicates the number of rows for processor i in the permuted matrix)*/
//int *partBegin; /* array of size P+1 (idxRowBegin[i] indicates the position of the first row of processor i in the permuted matrix)*/
/* infos about the separator also accessible by the user */
int *sep_mcounts;
int *sep_moffsets;
int sep_nrows;
double *eigvalues; /* The eigenvalues from the eigenvalue problem of lorasc */
double *eigvectors; /* The eigenvectors from the eigenvalue problem of lorasc (allocated on the root only) */
int eigvalues_deflation; /* Number of eigenvalues selected for the deflation*/
/* The global communicator */
MPI_Comm comm; /* The MPI communicator used to build the preconditioner. Should be the same to apply it. */
/* Multilevel communicators */
MPI_Comm comm_masterLevel; /* The MPI communicator for the master group of processors */
MPI_Comm comm_localLevel; /* The MPI communicator for the local group of processors */
int *Aii_mcounts;
int *Aii_moffsets;
int *Aig_mcounts;
int *Aig_moffsets;
int *Agi_mcounts;
int *Agi_moffsets;
int nev; /* Number of eigenvalues computed */
/* Lorasc required matrices */
CPLM_Mat_CSR_t *Aii;
CPLM_Mat_CSR_t *Aig;
CPLM_Mat_CSR_t *Agi;
CPLM_Mat_CSR_t *Aggloc;
/* Lorasc required solvers object */
preAlps_solver_t *Aii_sv;
preAlps_solver_t *Agg_sv;
/* eigenvalues workspace */
double *sigma; /* Array of the same size as the number of eigenvalues computed */
/* workspace */
double *vi; //buffer with the same size as the number of rows of Aii
double *zi; //buffer with the same size as the number of rows of Aii
double *dwork1;
double *dwork2;
double *eigWork; //a buffer with the same as the number of eigenvalues computed * nrhs
double tPartition;
} preAlps_Lorasc_t;
/*Allocate workspace for the preconditioner*/
int preAlps_LorascAlloc(preAlps_Lorasc_t **lorasc);
/*
* Build the preconditioner
* lorasc:
* input/output: the preconditioner object to construct
* commMultilevel:
* input: a multilevel communicator built with preAlps_comm2LevelsSplit
* A:
* input: the input matrix on processor 0
* locAP:
* output: the local permuted matrix on each proc after the preconditioner is built
* partCount:
* output: the number of rows in each part
* partBegin:
* output: the begining rows of each part.
* perm:
* output: the permutation vector
*/
int preAlps_LorascBuild(preAlps_Lorasc_t *lorasc, MPI_Comm *commMultilevel, CPLM_Mat_CSR_t *A, CPLM_Mat_CSR_t *locAP, int **partCount, int **partBegin, int *perm);
/*Destroy the preconditioner*/
int preAlps_LorascDestroy(preAlps_Lorasc_t **lorasc);
/*
* Apply Lorasc preconditioner on a dense matrice
* i.e Compute W = M_{lorasc}^{-1} * V
*/
int preAlps_LorascMatApply(preAlps_Lorasc_t *lorasc, CPLM_Mat_Dense_t *X, CPLM_Mat_Dense_t *Y);
/* Free internal allocated workspace */
int preAlps_LorascMatApplyWorkspaceFree(preAlps_Lorasc_t *lorasc);
/* Allocate workspace if required */
int preAlps_LorascMatApplyWorkspacePrepare(preAlps_Lorasc_t *lorasc, int Aii_m, int separator_m, int v_nrhs);
#endif
| 2.359375 | 2 |
2024-11-18T18:56:52.071768+00:00 | 2021-02-20T20:47:54 | 3c953e15066ef872803e8cf8f91ebd856c956737 | {
"blob_id": "3c953e15066ef872803e8cf8f91ebd856c956737",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-21T19:38:34",
"content_id": "731372029dc0aaa3c384ea1a5ec52be9b77612d1",
"detected_licenses": [
"MIT"
],
"directory_id": "9905d90b89995a7eb7a9d67e807da118a1e00fc5",
"extension": "c",
"filename": "ebyte.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 340753727,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9552,
"license": "MIT",
"license_type": "permissive",
"path": "/ebyte.c",
"provenance": "stackv2-0004.json.gz:30258",
"repo_name": "jkoelker/esp32-ebyte",
"revision_date": "2021-02-20T20:47:54",
"revision_id": "756e66332c1c6ca873ffa7a5dc052caaa8fb1d64",
"snapshot_id": "910917e250e49df721a5f1a592d57559e2bc7418",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jkoelker/esp32-ebyte/756e66332c1c6ca873ffa7a5dc052caaa8fb1d64/ebyte.c",
"visit_date": "2023-03-05T01:50:28.143654"
} | stackv2 | /* */
#include <string.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <driver/gpio.h>
#include <driver/uart.h>
#include "esp_ebyte.h"
static const char EBYTE_PARAMS_CMD[3] = { 0xC1, 0xC1, 0xC1 };
static const char EBYTE_VERSION_CMD[3] = { 0xC3, 0xC3, 0xC3 };
static const char EBYTE_RESET_CMD[3] = { 0xC4, 0xC4, 0xC4 };
esp_err_t ebyte_wait_aux(struct ebyte_config *config) {
while (gpio_get_level(config->aux) == 0) {
vTaskDelay(10 / portTICK_PERIOD_MS);
};
vTaskDelay(20 / portTICK_PERIOD_MS);
return ESP_OK;
}
esp_err_t ebyte_init(struct ebyte_config *config) {
gpio_set_direction(config->aux, GPIO_MODE_INPUT);
gpio_set_direction(config->m0, GPIO_MODE_OUTPUT);
gpio_set_direction(config->m1, GPIO_MODE_OUTPUT);
ebyte_set_mode(config, EBYTE_NORMAL);
if (ebyte_read_version(config, config->version) != ESP_OK) {
return ESP_FAIL;
}
if (ebyte_read_params(config, config->params) != ESP_OK) {
return ESP_FAIL;
}
return ESP_OK;
}
esp_err_t ebyte_reset(struct ebyte_config *config) {
ebyte_set_mode(config, EBYTE_PROGRAM);
uart_write_bytes(config->uart, EBYTE_RESET_CMD, sizeof(EBYTE_RESET_CMD));
ebyte_wait_aux(config);
ebyte_set_mode(config, EBYTE_PROGRAM);
return ESP_OK;
}
esp_err_t ebyte_read_params(
struct ebyte_config *config,
struct ebyte_params *params) {
uint8_t buf[6] = { 0 };
ebyte_set_mode(config, EBYTE_PROGRAM);
uart_write_bytes(config->uart, EBYTE_PARAMS_CMD, sizeof(EBYTE_PARAMS_CMD));
uart_read_bytes(config->uart, (uint8_t *)&buf, sizeof(buf), 20 / portTICK_RATE_MS);
ebyte_set_mode(config, EBYTE_NORMAL);
if (buf[0] == 0xC0 || buf[0] == 0xC2) {
params->save_on_power_down = (buf[0] == 0xC0);
params->address = (buf[1] << 8) | buf[2];
switch ((buf[3] & 0xC0) >> 6) {
case 0:
params->parity = UART_PARITY_DISABLE;
break;
case 1:
params->parity = UART_PARITY_ODD;
break;
case 2:
params->parity = UART_PARITY_EVEN;
break;
default:
params->parity = UART_PARITY_DISABLE;
break;
}
switch ((buf[3] & 0x38) >> 3) {
case 0:
params->baud_rate = 1200;
break;
case 1:
params->baud_rate = 2400;
break;
case 2:
params->baud_rate = 4800;
break;
case 3:
params->baud_rate = 9600;
break;
case 4:
params->baud_rate = 19200;
break;
case 5:
params->baud_rate = 38400;
break;
case 6:
params->baud_rate = 57600;
break;
case 7:
params->baud_rate = 115200;
break;
default:
params->baud_rate = 9600;
break;
}
switch (buf[3] & 0x07) {
case 0:
params->air_rate = 300;
break;
case 1:
params->air_rate = 1200;
break;
case 2:
params->air_rate = 2400;
break;
case 3:
params->air_rate = 4800;
break;
case 4:
params->air_rate = 9600;
break;
case 5:
params->air_rate = 19200;
break;
case 6:
params->air_rate = 19200;
break;
case 7:
params->air_rate = 19200;
break;
default:
params->air_rate = 2400;
break;
}
params->channel = buf[4];
params->transmission_fixed = (buf[5] & 0X80) >> 7;
params->pullup = (buf[5] & 0X40) >> 6;
switch ((buf[5] & 0X38) >> 3) {
case 0:
params->wakeup = 250;
break;
case 1:
params->wakeup = 500;
break;
case 2:
params->wakeup = 750;
break;
case 3:
params->wakeup = 1000;
break;
case 4:
params->wakeup = 1250;
break;
case 5:
params->wakeup = 1500;
break;
case 6:
params->wakeup = 1750;
break;
case 7:
params->wakeup = 2000;
break;
default:
params->wakeup = 250;
break;
}
params->fec = (buf[5] & 0X07) >> 2;
switch (buf[5] & 0X03) {
case 0:
params->power = 30;
break;
case 1:
params->power = 27;
break;
case 2:
params->power = 24;
break;
case 3:
params->power = 21;
break;
default:
params->power = 30;
break;
}
return ESP_OK;
}
return ESP_FAIL;
}
esp_err_t ebyte_read_version(
struct ebyte_config *config,
struct ebyte_version *version) {
uint8_t buf[6] = { 0 };
ebyte_set_mode(config, EBYTE_PROGRAM);
uart_write_bytes(config->uart, EBYTE_VERSION_CMD, sizeof(EBYTE_VERSION_CMD));
uart_read_bytes(config->uart, (uint8_t *)&buf, sizeof(buf), 20 / portTICK_RATE_MS);
ebyte_set_mode(config, EBYTE_NORMAL);
if (buf[0] == 0xC3) {
version->model = buf[1];
version->version = buf[2];
version->version = buf[3];
return ESP_OK;
}
return ESP_FAIL;
}
esp_err_t ebyte_set_mode(
struct ebyte_config *config,
enum ebyte_operating_mode mode) {
gpio_set_level(config->m0, (mode & 0x02) >> 1);
gpio_set_level(config->m1, (mode & 0x01));
ebyte_wait_aux(config);
uart_config_t uart_config = {
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
};
switch (mode) {
case EBYTE_PROGRAM:
uart_config.baud_rate = 9600;
break;
default:
uart_config.baud_rate = config->baud_rate;
break;
}
uart_param_config(config->uart, &uart_config);
uart_set_pin(config->uart, config->tx, config->rx, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
uart_driver_install(config->uart, 256, 256, 0, NULL, 0);
return ESP_OK;
}
esp_err_t ebyte_write_params(
struct ebyte_config *config,
struct ebyte_params *params) {
uint8_t buf[6] = { 0 };
buf[0] = params->save_on_power_down ? 0xC0 : 0xC2;
buf[1] = params->address >> 8;
buf[2] = params->address & 0xFF;
switch (params->parity) {
case UART_PARITY_DISABLE:
break;
case UART_PARITY_ODD:
buf[3] |= 0x40;
break;
case UART_PARITY_EVEN:
buf[3] |= 0x80;
break;
}
switch (params->baud_rate) {
case 1200:
break;
case 2400:
buf[3] |= 0x08;
break;
case 4800:
buf[3] |= 0x10;
break;
case 9600:
buf[3] |= 0x18;
break;
case 19200:
buf[3] |= 0x20;
break;
case 38400:
buf[3] |= 0x28;
break;
case 57600:
buf[3] |= 0x30;
break;
case 115200:
buf[3] |= 0x38;
break;
}
switch (params->air_rate) {
case 300:
break;
case 1200:
buf[3] |= 0x01;
break;
case 2400:
buf[3] |= 0x02;
break;
case 4800:
buf[3] |= 0x03;
break;
case 9600:
buf[3] |= 0x04;
break;
case 19200:
buf[3] |= 0x05;
break;
}
buf[4] = params->channel;
if (params->transmission_fixed) {
buf[5] |= 0x80;
}
if (params->pullup) {
buf[5] |= 0x40;
}
switch (params->wakeup) {
case 250:
break;
case 500:
buf[5] |= 0x08;
break;
case 750:
buf[5] |= 0x10;
break;
case 1000:
buf[5] |= 0x18;
break;
case 1250:
buf[5] |= 0x20;
break;
case 1500:
buf[5] |= 0x28;
break;
case 1750:
buf[5] |= 0x30;
break;
case 2000:
buf[5] |= 0x38;
break;
}
if (params->fec) {
buf[5] |= 0x04;
}
switch (params->power) {
case 30:
case 20:
break;
case 27:
case 17:
buf[5] |= 0x01;
break;
case 24:
case 14:
buf[5] |= 0x02;
break;
case 21:
case 10:
buf[5] |= 0x03;
break;
}
ebyte_set_mode(config, EBYTE_PROGRAM);
uart_write_bytes(config->uart, (const char*)buf, sizeof(buf));
ebyte_set_mode(config, EBYTE_NORMAL);
return ESP_OK;
}
| 2.1875 | 2 |
2024-11-18T18:56:52.140189+00:00 | 2021-07-23T20:02:23 | 626763a8d355fcf3109b5b7fc7e9611ad3616c22 | {
"blob_id": "626763a8d355fcf3109b5b7fc7e9611ad3616c22",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-23T20:02:23",
"content_id": "4fda5718be99c371aa4d4fcc36ff76bf0470db61",
"detected_licenses": [
"MIT"
],
"directory_id": "88886d17f78d3d09675b5aa6b656d8617d411d55",
"extension": "c",
"filename": "mic.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": 971,
"license": "MIT",
"license_type": "permissive",
"path": "/src/mic/mic.c",
"provenance": "stackv2-0004.json.gz:30386",
"repo_name": "vscherbo/upm",
"revision_date": "2021-07-23T20:02:23",
"revision_id": "d6f76ff8c231417666594214679c49399513112e",
"snapshot_id": "e031a90b925072c474b7855dee084fb36a8c7fee",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vscherbo/upm/d6f76ff8c231417666594214679c49399513112e/src/mic/mic.c",
"visit_date": "2023-06-18T21:50:14.692887"
} | stackv2 | /*
* Author: Brendan Le Foll <[email protected]>
* Sisinty Sasmita Patra <[email protected]>
*
* Copyright (c) 2016 Intel Corporation.
*
* This program and the accompanying materials are made available under the
* terms of the The MIT License which is available at
* https://opensource.org/licenses/MIT.
*
* SPDX-License-Identifier: MIT
*/
#include "mic.h"
mic_context upm_mic_init(int pin)
{
mic_context dev = (mic_context)malloc(sizeof(struct _mic_context));
if(dev == NULL) return NULL;
dev->analog_pin = pin;
dev->aio = mraa_aio_init(dev->analog_pin);
if(dev->aio == NULL)
{
printf("unable to initialize the AIO pin");
free(dev);
return NULL;
}
return dev;
}
void mic_close(mic_context dev)
{
mraa_aio_close(dev->aio);
free(dev);
}
upm_result_t mic_get_value(mic_context dev, float *micval)
{
*micval = mraa_aio_read(dev->aio);
return UPM_SUCCESS;
}
| 2.578125 | 3 |
2024-11-18T18:56:52.263502+00:00 | 2017-09-26T04:34:42 | 7eb4aefb021755ec75afbd81167bd0cfdd857d06 | {
"blob_id": "7eb4aefb021755ec75afbd81167bd0cfdd857d06",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-26T04:34:42",
"content_id": "b1488e77739cc8a9b1e2718f9fa5483d45cb2eb1",
"detected_licenses": [
"MIT"
],
"directory_id": "4c1dd31e9eb1015bf9689e8ac1fcbae1bd2e0729",
"extension": "c",
"filename": "testlower.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 104835748,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 124,
"license": "MIT",
"license_type": "permissive",
"path": "/C2/testlower.c",
"provenance": "stackv2-0004.json.gz:30514",
"repo_name": "josephmcasey/The-C-Programming-Language-Second-Edition",
"revision_date": "2017-09-26T04:34:42",
"revision_id": "de17191f211349ca1dd2bed83ef1dc5ed3e58e48",
"snapshot_id": "4a67b504f77f70a168e015fb8364c08420eb227d",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/josephmcasey/The-C-Programming-Language-Second-Edition/de17191f211349ca1dd2bed83ef1dc5ed3e58e48/C2/testlower.c",
"visit_date": "2021-07-06T07:21:51.779700"
} | stackv2 | #include <stdio.h>
#include "lower.c"
main()
{
int c;
while ((c = getchar()) != EOF)
putchar(lower(c));
return 0;
}
| 2.34375 | 2 |
2024-11-18T18:56:52.534820+00:00 | 2021-07-31T08:11:55 | 68f1ad524946c2c689e38f93a52583ffb4fe4cf4 | {
"blob_id": "68f1ad524946c2c689e38f93a52583ffb4fe4cf4",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-31T08:11:55",
"content_id": "a17fb327f4c59f8ff591511f0f01bd07354b81ee",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ad1160c77440fc178eda12141256d4c1fa576e84",
"extension": "c",
"filename": "05.recursion.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 386902890,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1239,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/chapter4/05.recursion.c",
"provenance": "stackv2-0004.json.gz:30898",
"repo_name": "wosta/imooc_c",
"revision_date": "2021-07-31T08:11:55",
"revision_id": "76a826168d9f1256f04de4e32c198e9e9e8e86f5",
"snapshot_id": "4e7d1a26e087c7ed6d12f65a50b3507b5e6ee03f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wosta/imooc_c/76a826168d9f1256f04de4e32c198e9e9e8e86f5/chapter4/05.recursion.c",
"visit_date": "2023-06-30T22:46:51.830318"
} | stackv2 | //
// Created by olive on 2021/7/31.
//
#include <stdio.h>
unsigned int Factorial(unsigned int n) {
if (n == 0) {
return 1; // f(0) = 1
} else {
return n * Factorial(n - 1); // f(n) = nf(n - 1)
}
}
unsigned int FactorialByIteration(unsigned int n) {
unsigned int result = 1;
for (unsigned int i = n; i > 0; --i) {
result *= i;
}
return result;
}
unsigned int Fibonacci(unsigned int n) {
if (n == 1 || n == 0) {
return n; // f(0) = 0, f(1) = 1
} else {
return Fibonacci(n - 1) + Fibonacci(n - 2); // f(n) = f(n - 1) + f(n - 2)
}
}
unsigned int FibonacciByIteration(unsigned int n) {
if (n == 1 || n == 0) {
return n; // f(0) = 0, f(1) = 1
}
unsigned int last = 0;
unsigned int current = 1;
for (int i = 0; i <= n - 2; ++i) {
unsigned int temp = current;
current += last;
last = temp;
}
return current;
}
int main(void) {
printf("3! : %d\n", Factorial(3));
printf("5! : %d\n", Factorial(5));
printf("10! : %d\n", FactorialByIteration(10));
printf("Fibonacci(3): %d\n", Fibonacci(3));
printf("Fibonacci(5): %d\n", Fibonacci(5));
printf("Fibonacci(10) : %d\n", Fibonacci(10));
printf("Fibonacci(10) : %d\n", FibonacciByIteration(10));
return 0;
}
| 3.640625 | 4 |
2024-11-18T18:56:54.534567+00:00 | 2017-05-01T13:16:48 | 65f742bc289649ce3e1c1ce19b35b93b9c151bf5 | {
"blob_id": "65f742bc289649ce3e1c1ce19b35b93b9c151bf5",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-01T13:20:33",
"content_id": "4d98a1aee7c797484cbab1367cccc20a55ed0975",
"detected_licenses": [
"MIT"
],
"directory_id": "008aded6026b1050b955b8744d3fa177a236e195",
"extension": "c",
"filename": "sigtrace.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 89925300,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10764,
"license": "MIT",
"license_type": "permissive",
"path": "/sigtrace.c",
"provenance": "stackv2-0004.json.gz:31539",
"repo_name": "sschroe/sigtrace",
"revision_date": "2017-05-01T13:16:48",
"revision_id": "847c1d0451461ab911b7267dbccd0986c30548ad",
"snapshot_id": "98faf6cfca1ffd3b1964877dbab5f9e73b28cf7f",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/sschroe/sigtrace/847c1d0451461ab911b7267dbccd0986c30548ad/sigtrace.c",
"visit_date": "2021-01-20T06:44:45.312142"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <getopt.h>
#include <unistd.h>
#include <stdint.h>
static uint8_t running = 1;
static void signal_handler(int signum)
{
if (signum == SIGINT ||
signum == SIGTERM) {
running = 0;
}
}
/* Returns string with the signal name. enum values are mapped here
* rather than the plain value as the values may differ depending
* on the platform. */
static const char * const get_signal_name_from_id(const int signal) {
switch (signal) {
#ifdef SIGHUP
case SIGHUP: return "SIGHUP";
#endif
#ifdef SIGINT
case SIGINT: return "SIGINT";
#endif
#ifdef SIGQUIT
case SIGQUIT: return "SIGQUIT";
#endif
#ifdef SIGILL
case SIGILL: return "SIGILL";
#endif
#ifdef SIGABRT
case SIGABRT: return "SIGABRT";
#endif
#ifdef SIGFPE
case SIGFPE: return "SIGFPE";
#endif
#ifdef SIGKILL
case SIGKILL: return "SIGKILL";
#endif
#ifdef SIGSEGV
case SIGSEGV: return "SIGSEGV";
#endif
#ifdef SIGPIPE
case SIGPIPE: return "SIGPIPE";
#endif
#ifdef SIGALRM
case SIGALRM: return "SIGALRM";
#endif
#ifdef SIGTERM
case SIGTERM: return "SIGTERM";
#endif
#ifdef SIGUSR1
case SIGUSR1: return "SIGUSR1";
#endif
#ifdef SIGUSR2
case SIGUSR2: return "SIGUSR2";
#endif
#ifdef SIGCHLD
case SIGCHLD: return "SIGCHLD";
#endif
#ifdef SIGCONT
case SIGCONT: return "SIGCONT";
#endif
#ifdef SIGSTOP
case SIGSTOP: return "SIGSTOP";
#endif
#ifdef SIGTSTP
case SIGTSTP: return "SIGTSTP";
#endif
#ifdef SIGTTIN
case SIGTTIN: return "SIGTTIN";
#endif
#ifdef SIGTTOU
case SIGTTOU: return "SIGTTOU";
#endif
#ifdef SIGBUS
case SIGBUS: return "SIGBUS";
#endif
#ifdef SIGPOLL
case SIGPOLL: return "SIGPOLL";
#endif
#ifdef SIGPROF
case SIGPROF: return "SIGPROF";
#endif
#ifdef SIGSYS
case SIGSYS: return "SIGSYS";
#endif
#ifdef SIGTRAP
case SIGTRAP: return "SIGTRAP";
#endif
#ifdef SIGURG
case SIGURG: return "SIGURG";
#endif
#ifdef SIGVTALRM
case SIGVTALRM: return "SIGVTALRM";
#endif
#ifdef SIGXCPU
case SIGXCPU: return "SIGXCPU";
#endif
#ifdef SIGXFSZ
case SIGXFSZ: return "SIGXFSZ";
#endif
#ifdef SIGEMT
case SIGEMT: return "SIGEMT";
#endif
#ifdef SIGSTKFLT
case SIGSTKFLT: return "SIGSTKFLT";
#endif
#ifdef SIGPWR
case SIGPWR: return "SIGPWR";
#endif
#ifdef SIGINFO
case SIGINFO: return "SIGINFO";
#endif
#ifdef SIGLOST
case SIGLOST: return "SIGLOST";
#endif
#ifdef SIGWINCH
case SIGWINCH: return "SIGWINCH";
#endif
}
return "Unknown";
}
/* Prints information for the given process id by reading files from /proc/<pid> */
static void print_process_info(const pid_t pid) {
printf(" %5d ", pid);
static const int buffer_size = 100;
char * const buffer = malloc(buffer_size);
if (buffer == NULL) {
return ;
}
snprintf(buffer, buffer_size, "/proc/%d/status", pid);
FILE * const status = fopen(buffer, "r");
if (status != NULL) {
int parent = 0;
size_t n = 0;
char *line = NULL;
ssize_t len;
while ((len = getline(&line, &n, status)) > 0) {
if (len > 6 && memcmp(line, "PPid:", 5) == 0) {
parent = atoi(&line[6]);
} else if (len > 6 && memcmp(line, "Name:", 5) == 0) {
printf("%.*s", (int)strlen(&line[6]) - 1, &line[6]);
}
}
free(line);
fclose(status);
/* Get the executable path if available */
snprintf(buffer, buffer_size, "/proc/%d/exe", pid);
len = readlink(buffer, buffer, buffer_size);
if (len > 0) {
printf(" [%.*s]", (int)len, buffer);
}
printf("\n");
/* Get cmdline if available */
snprintf(buffer, buffer_size, "/proc/%d/cmdline", pid);
FILE * const cmdline = fopen(buffer, "r");
if (cmdline != NULL) {
if (fread(buffer, 1, 1, cmdline) > 0 && buffer[0] != 0) {
printf(" %5s %c", "", buffer[0]);
while (fread(buffer, 1, 1, cmdline) > 0) {
printf("%c", buffer[0] == 0 ? ' ' : buffer[0]);
}
printf("\n");
}
fclose(cmdline);
}
printf("\n");
free(buffer);
if (parent > 0) {
print_process_info(parent);
}
return;
}
printf("\n");
free(buffer);
}
static void print_help() {
printf(
"Usage: sigtrace [options] [program] [program args]\n"
"\n"
"Options:\n"
" -h - Displays this help\n"
" -v - Show version\n"
" -p <pid> - Attach to pid\n"
" -s <signal ids> - Comma separated list of signals to report (default = all)\n"
" -b <signal ids> - Comma separated list of signals to block\n"
" -q - Disable stdout output\n"
" -a - Attach to the process sending the signal. May help with fast exiting senders.\n"
"\n"
"Examples:\n"
" sigtrace -a /bin/ls -ahl\n"
" sigtrace -b 2,15 -p 1234\n"
);
}
/* Converts are comma separated list of numbers to a u64 bitmask */
static uint64_t list_to_bitmask(char * const comma_sep_list) {
uint64_t ret = 0;
char *arg = NULL;
for (arg = strtok(comma_sep_list, ",");
arg != NULL;
arg = strtok(NULL, ",")) {
const int value = atoi(arg);
if (value < 0 || value > sizeof(uint64_t) * 8 - 1) {
fprintf(stderr, "Ignored value '%s'.", arg);
continue;
}
ret |= 1 << value;
}
return ret;
}
static char signal_is_in_bitmask(const int signal, const uint64_t bitmask) {
return signal > 0 && signal < sizeof(bitmask) * 8 - 1 && bitmask & (1 << signal);
}
int main(int argc, char *argv[], char *envp[]) {
uint64_t show_signal_mask = ~((uint64_t)1 << SIGTRAP);
uint64_t block_signal_mask = 0;
int status;
uint8_t quiet = 0;
uint8_t attach_to_sender = 0;
pid_t pid = 0;
const struct option option_list[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'v'},
{"block", required_argument, 0, 'b'},
{"show", required_argument, 0, 's'},
{"pid", required_argument, 0, 'p'},
{"quiet", no_argument, 0, 'q'},
{"attach_to_sender", no_argument, 0, 'a'},
{0, 0, 0, 0}
};
int option;
struct sigaction sa = { .sa_handler = signal_handler };
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
while ((option = getopt_long(argc, argv, "+hvb:s:p:qa", &option_list[0], NULL)) > 0) {
char stop = 0;
/* Global options */
switch (option) {
case 'h':
print_help();
return 0;
case 'v':
printf("sigtrace version 0.1.0\n");
return 0;
case 'b':
block_signal_mask = list_to_bitmask(optarg);
break;
case 's':
show_signal_mask = list_to_bitmask(optarg);
break;
case 'q':
quiet = 1;
break;
case 'a':
attach_to_sender = 1;
break;
case 'p':
pid = atoi(optarg);
break;
default:
stop = 1;
break;
}
if (stop) {
break;
}
}
block_signal_mask |= 1 << SIGTRAP; /* Don't forward SIGTRAP */
if (pid == 0) {
/* Try to execute the given program as child process */
if (optind < argc) {
if ((pid = fork()) < 0) {
fprintf(stderr, "fork failed: %s\n", strerror(pid));
return 1;
}
if (pid == 0) {
/* Child process */
if (ptrace (PTRACE_TRACEME, 0, NULL, NULL) < 0) {
fprintf(stderr, "ptrace failed: %s\n", strerror(errno));
return 1;
}
if (execve(argv[optind], &argv[optind], envp) < 0) {
fprintf(stderr, "execve failed: %s\n", strerror(errno));
return 1;
}
return 0;
}
} else {
fprintf(stderr, "Neither a PID nor a program to execute were given.\n");
return 1;
}
} else {
if (ptrace (PTRACE_ATTACH, pid, NULL, NULL) < 0) {
fprintf(stderr, "Attach failed: %s\n", strerror(errno));
return 1;
}
waitpid(pid, &status, 0);
printf("Attached to %d\n", pid);
if (ptrace(PTRACE_CONT, pid, NULL, NULL) < 0) {
fprintf(stderr, "%s\n", strerror(errno));
return 1;
}
}
while(running) {
waitpid(pid, &status, 0);
/* Process has stopped, grab and process the signal. */
siginfo_t signal;
if (ptrace(PTRACE_GETSIGINFO, pid, NULL, &signal) < 0) {
if (errno != ESRCH) {
fprintf(stderr, "%s\n", strerror(errno));
return 1;
}
break;
}
if (quiet == 0 && (signal.si_pid != 0 || signal.si_uid != 0) && signal_is_in_bitmask(signal.si_signo, show_signal_mask)) {
char attached = 0;
/* Try to stop the signal sending process to avoid loosing information.
* Errors are ignored as this is optional. */
if (attach_to_sender != 0 && ptrace(PTRACE_ATTACH, signal.si_pid, NULL, NULL) == 0) {
attached = 1;
}
printf("Got %s (%d) with uid %u\n",
get_signal_name_from_id(signal.si_signo),
signal.si_signo,
signal.si_uid);
print_process_info(signal.si_pid);
if (attached && waitpid(signal.si_pid, &status, 0) > 0) {
ptrace(PTRACE_DETACH, signal.si_pid, NULL, NULL);
}
}
if (ptrace(PTRACE_CONT, pid, NULL, signal_is_in_bitmask(signal.si_signo, block_signal_mask) ? NULL : (void *)(uintptr_t)signal.si_signo) < 0) {
if (errno != ESRCH) {
fprintf(stderr, "%s\n", strerror(errno));
return 1;
}
break;
}
}
ptrace(PTRACE_DETACH, pid, NULL, NULL);
return 0;
}
| 2.453125 | 2 |
2024-11-18T18:56:54.598747+00:00 | 2021-05-05T10:42:59 | 013a796ced5549a68d4e6ea093a5393357d0fe88 | {
"blob_id": "013a796ced5549a68d4e6ea093a5393357d0fe88",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-05T10:42:59",
"content_id": "fcfaeec810535b3c10e5403879a688794afcf112",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2cb61a00b283878be9aa0808e1961201f4b190fc",
"extension": "c",
"filename": "buffer.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": 1303,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/source/msw/buffer.c",
"provenance": "stackv2-0004.json.gz:31667",
"repo_name": "CyberFlameGO/revanc",
"revision_date": "2021-05-05T10:42:59",
"revision_id": "22530bcad21aa4448432884e0a42cae32eebf8c1",
"snapshot_id": "b789d1c6559cbb1284fc224667fb560e2b85414d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CyberFlameGO/revanc/22530bcad21aa4448432884e0a42cae32eebf8c1/source/msw/buffer.c",
"visit_date": "2023-05-01T19:27:16.394307"
} | stackv2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <stdlib.h>
#include <string.h>
#define WIN32_MEAN_AND_LEAN
#define NOMINMAX
#include <windows.h>
#include "buffer.h"
#include "macros.h"
#include "paging.h"
struct buffer *new_buffer(struct page_format *fmt, void *target)
{
struct buffer *buffer;
struct page_level *level;
char *page;
size_t stride = 0;
size_t i, j;
if (!(buffer = malloc(sizeof *buffer)))
return NULL;
buffer->size = 0;
for (i = 0, level = fmt->levels; i < fmt->nlevels; ++i, ++level) {
stride = level->page_size;
buffer->size = max(buffer->size, level->npages * stride);
}
if (!(buffer->data = VirtualAlloc(target, buffer->size, MEM_RESERVE,
PAGE_READWRITE)))
goto err_free_buffer;
for (j = 0, level = fmt->levels; j < fmt->nlevels; ++j, ++level) {
page = buffer->data;
for (i = 0; i < level->npages; ++i) {
VirtualAlloc(page, 4 * KIB, MEM_COMMIT, PAGE_READWRITE);
page += level->page_size;
}
}
return buffer;
err_free_buffer:
free(buffer);
return NULL;
}
void del_buffer(struct buffer *buffer)
{
VirtualFree(buffer->data, buffer->size, MEM_RELEASE);
free(buffer);
}
| 2.53125 | 3 |
2024-11-18T18:56:55.073261+00:00 | 2020-10-29T14:15:02 | f0bf58372d5b470b6ddac2a7d703f07e65896493 | {
"blob_id": "f0bf58372d5b470b6ddac2a7d703f07e65896493",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-29T14:15:02",
"content_id": "fffdf8ce9784a6c069f4a38613c5f73bca0e4acc",
"detected_licenses": [
"MIT"
],
"directory_id": "69e42e1dadfebdcca3e53bcbf44edd07c68ec609",
"extension": "c",
"filename": "kupyna.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 308349110,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7484,
"license": "MIT",
"license_type": "permissive",
"path": "/src/kupyna.c",
"provenance": "stackv2-0004.json.gz:32436",
"repo_name": "RestlessDream/kupyna",
"revision_date": "2020-10-29T14:15:02",
"revision_id": "b7735c084df397799adb7aa5ccdfcabe12f84a0b",
"snapshot_id": "af3c5866c6fe4fff0a98630d1e2dc932131fa00a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RestlessDream/kupyna/b7735c084df397799adb7aa5ccdfcabe12f84a0b/src/kupyna.c",
"visit_date": "2023-01-06T17:01:13.452861"
} | stackv2 | #include "kupyna.h"
#include "util.h"
#include "stdlib.h"
#include "string.h"
#include "stdio.h"
extern kupyna_config * kupyna;
extern const size_t rows_count;
extern size_t byte_size;
extern const byte s_box[4][16][16];
extern size_t s_box_dimensions;
extern byte mds_matrix[8][8];
/**
* For inputed message returns digest
*
* @param msg - input message
* @param blocks - message block size
* @param out - message digest
*/
void hash(dw * msg, size_t blocks, dw * out) {
dw * state = (dw *) malloc(rows_count * kupyna->state_rows);
dw * t1 = (dw *) malloc(rows_count * kupyna->state_rows);
dw * t2 = (dw *) malloc(rows_count * kupyna->state_rows);
dw * cur_msg;
memset(state, 0, rows_count * kupyna->state_rows);
((byte *)&state[0])[0] = 0x80;
if (kupyna->block_size == 512) {
((byte *)&state[0])[0] >>= 1;
}
for (int i = 0; i < blocks; i++) {
cur_msg = msg + i * kupyna->block_dwsize;
xor_arr(t1, state, cur_msg);
memcpy(t2, cur_msg, kupyna->block_bsize);
t_map_xor(t1);
t_map_add(t2);
xor_3arr(state, state, t1, t2);
}
memcpy(t1, state, kupyna->block_bsize);
t_map_xor(t1);
xor_arr(state, state, t1);
memcpy(out, state, kupyna->message_diggest_bsize);
free(state);
free(t1);
free(t2);
}
/**
* T xor transformation
*
* @param state - state matrix
*/
void t_map_xor(dw * state) {
for (size_t i = 0; i < kupyna->rounds; i++) {
xor_round_key(state, i);
sub_bytes(state);
shift_rows(state);
mix_columns(state);
}
}
/**
* T add transformation
*
* @param state - state matrix
*/
void t_map_add(dw * state) {
for (size_t i = 0; i < kupyna->rounds; i++) {
add_round_key(state, i);
sub_bytes(state);
shift_rows(state);
mix_columns(state);
}
}
/**
* Realization of sub bytes
*
* @param state - state matrix
*/
void sub_bytes(dw * state) {
for (size_t clmn = 0; clmn < kupyna->state_rows; clmn++) {
byte * state_clmn = (byte *)&state[clmn];
for (size_t row = 0; row < rows_count; row++) {
state_clmn[row] = s_box[row % s_box_dimensions][high_bits(state_clmn[row])]
[low_bits(state_clmn[row])];
}
}
}
/**
* Realization of shift rows
*
* @param state - state matrix
*/
void shift_rows(dw * state) {
size_t i;
for (i = 0; i < rows_count - 1; i++) {
size_t shift_s = i;
for (int j = 0; j < shift_s; j++) {
byte swp = ((byte *)&state[kupyna->state_rows - 1])[i];
for (int k = kupyna->state_rows - 1; k > 0; k--) {
((byte *)&state[k])[i] = ((byte *)&state[k - 1])[i];
}
((byte *)&state[0])[i] = swp;
}
}
size_t shift_s = kupyna->block_size == 512 ? i : 11;
for (int j = 0; j < shift_s; j++) {
byte swp = ((byte *)&state[kupyna->state_rows - 1])[i];
for (int k = kupyna->state_rows - 1; k > 0; k--) {
((byte *)&state[k])[i] = ((byte *)&state[k - 1])[i];
}
((byte *)&state[0])[i] = swp;
}
}
/**
* Realization of mix columns
*
* @param state - state matrix
*/
void mix_columns(dw * state) {
matrix_multiply(state, mds_matrix);
}
/**
* Realization of xor round key
*
* @param dest - xor destination
* @param state - first array
* @param msg - second array
*/
void xor_round_key(dw * state, size_t round) {
for (size_t i = 0; i < kupyna->state_rows; i++) {
((byte *)&state[i])[0] ^= (i << 4) ^ round;
}
}
/**
* Realization of add round key
*
* @param dest - xor destination
* @param state - first array
* @param msg - second array
*/
void add_round_key(dw * state, size_t round) {
for (size_t i = 0; i < kupyna->state_rows; i++) {
state[i] += 0x00F0F0F0F0F0F0F3 ^ ((kupyna->state_rows - i - 1) << 4);
}
}
/**
* Xors arrays
*
* @param dest - xor destination
* @param state - first array
* @param msg - second array
*/
void xor_arr(dw * dest, dw * state, dw * msg) {
for (size_t i = 0; i < kupyna->state_rows; i++) {
dest[i] = state[i] ^ msg[i];
}
}
/**
* Xors 3 arrays
*
* @param dest - xor destination
* @param state - first array
* @param t1 - second array
* @param t2 - third array
*/
void xor_3arr(dw * dest, dw * state, dw * t1, dw * t2) {
for (size_t i = 0; i < kupyna->state_rows; i++) {
dest[i] = state[i] ^ t1[i] ^ t2[i];
}
}
/**
* Multiply matrix in GF
*
* @param state - first matrix
* @param mat - second matrix
*
* @return - result of multiply
*/
void matrix_multiply(dw * state, uint8_t mat[8][8]) {
byte product;
dw result;
for (int col = 0; col < kupyna->state_rows; col++) {
result = 0;
for (int row = rows_count - 1; row >= 0; row--) {
product = 0;
for (int i = rows_count - 1; i >= 0; i--) {
product ^= multiplyGF(((byte *)&state[col])[i], mat[row][i]);
}
result |= (dw)product << (row * rows_count);
}
state[col] = result;
}
}
/**
* Multiply bytes in GF
*
* @param x - first byte
* @param y - second
*
* @return - result of multiply
*/
byte multiplyGF(byte x, byte y) {
byte r = 0;
byte hbit = 0;
for (size_t i = 0; i < byte_size; i++) {
if ((y & 0x1) == 1) {
r ^= x;
}
hbit = x & 0x80;
x <<= 1;
if (hbit == 0x80) {
x ^= 0x011d;
}
y >>= 1;
}
return r;
}
/**
* Padding ensures that the padded message is a miltiple of block bits.
*
* Padd message with 10..0 and number that represent size of message in block.
*
* @param msg_block - the last message block, that going to be padded;
* @param size - the whole message size.
*/
void pad_block(dw * msg_block, uint64_t size) {
size_t block_size = size % kupyna->block_size;
size_t pad_zeros = kupyna->block_size - block_size - 96;
byte * msg = (byte *) msg_block;
msg[block_size/byte_size] = 0x80;
memset(msg + block_size/byte_size + 1, 0, pad_zeros/byte_size);
for (size_t i = 0; i < 12; i++) {
if (i < sizeof(uint64_t)) {
*(msg + kupyna->block_bsize - i - 1) = ((byte *)&size)[i];
} else {
*(msg + kupyna->block_bsize - i - 1) = 0;
}
}
}
void setup(kupyna_config * kupyna_std) {
kupyna = kupyna_std;
}
/**
* Realization of proof of work
*
* @param in - input message
* @param blocks - size of message in blocks
* @param zeros_count - seeked zeros count at the begining
* @param out - seeked digest
*
* @return 0 if all OK
*/
int proof_of_work(dw * in, size_t blocks, size_t zeros_count, dw * out) {
if (zeros_count >= 64) {
return -1;
}
dw x = 0;
size_t i = 0;
do {
in[blocks * kupyna->block_dwsize + i] = x;
hash(in, blocks + 1, out);
x++;
if (x == 0xFFFFFFFFFFFFFFFF) {
i++;
}
} while(cmpbits(out[kupyna->message_diggest_bsize/sizeof(dw) - 1], 0, zeros_count) == 0);
return 0;
}
/**
* Finds out is the value v1 starts count zeros
*
* @param v1 - tested value
* @param v2 - ored value
* @return 1 - if value starts with count zeros
*/
int cmpbits(dw v1, dw v2, size_t count) {
if (((v1 | v2) & (0xFFFFFFFFFFFFFFFF >> (64 - count))) != 0) {
return 0;
}
return 1;
}
| 2.546875 | 3 |
2024-11-18T18:56:55.151121+00:00 | 2016-03-31T16:22:38 | 0574f4a564c27b293d115eaf3fd1fe804b5f569a | {
"blob_id": "0574f4a564c27b293d115eaf3fd1fe804b5f569a",
"branch_name": "refs/heads/master",
"committer_date": "2016-03-31T16:22:38",
"content_id": "b9babba1fa40c6b97af6c9fe9b0a309f66fc2a19",
"detected_licenses": [
"MIT"
],
"directory_id": "bb8867628faa6f0963b0fe0211bc936bc2a8ad60",
"extension": "c",
"filename": "primes.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32920981,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1889,
"license": "MIT",
"license_type": "permissive",
"path": "/parprog2015-lec3-src/_task/primes.c",
"provenance": "stackv2-0004.json.gz:32564",
"repo_name": "mkurnosov/course-parprog-2015",
"revision_date": "2016-03-31T16:22:38",
"revision_id": "c855cdcdb010f1fa47a6e727ae31866893009bb4",
"snapshot_id": "7f10e44dce0b0af9d5540ec4de91836b6c15ec02",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/mkurnosov/course-parprog-2015/c855cdcdb010f1fa47a6e727ae31866893009bb4/parprog2015-lec3-src/_task/primes.c",
"visit_date": "2021-01-21T04:27:24.459823"
} | stackv2 | /*
* primes.c: Example of prime numbers counting in OpenMP.
*
* (C) 2015 Mikhail Kurnosov <[email protected]>
*/
#include <stdio.h>
#include <math.h>
#include <sys/time.h>
#include <omp.h>
const int a = 1;
const int b = 20000000;
double wtime()
{
struct timeval t;
gettimeofday(&t, NULL);
return (double)t.tv_sec + (double)t.tv_usec * 1E-6;
}
/*
* is_prime_number: Returns 1 if n is a prime number and 0 otherwise.
* This function uses trial division primality test.
*/
int is_prime_number(int n)
{
int limit = sqrt(n) + 1;
for (int i = 2; i <= limit; i++) {
if (n % i == 0)
return 0;
}
return (n > 1) ? 1 : 0;
}
int count_prime_numbers(int a, int b)
{
int nprimes = 0;
/* Count '2' as a prime number */
if (a <= 2) {
nprimes = 1;
a = 2;
}
/* Shift 'a' to odd number */
if (a % 2 == 0)
a++;
/* Loop over odd numbers: a, a + 2, a + 4, ... , b */
for (int i = a; i <= b; i += 2) {
if (is_prime_number(i))
nprimes++;
}
return nprimes;
}
int count_prime_numbers_omp(int a, int b)
{
/* TODO */
}
double run_serial()
{
double t = wtime();
int n = count_prime_numbers(a, b);
t = wtime() - t;
printf("Result (serial): %d\n", n);
return t;
}
double run_parallel()
{
double t = wtime();
int n = count_prime_numbers_omp(a, b);
t = wtime() - t;
printf("Result (parallel): %d\n", n);
return t;
}
int main(int argc, char **argv)
{
printf("Count prime numbers on [%d, %d]\n", a, b);
double tserial = run_serial();
double tparallel = run_parallel();
printf("Execution time (serial): %.6f\n", tserial);
printf("Execution time (parallel): %.6f\n", tparallel);
printf("Speedup: %.2f\n", tserial / tparallel);
return 0;
}
| 3.6875 | 4 |
2024-11-18T18:56:55.411239+00:00 | 2020-04-03T01:02:33 | d5975ca6b193b5f2b7b6898167f10d48b820142f | {
"blob_id": "d5975ca6b193b5f2b7b6898167f10d48b820142f",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-03T01:02:33",
"content_id": "30200f738af85ea9095ec7b3a76c9fd4c851606c",
"detected_licenses": [
"Unlicense"
],
"directory_id": "957feaec593168a9e40491056459cf4451e6df8f",
"extension": "c",
"filename": "1b.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": 1045,
"license": "Unlicense",
"license_type": "permissive",
"path": "/Ano3/SO/set02/1b.c",
"provenance": "stackv2-0004.json.gz:32951",
"repo_name": "dannydd02/FEUP",
"revision_date": "2020-04-03T01:02:33",
"revision_id": "673a400c71f0a92510a30d864d6911902ecbd684",
"snapshot_id": "253e7da045bb8a90d02a55cffc67f670b1940c4e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dannydd02/FEUP/673a400c71f0a92510a30d864d6911902ecbd684/Ano3/SO/set02/1b.c",
"visit_date": "2022-04-15T21:13:34.651004"
} | stackv2 | #include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <common.c>
int main(int ArgCount, char *ArgVals[]) {
if(ArgCount < 3) {
char *ErrorMsg = "This program needs 2 arguments: FileToRead NewFile\n";
write(STDERR_FILENO, ErrorMsg, stringLength(ErrorMsg));
return 1;
}
int OrigFile = open(ArgVals[1], O_RDONLY);
if(OrigFile < 0) {
char *ErrorMsg = "Could not open the specified file\n";
write(STDERR_FILENO, ErrorMsg, stringLength(ErrorMsg));
return 1;
}
int DestFile = open(ArgVals[2], O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if(DestFile < 0) {
char *ErrorMsg = "Could not create new file to be written\n";
write(STDERR_FILENO, ErrorMsg, stringLength(ErrorMsg));
}
char Buffer[1<<10];
for(;;) {
int BytesRead = read(OrigFile, Buffer, arrayCount(Buffer));
if(BytesRead <= 0) {
break;
}
write(DestFile, Buffer, BytesRead);
}
return 0;
}
| 2.84375 | 3 |
2024-11-18T18:56:55.578151+00:00 | 2018-04-03T06:23:21 | 6477055be13db8a89ac76dd25602a6a86e79fe0c | {
"blob_id": "6477055be13db8a89ac76dd25602a6a86e79fe0c",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-03T06:23:21",
"content_id": "1f5f1fbf431ba9f066bd22ffa4dce0a67d46f72a",
"detected_licenses": [
"MIT"
],
"directory_id": "3714a91ae98a13ac17613f117f7b791e0ca476d4",
"extension": "c",
"filename": "h_conversions.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 118864457,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1777,
"license": "MIT",
"license_type": "permissive",
"path": "/src/conversions/h_conversions.c",
"provenance": "stackv2-0004.json.gz:33079",
"repo_name": "regien/ft_printf",
"revision_date": "2018-04-03T06:23:21",
"revision_id": "887ef8c21036997fae185029dd80a912209ff29a",
"snapshot_id": "ed9d416bdd2a3e3458f54f59ed63711ca36dfeec",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/regien/ft_printf/887ef8c21036997fae185029dd80a912209ff29a/src/conversions/h_conversions.c",
"visit_date": "2021-05-05T07:23:12.637610"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* h_conversions.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gmalpart <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/21 05:19:58 by gmalpart #+# #+# */
/* Updated: 2018/03/24 05:48:03 by gmalpart ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void f_hhexa(va_list args, t_total *e)
{
unsigned short holder;
holder = (unsigned short)va_arg(args, void*);
print_hexa((unsigned int)holder, e);
e->e = e->e - 3;
}
void f_hhexacap(va_list args, t_total *e)
{
unsigned short holder;
holder = (unsigned short)va_arg(args, void*);
print_caphexa((unsigned int)holder, e);
e->e = e->e - 3;
}
void f_hoctal(va_list args, t_total *e)
{
unsigned short holder;
holder = (unsigned short)va_arg(args, void*);
ft_putnbroct((unsigned int)holder, e);
e->e = e->e - 3;
}
void f_huint(va_list args, t_total *e)
{
unsigned short holder;
holder = (unsigned short)va_arg(args, void*);
ft_putnbruint((unsigned int)holder, e);
e->e = e->e - 3;
}
void f_hint(va_list args, t_total *e)
{
short holder;
holder = (unsigned short)va_arg(args, void*);
ft_putnbrcont((long long)holder, e);
e->e = e->e - 3;
}
| 2.28125 | 2 |
2024-11-18T18:56:55.653888+00:00 | 2019-10-03T12:01:21 | 7760c5575e3cab5c4a7ad5118426a2ae87e7e553 | {
"blob_id": "7760c5575e3cab5c4a7ad5118426a2ae87e7e553",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-03T12:01:21",
"content_id": "7439b73407f629c34f8475441434edcf36b0bf20",
"detected_licenses": [
"MIT"
],
"directory_id": "f14205a2a5958cf96f445609645e7674fdee644f",
"extension": "c",
"filename": "jni_helper.c",
"fork_events_count": 0,
"gha_created_at": "2019-10-03T12:01:06",
"gha_event_created_at": "2019-10-03T12:01:06",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 212569147,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12245,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/c/jni_helper.c",
"provenance": "stackv2-0004.json.gz:33207",
"repo_name": "Deraen/jsass",
"revision_date": "2019-10-03T12:01:21",
"revision_id": "3cf0ac92a2a268f2f6cd5b4727f7b4127bf327d7",
"snapshot_id": "babef5971143b8a91a4263e77f12c32782b7b0d8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Deraen/jsass/3cf0ac92a2a268f2f6cd5b4727f7b4127bf327d7/src/main/c/jni_helper.c",
"visit_date": "2020-08-05T14:00:13.755955"
} | stackv2 | /*
* A collection of methods that makes working with Java objects easier.
*/
/**
* Call a JNI method and return its jobject value.
*
* @param env The JNI environment.
* @param j_object The jobject to call the method on.
* @param j_class The class the method is defined in.
* @param method_name The name of the method.
* @param method_signature The signature of the method.
*
* @return The return value of the method.
*/
jobject call_class_object_method(
JNIEnv *env,
jobject j_object,
jclass j_class,
const char *method_name,
const char *method_signature
) {
jmethodID j_method = (*env)->GetMethodID(env, j_class, method_name, method_signature);
jobject result = (*env)->CallObjectMethod(env, j_object, j_method);
return result;
}
/**
* Call a JNI method and return its jstring as c string.
*
* The method will dup the methods result and release the jstring directly.
* Then it returns the duplicated c string.
*
* @param env The JNI environment.
* @param j_object The jobject to call the method on.
* @param j_class The class the method is defined in.
* @param method_name The name of the method.
*
* @return The return value of the method.
*/
char *call_class_string_method(
JNIEnv *env,
jobject j_object,
jclass j_class,
const char *method_name
) {
const char *method_signature = "()Ljava/lang/String;";
jmethodID j_method = (*env)->GetMethodID(env, j_class, method_name, method_signature);
jobject j_result = (*env)->CallObjectMethod(env, j_object, j_method);
char *c_string;
if (j_result) {
const char *c_temp = (*env)->GetStringUTFChars(env, j_result, 0);
c_string = strdup(c_temp);
(*env)->ReleaseStringUTFChars(env, j_result, c_temp);
} else {
c_string = strdup("");
}
return c_string;
}
/**
* Call a JNI method and return its char value.
*
* @param env The JNI environment.
* @param j_object The jobject to call the method on.
* @param j_class The class the method is defined in.
* @param method_name The name of the method.
*
* @return The return value of the method.
*/
char call_class_char_method(
JNIEnv *env,
jobject j_object,
jclass j_class,
const char *method_name
) {
const char *method_signature = "()C";
jmethodID j_method = (*env)->GetMethodID(env, j_class, method_name, method_signature);
char result = (char) (*env)->CallCharMethod(env, j_object, j_method);
return result;
}
/**
* Call a JNI method and return its boolean value.
*
* @param env The JNI environment.
* @param j_object The jobject to call the method on.
* @param j_class The class the method is defined in.
* @param method_name The name of the method.
*
* @return The return value of the method.
*/
bool call_class_boolean_method(
JNIEnv *env,
jobject j_object,
jclass j_class,
const char *method_name
) {
const char *method_signature = "()Z";
jmethodID j_method = (*env)->GetMethodID(env, j_class, method_name, method_signature);
bool result = (*env)->CallBooleanMethod(env, j_object, j_method);
return result;
}
/**
* Call a JNI method and return its int value.
*
* @param env The JNI environment.
* @param j_object The jobject to call the method on.
* @param j_class The class the method is defined in.
* @param method_name The name of the method.
*
* @return The return value of the method.
*/
int call_class_int_method(
JNIEnv *env,
jobject j_object,
jclass j_class,
const char *method_name
) {
const char *method_signature = "()I";
jmethodID j_method = (*env)->GetMethodID(env, j_class, method_name, method_signature);
int result = (*env)->CallIntMethod(env, j_object, j_method);
return result;
}
/**
* Call a JNI method and return its double value.
*
* @param env The JNI environment.
* @param j_object The jobject to call the method on.
* @param j_class The class the method is defined in.
* @param method_name The name of the method.
*
* @return The return value of the method.
*/
double call_class_double_method(
JNIEnv *env,
jobject j_object,
jclass j_class,
const char *method_name
) {
const char *method_signature = "()D";
jmethodID j_method = (*env)->GetMethodID(env, j_class, method_name, method_signature);
double result = (*env)->CallDoubleMethod(env, j_object, j_method);
return result;
}
/**
* Call a JNI method and return its jobject value.
*
* The jclass is derived from the jobject.
*
* @param env The JNI environment.
* @param j_object The jobject to call the method on.
* @param method_name The name of the method.
* @param method_signature The signature of the method.
*
* @return The return value of the method.
*/
jobject call_object_method(
JNIEnv *env,
jobject j_object,
const char *method_name,
const char *method_signature
) {
jclass j_class = (*env)->GetObjectClass(env, j_object);
jobject result = call_class_object_method(env, j_object, j_class, method_name, method_signature);
(*env)->DeleteLocalRef(env, j_class);
return result;
}
/**
* Call a JNI method and return its jstring as c string.
*
* The jclass is derived from the jobject.
*
* The method will dup the methods result and release the jstring directly.
* Then it returns the duplicated c string.
*
* @param env The JNI environment.
* @param j_object The jobject to call the method on.
* @param method_name The name of the method.
*
* @return The return value of the method.
*/
char *call_string_method(
JNIEnv *env,
jobject j_object,
const char *method_name
) {
jclass j_class = (*env)->GetObjectClass(env, j_object);
char *result = call_class_string_method(env, j_object, j_class, method_name);
(*env)->DeleteLocalRef(env, j_class);
return result;
}
/**
* Call a JNI method and return its boolean value.
*
* The jclass is derived from the jobject.
*
* @param env The JNI environment.
* @param j_object The jobject to call the method on.
* @param method_name The name of the method.
*
* @return The return value of the method.
*/
bool call_boolean_method(
JNIEnv *env,
jobject j_object,
const char *method_name
) {
jclass j_class = (*env)->GetObjectClass(env, j_object);
bool result = call_class_boolean_method(env, j_object, j_class, method_name);
(*env)->DeleteLocalRef(env, j_class);
return result;
}
/**
* Return a jobject property value.
*
* @param env The JNI environment.
* @param j_object The jobject to call get the property value from.
* @param j_class The class the property is defined in.
* @param property_name The name of the property.
*
* @return The return value of the property.
*/
jobject get_class_object_property(
JNIEnv *env,
jobject j_object,
jclass j_class,
const char *property_name,
const char *property_signature
) {
jfieldID j_field = (*env)->GetFieldID(env, j_class, property_name, property_signature);
jobject j_result = (*env)->GetObjectField(env, j_object, j_field);
return j_result;
}
/**
* Return a jstring property value as c string.
*
* The method will dup the property value and release the jstring directly.
* Then it returns the duplicated c string.
*
* @param env The JNI environment.
* @param j_object The jobject to call get the property value from.
* @param j_field The field id of the property.
*
* @return The return value of the property.
*/
char *get_field_string(
JNIEnv *env,
jobject j_object,
jfieldID j_field
) {
jobject j_result = (*env)->GetObjectField(env, j_object, j_field);
char *c_string;
if (j_result) {
const char *c_temp = (*env)->GetStringUTFChars(env, j_result, 0);
c_string = strdup(c_temp);
(*env)->ReleaseStringUTFChars(env, j_result, c_temp);
} else {
c_string = strdup("");
}
return c_string;
}
/**
* Return a jstring property value as c string.
*
* The method will dup the property value and release the jstring directly.
* Then it returns the duplicated c string.
*
* @param env The JNI environment.
* @param j_object The jobject to call get the property value from.
* @param j_class The class the property is defined in.
* @param property_name The name of the property.
*
* @return The return value of the property.
*/
char *get_class_string_property(
JNIEnv *env,
jobject j_object,
jclass j_class,
const char *property_name
) {
const char *property_signature = "Ljava/lang/String;";
jfieldID j_field = (*env)->GetFieldID(env, j_class, property_name, property_signature);
jobject j_result = (*env)->GetObjectField(env, j_object, j_field);
char *c_string;
if (j_result) {
const char *c_temp = (*env)->GetStringUTFChars(env, j_result, 0);
c_string = strdup(c_temp);
(*env)->ReleaseStringUTFChars(env, j_result, c_temp);
} else {
c_string = strdup("");
}
return c_string;
}
/**
* Return a boolean property value.
*
* @param env The JNI environment.
* @param j_object The jobject to call get the property value from.
* @param j_class The class the property is defined in.
* @param property_name The name of the property.
*
* @return The return value of the property.
*/
bool get_class_bool_property(
JNIEnv *env,
jobject j_object,
jclass j_class,
const char *property_name
) {
const char *property_signature = "Z";
jfieldID j_field = (*env)->GetFieldID(env, j_class, property_name, property_signature);
jboolean j_result = (*env)->GetBooleanField(env, j_object, j_field);
return j_result;
}
/**
* Return a int property value.
*
* @param env The JNI environment.
* @param j_object The jobject to call get the property value from.
* @param j_class The class the property is defined in.
* @param property_name The name of the property.
*
* @return The return value of the property.
*/
int get_class_int_property(
JNIEnv *env,
jobject j_object,
jclass j_class,
const char *property_name
) {
const char *property_signature = "I";
jfieldID j_field = (*env)->GetFieldID(env, j_class, property_name, property_signature);
jint j_result = (*env)->GetIntField(env, j_object, j_field);
return j_result;
}
/**
* Return a jobject property value.
*
* @param env The JNI environment.
* @param j_object The jobject to call get the property value from.
* @param property_name The name of the property.
*
* @return The return value of the property.
*/
jobject get_object_property(
JNIEnv *env,
jobject j_object,
const char *property_name,
const char *property_signature
) {
jclass j_class = (*env)->GetObjectClass(env, j_object);
jobject j_result = get_class_object_property(env, j_object, j_class, property_name, property_signature);
(*env)->DeleteLocalRef(env, j_class);
return j_result;
}
/**
* Return a jstring property value as c string.
*
* The method will dup the property value and release the jstring directly.
* Then it returns the duplicated c string.
*
* @param env The JNI environment.
* @param j_object The jobject to call get the property value from.
* @param j_class The class the property is defined in.
* @param property_name The name of the property.
*
* @return The return value of the property.
*/
char *get_string_property(
JNIEnv *env,
jobject j_object,
const char *property_name
) {
jclass j_class = (*env)->GetObjectClass(env, j_object);
char* c_result = get_class_string_property(env, j_object, j_class, property_name);
(*env)->DeleteLocalRef(env, j_class);
return c_result;
}
| 2.734375 | 3 |
2024-11-18T18:56:55.866768+00:00 | 2020-10-28T15:19:19 | 10c4ad0ee91db73b582044a9481176a7b886fe38 | {
"blob_id": "10c4ad0ee91db73b582044a9481176a7b886fe38",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-28T15:19:19",
"content_id": "217aa0666ac86652d61a57bd7af1f057d7ec159b",
"detected_licenses": [
"MIT"
],
"directory_id": "fad58cf239c9aaa146710ab33e77473d750ff142",
"extension": "c",
"filename": "primele_n_numere_prime.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 213328816,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 559,
"license": "MIT",
"license_type": "permissive",
"path": "/Lectia 1/Probleme grele/primele_n_numere_prime.c",
"provenance": "stackv2-0004.json.gz:33463",
"repo_name": "georgescubogdan/programare-pentru-toti",
"revision_date": "2020-10-28T15:19:19",
"revision_id": "114c46c33a1c5b3aab97cc7efd27a0cd31ef68b7",
"snapshot_id": "1ff081e8206d92bc6a2a8eff5e304fcab01e5810",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/georgescubogdan/programare-pentru-toti/114c46c33a1c5b3aab97cc7efd27a0cd31ef68b7/Lectia 1/Probleme grele/primele_n_numere_prime.c",
"visit_date": "2021-07-11T02:32:48.070728"
} | stackv2 | /**
* Gasirea primelor n numere prime.
*
* Authors: PPT Team
**/
#include<stdio.h>
int main()
{
int n, i = 3, count, c;
printf("Numarul de numere prime dorit: ");
scanf("%d", &n);
if (n >= 1)
{
printf("Primele %d numere prime sunt: ", n);
printf("2 ");
}
for (count = 2; count <= n; i++) {
for(c = 2; c < i; c++) {
if(i%c == 0)
break;
}
if (c == i) {
printf("%d ", i);
count++;
}
}
printf("\n");
return 0;
} | 3.4375 | 3 |
2024-11-18T18:56:55.929099+00:00 | 2019-07-26T10:51:36 | 8ce42cd1214629b24494935f48c574ebeed84031 | {
"blob_id": "8ce42cd1214629b24494935f48c574ebeed84031",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-26T10:51:36",
"content_id": "d8135a5c9df337d6499fa843b69d15d8a52b212d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b0c5308bfa8770d2b447f8bd859b7fdf84e2882d",
"extension": "c",
"filename": "base_64.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 192253166,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5795,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/core/base_64.c",
"provenance": "stackv2-0004.json.gz:33591",
"repo_name": "SABERYJS/tiny-http-server",
"revision_date": "2019-07-26T10:51:36",
"revision_id": "884fe2a193f323cacbed71cdf62228ed1cc6dc2e",
"snapshot_id": "c265d87c5cac4fcd96aa59b1618fb8f5d2affe8e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SABERYJS/tiny-http-server/884fe2a193f323cacbed71cdf62228ed1cc6dc2e/src/core/base_64.c",
"visit_date": "2020-06-05T00:37:21.744532"
} | stackv2 | /*Copyright (c) 2019 , [email protected]
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. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by the <organization>.
4. Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''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 <COPYRIGHT HOLDER> 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 "base_64.h"
/**
* normal char map to encoded char
* **/
static char Base64CharMap(short c) {
if (c >= 0 && c <= 25) {
return 'A' + c;
} else if (c >= 26 && c <= 51) {
return 'a' + (c - 26);
} else if (c >= 52 && c <= 61) {
return '0' + (c - 52);
} else if (c == 62) {
return '+';
} else {
return '/';
}
}
static short Base64CharDecode(char c) {
if (c >= 'A' && c <= 'Z') {
return c - 'A';
} else if (c >= 'a' && c <= 'z') {
return c - 'a' + 26;
} else if (c >= '0' && c <= '9') {
return c - '0' + 52;
} else if (c == '+') {
return 62;
} else {
return 63;
}
}
char *Base64Encrypt(char *src, size_t len) {
unsigned int m = 0, n = 0, k = 0, a = 0;//32 bits
int cycle = len / 3;
int left = len % 3;
int equalCount = (left == 0 ? 0 : (left == 1 ? 2 : 1));
int memLen = cycle * 4 + (left == 0 ? 0 : (left == 1 ? 2 : 3)) + 1 + equalCount;//tail char '\0'
char *buf;
int i, j = 0;
if (!(buf = MemAlloc(memLen))) {
return NULL;
} else {
for (i = 0; i < cycle; i++) {
m = n = k = 0;
m = ((m | src[3 * i + 0]) << 16);
n = ((n | src[3 * i + 1]) << 8);
k = ((k | src[3 * i + 2]) << 0);
a = m | n | k;
buf[j++] = Base64CharMap((a & MASK_FOURTH_CHAR) >> 18);
buf[j++] = Base64CharMap((a & MASK_THIRD_CHAR) >> 12);
buf[j++] = (Base64CharMap((a & MASK_SECOND_CHAR) >> 6));
buf[j++] = Base64CharMap((a & MASK_FIRST_CHAR) >> 0);
}
if (left > 0) {
if (left == 1) {
//need extra 4 bits (0)
unsigned short s = 0;
s = src[len - 1] << 4;
buf[j++] = Base64CharMap(s >> 6);
buf[j++] = Base64CharMap(s & MASK_FIRST_CHAR);
} else {
//left=2,so filling 2 bits
unsigned int s = 0;
m = src[len - 2] << 8;
n = src[len - 1] << 0;
s = (m | n) << 2;
buf[j++] = Base64CharMap((s & MASK_THIRD_CHAR) >> 12);
buf[j++] = Base64CharMap((s & MASK_SECOND_CHAR) >> 6);
buf[j++] = Base64CharMap((s & MASK_FIRST_CHAR) >> 0);
}
buf[j++] = '=';
if (equalCount == 2) {
buf[j++] = '=';
}
}
return buf;
}
}
char *Base64Decrypt(char *src, size_t len) {
unsigned int m = 0, n = 0, k = 0, h = 0, a = 0;//32 bits
int equalCount = 0;
if (src[len - 1] == '=') {
equalCount++;
}
if (src[len - 2] == '=') {
equalCount++;
}
len -= equalCount;
int cycle = len / 4;
int left = len % 4;
int memLen = cycle * 3 + (left == 0 ? 0 : (left == 2 ? 1 : 2)) + 1;//tail char '\0'
char *buf;
int i, j = 0;
if (!(buf = MemAlloc(memLen))) {
return NULL;
} else {
for (i = 0; i < cycle; i++) {
m = n = k = h = 0;
m = ((m | Base64CharDecode(src[4 * i + 0])) << 18);
n = ((n | Base64CharDecode(src[4 * i + 1])) << 12);
k = ((k | Base64CharDecode(src[4 * i + 2])) << 6);
h = ((h | Base64CharDecode(src[4 * i + 3])) << 0);
a = m | n | k | h;
buf[j++] = (a & BASE64_DECODE_MASK_THIRD) >> 16;
buf[j++] = (a & BASE64_DECODE_MASK_SECOND) >> 8;
buf[j++] = (a & BASE64_DECODE_MASK_FIRST) >> 0;
}
if (left > 0) {
if (left == 2) {
unsigned char s;
s = ((Base64CharDecode(src[len - 2]) << 6) | (Base64CharDecode(src[len - 1]) << 0)) >> 4;
buf[j] = s;
} else {
unsigned int s;
s = ((Base64CharDecode(src[len - 3]) << 12) | (Base64CharDecode(src[len - 2]) << 6) |
(Base64CharDecode(src[len - 1]) << 0)) >> 2;
buf[j++] = s >> 8;
buf[j] = s & BASE64_DECODE_MASK_FIRST;
}
}
return buf;
}
} | 2.15625 | 2 |
2024-11-18T18:56:56.541929+00:00 | 2021-06-28T18:29:27 | 578b0b93ff977cef4c962eee69e536a4f97e4025 | {
"blob_id": "578b0b93ff977cef4c962eee69e536a4f97e4025",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-28T18:29:27",
"content_id": "a6e1b72c785da70d26ec6e771718b1a928c4c7e9",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "80c5cd87efd9a6069c81d4927edce35f752d4dd0",
"extension": "h",
"filename": "pthread_once.h",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 255646341,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1678,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/fake_pthread/include/pthread_once.h",
"provenance": "stackv2-0004.json.gz:33847",
"repo_name": "raytheonbbn/weldr",
"revision_date": "2021-06-28T18:29:27",
"revision_id": "88b0ad7104a305745490c33eb67afd6ee5871feb",
"snapshot_id": "2f2b0cfcee334885864f517d7dfe0f998f8be74d",
"src_encoding": "UTF-8",
"star_events_count": 18,
"url": "https://raw.githubusercontent.com/raytheonbbn/weldr/88b0ad7104a305745490c33eb67afd6ee5871feb/fake_pthread/include/pthread_once.h",
"visit_date": "2023-06-03T19:15:58.298224"
} | stackv2 | // Copyright (c) 2019, Raytheon BBN Technologies, Inc. All Rights Reserved.
//
// This document does not contain technology or Technical Data controlled under either
// the U.S. International Traffic in Arms Regulations or the U.S. Export Administration
//
// Distribution A: Approved for Public Release, Distribution Unlimited
#ifndef __PTHREAD_ONCE_H__
#define __PTHREAD_ONCE_H__
#include "pthread_shared.h"
//Definitions for fake_pthread_once
//Coordinator type for fake_pthread_once.
typedef int pthread_once_t;
//Constant initializer for fake_pthread_once_t;
//The _only_ way to initialize fake_pthread_once_t
//is to execute "pthread_once_t once = PTHREAD_ONCE_INIT";
#define PTHREAD_ONCE_INIT 0;
//Call a function exactly once across multiple threads.
//
//pthread_once attempts to invoke a function (via the init_routine)
//pointer. Behavior depends on the value stored in once_control;
//If this is the first thread to call fake_pthread_once with a given
//once_control object, init_routine is executed normally,
//after which the call to fake_pthread_once returns 0.
//If any other thread tries afterwards to execute fake_pthread_once with the same
//once_control object, fake_pthread_once returns immediately with a value of -1.
int fake_pthread_once(pthread_once_t *once_control, void(*init_routine)());
//Design:
//
//For our implementation, this doesn't need to be complicated.
//Since all control flow is serialized, fake_pthread_once_t
//can be as simple as an int. If no one's called fake_pthread_once
//on that once_control, the int will be 0. fake_pthread_once will
//set the int to 1, notifying all future calls that they should
//turn back.
#endif
| 2.140625 | 2 |
2024-11-18T18:56:56.621575+00:00 | 2021-04-04T07:56:39 | 8e1cd9c9130ece0466035606f5baceb4ce3adb6f | {
"blob_id": "8e1cd9c9130ece0466035606f5baceb4ce3adb6f",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-04T07:56:39",
"content_id": "94c5c2a8b732e587a0ced6407867a7d1c363760c",
"detected_licenses": [
"MIT"
],
"directory_id": "feb08124b75d9115f87444fcc00d685e9a11d7a4",
"extension": "c",
"filename": "podzol.c",
"fork_events_count": 0,
"gha_created_at": "2021-03-10T18:26:54",
"gha_event_created_at": "2021-03-10T18:26:55",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 346453201,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 479,
"license": "MIT",
"license_type": "permissive",
"path": "/src/block/podzol.c",
"provenance": "stackv2-0004.json.gz:33975",
"repo_name": "12Me21/minecraft-weekend",
"revision_date": "2021-04-04T07:56:39",
"revision_id": "77ec121b0b144610ddf8677205535f73314d6246",
"snapshot_id": "9004277a5b5b521b4105f0dcaefd9299c34d51a7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/12Me21/minecraft-weekend/77ec121b0b144610ddf8677205535f73314d6246/src/block/podzol.c",
"visit_date": "2023-03-29T00:12:29.188350"
} | stackv2 | #include "block.h"
static ivec2s get_texture_location(struct World *world, ivec3s pos, enum Direction d) {
switch (d) {
case UP:
return (ivec2s) {{ 4, 2 }};
case DOWN:
return (ivec2s) {{ 2, 0 }};
default:
return (ivec2s) {{ 5, 2 }};
}
}
void podzol_init() {
struct Block podzol = BLOCK_DEFAULT;
podzol.id = PODZOL;
podzol.get_texture_location = get_texture_location;
BLOCKS[PODZOL] = podzol;
} | 2.3125 | 2 |
2024-11-18T18:56:56.779092+00:00 | 2017-02-24T06:42:07 | db90396728d43834d394ea4c8fd9a216ec018d81 | {
"blob_id": "db90396728d43834d394ea4c8fd9a216ec018d81",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-24T06:42:07",
"content_id": "4e69485a8b6c297ea3aa612767357d582858723d",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "376a6fb2352781643d84f69027762eab3271e3ed",
"extension": "c",
"filename": "runprogram.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 83009717,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2974,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/os161-1.11/kern/userprog/runprogram.c",
"provenance": "stackv2-0004.json.gz:34103",
"repo_name": "prasadk27/OS-161-Projects",
"revision_date": "2017-02-24T06:42:07",
"revision_id": "092bcc173ee82c86b72ed1de538bc79bce9a83a0",
"snapshot_id": "ba07ddba57529fb7aee523a1a211a7ce7fc88527",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/prasadk27/OS-161-Projects/092bcc173ee82c86b72ed1de538bc79bce9a83a0/os161-1.11/kern/userprog/runprogram.c",
"visit_date": "2020-04-06T04:11:59.086220"
} | stackv2 | /*
* Sample/test code for running a user program. You can use this for
* reference when implementing the execv() system call. Remember though
* that execv() needs to do more than this function does.
*/
#include <types.h>
#include <kern/unistd.h>
#include <kern/errno.h>
#include <lib.h>
#include <addrspace.h>
#include <thread.h>
#include <curthread.h>
#include <vm.h>
#include <vfs.h>
#include <test.h>
/*
* Load program "progname" and start running it in usermode.
* Does not return except on error.
*
* Calls vfs_open on progname and thus may destroy it.
*/
int runprogram(char *progname, char ** args, unsigned long nargs) {
vaddr_t entrypoint, stackptr;
int result;
/* We should be a new thread. */
assert(curthread->t_vmspace == NULL);
/* Create a new address space. */
curthread->t_vmspace = as_create();
if (curthread->t_vmspace == NULL) {
return ENOMEM;
}
/* Activate it. */
as_activate(curthread->t_vmspace);
assert(curthread->t_vmspace != NULL);
/* Load the executable. */
result = load_elf(progname, &entrypoint);
if (result) {
/* thread_exit destroys curthread->t_vmspace */
return result;
}
/* Define the user stack in the address space */
result = as_define_stack(curthread->t_vmspace, &stackptr);
if (result) {
/* thread_exit destroys curthread->t_vmspace */
return result;
}
/* calculate the size of the stack frame for the main() function */
int stackFrameSize = 8; //minimum size for argc=0, argv[0]=NULL
unsigned long i;
for (i = 0; i < nargs; i++) {
stackFrameSize += strlen(args[i]) + 1 + 4; //add the length of each argument, plus the space for the pointer
}
/* Decide the stackpointer address */
stackptr -= stackFrameSize;
//decrement the stackptr until it is divisible by 8
for (; (stackptr % 8) > 0; stackptr--) {
}
/* copy the arguments to the proper location on the stack */
int argumentStringLocation = (int) stackptr + 4 + ((nargs + 1) * 4); //begining of where strings will be stored
copyout((void *) & nargs, (userptr_t) stackptr, (size_t) 4); //copy argc
for (i = 0; i < nargs; i++) {
copyout((void *) & argumentStringLocation, (userptr_t) (stackptr + 4 + (4 * i)), (size_t) 4); //copy address of string into argv[i+1]
copyoutstr(args[i], (userptr_t) argumentStringLocation, (size_t) strlen(args[i]), NULL); //copy the argument string
argumentStringLocation += strlen(args[i]) + 1; //update the location for the next iteration
}
int *nullValue = NULL;
copyout((void *) & nullValue, (userptr_t) (stackptr + 4 + (4 * i)), (size_t) 4); //copy null into last position of argv
md_usermode(nargs /*argc*/, (userptr_t) (stackptr + 4) /*userspace addr of argv*/, stackptr, entrypoint);
/* md_usermode does not return */
panic("md_usermode returned\n");
return EINVAL;
}
| 2.890625 | 3 |
2024-11-18T18:56:57.057253+00:00 | 2020-02-22T18:44:45 | 18936ca320f92b1bf1e0905dea8d8a372b8618cf | {
"blob_id": "18936ca320f92b1bf1e0905dea8d8a372b8618cf",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-22T18:44:45",
"content_id": "e7ae519f6d47cf16a566216d98dfecab60b35859",
"detected_licenses": [
"MIT"
],
"directory_id": "03864d4ab05c15e7bb87a25590ac752d3ccf0c5c",
"extension": "c",
"filename": "RamDisk.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 223035300,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6658,
"license": "MIT",
"license_type": "permissive",
"path": "/GodHands/GodHands/Source/System/RamDisk/RamDisk.c",
"provenance": "stackv2-0004.json.gz:34360",
"repo_name": "collinsmichael/GodHands",
"revision_date": "2020-02-22T18:44:45",
"revision_id": "d4523ec83e7c9dac9199b67f365cf44b69c1a5b2",
"snapshot_id": "456aca678a982eba28c00eacd58a5e0f190fc59c",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/collinsmichael/GodHands/d4523ec83e7c9dac9199b67f365cf44b69c1a5b2/GodHands/GodHands/Source/System/RamDisk/RamDisk.c",
"visit_date": "2020-09-14T05:38:34.190627"
} | stackv2 | /* ************************************************************************** */
/* Implements in-memory file system. */
/* Uses lazy loading when reading from Disk */
/* All changes are immediately committed to to disk. */
/* ************************************************************************** */
#include <memory.h>
#include <windows.h>
#include "GodHands.h"
extern struct SYSTEM System;
extern struct LOGGER Logger;
extern struct JOBQUEUE JobQueue;
static char disk[0x26F57800];
static char map[0x4DEAF];
static void *file;
static int size;
static int is_iso;
static int consumed;
static int total;
static int RamDisk_Read(int lba, int len) {
int pos;
if (!file) return Logger.Fail("RamDisk.Read", "No disk");
if ((lba < 0) || (lba+len > size)) {
return Logger.Fail("RamDisk.Read", "Out of bounds lba=%08X", lba);
}
for (pos = 0; pos < len; pos++, lba++) {
if (map[lba] == ' ') {
DWORD word;
if (is_iso) {
SetFilePointer(file, lba*2*KB, 0, 0);
} else {
SetFilePointer(file, lba*2352 + 24, 0, 0);
}
if (!ReadFile(file, &disk[lba*2*KB], 2*KB, &word, 0)) {
return Logger.Error("RamDisk.Read", "Failed lba=%08X", lba);
}
map[lba] = 'x';
}
}
return Logger.Done("RamDisk.Read", "Done");
}
static int RamDisk_Write(int lba, int len) {
int pos;
if (!file) return Logger.Fail("RamDisk.Write", "No disk");
if ((lba < 0) || (lba+len > size)) {
return Logger.Fail("RamDisk.Write", "Out of bounds lba=%08X", lba);
}
for (pos = 0; pos < len; pos++) {
DWORD word;
if (is_iso) {
SetFilePointer(file, lba*2*KB, 0, 0);
} else {
SetFilePointer(file, lba*2352 + 24, 0, 0);
}
if (!WriteFile(file, &disk[lba*2*KB], 2*KB, &word, 0)) {
return Logger.Error("RamDisk.Write", "Failed lba=%08X", lba);
}
map[lba] = 'x';
}
return Logger.Done("RamDisk.Write", "Done");
}
static int RamDisk_Scan(int lba) {
int pos;
if (!file) return Logger.Fail("RamDisk.Scan", "No disk");
if ((lba < 0) || (lba >= size)) {
return Logger.Fail("RamDisk.Scan", "Out of bounds lba=%08X", lba);
}
if (map[lba] == ' ') {
DWORD word;
char mark;
if (is_iso) {
SetFilePointer(file, lba*2*KB, 0, 0);
} else {
SetFilePointer(file, lba*2352 + 24, 0, 0);
}
if (!ReadFile(file, &disk[lba*2*KB], 2*KB, &word, 0)) {
return Logger.Error("RamDisk.Scan", "Failed lba=%08X", lba);
}
mark = '-';
for (pos = 0; pos < 2*KB; pos++) {
if (disk[lba*2*KB + pos] != 0x00) {
mark = 'H';
break;
}
}
map[lba] = mark;
}
return Logger.Done("RamDisk.Scan", "Done");
}
static int RamDisk_Clear(int lba, int len) {
int pos;
if (!file) return Logger.Fail("RamDisk.Clear", "No disk");
if ((lba < 0) || (lba+len > size)) {
return Logger.Fail("RamDisk.Clear", "Out of bounds lba=%08X", lba);
}
stosd(&disk[lba*2*KB], 0, len*2*KB/4);
for (pos = 0; pos < len; pos++, lba++) {
DWORD word;
if (is_iso) {
SetFilePointer(file, lba*2*KB, 0, 0);
} else {
SetFilePointer(file, lba*2352 + 24, 0, 0);
}
if (!WriteFile(file, &disk[lba*2*KB], 2*KB, &word, 0)) {
return Logger.Error("RamDisk.Clear", "Failed lba=%08X", lba);
}
map[lba] = '-';
}
return Logger.Done("RamDisk.Clear", "Done");
}
static int RamDisk_Close(void) {
if ((file != 0) && (file != INVALID_HANDLE_VALUE)) {
System.Reset();
CloseHandle(file);
}
file = 0;
size = 0;
is_iso = 0;
stosd(map, 0x20202020, sizeof(map)/4);
stosd(disk, 0, sizeof(disk)/4);
return Logger.Done("RamDisk.Close", "Done");
}
static int RamDisk_Reset(void) {
RamDisk_Close();
return Logger.Done("RamDisk.Reset", "Done");
}
static int RamDisk_Open(char *path) {
static char sync[] = "\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x00";
char buf[16];
DWORD word;
RamDisk_Close();
file = CreateFileA(path, 0xC0000000, 0x03,0,0x03,0x80,0);
if (file == INVALID_HANDLE_VALUE) {
return Logger.Error("RamDisk.Open", "File not found %s", path);
}
SetFilePointer(file, 0, 0, 0);
if (!ReadFile(file, buf, 16, &word, 0)) {
RamDisk_Close();
return Logger.Fail("RamDisk.Open", "File is Read Only");
}
size = GetFileSize(file, 0);
if (cmpsd(buf, sync, sizeof(sync)/4) == 0) {
is_iso = 0;
if ((size % 2352) != 0) {
Logger.Warn("RamDisk.Open", "Not aligned to sector boundary");
}
size = size/2352;
} else {
is_iso = 1;
if ((size % (2*KB)) != 0) {
Logger.Warn("RamDisk.Open", "Not aligned to sector boundary");
}
size = size/(2*KB);
}
if (size > sizeof(disk)) {
RamDisk_Close();
return Logger.Fail("RamDisk.Open", "File too large %s", path);
}
return Logger.Done("RamDisk.Open", "Done");
}
static char *RamDisk_AddressOf(int lba) {
if ((!file) || (lba < 0) || (lba >= size)) return 0;
return &disk[lba*2*KB];
}
static int RamDisk_SaveMap(char *path) {
int i;
void *file = CreateFileA(path, 0xC0000000, 0x03,0,0x02,0x80,0);
if (file == INVALID_HANDLE_VALUE) {
return Logger.Error("RamDisk.SaveMap", "File not created %s", path);
}
SetFilePointer(file, 0, 0, 0);
for (i = 0; i < size; i += 64) {
DWORD word;
char newline = '\n';
int len = (i + 64 > size) ? size-i : 64;
if (!WriteFile(file, &map[i], len, &word, 0)) {
return Logger.Fail("RamDisk.SaveMap", "File is Read Only");
}
if (!WriteFile(file, &newline, 1, &word, 0)) {
return Logger.Fail("RamDisk.SaveMap", "File is Read Only");
}
}
return Logger.Done("RamDisk.SaveMap", "Done");
}
struct RAMDISK RamDisk = {
RamDisk_Reset,
RamDisk_Open,
RamDisk_Close,
RamDisk_Read,
RamDisk_Write,
RamDisk_Scan,
RamDisk_Clear,
RamDisk_AddressOf,
RamDisk_SaveMap
};
| 2.25 | 2 |
2024-11-18T18:56:57.159498+00:00 | 2020-11-23T15:35:39 | d625157b9bd0901e220147335a6398d4473a0530 | {
"blob_id": "d625157b9bd0901e220147335a6398d4473a0530",
"branch_name": "refs/heads/main",
"committer_date": "2020-11-23T15:35:39",
"content_id": "5bc1fa6f3b216f238b414cdb027e1b6b8a0aa709",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "08e7524268c42aafc49a9642d4b18d86bf66f6ae",
"extension": "c",
"filename": "youreditor.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 314987904,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10695,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/youreditor.c",
"provenance": "stackv2-0004.json.gz:34488",
"repo_name": "xiaofeiMophsic/YourTextEditor",
"revision_date": "2020-11-23T15:35:39",
"revision_id": "f49e1bd8752cdfc5ab863ae6c49551b84f9c85a2",
"snapshot_id": "d418f13da1dad89f8934cc4eb88fb91ccc927f05",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xiaofeiMophsic/YourTextEditor/f49e1bd8752cdfc5ab863ae6c49551b84f9c85a2/youreditor.c",
"visit_date": "2023-01-13T11:52:28.755877"
} | stackv2 | #include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#define _DEFALUT_SOURCE
#define _BSD_SOURCE
#define _GNU_SOURCE
#define YOUR_EDITOR_VERSION "0.0.1"
// ctrl 组合键时,其编码会将对应按键第5,6位设置为0
#define CTRL_KEY(k) ((k)&0x1f)
#define LINE_HEAD "~"
enum editorKey{
ARROW_LEFT = 1000,
ARROW_RIGHT = 1001,
ARROW_UP = 1002,
ARROW_DOWN = 1003,
PAGE_UP,
PAGE_DOWN,
HOME_KEY,
END_KEY,
DEL_KEY
};
/*** data ***/
typedef struct erow {
int size;
char *chars;
} erow;
struct editorConfig {
// 当前光标位置
int cx, cy;
int rowoff;
int screenrows;
int screencols;
int numrows;
erow *row;
struct termios orig_termios;
};
struct editorConfig E;
void die(const char *s) {
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
perror(s);
exit(1);
}
void disableRawMode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1) {
die("tcsetattr");
}
}
void enableRawMode() {
if (tcgetattr(STDIN_FILENO, &E.orig_termios) == -1) {
die("tcgetattr");
};
atexit(disableRawMode);
struct termios raw = E.orig_termios;
// 关闭echo和canonical mode。可以按
// 字节输入。
// ISIG 表示关闭 ctrl-c 和 ctrl-z信号
// IXON 表示关闭 ctrl-s 和 ctrl-q
// IEXTEN 关闭 ctrl-v
// ICRNL 关闭 回车到换行映射
raw.c_iflag &= ~(BRKINT | ICRNL | IXON | INPCK | ISTRIP);
// \n 字符转为 \r\n
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
// read 之前等待的最小字节数量
raw.c_cc[VMIN] = 0;
// read 之前最小等待时间
raw.c_cc[VTIME] = 1;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) {
die("tcsetattr");
};
}
int editorReadKey() {
int nread;
char c;
while ((nread = read(STDIN_FILENO, &c, 1)) != 1) {
if (nread == -1 && errno != EAGAIN) {
die("read");
}
}
// 映射上下左右方向键到wsad,
// 方向键以转移字符开头,后面为 ABCD 字母
if (c == '\x1b') {
char seq[3];
if(read(STDIN_FILENO, &seq[0], 1) != 1) return '\x1b';
if(read(STDIN_FILENO, &seq[1], 1) != 1) return '\x1b';
if(seq[0] == '[') {
// page up, page down. [5~, [6~
// del [3~]
if(seq[1] >= '0' && seq[1] <= '9') {
if (read(STDIN_FILENO, &seq[2], 1) != 1) return '\x1b';
if (seq[2] == '~') {
switch(seq[1]) {
case '5': return PAGE_UP;
case '6': return PAGE_DOWN;
case '1':
case '7': return HOME_KEY;
case '4':
case '8': return END_KEY;
case '3': return DEL_KEY;
}
}
}else {
switch(seq[1]) {
case 'A': return ARROW_UP;
case 'B': return ARROW_DOWN;
case 'C': return ARROW_RIGHT;
case 'D': return ARROW_LEFT;
case 'H': return HOME_KEY;
case 'F': return END_KEY;
}
}
} else if (seq[0] == 'O') {
switch(seq[1]) {
case 'H': return HOME_KEY;
case 'F': return END_KEY;
}
}
return '\x1b';
} else {
return c;
}
}
int getCursorPosition(int *rows, int *cols) {
char buf[32];
unsigned int i = 0;
// 写入 n 命令获取屏幕信息,参数6表示获取光标信息。
// 后面通过 read 来读取返回的信息
// 返回信息如:\x1b[30;100R
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4)
return -1;
while (i < sizeof(buf) - 1) {
if (read(STDOUT_FILENO, &buf[i], 1) != 1)
break;
if (buf[i] == 'R')
break;
i++;
}
buf[i] = '\0';
if (buf[0] != '\x1b' || buf[1] != '[')
return -1;
if (sscanf(&buf[2], "%d;%d", rows, cols) != 2)
return -1;
return 0;
}
int getWindowSize(int *rows, int *cols) {
struct winsize ws;
// ioctl 获取屏幕窗口尺寸失败时,一种策略是将光标移动到屏幕右下角
// 间接获取屏幕窗口尺寸
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12)
return -1;
return getCursorPosition(rows, cols);
} else {
*cols = ws.ws_col;
*rows = ws.ws_row;
return 0;
}
}
/*** row operations ***/
void editorAppendRow(char *s, size_t len) {
E.row = realloc(E.row, sizeof(erow) * (E.numrows + 1));
int at = E.numrows;
E.row[at].size = len;
E.row[at].chars = malloc(len + 1);
memcpy(E.row[at].chars, s, len);
E.row[at].chars[len] = '\0';
E.numrows++;
}
void editorOpen(char *filename) {
FILE *fp = fopen(filename, "r");
if (!fp) die("fopen");
char *line = NULL;
size_t linecap = 0;
ssize_t linelen;
while((linelen = getline(&line, &linecap, fp)) != -1) {
while (linelen > 0&&(line[linelen - 1] == '\n' || line[linelen - 1] == '\r'))
linelen --;
editorAppendRow(line, linelen);
}
free(line);
fclose(fp);
}
/*** append buffer ***/
/**
*
* 构建缓冲区,而不是直接write
*/
struct abuf {
char *b;
int len;
};
#define ABUF_INIT {NULL, 0};
void abAppend(struct abuf *ab, const char *s, int len) {
char *new = realloc(ab->b, ab->len + len);
if (new == NULL)
return;
memcpy(&new[ab->len], s, len);
ab->b = new;
ab->len += len;
}
void abFree(struct abuf *ab) { free(ab->b); }
/*** output ***/
void printWelcome(struct abuf *ab, char *s, int len){
int padding = (E.screencols - len) / 2;
if (padding) {
abAppend(ab, LINE_HEAD, 1);
padding--;
}
while (padding--) {
abAppend(ab, " ", 1);
}
abAppend(ab, s, len);
}
void editorScroll() {
if (E.cy < E.rowoff) {
E.rowoff = E.cy;
}
if (E.cy >= E.rowoff + E.screenrows) {
E.rowoff = E.cy - E.screenrows + 1;
}
}
/**
*
* 绘制 "~"
*/
void editorDrawRows(struct abuf *ab) {
int y;
int welcomep = E.screenrows / 3;
int authorp = welcomep + 2;
for (y = 0; y < E.screenrows; y++) {
int filerow = y + E.rowoff;
if (filerow >= E.numrows) {
if (E.numrows == 0) {
if (y == welcomep) {
char welcome[80];
int welcomelen =
snprintf(welcome, sizeof(welcome), "Your editor -- version %s",
YOUR_EDITOR_VERSION);
if (welcomelen > E.screencols) {
welcomelen = E.screencols;
}
printWelcome(ab, welcome, welcomelen);
} else if(y == authorp){
char author[80];
int authorlen =
snprintf(author, sizeof(author), "by xiaofei");
if (authorlen > E.screencols) {
authorlen = E.screencols;
}
printWelcome(ab, author, authorlen);
} else {
abAppend(ab, LINE_HEAD, 1);
}
} else {
abAppend(ab, LINE_HEAD, 1);
}
} else {
int len = E.row[filerow].size;
if (len > E.screencols) {
len = E.screencols;
}
abAppend(ab, E.row[filerow].chars, len);
}
// K 表示清除当前行
// 和J的作用类似
// 默认0,清除光标到行尾内容
abAppend(ab, "\x1b[K", 3);
if (y < E.screenrows - 1) {
abAppend(ab, "\r\n", 2);
}
}
}
void editorRefreshScreen() {
editorScroll();
struct abuf ab = ABUF_INIT;
// 隐藏光标
abAppend(&ab, "\x1b[?25l", 6);
// \x1b(27) is escape。
// 0 表示清除从光标到屏幕结尾;
// 1 表示清除从屏幕开始到光标位置;
// 2 表示清除整个屏幕。清除完之后,
// 光标在屏幕末尾位置。
// 默认 0
// abAppend(&ab, "\x1b[2J", 4);
abAppend(&ab, "\x1b[H", 3);
// 每次清空屏幕之后,重新绘制 ‘~’
editorDrawRows(&ab);
char buf[32];
snprintf(buf, sizeof(buf), "\x1b[%d;%dH", (E.cy - E.rowoff), E.cx + 1);
abAppend(&ab, buf, strlen(buf));
// 展示光标
abAppend(&ab, "\x1b[?25h", 6);
write(STDOUT_FILENO, ab.b, ab.len);
abFree(&ab);
}
/*** input ***/
void editorMoveCursor(int key) {
switch (key) {
case ARROW_LEFT:
if(E.cx != 0)
E.cx--;
break;
case ARROW_RIGHT:
if(E.cx != E.screencols - 1)
E.cx++;
break;
case ARROW_UP:
if(E.cy != 0)
E.cy--;
break;
case ARROW_DOWN:
if(E.cy < E.numrows)
E.cy++;
break;
}
}
void editorProcessKeypress() {
int c = editorReadKey();
switch (c) {
case CTRL_KEY('q'):
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
exit(0);
break;
case PAGE_UP:
case PAGE_DOWN: {
int times = E.screenrows;
while(times--) {
editorMoveCursor(c == PAGE_UP ? ARROW_UP : ARROW_DOWN);
}
}
break;
case HOME_KEY:
E.cx = 0;
break;
case END_KEY:
E.cx = E.screencols - 1;
break;
case ARROW_UP:
case ARROW_DOWN:
case ARROW_LEFT:
case ARROW_RIGHT:
editorMoveCursor(c);
break;
}
}
/*** init ***/
void initEditor() {
E.cx = 0;
E.cy = 0;
E.numrows = 0;
E.row = NULL;
E.rowoff = 0;
if (getWindowSize(&E.screenrows, &E.screencols) == -1) {
die("getWindowSize");
}
}
int main(int argc, char *argv[]) {
enableRawMode();
initEditor();
if (argc >= 2){
editorOpen(argv[1]);
}
while (1) {
struct abuf ab = ABUF_INIT;
editorRefreshScreen();
editorProcessKeypress();
editorDrawRows(&ab);
// 重新设定光标位置到左上角
write(STDOUT_FILENO, "\x1b[H", 3);
};
return 0;
} | 2.703125 | 3 |
2024-11-18T18:56:57.237463+00:00 | 2018-09-07T01:00:13 | d8106804ade5a35efd62fca156e02557e8ef3006 | {
"blob_id": "d8106804ade5a35efd62fca156e02557e8ef3006",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-07T01:00:13",
"content_id": "13fc2b52b499175a7f95ddd596b333bd2c6dabca",
"detected_licenses": [
"MIT"
],
"directory_id": "bfe7ca76529dcfde26befdbd4140dc2f4789d926",
"extension": "c",
"filename": "rightClick.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 146523531,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7072,
"license": "MIT",
"license_type": "permissive",
"path": "/zanChat/Lib/Helper/rightClick.c",
"provenance": "stackv2-0004.json.gz:34616",
"repo_name": "spencerwooo/zan-chat",
"revision_date": "2018-09-07T01:00:13",
"revision_id": "6b5b478a125da7ae24bc11dd89ef97d5a3722b84",
"snapshot_id": "9a05da14749f8f2859bd2c7af1f2b8bc1f9f41a0",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/spencerwooo/zan-chat/6b5b478a125da7ae24bc11dd89ef97d5a3722b84/zanChat/Lib/Helper/rightClick.c",
"visit_date": "2020-03-27T12:04:15.916711"
} | stackv2 | #include "../../Include/rightClick.h"
#include "../../Include/userInfo.h"
#include "../../Include/chatWindow.h"
/**************************************************/
/*名称:rightClick.c
/*描述:定义右键菜单相关回调、显示、功能函数
/*作成日期: 2018-09-04
/*作者: 李文煜、万伯阳
/***************************************************/
extern int my_img_code;
extern int my_avatar_code;
extern char user_name[100];
extern char user_group[100];
extern char sigh[100];
/**************************************************/
/*名称:record_display
/*描述:生成右键菜单
/*作成日期: 2018-09-02
/*参数: void
/*返回值:GtkWidget、右键窗口容器
/*作者: 李文煜
/***************************************************/
GtkWidget *getMenu_right(void)
{
GtkWidget *menu_right, *menu_items_right;
int i;
char buf[128];
menu_right = gtk_menu_new();
for (i = 0; i < 3; i++)
{
switch (i)
{
case 0:
sprintf(buf, "单人聊天");
break;
case 1:
sprintf(buf, "群组聊天");
break;
case 2:
sprintf(buf, "查看资料");
break;
}
menu_items_right = gtk_menu_item_new_with_label(buf);
gtk_menu_shell_append(GTK_MENU_SHELL(menu_right), menu_items_right);
g_signal_connect_swapped(G_OBJECT(menu_items_right), "activate", G_CALLBACK(right_response), (gpointer)g_strdup(buf));
gtk_widget_show(menu_items_right);
}
return menu_right;
}
gint right_button_press(GtkWidget *wid, GdkEvent *event)
{
GdkEventButton *bevent;
if (event->type == GDK_BUTTON_PRESS)
{
bevent = (GdkEventButton *)event;
if (bevent->button == 3)
{
gtk_menu_popup(GTK_MENU(wid), NULL, NULL, NULL, NULL,
bevent->button, bevent->time);
return TRUE;
}
}
return FALSE;
}
void ga_add_popup_menu(GtkWidget *wid, GtkMenu *menu)
{
g_signal_connect_swapped(G_OBJECT(wid), "event",
G_CALLBACK(right_button_press), menu);
}
/**************************************************************/
//右键菜单响应
/**************************************************************/
void right_response(gchar *string)
{
char *a[3] = {"单人聊天", "群组聊天", "查看资料"};
if (strcmp(string, a[0]) == 0)
talk_item(GTK_WIDGET(entry), entry);
else if (strcmp(string, a[1]) == 0)
grouptalk(GTK_WIDGET(entry), entry);
else if (strcmp(string, a[2]) == 0)
look_item(GTK_WIDGET(entry), entry);
}
/**************************************************************/
//查看资料
/**************************************************************/
void look_item(GtkWidget *widget, gpointer entry)
{
extern struct userinfo *head;
struct userinfo *p = head;
const char *str = gtk_entry_get_text(entry);
char node[50];
char l[50];
while (p != NULL)
{
strcpy(node, p->name);
strcat(node, "(");
strcat(node, p->ip);
strcat(node, ")");
if (0 == strcmp(str, node))
{
printf("name:%s\n", p->name);
printf("group:%s\n", p->group);
printf("IP:%s\n", p->ip);
printf("signature:%s\n", p->signature);
printf("avatar code:%d\n", p->avatar_code);
printf("image code:%d\n", p->image_code);
get_usr_info(p->name, p->group, p->ip, p->signature, p->image_code, p->avatar_code);
}
p = p->next;
strcpy(node, l);
}
}
/**************************************************************/
//单人聊天
/**************************************************************/
void talk_item(GtkWidget *widget, gpointer entry)
{
extern struct userinfo *head;
struct userinfo *p = head;
const char *str = gtk_entry_get_text(entry);
char node[50] = {0};
char l[50] = {0};
while (p != NULL)
{
strcpy(node, p->name);
strcat(node, "(");
strcat(node, p->ip);
strcat(node, ")");
if (0 == strcmp(str, node))
{
printf("name:%s\n", p->name);
printf("group:%s\n", p->group);
printf("IP:%s\n", p->ip);
printf("signature:%s\n", p->signature);
printf("avatar code:%d\n", p->avatar_code);
printf("image code:%d\n", p->image_code);
if (p->textViewAll == NULL)
createChatWindow(p->ip, p->name, NULL, p->signature, p->image_code, p->avatar_code);
}
//break;
p = p->next;
strcpy(node, l);
//memset(node, 0 , sizeof(node));
}
}
/**************************************************************/
//群组聊天
/**************************************************************/
void grouptalk(GtkWidget *widget, gpointer entry)
{
extern struct userinfo *head;
struct userinfo *p = head;
const char *str = gtk_entry_get_text(entry);
char node[50];
char l[50];
while (p != NULL)
{
strcpy(node, p->name);
//strcat(node,"pg_chat(");
strcat(node, "(");
strcat(node, p->ip);
strcat(node, ")");
//if(0 == strcmp(str,p->node)){
if (0 == strcmp(str, node))
{
printf("-----------------------\n");
printf("name:%s\n", p->name);
printf("group:%s\n", p->group);
printf("IP:%s\n", p->ip);
printf("signature:%s\n", p->signature);
printf("picture:%d\n", p->picture);
//if(p->textViewAll == NULL)
}
p = p->next;
strcpy(node, l);
}
}
/**************************************************************/
//查看资料界面
/**************************************************************/
void get_usr_info(char *name, char *group, char *ip, char *sig, int img_code, int avatar_code)
{
GtkWidget *usr_info;
GtkWidget *table;
GtkWidget *label;
GtkWidget *pic;
GtkWidget *usr;
usr_info = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_set_size_request(GTK_WIDGET(usr_info), 300, 300);
gtk_window_set_keep_above(GTK_WINDOW(usr_info), TRUE);
gtk_window_set_skip_taskbar_hint(GTK_WINDOW(usr_info), TRUE);
gtk_window_set_resizable(GTK_WINDOW(usr_info), FALSE);
gtk_window_set_title(GTK_WINDOW(usr_info), "查看资料");
char avatar_path[255] = {0};
parse_avatar_path(avatar_code, avatar_path);
printf("avatar path %s\n", avatar_path);
pic = gtk_image_new_from_file(avatar_path);
table = gtk_table_new(8, 7, TRUE);
gtk_container_add(GTK_CONTAINER(usr_info), table);
label = gtk_label_new("用户名:");
gtk_table_attach_defaults(GTK_TABLE(table), label, 0, 2, 0, 1);
label = gtk_label_new("群组:");
gtk_table_attach_defaults(GTK_TABLE(table), label, 0, 2, 1, 2);
label = gtk_label_new("IP:");
gtk_table_attach_defaults(GTK_TABLE(table), label, 0, 2, 2, 3);
label = gtk_label_new("个性签名:");
gtk_table_attach_defaults(GTK_TABLE(table), label, 0, 2, 3, 4);
gtk_table_attach_defaults(GTK_TABLE(table), pic, 5, 7, 0, 2);
label = gtk_label_new(name);
gtk_table_attach_defaults(GTK_TABLE(table), label, 2, 5, 0, 1);
label = gtk_label_new(group);
gtk_table_attach_defaults(GTK_TABLE(table), label, 2, 5, 1, 2);
label = gtk_label_new(ip);
gtk_table_attach_defaults(GTK_TABLE(table), label, 2, 5, 2, 3);
label = gtk_label_new(sig);
gtk_table_attach_defaults(GTK_TABLE(table), label, 2, 5, 3, 4);
gtk_widget_show_all(usr_info);
}
| 2.21875 | 2 |
2024-11-18T18:56:57.337107+00:00 | 2022-04-03T15:47:09 | ae31bf30aca3ff869bbd401ba76a84d106102511 | {
"blob_id": "ae31bf30aca3ff869bbd401ba76a84d106102511",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-03T21:52:54",
"content_id": "ba39f592d16e6d1fe8c73f02bd15eb610a649727",
"detected_licenses": [
"MIT"
],
"directory_id": "e317ae18338e42fce6e6472222356bbc1620b4db",
"extension": "c",
"filename": "testsuite_port_connector_change_table.c",
"fork_events_count": 9,
"gha_created_at": "2017-02-18T21:20:06",
"gha_event_created_at": "2022-04-03T21:52:55",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 82416804,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9388,
"license": "MIT",
"license_type": "permissive",
"path": "/apx/test/testsuite_port_connector_change_table.c",
"provenance": "stackv2-0004.json.gz:34745",
"repo_name": "cogu/c-apx",
"revision_date": "2022-04-03T15:47:09",
"revision_id": "2703f3e9ea8727fad7a62214bfd7940ab855b3bf",
"snapshot_id": "655a9141995602899aded999089e370c5ed576a3",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/cogu/c-apx/2703f3e9ea8727fad7a62214bfd7940ab855b3bf/apx/test/testsuite_port_connector_change_table.c",
"visit_date": "2022-05-09T06:31:13.707351"
} | stackv2 | //////////////////////////////////////////////////////////////////////////////
// INCLUDES
//////////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include "CuTest.h"
#include <stdio.h>
#include "apx/port_connector_change_table.h"
#include "apx/node_manager.h"
#ifdef MEM_LEAK_CHECK
#include "CMemLeak.h"
#endif
//////////////////////////////////////////////////////////////////////////////
// PRIVATE CONSTANTS AND DATA TYPES
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// PRIVATE FUNCTION PROTOTYPES
//////////////////////////////////////////////////////////////////////////////
static void test_create_table(CuTest *tc);
static void test_connect_vehicle_speed_ports(CuTest *tc);
static void test_disconnect_require_ports(CuTest *tc);
static void test_disconnect_provide_ports(CuTest *tc);
//////////////////////////////////////////////////////////////////////////////
// PRIVATE VARIABLES
//////////////////////////////////////////////////////////////////////////////
static const char *m_node_text1 =
"APX/1.2\n"
"N\"LocalTestNode1\"\n"
"P\"EngineSpeed\"S:=65535\n"
"P\"VehicleSpeed\"S:=65535\n";
static const char *m_node_text2 =
"APX/1.2\n"
"N\"LocalTestNode2\"\n"
"R\"VehicleSpeed\"S:=65535\n";
static const char *m_node_text3 =
"APX/1.2\n"
"N\"LocalTestNode3\"\n"
"R\"VehicleSpeed\"S:=65535\n";
//////////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////////////////////
CuSuite* testSuite_apx_portConnectorChangeTable(void)
{
CuSuite* suite = CuSuiteNew();
SUITE_ADD_TEST(suite, test_create_table);
SUITE_ADD_TEST(suite, test_connect_vehicle_speed_ports);
SUITE_ADD_TEST(suite, test_disconnect_require_ports);
SUITE_ADD_TEST(suite, test_disconnect_provide_ports);
return suite;
}
//////////////////////////////////////////////////////////////////////////////
// PRIVATE FUNCTIONS
//////////////////////////////////////////////////////////////////////////////
static void test_create_table(CuTest *tc)
{
apx_portConnectorChangeTable_t *table = apx_portConnectorChangeTable_new(3);
CuAssertPtrNotNull(tc, table);
CuAssertPtrNotNull(tc, table->entries);
CuAssertIntEquals(tc, 3, table->num_ports);
apx_portConnectorChangeTable_delete(table);
}
static void test_connect_vehicle_speed_ports(CuTest *tc)
{
apx_portConnectorChangeTable_t *port_connections;
apx_nodeManager_t *node_manager;
apx_nodeInstance_t *node_instance1;
apx_nodeInstance_t *node_instance2;
apx_portInstance_t *local_port;
apx_portInstance_t *remote_port;
node_manager = apx_nodeManager_new(APX_SERVER_MODE);
CuAssertPtrNotNull(tc, node_manager);
CuAssertIntEquals(tc, APX_NO_ERROR, apx_nodeManager_build_node(node_manager, m_node_text1));
node_instance1 = apx_nodeManager_get_last_attached(node_manager);
CuAssertPtrNotNull(tc, node_instance1);
CuAssertIntEquals(tc, APX_NO_ERROR, apx_nodeManager_build_node(node_manager, m_node_text2));
node_instance2 = apx_nodeManager_get_last_attached(node_manager);
CuAssertPtrNotNull(tc, node_instance2);
port_connections = apx_portConnectorChangeTable_new(2);
CuAssertPtrNotNull(tc, port_connections);
//create a connection between nodeInstance1.P[1] and nodeInstance1.R[0]. nodeInstance1 is local node.
local_port = apx_nodeInstance_get_provide_port(node_instance1, 1); // nodeInstance1.P[1]
remote_port = apx_nodeInstance_get_require_port(node_instance2, 0); //nodeInstance1.R[0]
CuAssertIntEquals(tc, 0, apx_portConnectorChangeTable_count(port_connections, 0));
CuAssertIntEquals(tc, 0, apx_portConnectorChangeTable_count(port_connections, 1));
CuAssertIntEquals(tc, APX_NO_ERROR, apx_portConnectorChangeTable_connect(port_connections, local_port, remote_port));
CuAssertIntEquals(tc, 0, apx_portConnectorChangeTable_count(port_connections, 0));
CuAssertIntEquals(tc, 1, apx_portConnectorChangeTable_count(port_connections, 1));
apx_nodeManager_delete(node_manager);
apx_portConnectorChangeTable_delete(port_connections);
}
static void test_disconnect_require_ports(CuTest *tc)
{
apx_portConnectorChangeTable_t *node_connections;
apx_nodeManager_t *node_manager;
apx_nodeInstance_t *node_instance1;
apx_nodeInstance_t *node_instance2;
apx_nodeInstance_t *node_instance3;
apx_portInstance_t *provide_port;
apx_portInstance_t *require_port_ref1;
apx_portInstance_t *require_port_ref2;
node_manager = apx_nodeManager_new(APX_SERVER_MODE);
CuAssertPtrNotNull(tc, node_manager);
CuAssertIntEquals(tc, APX_NO_ERROR, apx_nodeManager_build_node(node_manager, m_node_text1));
node_instance1 = apx_nodeManager_get_last_attached(node_manager);
CuAssertPtrNotNull(tc, node_instance1);
CuAssertIntEquals(tc, APX_NO_ERROR, apx_nodeManager_build_node(node_manager, m_node_text2));
node_instance2 = apx_nodeManager_get_last_attached(node_manager);
CuAssertPtrNotNull(tc, node_instance2);
CuAssertIntEquals(tc, APX_NO_ERROR, apx_nodeManager_build_node(node_manager, m_node_text3));
node_instance3 = apx_nodeManager_get_last_attached(node_manager);
CuAssertPtrNotNull(tc, node_instance3);
node_connections = apx_portConnectorChangeTable_new(2);
CuAssertPtrNotNull(tc, node_connections);
provide_port = apx_nodeInstance_get_provide_port(node_instance1, 1); // nodeInstance1.P[1]
require_port_ref1 = apx_nodeInstance_get_require_port(node_instance2, 0); //nodeInstance2.R[0]
require_port_ref2 = apx_nodeInstance_get_require_port(node_instance3, 0); //nodeInstance3.R[0]
//disconnect nodeData2.R[0] and nodeData3.R[0] from nodeData1.P[1]
CuAssertIntEquals(tc, 0, apx_portConnectorChangeTable_count(node_connections, 0));
CuAssertIntEquals(tc, 0, apx_portConnectorChangeTable_count(node_connections, 1));
CuAssertIntEquals(tc, APX_NO_ERROR, apx_portConnectorChangeTable_disconnect(node_connections, provide_port, require_port_ref1));
CuAssertIntEquals(tc, APX_NO_ERROR, apx_portConnectorChangeTable_disconnect(node_connections, provide_port, require_port_ref2));
CuAssertIntEquals(tc, 0, apx_portConnectorChangeTable_count(node_connections, 0));
CuAssertIntEquals(tc, -2, apx_portConnectorChangeTable_count(node_connections, 1));
apx_nodeManager_delete(node_manager);
apx_portConnectorChangeTable_delete(node_connections);
}
static void test_disconnect_provide_ports(CuTest *tc)
{
apx_portConnectorChangeTable_t *node2_require_connections;
apx_portConnectorChangeTable_t *node3_require_connections;
apx_nodeManager_t *node_manager;
apx_nodeInstance_t *node_instance1;
apx_nodeInstance_t *node_instance2;
apx_nodeInstance_t *node_instance3;
apx_portInstance_t *provide_port;
apx_portInstance_t *require_port1;
apx_portInstance_t *require_port2;
node_manager = apx_nodeManager_new(APX_SERVER_MODE);
CuAssertPtrNotNull(tc, node_manager);
CuAssertIntEquals(tc, APX_NO_ERROR, apx_nodeManager_build_node(node_manager, m_node_text1));
node_instance1 = apx_nodeManager_get_last_attached(node_manager);
CuAssertPtrNotNull(tc, node_instance1);
CuAssertIntEquals(tc, APX_NO_ERROR, apx_nodeManager_build_node(node_manager, m_node_text2));
node_instance2 = apx_nodeManager_get_last_attached(node_manager);
CuAssertPtrNotNull(tc, node_instance2);
CuAssertIntEquals(tc, APX_NO_ERROR, apx_nodeManager_build_node(node_manager, m_node_text3));
node_instance3 = apx_nodeManager_get_last_attached(node_manager);
CuAssertPtrNotNull(tc, node_instance3);
node2_require_connections = apx_portConnectorChangeTable_new(1);
node3_require_connections = apx_portConnectorChangeTable_new(1);
CuAssertPtrNotNull(tc, node2_require_connections);
CuAssertPtrNotNull(tc, node3_require_connections);
provide_port = apx_nodeInstance_get_provide_port(node_instance1, 1); //nodeInstance1.P[1]
require_port1 = apx_nodeInstance_get_require_port(node_instance2, 0); //nodeInstance2.R[0]
require_port2 = apx_nodeInstance_get_require_port(node_instance3, 0); //nodeInstance3.R[0]
//disconnect nodeInstance2.R[0] and nodeInstance3.R[0] from nodeInstance1.P[1]
CuAssertIntEquals(tc, 0, apx_portConnectorChangeTable_count(node2_require_connections, 0));
CuAssertIntEquals(tc, 0, apx_portConnectorChangeTable_count(node3_require_connections, 0));
CuAssertIntEquals(tc, APX_NO_ERROR, apx_portConnectorChangeTable_disconnect(node2_require_connections, require_port1, provide_port));
CuAssertIntEquals(tc, APX_NO_ERROR, apx_portConnectorChangeTable_disconnect(node3_require_connections, require_port2, provide_port));
CuAssertIntEquals(tc, -1, apx_portConnectorChangeTable_count(node2_require_connections, 0));
CuAssertIntEquals(tc, -1, apx_portConnectorChangeTable_count(node3_require_connections, 0));
apx_nodeManager_delete(node_manager);
apx_portConnectorChangeTable_delete(node2_require_connections);
apx_portConnectorChangeTable_delete(node3_require_connections);
} | 2.125 | 2 |
2024-11-18T18:56:58.051073+00:00 | 2017-05-05T13:28:52 | 03ede7c0b918b2315e08caa6df038e7d722ebc6e | {
"blob_id": "03ede7c0b918b2315e08caa6df038e7d722ebc6e",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-05T13:28:52",
"content_id": "ff57549468325d5b12605bc1f90d43560a0b868d",
"detected_licenses": [
"MIT"
],
"directory_id": "ef1b263496b8cf73ba2986ba51ce7ac5225cd093",
"extension": "h",
"filename": "cio_socket.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": 2221,
"license": "MIT",
"license_type": "permissive",
"path": "/src/cio_socket.h",
"provenance": "stackv2-0004.json.gz:35513",
"repo_name": "PlumpMath/cio",
"revision_date": "2017-05-05T13:28:52",
"revision_id": "a247eeab3d1e1bf15930be11115cf63634b9c6cf",
"snapshot_id": "9e1cde6978e8f9a72c585af7346628e51e4d9d7e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PlumpMath/cio/a247eeab3d1e1bf15930be11115cf63634b9c6cf/src/cio_socket.h",
"visit_date": "2021-01-20T12:51:58.141498"
} | stackv2 | /*
* The MIT License (MIT)
*
* Copyright (c) <2017> <Stephan Gatzka>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef CIO_SOCKET_H
#define CIO_SOCKET_H
#include "cio_io_stream.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @file
* @brief This file contains the interface of a socket.
*
* You can @ref cio_socket_get_io_stream "get an I/O stream"
* from a socket or @ref cio_socket_close "close" the socket.
*/
struct cio_socket {
/**
* @brief The context pointer which is passed to the functions
* specified below.
*/
void *context;
/**
* @anchor cio_socket_get_io_stream
* @brief Gets an I/O stream from the socket.
*
* @param context The cio_server_socket::context.
*
* @return An I/O stream for reading from and writing to this socket.
*/
struct cio_io_stream *(*get_io_stream)(void *context);
/**
* @anchor cio_socket_close
* @brief Closes the cio_socket.
*
* Once a socket has been closed, no further communication is possible. Closing the socket
* also closes the socket's cio_io_stream.
*
* @param context The cio_server_socket::context.
*/
void (*close)(void *context);
};
#ifdef __cplusplus
}
#endif
#endif
| 2.09375 | 2 |
2024-11-18T18:56:58.172628+00:00 | 2019-12-14T17:30:32 | db265b418d0597d413c2d0ab062c16971885e5a1 | {
"blob_id": "db265b418d0597d413c2d0ab062c16971885e5a1",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-14T17:30:32",
"content_id": "6f3a7898f8138cbe3d1bc99e58cb6c8721648a1a",
"detected_licenses": [
"MIT"
],
"directory_id": "f70e7cd362bbf8ac43d3b9de4f9a67a60331694d",
"extension": "c",
"filename": "commanddb.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 205255145,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1677,
"license": "MIT",
"license_type": "permissive",
"path": "/src/microcli/commanddb/commanddb.c",
"provenance": "stackv2-0004.json.gz:35642",
"repo_name": "baronleonardo/MicroCLI",
"revision_date": "2019-12-14T17:30:32",
"revision_id": "e4022346a34c035c4af592f425e0e916dcb8c7ab",
"snapshot_id": "05cbecc8d7ca5b191ea10b3fe6a812ca1bc63bd2",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/baronleonardo/MicroCLI/e4022346a34c035c4af592f425e0e916dcb8c7ab/src/microcli/commanddb/commanddb.c",
"visit_date": "2020-07-14T06:00:49.783980"
} | stackv2 | #include "commanddbmanager.h"
#include "commands/test/test.h"
#include "commands/reg/reg.h"
#include "commands/io/io.h"
#include "commands/inc_dec/inc_dec.h"
#include "commands/end_chain/end.h"
#include "commands/forloop/forloop.h"
#include "commands/ifcondition/ifcondition.h"
#include "commands/sdcard_cmds/sdcard_cmds.h"
#include "commands/file_exec/file_exec.h"
void CommandDB_createDatabase() {
CommandDB_add("test", sizeof("test") - 1, cmd_test);
CommandDB_add("regset", sizeof("regset") - 1, regSet);
CommandDB_add("regget", sizeof("regget") - 1, regGet);
CommandDB_add("io", sizeof("io") - 1, cmd_io);
CommandDB_add("inc", sizeof("inc") - 1, cmd_inc);
CommandDB_add("dec", sizeof("dec") - 1, cmd_dec);
CommandDB_add("ls", sizeof("ls") - 1, cmd_ls);
//CommandDB_add("cd", sizeof("cd") - 1, cmd_cd);
//CommandDB_add("pwd", sizeof("pwd") - 1, cmd_pwd);
CommandDB_add("cat", sizeof("cat") - 1, cmd_cat);
CommandDB_add("mount", sizeof("mount") - 1, cmd_mount);
CommandDB_add("umount", sizeof("umount") - 1, cmd_umount);
CommandDB_add("fexec", sizeof("fexec" - 1), file_exec);
CommandDB_addChainCommand("for", sizeof("for") - 1, forloop, COMMAND_DB_MAXITRNUM_INFINITY);
CommandDB_addChainCommand("if", sizeof("if") - 1, cmd_if, COMMAND_DB_MAXITRNUM_ONE);
/* NOTE: Don't change or delete this part
* NOTE: Don't add anyother end chain command
* NOTE: This command is important to indicate the end of chained commands
* used for for-loop and if-condition
*/
CommandDB_addEndChain("end", sizeof("end") - 1, cmd_end);
}
| 2.046875 | 2 |
2024-11-18T19:20:24.537249+00:00 | 2021-05-27T16:18:33 | f73778bff61203f280839b86a318716bb6555cb0 | {
"blob_id": "f73778bff61203f280839b86a318716bb6555cb0",
"branch_name": "refs/heads/kmp",
"committer_date": "2021-05-27T16:18:33",
"content_id": "8cfde415e0f5edad7e657ee449943edafc96594a",
"detected_licenses": [
"MIT"
],
"directory_id": "54d6fb37c9f64413797f67093b3f86f2f61dbe36",
"extension": "c",
"filename": "test.c",
"fork_events_count": 1,
"gha_created_at": "2020-04-25T04:11:37",
"gha_event_created_at": "2020-11-25T13:58:19",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 258684593,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 214,
"license": "MIT",
"license_type": "permissive",
"path": "/src/compat/libmcompat/math/exp/test.c",
"provenance": "stackv2-0004.json.gz:78164",
"repo_name": "MJChku/nautilus",
"revision_date": "2021-05-27T16:18:33",
"revision_id": "e2c6bfdac9fed62987ff590d827bef9c6e7d5545",
"snapshot_id": "9e50240aafb8b9f3057b2a2d6af2a15f6e8cfa4e",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/MJChku/nautilus/e2c6bfdac9fed62987ff590d827bef9c6e7d5545/src/compat/libmcompat/math/exp/test.c",
"visit_date": "2023-06-02T16:31:34.751651"
} | stackv2 | #include <stdio.h>
#include "nas_exp.h"
main(){
double input1, input2;
input1 = 22.18070977791824;
input2 = 33;
//scanf("%lf %lf", &input1, &input2);
double a = exp(input1);
printf("%20.20f",a);
}
| 2.375 | 2 |
2024-11-18T19:50:40.936088+00:00 | 2018-03-06T11:19:49 | d190069c3104baaf06f45b47ae8086a52b56f38d | {
"blob_id": "d190069c3104baaf06f45b47ae8086a52b56f38d",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-06T11:19:49",
"content_id": "15f5022fb67c2b39c74a4c095c77e607b41f220d",
"detected_licenses": [
"MIT"
],
"directory_id": "b29b03b4f456070ed818eaca7fc37d81a1331dea",
"extension": "h",
"filename": "LinearList.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 124063738,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1239,
"license": "MIT",
"license_type": "permissive",
"path": "/LinearList/LinearList.h",
"provenance": "stackv2-0004.json.gz:133673",
"repo_name": "JackysongNI/LinearList",
"revision_date": "2018-03-06T11:19:49",
"revision_id": "16d8f3fe20ff4da2a26722cf007a5c074ba6e58b",
"snapshot_id": "663da6f4eff0831c16886e160e205b47d8b7d291",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JackysongNI/LinearList/16d8f3fe20ff4da2a26722cf007a5c074ba6e58b/LinearList/LinearList.h",
"visit_date": "2021-04-26T22:17:40.823347"
} | stackv2 | //
// LinearList.h
// LinearList
//
// Created by Jacky on 18/1/9.
// Copyright © 2018年 Song Guoxiang. All rights reserved.
//
#ifndef LinearList_h
#define LinearList_h
#include <stdio.h>
typedef int LinearListNodeValue;
// 线性表
typedef struct {
int capacity;//容量
int length;//长度
LinearListNodeValue * value;//节点数据的指针
}LinearList;
/**定义一个函数创建线性表*/
LinearList *listCreat(int capacity);
/**销毁线性表*/
void listReleas(LinearList * list);
/**清空线性表*/
void listClear(LinearList * list);
/**获取线性表的长度*/
int listLength(LinearList * list);
/**获取index对应的数据*/
LinearListNodeValue listGet(LinearList * list,int index);
/**插入数据*/
void listInsert(LinearList * list, int index,LinearListNodeValue value);
/**添加数据*/
void listAdd(LinearList * list,LinearListNodeValue value);
/**设置元素*/
void listSet(LinearList * list,int index,LinearListNodeValue value);
/**删除元素*/
void listRemove(LinearList * list,int index);
/**删除某个值的所有数据*/
void listRemoveValue(LinearList * list,LinearListNodeValue value);
/**打印当前线性表*/
void listPrint(LinearList * list);
#endif /* LinearList_h */
| 2.53125 | 3 |
2024-11-18T19:50:41.208063+00:00 | 2023-09-03T16:23:51 | e0b491078a0c3b801715278c7f7bd323bb10f696 | {
"blob_id": "e0b491078a0c3b801715278c7f7bd323bb10f696",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-03T16:23:51",
"content_id": "7bb7f759ccd1be355907e4b250517a08ec97592a",
"detected_licenses": [
"MIT"
],
"directory_id": "55cda2ebcfd995b9cf0c2eb4bb17b695bd24a6d1",
"extension": "h",
"filename": "cm3_regs.h",
"fork_events_count": 1779,
"gha_created_at": "2013-11-10T01:41:14",
"gha_event_created_at": "2023-09-09T22:52:09",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 14268809,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4367,
"license": "MIT",
"license_type": "permissive",
"path": "/src/platforms/arm/stm32/cm3_regs.h",
"provenance": "stackv2-0004.json.gz:134058",
"repo_name": "FastLED/FastLED",
"revision_date": "2023-09-03T16:23:51",
"revision_id": "2874c7c8eb13d99ec4ad9a3201054c387d2d8aaa",
"snapshot_id": "744ae7eda80a8d4ab83ff87b42f3a65279535569",
"src_encoding": "UTF-8",
"star_events_count": 5936,
"url": "https://raw.githubusercontent.com/FastLED/FastLED/2874c7c8eb13d99ec4ad9a3201054c387d2d8aaa/src/platforms/arm/stm32/cm3_regs.h",
"visit_date": "2023-09-05T12:37:27.125510"
} | stackv2 | #ifndef __CM3_REGS
#define __CM3_REGS
#include <stdint.h>
#ifdef __cplusplus
#define __I volatile /*!< Defines 'read only' permissions */
#else
#define __I volatile const /*!< Defines 'read only' permissions */
#endif
#define __O volatile /*!< Defines 'write only' permissions */
#define __IO volatile /*!< Defines 'read / write' permissions */
typedef struct
{
__IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */
__O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */
__IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */
__IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */
} CoreDebug_Type;
#define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */
#define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */
#define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */
#define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */
typedef struct
{
__IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */
__IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */
__IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */
__IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */
__IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */
__IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */
__IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */
__I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */
__IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */
__IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */
__IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */
uint32_t RESERVED0[1];
__IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */
__IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */
__IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */
uint32_t RESERVED1[1];
__IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */
__IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */
__IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */
uint32_t RESERVED2[1];
__IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */
__IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */
__IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */
} DWT_Type;
#define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */
#define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */
#define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */
#define DWT_CTRL_CYCCNTENA_Msk (0x1UL << DWT_CTRL_CYCCNTENA_Pos) /*!< DWT CTRL: CYCCNTENA Mask */
#endif // __CM3_REGS
| 2.125 | 2 |
2024-11-18T19:50:41.270106+00:00 | 2021-05-29T21:54:27 | 13afe9476e3f439573d09f3b7895b9ee3666957b | {
"blob_id": "13afe9476e3f439573d09f3b7895b9ee3666957b",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-29T21:54:27",
"content_id": "dd965841a5816a36aa5598c457fde92785efabb2",
"detected_licenses": [
"MIT"
],
"directory_id": "bbef250b043b245e2cdcb3c7dbb713d4d2840b4d",
"extension": "c",
"filename": "tree.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 369342727,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2994,
"license": "MIT",
"license_type": "permissive",
"path": "/tree.c",
"provenance": "stackv2-0004.json.gz:134186",
"repo_name": "JohnMaxVal/BST",
"revision_date": "2021-05-29T21:54:27",
"revision_id": "bfcceb1c4503f462dbbf16dc7dbf5cd1fbd1180e",
"snapshot_id": "43d11d407c95474067dfa836f34aa18113a27333",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JohnMaxVal/BST/bfcceb1c4503f462dbbf16dc7dbf5cd1fbd1180e/tree.c",
"visit_date": "2023-05-09T08:01:00.610143"
} | stackv2 | #include "tree.h"
#include <stdlib.h>
Tree*
init_tree(void) {
Tree* tree = (Tree*)malloc(sizeof(Tree));
tree->root = NULL;
return tree;
}
void
register_cmpFn(Tree* tree, int (*cmpFn)(void*, void*)) {
tree->cmpFn = cmpFn;
}
void
register_tree_key_matchFn(Tree* tree, int (*key_matchFn)(void*, void*)) {
tree->key_match = key_matchFn;
}
void
tree_insert(Tree* tree, void* data) {
if(tree == NULL || data == NULL)
return;
TreeNode* tmp = NULL;
TreeNode* root = tree->root;
while(root != NULL) {
tmp = root;
if(tree->cmpFn(data, root->data) == -1)
root = root->left;
else
root = root->right;
}
TreeNode* new = malloc_tree_node();
new->data = data;
new->parent = tmp;
if(tmp == NULL)
tree->root = new;
else if(tree->cmpFn(new->data, tmp->data) == -1)
tmp->left = new;
else
tmp->right = new;
}
static TreeNode*
malloc_tree_node(void) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = NULL;
node->parent = NULL;
node->left = NULL;
node->right = NULL;
}
TreeNode*
tree_search(Tree* tree, void* key) {
if(tree == NULL)
return NULL;
TreeNode* node = tree->root;
while(node != NULL && tree->key_match(node->data, key) != 0)
if(tree->key_match(node->data, key) == -1)
node = node->right;
else
node = node->left;
return node;
}
/* TreeNode* */
/* tree_min(Tree* tree) { */
/* if(tree == NULL || tree->root == NULL) */
/* return NULL; */
/* TreeNode* node = tree->root; */
/* while(node->left != NULL) */
/* node = node->left; */
/* return node; */
/* } */
TreeNode*
tree_min(TreeNode* node) {
while(node->right != NULL)
node = node->right;
return node;
}
TreeNode*
tree_max(TreeNode* node) {
while(node->left != NULL)
node = node->left;
return node;
}
/* TreeNode* */
/* tree_max(Tree* tree) { */
/* if(tree == NULL || tree->root == NULL) */
/* return NULL; */
/* TreeNode* node = tree->root; */
/* while(node->right != NULL) */
/* node = node->right; */
/* return node; */
/* } */
void
tree_delete(Tree* tree, void* data) {
TreeNode* node = tree_search(tree, data);
TreeNode* tmp = NULL;
if(node->left == NULL || node->right == NULL)
tmp = node;
else
tmp = tree_successor(node);
TreeNode* tmp2 = NULL;
if(tmp->left != NULL)
tmp2 = tmp->left;
else
tmp2 = tmp->right;
if(tmp2 != NULL)
tmp2->parent = tmp->parent;
if(tmp->parent == NULL)
tree->root = tmp2;
else {
if(tmp == tmp->parent->left)
tmp->parent->left = tmp2;
else
tmp->parent->right = tmp2;
}
if(tmp != node)
node->data = tmp->data;
free(tmp);
}
TreeNode*
tree_successor(TreeNode* node) {
if(node == NULL)
return NULL;
if(node->right != NULL)
return tree_min(node->right);
TreeNode* parent = node->parent;
while(parent != NULL && node == parent->right) {
node = parent;
parent = parent->parent;
}
return parent;
}
| 3.234375 | 3 |
2024-11-18T17:55:01.039622+00:00 | 2016-06-09T10:31:48 | f3447830d2c6fd581bc22a2c94944e2aff25992a | {
"blob_id": "f3447830d2c6fd581bc22a2c94944e2aff25992a",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-09T10:31:48",
"content_id": "2993f7ccf9ae78193b3e951b2ff53af5ccc14634",
"detected_licenses": [
"MIT"
],
"directory_id": "5b306e0e0d144a4fe30dc738bd08f475648b12b9",
"extension": "c",
"filename": "intel_impl.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 59677754,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4971,
"license": "MIT",
"license_type": "permissive",
"path": "/intel_impl.c",
"provenance": "stackv2-0005.json.gz:2153",
"repo_name": "jakelongo/aesni-benchmarks",
"revision_date": "2016-06-09T10:31:48",
"revision_id": "c3d420314c598ba9edf93953e3eb81951c1b15a2",
"snapshot_id": "2ecbf3cfff386ed32aa395aa9f2d23e7ced8f259",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/jakelongo/aesni-benchmarks/c3d420314c598ba9edf93953e3eb81951c1b15a2/intel_impl.c",
"visit_date": "2020-12-31T04:56:30.997954"
} | stackv2 | // Author: Jake Longo
// Description: Code based on the Intel AES-NI reference doc
//
#include <stdint.h>
#include <wmmintrin.h>
#ifndef _WIN32
#include <x86intrin.h>
#endif
#include "intel_impl.h"
inline __m128i AES_128_ASSIST (__m128i temp1, __m128i temp2) {
__m128i temp3;
temp2 = _mm_shuffle_epi32 (temp2 ,0xff);
temp3 = _mm_slli_si128 (temp1, 0x4);
temp1 = _mm_xor_si128 (temp1, temp3);
temp3 = _mm_slli_si128 (temp3, 0x4);
temp1 = _mm_xor_si128 (temp1, temp3);
temp3 = _mm_slli_si128 (temp3, 0x4);
temp1 = _mm_xor_si128 (temp1, temp3);
temp1 = _mm_xor_si128 (temp1, temp2);
return temp1;
}
void AES_128_Key_Expansion (uint8_t *userkey, uint8_t *key) {
__m128i temp1, temp2;
__m128i *Key_Schedule = (__m128i*)key;
temp1 = _mm_loadu_si128((__m128i*)userkey);
Key_Schedule[0] = temp1;
temp2 = _mm_aeskeygenassist_si128 (temp1 ,0x1);
temp1 = AES_128_ASSIST(temp1, temp2);
Key_Schedule[1] = temp1;
temp2 = _mm_aeskeygenassist_si128 (temp1,0x2);
temp1 = AES_128_ASSIST(temp1, temp2);
Key_Schedule[2] = temp1;
temp2 = _mm_aeskeygenassist_si128 (temp1,0x4);
temp1 = AES_128_ASSIST(temp1, temp2);
Key_Schedule[3] = temp1;
temp2 = _mm_aeskeygenassist_si128 (temp1,0x8);
temp1 = AES_128_ASSIST(temp1, temp2);
Key_Schedule[4] = temp1;
temp2 = _mm_aeskeygenassist_si128 (temp1,0x10);
temp1 = AES_128_ASSIST(temp1, temp2);
Key_Schedule[5] = temp1;
temp2 = _mm_aeskeygenassist_si128 (temp1,0x20);
temp1 = AES_128_ASSIST(temp1, temp2);
Key_Schedule[6] = temp1;
temp2 = _mm_aeskeygenassist_si128 (temp1,0x40);
temp1 = AES_128_ASSIST(temp1, temp2);
Key_Schedule[7] = temp1;
temp2 = _mm_aeskeygenassist_si128 (temp1,0x80);
temp1 = AES_128_ASSIST(temp1, temp2);
Key_Schedule[8] = temp1;
temp2 = _mm_aeskeygenassist_si128 (temp1,0x1b);
temp1 = AES_128_ASSIST(temp1, temp2);
Key_Schedule[9] = temp1;
temp2 = _mm_aeskeygenassist_si128 (temp1,0x36);
temp1 = AES_128_ASSIST(temp1, temp2);
Key_Schedule[10] = temp1;
}
void AES_ECB_encrypt(uint8_t *in, uint8_t *out, uint8_t *key) {
__m128i tmp;
int j;
tmp = _mm_loadu_si128((__m128i*)in);
tmp = _mm_xor_si128(tmp,((__m128i*)key)[0]);
for(j=1; j < 10; j++) {
tmp = _mm_aesenc_si128(tmp,((__m128i*)key)[j]);
}
tmp = _mm_aesenclast_si128(tmp,((__m128i*)key)[j]);
_mm_storeu_si128((__m128i*)out,tmp);
}
void c_intel_benchmark(uint8_t* keys, uint8_t*data, uint8_t *dataOut) {
// create a store for the keys
uint8_t expandedKeys[176];
// Expand the key and encrypt
AES_128_Key_Expansion(keys, expandedKeys);
AES_ECB_encrypt(data, dataOut, expandedKeys);
}
void c_intel_interleaved_4x(uint8_t *keys, uint8_t *data, uint8_t *dataOut) {
__m128i mask = _mm_set_epi32(0x0c0f0e0d,0x0c0f0e0d,0x0c0f0e0d,0x0c0f0e0d);
__m128i dataIn = _mm_loadu_si128((__m128i*)&data[0]);
__m128i mmrconInit = _mm_set_epi32(1,1,1,1);
__m128i mmrconFinal = _mm_set_epi32(0x1b,0x1b,0x1b,0x1b);
__m128i mmrcon;
__m128i mmrk;
__m128i scratch0;
__m128i scratch1;
__m128i state;
for (uint8_t keyIdx = 0; keyIdx < 64; keyIdx += 16) {
mmrk = _mm_loadu_si128((__m128i*)&keys[keyIdx]);
state = _mm_xor_si128(dataIn, mmrk);
mmrcon = mmrconInit;
for (uint8_t rouncCounter = 0; rouncCounter <= 7; ++rouncCounter) {
scratch1 = _mm_shuffle_epi8(mmrk, mask);
scratch1 = _mm_aesenclast_si128 (scratch1,mmrcon);
mmrcon = _mm_slli_epi32(mmrcon,1);
scratch0 = _mm_slli_si128 (mmrk, 0x4);
mmrk = _mm_xor_si128 (mmrk, scratch0);
scratch0 = _mm_slli_si128 (scratch0, 0x4);
mmrk = _mm_xor_si128 (mmrk, scratch0);
scratch0 = _mm_slli_si128 (scratch0, 0x4);
mmrk = _mm_xor_si128 (mmrk, scratch0);
mmrk = _mm_xor_si128 (mmrk, scratch1);
state = _mm_aesenc_si128 (state, mmrk);
}
mmrcon = mmrconFinal;
scratch1 = _mm_shuffle_epi8(mmrk, mask);
scratch1 = _mm_aesenclast_si128(scratch1,mmrcon);
mmrcon = _mm_slli_epi32(mmrcon,1);
scratch0 = _mm_slli_si128(mmrk, 0x4);
mmrk = _mm_xor_si128(mmrk, scratch0);
scratch0 = _mm_slli_si128(scratch0, 0x4);
mmrk = _mm_xor_si128(mmrk, scratch0);
scratch0 = _mm_slli_si128(scratch0, 0x4);
mmrk = _mm_xor_si128(mmrk, scratch0);
mmrk = _mm_xor_si128(mmrk, scratch1);
state = _mm_aesenc_si128(state, mmrk);
scratch1 = _mm_shuffle_epi8(mmrk, mask);
scratch1 = _mm_aesenclast_si128(scratch1,mmrcon);
scratch0 = _mm_slli_si128(mmrk, 0x4);
mmrk = _mm_xor_si128(mmrk, scratch0);
scratch0 = _mm_slli_si128(scratch0, 0x4);
mmrk = _mm_xor_si128(mmrk, scratch0);
scratch0 = _mm_slli_si128(scratch0, 0x4);
mmrk = _mm_xor_si128(mmrk, scratch0);
mmrk = _mm_xor_si128(mmrk, scratch1);
state = _mm_aesenclast_si128(state, mmrk);
_mm_storeu_si128((__m128i*)&dataOut[keyIdx] ,state);
}
}
| 2.25 | 2 |
2024-11-18T17:55:01.160244+00:00 | 2021-11-02T22:15:50 | 79f705d2606b85256dab4b4b7f8207b9eb363e60 | {
"blob_id": "79f705d2606b85256dab4b4b7f8207b9eb363e60",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-03T20:37:39",
"content_id": "9ef55f6146282e86f2a00c94873b9ad9447895ba",
"detected_licenses": [
"MIT"
],
"directory_id": "6486481932cab2fe6ff03a394c5dcf524f75ba15",
"extension": "c",
"filename": "zip.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": 7684,
"license": "MIT",
"license_type": "permissive",
"path": "/src/util/ifile/zip/zip.c",
"provenance": "stackv2-0005.json.gz:2409",
"repo_name": "Watch-Later/TotalGB",
"revision_date": "2021-11-02T22:15:50",
"revision_id": "91ed6d772c6e0bfe995ec84ef0bc7205d743ea9f",
"snapshot_id": "d1b98e8ddc356d3d49e1a972efd3f0f08bbabfd0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Watch-Later/TotalGB/91ed6d772c6e0bfe995ec84ef0bc7205d743ea9f/src/util/ifile/zip/zip.c",
"visit_date": "2023-08-29T22:00:33.004008"
} | stackv2 | #include "zip.h"
#include "../../util.h"
#include <zip.h>
#include <unzip.h>
#include <ioapi_mem.h>
typedef struct {
union {
unzFile u;
zipFile z;
} file;
ourmemory_t* ourmem;
enum IFileMode mode;
} ctx_t;
#define PRIVATE_TO_CTX ctx_t* ctx = (ctx_t*)_private
#define IFILE_TO_CTX ctx_t* ctx = (ctx_t*)ifile->_private
struct Hacky {
char _hack; // this will be 0 (NULL)
int flags;
};
static int comp(unzFile ufile, const char* f1, const char* f2) {
(void)ufile;
// yes, this is hacky, it's the only way to pass user data...
const struct Hacky* hacky = (const struct Hacky*)f2;
// the result expects 0 to be yes, and anything else false
const enum ExtensionType type = util_get_extension_type(f1, ExtensionOffsetType_LAST);
printf("found: %s\n", f1);
return !(type & hacky->flags);
}
static bool find_and_open_file_type(IFile_t* ifile, int flags) {
IFILE_TO_CTX;
if (ctx->mode != IFileMode_READ) {
return false;
}
// this is used as mz calls strlen on the passed in name, so
// we need to be NULL somewhere.
struct Hacky hacky = {
._hack = '\0',
.flags = flags
};
if (Z_OK != unzLocateFile(ctx->file.u, (const char*)&hacky, comp)) {
printf("failed to locate rom\n");
return false;
}
return UNZ_OK == unzOpenCurrentFile(ctx->file.u);
}
static void iclose(void* _private) {
PRIVATE_TO_CTX;
if (ctx) {
switch (ctx->mode) {
case IFileMode_READ:
if (ctx->file.u) {
unzCloseCurrentFile(ctx->file.u);
unzClose(ctx->file.u);
ctx->file.u = NULL;
}
break;
case IFileMode_WRITE:
if (ctx->file.z) {
zipCloseFileInZip(ctx->file.z);
zipClose(ctx->file.z, NULL);
ctx->file.z = NULL;
}
break;
}
if (ctx->ourmem) {
if (ctx->ourmem->base) {
free(ctx->ourmem->base);
ctx->ourmem->base = NULL;
}
free(ctx->ourmem);
ctx->ourmem = NULL;
}
free(ctx);
ctx = NULL;
}
}
static bool iread(void* _private, void* data, size_t len) {
PRIVATE_TO_CTX;
if (ctx->mode != IFileMode_READ) {
return false;
}
return 0 < unzReadCurrentFile(ctx->file.u, data, len);
}
static bool iwrite(void* _private, const void* data, size_t len) {
PRIVATE_TO_CTX;
if (ctx->mode != IFileMode_WRITE) {
return false;
}
return 0 < zipWriteInFileInZip(ctx->file.z, data, len);
}
static bool iseek(void* _private, long offset, int whence) {
PRIVATE_TO_CTX;
if (ctx->mode != IFileMode_READ) {
return false;
}
// cannot seek backwards!
if (offset < 0) {
return false;
}
return UNZ_OK == unzSeek(ctx->file.u, (uint32_t)offset, whence);
}
static size_t itell(void* _private) {
PRIVATE_TO_CTX;
if (ctx->mode != IFileMode_READ) {
return 0;
}
// returns uncompressed offset
const int32_t r = unzTell(ctx->file.u);
return r < 0 ? 0 : r;
}
static size_t isize(void* _private) {
PRIVATE_TO_CTX;
if (ctx->mode != IFileMode_READ) {
return false;
}
unz_file_info info = {0};
const int result = unzGetCurrentFileInfo(
ctx->file.u, &info,
NULL, 0, NULL, 0, NULL, 0
);
if (result != UNZ_OK) {
return 0;
}
return info.uncompressed_size;
}
static IFile_t* open_read(const char* path, int flags) {
IFile_t* ifile = NULL;
ctx_t* ctx = NULL;
unzFile file = NULL;
ifile = malloc(sizeof(IFile_t));
if (!ifile) {
goto fail;
}
ctx = malloc(sizeof(ctx_t));
if (!ctx) {
goto fail;
}
file = unzOpen(path);
if (!file) {
goto fail;
}
const ctx_t _ctx = {
.file.u = file,
.ourmem = NULL, // unused!
.mode = IFileMode_READ
};
*ctx = _ctx;
const IFile_t _ifile = {
._private = ctx,
.close = iclose,
.read = iread,
.write = iwrite,
.seek = iseek,
.tell = itell,
.size = isize,
};
*ifile = _ifile;
if (!find_and_open_file_type(ifile, flags)) {
goto fail;
}
return ifile;
fail:
if (ifile) {
free(ifile);
ifile = NULL;
}
if (ctx) {
free(ctx);
ctx = NULL;
}
if (file) {
unzClose(file);
file = NULL;
}
return NULL;
}
static IFile_t* open_write(const char* path, int flags) {
IFile_t* ifile = NULL;
ctx_t* ctx = NULL;
unzFile file = NULL;
ifile = malloc(sizeof(IFile_t));
if (!ifile) {
goto fail;
}
ctx = malloc(sizeof(ctx_t));
if (!ctx) {
goto fail;
}
file = zipOpen(path, APPEND_STATUS_CREATE);
if (!file) {
goto fail;
}
const ctx_t _ctx = {
.file.z = file,
.ourmem = NULL, // unused!
.mode = IFileMode_WRITE
};
*ctx = _ctx;
const IFile_t _ifile = {
._private = ctx,
.close = iclose,
.read = iread,
.write = iwrite,
.seek = iseek,
.tell = itell,
.size = isize,
};
*ifile = _ifile;
return ifile;
fail:
if (ifile) {
free(ifile);
ifile = NULL;
}
if (ctx) {
free(ctx);
ctx = NULL;
}
if (file) {
unzClose(file);
file = NULL;
}
return NULL;
}
IFile_t* izip_open(const char* path, enum IFileMode mode, int flags) {
switch (mode) {
case IFileMode_READ:
return open_read(path, flags);
case IFileMode_WRITE:
return open_write(path, flags);
}
return NULL;
}
static IFile_t* open_read_mem(void* data, size_t size, int flags) {
IFile_t* ifile = NULL;
ctx_t* ctx = NULL;
unzFile file = NULL;
ourmemory_t* ourmemory = NULL;
zlib_filefunc_def filefunc32 = {0};
ifile = malloc(sizeof(IFile_t));
if (!ifile) {
goto fail;
}
ctx = malloc(sizeof(ctx_t));
if (!ctx) {
goto fail;
}
ourmemory = malloc(sizeof(ourmemory_t));
if (!ourmemory) {
goto fail;
}
ourmemory->size = size;
ourmemory->base = (char*)data;
fill_memory_filefunc(&filefunc32, ourmemory);
file = unzOpen2("__notused__", &filefunc32);
if (!file) {
goto fail;
}
const ctx_t _ctx = {
.file.u = file,
.ourmem = ourmemory,
.mode = IFileMode_READ
};
*ctx = _ctx;
const IFile_t _ifile = {
._private = ctx,
.close = iclose,
.read = iread,
.write = iwrite,
.seek = iseek,
.tell = itell,
.size = isize,
};
*ifile = _ifile;
if (!find_and_open_file_type(ifile, flags)) {
printf("failed to find rom!\n");
goto fail;
}
return ifile;
fail:
if (ifile) {
free(ifile);
ifile = NULL;
}
if (ctx) {
free(ctx);
ctx = NULL;
}
if (ourmemory) {
free(ourmemory);
ourmemory = NULL;
}
if (file) {
unzClose(file);
file = NULL;
}
return NULL;
}
IFile_t* izip_open_mem(void* data, size_t size, enum IFileMode mode, int flags) {
switch (mode) {
case IFileMode_READ:
return open_read_mem(data, size, flags);
case IFileMode_WRITE:
return NULL;
}
return NULL;
}
| 2.453125 | 2 |
2024-11-18T17:55:01.414043+00:00 | 2018-05-02T14:46:59 | 2775e37f4bc91d12f15c87cfde8f1af615d60389 | {
"blob_id": "2775e37f4bc91d12f15c87cfde8f1af615d60389",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-02T14:46:59",
"content_id": "2d246187766888f1d2ec127b0cd2105536d8d57a",
"detected_licenses": [
"MIT"
],
"directory_id": "ab9726c5128c4e791409a5db3cbc3c6819cb7ee0",
"extension": "h",
"filename": "ds2781.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 112611134,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3726,
"license": "MIT",
"license_type": "permissive",
"path": "/Inc/ds2781.h",
"provenance": "stackv2-0005.json.gz:2538",
"repo_name": "Group28/2-infinity-and-beyond",
"revision_date": "2018-05-02T14:46:59",
"revision_id": "fc086565098356b4c8b50c48382ef7c5a00d20d1",
"snapshot_id": "aeb353e43d19ed47f2547159bd521d221383cd3a",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Group28/2-infinity-and-beyond/fc086565098356b4c8b50c48382ef7c5a00d20d1/Inc/ds2781.h",
"visit_date": "2021-09-13T17:46:24.104830"
} | stackv2 | #include "OneWire.h"
#include "GenericTypeDefs.h"
#ifndef __DS2781_H
#define __DS2781_H
/*
* DS2781 sensor handle
*
*/
typedef struct {
OW ow; //< One wire interface handle
} __DS2781, *DS2781;
/*
* Initialize the battery voltage and current sensor
*
* @param port - Port of data line
* @param pin - Pin number of data line
* @return handle to the sensor
*/
DS2781 DS2781_init(GPIO_TypeDef *port, uint32_t pin);
/*
* Writes a 8bit value to the addressed register
*
* @param ds - sensor handle
* @param addr - register address
* @param data - 8bit data value
* @return
*/
inline void DS2781_write8bitReg(DS2781 ds, uint8_t addr, uint8_t data);
/*
* Writes a 16bit value to the addressed register
*
* @param ds - sensor handle
* @param addr - register address
* @param data - 16bit data value
* @return
*/
inline void DS2781_write16bitReg(DS2781 ds, uint8_t addr, uint16_t data);
/*
* Reads a 8bit value to the addressed register
*
* @param ds - sensor handle
* @param addr - register address
* @return 8bit data value at the address
*/
inline uint8_t DS2781_read8bitReg(DS2781 ds, uint8_t addr);
/*
* Reads a 16bit value to the addressed register
*
* @param ds - sensor handle
* @param addr - register address
* @return 16bit data value at the address
*/
inline uint16_t DS2781_read16bitReg(DS2781 ds, uint8_t addr);
/*
* Reads a 32bit value to the addressed register
*
* @param ds - sensor handle
* @param addr - register address
* @return 32bit data value at the address
*/
inline uint32_t DS2781_read32bitReg(DS2781 ds, uint8_t addr);
/*
* Reads a 64bit value to the addressed register
*
* @param ds - sensor handle
* @param addr - register address
* @return 64bit data value at the address
*/
inline uint64_t DS2781_read64bitReg(DS2781 ds, uint8_t addr);
/*
* Reads the battery voltage
*
* @param ds - sensor handle
* @return battery voltage (V)
*/
double DS2781_readVoltage (DS2781 ds);
/*
* Reads the battery current
*
* @param ds - sensor handle
* @return battery current (A)
*/
double DS2781_readCurrent (DS2781 ds);
/*
* Reads the accumulated battery current - used for capacity estimation
*
* @param ds - sensor handle
* @return accumulated battery current mAh
*/
double DS2781_readAccumulatedCurrent (DS2781 ds);
/*
* Resets the accumulated battery current
*
* @param ds - sensor handle
*/
void DS2781_resetAccumulatedCurrent (DS2781 ds);
/*
* Reads net address
*
* @param ds - sensor handle
* @return 64bit net address
*/
uint64_t DS2781_readNetAddress (DS2781 ds);
/*
* Reads the temperature
*
* @param ds - sensor handle
* @return temperature (*C)
*/
double DS2781_readTemperature (DS2781 ds);
/*
* Reads current callibration offset
*
* @param ds - sensor handle
* @return offset value
*/
uint8_t DS2781_readCurrentOffset (DS2781 ds);
/*
* Writes current callibration offset
*
* @param ds - sensor handle
* @param offset - offset value
*/
void DS2781_writeCurrentOffset (DS2781 ds, uint8_t offset);
/*
* Unknown
*
* @param
* @return
*/
void DS2781_adjustCurrentOffset (DS2781 ds);
/*
* Updates the controll regiseter
*
* @param
* @return
*/
void DS2781_updateControlRegister (DS2781 ds, uint8_t control);
/*
* Unused
*
* @param
* @return
*/
uint8_t DS2781_readRAM (DS2781 ds, uint8_t addr);
/*
* Unused
*
* @param
* @return
*/
void DS2781_writeRAM (DS2781 ds, uint8_t addr, uint8_t byte);
/*
* Copies EEPROM content to address
*
* @param ds - sensor handle
* @param addr - register address
*/
void DS2781_copyEEPROM (DS2781 ds, uint8_t addr);
/*
* Unused
*
* @param
* @return
*/
inline void DS2781_recallEEPROM (DS2781 ds, uint8_t addr);
#endif
| 2.28125 | 2 |
2024-11-18T17:55:02.441750+00:00 | 2023-02-16T11:27:40 | e217e99fd5ef319f6b3104cf10c7b61b3ec5289b | {
"blob_id": "e217e99fd5ef319f6b3104cf10c7b61b3ec5289b",
"branch_name": "refs/heads/main",
"committer_date": "2023-02-16T14:59:16",
"content_id": "a5b408716ec404bca80f90646cf8731dd67c77f8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493",
"extension": "h",
"filename": "adc.h",
"fork_events_count": 32,
"gha_created_at": "2016-08-05T22:14:50",
"gha_event_created_at": "2022-04-05T17:14:07",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 65052293,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 25681,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/include/zephyr/drivers/adc.h",
"provenance": "stackv2-0005.json.gz:3306",
"repo_name": "intel/zephyr",
"revision_date": "2023-02-16T11:27:40",
"revision_id": "06d5bc51b580777079bb0b7e769e4127598ea5ee",
"snapshot_id": "819362089aa44ae378a5558f3b222197aaa811f7",
"src_encoding": "UTF-8",
"star_events_count": 32,
"url": "https://raw.githubusercontent.com/intel/zephyr/06d5bc51b580777079bb0b7e769e4127598ea5ee/include/zephyr/drivers/adc.h",
"visit_date": "2023-09-04T00:20:35.217393"
} | stackv2 | /**
* @file
* @brief ADC public API header file.
*/
/*
* Copyright (c) 2018 Nordic Semiconductor ASA
* Copyright (c) 2015 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_ADC_H_
#define ZEPHYR_INCLUDE_DRIVERS_ADC_H_
#include <zephyr/device.h>
#include <zephyr/dt-bindings/adc/adc.h>
#include <zephyr/kernel.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief ADC driver APIs
* @defgroup adc_interface ADC driver APIs
* @ingroup io_interfaces
* @{
*/
/** @brief ADC channel gain factors. */
enum adc_gain {
ADC_GAIN_1_6, /**< x 1/6. */
ADC_GAIN_1_5, /**< x 1/5. */
ADC_GAIN_1_4, /**< x 1/4. */
ADC_GAIN_1_3, /**< x 1/3. */
ADC_GAIN_2_5, /**< x 2/5. */
ADC_GAIN_1_2, /**< x 1/2. */
ADC_GAIN_2_3, /**< x 2/3. */
ADC_GAIN_4_5, /**< x 4/5. */
ADC_GAIN_1, /**< x 1. */
ADC_GAIN_2, /**< x 2. */
ADC_GAIN_3, /**< x 3. */
ADC_GAIN_4, /**< x 4. */
ADC_GAIN_6, /**< x 6. */
ADC_GAIN_8, /**< x 8. */
ADC_GAIN_12, /**< x 12. */
ADC_GAIN_16, /**< x 16. */
ADC_GAIN_24, /**< x 24. */
ADC_GAIN_32, /**< x 32. */
ADC_GAIN_64, /**< x 64. */
ADC_GAIN_128, /**< x 128. */
};
/**
* @brief Invert the application of gain to a measurement value.
*
* For example, if the gain passed in is ADC_GAIN_1_6 and the
* referenced value is 10, the value after the function returns is 60.
*
* @param gain the gain used to amplify the input signal.
*
* @param value a pointer to a value that initially has the effect of
* the applied gain but has that effect removed when this function
* successfully returns. If the gain cannot be reversed the value
* remains unchanged.
*
* @retval 0 if the gain was successfully reversed
* @retval -EINVAL if the gain could not be interpreted
*/
int adc_gain_invert(enum adc_gain gain,
int32_t *value);
/** @brief ADC references. */
enum adc_reference {
ADC_REF_VDD_1, /**< VDD. */
ADC_REF_VDD_1_2, /**< VDD/2. */
ADC_REF_VDD_1_3, /**< VDD/3. */
ADC_REF_VDD_1_4, /**< VDD/4. */
ADC_REF_INTERNAL, /**< Internal. */
ADC_REF_EXTERNAL0, /**< External, input 0. */
ADC_REF_EXTERNAL1, /**< External, input 1. */
};
/**
* @brief Structure for specifying the configuration of an ADC channel.
*/
struct adc_channel_cfg {
/** Gain selection. */
enum adc_gain gain;
/** Reference selection. */
enum adc_reference reference;
/**
* Acquisition time.
* Use the ADC_ACQ_TIME macro to compose the value for this field or
* pass ADC_ACQ_TIME_DEFAULT to use the default setting for a given
* hardware (e.g. when the hardware does not allow to configure the
* acquisition time).
* Particular drivers do not necessarily support all the possible units.
* Value range is 0-16383 for a given unit.
*/
uint16_t acquisition_time;
/**
* Channel identifier.
* This value primarily identifies the channel within the ADC API - when
* a read request is done, the corresponding bit in the "channels" field
* of the "adc_sequence" structure must be set to include this channel
* in the sampling.
* For hardware that does not allow selection of analog inputs for given
* channels, but rather have dedicated ones, this value also selects the
* physical ADC input to be used in the sampling. Otherwise, when it is
* needed to explicitly select an analog input for the channel, or two
* inputs when the channel is a differential one, the selection is done
* in "input_positive" and "input_negative" fields.
* Particular drivers indicate which one of the above two cases they
* support by selecting or not a special hidden Kconfig option named
* ADC_CONFIGURABLE_INPUTS. If this option is not selected, the macro
* CONFIG_ADC_CONFIGURABLE_INPUTS is not defined and consequently the
* mentioned two fields are not present in this structure.
* While this API allows identifiers from range 0-31, particular drivers
* may support only a limited number of channel identifiers (dependent
* on the underlying hardware capabilities or configured via a dedicated
* Kconfig option).
*/
uint8_t channel_id : 5;
/** Channel type: single-ended or differential. */
uint8_t differential : 1;
#ifdef CONFIG_ADC_CONFIGURABLE_INPUTS
/**
* Positive ADC input.
* This is a driver dependent value that identifies an ADC input to be
* associated with the channel.
*/
uint8_t input_positive;
/**
* Negative ADC input (used only for differential channels).
* This is a driver dependent value that identifies an ADC input to be
* associated with the channel.
*/
uint8_t input_negative;
#endif /* CONFIG_ADC_CONFIGURABLE_INPUTS */
};
/**
* @brief Get ADC channel configuration from a given devicetree node.
*
* This returns a static initializer for a <tt>struct adc_channel_cfg</tt>
* filled with data from a given devicetree node.
*
* Example devicetree fragment:
*
* @code{.dts}
* &adc {
* #address-cells = <1>;
* #size-cells = <0>;
*
* channel@0 {
* reg = <0>;
* zephyr,gain = "ADC_GAIN_1_6";
* zephyr,reference = "ADC_REF_INTERNAL";
* zephyr,acquisition-time = <ADC_ACQ_TIME(ADC_ACQ_TIME_MICROSECONDS, 20)>;
* zephyr,input-positive = <NRF_SAADC_AIN6>;
* zephyr,input-negative = <NRF_SAADC_AIN7>;
* };
*
* channel@1 {
* reg = <1>;
* zephyr,gain = "ADC_GAIN_1_6";
* zephyr,reference = "ADC_REF_INTERNAL";
* zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>;
* zephyr,input-positive = <NRF_SAADC_AIN0>;
* };
* };
* @endcode
*
* Example usage:
*
* @code{.c}
* static const struct adc_channel_cfg ch0_cfg_dt =
* ADC_CHANNEL_CFG_DT(DT_CHILD(DT_NODELABEL(adc), channel_0));
* static const struct adc_channel_cfg ch1_cfg_dt =
* ADC_CHANNEL_CFG_DT(DT_CHILD(DT_NODELABEL(adc), channel_1));
*
* // Initializes 'ch0_cfg_dt' to:
* // {
* // .channel_id = 0,
* // .gain = ADC_GAIN_1_6,
* // .reference = ADC_REF_INTERNAL,
* // .acquisition_time = ADC_ACQ_TIME(ADC_ACQ_TIME_MICROSECONDS, 20),
* // .differential = true,
* // .input_positive = NRF_SAADC_AIN6,
* // .input-negative = NRF_SAADC_AIN7,
* // }
* // and 'ch1_cfg_dt' to:
* // {
* // .channel_id = 1,
* // .gain = ADC_GAIN_1_6,
* // .reference = ADC_REF_INTERNAL,
* // .acquisition_time = ADC_ACQ_TIME_DEFAULT,
* // .input_positive = NRF_SAADC_AIN0,
* // }
* @endcode
*
* @param node_id Devicetree node identifier.
*
* @return Static initializer for an adc_channel_cfg structure.
*/
#define ADC_CHANNEL_CFG_DT(node_id) { \
.gain = DT_STRING_TOKEN(node_id, zephyr_gain), \
.reference = DT_STRING_TOKEN(node_id, zephyr_reference), \
.acquisition_time = DT_PROP(node_id, zephyr_acquisition_time), \
.channel_id = DT_REG_ADDR(node_id), \
IF_ENABLED(CONFIG_ADC_CONFIGURABLE_INPUTS, \
(.differential = DT_NODE_HAS_PROP(node_id, zephyr_input_negative), \
.input_positive = DT_PROP_OR(node_id, zephyr_input_positive, 0), \
.input_negative = DT_PROP_OR(node_id, zephyr_input_negative, 0),)) \
}
/**
* @brief Container for ADC channel information specified in devicetree.
*
* @see ADC_DT_SPEC_GET_BY_IDX
* @see ADC_DT_SPEC_GET
*/
struct adc_dt_spec {
/**
* Pointer to the device structure for the ADC driver instance
* used by this io-channel.
*/
const struct device *dev;
/** ADC channel identifier used by this io-channel. */
uint8_t channel_id;
/**
* Flag indicating whether configuration of the associated ADC channel
* is provided as a child node of the corresponding ADC controller in
* devicetree.
*/
bool channel_cfg_dt_node_exists;
/**
* Configuration of the associated ADC channel specified in devicetree.
* This field is valid only when @a channel_cfg_dt_node_exists is set
* to @a true.
*/
struct adc_channel_cfg channel_cfg;
/**
* Voltage of the reference selected for the channel or 0 if this
* value is not provided in devicetree.
* This field is valid only when @a channel_cfg_dt_node_exists is set
* to @a true.
*/
uint16_t vref_mv;
/**
* ADC resolution to be used for that channel.
* This field is valid only when @a channel_cfg_dt_node_exists is set
* to @a true.
*/
uint8_t resolution;
/**
* Oversampling setting to be used for that channel.
* This field is valid only when @a channel_cfg_dt_node_exists is set
* to @a true.
*/
uint8_t oversampling;
};
/** @cond INTERNAL_HIDDEN */
#define ADC_DT_SPEC_STRUCT(ctlr, input) { \
.dev = DEVICE_DT_GET(ctlr), \
.channel_id = input, \
ADC_CHANNEL_CFG_FROM_DT_NODE(\
ADC_CHANNEL_DT_NODE(ctlr, input)) \
}
#define ADC_CHANNEL_DT_NODE(ctlr, input) \
DT_FOREACH_CHILD_VARGS(ctlr, ADC_FOREACH_INPUT, input)
#define ADC_FOREACH_INPUT(node, input) \
IF_ENABLED(IS_EQ(DT_REG_ADDR(node), input), (node))
#define ADC_CHANNEL_CFG_FROM_DT_NODE(node_id) \
IF_ENABLED(DT_NODE_EXISTS(node_id), \
(.channel_cfg_dt_node_exists = true, \
.channel_cfg = ADC_CHANNEL_CFG_DT(node_id), \
.vref_mv = DT_PROP_OR(node_id, zephyr_vref_mv, 0), \
.resolution = DT_PROP_OR(node_id, zephyr_resolution, 0), \
.oversampling = DT_PROP_OR(node_id, zephyr_oversampling, 0),))
/** @endcond */
/**
* @brief Get ADC io-channel information from devicetree.
*
* This returns a static initializer for an @p adc_dt_spec structure
* given a devicetree node and a channel index. The node must have
* the "io-channels" property defined.
*
* Example devicetree fragment:
*
* @code{.dts}
* / {
* zephyr,user {
* io-channels = <&adc0 1>, <&adc0 3>;
* };
* };
*
* &adc0 {
* #address-cells = <1>;
* #size-cells = <0>;
*
* channel@3 {
* reg = <3>;
* zephyr,gain = "ADC_GAIN_1_5";
* zephyr,reference = "ADC_REF_VDD_1_4";
* zephyr,vref-mv = <750>;
* zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>;
* zephyr,resolution = <12>;
* zephyr,oversampling = <4>;
* };
* };
* @endcode
*
* Example usage:
*
* @code{.c}
* static const struct adc_dt_spec adc_chan0 =
* ADC_DT_SPEC_GET_BY_IDX(DT_PATH(zephyr_user), 0);
* static const struct adc_dt_spec adc_chan1 =
* ADC_DT_SPEC_GET_BY_IDX(DT_PATH(zephyr_user), 1);
*
* // Initializes 'adc_chan0' to:
* // {
* // .dev = DEVICE_DT_GET(DT_NODELABEL(adc0)),
* // .channel_id = 1,
* // }
* // and 'adc_chan1' to:
* // {
* // .dev = DEVICE_DT_GET(DT_NODELABEL(adc0)),
* // .channel_id = 3,
* // .channel_cfg_dt_node_exists = true,
* // .channel_cfg = {
* // .channel_id = 3,
* // .gain = ADC_GAIN_1_5,
* // .reference = ADC_REF_VDD_1_4,
* // .acquisition_time = ADC_ACQ_TIME_DEFAULT,
* // },
* // .vref_mv = 750,
* // .resolution = 12,
* // .oversampling = 4,
* // }
* @endcode
*
* @see ADC_DT_SPEC_GET()
*
* @param node_id Devicetree node identifier.
* @param idx Channel index.
*
* @return Static initializer for an adc_dt_spec structure.
*/
#define ADC_DT_SPEC_GET_BY_IDX(node_id, idx) \
ADC_DT_SPEC_STRUCT(DT_IO_CHANNELS_CTLR_BY_IDX(node_id, idx), \
DT_IO_CHANNELS_INPUT_BY_IDX(node_id, idx))
/** @brief Get ADC io-channel information from a DT_DRV_COMPAT devicetree
* instance.
*
* @see ADC_DT_SPEC_GET_BY_IDX()
*
* @param inst DT_DRV_COMPAT instance number
* @param idx Channel index.
*
* @return Static initializer for an adc_dt_spec structure.
*/
#define ADC_DT_SPEC_INST_GET_BY_IDX(inst, idx) \
ADC_DT_SPEC_GET_BY_IDX(DT_DRV_INST(inst), idx)
/**
* @brief Equivalent to ADC_DT_SPEC_GET_BY_IDX(node_id, 0).
*
* @see ADC_DT_SPEC_GET_BY_IDX()
*
* @param node_id Devicetree node identifier.
*
* @return Static initializer for an adc_dt_spec structure.
*/
#define ADC_DT_SPEC_GET(node_id) ADC_DT_SPEC_GET_BY_IDX(node_id, 0)
/** @brief Equivalent to ADC_DT_SPEC_INST_GET_BY_IDX(inst, 0).
*
* @see ADC_DT_SPEC_GET()
*
* @param inst DT_DRV_COMPAT instance number
*
* @return Static initializer for an adc_dt_spec structure.
*/
#define ADC_DT_SPEC_INST_GET(inst) ADC_DT_SPEC_GET(DT_DRV_INST(inst))
/* Forward declaration of the adc_sequence structure. */
struct adc_sequence;
/**
* @brief Action to be performed after a sampling is done.
*/
enum adc_action {
/** The sequence should be continued normally. */
ADC_ACTION_CONTINUE = 0,
/**
* The sampling should be repeated. New samples or sample should be
* read from the ADC and written in the same place as the recent ones.
*/
ADC_ACTION_REPEAT,
/** The sequence should be finished immediately. */
ADC_ACTION_FINISH,
};
/**
* @brief Type definition of the optional callback function to be called after
* a requested sampling is done.
*
* @param dev Pointer to the device structure for the driver
* instance.
* @param sequence Pointer to the sequence structure that triggered
* the sampling. This parameter points to a copy of
* the structure that was supplied to the call that
* started the sampling sequence, thus it cannot be
* used with the CONTAINER_OF() macro to retrieve
* some other data associated with the sequence.
* Instead, the adc_sequence_options::user_data field
* should be used for such purpose.
*
* @param sampling_index Index (0-65535) of the sampling done.
*
* @returns Action to be performed by the driver. See @ref adc_action.
*/
typedef enum adc_action (*adc_sequence_callback)(const struct device *dev,
const struct adc_sequence *sequence,
uint16_t sampling_index);
/**
* @brief Structure defining additional options for an ADC sampling sequence.
*/
struct adc_sequence_options {
/**
* Interval between consecutive samplings (in microseconds), 0 means
* sample as fast as possible, without involving any timer.
* The accuracy of this interval is dependent on the implementation of
* a given driver. The default routine that handles the intervals uses
* a kernel timer for this purpose, thus, it has the accuracy of the
* kernel's system clock. Particular drivers may use some dedicated
* hardware timers and achieve a better precision.
*/
uint32_t interval_us;
/**
* Callback function to be called after each sampling is done.
* Optional - set to NULL if it is not needed.
*/
adc_sequence_callback callback;
/**
* Pointer to user data. It can be used to associate the sequence
* with any other data that is needed in the callback function.
*/
void *user_data;
/**
* Number of extra samplings to perform (the total number of samplings
* is 1 + extra_samplings).
*/
uint16_t extra_samplings;
};
/**
* @brief Structure defining an ADC sampling sequence.
*/
struct adc_sequence {
/**
* Pointer to a structure defining additional options for the sequence.
* If NULL, the sequence consists of a single sampling.
*/
const struct adc_sequence_options *options;
/**
* Bit-mask indicating the channels to be included in each sampling
* of this sequence.
* All selected channels must be configured with adc_channel_setup()
* before they are used in a sequence.
* The least significant bit corresponds to channel 0.
*/
uint32_t channels;
/**
* Pointer to a buffer where the samples are to be written. Samples
* from subsequent samplings are written sequentially in the buffer.
* The number of samples written for each sampling is determined by
* the number of channels selected in the "channels" field.
* The values written to the buffer represent a sample from each
* selected channel starting from the one with the lowest ID.
* The buffer must be of an appropriate size, taking into account
* the number of selected channels and the ADC resolution used,
* as well as the number of samplings contained in the sequence.
*/
void *buffer;
/**
* Specifies the actual size of the buffer pointed by the "buffer"
* field (in bytes). The driver must ensure that samples are not
* written beyond the limit and it must return an error if the buffer
* turns out to be not large enough to hold all the requested samples.
*/
size_t buffer_size;
/**
* ADC resolution.
* For single-ended channels the sample values are from range:
* 0 .. 2^resolution - 1,
* for differential ones:
* - 2^(resolution-1) .. 2^(resolution-1) - 1.
*/
uint8_t resolution;
/**
* Oversampling setting.
* Each sample is averaged from 2^oversampling conversion results.
* This feature may be unsupported by a given ADC hardware, or in
* a specific mode (e.g. when sampling multiple channels).
*/
uint8_t oversampling;
/**
* Perform calibration before the reading is taken if requested.
*
* The impact of channel configuration on the calibration
* process is specific to the underlying hardware. ADC
* implementations that do not support calibration should
* ignore this flag.
*/
bool calibrate;
};
/**
* @brief Type definition of ADC API function for configuring a channel.
* See adc_channel_setup() for argument descriptions.
*/
typedef int (*adc_api_channel_setup)(const struct device *dev,
const struct adc_channel_cfg *channel_cfg);
/**
* @brief Type definition of ADC API function for setting a read request.
* See adc_read() for argument descriptions.
*/
typedef int (*adc_api_read)(const struct device *dev,
const struct adc_sequence *sequence);
/**
* @brief Type definition of ADC API function for setting an asynchronous
* read request.
* See adc_read_async() for argument descriptions.
*/
typedef int (*adc_api_read_async)(const struct device *dev,
const struct adc_sequence *sequence,
struct k_poll_signal *async);
/**
* @brief ADC driver API
*
* This is the mandatory API any ADC driver needs to expose.
*/
__subsystem struct adc_driver_api {
adc_api_channel_setup channel_setup;
adc_api_read read;
#ifdef CONFIG_ADC_ASYNC
adc_api_read_async read_async;
#endif
uint16_t ref_internal; /* mV */
};
/**
* @brief Configure an ADC channel.
*
* It is required to call this function and configure each channel before it is
* selected for a read request.
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel_cfg Channel configuration.
*
* @retval 0 On success.
* @retval -EINVAL If a parameter with an invalid value has been provided.
*/
__syscall int adc_channel_setup(const struct device *dev,
const struct adc_channel_cfg *channel_cfg);
static inline int z_impl_adc_channel_setup(const struct device *dev,
const struct adc_channel_cfg *channel_cfg)
{
const struct adc_driver_api *api =
(const struct adc_driver_api *)dev->api;
return api->channel_setup(dev, channel_cfg);
}
/**
* @brief Configure an ADC channel from a struct adc_dt_spec.
*
* @param spec ADC specification from Devicetree.
*
* @return A value from adc_channel_setup() or -ENOTSUP if information from
* Devicetree is not valid.
* @see adc_channel_setup()
*/
static inline int adc_channel_setup_dt(const struct adc_dt_spec *spec)
{
if (!spec->channel_cfg_dt_node_exists) {
return -ENOTSUP;
}
return adc_channel_setup(spec->dev, &spec->channel_cfg);
}
/**
* @brief Set a read request.
*
* @param dev Pointer to the device structure for the driver instance.
* @param sequence Structure specifying requested sequence of samplings.
*
* If invoked from user mode, any sequence struct options for callback must
* be NULL.
*
* @retval 0 On success.
* @retval -EINVAL If a parameter with an invalid value has been provided.
* @retval -ENOMEM If the provided buffer is to small to hold the results
* of all requested samplings.
* @retval -ENOTSUP If the requested mode of operation is not supported.
* @retval -EBUSY If another sampling was triggered while the previous one
* was still in progress. This may occur only when samplings
* are done with intervals, and it indicates that the selected
* interval was too small. All requested samples are written
* in the buffer, but at least some of them were taken with
* an extra delay compared to what was scheduled.
*/
__syscall int adc_read(const struct device *dev,
const struct adc_sequence *sequence);
static inline int z_impl_adc_read(const struct device *dev,
const struct adc_sequence *sequence)
{
const struct adc_driver_api *api =
(const struct adc_driver_api *)dev->api;
return api->read(dev, sequence);
}
/**
* @brief Set an asynchronous read request.
*
* @note This function is available only if @kconfig{CONFIG_ADC_ASYNC}
* is selected.
*
* If invoked from user mode, any sequence struct options for callback must
* be NULL.
*
* @param dev Pointer to the device structure for the driver instance.
* @param sequence Structure specifying requested sequence of samplings.
* @param async Pointer to a valid and ready to be signaled struct
* k_poll_signal. (Note: if NULL this function will not notify
* the end of the transaction, and whether it went successfully
* or not).
*
* @returns 0 on success, negative error code otherwise.
* See adc_read() for a list of possible error codes.
*
*/
__syscall int adc_read_async(const struct device *dev,
const struct adc_sequence *sequence,
struct k_poll_signal *async);
#ifdef CONFIG_ADC_ASYNC
static inline int z_impl_adc_read_async(const struct device *dev,
const struct adc_sequence *sequence,
struct k_poll_signal *async)
{
const struct adc_driver_api *api =
(const struct adc_driver_api *)dev->api;
return api->read_async(dev, sequence, async);
}
#endif /* CONFIG_ADC_ASYNC */
/**
* @brief Get the internal reference voltage.
*
* Returns the voltage corresponding to @ref ADC_REF_INTERNAL,
* measured in millivolts.
*
* @return a positive value is the reference voltage value. Returns
* zero if reference voltage information is not available.
*/
static inline uint16_t adc_ref_internal(const struct device *dev)
{
const struct adc_driver_api *api =
(const struct adc_driver_api *)dev->api;
return api->ref_internal;
}
/**
* @brief Convert a raw ADC value to millivolts.
*
* This function performs the necessary conversion to transform a raw
* ADC measurement to a voltage in millivolts.
*
* @param ref_mv the reference voltage used for the measurement, in
* millivolts. This may be from adc_ref_internal() or a known
* external reference.
*
* @param gain the ADC gain configuration used to sample the input
*
* @param resolution the number of bits in the absolute value of the
* sample. For differential sampling this needs to be one less than the
* resolution in struct adc_sequence.
*
* @param valp pointer to the raw measurement value on input, and the
* corresponding millivolt value on successful conversion. If
* conversion fails the stored value is left unchanged.
*
* @retval 0 on successful conversion
* @retval -EINVAL if the gain is not reversible
*/
static inline int adc_raw_to_millivolts(int32_t ref_mv,
enum adc_gain gain,
uint8_t resolution,
int32_t *valp)
{
int32_t adc_mv = *valp * ref_mv;
int ret = adc_gain_invert(gain, &adc_mv);
if (ret == 0) {
*valp = (adc_mv >> resolution);
}
return ret;
}
/**
* @brief Convert a raw ADC value to millivolts using information stored
* in a struct adc_dt_spec.
*
* @param[in] spec ADC specification from Devicetree.
* @param[in,out] valp Pointer to the raw measurement value on input, and the
* corresponding millivolt value on successful conversion. If conversion fails
* the stored value is left unchanged.
*
* @return A value from adc_raw_to_millivolts() or -ENOTSUP if information from
* Devicetree is not valid.
* @see adc_raw_to_millivolts()
*/
static inline int adc_raw_to_millivolts_dt(const struct adc_dt_spec *spec,
int32_t *valp)
{
int32_t vref_mv;
uint8_t resolution;
if (!spec->channel_cfg_dt_node_exists) {
return -ENOTSUP;
}
if (spec->channel_cfg.reference == ADC_REF_INTERNAL) {
vref_mv = (int32_t)adc_ref_internal(spec->dev);
} else {
vref_mv = spec->vref_mv;
}
resolution = spec->resolution;
/*
* For differential channels, one bit less needs to be specified
* for resolution to achieve correct conversion.
*/
if (spec->channel_cfg.differential) {
resolution -= 1U;
}
return adc_raw_to_millivolts(vref_mv, spec->channel_cfg.gain,
resolution, valp);
}
/**
* @brief Initialize a struct adc_sequence from information stored in
* struct adc_dt_spec.
*
* Note that this function only initializes the following fields:
*
* - @ref adc_sequence.channels
* - @ref adc_sequence.resolution
* - @ref adc_sequence.oversampling
*
* Other fields should be initialized by the caller.
*
* @param[in] spec ADC specification from Devicetree.
* @param[out] seq Sequence to initialize.
*
* @retval 0 On success
* @retval -ENOTSUP If @p spec does not have valid channel configuration
*/
static inline int adc_sequence_init_dt(const struct adc_dt_spec *spec,
struct adc_sequence *seq)
{
if (!spec->channel_cfg_dt_node_exists) {
return -ENOTSUP;
}
seq->channels = BIT(spec->channel_id);
seq->resolution = spec->resolution;
seq->oversampling = spec->oversampling;
return 0;
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <syscalls/adc.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_ADC_H_ */
| 2.421875 | 2 |
2024-11-18T17:55:03.221224+00:00 | 2020-04-14T15:31:43 | af4fafdeba26d43e6e45c38d872b907c21622e74 | {
"blob_id": "af4fafdeba26d43e6e45c38d872b907c21622e74",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-14T15:31:43",
"content_id": "4bbcf55c49cc330cd9e9ac14298c7ed69bee200a",
"detected_licenses": [
"Unlicense"
],
"directory_id": "70a22b3cf5256c99432539d1f490a8357e94bb7f",
"extension": "c",
"filename": "base64.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 205843412,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2724,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/base64.c",
"provenance": "stackv2-0005.json.gz:3818",
"repo_name": "yogo1212/libbase64",
"revision_date": "2020-04-14T15:31:43",
"revision_id": "b6a76a07f729cd3e8b0a8d0c2a32fb31e19caa72",
"snapshot_id": "55b24830a4aabbc239c0300e494fd210263d9e7d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yogo1212/libbase64/b6a76a07f729cd3e8b0a8d0c2a32fb31e19caa72/src/base64.c",
"visit_date": "2020-07-16T18:33:12.189857"
} | stackv2 | #include <stdlib.h>
#include "base64.h"
static char base64_alphabet[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/',
};
static uint8_t decoding_table[256];
static int mod_table[] = {0, 2, 1};
size_t base64_encode_len(size_t input_length)
{
return 4 * ((input_length + 2) / 3) + 1;
}
void base64_encode(const void *_data, size_t input_length, char *encoded_data)
{
const uint8_t *data = _data;
size_t output_length = base64_encode_len(input_length);
for (size_t i = 0, j = 0; i < input_length;) {
uint8_t octet_a = (i < input_length) ? (uint8_t) data[i++] : 0;
uint8_t octet_b = (i < input_length) ? (uint8_t) data[i++] : 0;
uint8_t octet_c = (i < input_length) ? (uint8_t) data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = base64_alphabet[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = base64_alphabet[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = base64_alphabet[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = base64_alphabet[(triple >> 0 * 6) & 0x3F];
}
for (size_t i = 0; i < mod_table[input_length % 3]; i++)
encoded_data[output_length - 2 - i] = '=';
encoded_data[output_length - 1] = '\0';
}
size_t base64_decode_len(const char *data, size_t input_length)
{
size_t res = input_length / 4 * 3;
if (data[input_length - 1] == '=')
res--;
if (data[input_length - 2] == '=')
res--;
return res;
}
bool base64_decode(const char *data, size_t input_length, void *_out)
{
uint8_t *out = _out;
if (input_length % 4 != 0)
return false;
size_t output_length = base64_decode_len(data, input_length);
for (size_t i = 0, j = 0; i < input_length;) {
uint32_t sextet_a = (data[i] == '=') ? (0 & i++) : decoding_table[(int) data[i++]];
uint32_t sextet_b = (data[i] == '=') ? (0 & i++) : decoding_table[(int) data[i++]];
uint32_t sextet_c = (data[i] == '=') ? (0 & i++) : decoding_table[(int) data[i++]];
uint32_t sextet_d = (data[i] == '=') ? (0 & i++) : decoding_table[(int) data[i++]];
uint32_t triple = (sextet_a << 3 * 6)
+ (sextet_b << 2 * 6)
+ (sextet_c << 1 * 6)
+ (sextet_d << 0 * 6);
if (j < output_length)
out[j++] = (triple >> 2 * 8) & 0xFF;
if (j < output_length)
out[j++] = (triple >> 1 * 8) & 0xFF;
if (j < output_length)
out[j++] = (triple >> 0 * 8) & 0xFF;
}
return true;
}
void base64_init(void)
{
for (int i = 0; i < 64; i++)
decoding_table[(uint8_t) base64_alphabet[i]] = i;
}
| 2.640625 | 3 |
2024-11-18T17:55:03.356324+00:00 | 2015-04-21T05:23:04 | b2dfde59df2d694ba02c0941098de685c097b959 | {
"blob_id": "b2dfde59df2d694ba02c0941098de685c097b959",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-21T05:23:04",
"content_id": "05e5d18ae33b237dafa595b801848c9c39d33e9c",
"detected_licenses": [
"MIT"
],
"directory_id": "cf3e3ef75ba8b0e27ef64a50e4446a2957f49358",
"extension": "c",
"filename": "l2cap-ble.c",
"fork_events_count": 0,
"gha_created_at": "2015-04-20T23:15:49",
"gha_event_created_at": "2015-04-20T23:15:49",
"gha_language": null,
"gha_license_id": null,
"github_id": 34291768,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6334,
"license": "MIT",
"license_type": "permissive",
"path": "/src/l2cap-ble.c",
"provenance": "stackv2-0005.json.gz:3946",
"repo_name": "KhaosT/bleno",
"revision_date": "2015-04-21T05:23:04",
"revision_id": "0b69c53137d3a98b9287f835c1116bd36e5b18f5",
"snapshot_id": "914ed237270f0a122e3f07d630e8e43abd8f0c53",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/KhaosT/bleno/0b69c53137d3a98b9287f835c1116bd36e5b18f5/src/l2cap-ble.c",
"visit_date": "2021-01-18T02:09:55.748831"
} | stackv2 | #include <errno.h>
#include <signal.h>
#include <sys/prctl.h>
#include <unistd.h>
#include <stdlib.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include "utility.h"
#define ATT_CID 4
#define BDADDR_LE_PUBLIC 0x01
struct sockaddr_l2 {
sa_family_t l2_family;
unsigned short l2_psm;
bdaddr_t l2_bdaddr;
unsigned short l2_cid;
uint8_t l2_bdaddr_type;
};
#define L2CAP_CONNINFO 0x02
struct l2cap_conninfo {
uint16_t hci_handle;
uint8_t dev_class[3];
};
int lastSignal = 0;
static void signalHandler(int signal) {
lastSignal = signal;
}
int main(int argc, const char* argv[]) {
char *hciDeviceIdOverride = NULL;
int hciDeviceId = 0;
int hciSocket;
int serverL2capSock;
struct sockaddr_l2 sockAddr;
socklen_t sockAddrLen;
int result;
bdaddr_t clientBdAddr;
int clientL2capSock;
struct l2cap_conninfo l2capConnInfo;
socklen_t l2capConnInfoLen;
int hciHandle;
fd_set afds;
fd_set rfds;
struct timeval tv;
char stdinBuf[256 * 2 + 1];
char l2capSockBuf[256];
int len;
int i;
struct bt_security btSecurity;
socklen_t btSecurityLen;
uint8_t securityLevel = 0;
// remove buffering
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
// setup signal handlers
signal(SIGINT, signalHandler);
signal(SIGKILL, signalHandler);
signal(SIGHUP, signalHandler);
signal(SIGUSR1, signalHandler);
prctl(PR_SET_PDEATHSIG, SIGKILL);
// create socket
serverL2capSock = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP);
hciDeviceIdOverride = getenv("BLENO_HCI_DEVICE_ID");
if (hciDeviceIdOverride != NULL) {
hciDeviceId = atoi(hciDeviceIdOverride);
} else {
// if no env variable given, use the first available device
hciDeviceId = hci_get_route(NULL);
}
if (hciDeviceId < 0) {
hciDeviceId = 0; // use device 0, if device id is invalid
}
bdaddr_t daddr;
hciSocket = hci_open_dev(hciDeviceId);
if (hciSocket == -1) {
printf("adapterState unsupported\n");
return -1;
}
if (hci_read_bd_addr(hciSocket, &daddr, 1000) == -1){
daddr = *BDADDR_ANY;
}
// bind
memset(&sockAddr, 0, sizeof(sockAddr));
sockAddr.l2_family = AF_BLUETOOTH;
sockAddr.l2_bdaddr = daddr;
sockAddr.l2_cid = htobs(ATT_CID);
sockAddr.l2_bdaddr_type = BDADDR_LE_PUBLIC;
result = bind(serverL2capSock, (struct sockaddr*)&sockAddr, sizeof(sockAddr));
printf("bind %s\n", (result == -1) ? strerror(errno) : "success");
result = listen(serverL2capSock, 1);
printf("listen %s\n", (result == -1) ? strerror(errno) : "success");
while (result != -1) {
FD_ZERO(&afds);
FD_SET(serverL2capSock, &afds);
tv.tv_sec = 1;
tv.tv_usec = 0;
result = select(serverL2capSock + 1, &afds, NULL, NULL, &tv);
if (-1 == result) {
if (SIGINT == lastSignal || SIGKILL == lastSignal) {
break;
} else if (SIGHUP == lastSignal || SIGUSR1 == lastSignal) {
result = 0;
}
} else if (result && FD_ISSET(serverL2capSock, &afds)) {
sockAddrLen = sizeof(sockAddr);
clientL2capSock = accept(serverL2capSock, (struct sockaddr *)&sockAddr, &sockAddrLen);
baswap(&clientBdAddr, &sockAddr.l2_bdaddr);
printf("accept %s\n", batostr(&clientBdAddr));
l2capConnInfoLen = sizeof(l2capConnInfo);
getsockopt(clientL2capSock, SOL_L2CAP, L2CAP_CONNINFO, &l2capConnInfo, &l2capConnInfoLen);
hciHandle = l2capConnInfo.hci_handle;
while(1) {
FD_ZERO(&rfds);
FD_SET(0, &rfds);
FD_SET(clientL2capSock, &rfds);
tv.tv_sec = 1;
tv.tv_usec = 0;
result = select(clientL2capSock + 1, &rfds, NULL, NULL, &tv);
if (-1 == result) {
if (SIGINT == lastSignal || SIGKILL == lastSignal) {
break;
} else if (SIGHUP == lastSignal) {
result = 0;
hci_disconnect(hciSocket, hciHandle, HCI_OE_USER_ENDED_CONNECTION, 1000);
} else if (SIGUSR1 == lastSignal) {
int8_t rssi = 0;
for (i = 0; i < 100; i++) {
hci_read_rssi(hciSocket, hciHandle, &rssi, 1000);
if (rssi != 0) {
break;
}
}
if (rssi == 0) {
rssi = 127;
}
printf("rssi = %d\n", rssi);
}
} else if (result) {
if (FD_ISSET(0, &rfds)) {
len = readLine(0, stdinBuf, sizeof(stdinBuf));
if (len <= 0) {
break;
}
for (i = 0; i < len; i += 2) {
unsigned int data = 0;
sscanf(&stdinBuf[i], "%02x", &data);
l2capSockBuf[i / 2] = data;
}
len = write(clientL2capSock, l2capSockBuf, len / 2);
}
if (FD_ISSET(clientL2capSock, &rfds)) {
len = read(clientL2capSock, l2capSockBuf, sizeof(l2capSockBuf));
if (len <= 0) {
break;
}
btSecurityLen = sizeof(btSecurity);
memset(&btSecurity, 0, btSecurityLen);
getsockopt(clientL2capSock, SOL_BLUETOOTH, BT_SECURITY, &btSecurity, &btSecurityLen);
if (securityLevel != btSecurity.level) {
securityLevel = btSecurity.level;
const char *securityLevelString;
switch(securityLevel) {
case BT_SECURITY_LOW:
securityLevelString = "low";
break;
case BT_SECURITY_MEDIUM:
securityLevelString = "medium";
break;
case BT_SECURITY_HIGH:
securityLevelString = "high";
break;
default:
securityLevelString = "unknown";
break;
}
printf("security %s\n", securityLevelString);
}
printf("data ");
for(i = 0; i < len; i++) {
printf("%02x", ((int)l2capSockBuf[i]) & 0xff);
}
printf("\n");
}
}
}
printf("disconnect %s\n", batostr(&clientBdAddr));
close(clientL2capSock);
}
}
printf("close\n");
close(serverL2capSock);
close(hciSocket);
return 0;
}
| 2.140625 | 2 |
2024-11-18T17:55:03.549155+00:00 | 2023-08-16T08:50:33 | 16b5729fefc94e0789635d77f8bb06fa9610afb9 | {
"blob_id": "16b5729fefc94e0789635d77f8bb06fa9610afb9",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-18T09:13:27",
"content_id": "add1588791a3fafb3b39c211793b656646fddd69",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "55540f3e86f1d5d86ef6b5d295a63518e274efe3",
"extension": "h",
"filename": "spi.h",
"fork_events_count": 101,
"gha_created_at": "2020-10-26T11:16:30",
"gha_event_created_at": "2023-08-28T06:29:02",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 307347250,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2668,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/components/fs/vfs/include/hal/soc/spi.h",
"provenance": "stackv2-0005.json.gz:4202",
"repo_name": "bouffalolab/bl_iot_sdk",
"revision_date": "2023-08-16T08:50:33",
"revision_id": "b90664de0bd4c1897a9f1f5d9e360a9631d38b34",
"snapshot_id": "bc5eaf036b70f8c65dd389439062b169f8d09daa",
"src_encoding": "UTF-8",
"star_events_count": 244,
"url": "https://raw.githubusercontent.com/bouffalolab/bl_iot_sdk/b90664de0bd4c1897a9f1f5d9e360a9631d38b34/components/fs/vfs/include/hal/soc/spi.h",
"visit_date": "2023-08-31T03:38:03.369853"
} | stackv2 | /*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef HAL_SPI_H
#define HAL_SPI_H
#define HAL_SPI_MODE_MASTER 1 /* spi communication is master mode */
#define HAL_SPI_MODE_SLAVE 2 /* spi communication is slave mode */
typedef struct {
uint8_t mode; /* spi communication mode */
uint32_t freq; /* communication frequency Hz */
} spi_config_t;
typedef struct {
uint8_t port; /* spi port */
spi_config_t config; /* spi config */
void *priv; /* priv data */
} spi_dev_t;
/**
* Initialises the SPI interface for a given SPI device
*
* @param[in] spi the spi device
*
* @return 0 : on success, EIO : if the SPI device could not be initialised
*/
int32_t hal_spi_init(spi_dev_t *spi);
/**
* Spi send
*
* @param[in] spi the spi device
* @param[in] data spi send data
* @param[in] size spi send data size
* @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER
* if you want to wait forever
*
* @return 0 : on success, EIO : if the SPI device could not be initialised
*/
int32_t hal_spi_send(spi_dev_t *spi, const uint8_t *data, uint16_t size, uint32_t timeout);
/**
* spi_recv
*
* @param[in] spi the spi device
* @param[out] data spi recv data
* @param[in] size spi recv data size
* @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER
* if you want to wait forever
*
* @return 0 : on success, EIO : if the SPI device could not be initialised
*/
int32_t hal_spi_recv(spi_dev_t *spi, uint8_t *data, uint16_t size, uint32_t timeout);
/**
* spi send data and recv
*
* @param[in] spi the spi device
* @param[in] tx_data spi send data
* @param[in] rx_data spi recv data
* @param[in] size spi data to be sent and recived
* @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER
* if you want to wait forever
*
* @return 0, on success; EIO : if the SPI device could not be initialised
*/
int32_t hal_spi_send_recv(spi_dev_t *spi, uint8_t *tx_data, uint8_t *rx_data,
uint16_t size, uint32_t timeout);
/**
* De-initialises a SPI interface
*
*
* @param[in] spi the SPI device to be de-initialised
*
* @return 0 : on success, EIO : if an error occurred
*/
int32_t hal_spi_finalize(spi_dev_t *spi);
int hal_spi_set_rwmode(spi_dev_t *spi_dev, int mode);
int hal_spi_set_rwspeed(spi_dev_t *spi_dev, uint32_t speed);
int hal_spi_transfer(spi_dev_t *spi_dev, void *xfer, uint8_t size);/* spi_ioc_transfer_t */
#endif /* HAL_SPI_H */
| 2.34375 | 2 |
2024-11-18T17:55:03.610006+00:00 | 2023-01-30T10:03:23 | 5383416d2bda2cd135430cf7d24498ad9ce732eb | {
"blob_id": "5383416d2bda2cd135430cf7d24498ad9ce732eb",
"branch_name": "refs/heads/main",
"committer_date": "2023-01-30T10:03:23",
"content_id": "626933b70d06fdd6160d4c6f6adcddbd70fd7802",
"detected_licenses": [
"MIT"
],
"directory_id": "d0dc556f8b1d18ecbadef182bafd97b632dd3104",
"extension": "c",
"filename": "main.c",
"fork_events_count": 36,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 315618086,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1169,
"license": "MIT",
"license_type": "permissive",
"path": "/common/esp-idf-lib/examples/tsl2561/main/main.c",
"provenance": "stackv2-0005.json.gz:4330",
"repo_name": "PacktPublishing/Internet-of-Things-with-ESP32",
"revision_date": "2023-01-30T10:03:23",
"revision_id": "3ada8b905e53961940511636991a839059de7cd1",
"snapshot_id": "da3f2c57e2bd871b134b22841fd275c51f88d487",
"src_encoding": "UTF-8",
"star_events_count": 114,
"url": "https://raw.githubusercontent.com/PacktPublishing/Internet-of-Things-with-ESP32/3ada8b905e53961940511636991a839059de7cd1/common/esp-idf-lib/examples/tsl2561/main/main.c",
"visit_date": "2023-02-08T13:58:32.585403"
} | stackv2 | #include <stdio.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_system.h>
#include <tsl2561.h>
#include <string.h>
#if defined(CONFIG_IDF_TARGET_ESP8266)
#define SDA_GPIO 4
#define SCL_GPIO 5
#else
#define SDA_GPIO 18
#define SCL_GPIO 19
#endif
#if defined(CONFIG_IDF_TARGET_ESP32S2)
#define APP_CPU_NUM PRO_CPU_NUM
#endif
#define ADDR TSL2561_I2C_ADDR_FLOAT
void tsl2561_test(void *pvParamters)
{
tsl2561_t dev;
memset(&dev, 0, sizeof(tsl2561_t));
ESP_ERROR_CHECK(tsl2561_init_desc(&dev, ADDR, 0, SDA_GPIO, SCL_GPIO));
ESP_ERROR_CHECK(tsl2561_init(&dev));
printf("Found TSL2561 in package %s\n", dev.package_type == TSL2561_PACKAGE_CS ? "CS" : "T/FN/CL");
uint32_t lux;
esp_err_t res;
while (1)
{
vTaskDelay(100 / portTICK_PERIOD_MS);
if ((res = tsl2561_read_lux(&dev, &lux)) != ESP_OK)
printf("Could not read lux value: %d\n", res);
else
printf("Lux: %u\n", lux);
}
}
void app_main()
{
ESP_ERROR_CHECK(i2cdev_init());
xTaskCreatePinnedToCore(tsl2561_test, "tsl2561_test", configMINIMAL_STACK_SIZE * 8, NULL, 5, NULL, APP_CPU_NUM);
}
| 2.34375 | 2 |
2024-11-18T17:55:04.069181+00:00 | 2017-01-05T07:29:27 | 81ba0e79dd90fb1e1c20b1e1821b3230f7205edd | {
"blob_id": "81ba0e79dd90fb1e1c20b1e1821b3230f7205edd",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-05T07:29:27",
"content_id": "bd9d10873734947392244cdd6e2291680539ad9b",
"detected_licenses": [
"MIT"
],
"directory_id": "e4b6d23207da164d740803ff1f6a4a36949adc3e",
"extension": "c",
"filename": "lagrangePolynomial.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 78090207,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 686,
"license": "MIT",
"license_type": "permissive",
"path": "/lagrangePolynomial.c",
"provenance": "stackv2-0005.json.gz:4714",
"repo_name": "yukito/hod_cryptanalysis",
"revision_date": "2017-01-05T07:29:27",
"revision_id": "1451eeac00a6be23b809f403a31b49f1f8c9f296",
"snapshot_id": "b30ff7d37d0596fe115e3e20c2f4705fbed45799",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yukito/hod_cryptanalysis/1451eeac00a6be23b809f403a31b49f1f8c9f296/lagrangePolynomial.c",
"visit_date": "2021-01-12T02:45:35.384160"
} | stackv2 | #include <stdlib.h>
#include "poly_operation.c"
//#include "extend_euc.c"
poly *lagrangePolynomial(int *point, int numofpoint, int q)
{
int x,j;
unsigned sum, jx;
poly *px=setpoly(0,0);
poly *form;
poly *tmp;
for(j=0;j<numofpoint;j++){
sum=1;
form=setpoly(1,0);
for(x=0;x<numofpoint;x++){
if(x==j) x++;
if(x==numofpoint) break;
if(j-x<0) jx=(q+(j-x))%q;
else jx=j-x;
sum=(sum*jx)%q;
tmp=setpoly(1,1);
exorpoly(tmp,setpoly(q-1*x,0));
form=mulpoly(form,tmp,q);
sortpoly(form);
unipoly(form);
}
ntimepoly(point[j]*Ex_Euc(sum%q,q),form);
modpoly(form,q);
exorpoly(px,form);
sortpoly(px);
unipoly(px);
modpoly(px,q);
}
return px;
}
| 2.390625 | 2 |
2024-11-18T17:55:04.398769+00:00 | 2020-04-15T20:58:21 | 6c8a854f4db09441317f5729b4f4c62afe195cf8 | {
"blob_id": "6c8a854f4db09441317f5729b4f4c62afe195cf8",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-15T20:58:21",
"content_id": "eb94ec6a7ddd8cab35a832aacb83c8d385749ebb",
"detected_licenses": [
"MIT"
],
"directory_id": "ebc700cb11b49d5319544d3f7bbc8882250a8e5a",
"extension": "c",
"filename": "interrupt0.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 264354106,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1461,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/altium_crap/Soft Designs/Legacy/NB1/EX01/MAX1104_C/interrupt0.c",
"provenance": "stackv2-0005.json.gz:5098",
"repo_name": "hanun2999/Altium-Schematic-Parser",
"revision_date": "2020-04-15T20:58:21",
"revision_id": "a9bd5b1a865f92f2e3f749433fb29107af528498",
"snapshot_id": "1c6dde56f673f7cb2a517f7dba8596e55282b246",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/hanun2999/Altium-Schematic-Parser/a9bd5b1a865f92f2e3f749433fb29107af528498/tests/altium_crap/Soft Designs/Legacy/NB1/EX01/MAX1104_C/interrupt0.c",
"visit_date": "2022-04-16T21:43:18.502597"
} | stackv2 | #include "Interrupt0.h"
// INT 0 /////////////////////////////////////////////////
__interrupt(0*8+3) void Interrupt0IntHandler( void )
{
Interrupt0();
}
void InitInterrupt0( void )
{
IT0 = 1;
EX0 = 1; /* Enable Int0 interrupt */
}
void EnableInt0Interrupt( void )
{
EX0 = 1; /* Enable timer 0 interrupt */
}
void DisableInt0Interrupt( void )
{
EX0 = 0; /* Disable Int 0 interrupt */
}
__interrupt(2*8+3) void Interrupt1IntHandler( void )
{
Interrupt1();
}
void InitInterrupt1( void )
{
IT1 = 1;
EX1 = 1; /* Enable Int0 interrupt */
}
void EnableInt1Interrupt( void )
{
EX1 = 1; /* Enable timer 0 interrupt */
}
void DisableInt1Interrupt( void )
{
EX1 = 0; /* Disable Int 0 interrupt */
}
// Timer 0 /////////////////////////////////////////////////
__interrupt(1*8+3) void Timer0IntHandler( void )
{
// TH0 = 2;
Timer0Interrupt();
}
void InitTimer0(WORD hzFreq )
{
BYTE temp;
TMOD = 0x02; // Timer0 Mode 2
// TH0 = MODE_2_TIMER(hzFreq);
temp = MODE_2_TIMER(22050);
TH0 = temp;
TR0 = 1; // Enable Timer0
ET0 = 1; // Enable Timer0 interrupt
}
void EnableTimer0Interrupt( void )
{
ET0 = 1; /* Enable timer 0 interrupt */
}
void DisableTimer0Interrupt( void )
{
ET0 = 0; /* Disable Int 0 interrupt */
}
| 2.5 | 2 |
2024-11-18T17:55:04.626009+00:00 | 2021-05-29T13:56:08 | 1e97749c1ed94b734bb87a20a7449b9e2f26c150 | {
"blob_id": "1e97749c1ed94b734bb87a20a7449b9e2f26c150",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-29T13:56:08",
"content_id": "9ecf31d729776cda06d1911b97e31b0a606125f4",
"detected_licenses": [
"MIT"
],
"directory_id": "14b3a0d91284d5c929b113f351799f0e3361a327",
"extension": "c",
"filename": "limpa.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 311709947,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 390,
"license": "MIT",
"license_type": "permissive",
"path": "/docs/conio_orientacoes/usodeconio/limpa.c",
"provenance": "stackv2-0005.json.gz:5354",
"repo_name": "ArthurHW/Lolo-s-Adventure-Game",
"revision_date": "2021-05-29T13:56:08",
"revision_id": "656d4346d4bbb79808688a2303e93604aafedbe0",
"snapshot_id": "e2d53f9c0e07330c8ad05662f71ffbe4b726729c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/ArthurHW/Lolo-s-Adventure-Game/656d4346d4bbb79808688a2303e93604aafedbe0/docs/conio_orientacoes/usodeconio/limpa.c",
"visit_date": "2023-05-04T10:10:19.607813"
} | stackv2 | /*
Programa: limpa.c
Autor: Liviu Gabriel Anghel
Objetivo: limpar tela
Aprender usar clrscr();
Data: 14/05/2002
*/
/* Bibliotecas usadas pelo programa */
#include <stdio.h>
#include <conio2.h>
void main (void)
{
char s[80];
puts("Entre com uma frase");
gets(s);
puts("Aperta qualquer tecla para limpar a tela");
getchar();
clrscr();
puts("Parabens!");
getchar();
}
| 3.046875 | 3 |
2024-11-18T17:55:04.957558+00:00 | 2015-05-01T08:41:31 | 08cf7647647b868e4ff1fa118fce2e1af9b0816a | {
"blob_id": "08cf7647647b868e4ff1fa118fce2e1af9b0816a",
"branch_name": "refs/heads/master",
"committer_date": "2015-05-01T08:41:31",
"content_id": "f0cf6f660a75e04349068b9055a3884efd5e663d",
"detected_licenses": [
"MIT"
],
"directory_id": "2c5ce2b5deb73aa8fef4b984f9534bbb2ef33c98",
"extension": "c",
"filename": "factor.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 33067786,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 928,
"license": "MIT",
"license_type": "permissive",
"path": "/challenges/factor/factor.c",
"provenance": "stackv2-0005.json.gz:5482",
"repo_name": "Jexah/comp2129",
"revision_date": "2015-05-01T08:41:31",
"revision_id": "296afc684541717a1800af4ad86b7d40f605dd29",
"snapshot_id": "ce45797c56cf106781a420647ae01773cd6036d7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Jexah/comp2129/296afc684541717a1800af4ad86b7d40f605dd29/challenges/factor/factor.c",
"visit_date": "2020-05-28T13:47:03.752492"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void printPrimeFactorsAsString(int input)
{
int first = 1;
for(int i = 2; i <= input; ++i)
{
if(input % i == 0)
{
int notPrime = 0;
for(int j = 2; j <= i; ++j)
{
if(i % j == 0 && i != j)
{
notPrime = 1;
break;
}
}
if(!notPrime)
{
input /= i;
printf((first?"%d":" %d"), i);
i = 1;
first = 0;
}
}
}
}
int main(void)
{
char *buffer = calloc(sizeof(char), 11);
if(fgets(buffer, sizeof(char)*11, stdin))
{
for(int i = 0; i < 11; ++i)
{
if(*(buffer+i) != 0 && *(buffer+i) != '\n' && *(buffer+i) != '-' && !isdigit(*(buffer+i)))
{
printf("Invalid input\n");
return 1;
}
}
int number = atoi(buffer);
if(number <= 1)
{
printf("%d has no prime factors", number);
return 1;
}
printPrimeFactorsAsString(number);
return 0;
}
printf("Invalid input\n");
return 1;
}
| 3.4375 | 3 |
2024-11-18T17:55:05.025214+00:00 | 2019-08-16T20:38:59 | bda0f85b324737ebda16e99a00900145061e83cd | {
"blob_id": "bda0f85b324737ebda16e99a00900145061e83cd",
"branch_name": "refs/heads/ms-iot",
"committer_date": "2019-08-16T20:38:59",
"content_id": "1cc9a6107301a475b7327e9124fae9e882a76e67",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "c695e8d1b85094e180b05c8782bd81f2a182fe72",
"extension": "c",
"filename": "aes-cts.c",
"fork_events_count": 16,
"gha_created_at": "2017-03-13T22:09:30",
"gha_event_created_at": "2019-10-23T20:40:13",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 84879344,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3454,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/core/crypto/aes-cts.c",
"provenance": "stackv2-0005.json.gz:5610",
"repo_name": "ms-iot/optee_os",
"revision_date": "2019-08-16T20:38:59",
"revision_id": "59e21ac8e9e461b50d7328eeabe89d47d3d67fa4",
"snapshot_id": "f6a6408bbb62ec06320fe627c04d6661d52ec038",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/ms-iot/optee_os/59e21ac8e9e461b50d7328eeabe89d47d3d67fa4/core/crypto/aes-cts.c",
"visit_date": "2022-04-01T01:08:54.175594"
} | stackv2 | // SPDX-License-Identifier: BSD-2-Clause
/*
* Copyright (c) 2014-2019, Linaro Limited
*/
#include <assert.h>
#include <crypto/crypto.h>
#include <crypto/crypto_impl.h>
#include <stdlib.h>
#include <tee_api_types.h>
#include <tee/tee_cryp_utl.h>
#include <util.h>
/* From libtomcrypt doc:
* Ciphertext stealing is a method of dealing with messages
* in CBC mode which are not a multiple of the block
* length. This is accomplished by encrypting the last
* ciphertext block in ECB mode, and XOR'ing the output
* against the last partial block of plaintext. LibTomCrypt
* does not support this mode directly but it is fairly
* easy to emulate with a call to the cipher's
* ecb encrypt() callback function.
* The more sane way to deal with partial blocks is to pad
* them with zeroes, and then use CBC normally
*/
/*
* From Global Platform: CTS = CBC-CS3
*/
struct cts_ctx {
struct crypto_cipher_ctx ctx;
struct crypto_cipher_ctx *ecb;
struct crypto_cipher_ctx *cbc;
TEE_OperationMode mode;
};
static const struct crypto_cipher_ops cts_ops;
static struct cts_ctx *to_cts_ctx(struct crypto_cipher_ctx *ctx)
{
assert(ctx && ctx->ops == &cts_ops);
return container_of(ctx, struct cts_ctx, ctx);
}
static TEE_Result cts_init(struct crypto_cipher_ctx *ctx,
TEE_OperationMode mode, const uint8_t *key1,
size_t key1_len, const uint8_t *key2,
size_t key2_len, const uint8_t *iv, size_t iv_len)
{
TEE_Result res = TEE_SUCCESS;
struct cts_ctx *c = to_cts_ctx(ctx);
c->mode = mode;
res = crypto_cipher_init(c->ecb, TEE_ALG_AES_ECB_NOPAD, mode, key1,
key1_len, key2, key2_len, iv, iv_len);
if (res)
return res;
return crypto_cipher_init(c->cbc, TEE_ALG_AES_CBC_NOPAD, mode, key1,
key1_len, key2, key2_len, iv, iv_len);
}
static TEE_Result cts_update(struct crypto_cipher_ctx *ctx, bool last_block,
const uint8_t *data, size_t len, uint8_t *dst)
{
struct cts_ctx *c = to_cts_ctx(ctx);
return tee_aes_cbc_cts_update(c->cbc, c->ecb, c->mode, last_block,
data, len, dst);
}
static void cts_final(struct crypto_cipher_ctx *ctx)
{
struct cts_ctx *c = to_cts_ctx(ctx);
crypto_cipher_final(c->cbc, TEE_ALG_AES_CBC_NOPAD);
crypto_cipher_final(c->ecb, TEE_ALG_AES_ECB_NOPAD);
}
static void cts_free_ctx(struct crypto_cipher_ctx *ctx)
{
struct cts_ctx *c = to_cts_ctx(ctx);
crypto_cipher_free_ctx(c->cbc, TEE_ALG_AES_CBC_NOPAD);
crypto_cipher_free_ctx(c->ecb, TEE_ALG_AES_ECB_NOPAD);
free(c);
}
static void cts_copy_state(struct crypto_cipher_ctx *dst_ctx,
struct crypto_cipher_ctx *src_ctx)
{
struct cts_ctx *src = to_cts_ctx(src_ctx);
struct cts_ctx *dst = to_cts_ctx(dst_ctx);
crypto_cipher_copy_state(dst->cbc, src->cbc, TEE_ALG_AES_CBC_NOPAD);
crypto_cipher_copy_state(dst->ecb, src->ecb, TEE_ALG_AES_ECB_NOPAD);
}
static const struct crypto_cipher_ops cts_ops = {
.init = cts_init,
.update = cts_update,
.final = cts_final,
.free_ctx = cts_free_ctx,
.copy_state = cts_copy_state,
};
TEE_Result crypto_aes_cts_alloc_ctx(struct crypto_cipher_ctx **ctx)
{
TEE_Result res = TEE_SUCCESS;
struct cts_ctx *c = calloc(1, sizeof(*c));
if (!c)
return TEE_ERROR_OUT_OF_MEMORY;
res = crypto_aes_ecb_alloc_ctx(&c->ecb);
if (res)
goto err;
res = crypto_aes_cbc_alloc_ctx(&c->cbc);
if (res)
goto err;
c->ctx.ops = &cts_ops;
*ctx = &c->ctx;
return TEE_SUCCESS;
err:
crypto_cipher_free_ctx(c->ecb, TEE_ALG_AES_ECB_NOPAD);
free(c);
return res;
}
| 2.40625 | 2 |
2024-11-18T17:55:05.304893+00:00 | 2019-08-12T21:38:44 | 0045a7f34975d9e643ce97203aaca3771d86ad52 | {
"blob_id": "0045a7f34975d9e643ce97203aaca3771d86ad52",
"branch_name": "refs/heads/ms-iot",
"committer_date": "2019-08-12T21:38:44",
"content_id": "83fcdf4f1a7742fab38b38b9467864d6c8f319c2",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "b3f4553cea6babe8b25ed0bc0865130c69cd5c72",
"extension": "c",
"filename": "PciHostBridge.c",
"fork_events_count": 41,
"gha_created_at": "2016-02-25T21:44:37",
"gha_event_created_at": "2019-10-29T21:34:57",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 52559049,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 48658,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/PcAtChipsetPkg/PciHostBridgeDxe/PciHostBridge.c",
"provenance": "stackv2-0005.json.gz:5994",
"repo_name": "ms-iot/RPi-UEFI",
"revision_date": "2019-08-12T21:38:44",
"revision_id": "5bfd48d674e6c7efea6e31f9eb97b9da90c20263",
"snapshot_id": "d7a7c3bb9820a8f68948cc5c8d494c6dbf6a17c4",
"src_encoding": "UTF-8",
"star_events_count": 97,
"url": "https://raw.githubusercontent.com/ms-iot/RPi-UEFI/5bfd48d674e6c7efea6e31f9eb97b9da90c20263/PcAtChipsetPkg/PciHostBridgeDxe/PciHostBridge.c",
"visit_date": "2021-05-03T08:03:45.752721"
} | stackv2 | /** @file
Provides the basic interfaces to abstract a PCI Host Bridge Resource Allocation
Copyright (c) 2008 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials are
licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include "PciHostBridge.h"
//
// Hard code: Root Bridge Number within the host bridge
// Root Bridge's attribute
// Root Bridge's device path
// Root Bridge's resource appeture
//
UINTN RootBridgeNumber[1] = { 1 };
UINT64 RootBridgeAttribute[1][1] = { { EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM } };
EFI_PCI_ROOT_BRIDGE_DEVICE_PATH mEfiPciRootBridgeDevicePath[1][1] = {
{
{
{
{
ACPI_DEVICE_PATH,
ACPI_DP,
{
(UINT8) (sizeof(ACPI_HID_DEVICE_PATH)),
(UINT8) ((sizeof(ACPI_HID_DEVICE_PATH)) >> 8)
}
},
EISA_PNP_ID(0x0A03),
0
},
{
END_DEVICE_PATH_TYPE,
END_ENTIRE_DEVICE_PATH_SUBTYPE,
{
END_DEVICE_PATH_LENGTH,
0
}
}
}
}
};
PCI_ROOT_BRIDGE_RESOURCE_APPETURE mResAppeture[1][1] = {
{{0, 0xff, 0x80000000, 0xffffffff, 0, 0xffff}}
};
EFI_HANDLE mDriverImageHandle;
PCI_HOST_BRIDGE_INSTANCE mPciHostBridgeInstanceTemplate = {
PCI_HOST_BRIDGE_SIGNATURE, // Signature
NULL, // HostBridgeHandle
0, // RootBridgeNumber
{NULL, NULL}, // Head
FALSE, // ResourceSubiteed
TRUE, // CanRestarted
{
NotifyPhase,
GetNextRootBridge,
GetAttributes,
StartBusEnumeration,
SetBusNumbers,
SubmitResources,
GetProposedResources,
PreprocessController
}
};
//
// Implementation
//
/**
Entry point of this driver
@param ImageHandle Handle of driver image
@param SystemTable Point to EFI_SYSTEM_TABLE
@retval EFI_OUT_OF_RESOURCES Can not allocate memory resource
@retval EFI_DEVICE_ERROR Can not install the protocol instance
@retval EFI_SUCCESS Success to initialize the Pci host bridge.
**/
EFI_STATUS
EFIAPI
InitializePciHostBridge (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
UINTN Loop1;
UINTN Loop2;
PCI_HOST_BRIDGE_INSTANCE *HostBridge;
PCI_ROOT_BRIDGE_INSTANCE *PrivateData;
mDriverImageHandle = ImageHandle;
//
// Create Host Bridge Device Handle
//
for (Loop1 = 0; Loop1 < HOST_BRIDGE_NUMBER; Loop1++) {
HostBridge = AllocateCopyPool (sizeof(PCI_HOST_BRIDGE_INSTANCE), &mPciHostBridgeInstanceTemplate);
if (HostBridge == NULL) {
return EFI_OUT_OF_RESOURCES;
}
HostBridge->RootBridgeNumber = RootBridgeNumber[Loop1];
InitializeListHead (&HostBridge->Head);
Status = gBS->InstallMultipleProtocolInterfaces (
&HostBridge->HostBridgeHandle,
&gEfiPciHostBridgeResourceAllocationProtocolGuid, &HostBridge->ResAlloc,
NULL
);
if (EFI_ERROR (Status)) {
FreePool (HostBridge);
return EFI_DEVICE_ERROR;
}
//
// Create Root Bridge Device Handle in this Host Bridge
//
for (Loop2 = 0; Loop2 < HostBridge->RootBridgeNumber; Loop2++) {
PrivateData = AllocateZeroPool (sizeof(PCI_ROOT_BRIDGE_INSTANCE));
if (PrivateData == NULL) {
return EFI_OUT_OF_RESOURCES;
}
PrivateData->Signature = PCI_ROOT_BRIDGE_SIGNATURE;
PrivateData->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)&mEfiPciRootBridgeDevicePath[Loop1][Loop2];
RootBridgeConstructor (
&PrivateData->Io,
HostBridge->HostBridgeHandle,
RootBridgeAttribute[Loop1][Loop2],
&mResAppeture[Loop1][Loop2]
);
Status = gBS->InstallMultipleProtocolInterfaces(
&PrivateData->Handle,
&gEfiDevicePathProtocolGuid, PrivateData->DevicePath,
&gEfiPciRootBridgeIoProtocolGuid, &PrivateData->Io,
NULL
);
if (EFI_ERROR (Status)) {
FreePool(PrivateData);
return EFI_DEVICE_ERROR;
}
InsertTailList (&HostBridge->Head, &PrivateData->Link);
}
}
return EFI_SUCCESS;
}
/**
These are the notifications from the PCI bus driver that it is about to enter a certain
phase of the PCI enumeration process.
This member function can be used to notify the host bridge driver to perform specific actions,
including any chipset-specific initialization, so that the chipset is ready to enter the next phase.
Eight notification points are defined at this time. See belows:
EfiPciHostBridgeBeginEnumeration Resets the host bridge PCI apertures and internal data
structures. The PCI enumerator should issue this notification
before starting a fresh enumeration process. Enumeration cannot
be restarted after sending any other notification such as
EfiPciHostBridgeBeginBusAllocation.
EfiPciHostBridgeBeginBusAllocation The bus allocation phase is about to begin. No specific action is
required here. This notification can be used to perform any
chipset-specific programming.
EfiPciHostBridgeEndBusAllocation The bus allocation and bus programming phase is complete. No
specific action is required here. This notification can be used to
perform any chipset-specific programming.
EfiPciHostBridgeBeginResourceAllocation
The resource allocation phase is about to begin. No specific
action is required here. This notification can be used to perform
any chipset-specific programming.
EfiPciHostBridgeAllocateResources Allocates resources per previously submitted requests for all the PCI
root bridges. These resource settings are returned on the next call to
GetProposedResources(). Before calling NotifyPhase() with a Phase of
EfiPciHostBridgeAllocateResource, the PCI bus enumerator is responsible
for gathering I/O and memory requests for
all the PCI root bridges and submitting these requests using
SubmitResources(). This function pads the resource amount
to suit the root bridge hardware, takes care of dependencies between
the PCI root bridges, and calls the Global Coherency Domain (GCD)
with the allocation request. In the case of padding, the allocated range
could be bigger than what was requested.
EfiPciHostBridgeSetResources Programs the host bridge hardware to decode previously allocated
resources (proposed resources) for all the PCI root bridges. After the
hardware is programmed, reassigning resources will not be supported.
The bus settings are not affected.
EfiPciHostBridgeFreeResources Deallocates resources that were previously allocated for all the PCI
root bridges and resets the I/O and memory apertures to their initial
state. The bus settings are not affected. If the request to allocate
resources fails, the PCI enumerator can use this notification to
deallocate previous resources, adjust the requests, and retry
allocation.
EfiPciHostBridgeEndResourceAllocation The resource allocation phase is completed. No specific action is
required here. This notification can be used to perform any chipsetspecific
programming.
@param[in] This The instance pointer of EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL
@param[in] Phase The phase during enumeration
@retval EFI_NOT_READY This phase cannot be entered at this time. For example, this error
is valid for a Phase of EfiPciHostBridgeAllocateResources if
SubmitResources() has not been called for one or more
PCI root bridges before this call
@retval EFI_DEVICE_ERROR Programming failed due to a hardware error. This error is valid
for a Phase of EfiPciHostBridgeSetResources.
@retval EFI_INVALID_PARAMETER Invalid phase parameter
@retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources.
This error is valid for a Phase of EfiPciHostBridgeAllocateResources if the
previously submitted resource requests cannot be fulfilled or
were only partially fulfilled.
@retval EFI_SUCCESS The notification was accepted without any errors.
**/
EFI_STATUS
EFIAPI
NotifyPhase(
IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PHASE Phase
)
{
PCI_HOST_BRIDGE_INSTANCE *HostBridgeInstance;
PCI_ROOT_BRIDGE_INSTANCE *RootBridgeInstance;
PCI_RESOURCE_TYPE Index;
LIST_ENTRY *List;
EFI_PHYSICAL_ADDRESS BaseAddress;
UINT64 AddrLen;
UINTN BitsOfAlignment;
EFI_STATUS Status;
EFI_STATUS ReturnStatus;
HostBridgeInstance = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
switch (Phase) {
case EfiPciHostBridgeBeginEnumeration:
if (HostBridgeInstance->CanRestarted) {
//
// Reset the Each Root Bridge
//
List = HostBridgeInstance->Head.ForwardLink;
while (List != &HostBridgeInstance->Head) {
RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
for (Index = TypeIo; Index < TypeMax; Index++) {
RootBridgeInstance->ResAllocNode[Index].Type = Index;
RootBridgeInstance->ResAllocNode[Index].Base = 0;
RootBridgeInstance->ResAllocNode[Index].Length = 0;
RootBridgeInstance->ResAllocNode[Index].Status = ResNone;
}
List = List->ForwardLink;
}
HostBridgeInstance->ResourceSubmited = FALSE;
HostBridgeInstance->CanRestarted = TRUE;
} else {
//
// Can not restart
//
return EFI_NOT_READY;
}
break;
case EfiPciHostBridgeEndEnumeration:
break;
case EfiPciHostBridgeBeginBusAllocation:
//
// No specific action is required here, can perform any chipset specific programing
//
HostBridgeInstance->CanRestarted = FALSE;
break;
case EfiPciHostBridgeEndBusAllocation:
//
// No specific action is required here, can perform any chipset specific programing
//
//HostBridgeInstance->CanRestarted = FALSE;
break;
case EfiPciHostBridgeBeginResourceAllocation:
//
// No specific action is required here, can perform any chipset specific programing
//
//HostBridgeInstance->CanRestarted = FALSE;
break;
case EfiPciHostBridgeAllocateResources:
ReturnStatus = EFI_SUCCESS;
if (HostBridgeInstance->ResourceSubmited) {
//
// Take care of the resource dependencies between the root bridges
//
List = HostBridgeInstance->Head.ForwardLink;
while (List != &HostBridgeInstance->Head) {
RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
for (Index = TypeIo; Index < TypeBus; Index++) {
if (RootBridgeInstance->ResAllocNode[Index].Status != ResNone) {
AddrLen = RootBridgeInstance->ResAllocNode[Index].Length;
//
// Get the number of '1' in Alignment.
//
BitsOfAlignment = (UINTN) (HighBitSet64 (RootBridgeInstance->ResAllocNode[Index].Alignment) + 1);
switch (Index) {
case TypeIo:
//
// It is impossible for this chipset to align 0xFFFF for IO16
// So clear it
//
if (BitsOfAlignment >= 16) {
BitsOfAlignment = 0;
}
Status = gDS->AllocateIoSpace (
EfiGcdAllocateAnySearchBottomUp,
EfiGcdIoTypeIo,
BitsOfAlignment,
AddrLen,
&BaseAddress,
mDriverImageHandle,
NULL
);
if (!EFI_ERROR (Status)) {
RootBridgeInstance->ResAllocNode[Index].Base = (UINTN)BaseAddress;
RootBridgeInstance->ResAllocNode[Index].Status = ResAllocated;
} else {
ReturnStatus = Status;
if (Status != EFI_OUT_OF_RESOURCES) {
RootBridgeInstance->ResAllocNode[Index].Length = 0;
}
}
break;
case TypeMem32:
//
// It is impossible for this chipset to align 0xFFFFFFFF for Mem32
// So clear it
//
if (BitsOfAlignment >= 32) {
BitsOfAlignment = 0;
}
Status = gDS->AllocateMemorySpace (
EfiGcdAllocateAnySearchBottomUp,
EfiGcdMemoryTypeMemoryMappedIo,
BitsOfAlignment,
AddrLen,
&BaseAddress,
mDriverImageHandle,
NULL
);
if (!EFI_ERROR (Status)) {
// We were able to allocate the PCI memory
RootBridgeInstance->ResAllocNode[Index].Base = (UINTN)BaseAddress;
RootBridgeInstance->ResAllocNode[Index].Status = ResAllocated;
} else {
// Not able to allocate enough PCI memory
ReturnStatus = Status;
if (Status != EFI_OUT_OF_RESOURCES) {
RootBridgeInstance->ResAllocNode[Index].Length = 0;
}
ASSERT (FALSE);
}
break;
case TypePMem32:
case TypeMem64:
case TypePMem64:
ReturnStatus = EFI_ABORTED;
break;
default:
ASSERT (FALSE);
break;
}; //end switch
}
}
List = List->ForwardLink;
}
return ReturnStatus;
} else {
return EFI_NOT_READY;
}
break;
case EfiPciHostBridgeSetResources:
break;
case EfiPciHostBridgeFreeResources:
ReturnStatus = EFI_SUCCESS;
List = HostBridgeInstance->Head.ForwardLink;
while (List != &HostBridgeInstance->Head) {
RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
for (Index = TypeIo; Index < TypeBus; Index++) {
if (RootBridgeInstance->ResAllocNode[Index].Status == ResAllocated) {
AddrLen = RootBridgeInstance->ResAllocNode[Index].Length;
BaseAddress = RootBridgeInstance->ResAllocNode[Index].Base;
switch (Index) {
case TypeIo:
Status = gDS->FreeIoSpace (BaseAddress, AddrLen);
if (EFI_ERROR (Status)) {
ReturnStatus = Status;
}
break;
case TypeMem32:
Status = gDS->FreeMemorySpace (BaseAddress, AddrLen);
if (EFI_ERROR (Status)) {
ReturnStatus = Status;
}
break;
case TypePMem32:
break;
case TypeMem64:
break;
case TypePMem64:
break;
default:
ASSERT (FALSE);
break;
}; //end switch
RootBridgeInstance->ResAllocNode[Index].Type = Index;
RootBridgeInstance->ResAllocNode[Index].Base = 0;
RootBridgeInstance->ResAllocNode[Index].Length = 0;
RootBridgeInstance->ResAllocNode[Index].Status = ResNone;
}
}
List = List->ForwardLink;
}
HostBridgeInstance->ResourceSubmited = FALSE;
HostBridgeInstance->CanRestarted = TRUE;
return ReturnStatus;
case EfiPciHostBridgeEndResourceAllocation:
HostBridgeInstance->CanRestarted = FALSE;
break;
default:
return EFI_INVALID_PARAMETER;
}
return EFI_SUCCESS;
}
/**
Return the device handle of the next PCI root bridge that is associated with this Host Bridge.
This function is called multiple times to retrieve the device handles of all the PCI root bridges that
are associated with this PCI host bridge. Each PCI host bridge is associated with one or more PCI
root bridges. On each call, the handle that was returned by the previous call is passed into the
interface, and on output the interface returns the device handle of the next PCI root bridge. The
caller can use the handle to obtain the instance of the EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL
for that root bridge. When there are no more PCI root bridges to report, the interface returns
EFI_NOT_FOUND. A PCI enumerator must enumerate the PCI root bridges in the order that they
are returned by this function.
For D945 implementation, there is only one root bridge in PCI host bridge.
@param[in] This The instance pointer of EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL
@param[in, out] RootBridgeHandle Returns the device handle of the next PCI root bridge.
@retval EFI_SUCCESS If parameter RootBridgeHandle = NULL, then return the first Rootbridge handle of the
specific Host bridge and return EFI_SUCCESS.
@retval EFI_NOT_FOUND Can not find the any more root bridge in specific host bridge.
@retval EFI_INVALID_PARAMETER RootBridgeHandle is not an EFI_HANDLE that was
returned on a previous call to GetNextRootBridge().
**/
EFI_STATUS
EFIAPI
GetNextRootBridge(
IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
IN OUT EFI_HANDLE *RootBridgeHandle
)
{
BOOLEAN NoRootBridge;
LIST_ENTRY *List;
PCI_HOST_BRIDGE_INSTANCE *HostBridgeInstance;
PCI_ROOT_BRIDGE_INSTANCE *RootBridgeInstance;
NoRootBridge = TRUE;
HostBridgeInstance = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
List = HostBridgeInstance->Head.ForwardLink;
while (List != &HostBridgeInstance->Head) {
NoRootBridge = FALSE;
RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
if (*RootBridgeHandle == NULL) {
//
// Return the first Root Bridge Handle of the Host Bridge
//
*RootBridgeHandle = RootBridgeInstance->Handle;
return EFI_SUCCESS;
} else {
if (*RootBridgeHandle == RootBridgeInstance->Handle) {
//
// Get next if have
//
List = List->ForwardLink;
if (List!=&HostBridgeInstance->Head) {
RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
*RootBridgeHandle = RootBridgeInstance->Handle;
return EFI_SUCCESS;
} else {
return EFI_NOT_FOUND;
}
}
}
List = List->ForwardLink;
} //end while
if (NoRootBridge) {
return EFI_NOT_FOUND;
} else {
return EFI_INVALID_PARAMETER;
}
}
/**
Returns the allocation attributes of a PCI root bridge.
The function returns the allocation attributes of a specific PCI root bridge. The attributes can vary
from one PCI root bridge to another. These attributes are different from the decode-related
attributes that are returned by the EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL.GetAttributes() member function. The
RootBridgeHandle parameter is used to specify the instance of the PCI root bridge. The device
handles of all the root bridges that are associated with this host bridge must be obtained by calling
GetNextRootBridge(). The attributes are static in the sense that they do not change during or
after the enumeration process. The hardware may provide mechanisms to change the attributes on
the fly, but such changes must be completed before EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL is
installed. The permitted values of EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_ATTRIBUTES are defined in
"Related Definitions" below. The caller uses these attributes to combine multiple resource requests.
For example, if the flag EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM is set, the PCI bus enumerator needs to
include requests for the prefetchable memory in the nonprefetchable memory pool and not request any
prefetchable memory.
Attribute Description
------------------------------------ ----------------------------------------------------------------------
EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM If this bit is set, then the PCI root bridge does not support separate
windows for nonprefetchable and prefetchable memory. A PCI bus
driver needs to include requests for prefetchable memory in the
nonprefetchable memory pool.
EFI_PCI_HOST_BRIDGE_MEM64_DECODE If this bit is set, then the PCI root bridge supports 64-bit memory
windows. If this bit is not set, the PCI bus driver needs to include
requests for a 64-bit memory address in the corresponding 32-bit
memory pool.
@param[in] This The instance pointer of EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL
@param[in] RootBridgeHandle The device handle of the PCI root bridge in which the caller is interested. Type
EFI_HANDLE is defined in InstallProtocolInterface() in the UEFI 2.0 Specification.
@param[out] Attributes The pointer to attribte of root bridge, it is output parameter
@retval EFI_INVALID_PARAMETER Attribute pointer is NULL
@retval EFI_INVALID_PARAMETER RootBridgehandle is invalid.
@retval EFI_SUCCESS Success to get attribute of interested root bridge.
**/
EFI_STATUS
EFIAPI
GetAttributes(
IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
IN EFI_HANDLE RootBridgeHandle,
OUT UINT64 *Attributes
)
{
LIST_ENTRY *List;
PCI_HOST_BRIDGE_INSTANCE *HostBridgeInstance;
PCI_ROOT_BRIDGE_INSTANCE *RootBridgeInstance;
if (Attributes == NULL) {
return EFI_INVALID_PARAMETER;
}
HostBridgeInstance = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
List = HostBridgeInstance->Head.ForwardLink;
while (List != &HostBridgeInstance->Head) {
RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
if (RootBridgeHandle == RootBridgeInstance->Handle) {
*Attributes = RootBridgeInstance->RootBridgeAttrib;
return EFI_SUCCESS;
}
List = List->ForwardLink;
}
//
// RootBridgeHandle is not an EFI_HANDLE
// that was returned on a previous call to GetNextRootBridge()
//
return EFI_INVALID_PARAMETER;
}
/**
Sets up the specified PCI root bridge for the bus enumeration process.
This member function sets up the root bridge for bus enumeration and returns the PCI bus range
over which the search should be performed in ACPI 2.0 resource descriptor format.
@param[in] This The EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_ PROTOCOL instance.
@param[in] RootBridgeHandle The PCI Root Bridge to be set up.
@param[out] Configuration Pointer to the pointer to the PCI bus resource descriptor.
@retval EFI_INVALID_PARAMETER Invalid Root bridge's handle
@retval EFI_OUT_OF_RESOURCES Fail to allocate ACPI resource descriptor tag.
@retval EFI_SUCCESS Sucess to allocate ACPI resource descriptor.
**/
EFI_STATUS
EFIAPI
StartBusEnumeration(
IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
IN EFI_HANDLE RootBridgeHandle,
OUT VOID **Configuration
)
{
LIST_ENTRY *List;
PCI_HOST_BRIDGE_INSTANCE *HostBridgeInstance;
PCI_ROOT_BRIDGE_INSTANCE *RootBridgeInstance;
VOID *Buffer;
UINT8 *Temp;
UINT64 BusStart;
UINT64 BusEnd;
HostBridgeInstance = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
List = HostBridgeInstance->Head.ForwardLink;
while (List != &HostBridgeInstance->Head) {
RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
if (RootBridgeHandle == RootBridgeInstance->Handle) {
//
// Set up the Root Bridge for Bus Enumeration
//
BusStart = RootBridgeInstance->BusBase;
BusEnd = RootBridgeInstance->BusLimit;
//
// Program the Hardware(if needed) if error return EFI_DEVICE_ERROR
//
Buffer = AllocatePool (sizeof(EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) + sizeof(EFI_ACPI_END_TAG_DESCRIPTOR));
if (Buffer == NULL) {
return EFI_OUT_OF_RESOURCES;
}
Temp = (UINT8 *)Buffer;
((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp)->Desc = 0x8A;
((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp)->Len = 0x2B;
((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp)->ResType = 2;
((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp)->GenFlag = 0;
((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp)->SpecificFlag = 0;
((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp)->AddrSpaceGranularity = 0;
((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp)->AddrRangeMin = BusStart;
((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp)->AddrRangeMax = 0;
((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp)->AddrTranslationOffset = 0;
((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp)->AddrLen = BusEnd - BusStart + 1;
Temp = Temp + sizeof(EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR);
((EFI_ACPI_END_TAG_DESCRIPTOR *)Temp)->Desc = 0x79;
((EFI_ACPI_END_TAG_DESCRIPTOR *)Temp)->Checksum = 0x0;
*Configuration = Buffer;
return EFI_SUCCESS;
}
List = List->ForwardLink;
}
return EFI_INVALID_PARAMETER;
}
/**
Programs the PCI root bridge hardware so that it decodes the specified PCI bus range.
This member function programs the specified PCI root bridge to decode the bus range that is
specified by the input parameter Configuration.
The bus range information is specified in terms of the ACPI 2.0 resource descriptor format.
@param[in] This The EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_ PROTOCOL instance
@param[in] RootBridgeHandle The PCI Root Bridge whose bus range is to be programmed
@param[in] Configuration The pointer to the PCI bus resource descriptor
@retval EFI_INVALID_PARAMETER RootBridgeHandle is not a valid root bridge handle.
@retval EFI_INVALID_PARAMETER Configuration is NULL.
@retval EFI_INVALID_PARAMETER Configuration does not point to a valid ACPI 2.0 resource descriptor.
@retval EFI_INVALID_PARAMETER Configuration does not include a valid ACPI 2.0 bus resource descriptor.
@retval EFI_INVALID_PARAMETER Configuration includes valid ACPI 2.0 resource descriptors other than
bus descriptors.
@retval EFI_INVALID_PARAMETER Configuration contains one or more invalid ACPI resource descriptors.
@retval EFI_INVALID_PARAMETER "Address Range Minimum" is invalid for this root bridge.
@retval EFI_INVALID_PARAMETER "Address Range Length" is invalid for this root bridge.
@retval EFI_DEVICE_ERROR Programming failed due to a hardware error.
@retval EFI_SUCCESS The bus range for the PCI root bridge was programmed.
**/
EFI_STATUS
EFIAPI
SetBusNumbers(
IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
IN EFI_HANDLE RootBridgeHandle,
IN VOID *Configuration
)
{
LIST_ENTRY *List;
PCI_HOST_BRIDGE_INSTANCE *HostBridgeInstance;
PCI_ROOT_BRIDGE_INSTANCE *RootBridgeInstance;
UINT8 *Ptr;
UINTN BusStart;
UINTN BusEnd;
UINTN BusLen;
if (Configuration == NULL) {
return EFI_INVALID_PARAMETER;
}
Ptr = Configuration;
//
// Check the Configuration is valid
//
if(*Ptr != ACPI_ADDRESS_SPACE_DESCRIPTOR) {
return EFI_INVALID_PARAMETER;
}
if (((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Ptr)->ResType != 2) {
return EFI_INVALID_PARAMETER;
}
Ptr += sizeof(EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR);
if (*Ptr != ACPI_END_TAG_DESCRIPTOR) {
return EFI_INVALID_PARAMETER;
}
HostBridgeInstance = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
List = HostBridgeInstance->Head.ForwardLink;
Ptr = Configuration;
while (List != &HostBridgeInstance->Head) {
RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
if (RootBridgeHandle == RootBridgeInstance->Handle) {
BusStart = (UINTN)((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Ptr)->AddrRangeMin;
BusLen = (UINTN)((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Ptr)->AddrLen;
BusEnd = BusStart + BusLen - 1;
if (BusStart > BusEnd) {
return EFI_INVALID_PARAMETER;
}
if ((BusStart < RootBridgeInstance->BusBase) || (BusEnd > RootBridgeInstance->BusLimit)) {
return EFI_INVALID_PARAMETER;
}
//
// Update the Bus Range
//
RootBridgeInstance->ResAllocNode[TypeBus].Base = BusStart;
RootBridgeInstance->ResAllocNode[TypeBus].Length = BusLen;
RootBridgeInstance->ResAllocNode[TypeBus].Status = ResAllocated;
//
// Program the Root Bridge Hardware
//
return EFI_SUCCESS;
}
List = List->ForwardLink;
}
return EFI_INVALID_PARAMETER;
}
/**
Submits the I/O and memory resource requirements for the specified PCI root bridge.
This function is used to submit all the I/O and memory resources that are required by the specified
PCI root bridge. The input parameter Configuration is used to specify the following:
- The various types of resources that are required
- The associated lengths in terms of ACPI 2.0 resource descriptor format
@param[in] This Pointer to the EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL instance.
@param[in] RootBridgeHandle The PCI root bridge whose I/O and memory resource requirements are being submitted.
@param[in] Configuration The pointer to the PCI I/O and PCI memory resource descriptor.
@retval EFI_SUCCESS The I/O and memory resource requests for a PCI root bridge were accepted.
@retval EFI_INVALID_PARAMETER RootBridgeHandle is not a valid root bridge handle.
@retval EFI_INVALID_PARAMETER Configuration is NULL.
@retval EFI_INVALID_PARAMETER Configuration does not point to a valid ACPI 2.0 resource descriptor.
@retval EFI_INVALID_PARAMETER Configuration includes requests for one or more resource types that are
not supported by this PCI root bridge. This error will happen if the caller
did not combine resources according to Attributes that were returned by
GetAllocAttributes().
@retval EFI_INVALID_PARAMETER Address Range Maximum" is invalid.
@retval EFI_INVALID_PARAMETER "Address Range Length" is invalid for this PCI root bridge.
@retval EFI_INVALID_PARAMETER "Address Space Granularity" is invalid for this PCI root bridge.
**/
EFI_STATUS
EFIAPI
SubmitResources(
IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
IN EFI_HANDLE RootBridgeHandle,
IN VOID *Configuration
)
{
LIST_ENTRY *List;
PCI_HOST_BRIDGE_INSTANCE *HostBridgeInstance;
PCI_ROOT_BRIDGE_INSTANCE *RootBridgeInstance;
UINT8 *Temp;
EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Ptr;
UINT64 AddrLen;
UINT64 Alignment;
//
// Check the input parameter: Configuration
//
if (Configuration == NULL) {
return EFI_INVALID_PARAMETER;
}
HostBridgeInstance = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
List = HostBridgeInstance->Head.ForwardLink;
Temp = (UINT8 *)Configuration;
while ( *Temp == 0x8A) {
Temp += sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) ;
}
if (*Temp != 0x79) {
return EFI_INVALID_PARAMETER;
}
Temp = (UINT8 *)Configuration;
while (List != &HostBridgeInstance->Head) {
RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
if (RootBridgeHandle == RootBridgeInstance->Handle) {
while ( *Temp == 0x8A) {
Ptr = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp ;
//
// Check Address Length
//
if (Ptr->AddrLen > 0xffffffff) {
return EFI_INVALID_PARAMETER;
}
//
// Check address range alignment
//
if (Ptr->AddrRangeMax >= 0xffffffff || Ptr->AddrRangeMax != (GetPowerOfTwo64 (Ptr->AddrRangeMax + 1) - 1)) {
return EFI_INVALID_PARAMETER;
}
switch (Ptr->ResType) {
case 0:
//
// Check invalid Address Sapce Granularity
//
if (Ptr->AddrSpaceGranularity != 32) {
return EFI_INVALID_PARAMETER;
}
//
// check the memory resource request is supported by PCI root bridge
//
if (RootBridgeInstance->RootBridgeAttrib == EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM &&
Ptr->SpecificFlag == 0x06) {
return EFI_INVALID_PARAMETER;
}
AddrLen = Ptr->AddrLen;
Alignment = Ptr->AddrRangeMax;
if (Ptr->AddrSpaceGranularity == 32) {
if (Ptr->SpecificFlag == 0x06) {
//
// Apply from GCD
//
RootBridgeInstance->ResAllocNode[TypePMem32].Status = ResSubmitted;
} else {
RootBridgeInstance->ResAllocNode[TypeMem32].Length = AddrLen;
RootBridgeInstance->ResAllocNode[TypeMem32].Alignment = Alignment;
RootBridgeInstance->ResAllocNode[TypeMem32].Status = ResRequested;
HostBridgeInstance->ResourceSubmited = TRUE;
}
}
if (Ptr->AddrSpaceGranularity == 64) {
if (Ptr->SpecificFlag == 0x06) {
RootBridgeInstance->ResAllocNode[TypePMem64].Status = ResSubmitted;
} else {
RootBridgeInstance->ResAllocNode[TypeMem64].Status = ResSubmitted;
}
}
break;
case 1:
AddrLen = (UINTN) Ptr->AddrLen;
Alignment = (UINTN) Ptr->AddrRangeMax;
RootBridgeInstance->ResAllocNode[TypeIo].Length = AddrLen;
RootBridgeInstance->ResAllocNode[TypeIo].Alignment = Alignment;
RootBridgeInstance->ResAllocNode[TypeIo].Status = ResRequested;
HostBridgeInstance->ResourceSubmited = TRUE;
break;
default:
break;
};
Temp += sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) ;
}
return EFI_SUCCESS;
}
List = List->ForwardLink;
}
return EFI_INVALID_PARAMETER;
}
/**
Returns the proposed resource settings for the specified PCI root bridge.
This member function returns the proposed resource settings for the specified PCI root bridge. The
proposed resource settings are prepared when NotifyPhase() is called with a Phase of
EfiPciHostBridgeAllocateResources. The output parameter Configuration
specifies the following:
- The various types of resources, excluding bus resources, that are allocated
- The associated lengths in terms of ACPI 2.0 resource descriptor format
@param[in] This Pointer to the EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL instance.
@param[in] RootBridgeHandle The PCI root bridge handle. Type EFI_HANDLE is defined in InstallProtocolInterface() in the UEFI 2.0 Specification.
@param[out] Configuration The pointer to the pointer to the PCI I/O and memory resource descriptor.
@retval EFI_SUCCESS The requested parameters were returned.
@retval EFI_INVALID_PARAMETER RootBridgeHandle is not a valid root bridge handle.
@retval EFI_DEVICE_ERROR Programming failed due to a hardware error.
@retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources.
**/
EFI_STATUS
EFIAPI
GetProposedResources(
IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
IN EFI_HANDLE RootBridgeHandle,
OUT VOID **Configuration
)
{
LIST_ENTRY *List;
PCI_HOST_BRIDGE_INSTANCE *HostBridgeInstance;
PCI_ROOT_BRIDGE_INSTANCE *RootBridgeInstance;
UINTN Index;
UINTN Number;
VOID *Buffer;
UINT8 *Temp;
EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Ptr;
UINT64 ResStatus;
Buffer = NULL;
Number = 0;
//
// Get the Host Bridge Instance from the resource allocation protocol
//
HostBridgeInstance = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
List = HostBridgeInstance->Head.ForwardLink;
//
// Enumerate the root bridges in this host bridge
//
while (List != &HostBridgeInstance->Head) {
RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
if (RootBridgeHandle == RootBridgeInstance->Handle) {
for (Index = 0; Index < TypeBus; Index ++) {
if (RootBridgeInstance->ResAllocNode[Index].Status != ResNone) {
Number ++;
}
}
if (Number == 0) {
return EFI_INVALID_PARAMETER;
}
Buffer = AllocateZeroPool (Number * sizeof(EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) + sizeof(EFI_ACPI_END_TAG_DESCRIPTOR));
if (Buffer == NULL) {
return EFI_OUT_OF_RESOURCES;
}
Temp = Buffer;
for (Index = 0; Index < TypeBus; Index ++) {
if (RootBridgeInstance->ResAllocNode[Index].Status != ResNone) {
Ptr = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp ;
ResStatus = RootBridgeInstance->ResAllocNode[Index].Status;
switch (Index) {
case TypeIo:
//
// Io
//
Ptr->Desc = 0x8A;
Ptr->Len = 0x2B;
Ptr->ResType = 1;
Ptr->GenFlag = 0;
Ptr->SpecificFlag = 0;
Ptr->AddrRangeMin = RootBridgeInstance->ResAllocNode[Index].Base;
Ptr->AddrRangeMax = 0;
Ptr->AddrTranslationOffset = \
(ResStatus == ResAllocated) ? EFI_RESOURCE_SATISFIED : EFI_RESOURCE_LESS;
Ptr->AddrLen = RootBridgeInstance->ResAllocNode[Index].Length;
break;
case TypeMem32:
//
// Memory 32
//
Ptr->Desc = 0x8A;
Ptr->Len = 0x2B;
Ptr->ResType = 0;
Ptr->GenFlag = 0;
Ptr->SpecificFlag = 0;
Ptr->AddrSpaceGranularity = 32;
Ptr->AddrRangeMin = RootBridgeInstance->ResAllocNode[Index].Base;
Ptr->AddrRangeMax = 0;
Ptr->AddrTranslationOffset = \
(ResStatus == ResAllocated) ? EFI_RESOURCE_SATISFIED : EFI_RESOURCE_LESS;
Ptr->AddrLen = RootBridgeInstance->ResAllocNode[Index].Length;
break;
case TypePMem32:
//
// Prefetch memory 32
//
Ptr->Desc = 0x8A;
Ptr->Len = 0x2B;
Ptr->ResType = 0;
Ptr->GenFlag = 0;
Ptr->SpecificFlag = 6;
Ptr->AddrSpaceGranularity = 32;
Ptr->AddrRangeMin = 0;
Ptr->AddrRangeMax = 0;
Ptr->AddrTranslationOffset = EFI_RESOURCE_NONEXISTENT;
Ptr->AddrLen = 0;
break;
case TypeMem64:
//
// Memory 64
//
Ptr->Desc = 0x8A;
Ptr->Len = 0x2B;
Ptr->ResType = 0;
Ptr->GenFlag = 0;
Ptr->SpecificFlag = 0;
Ptr->AddrSpaceGranularity = 64;
Ptr->AddrRangeMin = 0;
Ptr->AddrRangeMax = 0;
Ptr->AddrTranslationOffset = EFI_RESOURCE_NONEXISTENT;
Ptr->AddrLen = 0;
break;
case TypePMem64:
//
// Prefetch memory 64
//
Ptr->Desc = 0x8A;
Ptr->Len = 0x2B;
Ptr->ResType = 0;
Ptr->GenFlag = 0;
Ptr->SpecificFlag = 6;
Ptr->AddrSpaceGranularity = 64;
Ptr->AddrRangeMin = 0;
Ptr->AddrRangeMax = 0;
Ptr->AddrTranslationOffset = EFI_RESOURCE_NONEXISTENT;
Ptr->AddrLen = 0;
break;
};
Temp += sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR);
}
}
((EFI_ACPI_END_TAG_DESCRIPTOR *)Temp)->Desc = 0x79;
((EFI_ACPI_END_TAG_DESCRIPTOR *)Temp)->Checksum = 0x0;
*Configuration = Buffer;
return EFI_SUCCESS;
}
List = List->ForwardLink;
}
return EFI_INVALID_PARAMETER;
}
/**
Provides the hooks from the PCI bus driver to every PCI controller (device/function) at various
stages of the PCI enumeration process that allow the host bridge driver to preinitialize individual
PCI controllers before enumeration.
This function is called during the PCI enumeration process. No specific action is expected from this
member function. It allows the host bridge driver to preinitialize individual PCI controllers before
enumeration.
@param This Pointer to the EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL instance.
@param RootBridgeHandle The associated PCI root bridge handle. Type EFI_HANDLE is defined in
InstallProtocolInterface() in the UEFI 2.0 Specification.
@param PciAddress The address of the PCI device on the PCI bus. This address can be passed to the
EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL member functions to access the PCI
configuration space of the device. See Table 12-1 in the UEFI 2.0 Specification for
the definition of EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_PCI_ADDRESS.
@param Phase The phase of the PCI device enumeration.
@retval EFI_SUCCESS The requested parameters were returned.
@retval EFI_INVALID_PARAMETER RootBridgeHandle is not a valid root bridge handle.
@retval EFI_INVALID_PARAMETER Phase is not a valid phase that is defined in
EFI_PCI_CONTROLLER_RESOURCE_ALLOCATION_PHASE.
@retval EFI_DEVICE_ERROR Programming failed due to a hardware error. The PCI enumerator should
not enumerate this device, including its child devices if it is a PCI-to-PCI
bridge.
**/
EFI_STATUS
EFIAPI
PreprocessController (
IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
IN EFI_HANDLE RootBridgeHandle,
IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_PCI_ADDRESS PciAddress,
IN EFI_PCI_CONTROLLER_RESOURCE_ALLOCATION_PHASE Phase
)
{
PCI_HOST_BRIDGE_INSTANCE *HostBridgeInstance;
PCI_ROOT_BRIDGE_INSTANCE *RootBridgeInstance;
LIST_ENTRY *List;
HostBridgeInstance = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
List = HostBridgeInstance->Head.ForwardLink;
//
// Enumerate the root bridges in this host bridge
//
while (List != &HostBridgeInstance->Head) {
RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
if (RootBridgeHandle == RootBridgeInstance->Handle) {
break;
}
List = List->ForwardLink;
}
if (List == &HostBridgeInstance->Head) {
return EFI_INVALID_PARAMETER;
}
if ((UINT32)Phase > EfiPciBeforeResourceCollection) {
return EFI_INVALID_PARAMETER;
}
return EFI_SUCCESS;
}
| 2.140625 | 2 |
2024-11-18T17:55:05.472124+00:00 | 2021-05-31T10:23:43 | 32af3874b2ff17796f7318808c9db2b5a57e635b | {
"blob_id": "32af3874b2ff17796f7318808c9db2b5a57e635b",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-31T10:23:43",
"content_id": "ae70a79f7e3d43eb99d748773e6d29902cb5ac47",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "40e2c30062b0fbac739feae547b5f8827692b114",
"extension": "c",
"filename": "icicle_sys.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": 4764,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/zephyr/soc/riscv/riscv-privilege/icicle/icicle_sys.c",
"provenance": "stackv2-0005.json.gz:6122",
"repo_name": "nitindeshpande/polarfire-soc-zephyr-applications",
"revision_date": "2021-05-31T10:23:43",
"revision_id": "3813f97eff2a4aa8fc8191c5e95e06bf5e6d6f01",
"snapshot_id": "411b1fd5f4b76abea7746c32551374af3f156b9e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nitindeshpande/polarfire-soc-zephyr-applications/3813f97eff2a4aa8fc8191c5e95e06bf5e6d6f01/zephyr/soc/riscv/riscv-privilege/icicle/icicle_sys.c",
"visit_date": "2023-05-08T02:47:13.420269"
} | stackv2 | /*
* Copyright (c) 2021 Sagar Khadgi <[email protected]>
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <init.h>
#include "icicle_sys.h"
#include "encoding.h"
#include "mss_sysreg.h"
#include "mss_plic.h"
#include "mss_gpio.h"
inline void PLIC_init(void);
/* Selects the 16MHz oscilator on the HiFive1 board, which provides a clock
* that's accurate enough to actually drive serial ports off of.
*/
uint8_t icicleIRQHandler(void);
volatile uint32_t * p_gpio = (volatile uint32_t* )(0x20122000);
uint32_t a_gpio[5] = {0x00};
volatile uint32_t * p_subblock = (volatile uint32_t* )(0x20122084);
volatile uint32_t * p_softreset = (volatile uint32_t* )(0x20122088);
static int pre_icicle_init(const struct device *dev)
{
ARG_UNUSED(dev);
SYSREG->SUBBLK_CLOCK_CR |= (SUBBLK_CLOCK_CR_MMUART0_MASK | SUBBLK_CLOCK_CR_GPIO2_MASK | SUBBLK_CLOCK_CR_TIMER_MASK);
/* Remove soft reset */
SYSREG->SOFT_RESET_CR &= ~(SOFT_RESET_CR_MMUART0_MASK | SOFT_RESET_CR_GPIO2_MASK | SOFT_RESET_CR_TIMER_MASK);
SYSREG->SUBBLK_CLOCK_CR = 0xffffffff;
}
static int icicle_init(const struct device *dev)
{
ARG_UNUSED(dev);
int int_num, i;
PLIC_init();
#if 0
/* Initialization*/
// *(p_gpio+0x80) = 0xFFFFFFFFU;
// a_gpio[0] = (p_gpio+0x80);
*(p_gpio+0x20) = 0xFFFFFFFFU;
a_gpio[0] = (p_gpio+0x20);
for(volatile uint32_t i = 200; i>0; i--);
/* Configuring as O/P */
// *(p_gpio+0x40) = 0x00000005;
// a_gpio[1] = (p_gpio+0x40);
*(p_gpio+0x10) = 0x00000005;
a_gpio[1] = (p_gpio+0x10);
for(volatile uint32_t i = 200; i>0; i--);
/* Setting output to 0*/
// *(p_gpio+0x88) = 0x0;
// a_gpio[2] = (p_gpio+0x88);
*(p_gpio+0x22) = 0x0;
a_gpio[2] = (p_gpio+0x22);
for(volatile uint32_t i = 200; i>0; i--);
/* Setting GPIO_16 to 1*/
// *(p_gpio+0xA4) = 0x01 << 16;
// a_gpio[3] = (p_gpio+0xA4);
*(p_gpio+0x29) = 0x01 << 16;
a_gpio[3] = (p_gpio+0x29);
for(volatile uint32_t i = 200; i>0; i--);
#endif
SYSREG->GPIO_INTERRUPT_FAB_CR = 0xFFFFFFFFUL;
PLIC_SetPriority_Threshold(0);
for (int_num = 0u; int_num <= GPIO2_NON_DIRECT_PLIC; int_num++)
{
PLIC_SetPriority(GPIO0_BIT0_or_GPIO2_BIT0_PLIC_0 + int_num, 2u);
}
MSS_GPIO_init(GPIO2_LO);
for (int cnt = 16u; cnt< 20u; cnt++)
{
MSS_GPIO_config(GPIO2_LO,
cnt,
MSS_GPIO_OUTPUT_MODE);
}
MSS_GPIO_config(GPIO2_LO, MSS_GPIO_26, MSS_GPIO_OUTPUT_MODE);
MSS_GPIO_config(GPIO2_LO, MSS_GPIO_27, MSS_GPIO_OUTPUT_MODE);
MSS_GPIO_config(GPIO2_LO, MSS_GPIO_28, MSS_GPIO_OUTPUT_MODE);
MSS_GPIO_set_output(GPIO2_LO, MSS_GPIO_26, 0u);
MSS_GPIO_set_output(GPIO2_LO, MSS_GPIO_27, 0u);
MSS_GPIO_set_output(GPIO2_LO, MSS_GPIO_28, 0u);
MSS_GPIO_config(GPIO2_LO,
MSS_GPIO_30,
MSS_GPIO_INPUT_MODE | MSS_GPIO_IRQ_LEVEL_HIGH);
MSS_GPIO_config(GPIO2_LO,
MSS_GPIO_31,
MSS_GPIO_INPUT_MODE | MSS_GPIO_IRQ_LEVEL_HIGH);
MSS_GPIO_set_outputs(GPIO2_LO, 0u);
#if 1
MSS_GPIO_set_output(GPIO2_LO, MSS_GPIO_16, 1u);
MSS_GPIO_set_output(GPIO2_LO, MSS_GPIO_17, 1u);
MSS_GPIO_set_output(GPIO2_LO, MSS_GPIO_18, 1u);
#endif
/* Setup IRQ handler for PLIC driver */
IRQ_CONNECT(MSS_GPIO_30+13,
0,
icicleIRQHandler,
NULL,
0);
/* Setup IRQ handler for PLIC driver */
IRQ_CONNECT(MSS_GPIO_31+13,
0,
icicleIRQHandler,
NULL,
0);
MSS_GPIO_enable_irq(GPIO2_LO, MSS_GPIO_30);
MSS_GPIO_enable_irq(GPIO2_LO, MSS_GPIO_31);
/* Enable IRQ for PLIC driver */
//irq_enable(RISCV_MACHINE_EXT_IRQ);
//Read back registers
#if 0
volatile uint32_t *p_prio = 0xC000004;
volatile uint32_t * p_intrenab = 0xC002000;
volatile uint32_t * p_intrpend = 0xC001000;
volatile uint32_t prio_arr[54] = {0x00};
volatile uint32_t intrenab_arr[6] = {0x00};
volatile uint32_t intrpen_arr[6] = {0x00};
//read Priority reg
for(i = 1 ; i<= 53; i++)
{
prio_arr[i] = *p_prio;
p_prio++;
}
//read Interrupt enable register
for(i = 0 ; i < 6; i++)
{
intrenab_arr[i] = *p_intrenab;
p_intrenab++;
}
//read Interrupt pending register
for(i = 0 ; i < 6; i++)
{
intrpen_arr[i] = *p_intrpend;
p_intrpend++;
}
#endif
return 0;
}
uint8_t icicleIRQHandler(void)
{
MSS_GPIO_set_outputs(GPIO2_LO, 0u);
return 0;
}
SYS_INIT(pre_icicle_init, PRE_KERNEL_1, 0);
SYS_INIT(icicle_init, PRE_KERNEL_1, 2);
| 2.234375 | 2 |
2024-11-18T17:55:05.540536+00:00 | 2020-10-07T02:35:18 | 3b851b282463b6cacb6e8f833ab419983964e6f5 | {
"blob_id": "3b851b282463b6cacb6e8f833ab419983964e6f5",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-07T02:35:18",
"content_id": "8f24b94b6d3825c6fefc8811ee205966248eb051",
"detected_licenses": [
"MIT"
],
"directory_id": "49acd1bf41c9651967e492f8294c8280bcf303e0",
"extension": "h",
"filename": "genwait.h",
"fork_events_count": 1,
"gha_created_at": "2019-11-06T01:33:50",
"gha_event_created_at": "2020-10-07T02:35:19",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 219886102,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5875,
"license": "MIT",
"license_type": "permissive",
"path": "/deps/dc/kos/include/kos/genwait.h",
"provenance": "stackv2-0005.json.gz:6250",
"repo_name": "einsteinx2/glex",
"revision_date": "2020-10-07T02:35:18",
"revision_id": "87c41fd03a30beb7272635efb4fe62917ab039f2",
"snapshot_id": "4ddd7a6a4937843e041ea95beec608a77a2957d8",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/einsteinx2/glex/87c41fd03a30beb7272635efb4fe62917ab039f2/deps/dc/kos/include/kos/genwait.h",
"visit_date": "2021-07-17T19:28:03.085824"
} | stackv2 | /* KallistiOS ##version##
include/kos/genwait.h
Copyright (C) 2003 Dan Potter
Copyright (C) 2012 Lawrence Sebald
*/
/** \file kos/genwait.h
\brief Generic wait system.
The generic wait system in KOS, like many other portions of KOS, is based on
an idea from the BSD kernel. It allows you to sleep on any random object and
later wake up any threads that happen to be sleeping on thta object. All of
KOS' sync primatives (other than spinlocks) are based on this concept, and
it can be used for some fairly useful things.
\author Dan Potter
\author Lawrence Sebald
*/
#ifndef __KOS_GENWAIT_H
#define __KOS_GENWAIT_H
#include <sys/cdefs.h>
__BEGIN_DECLS
#include <kos/thread.h>
/** \brief Sleep on an object.
This function sleeps on the specified object. You are not allowed to call
this function inside an interrupt.
\param obj The object to sleep on
\param mesg A message to show in the status
\param timeout If not woken before this many milliseconds have
passed, wake up anyway
\param callback If non-NULL, call this function with obj as its
argument if the wait times out (but before the
calling thread has been woken back up)
\retval 0 On successfully being woken up (not by timeout)
\retval -1 On error or being woken by timeout
\par Error Conditions:
\em EAGAIN - on timeout
*/
int genwait_wait(void * obj, const char * mesg, int timeout, void (*callback)(void *));
/* Wake up N threads waiting on the given object. If cnt is <=0, then we
wake all threads. Returns the number of threads actually woken. */
/** \brief Wake up a number of threads sleeping on an object.
This function wakes up the specified number of threads sleeping on the
object specified.
\param obj The object to wake threads that are sleeping on it
\param cnt The number of threads to wake, if <= 0, wake all
\param err The errno code to set as the errno value on the
woken threads. If this is 0 (EOK), then the thread's
errno will not be changed, and the thread will get a
return value of 0 from the genwait_wait(). If it is
non-zero, the thread will get a return value of -1
and errno will be set to this value for the woken
threads.
\return The number of threads woken
*/
int genwait_wake_cnt(void * obj, int cnt, int err);
/** \brief Wake up all threads sleeping on an object.
This function simply calls genwait_wake_cnt(obj, -1, 0).
\param obj The object to wake threads that are sleeping on it
\see genwait_wake_cnt()
*/
void genwait_wake_all(void * obj);
/** \brief Wake up one thread sleeping on an object.
This function simply calls genwait_wake_cnt(obj, 1, 0).
\param obj The object to wake threads that are sleeping on it
\see genwait_wake_cnt()
*/
void genwait_wake_one(void * obj);
/** \brief Wake up all threads sleeping on an object, with an error.
This function simply calls genwait_wake_cnt(obj, -1, err).
\param obj The object to wake threads that are sleeping on it
\param err The value to set in the threads' errno values
\see genwait_wake_cnt()
*/
void genwait_wake_all_err(void *obj, int err);
/** \brief Wake up one thread sleeping on an object, with an error.
This function simply calls genwait_wake_cnt(obj, 1, err).
\param obj The object to wake threads that are sleeping on it
\param err The value to set in the threads' errno values
\see genwait_wake_cnt()
*/
void genwait_wake_one_err(void *obj, int err);
/** \brief Wake up a specific thread that is sleeping on an object.
This function wakes up the specfied thread, assuming it is sleeping on the
specified object.
\param obj The object to wake the thread from
\param thd The specific thread to wake
\param err The errno code to set as the errno value on the
woken thread. If this is 0 (EOK), then the thread's
errno will not be changed, and the thread will get a
return value of 0 from the genwait_wait(). If it is
non-zero, the thread will get a return value of -1
and errno will be set to this value for the woken
threads.
\return The number of threads woken, which should be 1 on
success.
*/
int genwait_wake_thd(void *obj, kthread_t *thd, int err);
/** \brief Look for timed out genwait_wait() calls.
There should be no reason you need to call this function, it is called
internally by the scheduler for you.
\param now The current system time, in milliseconds since boot
*/
void genwait_check_timeouts(uint64 now);
/** \brief Look for the next timeout event time.
This function looks up when the next genwait_wait() call will timeout. This
function is for the internal use of the scheduler, and should not be called
from user code.
\return The next timeout time in milliseconds since boot, or
0 if there are no pending genwait_wait() calls
*/
uint64 genwait_next_timeout();
/** \cond */
/* Initialize the genwait system */
int genwait_init();
/* Shut down the genwait system */
void genwait_shutdown();
/** \endcond */
__END_DECLS
#endif /* __KOS_GENWAIT_H */
| 2.65625 | 3 |
2024-11-18T17:55:05.631144+00:00 | 2018-09-16T05:55:20 | 757fda9d6c0c572baedaf8a592936abbde0ee947 | {
"blob_id": "757fda9d6c0c572baedaf8a592936abbde0ee947",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-16T05:55:20",
"content_id": "0ec14147fa61fa25d9ce4d908793c021d4eb9930",
"detected_licenses": [
"MIT"
],
"directory_id": "c24d59229b0d4a393cdc822a193a3f5880c186a0",
"extension": "cpp",
"filename": "tbh.cpp",
"fork_events_count": 0,
"gha_created_at": "2018-09-17T16:47:24",
"gha_event_created_at": "2018-09-17T16:47:25",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 149157517,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2156,
"license": "MIT",
"license_type": "permissive",
"path": "/sources/tbh.cpp",
"provenance": "stackv2-0005.json.gz:6378",
"repo_name": "LoJac10/650X",
"revision_date": "2018-09-16T05:55:20",
"revision_id": "095e89ae61e27dea6266c56d895f4f15c2c4f521",
"snapshot_id": "b5715ca2ade6aa3383f8eb8ad59556a6f877c571",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/LoJac10/650X/095e89ae61e27dea6266c56d895f4f15c2c4f521/sources/tbh.cpp",
"visit_date": "2020-03-28T21:27:18.873784"
} | stackv2 | /**
* tbh.c - A implementation of the Take Back Half algorithm
* Copyright (c) Brendan McGuire 2016. All Rights Reserved.
* This code has been created for Vex 3796B "Some Assembly Required"
* @TODO: Compile on an actual Windows Machine
* @TODO: Implement a point system to allow mulitple TBH controlled systems
*/
/** Flywheel Control **/
typedef struct {
// number of ticks in a revolution (for Vex 393 Turbo Motors)
float ticksPerRev = 261.333;
// current values (raw: ticks, current: RPM)
int currentRaw;
int current;
// Target, the target RPM
int target;
// Error, the difference between our current value and out target value
int error;
// Gain, equivalent to Kp in PID (je pense)
int gain = 0.00025;
// The last time we did a motor check (should always be 20, since we don't have super heavy calculations)
long lastTime = nSysTime;
// The last IME count
int lastCount = 0;
} TakeBackHalf
// Make it global to make my life easier (and because pointers are hard :/)
static TakeBackHalf flywheel;
// The actual value to write to the Motors
int drive;
int getMotorEncoderValue() {
return nMotorEncoder[FlywheelLeft];
}
void updateCurrentRPM() {
/** Calculate current RPM **/
int deltaTime;
int deltaCount;
// Calculate deltaTime
deltaTime = nSysTime - lastTime;
flywheel.lastTime = nSysTime;
// calculate raw encoder value
flywheel.currentRaw = getMotorEncoderValue();
// calculate deltaCount
flywheel.deltaCount = flywheel.currentRaw - flywheel.lastCount
// Calulate our current value, in RPM (before gearbox)
flywheel.current = (1000 / deltaTime) * deltaCount * (60 * flywheel.ticksPerRev)
}
task FlywheelControl() {
while(true) {
// Exactly how it looks (see function above)
updateCurrentRPM();
// Calculate error
flywheel.error = flywheel.target - flywheel.current;
// Calculate final drive
flywheel.drive+= flywheel.gain * flywheel.error
// Run at 50Hz clock
wait1Msec(20);
}
}
task main() {
startTask(FlywheelControl);
while (true) {
motor[FlywheelLeft] = flywheel.drive;
motor[FlywheelRight] = flywheel.drive;
}
}
| 2.640625 | 3 |
2024-11-18T17:55:05.699751+00:00 | 2017-05-16T20:50:06 | 154bccf4ad2947c5b6efd0f0eea57767679b9258 | {
"blob_id": "154bccf4ad2947c5b6efd0f0eea57767679b9258",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-16T20:50:06",
"content_id": "2a8e44fa6a92046a0d1e601518cab35f0630a2e2",
"detected_licenses": [
"MIT"
],
"directory_id": "9443642b0b07c4369eaabaf264b225d5423c0ee2",
"extension": "h",
"filename": "ssl.h",
"fork_events_count": 1,
"gha_created_at": "2017-05-22T14:17:28",
"gha_event_created_at": "2017-05-22T14:17:28",
"gha_language": null,
"gha_license_id": null,
"github_id": 92061803,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13152,
"license": "MIT",
"license_type": "permissive",
"path": "/vproc_sdk/include/ssl.h",
"provenance": "stackv2-0005.json.gz:6506",
"repo_name": "audioderant/ZLK38AVS",
"revision_date": "2017-05-16T20:50:06",
"revision_id": "7c64414745ab5d64a2b60ba34f4aaf602be1bcf6",
"snapshot_id": "a151b40e13826a4e9bb8f78699832dee2a866ff2",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/audioderant/ZLK38AVS/7c64414745ab5d64a2b60ba34f4aaf602be1bcf6/vproc_sdk/include/ssl.h",
"visit_date": "2021-01-21T18:34:24.557737"
} | stackv2 | /*
* ssl.h -- Header file for System Service Layer
*
* Copyright 2016 Microsemi Inc.
*/
#ifndef __SSL_H__
#define __SSL_H__
/**
* \file include/ssl.h
* \brief System Service Layer.
*
* System Service Layer is combination of 3 header files :
*
* ssl.h - Master file that prototypes functions and data structures to be ported
*
* typedefs.h - Base file defining data types as used by layers above
*
* vproc_dbg.h - Debug header file ported for debug messages. If no debugging
* supported, implementation to leave function/macro as stub but
* still should define
*
* This is Platform-Specific layer and must be ported to host platform-specific
* function for correct functioning of HBI Driver over host platform
*
* Expected and Intended use of data structures and functions are explained
* here. In case of confusion, developer may reach at <>
*/
#include "typedefs.h"
/**
* \ingroup ssl
*
* \{
*/
/*! \enum ssl_status_t
* \brief Enumerates Status Codes supported by SSL
*
*/
typedef enum
{
SSL_STATUS_NOT_INIT = -1, /*!< SSL Driver not initialised. Should be returned
* by any other call to SSL API if called before
* SSL_init()
*/
SSL_STATUS_INVALID_ARG = -2, /*!< Invalid argument passed to SSL API.
* Should be returned by every AAL API, if
* given argument doesn't fall in supported range
*/
SSL_STATUS_INTERNAL_ERR = -3, /*!< Indicates to caller than an error is
reported from platform specific layer*/
SSL_STATUS_BAD_HANDLE = -4, /*!< Invalid port handle passed.Should be returned
* by an API if called before successful
* SSL_port_open()
*/
SSL_STATUS_RESOURCE_ERR = -5, /*!< Requested resource unavailable.
* Should be returned by SSL API if requested
* resource not available.
* Example memory, bus, device
*/
SSL_STATUS_TIMEOUT = -6, /*!< Return if API times out waiting on a
* certain operation.
*/
SSL_STATUS_FAILED = -7, /*!< SSL API failed.
* A more generic message to indicate a
* call failure for any reason than listed
* above
*/
SSL_STATUS_OP_INCOMPLETE = -8, /*!< port read/write incomplete. May be returned
* when number of bytes read/written is less than
* actual requested. This is optional and
* depends upon developer choice of SSL_read()
* and SSL_write() implementation
*/
SSL_STATUS_OK=0 /*!< SSL API call successful. */
}ssl_status_t;
/*! \enum ssl_wait_t
* \brief Enumerates wait type on lock.
*
* Depends on System Service Layer implementation and support of locking
* mechanism.
*
* if Port layer does not support locking, these can be don't care or stub.
*
*/
typedef enum
{
SSL_WAIT_NONE, /*!< Return immediately, if failed to get lock */
SSL_WAIT_FOREVER /*!< Wait until lock is attained.Please note this
* may block the call
*/
}ssl_wait_t;
/*! \enum ssl_op_t
* \brief Enumerates port functions. Can be 'Read Only' ,
* 'Write Only' or 'Read/Write' both
*
*/
typedef enum
{
SSL_OP_PORT_RD=0x01, /*!< Read only operation on Port */
SSL_OP_PORT_WR=0x02, /*!< Write only operation on Port */
SSL_OP_PORT_RW = (SSL_OP_PORT_RD | SSL_OP_PORT_WR) /*! both Read and write
* operation on port
*/
}ssl_op_t;
/*! \brief user passed in structure during read/write done by making a call to
* SSL_port_read(), SSL_port_write() and SSL_port_rw()
*
*/
typedef struct
{
void *pSrc; /*!< Pointer to caller source buffer.
* Must be set to a valid value for PORT WRITE Operation
*/
void *pDst; /*!< Pointer to caller destination buffer,
* Must be set to a valid value for PORT READ Operation
*/
size_t nread; /*!< Number of bytes to read. Ignore in case of PORT
* Write operation
*/
size_t nwrite; /*!< Number of bytes to write. Ignore in case of PORT Write
* operation
*/
ssl_op_t op_type; /*!< Enum indicating port operation: 'read','write' or
* 'read/write'
*/
}ssl_port_access_t;
/*! \fn ssl_status_t SSL_init(ssl_drv_cfg_t *pCfg)
*
* \brief Driver initialization function.
*
* Developer should Allocate and initialize resources as required by driver in
* this function call. pCfg is optional argument and host system specific.
* if required, developer may add initialization configuration paramter.
* Definition of data type ssl_drv_cfg_t is developer-specific and should be
* defined in typedefs.h in sdk. if used, it should be one-time configuration
* parameter and should not be modified.
*
* @param [in] pCfg Pointer to driver init configuration.
This is optional parameter.
*/
ssl_status_t SSL_init(ssl_drv_cfg_t *pCfg);
/*! \fn ssl_status_t SSL_lock_create(ssl_lock_handle_t *pLock,
* const char *pName, void *pOption)
*
* \brief Lock Create Function
*
* This function implements Locking and Unlocking mechanism.
* pName and pOption are optional parameter and are implementation specific.
* ssl_lock_handle_t is host specific data type and should be declared by
* developer in typedefs.h
*
*
* @param [in] pLock Pointer to Lock structure. Should not be NULL.
* @param [in] pName Optional Null terminated string to identify lock
* @param [in] pOption Optional pointer to options structure as declared by
host system in typedef.h.
* @param [out] pLock Updated by call on successful completion
*
*/
ssl_status_t SSL_lock_create(ssl_lock_handle_t *pLock,
const char *pName, void *pOption);
/*! \fn ssl_status_t SSL_lock(ssl_lock_handle_t lock_id,ssl_wait_t wait_type)
*
* \brief Hold a lock
*
* This function is called to hold a Locking. This can act as stub function
* if implementation does not support a locking mechanism.
*
* @param [in] lock_id handle as returned by call to SSL_lock_create()
* @param [in] wait_type enum indicating WAIT_FOREVER or WAIT_NONE
*
*/
ssl_status_t SSL_lock(ssl_lock_handle_t lock_id,ssl_wait_t wait_type);
/*! \fn ssl_status_t SSL_unlock(ssl_lock_handle_t lock_id)
*
* \brief Release a lock
*
* This function is called to release a Lock. This can act as stub function
* if implementation doesnt support a locking mechanism.
*
* @param [in] lock_id handle as returned by call to SSL_lock_create()
*
*/
ssl_status_t SSL_unlock(ssl_lock_handle_t lock_id);
/*! \fn ssl_status_t SSL_lock_delete(ssl_lock_handle_t lock_id)
*
* \brief Deletes lock
*
* This function is called to delete a Lock created by call to SSL_lock_create.
*
* @param [in] lock_id handle as returned by call to SSL_lock_create()
*
*/
ssl_status_t SSL_lock_delete(ssl_lock_handle_t lock_id);
/*! \fn ssl_status_t SSL_term(void)
*
* \brief Terminates SSL Driver.
*
* This function should deallocate and free all resources as acquired
* during SSL_init() call.
*
*/
ssl_status_t SSL_term(void);
/*! \fn ssl_status_t SSL_port_open(ssl_port_handle_t *pHandle,
ssl_dev_cfg_t *pDevCfg)
*
* \brief Opens an port to device.
* This function should initialise, allocate
* and setup all necessary infrastructure required to transmit data to and
* from device. Initialisation of SPI / I2C interface happen here.
* User should be able to do read/write to device after successful
* execution of this API
*
* @param [in] *pHandle Pointer to port handle. ssl_port_handle_t data type should
* be declared by developer in typedefs.h
* @param [in] *pDevCfg Pointer to device configuration. User passed in bus number,
* chip address or id. Example for SPI, bus number can be spi bus
* number and device address can be chip select value. For i2c,
* device address can be allowable range of i2c addresses.
* @param [out] pHandle Should be updated by driver on successful execution of
* call
*
*/
ssl_status_t SSL_port_open(ssl_port_handle_t *pHandle, ssl_dev_cfg_t *pDevCfg);
/*! \fn ssl_status_t SSL_port_close(ssl_port_handle_t handle)
*
* \brief Close the port opened to device
*
* This function should deallocate and free all resources as acquired
* during SSL_port_open() call. After successful execution of this function, user
* should not be able to send/receive data to device.
*
* @param handle Port Handle as returned by SSL_port_open()
*/
ssl_status_t SSL_port_close(ssl_port_handle_t handle);
/*! \fn ssl_status_t SSL_port_read(ssl_port_handle_t handle,
* void *pDst, size_t *pNread)
*
* \brief Reads the data from port into user buffer pointed by pDst
*
* This function read data from device into user buffer pointed by pDst
*
* @param [in] handle Port Handle as returned by SSL_port_open()
* @param [in] pDst Pointer to user passed in destination buffer to read data
* in to
* @param [in] pNread Pointer to variable containing size of data to read
* @param [out] pNread Optional.May be updated by driver to indicate size of
* data actually read
*
*/
ssl_status_t SSL_port_read(ssl_port_handle_t handle, void *pDst, size_t *pNread);
/*! \fn ssl_status_t SSL_port_write(ssl_port_handle_t handle,
void *pSrc, size_t *pNwrite)
*
* \brief Write the data from user buffer to device
*
* This function writes user passed data in pSrc buffer to device.
*
* @param [in] handle Port Handle as returned by SSL_port_open()
* @param [in] pSrc Pointer to source buffer containing data to be sent to device
* @param [in] pNwrite Pointer to buffer containing size of data to be written
* @param [out] pNwrite Optional. May be updated by driver to indicate size of
data actually written
*
*/
ssl_status_t SSL_port_write(ssl_port_handle_t handle,void *pSrc, size_t *pNwrite);
/*! \fn ssl_status_t SSL_port_rw(ssl_port_handle_t handle,
* ssl_port_access_t *pPort)
*
* \brief Read and Writes the data from and to device
*
* This function performs both read/write transaction to device in a single call.
* May be supported by driver for combined transactions.
*
* @param [in] handle Port Handle as returned by SSL_port_open()
* @param [in] pPort Pointer to structure populated with valid arguments
* for read/write transactions
* @param [out] pPort May update size of data actually read/written in pPort
* structure
*
*/
ssl_status_t SSL_port_rw(ssl_port_handle_t handle, ssl_port_access_t *pPort);
/*! \fn ssl_status_t SSL_memset(void *pDst, int32_t val,size_t size)
*
* \brief Sets the content of memory to specified value
*
* Sets the content of memory to specified value. May be ported over system
* specific memset call.
*
* @param [in] pDst Pointer to memory location to be updated
* @param [in] val Value to be written to
* @param [in] size size of the memory to be updated
*
*/
ssl_status_t SSL_memset(void *pDst, int32_t val,size_t size);
/*! \fn ssl_status_t SSL_memcpy(void *pDst,const void *pSrc, size_t size)
*
* \brief Copy the content of memory from source to destination pointer
*
* Copies the content of source buffer to destination buffer. May be ported over
* system specific memcpy call.
*
* @param [in] pDst Pointer to memory location to be copied to
* @param [in] pSrc Pointer to memory location to copy from
* @param [in] size size of the data to be copied
*
*/
ssl_status_t SSL_memcpy(void *pDst,const void *pSrc, size_t size);
/*! \fn ssl_status_t SSL_delay(uint32_t tmsec)
*
* \brief Implements delay in millisecond
*
* Implements delay in milliseconds . May be ported over
* system specific delay/sleep call.
*
* @param [in] tmsec - time in milliseconds
*
*/
ssl_status_t SSL_delay(uint32_t tmsec);
/** \} */
#endif
| 2.15625 | 2 |
2024-11-18T17:55:05.857472+00:00 | 2023-07-19T17:59:18 | 0d431ec44da0d1f28b63bfb9c52db9f865912eff | {
"blob_id": "0d431ec44da0d1f28b63bfb9c52db9f865912eff",
"branch_name": "refs/heads/main",
"committer_date": "2023-07-19T17:59:18",
"content_id": "f4c12cbecb5d2ced1edf00bc914bf0e0551cf362",
"detected_licenses": [
"MIT"
],
"directory_id": "b960df3e90501dfe59dbfb18a8255127a9197c93",
"extension": "c",
"filename": "partition.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 176133848,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12307,
"license": "MIT",
"license_type": "permissive",
"path": "/src/partition.c",
"provenance": "stackv2-0005.json.gz:6762",
"repo_name": "Xinglab/TideHunter",
"revision_date": "2023-07-19T17:59:18",
"revision_id": "bdd21ca9fca275137590b2978d292854429e3439",
"snapshot_id": "a15f00dbed1b849dfa7a6a8e4f2e8fff49ee2a3a",
"src_encoding": "UTF-8",
"star_events_count": 22,
"url": "https://raw.githubusercontent.com/Xinglab/TideHunter/bdd21ca9fca275137590b2978d292854429e3439/src/partition.c",
"visit_date": "2023-08-07T14:28:10.328890"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "tandem_chain.h"
#include "edlib_align.h"
#include "abpoa_cons.h"
#include "ksw2_align.h"
#include "utils.h"
// pos: 0-base
int *partition_seqs_core(char *seq, int seq_len, int8_t *hit_array, int est_period, int chain_start, int chain_end, int *par_n) {
int i, j;
int *pos_array = (int*)_err_malloc(sizeof(int) * seq_len), *par_pos = (int*)_err_malloc(sizeof(int) * seq_len);
int hit_n = 0;
for (i = 0; i < seq_len; ++i) {
if (hit_array[i]) {
#ifdef __DEBUG__
printf("%d, ", i);
#endif
pos_array[hit_n++] = i;
}
}
#ifdef __DEBUG__
printf("\n");
#endif
// partition seq into period seperated seqs
int par_i = 0, l;
char *query_seq, *target_seq; int copy_num, ed, start, end, target_start;
// extend two ends
l = est_period / 2;
copy_num = (int)((double)(pos_array[0] - chain_start) / est_period + 0.5);
if (copy_num >= 1) {
for (j = copy_num; j >= 1; --j) {
query_seq = seq + pos_array[0];
target_start = pos_array[0] - est_period * j - (l<<0);
// target_start = pos_array[0] - period[pos_array[0]] * j - (l<<1);
if (target_start < 0) continue;
target_seq = seq + target_start;
ed = edlib_align_HW(query_seq, l, target_seq, l<<1, &start, &end, -1);
// ed = edlib_align_HW(query_seq, l, target_seq, l<<2, &start, &end);
if (ed >= 0) par_pos[par_i++] = target_start + start;
}
}
par_pos[par_i++] = pos_array[0];
for (i = 0; i < hit_n-1; ++i) {
// printf("%d: %d, %d, %d\n", pos_array[i], period[pos_array[i]], period[pos_array[i+1]], ave_p);
copy_num = (int)((double)(pos_array[i+1] - pos_array[i]) / est_period + 0.5);
if (copy_num > 1) { // multiple copies: semi-global alignment of prefix l-mer using edlib
query_seq = seq + pos_array[i];
for (j = 1; j < copy_num; ++j) {
target_start = pos_array[i] + est_period * j - (l << 0);
// target_start = pos_array[i] + ave_p * j - (l << 1);
target_seq = seq + target_start;
ed = edlib_align_HW(query_seq, l, target_seq, l<<1, &start, &end, -1);
// ed = edlib_align_HW(query_seq, l, target_seq, l<<2, &start, &end);
if (ed < 0) { // no alignment result
par_pos[par_i++] = -1; // skip this copy
} else {
par_pos[par_i++] = target_start + start;
}
}
}
par_pos[par_i++] = pos_array[i+1];
}
// extend par_pos on the right
copy_num = (int)((double)(chain_end - pos_array[hit_n-1]) / est_period + 0.5);
if (copy_num >= 1) {
for (j = 1; j <= copy_num; ++j) {
query_seq = seq + pos_array[hit_n-1];
target_start = pos_array[hit_n-1] + est_period * j - (l<<0);
// target_start = pos_array[hit_n-1] + period[pos_array[hit_n-1]] * j - (l<<1);
if (target_start + (l<<1) >= seq_len) continue;
// if (target_start + (l<<2) >= seq_len) continue;
target_seq = seq + target_start;
ed = edlib_align_HW(query_seq, l, target_seq, l<<1, &start, &end, -1);
// ed = edlib_align_HW(query_seq, l, target_seq, l<<2, &start, &end);
if (ed >= 0) par_pos[par_i++] = target_start + start;
}
}
free(pos_array);
*par_n = par_i;
return par_pos;
}
// TODO when (s2) >> (e1), i.e., anchor are too sparse
// start with est_start anchor?
int *get_partition_pos_with_global_alignment(uint8_t *bseq, int seq_len, dp_t **dp, chain_t ch, mini_tandem_para *mtp, int *par_n) {
int est_ch_i = ch.est_ch_i, est_start = ch.est_start, est_period = ch.est_period;
int first_end = dp[ch.cell[0].i][ch.cell[0].j].end, last_start = dp[ch.cell[ch.len-1].i][ch.cell[ch.len-1].j].start;
int *par_pos = (int*)_err_malloc(seq_len * sizeof(int)); *par_n = 0;
int i, j, k=mtp->k, ch_i1, ch_i2, s1, e1, s2, e2, iden_n, s, e;
int n_cigar; uint32_t *cigar;
cell_t c; dp_t d;
// find non-overlapping adjacent tandem repeat hits
// global alignment of [s1,s2] and [e1, e2]
// find best partition position with backtrack
ch_i2 = est_ch_i, s2 = est_start, e2 = est_start + est_period;
while (ch_i2 > 0 && s2 >= first_end) {
for (i = ch_i2 - 1; i >= 0; --i) {
c = ch.cell[i]; d = dp[c.i][c.j];
s1 = d.start; e1 = d.end;
if (e1 == s2) {
par_pos[(*par_n)++] = s1;
ch_i2 = i, s2 = s1, e2 = e1;
break;
} else if (e1 < s2) { // non-overlapping adjacent tandem repeat hits
// do global alignment
iden_n = ksw2_global_with_cigar(bseq+e1-k+1, e2-e1+k, bseq+s1-k+1, s2-s1+k, &n_cigar, &cigar);
#ifdef __DEBUG__
printf("iden_n: %d (%d,%d), (%d,%d)\n", iden_n, e2-e1+k, s2-s1+k, s1, s2);
#endif
if (iden_n >= MIN_OF_TWO(s2-s1+k, e2-e1+k) * (1-mtp->max_div)) { // extend partition
s = s2 - ksw2_backtrack_left_end(n_cigar, cigar, e2-e1+k, s2-s1+k, e2-s2);
par_pos[(*par_n)++] = s;
ch_i2 = i+1; e2 = s2, s2 = s;
} else { // skip this anchor
par_pos[(*par_n)++] = -1; // indicate a separation flag
par_pos[(*par_n)++] = e1;
par_pos[(*par_n)++] = s1;
ch_i2 = i; s2 = s1; e2 = e1;
}
if (cigar)
free(cigar);
break;
}
}
}
// reverse par_pos
for (i = 0; i < (*par_n)>> 1; ++i) {
j = par_pos[i]; par_pos[i] = par_pos[*par_n-i-1]; par_pos[*par_n-i-1] = j;
}
par_pos[(*par_n)++] = est_start;
par_pos[(*par_n)++] = est_start + est_period;
ch_i1 = est_ch_i, s1 = est_start, e1 = est_start + est_period;
while (ch_i1 < ch.len-1 && e1 <= last_start) {
for (i = ch_i1+1; i < ch.len; ++i) {
c = ch.cell[i]; d = dp[c.i][c.j];
s2 = d.start; e2 = d.end;
if (s2 == e1) {
par_pos[(*par_n)++] = e2;
ch_i1 = i, s1 = s2, e1 = e2;
break;
} else if (s2 > e1) { // non-overlapping adjacent tandem repeat hits
// do global alignment
iden_n = ksw2_global_with_cigar(bseq+s1-k+1, s2-s1+k, bseq+e1-k+1, e2-e1+k, &n_cigar, &cigar);
#ifdef __DEBUG__
printf("iden_n: %d (%d,%d), (%d,%d)\n", iden_n, e2-e1+k, s2-s1+k, s1, s2);
#endif
if (iden_n >= MIN_OF_TWO(s2-s1+k, e2-e1+k) * (1-mtp->max_div)) {
e = e2 - ksw2_backtrack_left_end(n_cigar, cigar, s2-s1+k, e2-e1+k, s2-e1);
par_pos[(*par_n)++] = e;
ch_i1 = i-1; s1 = e1, e1 = e;
} else {
par_pos[(*par_n)++] = -1;
par_pos[(*par_n)++] = s2;
par_pos[(*par_n)++] = e2;
ch_i1 = i; s1 = s2; e1 = e2;
}
if (cigar)
free(cigar);
break;
}
}
}
if (*par_n == 0) free(par_pos);
return par_pos;
}
// TODO do extension first, so that cons would start from the begining of the repeat
int *get_partition_pos_with_narrow_global_alignment(uint8_t *bseq, int seq_len, dp_t **dp, chain_t ch, mini_tandem_para *mtp, int *par_n) {
int est_ch_i = ch.est_ch_i, est_start = ch.est_start, est_period = ch.est_period;
int first_end = dp[ch.cell[0].i][ch.cell[0].j].end, last_start = dp[ch.cell[ch.len-1].i][ch.cell[ch.len-1].j].start;
int *par_pos = (int*)_err_malloc(seq_len * sizeof(int)); *par_n = 0;
int i, j, k=mtp->k, ch_i, s, e, s1, e1, s2, e2, iden_n;
int n_cigar; uint32_t *cigar;
cell_t c; dp_t d;
// find upstream anchor (s1, e1) and downstream (s2, e2)
// global alignment of [s1,s2] and [e1, e2]
// find best partition position by backtracking
// left extension: find S
// <=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=
// --s1---S---s2----e1---s---e2-------e--
// --|---------| vs |---------|----------
ch_i = est_ch_i, s = est_start, e = est_start + est_period;
while (s >= first_end && ch_i > 0) {
// find (s1, e1) and (s2, e2)
s2 = s, e2 = e; s1 = -1; e1 = -1;
for (i = ch_i - 1; i >= 0; --i) {
c = ch.cell[i]; d = dp[c.i][c.j];
s1 = d.start; e1 = d.end;
if (e1 == s) {
par_pos[(*par_n)++] = s1;
ch_i = i, s = s1, e = e1;
break;
} else if (e1 < s) {
// if (s - e1 < k) // overlapped
// do global alignment
iden_n = ksw2_global_with_cigar(bseq+e1-k+1, e2-e1+k, bseq+s1-k+1, s2-s1+k, &n_cigar, &cigar);
#ifdef __DEBUG__
printf("1: (%d,%d), 2: (%d,%d)\n", s1, e1, s2, e2);
printf("iden_n: %d (%d,%d), (%d,%d)\n", iden_n, e2-e1+k, s2-s1+k, s1, s2);
#endif
if (iden_n >= MIN_OF_TWO(s2-s1+k, e2-e1+k) * (1-mtp->max_div)) { // extend partition
e = s; s = s2 - ksw2_backtrack_left_end(n_cigar, cigar, e2-e1+k, s2-s1+k, e2-s);
if (e == s) { // no backtrack
ch_i = 0; break;
}
par_pos[(*par_n)++] = s;
ch_i = i+1;
} else { // skip this anchor
par_pos[(*par_n)++] = -1; // insert a separation flag
par_pos[(*par_n)++] = e1; // start of another tandem repeat, another consensus will be called separatedly
par_pos[(*par_n)++] = s1;
ch_i = i; s = s1; e = e1;
}
if (cigar) free(cigar);
break;
} else {
s2 = s1; e2 = e1;
}
}
}
// reverse par_pos
for (i = 0; i < (*par_n)>> 1; ++i) {
j = par_pos[i]; par_pos[i] = par_pos[*par_n-i-1]; par_pos[*par_n-i-1] = j;
}
par_pos[(*par_n)++] = est_start;
par_pos[(*par_n)++] = est_start + est_period;
// right extension: find E
// >=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=
// --s-------s1---e---s2----e1---E---e2--
// ----------|---------| vs |---------|--
ch_i = est_ch_i, s = est_start, e = est_start + est_period;
while (ch_i < ch.len-1 && e <= last_start) {
// find (s1,e1) and (s2,e2)
s1 = s, e1 = e, s2 = e2 = -1;
for (i = ch_i+1; i < ch.len; ++i) {
c = ch.cell[i]; d = dp[c.i][c.j];
s2 = d.start; e2 = d.end;
if (s2 == e) {
par_pos[(*par_n)++] = e2;
ch_i = i; s = s2; e = e2;
break;
} else if (s2 > e) { // first (s2, e2)
// if (s2 - e < k) // overlapped
iden_n = ksw2_global_with_cigar(bseq+s1-k+1, s2-s1+k, bseq+e1-k+1, e2-e1+k, &n_cigar, &cigar);
#ifdef __DEBUG__
printf("1: (%d,%d), 2: (%d,%d)\n", s1, e1, s2, e2);
printf("iden_n: %d (%d,%d), (%d,%d)\n", iden_n, e2-e1+k, s2-s1+k, s1, s2);
#endif
if (iden_n >= MIN_OF_TWO(s2-s1+k, e2-e1+k) * (1-mtp->max_div)) {
s = e; e = e2 - ksw2_backtrack_left_end(n_cigar, cigar, s2-s1+k, e2-e1+k, s2-e);
if (e == s) { // no backtrack
ch_i = ch.len; break;
}
par_pos[(*par_n)++] = e;
ch_i = i-1;
} else {
par_pos[(*par_n)++] = -1;
par_pos[(*par_n)++] = s2;
par_pos[(*par_n)++] = e2;
ch_i = i; s = s2; e = e2;
}
if (cigar) free(cigar);
break;
} else {
s1 = s2; e1 = e2;
}
}
}
if (*par_n == 0) free(par_pos);
return par_pos;
}
| 2.453125 | 2 |
2024-11-18T17:55:05.933126+00:00 | 2020-10-06T22:04:44 | 8271583c168d3e11f27b86fb49c4257d6cbccdf9 | {
"blob_id": "8271583c168d3e11f27b86fb49c4257d6cbccdf9",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-06T22:04:44",
"content_id": "096cdb76fd222c6b6c24dc487680c368ec488ea9",
"detected_licenses": [
"BSD-3-Clause-Clear"
],
"directory_id": "233a8c65e2936cb9323802764c62f4c5a1742389",
"extension": "c",
"filename": "2darray.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44290739,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 853,
"license": "BSD-3-Clause-Clear",
"license_type": "permissive",
"path": "/c/kr/s1/2darray.c",
"provenance": "stackv2-0005.json.gz:6890",
"repo_name": "newnix/Forge",
"revision_date": "2020-10-06T22:04:44",
"revision_id": "6d18105460fabc20592ed3c29813173cdb57d512",
"snapshot_id": "83a83bee28e6741ba42ad2e1f4a1488762f6b0ac",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/newnix/Forge/6d18105460fabc20592ed3c29813173cdb57d512/c/kr/s1/2darray.c",
"visit_date": "2021-05-25T09:08:59.814337"
} | stackv2 | /*
* This is a practice program to assign, write to, and read from a 2D array
*/
#include <stdio.h>
#include "../headers/get_line.h"
#include <stdlib.h>
#define MAX 10
int main()
{
/* first we need to set up the array(s) */
int d[10][MAX]; /* hold up to 10 MAX length strings */
int x,y; /* length of the input string */
/* somehow grab the stuff from the user and stuff it in the array */
for (x = 0; x < 10; x++)
{
/* and another, nested loop */
for (y = 0; y < MAX; y++)
{
d[x][y] = y; /* basically just store where we are right now */
}
}
/* do it again, but this time print the stuff out */
for (x = 0; x < 10; x++)
{
for (y = 0; y < MAX; y++)
{
printf("d[%d][%d] = %d\n",x,y,d[x][y]); /* according to valgrind, there's a leak here */
}
}
for (x = 0; x < MAX; x++)
{
free(d[x]);
}
free (d);
return 0;
}
| 3.640625 | 4 |
2024-11-18T17:55:05.991943+00:00 | 2020-10-17T15:50:54 | f53f0d42e7ec2c918517d3f7a0287a8efa7ad804 | {
"blob_id": "f53f0d42e7ec2c918517d3f7a0287a8efa7ad804",
"branch_name": "refs/heads/main",
"committer_date": "2020-10-17T15:50:54",
"content_id": "cbc9515c94a9f665f435c86c573182552cd5adce",
"detected_licenses": [
"MIT"
],
"directory_id": "760f4e5984425799743a14ceb4a4644fd10e9780",
"extension": "c",
"filename": "parabola.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": 1813,
"license": "MIT",
"license_type": "permissive",
"path": "/parabola.c",
"provenance": "stackv2-0005.json.gz:7019",
"repo_name": "dongtl4/OpenGL",
"revision_date": "2020-10-17T15:50:54",
"revision_id": "7dce549bd69c95d356eb66c2c189156ee201ffa8",
"snapshot_id": "ab278da70de5bdffc9999c8662b44ff0999a9e28",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dongtl4/OpenGL/7dce549bd69c95d356eb66c2c189156ee201ffa8/parabola.c",
"visit_date": "2022-12-30T11:38:40.326251"
} | stackv2 | /*
* parabola.c
* A parabola is drawn by approximating the curve with a line strip.
*/
#include <GL/glut.h>
#include <math.h>
#include <stdio.h>
// The number of vertices taken from the parabola to be
// joined line strip is 2M+1. Increase M for a finer approximation.
#define M 3
void init (void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
}
void display(void)
{
int i;
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
/*
* The 2M+1 approximating points on the parabola are
* equally spaced between their x-coordinates from
* -1 to 1. A better approximation would be obtained
* by making the points closer together in the x-coordinate
* as they move away from the origin as the parabola
* grows faster.
*/
glBegin(GL_LINE_STRIP);
for(i = -M; i <= M; ++i){
glVertex3f( (float) i/M, (float) (i*i)/(M*M), 0.0);
}
glEnd();
glFlush ();
}
void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt (0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
void keyboard (unsigned char key, int x, int y)
{
switch (key) {
case 27:
exit(0);
break;
default:
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Parabola");
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
| 3.09375 | 3 |
2024-11-18T17:55:06.087894+00:00 | 2018-03-27T10:24:11 | 875b4edca0f905f17524538bc7d31001b9e8c059 | {
"blob_id": "875b4edca0f905f17524538bc7d31001b9e8c059",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-27T10:24:11",
"content_id": "8cb3f850b9722f97afea3448e3446800f520ab9e",
"detected_licenses": [
"MIT"
],
"directory_id": "a45d143f79514a548f7ded776a733d7ccaa8ebda",
"extension": "c",
"filename": "stacklinkedlist.c",
"fork_events_count": 1,
"gha_created_at": "2018-02-28T15:42:46",
"gha_event_created_at": "2019-04-01T14:36:17",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 123305839,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1057,
"license": "MIT",
"license_type": "permissive",
"path": "/stacklinkedlist.c",
"provenance": "stackv2-0005.json.gz:7147",
"repo_name": "AdityaSher/datastructures",
"revision_date": "2018-03-27T10:24:11",
"revision_id": "f008020928292112f57054250d7107a4b7fec900",
"snapshot_id": "ef32062ddf53fd0ad94ff0dfb6cb583959c67f46",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AdityaSher/datastructures/f008020928292112f57054250d7107a4b7fec900/stacklinkedlist.c",
"visit_date": "2021-10-25T05:05:34.301395"
} | stackv2 | // C program for linked list implementation of stack
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct StackNode{
int data;
struct StackNode* next;
};
typedef struct StackNode SNODE;
//creation of new node in stack
SNODE* newNode(int data){
SNODE* snode=(SNODE*)malloc(sizeof(SNODE));
snode->data=data;
snode->next=NULL;
return snode;
}
//check whether stack is empty
int isEmpty(SNODE *root){
return !root;
}
//add new node!
void push(SNODE** root, int data){
SNODE* snode=newNode(data);
snode->next = *root;
*root=snode;
printf("%d pushed to stack \n",data);
}
int pop(SNODE** root){
if(isEmpty(*root))
return INT_MIN;
SNODE* temp=*root;
*root=(*root)->next;
int popped=temp->data;
free(temp);
return popped;
}
int peek(SNODE* root){
if(isEmpty(root))
return INT_MIN;
return root->data;
}
int main(){
SNODE* root=NULL;
push(&root, 10);
push(&root, 20);
push(&root, 30);
printf("%d popped from stack\n", pop(&root));
printf("Top element is %d\n", peek(root));
return 0;
}
| 4 | 4 |
2024-11-18T17:55:06.354752+00:00 | 2016-12-11T21:47:24 | 76395830e3bb9a56f9613b938a3820d1fa1c43bd | {
"blob_id": "76395830e3bb9a56f9613b938a3820d1fa1c43bd",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-11T21:47:24",
"content_id": "f0dfee015f1ffff69690124ab025866d53fc3e31",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e88683c6a8f7ae1e76ecf051c8c700544635affa",
"extension": "c",
"filename": "main_9_30_i.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": 3651,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Software/main_9_30_i.c",
"provenance": "stackv2-0005.json.gz:7532",
"repo_name": "imatlopez/emg-sensor",
"revision_date": "2016-12-11T21:47:24",
"revision_id": "f579ac75a1a6042efbeeac3ce2867490fae220fd",
"snapshot_id": "7195f4af3a133adc4ce9d71bf2a56ee28d2521ee",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/imatlopez/emg-sensor/f579ac75a1a6042efbeeac3ce2867490fae220fd/Software/main_9_30_i.c",
"visit_date": "2021-06-09T15:50:28.713565"
} | stackv2 | /*
* BME 464 - EMG Decoder
*
* Decodes signals from two EMG leads and sends result to an external interface
*
*/
#include "Lcd.h"
#include <delays.h> //delay header
#include <p18f46k22.h> //chip header
#include <stdio.h>
#pragma config FOSC = INTIO67 // Internal OSC block, Port Function on RA6/7
#pragma config WDTEN = SWON // Watch Dog Timer controlled by SWDTEN bit
#pragma config WDTPS = 512 // WDT Postscale of 1:512, equivalent to 2 secs
#pragma config XINST = OFF // Instruction set Extension and indexed Addressing mode disabled
//Define statements
#define Running 0
#define Sleeping 1
//Variable definitions
unsigned int V1; // signal from lead 1
unsigned int V2; // signal from lead 2
int EMG; // decoded result
int State;
//Function definitions
void SysInit(void);
void GetData(void);
int Decode(unsigned int voltage1, unsigned int voltage2);
void Transmit(int info);
void SleepMode(void);
void main(void)
{
//Initialize
SysInit();
LCDClear();
// EMG Decoder Loop
while(1) {
if (State == Running){
GetData(); // Acquire voltages
EMG=Decode(V1,V2); // Decode
Transmit(EMG); // Print value to screen or communication
Delay10KTCYx(200); // Delay 1 second
}
if (State == Sleeping){
SleepMode();
}
};
}
//Initialize necessary systems
void SysInit(void)
{
OSCCON=0b01010110; //4 MHz internal oscillator
//Set up buttons
ANSELBbits.ANSB0=0; //Digital
TRISAbits.RA4=1; //Input
TRISBbits.RB0=1; //Input
//Set up ADC channel on AN0
ANSELAbits.ANSA0 = 1;
TRISAbits.RA0 = 1; //Analog in
//Set up ADC channel on AN1
ANSELAbits.ANSA1 = 1;
TRISAbits.RA1 = 1; //Analog in
//Set up ADC parameters
ADCON2bits.ACQT=001; //2 TAD
ADCON2bits.ADCS=010; //FOSC/32
ADCON2bits.ADFM=1; //Right justified***
ADCON0bits.ADON=1; //Turn on A/D
//Set up sleep mode
OSCCONbits.IDLEN = 0;
//Set up Watchdog Timer
WDTCONbits.SWDTEN = 1; // Turn on WDT
//Set up LCD
ANSELD = 0x00;
TRISD = 0x00; //Digital out
LCDInit(); //Start LCD
LCDWriteStr("Starting device...");
//Reset variables
V1=0;
V2=0;
EMG=0;
State=0;
}
// ADC sampling of EMG leads
void GetData(void)
{
//Channel1
ADCON0bits.CHS=0000; //Select RA0
ADCON0bits.GO=1; //Start conversion
while(ADCON0bits.GO==1){}; //Wait for finish
V1=ADRESH;
V1=(V1<<8) | ADRESL; //Math needs to be done in the int variable
if(V1==1023) //Fix roundoff error
V1=1022;
//Channel2
ADCON0bits.CHS=0001; //Select RA1
ADCON0bits.GO=1; //Start conversion
while(ADCON0bits.GO==1){}; //Wait for finish
V2=ADRESH;
V2=(V2<<8) | ADRESL; //Math needs to be done in the int variable
if(V2==1023) //Fix roundoff error
V2=1022;
}
// Decode the two digital signals
int Decode(unsigned int voltage1, unsigned int voltage2){
return 0;
}
// Transmit the result to external interface
void Transmit(int info){
// Local variables
char str[4];
// For now, display the two voltage results
LCDClear();
LCDGoto(0,0);
sprintf(str,"%04u",V1);
LCDPutChar(str[0]);
LCDPutChar(str[1]);
LCDPutChar(str[2]);
LCDPutChar(str[3]);
LCDGoto(0,1);
sprintf(str,"%04u",V2);
LCDPutChar(str[0]);
LCDPutChar(str[1]);
LCDPutChar(str[2]);
LCDPutChar(str[3]);
State++;
}
void SleepMode(void){
LCDClear();
LCDWriteStr("SLEEP MODE");
Sleep();
State = 0;
}
| 2.78125 | 3 |
2024-11-18T17:55:06.438479+00:00 | 2021-09-15T15:16:35 | d2d42bde4cbfae4ed4a147e6573c402c9d2d3110 | {
"blob_id": "d2d42bde4cbfae4ed4a147e6573c402c9d2d3110",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-15T15:16:35",
"content_id": "5533a851eddb62a3349b3820735d8f4504cefe6c",
"detected_licenses": [
"MIT"
],
"directory_id": "09f96edf66b25e25a3eace7482ebba10a8ba70f3",
"extension": "h",
"filename": "fastassign.h",
"fork_events_count": 0,
"gha_created_at": "2021-09-17T19:03:48",
"gha_event_created_at": "2021-09-17T19:03:49",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 407651611,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1145,
"license": "MIT",
"license_type": "permissive",
"path": "/src/fastassign.h",
"provenance": "stackv2-0005.json.gz:7660",
"repo_name": "SamuelMarks/kissat",
"revision_date": "2021-09-15T15:16:35",
"revision_id": "abfa45fb782fa3b7c6e2eb6b939febe74d7270b7",
"snapshot_id": "d536378122fe9ec31d1e063c987ab58f22f1e3c0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SamuelMarks/kissat/abfa45fb782fa3b7c6e2eb6b939febe74d7270b7/src/fastassign.h",
"visit_date": "2023-08-18T09:11:43.139782"
} | stackv2 | #ifndef _fastassign_h_INCLUDED
#define _fastassign_h_INCLUDED
#define FAST_ASSIGN
#include "inline.h"
#include "inlineassign.h"
static inline void
kissat_fast_binary_assign (kissat * solver,
const bool probing, const unsigned level,
value * values, assigned * assigned,
bool redundant, unsigned lit, unsigned other)
{
kissat_fast_assign (solver, probing, level, values, assigned,
true, redundant, lit, other);
LOGBINARY (lit, other, "assign %s %s reason",
LOGLIT (lit), redundant ? "redundant" : "irredundant");
}
static inline void
kissat_fast_assign_reference (kissat * solver,
value * values, assigned * assigned,
unsigned lit, reference ref, clause * reason)
{
assert (reason == kissat_dereference_clause (solver, ref));
const unsigned level =
kissat_assignment_level (solver, values, assigned, lit, reason);
assert (level <= solver->level);
assert (ref != DECISION_REASON);
assert (ref != UNIT_REASON);
kissat_fast_assign (solver, solver->probing, level,
values, assigned, false, false, lit, ref);
LOGREF (ref, "assign %s reason", LOGLIT (lit));
}
#endif
| 2.078125 | 2 |
2024-11-18T17:55:06.517381+00:00 | 2016-08-22T09:56:13 | 6bccf3802d79b00651db385d75dc9e3398e48758 | {
"blob_id": "6bccf3802d79b00651db385d75dc9e3398e48758",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-22T09:56:13",
"content_id": "064e29d22191038c3760632a4d495aaa4734219a",
"detected_licenses": [
"MIT"
],
"directory_id": "94a99e0154a77a46a2f44e9ad2f8951aa4bc0a2b",
"extension": "c",
"filename": "q4.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 17437816,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 309,
"license": "MIT",
"license_type": "permissive",
"path": "/Labs/Lab 8/q4.c",
"provenance": "stackv2-0005.json.gz:7788",
"repo_name": "kieranhogan13/C",
"revision_date": "2016-08-22T09:56:13",
"revision_id": "db1e4cd43b25858830f9c75635eeb4e39c287011",
"snapshot_id": "57c658b3aa332b09bd389171cbc9fd5ebd1d7a17",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kieranhogan13/C/db1e4cd43b25858830f9c75635eeb4e39c287011/Labs/Lab 8/q4.c",
"visit_date": "2020-12-25T17:29:05.001038"
} | stackv2 | /*Q2 - Lab 19/03/2013 - pg146 - Q8
Kieran Hogan - DT228/1*/
#include <stdio.h>
#include <string.h>
/*Declare structure template*/
struct date_rec
{
int day;
int month;
int year;
};
struct date_rec current_date;
int main(void)
{
flushall();
getchar();
return 0;
}//end main | 2.375 | 2 |
2024-11-18T17:55:07.161598+00:00 | 2023-03-13T19:34:34 | 65d0cfec7527c17abb1d3ced608d0eb71a986dcc | {
"blob_id": "65d0cfec7527c17abb1d3ced608d0eb71a986dcc",
"branch_name": "refs/heads/v1.0.x",
"committer_date": "2023-03-13T19:34:34",
"content_id": "b407d19e73355531c14f10e7a99bd56871b6c05c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "1a5ee9578a794aea1ff6e731a9b25ca8cb92af09",
"extension": "c",
"filename": "icc_tx.c",
"fork_events_count": 6,
"gha_created_at": "2019-02-27T19:22:21",
"gha_event_created_at": "2023-08-25T21:39:54",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 172975569,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6632,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/sdk/app_cpu1/common/sys/icc_tx.c",
"provenance": "stackv2-0005.json.gz:8044",
"repo_name": "Severson-Group/AMDC-Firmware",
"revision_date": "2023-03-13T19:34:34",
"revision_id": "4dcb288f51b6879c003468ef5844b102ed3c6372",
"snapshot_id": "ae897a643d5a3d691a12f6cda71671fde254afa4",
"src_encoding": "UTF-8",
"star_events_count": 22,
"url": "https://raw.githubusercontent.com/Severson-Group/AMDC-Firmware/4dcb288f51b6879c003468ef5844b102ed3c6372/sdk/app_cpu1/common/sys/icc_tx.c",
"visit_date": "2023-08-17T01:57:55.677000"
} | stackv2 | #include "sys/icc_tx.h"
#include "sys/icc.h"
#include "sys/scheduler.h"
#include "xil_io.h"
#include <stdint.h>
#define TASK_ICC_TX_UPDATES_PER_SEC (10000)
#define TASK_ICC_TX_INTERVAL_USEC (USEC_IN_SEC / TASK_ICC_TX_UPDATES_PER_SEC)
// Scheduler TCB which holds task "context"
static task_control_block_t tcb;
#define BUFFER_LENGTH (10 * 1024)
static uint8_t send_buffer[BUFFER_LENGTH] = { 0 };
static uint32_t idx_writing = 0;
static uint32_t idx_reading = 0;
static uint32_t num_in_buffer = 0;
static inline char _pop(void)
{
char ret = send_buffer[idx_reading];
if (++idx_reading >= BUFFER_LENGTH) {
idx_reading = 0;
}
num_in_buffer -= 1;
return ret;
}
int task_icc_tx_get_buffer_space_available(void)
{
return BUFFER_LENGTH - num_in_buffer;
}
static inline void _push(char c)
{
send_buffer[idx_writing] = c;
if (++idx_writing >= BUFFER_LENGTH) {
idx_writing = 0;
}
num_in_buffer += 1;
}
static void task_icc_tx_callback(void *arg)
{
// Try to give all our ringbuf TCP/IP data to CPU0
//
// Bounded up to MAX_NUM_BYTES_TO_TRY bytes
//
// If we ever find that the ICC shared FIFO gets full,
// we'll just stop and wait until next time.
static const int MAX_NUM_BYTES_TO_TRY = 256;
int num_sent = 0;
while (num_in_buffer > 0) {
if (ICC_CPU1to0_CH0__GET_ProduceCount - ICC_CPU1to0_CH0__GET_ConsumeCount == ICC_BUFFER_SIZE) {
// Shared buffer is full
// Return and try again in the next time slice
return;
}
// Write one byte to the sharedBuffer BEFORE incrementing produceCount
uint8_t *sharedBuffer = ICC_CPU1to0_CH0__BufferBaseAddr;
char c = _pop();
sharedBuffer[ICC_CPU1to0_CH0__GET_ProduceCount % ICC_BUFFER_SIZE] = c;
// Memory barrier required here to ensure update of the sharedBuffer is
// visible to the other core before the update of produceCount
//
// Nathan thinks we don't actually have to do this since we turned off
// caching on the OCM, so the write should flush immediately, but,
// I might be wrong and it could be stuck in some pipeline...
// Just to be safe, we'll insert a DMB instruction.
dmb();
// Increment produce count
ICC_CPU1to0_CH0__SET_ProduceCount(ICC_CPU1to0_CH0__GET_ProduceCount + 1);
num_sent++;
if (num_sent > MAX_NUM_BYTES_TO_TRY) {
// We sent enough during this time slice!
// Stop now.
return;
}
}
}
void icc_tx_init(void)
{
if (scheduler_tcb_is_registered(&tcb)) {
return;
}
// Fill TCB with parameters
scheduler_tcb_init(&tcb, task_icc_tx_callback, NULL, "icc_tx", TASK_ICC_TX_INTERVAL_USEC);
// Register task with scheduler
scheduler_tcb_register(&tcb);
}
void icc_tx_append_char_to_fifo(char c)
{
_push(c);
}
void icc_tx_log_stream(int socket_id, int var_slot, uint32_t ts, uint32_t data)
{
// Create packet of data to send to host
//
// Packet format: HEADER, VAR_SLOT, TS, DATA, FOOTER
// where each entry is 32 bits
//
// Total packet length: 5*4 = 20 bytes
//
// HEADER = 0x11111111
// FOOTER = 0x22222222
static const int packet_len = 20;
uint8_t bytes_to_send[20] = { 0 };
uint32_t *ptr_header = (uint32_t *) &bytes_to_send[0];
uint32_t *ptr_var_slot = (uint32_t *) &bytes_to_send[4];
uint32_t *ptr_ts = (uint32_t *) &bytes_to_send[8];
uint32_t *ptr_data = (uint32_t *) &bytes_to_send[12];
uint32_t *ptr_footer = (uint32_t *) &bytes_to_send[16];
*ptr_header = 0x11111111;
*ptr_var_slot = var_slot;
*ptr_ts = ts;
*ptr_data = data;
*ptr_footer = 0x22222222;
for (int i = 0; i < packet_len; i++) {
uint8_t d = bytes_to_send[i];
int buffer_full = 0;
switch (socket_id) {
case 1:
buffer_full = ICC_CPU1to0_CH1__IsBufferFull;
break;
case 2:
buffer_full = ICC_CPU1to0_CH2__IsBufferFull;
break;
case 3:
buffer_full = ICC_CPU1to0_CH3__IsBufferFull;
break;
case 4:
buffer_full = ICC_CPU1to0_CH4__IsBufferFull;
break;
default:
// Invalid socket
// Return from function and fail silently
return;
}
if (buffer_full) {
// Shared buffer is full
// This is a silent error and will cause dropped data!
// For testing, print Q to UART terminal...
xil_printf("Q");
return;
}
// Write one byte to the sharedBuffer BEFORE incrementing produceCount
uint8_t *sharedBuffer;
switch (socket_id) {
case 1:
sharedBuffer = ICC_CPU1to0_CH1__BufferBaseAddr;
sharedBuffer[ICC_CPU1to0_CH1__GET_ProduceCount % ICC_BUFFER_SIZE] = d;
break;
case 2:
sharedBuffer = ICC_CPU1to0_CH2__BufferBaseAddr;
sharedBuffer[ICC_CPU1to0_CH2__GET_ProduceCount % ICC_BUFFER_SIZE] = d;
break;
case 3:
sharedBuffer = ICC_CPU1to0_CH3__BufferBaseAddr;
sharedBuffer[ICC_CPU1to0_CH3__GET_ProduceCount % ICC_BUFFER_SIZE] = d;
break;
case 4:
sharedBuffer = ICC_CPU1to0_CH4__BufferBaseAddr;
sharedBuffer[ICC_CPU1to0_CH4__GET_ProduceCount % ICC_BUFFER_SIZE] = d;
break;
default:
// Not a valid socket...
// Just silently ignore for now
break;
}
// Memory barrier required here to ensure update of the sharedBuffer is
// visible to the other core before the update of produceCount
//
// Nathan thinks we don't actually have to do this since we turned off
// caching on the OCM, so the write should flush immediately, but,
// I might be wrong and it could be stuck in some pipeline...
// Just to be safe, we'll insert a DMB instruction.
dmb();
// Increment produce count
switch (socket_id) {
case 1:
ICC_CPU1to0_CH1__INC_ProduceCount;
break;
case 2:
ICC_CPU1to0_CH2__INC_ProduceCount;
break;
case 3:
ICC_CPU1to0_CH3__INC_ProduceCount;
break;
case 4:
ICC_CPU1to0_CH4__INC_ProduceCount;
break;
default:
// Not a valid socket...
// Just silently ignore for now
break;
}
}
}
| 2.40625 | 2 |
2024-11-18T17:55:08.767299+00:00 | 2015-07-02T05:33:14 | 19671597e3cd5ca60a20cd9305a7f4b952ea86c0 | {
"blob_id": "19671597e3cd5ca60a20cd9305a7f4b952ea86c0",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-02T05:33:14",
"content_id": "3dcb1786c01eecb3e8efca22012e357375132e9f",
"detected_licenses": [
"BSD-4-Clause-UC"
],
"directory_id": "edf20ceb4b41f8b6bd0fcadba354bebf950e1fdf",
"extension": "c",
"filename": "vfs.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 38274817,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 69913,
"license": "BSD-4-Clause-UC",
"license_type": "permissive",
"path": "/akaros-latest/kern/src/vfs.c",
"provenance": "stackv2-0005.json.gz:8300",
"repo_name": "kstraube/hysim",
"revision_date": "2015-07-02T05:33:14",
"revision_id": "f6f3863d3ca32919d4f42c32f56ed1bf2592e5ea",
"snapshot_id": "e94eda41c67e6686023d69491a93426d19560821",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/kstraube/hysim/f6f3863d3ca32919d4f42c32f56ed1bf2592e5ea/akaros-latest/kern/src/vfs.c",
"visit_date": "2021-01-20T15:49:25.367126"
} | stackv2 | /* Copyright (c) 2009, 2010 The Regents of the University of California
* Barret Rhoden <[email protected]>
* See LICENSE for details.
*
* Default implementations and global values for the VFS. */
#include <vfs.h> // keep this first
#include <sys/queue.h>
#include <assert.h>
#include <stdio.h>
#include <atomic.h>
#include <slab.h>
#include <kmalloc.h>
#include <kfs.h>
#include <ext2fs.h>
#include <pmap.h>
#include <umem.h>
#include <smp.h>
struct sb_tailq super_blocks = TAILQ_HEAD_INITIALIZER(super_blocks);
spinlock_t super_blocks_lock = SPINLOCK_INITIALIZER;
struct fs_type_tailq file_systems = TAILQ_HEAD_INITIALIZER(file_systems);
struct namespace default_ns;
struct kmem_cache *dentry_kcache; // not to be confused with the dcache
struct kmem_cache *inode_kcache;
struct kmem_cache *file_kcache;
/* Mounts fs from dev_name at mnt_pt in namespace ns. There could be no mnt_pt,
* such as with the root of (the default) namespace. Not sure how it would work
* with multiple namespaces on the same FS yet. Note if you mount the same FS
* multiple times, you only have one FS still (and one SB). If we ever support
* that... */
struct vfsmount *__mount_fs(struct fs_type *fs, char *dev_name,
struct dentry *mnt_pt, int flags,
struct namespace *ns)
{
struct super_block *sb;
struct vfsmount *vmnt = kmalloc(sizeof(struct vfsmount), 0);
/* this first ref is stored in the NS tailq below */
kref_init(&vmnt->mnt_kref, fake_release, 1);
/* Build the vfsmount, if there is no mnt_pt, mnt is the root vfsmount (for now).
* fields related to the actual FS, like the sb and the mnt_root are set in
* the fs-specific get_sb() call. */
if (!mnt_pt) {
vmnt->mnt_parent = NULL;
vmnt->mnt_mountpoint = NULL;
} else { /* common case, but won't be tested til we try to mount another FS */
mnt_pt->d_mount_point = TRUE;
mnt_pt->d_mounted_fs = vmnt;
kref_get(&vmnt->mnt_kref, 1); /* held by mnt_pt */
vmnt->mnt_parent = mnt_pt->d_sb->s_mount;
vmnt->mnt_mountpoint = mnt_pt;
}
TAILQ_INIT(&vmnt->mnt_child_mounts);
vmnt->mnt_flags = flags;
vmnt->mnt_devname = dev_name;
vmnt->mnt_namespace = ns;
kref_get(&ns->kref, 1); /* held by vmnt */
/* Read in / create the SB */
sb = fs->get_sb(fs, flags, dev_name, vmnt);
if (!sb)
panic("You're FS sucks");
/* TODO: consider moving this into get_sb or something, in case the SB
* already exists (mounting again) (if we support that) */
spin_lock(&super_blocks_lock);
TAILQ_INSERT_TAIL(&super_blocks, sb, s_list); /* storing a ref here... */
spin_unlock(&super_blocks_lock);
/* Update holding NS */
spin_lock(&ns->lock);
TAILQ_INSERT_TAIL(&ns->vfsmounts, vmnt, mnt_list);
spin_unlock(&ns->lock);
/* note to self: so, right after this point, the NS points to the root FS
* mount (we return the mnt, which gets assigned), the root mnt has a dentry
* for /, backed by an inode, with a SB prepped and in memory. */
return vmnt;
}
void vfs_init(void)
{
struct fs_type *fs;
dentry_kcache = kmem_cache_create("dentry", sizeof(struct dentry),
__alignof__(struct dentry), 0, 0, 0);
inode_kcache = kmem_cache_create("inode", sizeof(struct inode),
__alignof__(struct inode), 0, 0, 0);
file_kcache = kmem_cache_create("file", sizeof(struct file),
__alignof__(struct file), 0, 0, 0);
/* default NS never dies, +1 to exist */
kref_init(&default_ns.kref, fake_release, 1);
spinlock_init(&default_ns.lock);
default_ns.root = NULL;
TAILQ_INIT(&default_ns.vfsmounts);
/* build list of all FS's in the system. put yours here. if this is ever
* done on the fly, we'll need to lock. */
TAILQ_INSERT_TAIL(&file_systems, &kfs_fs_type, list);
#ifdef __CONFIG_EXT2FS__
TAILQ_INSERT_TAIL(&file_systems, &ext2_fs_type, list);
#endif
TAILQ_FOREACH(fs, &file_systems, list)
printk("Supports the %s Filesystem\n", fs->name);
/* mounting KFS at the root (/), pending root= parameters */
// TODO: linux creates a temp root_fs, then mounts the real root onto that
default_ns.root = __mount_fs(&kfs_fs_type, "RAM", NULL, 0, &default_ns);
printk("vfs_init() completed\n");
}
/* Builds / populates the qstr of a dentry based on its d_iname. If there is an
* l_name, (long), it will use that instead of the inline name. This will
* probably change a bit. */
void qstr_builder(struct dentry *dentry, char *l_name)
{
dentry->d_name.name = l_name ? l_name : dentry->d_iname;
// TODO: pending what we actually do in d_hash
//dentry->d_name.hash = dentry->d_op->d_hash(dentry, &dentry->d_name);
dentry->d_name.hash = 0xcafebabe;
dentry->d_name.len = strnlen(dentry->d_name.name, MAX_FILENAME_SZ);
}
/* Useful little helper - return the string ptr for a given file */
char *file_name(struct file *file)
{
return file->f_dentry->d_name.name;
}
/* Some issues with this, coupled closely to fs_lookup.
*
* Note the use of __dentry_free, instead of kref_put. In those cases, we don't
* want to treat it like a kref and we have the only reference to it, so it is
* okay to do this. It makes dentry_release() easier too. */
static struct dentry *do_lookup(struct dentry *parent, char *name)
{
struct dentry *result, *query;
query = get_dentry(parent->d_sb, parent, name);
result = dcache_get(parent->d_sb, query);
if (result) {
__dentry_free(query);
return result;
}
/* No result, check for negative */
if (query->d_flags & DENTRY_NEGATIVE) {
__dentry_free(query);
return 0;
}
/* not in the dcache at all, need to consult the FS */
result = parent->d_inode->i_op->lookup(parent->d_inode, query, 0);
if (!result) {
/* Note the USED flag will get turned off when this gets added to the
* LRU in dentry_release(). There's a slight race here that we'll panic
* on, but I want to catch it (in dcache_put()) for now. */
query->d_flags |= DENTRY_NEGATIVE;
dcache_put(parent->d_sb, query);
kref_put(&query->d_kref);
return 0;
}
dcache_put(parent->d_sb, result);
/* This is because KFS doesn't return the same dentry, but ext2 does. this
* is ugly and needs to be fixed. (TODO) */
if (result != query)
__dentry_free(query);
/* TODO: if the following are done by us, how do we know the i_ino?
* also need to handle inodes that are already read in! For now, we're
* going to have the FS handle it in it's lookup() method:
* - get a new inode
* - read in the inode
* - put in the inode cache */
return result;
}
/* Update ND such that it represents having followed dentry. IAW the nd
* refcnting rules, we need to decref any references that were in there before
* they get clobbered. */
static int next_link(struct dentry *dentry, struct nameidata *nd)
{
assert(nd->dentry && nd->mnt);
/* update the dentry */
kref_get(&dentry->d_kref, 1);
kref_put(&nd->dentry->d_kref);
nd->dentry = dentry;
/* update the mount, if we need to */
if (dentry->d_sb->s_mount != nd->mnt) {
kref_get(&dentry->d_sb->s_mount->mnt_kref, 1);
kref_put(&nd->mnt->mnt_kref);
nd->mnt = dentry->d_sb->s_mount;
}
return 0;
}
/* Walk up one directory, being careful of mountpoints, namespaces, and the top
* of the FS */
static int climb_up(struct nameidata *nd)
{
printd("CLIMB_UP, from %s\n", nd->dentry->d_name.name);
/* Top of the world, just return. Should also check for being at the top of
* the current process's namespace (TODO) */
if (!nd->dentry->d_parent || (nd->dentry->d_parent == nd->dentry))
return -1;
/* Check if we are at the top of a mount, if so, we need to follow
* backwards, and then climb_up from that one. We might need to climb
* multiple times if we mount multiple FSs at the same spot (highly
* unlikely). This is completely untested. Might recurse instead. */
while (nd->mnt->mnt_root == nd->dentry) {
if (!nd->mnt->mnt_parent) {
warn("Might have expected a parent vfsmount (dentry had a parent)");
return -1;
}
next_link(nd->mnt->mnt_mountpoint, nd);
}
/* Backwards walk (no mounts or any other issues now). */
next_link(nd->dentry->d_parent, nd);
printd("CLIMB_UP, to %s\n", nd->dentry->d_name.name);
return 0;
}
/* nd->dentry might be on a mount point, so we need to move on to the child
* mount's root. */
static int follow_mount(struct nameidata *nd)
{
if (!nd->dentry->d_mount_point)
return 0;
next_link(nd->dentry->d_mounted_fs->mnt_root, nd);
return 0;
}
static int link_path_walk(char *path, struct nameidata *nd);
/* When nd->dentry is for a symlink, this will recurse and follow that symlink,
* so that nd contains the results of following the symlink (dentry and mnt).
* Returns when it isn't a symlink, 1 on following a link, and < 0 on error. */
static int follow_symlink(struct nameidata *nd)
{
int retval;
char *symname;
if (!S_ISLNK(nd->dentry->d_inode->i_mode))
return 0;
if (nd->depth > MAX_SYMLINK_DEPTH)
return -ELOOP;
printd("Following symlink for dentry %08p %s\n", nd->dentry,
nd->dentry->d_name.name);
nd->depth++;
symname = nd->dentry->d_inode->i_op->readlink(nd->dentry);
/* We need to pin in nd->dentry (the dentry of the symlink), since we need
* it's symname's storage to stay in memory throughout the upcoming
* link_path_walk(). The last_sym gets decreffed when we path_release() or
* follow another symlink. */
if (nd->last_sym)
kref_put(&nd->last_sym->d_kref);
kref_get(&nd->dentry->d_kref, 1);
nd->last_sym = nd->dentry;
/* If this an absolute path in the symlink, we need to free the old path and
* start over, otherwise, we continue from the PARENT of nd (the symlink) */
if (symname[0] == '/') {
path_release(nd);
if (!current)
nd->dentry = default_ns.root->mnt_root;
else
nd->dentry = current->fs_env.root;
nd->mnt = nd->dentry->d_sb->s_mount;
kref_get(&nd->mnt->mnt_kref, 1);
kref_get(&nd->dentry->d_kref, 1);
} else {
climb_up(nd);
}
/* either way, keep on walking in the free world! */
retval = link_path_walk(symname, nd);
return (retval == 0 ? 1 : retval);
}
/* Little helper, to make it easier to break out of the nested loops. Will also
* '\0' out the first slash if it's slashes all the way down. Or turtles. */
static bool packed_trailing_slashes(char *first_slash)
{
for (char *i = first_slash; *i == '/'; i++) {
if (*(i + 1) == '\0') {
*first_slash = '\0';
return TRUE;
}
}
return FALSE;
}
/* Simple helper to set nd to track it's last name to be Name. Also be careful
* with the storage of name. Don't use and nd's name past the lifetime of the
* string used in the path_lookup()/link_path_walk/whatever. Consider replacing
* parts of this with a qstr builder. Note this uses the dentry's d_op, which
* might not be the dentry we care about. */
static void stash_nd_name(struct nameidata *nd, char *name)
{
nd->last.name = name;
nd->last.len = strlen(name);
nd->last.hash = nd->dentry->d_op->d_hash(nd->dentry, &nd->last);
}
/* Resolves the links in a basic path walk. 0 for success, -EWHATEVER
* otherwise. The final lookup is returned via nd. */
static int link_path_walk(char *path, struct nameidata *nd)
{
struct dentry *link_dentry;
struct inode *link_inode, *nd_inode;
char *next_slash;
char *link = path;
int error;
/* Prevent crazy recursion */
if (nd->depth > MAX_SYMLINK_DEPTH)
return -ELOOP;
/* skip all leading /'s */
while (*link == '/')
link++;
/* if there's nothing left (null terminated), we're done. This should only
* happen for "/", which if we wanted a PARENT, should fail (there is no
* parent). */
if (*link == '\0') {
if (nd->flags & LOOKUP_PARENT) {
set_errno(ENOENT);
return -1;
}
/* o/w, we're good */
return 0;
}
/* iterate through each intermediate link of the path. in general, nd
* tracks where we are in the path, as far as dentries go. once we have the
* next dentry, we try to update nd based on that dentry. link is the part
* of the path string that we are looking up */
while (1) {
nd_inode = nd->dentry->d_inode;
if ((error = check_perms(nd_inode, nd->intent)))
return error;
/* find the next link, break out if it is the end */
next_slash = strchr(link, '/');
if (!next_slash) {
break;
} else {
if (packed_trailing_slashes(next_slash)) {
nd->flags |= LOOKUP_DIRECTORY;
break;
}
}
/* skip over any interim ./ */
if (!strncmp("./", link, 2))
goto next_loop;
/* Check for "../", walk up */
if (!strncmp("../", link, 3)) {
climb_up(nd);
goto next_loop;
}
*next_slash = '\0';
link_dentry = do_lookup(nd->dentry, link);
*next_slash = '/';
if (!link_dentry)
return -ENOENT;
/* make link_dentry the current step/answer */
next_link(link_dentry, nd);
kref_put(&link_dentry->d_kref); /* do_lookup gave us a refcnt dentry */
/* we could be on a mountpoint or a symlink - need to follow them */
follow_mount(nd);
if ((error = follow_symlink(nd)) < 0)
return error;
/* Turn off a possible DIRECTORY lookup, which could have been set
* during the follow_symlink (a symlink could have had a directory at
* the end), though it was in the middle of the real path. */
nd->flags &= ~LOOKUP_DIRECTORY;
if (!S_ISDIR(nd->dentry->d_inode->i_mode))
return -ENOTDIR;
next_loop:
/* move through the path string to the next entry */
link = next_slash + 1;
/* advance past any other interim slashes. we know we won't hit the end
* due to the for loop check above */
while (*link == '/')
link++;
}
/* Now, we're on the last link of the path. We need to deal with with . and
* .. . This might be weird with PARENT lookups - not sure what semantics
* we want exactly. This will give the parent of whatever the PATH was
* supposed to look like. Note that ND currently points to the parent of
* the last item (link). */
if (!strcmp(".", link)) {
if (nd->flags & LOOKUP_PARENT) {
assert(nd->dentry->d_name.name);
stash_nd_name(nd, nd->dentry->d_name.name);
climb_up(nd);
}
return 0;
}
if (!strcmp("..", link)) {
climb_up(nd);
if (nd->flags & LOOKUP_PARENT) {
assert(nd->dentry->d_name.name);
stash_nd_name(nd, nd->dentry->d_name.name);
climb_up(nd);
}
return 0;
}
/* need to attempt to look it up, in case it's a symlink */
link_dentry = do_lookup(nd->dentry, link);
if (!link_dentry) {
/* if there's no dentry, we are okay if we are looking for the parent */
if (nd->flags & LOOKUP_PARENT) {
assert(strcmp(link, ""));
stash_nd_name(nd, link);
return 0;
} else {
return -ENOENT;
}
}
next_link(link_dentry, nd);
kref_put(&link_dentry->d_kref); /* do_lookup gave us a refcnt'd dentry */
/* at this point, nd is on the final link, but it might be a symlink */
if (nd->flags & LOOKUP_FOLLOW) {
error = follow_symlink(nd);
if (error < 0)
return error;
/* if we actually followed a symlink, then nd is set and we're done */
if (error > 0)
return 0;
}
/* One way or another, nd is on the last element of the path, symlinks and
* all. Now we need to climb up to set nd back on the parent, if that's
* what we wanted */
if (nd->flags & LOOKUP_PARENT) {
assert(nd->dentry->d_name.name);
stash_nd_name(nd, link_dentry->d_name.name);
climb_up(nd);
return 0;
}
/* now, we have the dentry set, and don't want the parent, but might be on a
* mountpoint still. FYI: this hasn't been thought through completely. */
follow_mount(nd);
/* If we wanted a directory, but didn't get one, error out */
if ((nd->flags & LOOKUP_DIRECTORY) && !S_ISDIR(nd->dentry->d_inode->i_mode))
return -ENOTDIR;
return 0;
}
/* Given path, return the inode for the final dentry. The ND should be
* initialized for the first call - specifically, we need the intent.
* LOOKUP_PARENT and friends go in the flags var, which is not the intent.
*
* If path_lookup wants a PARENT, but hits the top of the FS (root or
* otherwise), we want it to error out. It's still unclear how we want to
* handle processes with roots that aren't root, but at the very least, we don't
* want to think we have the parent of /, but have / itself. Due to the way
* link_path_walk works, if that happened, we probably don't have a
* nd->last.name. This needs more thought (TODO).
*
* Need to be careful too. While the path has been copied-in to the kernel,
* it's still user input. */
int path_lookup(char *path, int flags, struct nameidata *nd)
{
int retval;
printd("Path lookup for %s\n", path);
/* we allow absolute lookups with no process context */
if (path[0] == '/') { /* absolute lookup */
if (!current)
nd->dentry = default_ns.root->mnt_root;
else
nd->dentry = current->fs_env.root;
} else { /* relative lookup */
assert(current);
/* Don't need to lock on the fs_env since we're reading one item */
nd->dentry = current->fs_env.pwd;
}
nd->mnt = nd->dentry->d_sb->s_mount;
/* Whenever references get put in the nd, incref them. Whenever they are
* removed, decref them. */
kref_get(&nd->mnt->mnt_kref, 1);
kref_get(&nd->dentry->d_kref, 1);
nd->flags = flags;
nd->depth = 0; /* used in symlink following */
retval = link_path_walk(path, nd);
/* make sure our PARENT lookup worked */
if (!retval && (flags & LOOKUP_PARENT))
assert(nd->last.name);
return retval;
}
/* Call this after any use of path_lookup when you are done with its results,
* regardless of whether it succeeded or not. It will free any references */
void path_release(struct nameidata *nd)
{
kref_put(&nd->dentry->d_kref);
kref_put(&nd->mnt->mnt_kref);
/* Free the last symlink dentry used, if there was one */
if (nd->last_sym) {
kref_put(&nd->last_sym->d_kref);
nd->last_sym = 0; /* catch reuse bugs */
}
}
/* External version of mount, only call this after having a / mount */
int mount_fs(struct fs_type *fs, char *dev_name, char *path, int flags)
{
struct nameidata nd_r = {0}, *nd = &nd_r;
int retval = 0;
retval = path_lookup(path, LOOKUP_DIRECTORY, nd);
if (retval)
goto out;
/* taking the namespace of the vfsmount of path */
if (!__mount_fs(fs, dev_name, nd->dentry, flags, nd->mnt->mnt_namespace))
retval = -EINVAL;
out:
path_release(nd);
return retval;
}
/* Superblock functions */
/* Dentry "hash" function for the hash table to use. Since we already have the
* hash in the qstr, we don't need to rehash. Also, note we'll be using the
* dentry in question as both the key and the value. */
static size_t __dcache_hash(void *k)
{
return (size_t)((struct dentry*)k)->d_name.hash;
}
/* Dentry cache hashtable equality function. This means we need to pass in some
* minimal dentry when doing a lookup. */
static ssize_t __dcache_eq(void *k1, void *k2)
{
if (((struct dentry*)k1)->d_parent != ((struct dentry*)k2)->d_parent)
return 0;
/* TODO: use the FS-specific string comparison */
return !strcmp(((struct dentry*)k1)->d_name.name,
((struct dentry*)k2)->d_name.name);
}
/* Helper to alloc and initialize a generic superblock. This handles all the
* VFS related things, like lists. Each FS will need to handle its own things
* in it's *_get_sb(), usually involving reading off the disc. */
struct super_block *get_sb(void)
{
struct super_block *sb = kmalloc(sizeof(struct super_block), 0);
sb->s_dirty = FALSE;
spinlock_init(&sb->s_lock);
kref_init(&sb->s_kref, fake_release, 1); /* for the ref passed out */
TAILQ_INIT(&sb->s_inodes);
TAILQ_INIT(&sb->s_dirty_i);
TAILQ_INIT(&sb->s_io_wb);
TAILQ_INIT(&sb->s_lru_d);
TAILQ_INIT(&sb->s_files);
sb->s_dcache = create_hashtable(100, __dcache_hash, __dcache_eq);
sb->s_icache = create_hashtable(100, __generic_hash, __generic_eq);
spinlock_init(&sb->s_lru_lock);
spinlock_init(&sb->s_dcache_lock);
spinlock_init(&sb->s_icache_lock);
sb->s_fs_info = 0; // can override somewhere else
return sb;
}
/* Final stages of initializing a super block, including creating and linking
* the root dentry, root inode, vmnt, and sb. The d_op and root_ino are
* FS-specific, but otherwise it's FS-independent, tricky, and not worth having
* around multiple times.
*
* Not the world's best interface, so it's subject to change, esp since we're
* passing (now 3) FS-specific things. */
void init_sb(struct super_block *sb, struct vfsmount *vmnt,
struct dentry_operations *d_op, unsigned long root_ino,
void *d_fs_info)
{
/* Build and init the first dentry / inode. The dentry ref is stored later
* by vfsmount's mnt_root. The parent is dealt with later. */
struct dentry *d_root = get_dentry(sb, 0, "/"); /* probably right */
/* a lot of here on down is normally done in lookup() or create, since
* get_dentry isn't a fully usable dentry. The two FS-specific settings are
* normally inherited from a parent within the same FS in get_dentry, but we
* have none here. */
d_root->d_op = d_op;
d_root->d_fs_info = d_fs_info;
struct inode *inode = get_inode(d_root);
if (!inode)
panic("This FS sucks!");
inode->i_ino = root_ino;
/* TODO: add the inode to the appropriate list (off i_list) */
/* TODO: do we need to read in the inode? can we do this on demand? */
/* if this FS is already mounted, we'll need to do something different. */
sb->s_op->read_inode(inode);
icache_put(sb, inode);
/* Link the dentry and SB to the VFS mount */
vmnt->mnt_root = d_root; /* ref comes from get_dentry */
vmnt->mnt_sb = sb;
/* If there is no mount point, there is no parent. This is true only for
* the rootfs. */
if (vmnt->mnt_mountpoint) {
kref_get(&vmnt->mnt_mountpoint->d_kref, 1); /* held by d_root */
d_root->d_parent = vmnt->mnt_mountpoint; /* dentry of the root */
} else {
d_root->d_parent = d_root; /* set root as its own parent */
}
/* insert the dentry into the dentry cache. when's the earliest we can?
* when's the earliest we should? what about concurrent accesses to the
* same dentry? should be locking the dentry... */
dcache_put(sb, d_root);
kref_put(&inode->i_kref); /* give up the ref from get_inode() */
}
/* Dentry Functions */
/* Helper to alloc and initialize a generic dentry. The following needs to be
* set still: d_op (if no parent), d_fs_info (opt), d_inode, connect the inode
* to the dentry (and up the d_kref again), maybe dcache_put(). The inode
* stitching is done in get_inode() or lookup (depending on the FS).
* The setting of the d_op might be problematic when dealing with mounts. Just
* overwrite it.
*
* If the name is longer than the inline name, it will kmalloc a buffer, so
* don't worry about the storage for *name after calling this. */
struct dentry *get_dentry(struct super_block *sb, struct dentry *parent,
char *name)
{
assert(name);
size_t name_len = strnlen(name, MAX_FILENAME_SZ); /* not including \0! */
struct dentry *dentry = kmem_cache_alloc(dentry_kcache, 0);
char *l_name = 0;
if (!dentry)
return 0;
//memset(dentry, 0, sizeof(struct dentry));
kref_init(&dentry->d_kref, dentry_release, 1); /* this ref is returned */
spinlock_init(&dentry->d_lock);
TAILQ_INIT(&dentry->d_subdirs);
dentry->d_time = 0;
kref_get(&sb->s_kref, 1);
dentry->d_sb = sb; /* storing a ref here... */
dentry->d_mount_point = FALSE;
dentry->d_mounted_fs = 0;
if (parent) { /* no parent for rootfs mount */
kref_get(&parent->d_kref, 1);
dentry->d_op = parent->d_op; /* d_op set in init_sb for parentless */
}
dentry->d_parent = parent;
dentry->d_flags = DENTRY_USED;
dentry->d_fs_info = 0;
if (name_len < DNAME_INLINE_LEN) {
strncpy(dentry->d_iname, name, name_len);
dentry->d_iname[name_len] = '\0';
qstr_builder(dentry, 0);
} else {
l_name = kmalloc(name_len + 1, 0);
assert(l_name);
strncpy(l_name, name, name_len);
l_name[name_len] = '\0';
qstr_builder(dentry, l_name);
}
/* Catch bugs by aggressively zeroing this (o/w we use old stuff) */
dentry->d_inode = 0;
return dentry;
}
/* Called when the dentry is unreferenced (after kref == 0). This works closely
* with the resurrection in dcache_get().
*
* The dentry is still in the dcache, but needs to be un-USED and added to the
* LRU dentry list. Even dentries that were used in a failed lookup need to be
* cached - they ought to be the negative dentries. Note that all dentries have
* parents, even negative ones (it is needed to find it in the dcache). */
void dentry_release(struct kref *kref)
{
struct dentry *dentry = container_of(kref, struct dentry, d_kref);
printd("'Releasing' dentry %08p: %s\n", dentry, dentry->d_name.name);
/* DYING dentries (recently unlinked / rmdir'd) just get freed */
if (dentry->d_flags & DENTRY_DYING) {
__dentry_free(dentry);
return;
}
/* This lock ensures the USED state and the TAILQ membership is in sync.
* Also used to check the refcnt, though that might not be necessary. */
spin_lock(&dentry->d_lock);
/* While locked, we need to double check the kref, in case someone already
* reup'd it. Re-up? you're crazy! Reee-up, you're outta yo mind! */
if (!kref_refcnt(&dentry->d_kref)) {
/* Note this is where negative dentries get set UNUSED */
if (dentry->d_flags & DENTRY_USED) {
dentry->d_flags &= ~DENTRY_USED;
spin_lock(&dentry->d_sb->s_lru_lock);
TAILQ_INSERT_TAIL(&dentry->d_sb->s_lru_d, dentry, d_lru);
spin_unlock(&dentry->d_sb->s_lru_lock);
} else {
/* and make sure it wasn't USED, then UNUSED again */
/* TODO: think about issues with this */
warn("This should be rare. Tell brho this happened.");
}
}
spin_unlock(&dentry->d_lock);
}
/* Called when we really dealloc and get rid of a dentry (like when it is
* removed from the dcache, either for memory or correctness reasons)
*
* This has to handle two types of dentries: full ones (ones that had been used)
* and ones that had been just for lookups - hence the check for d_inode.
*
* Note that dentries pin and kref their inodes. When all the dentries are
* gone, we want the inode to be released via kref. The inode has internal /
* weak references to the dentry, which are not refcounted. */
void __dentry_free(struct dentry *dentry)
{
if (dentry->d_inode)
printk("Freeing dentry %08p: %s\n", dentry, dentry->d_name.name);
assert(dentry->d_op); /* catch bugs. a while back, some lacked d_op */
dentry->d_op->d_release(dentry);
/* TODO: check/test the boundaries on this. */
if (dentry->d_name.len > DNAME_INLINE_LEN)
kfree((void*)dentry->d_name.name);
kref_put(&dentry->d_sb->s_kref);
if (dentry->d_parent)
kref_put(&dentry->d_parent->d_kref);
if (dentry->d_mounted_fs)
kref_put(&dentry->d_mounted_fs->mnt_kref);
if (dentry->d_inode) {
TAILQ_REMOVE(&dentry->d_inode->i_dentry, dentry, d_alias);
kref_put(&dentry->d_inode->i_kref); /* dentries kref inodes */
}
kmem_cache_free(dentry_kcache, dentry);
}
/* Looks up the dentry for the given path, returning a refcnt'd dentry (or 0).
* Permissions are applied for the current user, which is quite a broken system
* at the moment. Flags are lookup flags. */
struct dentry *lookup_dentry(char *path, int flags)
{
struct dentry *dentry;
struct nameidata nd_r = {0}, *nd = &nd_r;
int error;
error = path_lookup(path, flags, nd);
if (error) {
path_release(nd);
set_errno(-error);
return 0;
}
dentry = nd->dentry;
kref_get(&dentry->d_kref, 1);
path_release(nd);
return dentry;
}
/* Get a dentry from the dcache. At a minimum, we need the name hash and parent
* in what_i_want, though most uses will probably be from a get_dentry() call.
* We pass in the SB in the off chance that we don't want to use a get'd dentry.
*
* The unusual variable name (instead of just "key" or something) is named after
* ex-SPC Castro's porn folder. Caller deals with the memory for what_i_want.
*
* If the dentry is negative, we don't return the actual result - instead, we
* set the negative flag in 'what i want'. The reason is we don't want to
* kref_get() and then immediately put (causing dentry_release()). This also
* means that dentry_release() should never get someone who wasn't USED (barring
* the race, which it handles). And we don't need to ever have a dentry set as
* USED and NEGATIVE (which is always wrong, but would be needed for a cleaner
* dentry_release()).
*
* This is where we do the "kref resurrection" - we are returning a kref'd
* object, even if it wasn't kref'd before. This means the dcache does NOT hold
* krefs (it is a weak/internal ref), but it is a source of kref generation. We
* sync up with the possible freeing of the dentry by locking the table. See
* Doc/kref for more info. */
struct dentry *dcache_get(struct super_block *sb, struct dentry *what_i_want)
{
struct dentry *found;
/* This lock protects the hash, as well as ensures the returned object
* doesn't get deleted/freed out from under us */
spin_lock(&sb->s_dcache_lock);
found = hashtable_search(sb->s_dcache, what_i_want);
if (found) {
if (found->d_flags & DENTRY_NEGATIVE) {
what_i_want->d_flags |= DENTRY_NEGATIVE;
spin_unlock(&sb->s_dcache_lock);
return 0;
}
spin_lock(&found->d_lock);
__kref_get(&found->d_kref, 1); /* prob could be done outside the lock*/
/* If we're here (after kreffing) and it is not USED, we are the one who
* should resurrect */
if (!(found->d_flags & DENTRY_USED)) {
found->d_flags |= DENTRY_USED;
spin_lock(&sb->s_lru_lock);
TAILQ_REMOVE(&sb->s_lru_d, found, d_lru);
spin_unlock(&sb->s_lru_lock);
}
spin_unlock(&found->d_lock);
}
spin_unlock(&sb->s_dcache_lock);
return found;
}
/* Adds a dentry to the dcache. Note the *dentry is both the key and the value.
* If the value was already in there (which can happen iff it was negative), for
* now we'll remove it and put the new one in there. */
void dcache_put(struct super_block *sb, struct dentry *key_val)
{
struct dentry *old;
int retval;
spin_lock(&sb->s_dcache_lock);
old = hashtable_remove(sb->s_dcache, key_val);
if (old) {
assert(old->d_flags & DENTRY_NEGATIVE);
/* This is possible, but rare for now (about to be put on the LRU) */
assert(!(old->d_flags & DENTRY_USED));
assert(!kref_refcnt(&old->d_kref));
spin_lock(&sb->s_lru_lock);
TAILQ_REMOVE(&sb->s_lru_d, old, d_lru);
spin_unlock(&sb->s_lru_lock);
__dentry_free(old);
}
/* this returns 0 on failure (TODO: Fix this ghetto shit) */
retval = hashtable_insert(sb->s_dcache, key_val, key_val);
assert(retval);
spin_unlock(&sb->s_dcache_lock);
}
/* Will remove and return the dentry. Caller deallocs the key, but the retval
* won't have a reference. * Returns 0 if it wasn't found. Callers can't
* assume much - they should not use the reference they *get back*, (if they
* already had one for key, they can use that). There may be other users out
* there. */
struct dentry *dcache_remove(struct super_block *sb, struct dentry *key)
{
struct dentry *retval;
spin_lock(&sb->s_dcache_lock);
retval = hashtable_remove(sb->s_dcache, key);
spin_unlock(&sb->s_dcache_lock);
return retval;
}
/* This will clean out the LRU list, which are the unused dentries of the dentry
* cache. This will optionally only free the negative ones. Note that we grab
* the hash lock for the time we traverse the LRU list - this prevents someone
* from getting a kref from the dcache, which could cause us trouble (we rip
* someone off the list, who isn't unused, and they try to rip them off the
* list). */
void dcache_prune(struct super_block *sb, bool negative_only)
{
struct dentry *d_i, *temp;
struct dentry_tailq victims = TAILQ_HEAD_INITIALIZER(victims);
spin_lock(&sb->s_dcache_lock);
spin_lock(&sb->s_lru_lock);
TAILQ_FOREACH_SAFE(d_i, &sb->s_lru_d, d_lru, temp) {
if (!(d_i->d_flags & DENTRY_USED)) {
if (negative_only && !(d_i->d_flags & DENTRY_NEGATIVE))
continue;
/* another place where we'd be better off with tools, not sol'ns */
hashtable_remove(sb->s_dcache, d_i);
TAILQ_REMOVE(&sb->s_lru_d, d_i, d_lru);
TAILQ_INSERT_HEAD(&victims, d_i, d_lru);
}
}
spin_unlock(&sb->s_lru_lock);
spin_unlock(&sb->s_dcache_lock);
/* Now do the actual freeing, outside of the hash/LRU list locks. This is
* necessary since __dentry_free() will decref its parent, which may get
* released and try to add itself to the LRU. */
TAILQ_FOREACH_SAFE(d_i, &victims, d_lru, temp) {
TAILQ_REMOVE(&victims, d_i, d_lru);
assert(!kref_refcnt(&d_i->d_kref));
__dentry_free(d_i);
}
/* It is possible at this point that there are new items on the LRU. We
* could loop back until that list is empty, if we care about this. */
}
/* Inode Functions */
/* Creates and initializes a new inode. Generic fields are filled in.
* FS-specific fields are filled in by the callout. Specific fields are filled
* in in read_inode() based on what's on the disk for a given i_no, or when the
* inode is created (for new objects).
*
* i_no is set by the caller. Note that this means this inode can be for an
* inode that is already on disk, or it can be used when creating. */
struct inode *get_inode(struct dentry *dentry)
{
struct super_block *sb = dentry->d_sb;
/* FS allocs and sets the following: i_op, i_fop, i_pm.pm_op, and any FS
* specific stuff. */
struct inode *inode = sb->s_op->alloc_inode(sb);
if (!inode) {
set_errno(ENOMEM);
return 0;
}
TAILQ_INSERT_HEAD(&sb->s_inodes, inode, i_sb_list); /* weak inode ref */
TAILQ_INIT(&inode->i_dentry);
TAILQ_INSERT_TAIL(&inode->i_dentry, dentry, d_alias); /* weak dentry ref*/
/* one for the dentry->d_inode, one passed out */
kref_init(&inode->i_kref, inode_release, 2);
dentry->d_inode = inode;
inode->i_ino = 0; /* set by caller later */
inode->i_blksize = sb->s_blocksize;
spinlock_init(&inode->i_lock);
kref_get(&sb->s_kref, 1); /* could allow the dentry to pin it */
inode->i_sb = sb;
inode->i_rdev = 0; /* this has no real meaning yet */
inode->i_bdev = sb->s_bdev; /* storing an uncounted ref */
inode->i_state = 0; /* need real states, like I_NEW */
inode->dirtied_when = 0;
inode->i_flags = 0;
atomic_set(&inode->i_writecount, 0);
/* Set up the page_map structures. Default is to use the embedded one.
* Might push some of this back into specific FSs. For now, the FS tells us
* what pm_op they want via i_pm.pm_op, which we set again in pm_init() */
inode->i_mapping = &inode->i_pm;
pm_init(inode->i_mapping, inode->i_pm.pm_op, inode);
return inode;
}
/* Helper: loads/ reads in the inode numbered ino and attaches it to dentry */
void load_inode(struct dentry *dentry, unsigned int ino)
{
struct inode *inode;
/* look it up in the inode cache first */
inode = icache_get(dentry->d_sb, ino);
if (inode) {
/* connect the dentry to its inode */
TAILQ_INSERT_TAIL(&inode->i_dentry, dentry, d_alias);
dentry->d_inode = inode; /* storing the ref we got from icache_get */
return;
}
/* otherwise, we need to do it manually */
inode = get_inode(dentry);
inode->i_ino = ino;
dentry->d_sb->s_op->read_inode(inode);
/* TODO: race here, two creators could miss in the cache, and then get here.
* need a way to sync across a blocking call. needs to be either at this
* point in the code or per the ino (dentries could be different) */
icache_put(dentry->d_sb, inode);
kref_put(&inode->i_kref);
}
/* Helper op, used when creating regular files, directories, symlinks, etc.
* Note we make a distinction between the mode and the file type (for now).
* After calling this, call the FS specific version (create or mkdir), which
* will set the i_ino, the filetype, and do any other FS-specific stuff. Also
* note that a lot of inode stuff was initialized in get_inode/alloc_inode. The
* stuff here is pertinent to the specific creator (user), mode, and time. Also
* note we don't pass this an nd, like Linux does... */
static struct inode *create_inode(struct dentry *dentry, int mode)
{
/* note it is the i_ino that uniquely identifies a file in the specific
* filesystem. there's a diff between creating an inode (even for an in-use
* ino) and then filling it in, and vs creating a brand new one.
* get_inode() sets it to 0, and it should be filled in later in an
* FS-specific manner. */
struct inode *inode = get_inode(dentry);
if (!inode)
return 0;
inode->i_mode = mode & S_PMASK; /* note that after this, we have no type */
inode->i_nlink = 1;
inode->i_size = 0;
inode->i_blocks = 0;
inode->i_atime.tv_sec = 0; /* TODO: now! */
inode->i_ctime.tv_sec = 0;
inode->i_mtime.tv_sec = 0;
inode->i_atime.tv_nsec = 0; /* are these supposed to be the extra ns? */
inode->i_ctime.tv_nsec = 0;
inode->i_mtime.tv_nsec = 0;
inode->i_bdev = inode->i_sb->s_bdev;
/* when we have notions of users, do something here: */
inode->i_uid = 0;
inode->i_gid = 0;
return inode;
}
/* Create a new disk inode in dir associated with dentry, with the given mode.
* called when creating a regular file. dir is the directory/parent. dentry is
* the dentry of the inode we are creating. Note the lack of the nd... */
int create_file(struct inode *dir, struct dentry *dentry, int mode)
{
struct inode *new_file = create_inode(dentry, mode);
if (!new_file)
return -1;
dir->i_op->create(dir, dentry, mode, 0);
icache_put(new_file->i_sb, new_file);
kref_put(&new_file->i_kref);
return 0;
}
/* Creates a new inode for a directory associated with dentry in dir with the
* given mode. */
int create_dir(struct inode *dir, struct dentry *dentry, int mode)
{
struct inode *new_dir = create_inode(dentry, mode);
if (!new_dir)
return -1;
dir->i_op->mkdir(dir, dentry, mode);
dir->i_nlink++; /* Directories get a hardlink for every child dir */
/* Make sure my parent tracks me. This is okay, since no directory (dir)
* can have more than one dentry */
struct dentry *parent = TAILQ_FIRST(&dir->i_dentry);
assert(parent && parent == TAILQ_LAST(&dir->i_dentry, dentry_tailq));
/* parent dentry tracks dentry as a subdir, weak reference */
TAILQ_INSERT_TAIL(&parent->d_subdirs, dentry, d_subdirs_link);
icache_put(new_dir->i_sb, new_dir);
kref_put(&new_dir->i_kref);
return 0;
}
/* Creates a new inode for a symlink associated with dentry in dir, containing
* the symlink symname */
int create_symlink(struct inode *dir, struct dentry *dentry,
const char *symname, int mode)
{
struct inode *new_sym = create_inode(dentry, mode);
if (!new_sym)
return -1;
dir->i_op->symlink(dir, dentry, symname);
icache_put(new_sym->i_sb, new_sym);
kref_put(&new_sym->i_kref);
return 0;
}
/* Returns 0 if the given mode is acceptable for the inode, and an appropriate
* error code if not. Needs to be writen, based on some sensible rules, and
* will also probably use 'current' */
int check_perms(struct inode *inode, int access_mode)
{
return 0; /* anything goes! */
}
/* Called after all external refs are gone to clean up the inode. Once this is
* called, all dentries pointing here are already done (one of them triggered
* this via kref_put(). */
void inode_release(struct kref *kref)
{
struct inode *inode = container_of(kref, struct inode, i_kref);
TAILQ_REMOVE(&inode->i_sb->s_inodes, inode, i_sb_list);
icache_remove(inode->i_sb, inode->i_ino);
/* Might need to write back or delete the file/inode */
if (inode->i_nlink) {
if (inode->i_state & I_STATE_DIRTY)
inode->i_sb->s_op->write_inode(inode, TRUE);
} else {
inode->i_sb->s_op->delete_inode(inode);
}
/* Either way, we dealloc the in-memory version */
inode->i_sb->s_op->dealloc_inode(inode); /* FS-specific clean-up */
kref_put(&inode->i_sb->s_kref);
/* TODO: clean this up */
assert(inode->i_mapping == &inode->i_pm);
kmem_cache_free(inode_kcache, inode);
/* TODO: (BDEV) */
// kref_put(inode->i_bdev->kref); /* assuming it's a bdev */
}
/* Fills in kstat with the stat information for the inode */
void stat_inode(struct inode *inode, struct kstat *kstat)
{
kstat->st_dev = inode->i_sb->s_dev;
kstat->st_ino = inode->i_ino;
kstat->st_mode = inode->i_mode;
kstat->st_nlink = inode->i_nlink;
kstat->st_uid = inode->i_uid;
kstat->st_gid = inode->i_gid;
kstat->st_rdev = inode->i_rdev;
kstat->st_size = inode->i_size;
kstat->st_blksize = inode->i_blksize;
kstat->st_blocks = inode->i_blocks;
kstat->st_atime = inode->i_atime;
kstat->st_mtime = inode->i_mtime;
kstat->st_ctime = inode->i_ctime;
}
/* Inode Cache management. In general, search on the ino, get a refcnt'd value
* back. Remove does not give you a reference back - it should only be called
* in inode_release(). */
struct inode *icache_get(struct super_block *sb, unsigned int ino)
{
/* This is the same style as in pid2proc, it's the "safely create a strong
* reference from a weak one, so long as other strong ones exist" pattern */
spin_lock(&sb->s_icache_lock);
struct inode *inode = hashtable_search(sb->s_icache, (void*)ino);
if (inode)
if (!kref_get_not_zero(&inode->i_kref, 1))
inode = 0;
spin_unlock(&sb->s_icache_lock);
return inode;
}
void icache_put(struct super_block *sb, struct inode *inode)
{
spin_lock(&sb->s_icache_lock);
/* there's a race in load_ino() that could trigger this */
assert(!hashtable_search(sb->s_icache, (void*)inode->i_ino));
hashtable_insert(sb->s_icache, (void*)inode->i_ino, inode);
spin_unlock(&sb->s_icache_lock);
}
struct inode *icache_remove(struct super_block *sb, unsigned int ino)
{
struct inode *inode;
/* Presumably these hashtable removals could be easier since callers
* actually know who they are (same with the pid2proc hash) */
spin_lock(&sb->s_icache_lock);
inode = hashtable_remove(sb->s_icache, (void*)ino);
spin_unlock(&sb->s_icache_lock);
assert(inode && !kref_refcnt(&inode->i_kref));
return inode;
}
/* File functions */
/* Read count bytes from the file into buf, starting at *offset, which is increased
* accordingly, returning the number of bytes transfered. Most filesystems will
* use this function for their f_op->read. Note, this uses the page cache.
* Want to try out page remapping later on... */
ssize_t generic_file_read(struct file *file, char *buf, size_t count,
off_t *offset)
{
struct page *page;
int error;
off_t page_off;
unsigned long first_idx, last_idx;
size_t copy_amt;
char *buf_end;
/* Consider pushing some error checking higher in the VFS */
if (!count)
return 0;
if (*offset == file->f_dentry->d_inode->i_size)
return 0; /* EOF */
/* Make sure we don't go past the end of the file */
if (*offset + count > file->f_dentry->d_inode->i_size) {
count = file->f_dentry->d_inode->i_size - *offset;
}
page_off = *offset & (PGSIZE - 1);
first_idx = *offset >> PGSHIFT;
last_idx = (*offset + count) >> PGSHIFT;
buf_end = buf + count;
/* For each file page, make sure it's in the page cache, then copy it out.
* TODO: will probably need to consider concurrently truncated files here.*/
for (int i = first_idx; i <= last_idx; i++) {
error = pm_load_page(file->f_mapping, i, &page);
assert(!error); /* TODO: handle ENOMEM and friends */
copy_amt = MIN(PGSIZE - page_off, buf_end - buf);
/* TODO: (UMEM) think about this. if it's a user buffer, we're relying
* on current to detect whose it is (which should work for async calls).
* Also, need to propagate errors properly... Probably should do a
* user_mem_check, then free, and also to make a distinction between
* when the kernel wants a read/write (TODO: KFOP) */
if (current) {
memcpy_to_user(current, buf, page2kva(page) + page_off, copy_amt);
} else {
memcpy(buf, page2kva(page) + page_off, copy_amt);
}
buf += copy_amt;
page_off = 0;
page_decref(page); /* it's still in the cache, we just don't need it */
}
assert(buf == buf_end);
*offset += count;
return count;
}
/* Write count bytes from buf to the file, starting at *offset, which is increased
* accordingly, returning the number of bytes transfered. Most filesystems will
* use this function for their f_op->write. Note, this uses the page cache.
* Changes don't get flushed to disc til there is an fsync, page cache eviction,
* or other means of trying to writeback the pages. */
ssize_t generic_file_write(struct file *file, const char *buf, size_t count,
off_t *offset)
{
struct page *page;
int error;
off_t page_off;
unsigned long first_idx, last_idx;
size_t copy_amt;
const char *buf_end;
/* Consider pushing some error checking higher in the VFS */
if (!count)
return 0;
/* Extend the file. Should put more checks in here, and maybe do this per
* page in the for loop below. */
if (*offset + count > file->f_dentry->d_inode->i_size)
file->f_dentry->d_inode->i_size = *offset + count;
page_off = *offset & (PGSIZE - 1);
first_idx = *offset >> PGSHIFT;
last_idx = (*offset + count) >> PGSHIFT;
buf_end = buf + count;
/* For each file page, make sure it's in the page cache, then write it.*/
for (int i = first_idx; i <= last_idx; i++) {
error = pm_load_page(file->f_mapping, i, &page);
assert(!error); /* TODO: handle ENOMEM and friends */
copy_amt = MIN(PGSIZE - page_off, buf_end - buf);
/* TODO: (UMEM) (KFOP) think about this. if it's a user buffer, we're
* relying on current to detect whose it is (which should work for async
* calls). */
if (current) {
memcpy_from_user(current, page2kva(page) + page_off, buf, copy_amt);
} else {
memcpy(page2kva(page) + page_off, buf, copy_amt);
}
buf += copy_amt;
page_off = 0;
page_decref(page); /* it's still in the cache, we just don't need it */
}
assert(buf == buf_end);
*offset += count;
return count;
}
/* Directories usually use this for their read method, which is the way glibc
* currently expects us to do a readdir (short of doing linux's getdents). Will
* probably need work, based on whatever real programs want. */
ssize_t generic_dir_read(struct file *file, char *u_buf, size_t count,
off_t *offset)
{
struct kdirent dir_r = {0}, *dirent = &dir_r;
int retval = 1;
size_t amt_copied = 0;
char *buf_end = u_buf + count;
if (!S_ISDIR(file->f_dentry->d_inode->i_mode)) {
set_errno(ENOTDIR);
return -1;
}
if (!count)
return 0;
/* start readdir from where it left off: */
dirent->d_off = *offset;
for (; (u_buf < buf_end) && (retval == 1); u_buf += sizeof(struct kdirent)){
/* TODO: UMEM/KFOP (pin the u_buf in the syscall, ditch the local copy,
* get rid of this memcpy and reliance on current, etc). Might be
* tricky with the dirent->d_off and trust issues */
retval = file->f_op->readdir(file, dirent);
if (retval < 0) {
set_errno(-retval);
break;
}
/* Slight info exposure: could be extra crap after the name in the
* dirent (like the name of a deleted file) */
if (current) {
memcpy_to_user(current, u_buf, dirent, sizeof(struct dirent));
} else {
memcpy(u_buf, dirent, sizeof(struct dirent));
}
amt_copied += sizeof(struct dirent);
}
/* Next time read is called, we pick up where we left off */
*offset = dirent->d_off; /* UMEM */
/* important to tell them how much they got. they often keep going til they
* get 0 back (in the case of ls). it's also how much has been read, but it
* isn't how much the f_pos has moved (which is opaque to the VFS). */
return amt_copied;
}
/* Opens the file, using permissions from current for lack of a better option.
* It will attempt to create the file if it does not exist and O_CREAT is
* specified. This will return 0 on failure, and set errno. TODO: There's some
* stuff that we don't do, esp related file truncating/creation. flags are for
* opening, the mode is for creating. The flags related to how to create
* (O_CREAT_FLAGS) are handled in this function, not in create_file().
*
* It's tempting to split this into a do_file_create and a do_file_open, based
* on the O_CREAT flag, but the O_CREAT flag can be ignored if the file exists
* already and O_EXCL isn't specified. We could have open call create if it
* fails, but for now we'll keep it as is. */
struct file *do_file_open(char *path, int flags, int mode)
{
struct file *file = 0;
struct dentry *file_d;
struct inode *parent_i;
struct nameidata nd_r = {0}, *nd = &nd_r;
int error;
/* The file might exist, lets try to just open it right away */
nd->intent = LOOKUP_OPEN;
error = path_lookup(path, LOOKUP_FOLLOW, nd);
if (!error) {
/* Still need to make sure we didn't want to O_EXCL create */
if ((flags & O_CREAT) && (flags & O_EXCL)) {
set_errno(EEXIST);
goto out_path_only;
}
file_d = nd->dentry;
kref_get(&file_d->d_kref, 1);
goto open_the_file;
}
/* So it didn't already exist, release the path from the previous lookup,
* and then we try to create it. */
path_release(nd);
/* get the parent, following links. this means you get the parent of the
* final link (which may not be in 'path' in the first place. */
nd->intent = LOOKUP_CREATE;
error = path_lookup(path, LOOKUP_PARENT | LOOKUP_FOLLOW, nd);
if (error) {
set_errno(-error);
goto out_path_only;
}
/* see if the target is there (shouldn't be), and handle accordingly */
file_d = do_lookup(nd->dentry, nd->last.name);
if (!file_d) {
if (!(flags & O_CREAT)) {
set_errno(ENOENT);
goto out_path_only;
}
/* Create the inode/file. get a fresh dentry too: */
file_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
parent_i = nd->dentry->d_inode;
/* Note that the mode technically should only apply to future opens,
* but we apply it immediately. */
if (create_file(parent_i, file_d, mode)) /* sets errno */
goto out_file_d;
dcache_put(file_d->d_sb, file_d);
} else { /* something already exists */
/* this can happen due to concurrent access, but needs to be thought
* through */
panic("File shouldn't be here!");
if ((flags & O_CREAT) && (flags & O_EXCL)) {
/* wanted to create, not open, bail out */
set_errno(EEXIST);
goto out_file_d;
}
}
open_the_file:
/* now open the file (freshly created or if it already existed). At this
* point, file_d is a refcnt'd dentry, regardless of which branch we took.*/
if (flags & O_TRUNC)
warn("File truncation not supported yet.");
file = dentry_open(file_d, flags); /* sets errno */
/* Note the fall through to the exit paths. File is 0 by default and if
* dentry_open fails. */
out_file_d:
kref_put(&file_d->d_kref);
out_path_only:
path_release(nd);
return file;
}
/* Path is the location of the symlink, sometimes called the "new path", and
* symname is who we link to, sometimes called the "old path". */
int do_symlink(char *path, const char *symname, int mode)
{
struct dentry *sym_d;
struct inode *parent_i;
struct nameidata nd_r = {0}, *nd = &nd_r;
int error;
int retval = -1;
nd->intent = LOOKUP_CREATE;
/* get the parent, but don't follow links */
error = path_lookup(path, LOOKUP_PARENT, nd);
if (error) {
set_errno(-error);
goto out_path_only;
}
/* see if the target is already there, handle accordingly */
sym_d = do_lookup(nd->dentry, nd->last.name);
if (sym_d) {
set_errno(EEXIST);
goto out_sym_d;
}
/* Doesn't already exist, let's try to make it: */
sym_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
if (!sym_d) {
set_errno(ENOMEM);
goto out_path_only;
}
parent_i = nd->dentry->d_inode;
if (create_symlink(parent_i, sym_d, symname, mode))
goto out_sym_d;
dcache_put(sym_d->d_sb, sym_d);
retval = 0; /* Note the fall through to the exit paths */
out_sym_d:
kref_put(&sym_d->d_kref);
out_path_only:
path_release(nd);
return retval;
}
/* Makes a hard link for the file behind old_path to new_path */
int do_link(char *old_path, char *new_path)
{
struct dentry *link_d, *old_d;
struct inode *inode, *parent_dir;
struct nameidata nd_r = {0}, *nd = &nd_r;
int error;
int retval = -1;
nd->intent = LOOKUP_CREATE;
/* get the absolute parent of the new_path */
error = path_lookup(new_path, LOOKUP_PARENT | LOOKUP_FOLLOW, nd);
if (error) {
set_errno(-error);
goto out_path_only;
}
parent_dir = nd->dentry->d_inode;
/* see if the new target is already there, handle accordingly */
link_d = do_lookup(nd->dentry, nd->last.name);
if (link_d) {
set_errno(EEXIST);
goto out_link_d;
}
/* Doesn't already exist, let's try to make it. Still need to stitch it to
* an inode and set its FS-specific stuff after this.*/
link_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
if (!link_d) {
set_errno(ENOMEM);
goto out_path_only;
}
/* Now let's get the old_path target */
old_d = lookup_dentry(old_path, LOOKUP_FOLLOW);
if (!old_d) /* errno set by lookup_dentry */
goto out_link_d;
/* For now, can only link to files */
if (!S_ISREG(old_d->d_inode->i_mode)) {
set_errno(EPERM);
goto out_both_ds;
}
/* Must be on the same FS */
if (old_d->d_sb != link_d->d_sb) {
set_errno(EXDEV);
goto out_both_ds;
}
/* Do whatever FS specific stuff there is first (which is also a chance to
* bail out). */
error = parent_dir->i_op->link(old_d, parent_dir, link_d);
if (error) {
set_errno(-error);
goto out_both_ds;
}
/* Finally stitch it up */
inode = old_d->d_inode;
kref_get(&inode->i_kref, 1);
link_d->d_inode = inode;
inode->i_nlink++;
TAILQ_INSERT_TAIL(&inode->i_dentry, link_d, d_alias); /* weak ref */
dcache_put(link_d->d_sb, link_d);
retval = 0; /* Note the fall through to the exit paths */
out_both_ds:
kref_put(&old_d->d_kref);
out_link_d:
kref_put(&link_d->d_kref);
out_path_only:
path_release(nd);
return retval;
}
/* Unlinks path from the directory tree. Read the Documentation for more info.
*/
int do_unlink(char *path)
{
struct dentry *dentry;
struct inode *parent_dir;
struct nameidata nd_r = {0}, *nd = &nd_r;
int error;
int retval = -1;
/* get the parent of the target, and don't follow a final link */
error = path_lookup(path, LOOKUP_PARENT, nd);
if (error) {
set_errno(-error);
goto out_path_only;
}
parent_dir = nd->dentry->d_inode;
/* make sure the target is there */
dentry = do_lookup(nd->dentry, nd->last.name);
if (!dentry) {
set_errno(ENOENT);
goto out_path_only;
}
/* Make sure the target is not a directory */
if (S_ISDIR(dentry->d_inode->i_mode)) {
set_errno(EISDIR);
goto out_dentry;
}
/* Remove the dentry from its parent */
error = parent_dir->i_op->unlink(parent_dir, dentry);
if (error) {
set_errno(-error);
goto out_dentry;
}
/* Now that our parent doesn't track us, we need to make sure we aren't
* findable via the dentry cache. DYING, so we will be freed in
* dentry_release() */
dentry->d_flags |= DENTRY_DYING;
dcache_remove(dentry->d_sb, dentry);
dentry->d_inode->i_nlink--; /* TODO: race here, esp with a decref */
/* At this point, the dentry is unlinked from the FS, and the inode has one
* less link. When the in-memory objects (dentry, inode) are going to be
* released (after all open files are closed, and maybe after entries are
* evicted from the cache), then nlinks will get checked and the FS-file
* will get removed from the disk */
retval = 0; /* Note the fall through to the exit paths */
out_dentry:
kref_put(&dentry->d_kref);
out_path_only:
path_release(nd);
return retval;
}
/* Checks to see if path can be accessed via mode. Need to actually send the
* mode along somehow, so this doesn't do much now. This is an example of
* decent error propagation from the lower levels via int retvals. */
int do_access(char *path, int mode)
{
struct nameidata nd_r = {0}, *nd = &nd_r;
int retval = 0;
nd->intent = LOOKUP_ACCESS;
retval = path_lookup(path, 0, nd);
path_release(nd);
return retval;
}
int do_chmod(char *path, int mode)
{
struct nameidata nd_r = {0}, *nd = &nd_r;
int retval = 0;
retval = path_lookup(path, 0, nd);
if (!retval) {
#if 0
/* TODO: when we have notions of uid, check for the proc's uid */
if (nd->dentry->d_inode->i_uid != UID_OF_ME)
retval = -EPERM;
else
#endif
nd->dentry->d_inode->i_mode |= mode & S_PMASK;
}
path_release(nd);
return retval;
}
/* Make a directory at path with mode. Returns -1 and sets errno on errors */
int do_mkdir(char *path, int mode)
{
struct dentry *dentry;
struct inode *parent_i;
struct nameidata nd_r = {0}, *nd = &nd_r;
int error;
int retval = -1;
nd->intent = LOOKUP_CREATE;
/* get the parent, but don't follow links */
error = path_lookup(path, LOOKUP_PARENT, nd);
if (error) {
set_errno(-error);
goto out_path_only;
}
/* see if the target is already there, handle accordingly */
dentry = do_lookup(nd->dentry, nd->last.name);
if (dentry) {
set_errno(EEXIST);
goto out_dentry;
}
/* Doesn't already exist, let's try to make it: */
dentry = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
if (!dentry) {
set_errno(ENOMEM);
goto out_path_only;
}
parent_i = nd->dentry->d_inode;
if (create_dir(parent_i, dentry, mode))
goto out_dentry;
dcache_put(dentry->d_sb, dentry);
retval = 0; /* Note the fall through to the exit paths */
out_dentry:
kref_put(&dentry->d_kref);
out_path_only:
path_release(nd);
return retval;
}
int do_rmdir(char *path)
{
struct dentry *dentry;
struct inode *parent_i;
struct nameidata nd_r = {0}, *nd = &nd_r;
int error;
int retval = -1;
/* get the parent, following links (probably want this), and we must get a
* directory. Note, current versions of path_lookup can't handle both
* PARENT and DIRECTORY, at least, it doesn't check that *path is a
* directory. */
error = path_lookup(path, LOOKUP_PARENT | LOOKUP_FOLLOW | LOOKUP_DIRECTORY,
nd);
if (error) {
set_errno(-error);
goto out_path_only;
}
/* make sure the target is already there, handle accordingly */
dentry = do_lookup(nd->dentry, nd->last.name);
if (!dentry) {
set_errno(ENOENT);
goto out_path_only;
}
if (!S_ISDIR(dentry->d_inode->i_mode)) {
set_errno(ENOTDIR);
goto out_dentry;
}
if (dentry->d_mount_point) {
set_errno(EBUSY);
goto out_dentry;
}
/* TODO: make sure we aren't a mount or processes root (EBUSY) */
/* Now for the removal. the FSs will check if they are empty */
parent_i = nd->dentry->d_inode;
error = parent_i->i_op->rmdir(parent_i, dentry);
if (error < 0) {
set_errno(-error);
goto out_dentry;
}
/* Now that our parent doesn't track us, we need to make sure we aren't
* findable via the dentry cache. DYING, so we will be freed in
* dentry_release() */
dentry->d_flags |= DENTRY_DYING;
dcache_remove(dentry->d_sb, dentry);
/* Decref ourselves, so inode_release() knows we are done */
dentry->d_inode->i_nlink--;
TAILQ_REMOVE(&nd->dentry->d_subdirs, dentry, d_subdirs_link);
parent_i->i_nlink--; /* TODO: race on this, esp since its a decref */
/* we still have d_parent and a kref on our parent, which will go away when
* the in-memory dentry object goes away. */
retval = 0; /* Note the fall through to the exit paths */
out_dentry:
kref_put(&dentry->d_kref);
out_path_only:
path_release(nd);
return retval;
}
/* Opens and returns the file specified by dentry */
struct file *dentry_open(struct dentry *dentry, int flags)
{
struct inode *inode;
int desired_mode;
struct file *file = kmem_cache_alloc(file_kcache, 0);
if (!file) {
set_errno(ENOMEM);
return 0;
}
inode = dentry->d_inode;
/* Do the mode first, since we can still error out. f_mode stores how the
* OS file is open, which can be more restrictive than the i_mode */
switch (flags & (O_RDONLY | O_WRONLY | O_RDWR)) {
case O_RDONLY:
desired_mode = S_IRUSR;
break;
case O_WRONLY:
desired_mode = S_IWUSR;
break;
case O_RDWR:
desired_mode = S_IRUSR | S_IWUSR;
break;
default:
goto error_access;
}
if (check_perms(inode, desired_mode))
goto error_access;
file->f_mode = desired_mode;
/* one for the ref passed out, and *none* for the sb TAILQ */
kref_init(&file->f_kref, file_release, 1);
/* Add to the list of all files of this SB */
TAILQ_INSERT_TAIL(&inode->i_sb->s_files, file, f_list);
kref_get(&dentry->d_kref, 1);
file->f_dentry = dentry;
kref_get(&inode->i_sb->s_mount->mnt_kref, 1);
file->f_vfsmnt = inode->i_sb->s_mount; /* saving a ref to the vmnt...*/
file->f_op = inode->i_fop;
/* Don't store open mode or creation flags */
file->f_flags = flags & ~(O_ACCMODE | O_CREAT_FLAGS);
file->f_pos = 0;
file->f_uid = inode->i_uid;
file->f_gid = inode->i_gid;
file->f_error = 0;
// struct event_poll_tailq f_ep_links;
spinlock_init(&file->f_ep_lock);
file->f_fs_info = 0; /* prob overriden by the fs */
file->f_mapping = inode->i_mapping;
file->f_op->open(inode, file);
return file;
error_access:
set_errno(EACCES);
kmem_cache_free(file_kcache, file);
return 0;
}
/* Closes a file, fsync, whatever else is necessary. Called when the kref hits
* 0. Note that the file is not refcounted on the s_files list, nor is the
* f_mapping refcounted (it is pinned by the i_mapping). */
void file_release(struct kref *kref)
{
struct file *file = container_of(kref, struct file, f_kref);
struct super_block *sb = file->f_dentry->d_sb;
spin_lock(&sb->s_lock);
TAILQ_REMOVE(&sb->s_files, file, f_list);
spin_unlock(&sb->s_lock);
/* TODO: fsync (BLK). also, we may want to parallelize the blocking that
* could happen in here (spawn kernel threads)... */
file->f_op->release(file->f_dentry->d_inode, file);
/* Clean up the other refs we hold */
kref_put(&file->f_dentry->d_kref);
kref_put(&file->f_vfsmnt->mnt_kref);
kmem_cache_free(file_kcache, file);
}
/* Process-related File management functions */
/* Given any FD, get the appropriate file, 0 o/w */
struct file *get_file_from_fd(struct files_struct *open_files, int file_desc)
{
struct file *retval = 0;
if (file_desc < 0)
return 0;
spin_lock(&open_files->lock);
if (file_desc < open_files->max_fdset) {
if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, file_desc)) {
/* while max_files and max_fdset might not line up, we should never
* have a valid fdset higher than files */
assert(file_desc < open_files->max_files);
retval = open_files->fd[file_desc].fd_file;
assert(retval);
kref_get(&retval->f_kref, 1);
}
}
spin_unlock(&open_files->lock);
return retval;
}
/* Remove FD from the open files, if it was there, and return f. Currently,
* this decref's f, so the return value is not consumable or even usable. This
* hasn't been thought through yet. */
struct file *put_file_from_fd(struct files_struct *open_files, int file_desc)
{
struct file *file = 0;
if (file_desc < 0)
return 0;
spin_lock(&open_files->lock);
if (file_desc < open_files->max_fdset) {
if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, file_desc)) {
/* while max_files and max_fdset might not line up, we should never
* have a valid fdset higher than files */
assert(file_desc < open_files->max_files);
file = open_files->fd[file_desc].fd_file;
open_files->fd[file_desc].fd_file = 0;
assert(file);
kref_put(&file->f_kref);
CLR_BITMASK_BIT(open_files->open_fds->fds_bits, file_desc);
}
}
spin_unlock(&open_files->lock);
return file;
}
/* Inserts the file in the files_struct, returning the corresponding new file
* descriptor, or an error code. We start looking for open fds from low_fd. */
int insert_file(struct files_struct *open_files, struct file *file, int low_fd)
{
int slot = -1;
if ((low_fd < 0) || (low_fd > NR_FILE_DESC_MAX))
return -EINVAL;
spin_lock(&open_files->lock);
for (int i = low_fd; i < open_files->max_fdset; i++) {
if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, i))
continue;
slot = i;
SET_BITMASK_BIT(open_files->open_fds->fds_bits, slot);
assert(slot < open_files->max_files &&
open_files->fd[slot].fd_file == 0);
kref_get(&file->f_kref, 1);
open_files->fd[slot].fd_file = file;
open_files->fd[slot].fd_flags = 0;
if (slot >= open_files->next_fd)
open_files->next_fd = slot + 1;
break;
}
if (slot == -1) /* should expand the FD array and fd_set */
warn("Ran out of file descriptors, deal with me!");
spin_unlock(&open_files->lock);
return slot;
}
/* Closes all open files. Mostly just a "put" for all files. If cloexec, it
* will only close files that are opened with O_CLOEXEC. */
void close_all_files(struct files_struct *open_files, bool cloexec)
{
struct file *file;
spin_lock(&open_files->lock);
for (int i = 0; i < open_files->max_fdset; i++) {
if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, i)) {
/* while max_files and max_fdset might not line up, we should never
* have a valid fdset higher than files */
assert(i < open_files->max_files);
file = open_files->fd[i].fd_file;
if (cloexec && !(open_files->fd[i].fd_flags & O_CLOEXEC))
continue;
/* Actually close the file */
open_files->fd[i].fd_file = 0;
assert(file);
kref_put(&file->f_kref);
CLR_BITMASK_BIT(open_files->open_fds->fds_bits, i);
}
}
spin_unlock(&open_files->lock);
}
/* Inserts all of the files from src into dst, used by sys_fork(). */
void clone_files(struct files_struct *src, struct files_struct *dst)
{
struct file *file;
spin_lock(&src->lock);
spin_lock(&dst->lock);
for (int i = 0; i < src->max_fdset; i++) {
if (GET_BITMASK_BIT(src->open_fds->fds_bits, i)) {
/* while max_files and max_fdset might not line up, we should never
* have a valid fdset higher than files */
assert(i < src->max_files);
file = src->fd[i].fd_file;
assert(i < dst->max_files && dst->fd[i].fd_file == 0);
SET_BITMASK_BIT(dst->open_fds->fds_bits, i);
dst->fd[i].fd_file = file;
assert(file);
kref_get(&file->f_kref, 1);
if (i >= dst->next_fd)
dst->next_fd = i + 1;
}
}
spin_unlock(&dst->lock);
spin_unlock(&src->lock);
}
/* Change the working directory of the given fs env (one per process, at this
* point). Returns 0 for success, -ERROR for whatever error. */
int do_chdir(struct fs_struct *fs_env, char *path)
{
struct nameidata nd_r = {0}, *nd = &nd_r;
int retval;
retval = path_lookup(path, LOOKUP_DIRECTORY, nd);
if (!retval) {
/* nd->dentry is the place we want our PWD to be */
kref_get(&nd->dentry->d_kref, 1);
kref_put(&fs_env->pwd->d_kref);
fs_env->pwd = nd->dentry;
}
path_release(nd);
return retval;
}
/* Returns a null-terminated string of up to length cwd_l containing the
* absolute path of fs_env, (up to fs_env's root). Be sure to kfree the char*
* "kfree_this" when you are done with it. We do this since it's easier to
* build this string going backwards. Note cwd_l is not a strlen, it's an
* absolute size. */
char *do_getcwd(struct fs_struct *fs_env, char **kfree_this, size_t cwd_l)
{
struct dentry *dentry = fs_env->pwd;
size_t link_len;
char *path_start, *kbuf;
if (cwd_l < 2) {
set_errno(ERANGE);
return 0;
}
kbuf = kmalloc(cwd_l, 0);
if (!kbuf) {
set_errno(ENOMEM);
return 0;
}
*kfree_this = kbuf;
kbuf[cwd_l - 1] = '\0';
kbuf[cwd_l - 2] = '/';
/* for each dentry in the path, all the way back to the root of fs_env, we
* grab the dentry name, push path_start back enough, and write in the name,
* using /'s to terminate. We skip the root, since we don't want it's
* actual name, just "/", which is set before each loop. */
path_start = kbuf + cwd_l - 2; /* the last byte written */
while (dentry != fs_env->root) {
link_len = dentry->d_name.len; /* this does not count the \0 */
if (path_start - (link_len + 2) < kbuf) {
kfree(kbuf);
set_errno(ERANGE);
return 0;
}
path_start -= link_len + 1; /* the 1 is for the \0 */
strncpy(path_start, dentry->d_name.name, link_len);
path_start--;
*path_start = '/';
dentry = dentry->d_parent;
}
return path_start;
}
static void print_dir(struct dentry *dentry, char *buf, int depth)
{
struct dentry *child_d;
struct dirent next = {0};
struct file *dir;
int retval;
if (!S_ISDIR(dentry->d_inode->i_mode)) {
warn("Thought this was only directories!!");
return;
}
/* Print this dentry */
printk("%s%s/ nlink: %d\n", buf, dentry->d_name.name,
dentry->d_inode->i_nlink);
if (dentry->d_mount_point) {
dentry = dentry->d_mounted_fs->mnt_root;
}
if (depth >= 32)
return;
/* Set buffer for our kids */
buf[depth] = '\t';
dir = dentry_open(dentry, 0);
if (!dir)
panic("Filesystem seems inconsistent - unable to open a dir!");
/* Process every child, recursing on directories */
while (1) {
retval = dir->f_op->readdir(dir, &next);
if (retval >= 0) {
/* Skip .., ., and empty entries */
if (!strcmp("..", next.d_name) || !strcmp(".", next.d_name) ||
next.d_ino == 0)
goto loop_next;
/* there is an entry, now get its dentry */
child_d = do_lookup(dentry, next.d_name);
if (!child_d)
panic("Inconsistent FS, dirent doesn't have a dentry!");
/* Recurse for directories, or just print the name for others */
switch (child_d->d_inode->i_mode & __S_IFMT) {
case (__S_IFDIR):
print_dir(child_d, buf, depth + 1);
break;
case (__S_IFREG):
printk("%s%s size(B): %d nlink: %d\n", buf, next.d_name,
child_d->d_inode->i_size, child_d->d_inode->i_nlink);
break;
case (__S_IFLNK):
printk("%s%s -> %s\n", buf, next.d_name,
child_d->d_inode->i_op->readlink(child_d));
break;
case (__S_IFCHR):
printk("%s%s (char device) nlink: %d\n", buf, next.d_name,
child_d->d_inode->i_nlink);
break;
case (__S_IFBLK):
printk("%s%s (block device) nlink: %d\n", buf, next.d_name,
child_d->d_inode->i_nlink);
break;
default:
warn("Look around you! Unknown filetype!");
}
kref_put(&child_d->d_kref);
}
loop_next:
if (retval <= 0)
break;
}
/* Reset buffer to the way it was */
buf[depth] = '\0';
kref_put(&dir->f_kref);
}
/* Debugging */
int ls_dash_r(char *path)
{
struct nameidata nd_r = {0}, *nd = &nd_r;
int error;
char buf[32] = {0};
error = path_lookup(path, LOOKUP_ACCESS | LOOKUP_DIRECTORY, nd);
if (error) {
path_release(nd);
return error;
}
print_dir(nd->dentry, buf, 0);
path_release(nd);
return 0;
}
| 2.21875 | 2 |
2024-11-18T17:55:09.345547+00:00 | 2016-01-27T17:19:21 | 2e3d48c73298d8c67d8b5dfb95f2262cbb04789d | {
"blob_id": "2e3d48c73298d8c67d8b5dfb95f2262cbb04789d",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-27T17:19:21",
"content_id": "7fa63e0bcad8ba6abe5abb492b54b09cec024dee",
"detected_licenses": [
"MIT"
],
"directory_id": "649edc1598dbe9f17462ece9992295cb0832f274",
"extension": "c",
"filename": "task2.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 42600682,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2009,
"license": "MIT",
"license_type": "permissive",
"path": "/2015-2016/B/10/05/task2.c",
"provenance": "stackv2-0005.json.gz:8556",
"repo_name": "elsys/po-homework-2015-1",
"revision_date": "2016-01-27T17:19:21",
"revision_id": "797eb1bf06654c0947f71c2e2fdf9577fe334988",
"snapshot_id": "2963edb8d84a4ecc07a3a926f00e7ea852a1ca5a",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/elsys/po-homework-2015-1/797eb1bf06654c0947f71c2e2fdf9577fe334988/2015-2016/B/10/05/task2.c",
"visit_date": "2021-05-30T18:32:19.479230"
} | stackv2 | #include <stdio.h>
#define CELLS 20
#define MAX_LOOP 1000
void next_generation (int *,int *, int);
void print_gen(int *,int);
int main () {
int Current[CELLS],Next[CELLS];
int main_length,counter,n,main_counter;
char check;
do {
scanf("%d",&main_length);
}while (main_length>=20 || main_length <= 0);
for (counter = 0; counter < main_length; counter++) {
scanf("%d",&n); //Current cell
if (n == 0 || n == 1) {
Current[counter] = n;
} else {
printf("Only 0 or 1 !!!");
return 1;
}//else
}//for
if (Current[0] != 0 && Current[main_length - 1] != 0) {
printf("\nFirst and final cell must be only 0 !!!\n");
return 1;
}
for (counter = 0;counter < main_length; counter++) {
if (Current[counter] == 0) printf(".");
else if(Current[counter] == 1) printf("*");
}
printf("\n");
for(counter = 0;counter < CELLS ;counter++) Next[counter]=0;
for(main_counter = 1;main_counter <= MAX_LOOP; main_counter++) {
next_generation(Current,Next,main_length); //Create new generation function
print_gen(Next,main_length); //Print function
for(counter = 0; counter < main_length ; counter++) {
if(Next [counter] == 1)
check = 'a';
}
if(check != 'a') break;
}//Main for
return 0;
}
void next_generation(int *current, int *next, int length) {
int counter,l;
l = length - 1;
for (counter = 1; counter < l; counter++) {
if (current[counter - 1] != current[counter + 1]) next[counter] = 1;
else if (current[counter - 1] == current[counter + 1]) next[counter] = 0;
}
for (counter = 0;counter < length; counter++) {
current[counter] = next[counter];
}
}
void print_gen(int *pnext ,int p_length) {
int count;
for(count = 0;count < p_length;count++) {
if(pnext[count]==0)
printf(".");
else if(pnext[count]==1)
printf("*");
}
printf("\n");
}
| 3.5625 | 4 |
2024-11-18T17:55:09.493392+00:00 | 2020-09-18T00:14:49 | 070d1900710ab2f46d734f168bb8a8c30971e92a | {
"blob_id": "070d1900710ab2f46d734f168bb8a8c30971e92a",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-18T00:14:49",
"content_id": "febf3e1d73191091ddb8775fcc60ca1eb5143d10",
"detected_licenses": [
"MIT"
],
"directory_id": "0f611eb6e43627ac32fb15f599b3cae4104a339d",
"extension": "c",
"filename": "deque.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 209792424,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1948,
"license": "MIT",
"license_type": "permissive",
"path": "/src/deque.c",
"provenance": "stackv2-0005.json.gz:8684",
"repo_name": "Durfan/ufsj-ia-canibais",
"revision_date": "2020-09-18T00:14:49",
"revision_id": "7a9c24cc62c2e4776274f7825d478108147da81b",
"snapshot_id": "d8611b68d6ce9ed9b797ba5acfbed54ddc491781",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Durfan/ufsj-ia-canibais/7a9c24cc62c2e4776274f7825d478108147da81b/src/deque.c",
"visit_date": "2021-07-15T19:49:41.290093"
} | stackv2 | #include "./includes/main.h"
Deque *dqcreate(void) {
Deque *deque = malloc(sizeof(Deque));
assert(deque);
deque->head = deque->tail = NULL;
deque->size = 0;
return deque;
}
void dqpshHead(Deque *deque, int key) {
Node *node = malloc(sizeof(Node));
assert(node);
node->key = key;
node->next = deque->head;
node->prev = NULL;
if (deque->tail == NULL) {
deque->head = deque->tail = node;
} else {
deque->head->prev = node;
deque->head = node;
}
deque->size++;
}
void dqpshTail(Deque *deque, int key) {
Node *node = malloc(sizeof(Node));
assert(node);
node->key = key;
node->prev = deque->tail;
node->next = NULL;
if (deque->head == NULL) {
deque->head = deque->tail = node;
} else {
deque->tail->next = node;
deque->tail = node;
}
deque->size++;
}
int dqpopHead(Deque *deque) {
int key = deque->head->key;
Node *node = deque->head;
if (deque->head == deque->tail)
deque->head = deque->tail = NULL;
else {}
deque->head = node->next;
deque->size--;
free(node);
return key;
}
int dqpopTail(Deque *deque) {
int key = deque->tail->key;
Node *node = deque->tail;
if (deque->head == deque->tail)
deque->head = deque->tail = NULL;
else {
deque->tail = node->prev;
deque->tail->next = NULL;
}
deque->size--;
free(node);
return key;
}
int dqpekHead(Deque *deque) {
return deque->head ? deque->head->key : -1;
}
int dqpekTail(Deque *deque) {
return deque->tail ? deque->tail->key : -1;
}
void dqprt(Deque *deque) {
if (dqEmpty(deque))
return;
Node *node = deque->head;
printf(" F{%02d}:", deque->size);
while (node != NULL) {
printf(" %02d", node->key);
node = node->next;
}
printf("\n");
}
void dqclr(Deque *deque) {
if (dqEmpty(deque)) {
free(deque);
return;
}
Node *delete;
while (deque->head != NULL) {
delete = deque->head;
deque->head = deque->head->next;
free(delete);
}
free(deque);
}
bool dqEmpty(Deque *deque) {
return deque->head == NULL;
} | 3.140625 | 3 |
2024-11-18T17:55:09.564518+00:00 | 2022-12-13T20:43:38 | e4876056040e73f8d9b8fd09c716309db59004dc | {
"blob_id": "e4876056040e73f8d9b8fd09c716309db59004dc",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-13T20:43:38",
"content_id": "523d7779940e4d202d815ab99ac903ae8d6c5cc9",
"detected_licenses": [
"MIT"
],
"directory_id": "f66bd0290b806ecb34fe4e08a38be04417be4322",
"extension": "c",
"filename": "lib_flash.c",
"fork_events_count": 10,
"gha_created_at": "2018-10-20T20:59:01",
"gha_event_created_at": "2019-08-03T13:53:23",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 153947805,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2664,
"license": "MIT",
"license_type": "permissive",
"path": "/lib_flash.c",
"provenance": "stackv2-0005.json.gz:8812",
"repo_name": "unfrozen/stm8_libs",
"revision_date": "2022-12-13T20:43:38",
"revision_id": "f7c6504d93273f73e07451468125a323e7da13e0",
"snapshot_id": "f6202298daecdfe419de5853dec1b0c559131f65",
"src_encoding": "UTF-8",
"star_events_count": 34,
"url": "https://raw.githubusercontent.com/unfrozen/stm8_libs/f7c6504d93273f73e07451468125a323e7da13e0/lib_flash.c",
"visit_date": "2022-12-25T22:48:23.850704"
} | stackv2 | /*
* File name: lib_flash.c
* Date first: code clipped from lib_log
* Date last: 10/18/2018
*
* Description: Library for Flash memory functions
*
* Author: Richard Hodges
*
* Copyright (C) 2018 Richard Hodges. All rights reserved.
* Permission is hereby granted for any use.
*
******************************************************************************
*/
#include <string.h>
#include "stm8s_header.h"
#include "lib_flash.h"
#ifdef FLASH_BLOCK_ERASE
static char p_flash_erase(char *);
static char r_flash_erase[30];
#endif
#pragma disable_warning 59
/******************************************************************************
*
* Initialize Flash functions
* (Need to execute block erase from RAM)
*/
void flash_init(void)
{
#ifdef FLASH_BLOCK_ERASE
memcpy(r_flash_erase, p_flash_erase, 30);
#endif
}
#ifdef FLASH_BLOCK_ERASE
/******************************************************************************
*
* Erase FLASH block (64 or 128 bytes)
* in: block address
* out: zero = success
*/
char flash_erase(char *ptr)
{
ptr;
__asm
ldw x, (3, sp)
clr a
push cc
sim
call _r_flash_erase
pop cc
__endasm;
}
static char p_flash_erase(char *ptr)
{
ptr;
__asm
bset _FLASH_CR2, #5
bres _FLASH_NCR2, #5
ld (x), a
ld (1, x), a
ld (2, x), a
ld (3, x), a
ldw x, #4000*16/5
00001$:
decw x
jreq 00090$
btjt _FLASH_CR2, #5, 00001$
ret
00090$:
inc a
__endasm;
}
#endif /* FLASH_BLOCK_ERASE */
/******************************************************************************
*
* Unlock FLASH for writing
* out: zero = fail
*/
char flash_unlock(void)
{
__asm
mov _FLASH_PUKR, #0x56
mov _FLASH_PUKR, #0xae
clr a
00001$:
dec a
jreq 00090$
btjf _FLASH_IAPSR, #1, 00001$
00090$:
__endasm;
}
/******************************************************************************
*
* Lock FLASH from writing after write
*/
void flash_lock(void)
{
__asm
bres _FLASH_IAPSR, #1
__endasm;
}
/******************************************************************************
*
* Clear range of Flash memory
* in: block base, size in bytes
* out: zero = success
*/
char flash_clear(char *ptr, int size)
{
char retval;
retval = flash_unlock();
if (!retval)
return 1;
#ifdef FLASH_BLOCK_ERASE
while (((int)ptr & (FLASH_BLOCK - 1)) && size) {
*ptr = 0;
ptr++;
size--;
}
while (size >= FLASH_BLOCK) {
retval |= flash_erase(ptr);
ptr += FLASH_BLOCK;
size -= FLASH_BLOCK;
}
#endif
while (size) {
*ptr = 0;
ptr++;
size--;
}
flash_lock();
return retval;
}
| 2.59375 | 3 |
2024-11-18T17:55:09.628650+00:00 | 2019-11-08T01:23:42 | c38ab3afc4a7a19dad712e7d87d40e1568028c3f | {
"blob_id": "c38ab3afc4a7a19dad712e7d87d40e1568028c3f",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-08T01:23:42",
"content_id": "1f69fbc0641be5f0ef72f65bc271c911101ffcdc",
"detected_licenses": [
"BSL-1.0"
],
"directory_id": "ef33c6f2e330d465ce0c88f62295e446adb8db31",
"extension": "c",
"filename": "machines.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": 3489,
"license": "BSL-1.0",
"license_type": "permissive",
"path": "/src/format/pecoff/machines.c",
"provenance": "stackv2-0005.json.gz:8940",
"repo_name": "patha454/prim-draft",
"revision_date": "2019-11-08T01:23:42",
"revision_id": "049de9262f5ed78f67fafe36194f7834b56a5979",
"snapshot_id": "c6a365e23f5e076335aaacb3a416028e7e73180d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/patha454/prim-draft/049de9262f5ed78f67fafe36194f7834b56a5979/src/format/pecoff/machines.c",
"visit_date": "2022-02-27T10:35:18.072720"
} | stackv2 | /**
* @file machines.c
* @brief Defines names the machines types in the COFF specification.
*
* `machines.c` defines names for the machines recognised by the COFF
* specification, and string representations of their names.
*
* `machines.c` also provides a function to get the name of a machine from its'
* machine ID, and test if a machine ID is recognised.
*
* @author H Paterson.
* @copyright Boost Software License 1.0.
* @date 18/10/2019.
*/
#include "format/pecoff/machines.h"
#include "platform/types.h"
/**
* @struct machine_string
* @brief Associates a machine ID with a string name.
*/
struct machine_string
{
uint16_ne id;
const char* const name;
};
/**
* @var machine_strings
* @brief machine_strings pairs COFF machine IDs with human readable names.
*/
const struct machine_string machine_strings[] =
{
{COFF_MACH_UNKNOWN, "Unknown/Default (COFF)"},
{COFF_MACH_AM33, "Matsushita AM33 (COFF)"},
{COFF_MACH_AMD64, "x86_64 (COFF)"},
{COFF_MACH_ARM, "ARM32 little endian (COFF)"},
{COFF_MACH_ARM64, "ARM64 little endian (COFF)"},
{COFF_MACH_ARMNT, "ARM Thumb-2 little endian (COFF)"},
{COFF_MACH_EBC, "EFI bytecode (COFF)"},
{COFF_MACH_I386, "x86 (COFF)"},
{COFF_MACH_IA64, "IA64 Itanium (COFF)"},
{COFF_MACH_M32R, "Mitshubishi M32R little endian (COFF)"},
{COFF_MACH_MIPS16, "MIPS16 (COFF)"},
{COFF_MACH_MIPSFPU, "MIPS with FPU (COFF)"},
{COFF_MACH_MIPSFPU16, "MIPS 16-bit with FPU (COFF)"},
{COFF_MACH_POWERPC, "PowerPC (COFF)"},
{COFF_MACH_POWERPCFP, "PowerPC with FPU (COFF)"},
{COFF_MACH_MIPSFPU, "MIPS little endian (COFF)"},
{COFF_MACH_RISCV32, "RISC-V 32-bit (COFF)"},
{COFF_MACH_RISCV64, "RISC-V 64-bit (COFF)"},
{COFF_MACH_RISCV128, "RISC-V 128-bit (COFF)"},
{COFF_MACH_SH3, "Hitachi SH3 (COFF)"},
{COFF_MACH_SH3DP, "Hitachi Sh3 DSP (COFF)"},
{COFF_MACH_SH4, "Hitachi SH4 (COFF)"},
{COFF_MACH_SH5, "Hitachi SH5 (COFF)"},
{COFF_MACH_THUMB, "ARM Thumb (COFF)"},
{COFF_MACH_WCEMIPSV2, "MIPS WCE v2 little endian (COFF)"},
};
/**
* @brief Returns the human readable representation of a machine ID.
*
* @param machine_id The COFF machine ID.
* @return A pointer to a human readable machine name.
*/
const char* get_coff_machine_name(uint16_ne machine_id)
{
static const char* const unrecognised_machine = "Unrecognised (COFF)";
unsigned int i;
for (i = 0;
i < sizeof(machine_strings) / sizeof(struct machine_string);
i++)
{
if (machine_strings[i].id == machine_id)
{
return machine_strings[i].name;
}
}
return unrecognised_machine;
}
/**
* @brief Indicates if a machine ID corresponds to a known COFF machine ID.
*
* The PE/COFF specification includes a value for "Unknown" which is used as a
* default and as a "dont' care" value.
*
* @see machines.h for more information.
*
* @param machine_id The COFF machine ID.
* @return 1 if the machine type is recognised; 0 otherwise.
*/
int is_coff_machine_known(uint16_ne machine_id)
{
unsigned int i;
for (i = 0;
i < sizeof(machine_strings) / sizeof(struct machine_string);
i++)
{
if (machine_strings[i].id == machine_id)
{
return 1;
}
}
return 0;
}
| 2.578125 | 3 |
2024-11-18T17:55:09.701809+00:00 | 2019-03-01T05:16:46 | 5a98dfb498dc85e845345bdd89d28b7435055f98 | {
"blob_id": "5a98dfb498dc85e845345bdd89d28b7435055f98",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-01T05:16:46",
"content_id": "560f3b7f4d425cbd99e09d6404c7c3b166fe98d1",
"detected_licenses": [
"MIT"
],
"directory_id": "5a17a3d150c4773318d397a46878d2fd74c0671f",
"extension": "c",
"filename": "deliver.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": 15441,
"license": "MIT",
"license_type": "permissive",
"path": "/nitan/clone/quest/deliver.c",
"provenance": "stackv2-0005.json.gz:9069",
"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/clone/quest/deliver.c",
"visit_date": "2020-04-15T21:16:28.817947"
} | stackv2 | // 玩家任務:deliver.c
#include <ansi.h>
#include <quest.h>
inherit QUEST_OB;
#define QOB my["qob"]
#define NPC1 my["npc1"]
#define NPC2 my["npc2"]
#define QOB_NAME my["qob_name"]
#define QOB_UNIT my["qob_unit"]
#define NPC1_NAME my["npc1_name"]
#define NPC2_NAME my["npc2_name"]
#define QOB_ID my["qob_id"]
#define NPC1_ID my["npc1_id"]
#define NPC2_ID my["npc2_id"]
#define PLACE1 my["place1"]
#define PLACE2 my["place2"]
#define AMOUNT my["amount"]
int npc_accept_object(object me, object who, object ob);
mixed ask_for_qob(object npc2, object qob, string qob_name);
// 任務對象創建
void create()
{
setup();
}
// 啟動一個任務
// 自動生成兩個人物和兩個地點,輸入一種物品進行送貨,
// 找到第一個人接到物品,然後送給第二個人領取獎勵。
void init_quest(string qob_name, int amount)
{
string name;
string place1, place2;
object npc1, npc2;
mapping my;
object qob;
if (objectp(qob = find_object(qob_name)))
{
if( objectp(query_temp("quest_ob", qob)) )
{
// 該物品已經存在並用於其他任務,這個任務不能進行
destruct(this_object());
return;
}
} else
// 生成任務物品
qob = load_object(qob_name);
// 記錄該物品的任務屬性
set_temp("quest_ob", this_object(), qob);
qob->set_amount(amount);
// 生成任務的名字
name = "運送" + filter_color(qob->name());
set_name(name);
// 產生兩個隨機地點
place1 = NPC_D->random_place(({ "西域" }));
place2 = NPC_D->random_place(({ "西域", place1 }));
// 產生兩個隨機人物
npc1 = new(CLASS_D("generate") + "/questnpc");
npc2 = new(CLASS_D("generate") + "/questnpc");
set_temp("quest_ob", this_object(), npc1);
set_temp("quest_ob", this_object(), npc2);
// 記錄這些人物、地點和物品信息
my = query_entire_dbase();
QOB = qob;
QOB_NAME = filter_color(qob->name());
QOB_UNIT=query("base_unit", qob);
NPC1 = npc1;
NPC2 = npc2;
PLACE1 = place1;
PLACE2 = place2;
NPC1_NAME = npc1->name();
NPC2_NAME = npc2->name();
QOB_ID=query("id", qob);
NPC1_ID=query("id", npc1);
NPC2_ID=query("id", npc2);
AMOUNT = amount;
// 物品承載,保證送貨的NPC拿得動足夠的重量
npc2->set_max_encumbrance(1000000);
qob->move(npc2);
// 人物出現
NPC_D->place_npc(npc1, 0, ({ place1 }));
NPC_D->place_npc(npc2, 0, ({ place2 }));
// 設置對話信息
set("inquiry",([
name : "啊?你是送它來的?快給我。",
QOB_NAME : "那些貨物呀,我這裏的生意正急需呢!",
QOB_ID : "那些貨物呀,我這裏的生意正急需呢!",
NPC1_NAME : "那正是本人啊!",
NPC1_ID : "那正是本人啊!",
NPC2_NAME : "是呀,就是他答應派人送來的!",
NPC2_ID : "是呀,就是他答應派人送來的!" ]), npc1);
set("inquiry",([
name : "沒錯,你願意去幫我送這批貨!",
QOB_NAME : (: ask_for_qob, npc2, qob, qob->name() :),
QOB_ID : (: ask_for_qob, npc2, qob, qob->name() :),
NPC1_NAME : "這批貨就是要送給他的呀!",
NPC1_ID : "這批貨就是要送給他的呀!",
NPC2_NAME : "正是在下,有何貴幹?",
NPC2_ID : "正是在下,有何貴幹?" ]), npc2);
// 設置接收物品的信息:由於NPC存在的時候該任務對象必
// 定會存在(因為任務析構的時候會清除NPC),所以可以
// 讓NPC引用本地的"npc_accept_object"函數。
set_temp("override/accept_object", (:npc_accept_object:), npc1);
// 切換到正常狀態
change_status(QUEST_READY);
// 設置任務最長存活時間:30分鐘
set("live_time", 1200);
// 登記謠言消息
register_information();
}
// 任務終止
void cancel_quest()
{
mapping my = query_entire_dbase();
object env;
if (! mapp(my))
return;
if (objectp(NPC1))
destruct(NPC1);
if (objectp(NPC2))
destruct(NPC2);
if (objectp(QOB))
destruct(QOB);
// 任務消亡
::cancel_quest();
}
// user ask npc2 for quest ob
mixed ask_for_qob(object npc2, object qob, string qob_name)
{
object me;
object ob;
me = this_player();
message_vision(CYN "$N" CYN "對$n" CYN "説道:這" + qob_name +
CYN "您就交給我幫您運送吧,咱包您準時送到!\n" NOR,
me, npc2);
tell_object(me, HIC "你讓" + npc2->name() + HIC "將" + qob_name +
HIC "交託給你運送。\n" NOR);
if( query("score", me)<1000 )
{
message_vision(CYN "$N" CYN "眯着眼睛瞥了$n" CYN "一眼,哼"
"了一聲道:這批貨給你?我可不放心。”\n" NOR,
npc2, me);
return 1;
}
if (objectp(qob) && environment(qob) == npc2 && qob->query_amount())
{
if (me->query_encumbrance() + qob->weight() / qob->query_amount() <
me->query_max_encumbrance())
{
message_vision(CYN "$N" CYN "打量了$n" CYN "半天,"
"點點頭道:好吧,這批貨可是非常重要"
"的,你一定要準時送到啊。\n" NOR, npc2, me);
tell_object(me, HIY + npc2->name() + HIY "把一" +
query("base_unit", qob)+qob_name+
HIY "交給了你託運。\n" NOR);
/*
ob = new(base_name(qob));
qob->add_amount(-1);
if (! objectp(ob))
tell_object(me, CYN + npc2->name() + CYN "突"
"然臉色一變,大叫道:我的" + qob_name +
CYN "呢?怎麼不見了?\n" NOR);
ob->move(me, 1);
*/
qob->move(me, 1);
} else
{
message_vision(CYN "$N" CYN "眯着眼睛瞥了$n" CYN "一"
"眼,歎了口氣道:" + RANK_D->query_respect(me) +
CYN ",這批貨你運得了麼?\n" NOR, npc2, me);
}
} else
message_vision(CYN "$N" CYN "微笑着對$n" CYN "説:不用勞煩"
"你了,這批" + qob_name + CYN "已經有人送去"
"了。\n" NOR, npc2, me);
return 1;
}
// 詢問NPC1 - 接收貨物的人
string ask_npc1(object knower, object me)
{
mapping my = query_entire_dbase();
if (! objectp(NPC1))
return CYN "唉,怎麼" HIY + NPC1_NAME + NOR CYN
"好端端的," HIY + QOB_NAME + NOR CYN
"沒拿到,反而丟了命,真是可憐。" NOR;
return CYN "哦,他呀,據説正在" + PLACE1 + ",等人給他送去一批" +
HIY + QOB_NAME + NOR CYN "呢!" NOR;
}
// 詢問NPC2 - 持有物品的人
string ask_npc2(object knower, object me)
{
mapping my = query_entire_dbase();
if (! objectp(NPC2))
return CYN "聽人説" HIY + NPC2_NAME + NOR CYN
"居然被人殺了,也不知道惹了哪門子的禍!" NOR;
if( query("score", me)<500 )
call_out("do_whisper", 1, knower, me);
return CYN "哦,他呀,據説正在" + PLACE2 + ",急着等" +
"人幫他送貨呢!" NOR;
}
// 通知玩家
void do_whisper(object knower, object me)
{
if (! can_talk_with(knower, me))
return;
tell_object(me, WHT + knower->name() + WHT "悄悄的和你"
"説:“可惜你的江湖閲歷太低了,他不會給你運。”\n");
message("vision", knower->name() + "在" + me->name() +
"的耳邊悄悄的説了些什麼。\n", environment(me), ({ me }));
}
// 詢問QOB - 物品的信息
string ask_qob(object knower, object me)
{
mapping my = query_entire_dbase();
if (! objectp(QOB))
return CYN "難不成已經給山賊截去了?居然沒人"
"知道那" HIY + QOB_NAME + NOR CYN "的下落了。" NOR;
return CYN "這" HIY + QOB_NAME + NOR CYN + "呀,"
"不過是很普通的一批貨物而已嘛!" NOR;
}
// 任務介紹
string query_introduce(object knower)
{
mapping my = query_entire_dbase();
return CYN "聽説" HIY + NPC2_NAME + NOR CYN "急需將一批" +
HIY + QOB_NAME + NOR CYN "送到" HIY + NPC1_NAME + NOR
CYN "哪兒,你有沒有興趣?" NOR;
}
// 任務提示
string query_prompt()
{
switch (random(3))
{
case 0:
return CYN "倒是最近聽來往的商人説起『" HIY + name() +
NOR CYN "』的事來。";
case 1:
return "也沒什麼大事,只是聽説過『" HIY + name() +
NOR CYN "』的事罷了。";
default:
return "前兩天還聽人家説起『" HIY + name() +
NOR CYN "』的事呢。";
}
}
int npc_accept_object(object me, object who, object ob)
{
mapping my = query_entire_dbase();
mapping b;
object reward;
int exp;
int pot;
int score;
if (ob->is_character() || ob->is_item_make())
{
message_vision(CYN "$N" CYN "瞪着$n" CYN ",使勁的搖着頭"
"道:我要這幹什麼?\n" NOR, me, who);
return 0;
}
if( query("id", ob) != QOB_ID )
{
message_vision(CYN "$N" CYN "瞪着$n" CYN ",使勁的搖着頭"
"道:我要這幹什麼?\n" NOR, me, who);
return 0;
}
if (me->is_fighting())
return 0;
AMOUNT -= ob->query_amount();
message_vision(CYN "$N" CYN "看了看" + ob->name() + CYN ",對$n"
CYN "道:還不錯,辛苦你了。這點銀子你收下吧。\n" NOR,
me, who);
reward = new("/clone/money/silver");
reward->set_amount(ob->query_amount() / 1 + random(3));
reward->move(who, 1);
remove_call_out("do_notice");
if (AMOUNT < 1)
{
// 所有的物品全部接收完了,準備結束任務
message_vision(CYN "$N" CYN "抹了抹頭上的汗,道:總算"
"全運到了,這事可真夠羅嗦的。\n" NOR, me);
/*
CHANNEL_D->do_channel(find_object(QUEST_D), "rumor",
"聽説" + who->name(1) + "(" +
query("id", who)+")替"+
me->name() + HIM "安全送到了" +
"一批" + ob->name() + HIM "。" NOR);
*/
// 被列為門派中斷的自由任務
if( query("quest/freequest", who)>0 )
GIFT_D->delay_freequest_bonus(who);
call_out("do_finish", 4);
change_status("stopping");
} else
call_out("do_notice", 1 + random(3), me, who, ob);
// 獎勵
exp = 50 + random(50);
exp *= ob->query_amount();
pot = 20 + random(20);
pot *= ob->query_amount();
score = 4 + random(4);
score *= ob->query_amount();
if( query("combat_exp", who)>200000 )
{
// 經驗太高,削弱獎勵
exp = exp / 2 + 1;
pot = pot / 2 + 1;
score = score / 2 + 1;
if( query("combat_exp", who)>400000 )
{
// 再次削弱獎勵
exp = exp / 2 + 1;
pot = pot / 2 + 1;
score = score / 2 + 1;
}
}
if( mapp(b=query("bonus/"+query("id", who))) )
{
// 正在獎勵該人中
b["exp"] += exp;
b["pot"] += pot;
b["score"] += score;
} else
{
b = ([ "exp" : exp,
"pot" : pot,
"score" : score,
"prompt": "經過這次幫助" + me->name() +
"運送" + ob->name() + "的事情" ]);
set("bonus/"+query("id", who),b);
call_out("do_bonus",1+random(2),query("id", who),who);
}
destruct(ob);
return -1;
}
protected void do_notice(object me, object who, object ob)
{
mapping my = query_entire_dbase();
if (! can_talk_with(me, who))
return;
message_vision(CYN "$N" CYN "點了點貨,又對$n" CYN "道:我還需"
"要" + chinese_number(AMOUNT) + QOB_UNIT + QOB_NAME +
CYN "才夠。\n" NOR, me, who);
}
// 準備完成任務
protected void do_finish()
{
if (sizeof(query("bonus")) > 0)
{
call_out("do_finish", 4);
return;
}
// 該任務已經完成
cancel_quest();
}
// 給某人獎勵
protected void do_bonus(string who_id, object who)
{
mapping b;
b = query("bonus/" + who_id);
delete("bonus/" + who_id);
if (! mapp(b) || ! objectp(who) || ! living(who))
return;
GIFT_D->bonus(who, b);
}
// 這個消息能夠被散佈嗎?
int can_rumor_by(object knower)
{
// 20%的機率被散佈
return (random(10) < 2);
}
// 登記該任務的消息
void register_information()
{
mapping my = query_entire_dbase();
if (! clonep() || ! mapp(my))
// 不是任務,所以不登記
return;
set_information(NPC1_NAME, (: ask_npc1 :));
set_information(NPC2_NAME, (: ask_npc2 :));
set_information(QOB_NAME, (: ask_qob :));
set_information(NPC1_ID, (: ask_npc1 :));
set_information(NPC2_ID, (: ask_npc2 :));
set_information(QOB_ID, (: ask_qob :));
}
| 2.265625 | 2 |
2024-11-18T17:55:09.847636+00:00 | 2023-08-29T08:33:01 | 0ef8e2353da39b037eeb520cebd769b6ea157d14 | {
"blob_id": "0ef8e2353da39b037eeb520cebd769b6ea157d14",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-29T08:33:01",
"content_id": "a761b5af884de27a66909ecbb838c2be1e308919",
"detected_licenses": [
"MIT"
],
"directory_id": "ed7189bcb31973648dca4cb9f0d67cb4653d0e70",
"extension": "c",
"filename": "conj.c",
"fork_events_count": 173,
"gha_created_at": "2016-07-14T16:46:51",
"gha_event_created_at": "2023-09-10T10:55:53",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 63353495,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1086,
"license": "MIT",
"license_type": "permissive",
"path": "/options/ansi/generic/complex/conj.c",
"provenance": "stackv2-0005.json.gz:9325",
"repo_name": "managarm/mlibc",
"revision_date": "2023-08-29T08:33:01",
"revision_id": "74efefb5e9e546adab60a5730d95165334d7ee15",
"snapshot_id": "6dedaa86ed74f26a52e300d97f6e5949bac0f93c",
"src_encoding": "UTF-8",
"star_events_count": 717,
"url": "https://raw.githubusercontent.com/managarm/mlibc/74efefb5e9e546adab60a5730d95165334d7ee15/options/ansi/generic/complex/conj.c",
"visit_date": "2023-09-01T05:17:26.709378"
} | stackv2 | /* $NetBSD: conj.c,v 1.2 2010/09/15 16:11:29 christos Exp $ */
/*
* Written by Matthias Drochner <[email protected]>.
* Public domain.
*
* imported and modified include for newlib 2010/10/03
* Marco Atzeri <[email protected]>
*/
/*
FUNCTION
<<conj>>, <<conjf>>---complex conjugate
INDEX
conj
INDEX
conjf
ANSI_SYNOPSIS
#include <complex.h>
double complex conj(double complex <[z]>);
float complex conjf(float complex <[z]>);
DESCRIPTION
These functions compute the complex conjugate of <[z]>,
by reversing the sign of its imaginary part.
<<conjf>> is identical to <<conj>>, except that it performs
its calculations on <<floats complex>>.
RETURNS
The conj functions return the complex conjugate value.
PORTABILITY
<<conj>> and <<conjf>> are ISO C99
QUICKREF
<<conj>> and <<conjf>> are ISO C99
*/
#include <complex.h>
#include "fdlibm.h"
double complex
conj(double complex z)
{
double_complex w = { .z = z };
IMAG_PART(w) = -IMAG_PART(w);
return (w.z);
}
| 2.234375 | 2 |
2024-11-18T17:55:10.992028+00:00 | 2016-06-11T05:57:22 | 304cb4a8139d8221f132d72c64f93d14ae43a0dd | {
"blob_id": "304cb4a8139d8221f132d72c64f93d14ae43a0dd",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-11T05:57:22",
"content_id": "6c51760b49f17852a7594d07ce589de5ee188246",
"detected_licenses": [
"MIT"
],
"directory_id": "abdf361d4fdb85b9dac065fbbd70366ad6d52c0d",
"extension": "c",
"filename": "library-fine.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44295612,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1137,
"license": "MIT",
"license_type": "permissive",
"path": "/algorithms/warmup/library-fine/library-fine.c",
"provenance": "stackv2-0005.json.gz:9581",
"repo_name": "cohadar/hackerrank",
"revision_date": "2016-06-11T05:57:22",
"revision_id": "67facc966b299b53a3dcfe594bf97b454df7703a",
"snapshot_id": "27e985ec40f22f841ba94d418769552df0cc66f7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cohadar/hackerrank/67facc966b299b53a3dcfe594bf97b454df7703a/algorithms/warmup/library-fine/library-fine.c",
"visit_date": "2021-01-15T15:25:51.258647"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
int solve(time_t actual, time_t expected)
{
struct tm a = *gmtime(&actual);
struct tm e = *gmtime(&expected);
if (difftime(actual, expected) <= 0.0) {
return 0;
}
if (a.tm_year == e.tm_year) {
if (a.tm_mon == e.tm_mon) {
return (a.tm_mday - e.tm_mday) * 15;
} else {
return (a.tm_mon - e.tm_mon) * 500;
}
}
return 10000;
}
time_t load_date(FILE *in)
{
int D, M, Y;
fscanf(in, "%d %d %d\n", &D, &M, &Y);
assert(1 <= D && D <= 31);
assert(1 <= M && M <= 12);
assert(1 <= Y && Y <= 3000);
struct tm *temp = calloc(1, sizeof(*temp));
temp->tm_mday = D;
temp->tm_mon = M - 1;
temp->tm_year = Y - 1900; // lol at C
time_t ret = mktime(temp);
free(temp);
return ret;
}
void load(FILE *in)
{
time_t actual = load_date(in);
time_t expected = load_date(in);
printf("%d\n", solve(actual, expected));
}
int main(int argc, char const *argv[])
{
FILE *in;
if (argc == 2 && strcmp(argv[1], "COHADAR") == 0) {
in = fopen("library-fine.in", "r");
assert(in);
} else {
in = stdin;
}
load(in);
return 0;
}
| 2.59375 | 3 |
2024-11-18T17:55:12.377068+00:00 | 2020-12-09T14:18:28 | ef3fc96931c425c72601f63494d11aa4eb344b7d | {
"blob_id": "ef3fc96931c425c72601f63494d11aa4eb344b7d",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-09T14:18:28",
"content_id": "a6c66ba129fc7038b83e1a9bac0ab0aebcd85ec6",
"detected_licenses": [
"MIT"
],
"directory_id": "9f128fe6885188d7c5c95b1cb6c627cdde568d96",
"extension": "c",
"filename": "prime_numbers.c",
"fork_events_count": 0,
"gha_created_at": "2020-12-06T10:46:07",
"gha_event_created_at": "2020-12-09T14:18:29",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 319009239,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4232,
"license": "MIT",
"license_type": "permissive",
"path": "/2019/prime_numbers/prime_numbers.c",
"provenance": "stackv2-0005.json.gz:9966",
"repo_name": "codaishin/sort-algorithms",
"revision_date": "2020-12-09T14:18:28",
"revision_id": "902aed79a76c50765fad821839fc2aebdc3947dc",
"snapshot_id": "81d45e2734cb8e661b5327a2f7e93a3b1c2ccc37",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/codaishin/sort-algorithms/902aed79a76c50765fad821839fc2aebdc3947dc/2019/prime_numbers/prime_numbers.c",
"visit_date": "2023-01-25T01:19:54.930640"
} | stackv2 | #include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
// #include "tools.h"
// #include "testsuit.h"
// typedef struct timeval time_ptr_t;
// bool is_prime(int value, int* known, size_t size)
// {
// size_t i;
// bool prime = true;
// int divisor = 0;
// if (value < 2 || value == 4) {
// prime = false;
// } else if (value != 2) {
// for (i = 0; i < size && prime && divisor < value / 2; ++i) {
// divisor = known[i];
// if (value % divisor == 0) {
// prime = false;
// }
// }
// }
// return prime;
// }
// void primes(int *buff, int first, int last, int** primes, size_t *primes_count)
// {
// int value;
// size_t offset = 0;
// *primes_count = 0;
// for (value = 0; value <= last; ++value) {
// if (value == 2 || is_prime(value, buff, *primes_count)) {
// buff[(*primes_count)++] = value;
// if (value < first) {
// ++offset;
// }
// }
// }
// *primes = buff + offset;
// *primes_count -= offset;
// }
// void primes_forward(int *buff, int first, int last,
// int** primes, size_t *primes_count)
// {
// bool *numbers = malloc((last + 1) * sizeof(bool));
// size_t i, j, offset;
// int value;
// offset = 0;
// *primes_count = 0;
// memset(numbers, true, last + 1);
// for (i = 2; i <= last; ++i) {
// for(j = 2 * i; j <= last; j+=i) {
// numbers[j] = false;
// }
// }
// for (value = 2; value <= last; ++value) {
// if(numbers[value] == true) {
// buff[(*primes_count)++] = value;
// if (value < first) {
// ++offset;
// }
// }
// }
// *primes = buff + offset;
// *primes_count -= offset;
// free(numbers);
// }
// int* allign_primes(int *array, size_t time_start)
// {
// size_t allignment;
// for (allignment = 0; array[allignment] < time_start; ++allignment);
// return array + allignment;
// }
// double timediff(time_ptr_t* start, time_ptr_t* stop) {
// return (double)(stop->tv_usec - start->tv_usec) / 1000000 +
// (double)(stop->tv_sec - start->tv_sec);
// }
// int main()
// {
// size_t first = 0;
// size_t last = 99;
// size_t max_count = last + 1;
// size_t result_count;
// time_ptr_t time_start[1];
// time_ptr_t time_stop[1];
// int *result_buff;
// int *buff = malloc(max_count * sizeof(int));
// int expected[] = {
// 2, 3, 5, 7, 11, 13, 17,
// 19, 23, 29, 31, 37, 41,
// 43, 47, 53, 59, 61, 67,
// 71, 73, 79, 83, 89, 97
// };
// gettimeofday(time_start, NULL);
// // primes(buff, first, last, &result_buff, &result_count);
// primes_forward(buff, first, last, &result_buff, &result_count);
// gettimeofday(time_stop, NULL);
// if (max_count <= 100) {
// ASSERT_COLLECTION_EQUAL(
// allign_primes(expected, first), result_count,
// result_buff, result_count
// );
// }
// ARRAY_PRINT(result_buff, result_count, "\n");
// printf("Time to collect prime numbers: %f seconds\n", timediff(time_start, time_stop));
// free(buff);
// return 0;
// }
int is_prime(int value)
{
for (int i = 2; i <= value / 2; ++i) {
if (value % i == 0) {
return 0;
}
}
return 1;
}
int prime(int *array, size_t size, int min, int max)
{
int counter = 0;
int i;
if (min < 2) {
i = 2;
} else {
i = min;
}
for (; i <= max; ++i) {
if (is_prime(i)) {
array[counter] = i;
++counter;
}
}
return counter;
}
int main()
{
int min = 0;
int max = 10000;
size_t size = max - min + 1;
size_t counter = 0;
int array[size];
double time;
time = clock();
counter = prime(array, size, min, max);
time = (clock() - time) / CLOCKS_PER_SEC;
for (size_t i = 0; i < counter; ++i) {
printf("%i ", array[i]);
}
printf("\n");
printf("elapsed: %f sec\n", time);
}
| 2.625 | 3 |
2024-11-18T17:55:12.878969+00:00 | 2017-05-09T11:38:16 | 70121bb25b027181cad63f6048080ba3f5f44586 | {
"blob_id": "70121bb25b027181cad63f6048080ba3f5f44586",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-09T11:38:16",
"content_id": "494ac1e55ccbbc3aeb4f87fa0ccd60ebc593c60a",
"detected_licenses": [
"MIT"
],
"directory_id": "ea9b639c01882f52e1448c7fe8bd6a42c1d82073",
"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": 86951614,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10561,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0005.json.gz:10350",
"repo_name": "soutokevin/calculadora",
"revision_date": "2017-05-09T11:38:16",
"revision_id": "35cbe9f5275a51b099842c7590ab36ecc3d0714f",
"snapshot_id": "b26232ad3f448c5d56c9814d481ca9bb802d5ebb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/soutokevin/calculadora/35cbe9f5275a51b099842c7590ab36ecc3d0714f/main.c",
"visit_date": "2021-01-18T20:16:37.357656"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
typedef enum type {
Number,
Add,
Subtract,
Multiply,
Divide,
OpenParen,
CloseParen
} type_t;
// O(1)
char* type_name(type_t type) {
switch (type) {
case Number:
return "Number";
case Add:
return "Add";
case Subtract:
return "Subtract";
case Multiply:
return "Multiply";
case Divide:
return "Divide";
case OpenParen:
return "OpenParen";
case CloseParen:
return "CloseParen";
default:
return "Invalid";
}
}
// O(1)
int op_priority(type_t type) {
switch (type) {
case Add:
case Subtract:
return 1;
case Multiply:
case Divide:
return 2;
default:
return -1;
}
}
// O(1)
bool is_op(type_t type) {
return (
type == Add ||
type == Subtract ||
type == Multiply ||
type == Divide
);
}
// ---------------------------------------------------------------------------------------------- //
// Definição do nó da lista ligada //
// ---------------------------------------------------------------------------------------------- //
typedef struct node {
type_t type;
double data;
struct node *next;
} node_t;
// O(1)
node_t* new_node(type_t type, double data, node_t* next) {
node_t *node = (node_t*)malloc(sizeof(node_t));
node -> type = type;
node -> data = data;
node -> next = next;
return node;
}
// O(n)
void print_node(node_t* node) {
if (node -> type == Number) {
printf("%5.5f\n", node -> data);
} else {
printf("%s\n", type_name(node -> type));
}
}
// Fim do nó ------------------------------------------------------------------------------------ //
// ---------------------------------------------------------------------------------------------- //
// Definição da lista ligada //
// ---------------------------------------------------------------------------------------------- //
typedef struct list {
node_t *start, *end;
} list_t;
// O(1)
list_t* new_list() {
list_t *list = (list_t *)malloc(sizeof(list_t));
list -> start = NULL;
list -> end = NULL;
return list;
}
// O(n)
void drop_list(list_t *list) {
node_t *current = list -> start;
while (current) {
node_t *next = current -> next;
free(current);
current = next;
}
free(list);
}
// O(n)
void print_list(list_t *list) {
node_t *current = list -> start;
while (current) {
print_node(current);
current = current -> next;
}
}
// O(1)
bool is_empty_list(list_t *list) {
return list -> start == NULL;
}
// O(1)
void push_start(list_t *list, type_t type, double val) {
node_t *new_start = new_node(type, val, list -> start);
list -> start = new_start;
if (list -> end == NULL) {
list -> end = new_start;
}
}
// O(1)
void push_end(list_t * list, type_t type, double val) {
node_t * new_end = new_node(type, val, NULL);
if (list -> start == NULL){
list -> start = new_end;
} else {
list -> end -> next = new_end;
}
list -> end = new_end;
}
// O(1)
node_t* pop_start(list_t * list) {
if (is_empty_list(list)) {
return NULL;
}
node_t *removed = list -> start;
list -> start = list -> start -> next;
if (list -> start == NULL) {
list -> end = NULL;
}
return removed;
}
// Fim da Lista --------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------------- //
// Definição da Pilha //
// ---------------------------------------------------------------------------------------------- //
typedef struct stack {
list_t *list;
} stack_t;
// O(1)
stack_t* new_stack() {
stack_t *stack = (stack_t*)malloc(sizeof(stack_t));
stack -> list = new_list();
return stack;
}
// O(1)
void add_stack(stack_t *stack, type_t type, double val) {
push_start(stack -> list, type, val);
}
// O(1)
node_t* remove_stack(stack_t *stack) {
return pop_start(stack -> list);
}
// O(1)
type_t peek(stack_t *stack) {
return stack -> list -> start -> type;
}
// O(1)
type_t remove_stack_type(stack_t *stack) {
node_t *removed = remove_stack(stack);
type_t t = removed -> type;
free(removed);
return t;
}
// O(1)
double remove_stack_data(stack_t *stack) {
node_t *removed = remove_stack(stack);
double data = removed -> data;
free(removed);
return data;
}
// O(n)
void drop_stack(stack_t *stack) {
drop_list(stack -> list);
free(stack);
}
// O(1)
int is_stack_empty(stack_t *stack) {
return is_empty_list(stack -> list);
}
// Fim da pilha --------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------------- //
// Definição do fila //
// ---------------------------------------------------------------------------------------------- //
typedef struct queue {
list_t *list;
} queue_t;
// O(1)
queue_t* new_queue() {
queue_t * queue = (queue_t*)malloc(sizeof(queue_t));
queue -> list = new_list();
return queue;
}
// O(1)
void add_queue(queue_t *queue, type_t type, double val) {
push_end(queue -> list, type, val);
}
// O(1)
node_t* remove_queue(queue_t *queue) {
return pop_start(queue -> list);
}
// O(1)
type_t remove_queue_type(queue_t *queue) {
node_t *node = pop_start(queue -> list);
type_t type = node -> type;
free(node);
return type;
}
// O(1)
double remove_queue_data(queue_t *queue) {
node_t *node = pop_start(queue -> list);
double data = node -> data;
free(node);
return data;
}
// O(n)
void drop_queue(queue_t *queue) {
drop_list(queue -> list);
free(queue);
}
// O(1)
bool is_queue_empty(queue_t *queue) {
return is_empty_list(queue -> list);
}
// Fim da pilha --------------------------------------------------------------------------------- //
// O(n)
bool validate (queue_t *lista) {
stack_t* temp_stack = new_stack();
node_t* current = lista -> list -> start;
type_t type = Add;
while (current) {
if (
(is_op(type) && current -> type != Number && current -> type != OpenParen) ||
(type == OpenParen && current -> type != Number) ||
(type == CloseParen && !is_op(current -> type)) ||
(type == Number && (!is_op(current -> type) || current -> type == CloseParen))
) {
return false;
}
type = current -> type;
if (current -> type == OpenParen) {
add_stack(temp_stack, OpenParen, 0);
} else if (current -> type == CloseParen) {
if (is_stack_empty(temp_stack)) {
return false;
} else {
remove_stack(temp_stack);
}
}
current = current -> next;
}
return is_stack_empty(temp_stack);
}
// O(n)
queue_t* lexer(char input[]) {
queue_t *list = new_queue();
for (int i = 0; input[i]; i++) {
char c = input[i];
if (c >= '0' && c <= '9') {
double num = atoll(&input[i]);
add_queue(list, Number, num);
while ((input[i+1] >= '0' && input[i+1] <= '9')) i++;
} else if (c == '+') {
add_queue(list, Add, 0);
} else if (c == '-') {
add_queue(list, Subtract, 0);
} else if (c == '*') {
add_queue(list, Multiply, 0);
} else if (c == '/') {
add_queue(list, Divide, 0);
} else if (c == '(') {
add_queue(list, OpenParen, 0);
} else if (c == ')') {
add_queue(list, CloseParen, 0);
} else if (c == ' ') {
// no-op
} else {
drop_queue(list);
return NULL;
}
}
return list;
}
// O(n²)
queue_t* infix2postfix(queue_t *infix) {
stack_t *operadores = new_stack();
queue_t *postfix = new_queue();
node_t *current = remove_queue(infix);
while (current) {
switch (current -> type) {
case Number:
add_queue(postfix, current -> type, current -> data);
break;
case Add:
case Subtract:
case Divide:
case Multiply: {
while (
!is_stack_empty(operadores) &&
op_priority(peek(operadores)) >= op_priority(current -> type)
) {
type_t op = remove_stack_type(operadores);
add_queue(postfix, op, 0);
}
}
case OpenParen:
add_stack(operadores, current -> type, 0);
break;
case CloseParen: {
type_t op = remove_stack_type(operadores);
while (op != OpenParen) {
add_queue(postfix, op, 0);
op = remove_stack_type(operadores);
}
}
}
free(current);
current = remove_queue(infix);
}
while (!is_stack_empty(operadores)) {
type_t type = remove_stack_type(operadores);
add_queue(postfix, type, 0);
}
drop_stack(operadores);
return postfix;
}
// O(n)
double execute(list_t *expr) {
stack_t *values = new_stack();
node_t *current = expr -> start;
while (current) {
double result;
if (current -> type == Number) {
result = current -> data;
} else {
double n1 = remove_stack_data(values);
double n2 = remove_stack_data(values);
switch (current -> type) {
case Divide: result = n2 / n1; break;
case Multiply: result = n2 * n1; break;
case Add: result = n2 + n1; break;
case Subtract: result = n2 - n1; break;
default: exit(3);
}
}
add_stack(values, Number, result);
current = current -> next;
}
double result = remove_stack_data(values);
drop_stack(values);
return result;
}
// O(n)
int calculadora() {
char input[100];
printf("Digite uma expressão: ");
scanf("%[^\n]s", input);
getchar();
queue_t *infixa = lexer(input);
if (!infixa) {
fprintf(stderr, "Erro ao analizar a expresão.\n");
return 1;
}
if (!validate(infixa)) {
fprintf(stderr, "Expressão Invalida.\n");
return 3;
}
queue_t *posfixa = infix2postfix(infixa);
if (!posfixa) {
fprintf(stderr, "Erro na conversão de infixa p/ posfixa.\n");
return 2;
}
printf("Resultado: %.2f\n", execute(posfixa -> list));
drop_queue(infixa);
drop_queue(posfixa);
return 0;
}
int main(const int argc, char* argv[]) {
bool shell = argc == 2 && (strcmp(argv[1], "-s") == 0 || strcmp(argv[1], "--shell") == 0);
if (shell) while(1) calculadora();
return calculadora();
}
| 3.203125 | 3 |
2024-11-18T17:55:13.054525+00:00 | 2015-07-24T04:02:49 | 88b128519641d90ac2fda7d252cad4f35fe8758f | {
"blob_id": "88b128519641d90ac2fda7d252cad4f35fe8758f",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-24T04:02:49",
"content_id": "71bb46596b84de827ae69d4f209f7566661e2c90",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "b7bedb7c323d0ebd4c70d662cf85829cdcc21132",
"extension": "c",
"filename": "talloc.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 39360806,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2509,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/test/talloc.c",
"provenance": "stackv2-0005.json.gz:10606",
"repo_name": "aadityakalsi/msrv",
"revision_date": "2015-07-24T04:02:49",
"revision_id": "8fe3f4f4581923c1a228d02edb13e5f442ffadc7",
"snapshot_id": "1723a996d22004eb088343bfd6cc6a9895939a87",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aadityakalsi/msrv/8fe3f4f4581923c1a228d02edb13e5f442ffadc7/test/talloc.c",
"visit_date": "2016-09-05T20:22:35.334598"
} | stackv2 | /**
* \file talloc.c
* \date 2015
*/
#if defined(_WIN32)
# define _CRT_SECURE_NO_WARNINGS
# define CHDIR _chdir
#include <direct.h>
#else
# define _XOPEN_SOURCE 600
# define CHDIR chdir
#include <unistd.h>
#endif/*defined(_WIN32)*/
#include "unittest.h"
/* STDLIB includes
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* TEST includes
*/
#include <msrv/msrv_alloc.h>
#if !defined(NDEBUG)
int exists(const char* n)
{
FILE* f = fopen(n, "rb");
if (f) { fclose(f); }
return f != NULL;
}
static char FIND_EXE_BUFF[500];
void put_name(const char* pre, const char* name)
{
strcpy((char*)FIND_EXE_BUFF, "");
strcat((char*)FIND_EXE_BUFF, pre);
strcat((char*)FIND_EXE_BUFF, name);
#if defined(_WIN32)
strcat((char*)FIND_EXE_BUFF, ".exe");
#endif/*defined(_WIN32)*/
}
const char* find_exe(const char* str)
{
#if defined(_WIN32)
put_name("", str);
if (exists(FIND_EXE_BUFF)) { return FIND_EXE_BUFF; }
#else/*UNIX*/
put_name("./", str);
if (exists(FIND_EXE_BUFF)) { return FIND_EXE_BUFF; }
#endif/*defined(_WIN32)*/
put_name("../", str);
if (exists(FIND_EXE_BUFF)) { return FIND_EXE_BUFF; }
put_name("../../", str);
if (exists(FIND_EXE_BUFF)) { return FIND_EXE_BUFF; }
return NULL;
}
void get_exe_dir(char* buf, size_t s)
{
char* start = buf;
strcpy(buf, EXE_NAME);
#if defined(_WIN32)
while (*buf) {
*(buf++) = (*buf == '\\') ? '/' : *buf;
}
#endif/*defined(_WIN32)*/
{
char* lst = strrchr(start, '/');
*lst = '\0';
}
}
TEST_FUNC( hleak )
{
char curdir[1024];
get_exe_dir(curdir, 1024);
CHDIR( curdir );
const char* path = find_exe("hleak");
TEST_TRUE( path );
char cmd[1024];
strcpy(cmd, "");
strcat(cmd, path);
strcat(cmd, " > hleak.out");
system(cmd);
{
FILE* f = fopen("hleak.out", "rb");
TEST_FALSE( fgetc(f) == EOF );
fclose(f);
}
}
#endif/*defined(NDEBUG)*/
TEST_FUNC( alloc_free )
{
void* p = msrv_alloc(50);
TEST_TRUE( p );
msrv_free(p);
}
TEST_FUNC( calloc_free )
{
void* p = msrv_calloc(50);
{/* test calloc */
char* mem = p;
int i = 0;
for (; i != 50; ++i) {
TEST_TRUE( mem[i] == 0 );
}
}
TEST_TRUE( p );
msrv_free(p);
}
void SetupTests(void)
{
/* Correctness tests */
REG_TEST( alloc_free );
REG_TEST( calloc_free );
#if !defined(NDEBUG)
REG_TEST( hleak );
#endif/*defined(NDEBUG)*/
}
| 2.59375 | 3 |
2024-11-18T17:55:14.730304+00:00 | 2023-08-29T03:30:48 | baff63cc33aa6dc66c2ca44fbbd8cf53f646855e | {
"blob_id": "baff63cc33aa6dc66c2ca44fbbd8cf53f646855e",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-29T03:30:48",
"content_id": "7aeaa18198b4d5000032a705627870e3609665ce",
"detected_licenses": [
"MIT"
],
"directory_id": "ad3f34546afba57daf888798ad2d29db0361dcca",
"extension": "h",
"filename": "stdint.h",
"fork_events_count": 62,
"gha_created_at": "2012-12-04T05:29:25",
"gha_event_created_at": "2023-08-08T12:38:00",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 6994906,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4429,
"license": "MIT",
"license_type": "permissive",
"path": "/BacNetDllforVc/MainCpp/stdint.h",
"provenance": "stackv2-0005.json.gz:10990",
"repo_name": "temcocontrols/T3000_Building_Automation_System",
"revision_date": "2023-08-29T03:30:48",
"revision_id": "5fc9204df43aabfe57ccd1a5183b69940d525e2d",
"snapshot_id": "b7303be5d447cd8d40b1d2424b32b6c7683c2570",
"src_encoding": "UTF-8",
"star_events_count": 66,
"url": "https://raw.githubusercontent.com/temcocontrols/T3000_Building_Automation_System/5fc9204df43aabfe57ccd1a5183b69940d525e2d/BacNetDllforVc/MainCpp/stdint.h",
"visit_date": "2023-08-31T13:37:39.375528"
} | stackv2 | /* Defines the standard integer types that are used in code */
/* for the x86 processor and Borland Compiler */
#ifndef _STDINT_H
#define _STDINT_H
#include <stddef.h>
//typedef unsigned char uint8_t; /* 1 byte 0 to 255 */
//typedef signed char int8_t; /* 1 byte -127 to 127 */
//typedef unsigned short uint16_t; /* 2 bytes 0 to 65535 */
//typedef signed short int16_t; /* 2 bytes -32767 to 32767 */
///*typedef unsigned short long uint24_t; // 3 bytes 0 to 16777215 */
//typedef unsigned uint32_t; /* 4 bytes 0 to 4294967295 */
//typedef int int32_t; /* 4 bytes -2147483647 to 2147483647 */
//typedef signed long long int64_t;
//typedef unsigned long long uint64_t;
//
//#define INT8_MIN (-128)
//#define INT16_MIN (-32768)
//#define INT32_MIN (-2147483647 - 1)
//
//#define INT8_MAX 127
//#define INT16_MAX 32767
//#define INT32_MAX 2147483647
//
//#define UINT8_MAX 0xff /* 255U */
//#define UINT16_MAX 0xffff /* 65535U */
//#define UINT32_MAX 0xffffffff /* 4294967295U */
typedef signed char int8_t;
typedef short int16_t;
typedef int int32_t;
typedef long long int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
typedef signed char int_least8_t;
typedef short int_least16_t;
typedef int int_least32_t;
typedef long long int_least64_t;
typedef unsigned char uint_least8_t;
typedef unsigned short uint_least16_t;
typedef unsigned int uint_least32_t;
typedef unsigned long long uint_least64_t;
typedef signed char int_fast8_t;
typedef int int_fast16_t;
typedef int int_fast32_t;
typedef long long int_fast64_t;
typedef unsigned char uint_fast8_t;
typedef unsigned int uint_fast16_t;
typedef unsigned int uint_fast32_t;
typedef unsigned long long uint_fast64_t;
typedef long long intmax_t;
typedef unsigned long long uintmax_t;
// These macros must exactly match those in the Windows SDK's intsafe.h.
#define INT8_MIN (-127i8 - 1)
#define INT16_MIN (-32767i16 - 1)
#define INT32_MIN (-2147483647i32 - 1)
#define INT64_MIN (-9223372036854775807i64 - 1)
#define INT8_MAX 127i8
#define INT16_MAX 32767i16
#define INT32_MAX 2147483647i32
#define INT64_MAX 9223372036854775807i64
#define UINT8_MAX 0xffui8
#define UINT16_MAX 0xffffui16
#define UINT32_MAX 0xffffffffui32
#define UINT64_MAX 0xffffffffffffffffui64
#define INT_LEAST8_MIN INT8_MIN
#define INT_LEAST16_MIN INT16_MIN
#define INT_LEAST32_MIN INT32_MIN
#define INT_LEAST64_MIN INT64_MIN
#define INT_LEAST8_MAX INT8_MAX
#define INT_LEAST16_MAX INT16_MAX
#define INT_LEAST32_MAX INT32_MAX
#define INT_LEAST64_MAX INT64_MAX
#define UINT_LEAST8_MAX UINT8_MAX
#define UINT_LEAST16_MAX UINT16_MAX
#define UINT_LEAST32_MAX UINT32_MAX
#define UINT_LEAST64_MAX UINT64_MAX
#define INT_FAST8_MIN INT8_MIN
#define INT_FAST16_MIN INT32_MIN
#define INT_FAST32_MIN INT32_MIN
#define INT_FAST64_MIN INT64_MIN
#define INT_FAST8_MAX INT8_MAX
#define INT_FAST16_MAX INT32_MAX
#define INT_FAST32_MAX INT32_MAX
#define INT_FAST64_MAX INT64_MAX
#define UINT_FAST8_MAX UINT8_MAX
#define UINT_FAST16_MAX UINT32_MAX
#define UINT_FAST32_MAX UINT32_MAX
#define UINT_FAST64_MAX UINT64_MAX
#ifdef _WIN64
#define INTPTR_MIN INT64_MIN
#define INTPTR_MAX INT64_MAX
#define UINTPTR_MAX UINT64_MAX
#else
#define INTPTR_MIN INT32_MIN
#define INTPTR_MAX INT32_MAX
#define UINTPTR_MAX UINT32_MAX
#endif
#define INTMAX_MIN INT64_MIN
#define INTMAX_MAX INT64_MAX
#define UINTMAX_MAX UINT64_MAX
#define PTRDIFF_MIN INTPTR_MIN
#define PTRDIFF_MAX INTPTR_MAX
#ifndef SIZE_MAX
#define SIZE_MAX UINTPTR_MAX
#endif
#define SIG_ATOMIC_MIN INT32_MIN
#define SIG_ATOMIC_MAX INT32_MAX
#define WCHAR_MIN 0x0000
#define WCHAR_MAX 0xffff
#define WINT_MIN 0x0000
#define WINT_MAX 0xffff
#define INT8_C(x) (x)
#define INT16_C(x) (x)
#define INT32_C(x) (x)
#define INT64_C(x) (x ## LL)
#define UINT8_C(x) (x)
#define UINT16_C(x) (x)
#define UINT32_C(x) (x ## U)
#define UINT64_C(x) (x ## ULL)
#define INTMAX_C(x) INT64_C(x)
#define UINTMAX_C(x) UINT64_C(x)
#endif /* STDINT_H */
| 2.390625 | 2 |
2024-11-18T17:55:14.812318+00:00 | 2023-04-07T20:52:26 | ba331e736841c784e01a1cf6030dfbf5d4823886 | {
"blob_id": "ba331e736841c784e01a1cf6030dfbf5d4823886",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-07T20:52:26",
"content_id": "756eaa171ff126deada568b5399fecb964792eeb",
"detected_licenses": [
"MIT",
"BSD-3-Clause"
],
"directory_id": "c55d33ff376cd6ff07333d6ee0be053f62de9a76",
"extension": "h",
"filename": "myclosesocket.h",
"fork_events_count": 27,
"gha_created_at": "2019-02-02T03:26:35",
"gha_event_created_at": "2023-04-07T20:52:27",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 168789998,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 352,
"license": "MIT,BSD-3-Clause",
"license_type": "permissive",
"path": "/src/net/myclosesocket.h",
"provenance": "stackv2-0005.json.gz:11118",
"repo_name": "DigitalNoteXDN/DigitalNote-2",
"revision_date": "2023-04-07T20:52:26",
"revision_id": "fb73be8032491364892fb90b1c696105034f74e9",
"snapshot_id": "1d306c47ee962f6266be5caa6b03e4f96c3f179c",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/DigitalNoteXDN/DigitalNote-2/fb73be8032491364892fb90b1c696105034f74e9/src/net/myclosesocket.h",
"visit_date": "2023-04-13T18:02:19.719011"
} | stackv2 | #ifndef MYCLOSESOCKET_H
#define MYCLOSESOCKET_H
inline int myclosesocket(SOCKET& hSocket)
{
if (hSocket == INVALID_SOCKET)
{
return WSAENOTSOCK;
}
#ifdef WIN32
int ret = closesocket(hSocket);
#else
int ret = close(hSocket);
#endif
hSocket = INVALID_SOCKET;
return ret;
}
#define closesocket(s) myclosesocket(s)
#endif // MYCLOSESOCKET_H
| 2 | 2 |
2024-11-18T17:55:14.901878+00:00 | 2021-03-01T13:50:49 | 83ab398cc231ec395768e6270674be08a811c0a1 | {
"blob_id": "83ab398cc231ec395768e6270674be08a811c0a1",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-01T13:50:49",
"content_id": "417555562e9bbf8ba64fe26bf75c0db74087d7f9",
"detected_licenses": [
"MIT"
],
"directory_id": "dc9873ef446bb21ebce2168b480639991f68a87c",
"extension": "c",
"filename": "multistring.c",
"fork_events_count": 0,
"gha_created_at": "2021-03-06T07:19:58",
"gha_event_created_at": "2021-03-06T07:29:44",
"gha_language": "Pascal",
"gha_license_id": "MIT",
"github_id": 345031755,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3090,
"license": "MIT",
"license_type": "permissive",
"path": "/km-shared/multistring.c",
"provenance": "stackv2-0005.json.gz:11246",
"repo_name": "ansnapx/IRPMon",
"revision_date": "2021-03-01T13:50:49",
"revision_id": "6a07fa7145cd3fc4ec09d6df179ca02cf76323ce",
"snapshot_id": "ef3024f1a7cd502712685d14d47a55764faa62c9",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ansnapx/IRPMon/6a07fa7145cd3fc4ec09d6df179ca02cf76323ce/km-shared/multistring.c",
"visit_date": "2023-03-08T22:03:21.142214"
} | stackv2 |
#include <ntifs.h>
#include "preprocessor.h"
#include "multistring.h"
/************************************************************************/
/* PUBLIC FUNCTIONS */
/************************************************************************/
size_t _MultiStringSize(const wchar_t *Data)
{
SIZE_T ret = sizeof(wchar_t);
DEBUG_ENTER_FUNCTION("Data=0x%p", Data);
while (*Data != L'\0') {
SIZE_T len = wcslen(Data);
ret += (len + 1) * sizeof(wchar_t);
Data += (len + 1);
}
DEBUG_EXIT_FUNCTION("%Iu", ret);
return ret;
}
BOOLEAN _MultiStringExists(wchar_t *Data, PUNICODE_STRING Name, wchar_t **Position)
{
UNICODE_STRING uData;
BOOLEAN ret = FALSE;
DEBUG_ENTER_FUNCTION("Data=0x%p; Name=\"%wZ\"", Data, Name);
while (!ret && *Data != L'\0') {
RtlInitUnicodeString(&uData, Data);
ret = RtlEqualUnicodeString(&uData, Name, TRUE);
if (ret && Position != NULL)
*Position = Data;
Data += ((uData.Length / sizeof(wchar_t)) + 1);
}
DEBUG_EXIT_FUNCTION("%u", ret);
return ret;
}
BOOLEAN _MultiStringInsert(wchar_t *Data, PUNICODE_STRING Name, BOOLEAN Beginning, size_t *NewLength)
{
SIZE_T dataSize = 0;
BOOLEAN ret = FALSE;
DEBUG_ENTER_FUNCTION("Data=0x%p; Name=\"%wZ\"; Beginning=%u", Data, Name, Beginning);
ret = !_MultiStringExists(Data, Name, NULL);
if (ret) {
dataSize = _MultiStringSize(Data);
if (Beginning) {
memmove(Data + (Name->Length / sizeof(wchar_t)) + 1, Data, dataSize);
memcpy(Data, Name->Buffer, Name->Length);
Data[Name->Length / sizeof(wchar_t)] = L'\0';
}
else memcpy(Data + (dataSize / sizeof(wchar_t)) - 1, Name->Buffer, Name->Length);
dataSize += (Name->Length + sizeof(wchar_t));
*NewLength = dataSize;
}
DEBUG_EXIT_FUNCTION("%u, *NewLength=%Iu", ret, *NewLength);
return ret;
}
BOOLEAN _MultiStringRemove(wchar_t *Data, PUNICODE_STRING Name, size_t *NewSize)
{
SIZE_T len = 0;
SIZE_T dataSize = 0;
wchar_t *pos = NULL;
BOOLEAN ret = FALSE;
DEBUG_ENTER_FUNCTION("Data=0x%p; Name=\"%wZ\"", Data, Name);
ret = _MultiStringExists(Data, Name, &pos);
if (ret) {
dataSize = _MultiStringSize(Data);
len = Name->Length + sizeof(wchar_t);
dataSize -= len;
memmove(pos, pos + len / sizeof(wchar_t), dataSize - (pos - Data) * sizeof(wchar_t));
Data[dataSize / sizeof(wchar_t) - 1] = L'\0';
*NewSize = dataSize;
}
DEBUG_EXIT_FUNCTION("%u, *NewSize=%Iu", ret, *NewSize);
return ret;
}
BOOLEAN _MultiStringFirst(wchar_t *MultiString, wchar_t **Item)
{
BOOLEAN ret = FALSE;
DEBUG_ENTER_FUNCTION("MultiString=0x%p; Item=0x%p", MultiString, Item);
*Item = NULL;
ret = *MultiString != L'\0';
if (ret)
*Item = MultiString;
DEBUG_EXIT_FUNCTION("%u, *Item=\"%S\"", ret, *Item);
return ret;
}
BOOLEAN _MultiStringNext(wchar_t *Item, wchar_t **Next)
{
size_t len = 0;
BOOLEAN ret = FALSE;
DEBUG_ENTER_FUNCTION("Item=0x%p; Next=0x%p", Item, Next);
*Next = NULL;
len = wcslen(Item);
Item += (len + 1);
ret = *Item != L'\0';
if (ret)
*Next = Item;
DEBUG_EXIT_FUNCTION("%u, *Next=\"%S\"", ret, *Next);
return ret;
}
| 2.703125 | 3 |
2024-11-18T17:55:15.024408+00:00 | 2023-08-14T02:15:32 | c7f63c3a9fa1518fdb5c85e875582f097b6eef86 | {
"blob_id": "c7f63c3a9fa1518fdb5c85e875582f097b6eef86",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-14T07:27:35",
"content_id": "518d0cdbec56432bed1d9997098b81637accc4e5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0673edfa62c3ab801fd22d038ebfc000246543ec",
"extension": "c",
"filename": "dlog.c",
"fork_events_count": 6,
"gha_created_at": "2018-01-11T18:32:55",
"gha_event_created_at": "2023-09-14T09:05:54",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 117137706,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1858,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/dlog.c",
"provenance": "stackv2-0005.json.gz:11374",
"repo_name": "dalihub/tizenfx-stub",
"revision_date": "2023-08-14T02:15:32",
"revision_id": "25d9963c6a7d4030217d264bb364d9352086e64b",
"snapshot_id": "ed55e22a67333cd6031addb13a1acdf42b4718b9",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dalihub/tizenfx-stub/25d9963c6a7d4030217d264bb364d9352086e64b/src/dlog.c",
"visit_date": "2023-08-18T12:43:48.795228"
} | stackv2 | /*
* Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include "dlog.h"
#ifdef WIN32
#include "asprintf.h"
#endif
int dlog_print_internal( log_priority prio, const char *tag, const char *fmt, va_list arg )
{
int numChars = 0;
char *message = NULL;
int messageLength = vasprintf(&message, fmt, arg);
if(messageLength > 0)
{
// Append line feed if message is not end with line feed.
char lineFeed[2] = {'\0', '\0'};
if(message[messageLength-1] != '\n')
{
lineFeed[0] = '\n';
}
numChars = fprintf(stderr, "%s:\e[21m %s: %s%s\e[0m", prio==DLOG_DEBUG?"\e[1;37mDEBUG":prio==DLOG_INFO?"\e[1;34mINFO":prio==DLOG_WARN?"\e[1;33mWARN":prio==DLOG_ERROR?"\e[1;91mERROR":"", tag, message, lineFeed);
free(message);
}
return numChars;
}
int dlog_print( log_priority prio, const char *tag, const char *fmt, ... )
{
va_list arg;
va_start(arg, fmt);
int numChars = dlog_print_internal(prio, tag, fmt, arg);
va_end(arg);
return numChars;
}
int dlog_print_dotnet( log_priority prio, const char *tag, const char *fmt, ... )
{
va_list arg;
va_start(arg, fmt);
int numChars = dlog_print_internal(prio, tag, fmt, arg);
va_end(arg);
return numChars;
}
| 2.296875 | 2 |
2024-11-18T17:55:15.379836+00:00 | 2020-06-19T03:59:40 | ada0e340fcf5251ff1da45f518a9a7cdaeedeff1 | {
"blob_id": "ada0e340fcf5251ff1da45f518a9a7cdaeedeff1",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-19T03:59:40",
"content_id": "9b16f34761941cf7d22ef67550d7ac204067997f",
"detected_licenses": [
"MIT"
],
"directory_id": "d4fa997032edb41816a1773bdb4e3c92347b00cb",
"extension": "c",
"filename": "w25qxx.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": 30229,
"license": "MIT",
"license_type": "permissive",
"path": "/Src/w25qxx.c",
"provenance": "stackv2-0005.json.gz:11630",
"repo_name": "weimingtom/SmartBedAli",
"revision_date": "2020-06-19T03:59:40",
"revision_id": "fa0a54cbeb71b1abd83b2b4285cfb0c591f5e482",
"snapshot_id": "b45b134f82bd60bed2539130717caba7ed947d98",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/weimingtom/SmartBedAli/fa0a54cbeb71b1abd83b2b4285cfb0c591f5e482/Src/w25qxx.c",
"visit_date": "2022-11-07T07:35:10.797812"
} | stackv2 |
#include "w25qxx.h"
/*
page 256B
sector 4K = 16page
block 64K = 16sector
*/
#if (_W25QXX_DEBUG==1)
#include <stdio.h>
#endif
#define W25QXX_DUMMY_BYTE 0xA5
w25qxx_t w25qxx;
#if (_W25QXX_USE_FREERTOS==1)
#define W25qxx_Delay(delay) osDelay(delay)
#include "cmsis_os.h"
#else
#define W25qxx_Delay(delay) HAL_Delay(delay)
#endif
//###################################################################################################################
uint8_t W25qxx_Spi(uint8_t Data)
{
uint8_t ret;
HAL_SPI_TransmitReceive(&_W25QXX_SPI,&Data,&ret,1,100);
return ret;
}
//###################################################################################################################
uint32_t W25qxx_ReadID(void)
{
uint32_t Temp = 0, Temp0 = 0, Temp1 = 0, Temp2 = 0;
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0x9F);
Temp0 = W25qxx_Spi(W25QXX_DUMMY_BYTE);
Temp1 = W25qxx_Spi(W25QXX_DUMMY_BYTE);
Temp2 = W25qxx_Spi(W25QXX_DUMMY_BYTE);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
Temp = (Temp0 << 16) | (Temp1 << 8) | Temp2;
return Temp;
}
//###################################################################################################################
void W25qxx_ReadUniqID(void)
{
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0x4B);
for(uint8_t i=0;i<4;i++)
W25qxx_Spi(W25QXX_DUMMY_BYTE);
for(uint8_t i=0;i<8;i++)
w25qxx.UniqID[i] = W25qxx_Spi(W25QXX_DUMMY_BYTE);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
}
//###################################################################################################################
void W25qxx_WriteEnable(void)
{
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0x06);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
W25qxx_Delay(1);
}
//###################################################################################################################
void W25qxx_WriteDisable(void)
{
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0x04);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
W25qxx_Delay(1);
}
//###################################################################################################################
uint8_t W25qxx_ReadStatusRegister(uint8_t SelectStatusRegister_1_2_3)
{
uint8_t status=0;
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
if(SelectStatusRegister_1_2_3==1)
{
W25qxx_Spi(0x05);
status=W25qxx_Spi(W25QXX_DUMMY_BYTE);
w25qxx.StatusRegister1 = status;
}
else if(SelectStatusRegister_1_2_3==2)
{
W25qxx_Spi(0x35);
status=W25qxx_Spi(W25QXX_DUMMY_BYTE);
w25qxx.StatusRegister2 = status;
}
else
{
W25qxx_Spi(0x15);
status=W25qxx_Spi(W25QXX_DUMMY_BYTE);
w25qxx.StatusRegister3 = status;
}
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
return status;
}
//###################################################################################################################
void W25qxx_WriteStatusRegister(uint8_t SelectStatusRegister_1_2_3,uint8_t Data)
{
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
if(SelectStatusRegister_1_2_3==1)
{
W25qxx_Spi(0x01);
w25qxx.StatusRegister1 = Data;
}
else if(SelectStatusRegister_1_2_3==2)
{
W25qxx_Spi(0x31);
w25qxx.StatusRegister2 = Data;
}
else
{
W25qxx_Spi(0x11);
w25qxx.StatusRegister3 = Data;
}
W25qxx_Spi(Data);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
}
//###################################################################################################################
void W25qxx_WaitForWriteEnd(void)
{
W25qxx_Delay(1);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0x05);
do
{
w25qxx.StatusRegister1 = W25qxx_Spi(W25QXX_DUMMY_BYTE);
W25qxx_Delay(1);
}
while ((w25qxx.StatusRegister1 & 0x01) == 0x01);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
}
//###################################################################################################################
bool W25qxx_Init(void)
{
w25qxx.Lock=1;
while(HAL_GetTick()<100)
W25qxx_Delay(1);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
W25qxx_Delay(100);
uint32_t id;
#if (_W25QXX_DEBUG==1)
printf("w25qxx Init Begin...\r\n");
#endif
id=W25qxx_ReadID();
#if (_W25QXX_DEBUG==1)
printf("w25qxx ID:0x%X\r\n",id);
#endif
switch(id&0x0000FFFF)
{
case 0x401A: // w25q512
w25qxx.ID=W25Q512;
w25qxx.BlockCount=1024;
#if (_W25QXX_DEBUG==1)
printf("w25qxx Chip: w25q512\r\n");
#endif
break;
case 0x4019: // w25q256
w25qxx.ID=W25Q256;
w25qxx.BlockCount=512;
#if (_W25QXX_DEBUG==1)
printf("w25qxx Chip: w25q256\r\n");
#endif
break;
case 0x4018: // w25q128
w25qxx.ID=W25Q128;
w25qxx.BlockCount=256;
#if (_W25QXX_DEBUG==1)
printf("w25qxx Chip: w25q128\r\n");
#endif
break;
case 0x4017: // w25q64
w25qxx.ID=W25Q64;
w25qxx.BlockCount=128;
#if (_W25QXX_DEBUG==1)
printf("w25qxx Chip: w25q64\r\n");
#endif
break;
case 0x4016: // w25q32
w25qxx.ID=W25Q32;
w25qxx.BlockCount=64;
#if (_W25QXX_DEBUG==1)
printf("w25qxx Chip: w25q32\r\n");
#endif
break;
case 0x4015: // w25q16
w25qxx.ID=W25Q16;
w25qxx.BlockCount=32;
#if (_W25QXX_DEBUG==1)
printf("w25qxx Chip: w25q16\r\n");
#endif
break;
case 0x4014: // w25q80
w25qxx.ID=W25Q80;
w25qxx.BlockCount=16;
#if (_W25QXX_DEBUG==1)
printf("w25qxx Chip: w25q80\r\n");
#endif
break;
case 0x4013: // w25q40
w25qxx.ID=W25Q40;
w25qxx.BlockCount=8;
#if (_W25QXX_DEBUG==1)
printf("w25qxx Chip: w25q40\r\n");
#endif
break;
case 0x4012: // w25q20
w25qxx.ID=W25Q20;
w25qxx.BlockCount=4;
#if (_W25QXX_DEBUG==1)
printf("w25qxx Chip: w25q20\r\n");
#endif
break;
case 0x4011: // w25q10
w25qxx.ID=W25Q10;
w25qxx.BlockCount=2;
#if (_W25QXX_DEBUG==1)
printf("w25qxx Chip: w25q10\r\n");
#endif
break;
default:
#if (_W25QXX_DEBUG==1)
printf("w25qxx Unknown ID\r\n");
#endif
w25qxx.Lock=0;
return false;
}
w25qxx.PageSize=256;
w25qxx.SectorSize=0x1000;
w25qxx.SectorCount=w25qxx.BlockCount*16;
w25qxx.PageCount=(w25qxx.SectorCount*w25qxx.SectorSize)/w25qxx.PageSize;
w25qxx.BlockSize=w25qxx.SectorSize*16;
w25qxx.CapacityInKiloByte=(w25qxx.SectorCount*w25qxx.SectorSize)/1024;
W25qxx_ReadUniqID();
W25qxx_ReadStatusRegister(1);
W25qxx_ReadStatusRegister(2);
W25qxx_ReadStatusRegister(3);
#if (_W25QXX_DEBUG==1)
printf("w25qxx Page Size: %d Bytes\r\n",w25qxx.PageSize);
printf("w25qxx Page Count: %d\r\n",w25qxx.PageCount);
printf("w25qxx Sector Size: %d Bytes\r\n",w25qxx.SectorSize);
printf("w25qxx Sector Count: %d\r\n",w25qxx.SectorCount);
printf("w25qxx Block Size: %d Bytes\r\n",w25qxx.BlockSize);
printf("w25qxx Block Count: %d\r\n",w25qxx.BlockCount);
printf("w25qxx Capacity: %d KiloBytes\r\n",w25qxx.CapacityInKiloByte);
printf("w25qxx Init Done\r\n");
#endif
w25qxx.Lock=0;
return true;
}
//###################################################################################################################
void W25qxx_EraseChip(void)
{
while(w25qxx.Lock==1)
W25qxx_Delay(1);
w25qxx.Lock=1;
#if (_W25QXX_DEBUG==1)
uint32_t StartTime=HAL_GetTick();
printf("w25qxx EraseChip Begin...\r\n");
#endif
W25qxx_WriteEnable();
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0xC7);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
W25qxx_WaitForWriteEnd();
#if (_W25QXX_DEBUG==1)
printf("w25qxx EraseBlock done after %d ms!\r\n",HAL_GetTick()-StartTime);
#endif
W25qxx_Delay(10);
w25qxx.Lock=0;
}
//###################################################################################################################
void W25qxx_EraseSector(uint32_t SectorAddr)
{
while(w25qxx.Lock==1)
W25qxx_Delay(1);
w25qxx.Lock=1;
#if (_W25QXX_DEBUG==1)
uint32_t StartTime=HAL_GetTick();
printf("w25qxx EraseSector %d Begin...\r\n",SectorAddr);
#endif
W25qxx_WaitForWriteEnd();
SectorAddr = SectorAddr * w25qxx.SectorSize;
W25qxx_WriteEnable();
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0x20);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((SectorAddr & 0xFF000000) >> 24);
W25qxx_Spi((SectorAddr & 0xFF0000) >> 16);
W25qxx_Spi((SectorAddr & 0xFF00) >> 8);
W25qxx_Spi(SectorAddr & 0xFF);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
W25qxx_WaitForWriteEnd();
#if (_W25QXX_DEBUG==1)
printf("w25qxx EraseSector done after %d ms\r\n",HAL_GetTick()-StartTime);
#endif
W25qxx_Delay(1);
w25qxx.Lock=0;
}
//###################################################################################################################
void W25qxx_EraseBlock(uint32_t BlockAddr)
{
while(w25qxx.Lock==1)
W25qxx_Delay(1);
w25qxx.Lock=1;
#if (_W25QXX_DEBUG==1)
printf("w25qxx EraseBlock %d Begin...\r\n",BlockAddr);
W25qxx_Delay(100);
uint32_t StartTime=HAL_GetTick();
#endif
W25qxx_WaitForWriteEnd();
BlockAddr = BlockAddr * w25qxx.SectorSize*16;
W25qxx_WriteEnable();
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0xD8);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((BlockAddr & 0xFF000000) >> 24);
W25qxx_Spi((BlockAddr & 0xFF0000) >> 16);
W25qxx_Spi((BlockAddr & 0xFF00) >> 8);
W25qxx_Spi(BlockAddr & 0xFF);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
W25qxx_WaitForWriteEnd();
#if (_W25QXX_DEBUG==1)
printf("w25qxx EraseBlock done after %d ms\r\n",HAL_GetTick()-StartTime);
W25qxx_Delay(100);
#endif
W25qxx_Delay(1);
w25qxx.Lock=0;
}
//###################################################################################################################
uint32_t W25qxx_PageToSector(uint32_t PageAddress)
{
return ((PageAddress*w25qxx.PageSize)/w25qxx.SectorSize);
}
//###################################################################################################################
uint32_t W25qxx_PageToBlock(uint32_t PageAddress)
{
return ((PageAddress*w25qxx.PageSize)/w25qxx.BlockSize);
}
//###################################################################################################################
uint32_t W25qxx_SectorToBlock(uint32_t SectorAddress)
{
return ((SectorAddress*w25qxx.SectorSize)/w25qxx.BlockSize);
}
//###################################################################################################################
uint32_t W25qxx_SectorToPage(uint32_t SectorAddress)
{
return (SectorAddress*w25qxx.SectorSize)/w25qxx.PageSize;
}
//###################################################################################################################
uint32_t W25qxx_BlockToPage(uint32_t BlockAddress)
{
return (BlockAddress*w25qxx.BlockSize)/w25qxx.PageSize;
}
//###################################################################################################################
bool W25qxx_IsEmptyPage(uint32_t Page_Address,uint32_t OffsetInByte,uint32_t NumByteToCheck_up_to_PageSize)
{
while(w25qxx.Lock==1)
W25qxx_Delay(1);
w25qxx.Lock=1;
if(((NumByteToCheck_up_to_PageSize+OffsetInByte)>w25qxx.PageSize)||(NumByteToCheck_up_to_PageSize==0))
NumByteToCheck_up_to_PageSize=w25qxx.PageSize-OffsetInByte;
#if (_W25QXX_DEBUG==1)
printf("w25qxx CheckPage:%d, Offset:%d, Bytes:%d begin...\r\n",Page_Address,OffsetInByte,NumByteToCheck_up_to_PageSize);
W25qxx_Delay(100);
uint32_t StartTime=HAL_GetTick();
#endif
uint8_t pBuffer[32];
uint32_t WorkAddress;
uint32_t i;
for(i=OffsetInByte; i<w25qxx.PageSize; i+=sizeof(pBuffer))
{
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
WorkAddress=(i+Page_Address*w25qxx.PageSize);
W25qxx_Spi(0x0B);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((WorkAddress & 0xFF000000) >> 24);
W25qxx_Spi((WorkAddress & 0xFF0000) >> 16);
W25qxx_Spi((WorkAddress & 0xFF00) >> 8);
W25qxx_Spi(WorkAddress & 0xFF);
W25qxx_Spi(0);
HAL_SPI_Receive(&_W25QXX_SPI,pBuffer,sizeof(pBuffer),100);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
for(uint8_t x=0;x<sizeof(pBuffer);x++)
{
if(pBuffer[x]!=0xFF)
goto NOT_EMPTY;
}
}
if((w25qxx.PageSize+OffsetInByte)%sizeof(pBuffer)!=0)
{
i-=sizeof(pBuffer);
for( ; i<w25qxx.PageSize; i++)
{
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
WorkAddress=(i+Page_Address*w25qxx.PageSize);
W25qxx_Spi(0x0B);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((WorkAddress & 0xFF000000) >> 24);
W25qxx_Spi((WorkAddress & 0xFF0000) >> 16);
W25qxx_Spi((WorkAddress & 0xFF00) >> 8);
W25qxx_Spi(WorkAddress & 0xFF);
W25qxx_Spi(0);
HAL_SPI_Receive(&_W25QXX_SPI,pBuffer,1,100);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
if(pBuffer[0]!=0xFF)
goto NOT_EMPTY;
}
}
#if (_W25QXX_DEBUG==1)
printf("w25qxx CheckPage is Empty in %d ms\r\n",HAL_GetTick()-StartTime);
W25qxx_Delay(100);
#endif
w25qxx.Lock=0;
return true;
NOT_EMPTY:
#if (_W25QXX_DEBUG==1)
printf("w25qxx CheckPage is Not Empty in %d ms\r\n",HAL_GetTick()-StartTime);
W25qxx_Delay(100);
#endif
w25qxx.Lock=0;
return false;
}
//###################################################################################################################
bool W25qxx_IsEmptySector(uint32_t Sector_Address,uint32_t OffsetInByte,uint32_t NumByteToCheck_up_to_SectorSize)
{
while(w25qxx.Lock==1)
W25qxx_Delay(1);
w25qxx.Lock=1;
if((NumByteToCheck_up_to_SectorSize>w25qxx.SectorSize)||(NumByteToCheck_up_to_SectorSize==0))
NumByteToCheck_up_to_SectorSize=w25qxx.SectorSize;
#if (_W25QXX_DEBUG==1)
printf("w25qxx CheckSector:%d, Offset:%d, Bytes:%d begin...\r\n",Sector_Address,OffsetInByte,NumByteToCheck_up_to_SectorSize);
W25qxx_Delay(100);
uint32_t StartTime=HAL_GetTick();
#endif
uint8_t pBuffer[32];
uint32_t WorkAddress;
uint32_t i;
for(i=OffsetInByte; i<w25qxx.SectorSize; i+=sizeof(pBuffer))
{
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
WorkAddress=(i+Sector_Address*w25qxx.SectorSize);
W25qxx_Spi(0x0B);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((WorkAddress & 0xFF000000) >> 24);
W25qxx_Spi((WorkAddress & 0xFF0000) >> 16);
W25qxx_Spi((WorkAddress & 0xFF00) >> 8);
W25qxx_Spi(WorkAddress & 0xFF);
W25qxx_Spi(0);
HAL_SPI_Receive(&_W25QXX_SPI,pBuffer,sizeof(pBuffer),100);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
for(uint8_t x=0;x<sizeof(pBuffer);x++)
{
if(pBuffer[x]!=0xFF)
goto NOT_EMPTY;
}
}
if((w25qxx.SectorSize+OffsetInByte)%sizeof(pBuffer)!=0)
{
i-=sizeof(pBuffer);
for( ; i<w25qxx.SectorSize; i++)
{
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
WorkAddress=(i+Sector_Address*w25qxx.SectorSize);
W25qxx_Spi(0x0B);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((WorkAddress & 0xFF000000) >> 24);
W25qxx_Spi((WorkAddress & 0xFF0000) >> 16);
W25qxx_Spi((WorkAddress & 0xFF00) >> 8);
W25qxx_Spi(WorkAddress & 0xFF);
W25qxx_Spi(0);
HAL_SPI_Receive(&_W25QXX_SPI,pBuffer,1,100);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
if(pBuffer[0]!=0xFF)
goto NOT_EMPTY;
}
}
#if (_W25QXX_DEBUG==1)
printf("w25qxx CheckSector is Empty in %d ms\r\n",HAL_GetTick()-StartTime);
W25qxx_Delay(100);
#endif
w25qxx.Lock=0;
return true;
NOT_EMPTY:
#if (_W25QXX_DEBUG==1)
printf("w25qxx CheckSector is Not Empty in %d ms\r\n",HAL_GetTick()-StartTime);
W25qxx_Delay(100);
#endif
w25qxx.Lock=0;
return false;
}
//###################################################################################################################
bool W25qxx_IsEmptyBlock(uint32_t Block_Address,uint32_t OffsetInByte,uint32_t NumByteToCheck_up_to_BlockSize)
{
while(w25qxx.Lock==1)
W25qxx_Delay(1);
w25qxx.Lock=1;
if((NumByteToCheck_up_to_BlockSize>w25qxx.BlockSize)||(NumByteToCheck_up_to_BlockSize==0))
NumByteToCheck_up_to_BlockSize=w25qxx.BlockSize;
#if (_W25QXX_DEBUG==1)
printf("w25qxx CheckBlock:%d, Offset:%d, Bytes:%d begin...\r\n",Block_Address,OffsetInByte,NumByteToCheck_up_to_BlockSize);
W25qxx_Delay(100);
uint32_t StartTime=HAL_GetTick();
#endif
uint8_t pBuffer[32];
uint32_t WorkAddress;
uint32_t i;
for(i=OffsetInByte; i<w25qxx.BlockSize; i+=sizeof(pBuffer))
{
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
WorkAddress=(i+Block_Address*w25qxx.BlockSize);
W25qxx_Spi(0x0B);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((WorkAddress & 0xFF000000) >> 24);
W25qxx_Spi((WorkAddress & 0xFF0000) >> 16);
W25qxx_Spi((WorkAddress & 0xFF00) >> 8);
W25qxx_Spi(WorkAddress & 0xFF);
W25qxx_Spi(0);
HAL_SPI_Receive(&_W25QXX_SPI,pBuffer,sizeof(pBuffer),100);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
for(uint8_t x=0;x<sizeof(pBuffer);x++)
{
if(pBuffer[x]!=0xFF)
goto NOT_EMPTY;
}
}
if((w25qxx.BlockSize+OffsetInByte)%sizeof(pBuffer)!=0)
{
i-=sizeof(pBuffer);
for( ; i<w25qxx.BlockSize; i++)
{
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
WorkAddress=(i+Block_Address*w25qxx.BlockSize);
W25qxx_Spi(0x0B);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((WorkAddress & 0xFF000000) >> 24);
W25qxx_Spi((WorkAddress & 0xFF0000) >> 16);
W25qxx_Spi((WorkAddress & 0xFF00) >> 8);
W25qxx_Spi(WorkAddress & 0xFF);
W25qxx_Spi(0);
HAL_SPI_Receive(&_W25QXX_SPI,pBuffer,1,100);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
if(pBuffer[0]!=0xFF)
goto NOT_EMPTY;
}
}
#if (_W25QXX_DEBUG==1)
printf("w25qxx CheckBlock is Empty in %d ms\r\n",HAL_GetTick()-StartTime);
W25qxx_Delay(100);
#endif
w25qxx.Lock=0;
return true;
NOT_EMPTY:
#if (_W25QXX_DEBUG==1)
printf("w25qxx CheckBlock is Not Empty in %d ms\r\n",HAL_GetTick()-StartTime);
W25qxx_Delay(100);
#endif
w25qxx.Lock=0;
return false;
}
//###################################################################################################################
void W25qxx_WriteByte(uint8_t pBuffer, uint32_t WriteAddr_inBytes)
{
while(w25qxx.Lock==1)
W25qxx_Delay(1);
w25qxx.Lock=1;
#if (_W25QXX_DEBUG==1)
uint32_t StartTime=HAL_GetTick();
printf("w25qxx WriteByte 0x%02X at address %d begin...",pBuffer,WriteAddr_inBytes);
#endif
W25qxx_WaitForWriteEnd();
W25qxx_WriteEnable();
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0x02);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((WriteAddr_inBytes & 0xFF000000) >> 24);
W25qxx_Spi((WriteAddr_inBytes & 0xFF0000) >> 16);
W25qxx_Spi((WriteAddr_inBytes & 0xFF00) >> 8);
W25qxx_Spi(WriteAddr_inBytes & 0xFF);
W25qxx_Spi(pBuffer);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
W25qxx_WaitForWriteEnd();
#if (_W25QXX_DEBUG==1)
printf("w25qxx WriteByte done after %d ms\r\n",HAL_GetTick()-StartTime);
#endif
w25qxx.Lock=0;
}
//###################################################################################################################
void W25qxx_WritePage(uint8_t *pBuffer ,uint32_t Page_Address,uint32_t OffsetInByte,uint32_t NumByteToWrite_up_to_PageSize)
{
while(w25qxx.Lock==1)
W25qxx_Delay(1);
w25qxx.Lock=1;
if(((NumByteToWrite_up_to_PageSize+OffsetInByte)>w25qxx.PageSize)||(NumByteToWrite_up_to_PageSize==0))
NumByteToWrite_up_to_PageSize=w25qxx.PageSize-OffsetInByte;
if((OffsetInByte+NumByteToWrite_up_to_PageSize) > w25qxx.PageSize)
NumByteToWrite_up_to_PageSize = w25qxx.PageSize-OffsetInByte;
#if (_W25QXX_DEBUG==1)
printf("w25qxx WritePage:%d, Offset:%d ,Writes %d Bytes, begin...\r\n",Page_Address,OffsetInByte,NumByteToWrite_up_to_PageSize);
W25qxx_Delay(100);
uint32_t StartTime=HAL_GetTick();
#endif
W25qxx_WaitForWriteEnd();
W25qxx_WriteEnable();
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0x02);
Page_Address = (Page_Address*w25qxx.PageSize)+OffsetInByte;
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((Page_Address & 0xFF000000) >> 24);
W25qxx_Spi((Page_Address & 0xFF0000) >> 16);
W25qxx_Spi((Page_Address & 0xFF00) >> 8);
W25qxx_Spi(Page_Address&0xFF);
HAL_SPI_Transmit(&_W25QXX_SPI,pBuffer,NumByteToWrite_up_to_PageSize,100);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
W25qxx_WaitForWriteEnd();
#if (_W25QXX_DEBUG==1)
StartTime = HAL_GetTick()-StartTime;
for(uint32_t i=0;i<NumByteToWrite_up_to_PageSize ; i++)
{
if((i%8==0)&&(i>2))
{
printf("\r\n");
W25qxx_Delay(10);
}
printf("0x%02X,",pBuffer[i]);
}
printf("\r\n");
printf("w25qxx WritePage done after %d ms\r\n",StartTime);
W25qxx_Delay(100);
#endif
W25qxx_Delay(1);
w25qxx.Lock=0;
}
//###################################################################################################################
void W25qxx_WriteSector(uint8_t *pBuffer ,uint32_t Sector_Address,uint32_t OffsetInByte ,uint32_t NumByteToWrite_up_to_SectorSize)
{
if((NumByteToWrite_up_to_SectorSize>w25qxx.SectorSize)||(NumByteToWrite_up_to_SectorSize==0))
NumByteToWrite_up_to_SectorSize=w25qxx.SectorSize;
#if (_W25QXX_DEBUG==1)
printf("+++w25qxx WriteSector:%d, Offset:%d ,Write %d Bytes, begin...\r\n",Sector_Address,OffsetInByte,NumByteToWrite_up_to_SectorSize);
W25qxx_Delay(100);
#endif
if(OffsetInByte>=w25qxx.SectorSize)
{
#if (_W25QXX_DEBUG==1)
printf("---w25qxx WriteSector Faild!\r\n");
W25qxx_Delay(100);
#endif
return;
}
uint32_t StartPage;
int32_t BytesToWrite;
uint32_t LocalOffset;
if((OffsetInByte+NumByteToWrite_up_to_SectorSize) > w25qxx.SectorSize)
BytesToWrite = w25qxx.SectorSize-OffsetInByte;
else
BytesToWrite = NumByteToWrite_up_to_SectorSize;
StartPage = W25qxx_SectorToPage(Sector_Address)+(OffsetInByte/w25qxx.PageSize);
LocalOffset = OffsetInByte%w25qxx.PageSize;
do
{
W25qxx_WritePage(pBuffer,StartPage,LocalOffset,BytesToWrite);
StartPage++;
BytesToWrite-=w25qxx.PageSize-LocalOffset;
pBuffer+=w25qxx.PageSize;
LocalOffset=0;
}while(BytesToWrite>0);
#if (_W25QXX_DEBUG==1)
printf("---w25qxx WriteSector Done\r\n");
W25qxx_Delay(100);
#endif
}
//###################################################################################################################
void W25qxx_WriteBlock (uint8_t* pBuffer ,uint32_t Block_Address ,uint32_t OffsetInByte ,uint32_t NumByteToWrite_up_to_BlockSize)
{
if((NumByteToWrite_up_to_BlockSize>w25qxx.BlockSize)||(NumByteToWrite_up_to_BlockSize==0))
NumByteToWrite_up_to_BlockSize=w25qxx.BlockSize;
#if (_W25QXX_DEBUG==1)
printf("+++w25qxx WriteBlock:%d, Offset:%d ,Write %d Bytes, begin...\r\n",Block_Address,OffsetInByte,NumByteToWrite_up_to_BlockSize);
W25qxx_Delay(100);
#endif
if(OffsetInByte>=w25qxx.BlockSize)
{
#if (_W25QXX_DEBUG==1)
printf("---w25qxx WriteBlock Faild!\r\n");
W25qxx_Delay(100);
#endif
return;
}
uint32_t StartPage;
int32_t BytesToWrite;
uint32_t LocalOffset;
if((OffsetInByte+NumByteToWrite_up_to_BlockSize) > w25qxx.BlockSize)
BytesToWrite = w25qxx.BlockSize-OffsetInByte;
else
BytesToWrite = NumByteToWrite_up_to_BlockSize;
StartPage = W25qxx_BlockToPage(Block_Address)+(OffsetInByte/w25qxx.PageSize);
LocalOffset = OffsetInByte%w25qxx.PageSize;
do
{
W25qxx_WritePage(pBuffer,StartPage,LocalOffset,BytesToWrite);
StartPage++;
BytesToWrite-=w25qxx.PageSize-LocalOffset;
pBuffer+=w25qxx.PageSize;
LocalOffset=0;
}while(BytesToWrite>0);
#if (_W25QXX_DEBUG==1)
printf("---w25qxx WriteBlock Done\r\n");
W25qxx_Delay(100);
#endif
}
//###################################################################################################################
void W25qxx_ReadByte(uint8_t *pBuffer,uint32_t Bytes_Address)
{
while(w25qxx.Lock==1)
W25qxx_Delay(1);
w25qxx.Lock=1;
#if (_W25QXX_DEBUG==1)
uint32_t StartTime=HAL_GetTick();
printf("w25qxx ReadByte at address %d begin...\r\n",Bytes_Address);
#endif
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0x0B);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((Bytes_Address & 0xFF000000) >> 24);
W25qxx_Spi((Bytes_Address & 0xFF0000) >> 16);
W25qxx_Spi((Bytes_Address& 0xFF00) >> 8);
W25qxx_Spi(Bytes_Address & 0xFF);
W25qxx_Spi(0);
*pBuffer = W25qxx_Spi(W25QXX_DUMMY_BYTE);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
#if (_W25QXX_DEBUG==1)
printf("w25qxx ReadByte 0x%02X done after %d ms\r\n",*pBuffer,HAL_GetTick()-StartTime);
#endif
w25qxx.Lock=0;
}
//###################################################################################################################
void W25qxx_ReadBytes(uint8_t* pBuffer, uint32_t ReadAddr, uint32_t NumByteToRead)
{
while(w25qxx.Lock==1)
W25qxx_Delay(1);
w25qxx.Lock=1;
#if (_W25QXX_DEBUG==1)
uint32_t StartTime=HAL_GetTick();
printf("w25qxx ReadBytes at Address:%d, %d Bytes begin...\r\n",ReadAddr,NumByteToRead);
#endif
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0x0B);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((ReadAddr & 0xFF000000) >> 24);
W25qxx_Spi((ReadAddr & 0xFF0000) >> 16);
W25qxx_Spi((ReadAddr& 0xFF00) >> 8);
W25qxx_Spi(ReadAddr & 0xFF);
W25qxx_Spi(0);
HAL_SPI_Receive(&_W25QXX_SPI,pBuffer,NumByteToRead,2000);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
#if (_W25QXX_DEBUG==1)
StartTime = HAL_GetTick()-StartTime;
for(uint32_t i=0;i<NumByteToRead ; i++)
{
if((i%8==0)&&(i>2))
{
printf("\r\n");
W25qxx_Delay(10);
}
printf("0x%02X,",pBuffer[i]);
}
printf("\r\n");
printf("w25qxx ReadBytes done after %d ms\r\n",StartTime);
W25qxx_Delay(100);
#endif
W25qxx_Delay(1);
w25qxx.Lock=0;
}
//###################################################################################################################
void W25qxx_ReadPage(uint8_t *pBuffer,uint32_t Page_Address,uint32_t OffsetInByte,uint32_t NumByteToRead_up_to_PageSize)
{
while(w25qxx.Lock==1)
W25qxx_Delay(1);
w25qxx.Lock=1;
if((NumByteToRead_up_to_PageSize>w25qxx.PageSize)||(NumByteToRead_up_to_PageSize==0))
NumByteToRead_up_to_PageSize=w25qxx.PageSize;
if((OffsetInByte+NumByteToRead_up_to_PageSize) > w25qxx.PageSize)
NumByteToRead_up_to_PageSize = w25qxx.PageSize-OffsetInByte;
#if (_W25QXX_DEBUG==1)
printf("w25qxx ReadPage:%d, Offset:%d ,Read %d Bytes, begin...\r\n",Page_Address,OffsetInByte,NumByteToRead_up_to_PageSize);
W25qxx_Delay(100);
uint32_t StartTime=HAL_GetTick();
#endif
Page_Address = Page_Address*w25qxx.PageSize+OffsetInByte;
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_RESET);
W25qxx_Spi(0x0B);
if(w25qxx.ID>=W25Q256)
W25qxx_Spi((Page_Address & 0xFF000000) >> 24);
W25qxx_Spi((Page_Address & 0xFF0000) >> 16);
W25qxx_Spi((Page_Address& 0xFF00) >> 8);
W25qxx_Spi(Page_Address & 0xFF);
W25qxx_Spi(0);
HAL_SPI_Receive(&_W25QXX_SPI,pBuffer,NumByteToRead_up_to_PageSize,100);
HAL_GPIO_WritePin(_W25QXX_CS_GPIO,_W25QXX_CS_PIN,GPIO_PIN_SET);
#if (_W25QXX_DEBUG==1)
StartTime = HAL_GetTick()-StartTime;
for(uint32_t i=0;i<NumByteToRead_up_to_PageSize ; i++)
{
if((i%8==0)&&(i>2))
{
printf("\r\n");
W25qxx_Delay(10);
}
printf("0x%02X,",pBuffer[i]);
}
printf("\r\n");
printf("w25qxx ReadPage done after %d ms\r\n",StartTime);
W25qxx_Delay(100);
#endif
W25qxx_Delay(1);
w25qxx.Lock=0;
}
//###################################################################################################################
void W25qxx_ReadSector(uint8_t *pBuffer,uint32_t Sector_Address,uint32_t OffsetInByte,uint32_t NumByteToRead_up_to_SectorSize)
{
if((NumByteToRead_up_to_SectorSize>w25qxx.SectorSize)||(NumByteToRead_up_to_SectorSize==0))
NumByteToRead_up_to_SectorSize=w25qxx.SectorSize;
#if (_W25QXX_DEBUG==1)
printf("+++w25qxx ReadSector:%d, Offset:%d ,Read %d Bytes, begin...\r\n",Sector_Address,OffsetInByte,NumByteToRead_up_to_SectorSize);
W25qxx_Delay(100);
#endif
if(OffsetInByte>=w25qxx.SectorSize)
{
#if (_W25QXX_DEBUG==1)
printf("---w25qxx ReadSector Faild!\r\n");
W25qxx_Delay(100);
#endif
return;
}
uint32_t StartPage;
int32_t BytesToRead;
uint32_t LocalOffset;
if((OffsetInByte+NumByteToRead_up_to_SectorSize) > w25qxx.SectorSize)
BytesToRead = w25qxx.SectorSize-OffsetInByte;
else
BytesToRead = NumByteToRead_up_to_SectorSize;
StartPage = W25qxx_SectorToPage(Sector_Address)+(OffsetInByte/w25qxx.PageSize);
LocalOffset = OffsetInByte%w25qxx.PageSize;
do
{
W25qxx_ReadPage(pBuffer,StartPage,LocalOffset,BytesToRead);
StartPage++;
BytesToRead-=w25qxx.PageSize-LocalOffset;
pBuffer+=w25qxx.PageSize;
LocalOffset=0;
}while(BytesToRead>0);
#if (_W25QXX_DEBUG==1)
printf("---w25qxx ReadSector Done\r\n");
W25qxx_Delay(100);
#endif
}
//###################################################################################################################
void W25qxx_ReadBlock(uint8_t* pBuffer,uint32_t Block_Address,uint32_t OffsetInByte,uint32_t NumByteToRead_up_to_BlockSize)
{
if((NumByteToRead_up_to_BlockSize>w25qxx.BlockSize)||(NumByteToRead_up_to_BlockSize==0))
NumByteToRead_up_to_BlockSize=w25qxx.BlockSize;
#if (_W25QXX_DEBUG==1)
printf("+++w25qxx ReadBlock:%d, Offset:%d ,Read %d Bytes, begin...\r\n",Block_Address,OffsetInByte,NumByteToRead_up_to_BlockSize);
W25qxx_Delay(100);
#endif
if(OffsetInByte>=w25qxx.BlockSize)
{
#if (_W25QXX_DEBUG==1)
printf("w25qxx ReadBlock Faild!\r\n");
W25qxx_Delay(100);
#endif
return;
}
uint32_t StartPage;
int32_t BytesToRead;
uint32_t LocalOffset;
if((OffsetInByte+NumByteToRead_up_to_BlockSize) > w25qxx.BlockSize)
BytesToRead = w25qxx.BlockSize-OffsetInByte;
else
BytesToRead = NumByteToRead_up_to_BlockSize;
StartPage = W25qxx_BlockToPage(Block_Address)+(OffsetInByte/w25qxx.PageSize);
LocalOffset = OffsetInByte%w25qxx.PageSize;
do
{
W25qxx_ReadPage(pBuffer,StartPage,LocalOffset,BytesToRead);
StartPage++;
BytesToRead-=w25qxx.PageSize-LocalOffset;
pBuffer+=w25qxx.PageSize;
LocalOffset=0;
}while(BytesToRead>0);
#if (_W25QXX_DEBUG==1)
printf("---w25qxx ReadBlock Done\r\n");
W25qxx_Delay(100);
#endif
}
//###################################################################################################################
| 2.203125 | 2 |
2024-11-18T17:55:15.514927+00:00 | 2022-05-20T08:31:20 | 3879067c05eeef89267bc7a96c0820d5ed67638f | {
"blob_id": "3879067c05eeef89267bc7a96c0820d5ed67638f",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-28T20:02:33",
"content_id": "404a6d8844d4a60c051601508491504ace7c8545",
"detected_licenses": [],
"directory_id": "6b4c8cafe8b91c12b6d3e79bf90aea6f5948a00b",
"extension": "c",
"filename": "string.c",
"fork_events_count": 3,
"gha_created_at": "2016-09-20T11:57:08",
"gha_event_created_at": "2023-03-24T12:45:07",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 68707280,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5634,
"license": "",
"license_type": "permissive",
"path": "/src/string.c",
"provenance": "stackv2-0005.json.gz:11758",
"repo_name": "Parrot-Developers/libfutils",
"revision_date": "2022-05-20T08:31:20",
"revision_id": "884297e0576be62fcbb3b45dacf23973a4a70023",
"snapshot_id": "3d8f872a4a35984d774f082bc86ae2d991d5980f",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Parrot-Developers/libfutils/884297e0576be62fcbb3b45dacf23973a4a70023/src/string.c",
"visit_date": "2023-03-31T18:02:34.251539"
} | stackv2 | /******************************************************************************
* Copyright (c) 2022 Parrot S.A.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Parrot Company nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PARROT COMPANY 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.
*
* @file string.c
*
* @brief string utility functions
*
******************************************************************************/
#include "futils/string.h"
#include <errno.h>
#include <iconv.h>
#include <wchar.h>
#define ULOG_TAG futils_string
#include <ulog.h>
ULOG_DECLARE_TAG(ULOG_TAG);
static int to_wchar_string(const char *input_, size_t in_len, wchar_t **output_)
{
char *input, *output;
size_t inbytes, outbytes, outsize, sret;
wchar_t *woutput = NULL;
iconv_t conv;
int ret = 0;
*output_ = NULL;
conv = iconv_open("WCHAR_T", "UTF-8");
if (conv == (iconv_t)-1) {
ULOGD("iconv(WCHAR_T, UTF-8) is not available : %s(%d)",
strerror(errno),
errno);
return -ENOSYS;
}
woutput = calloc(in_len + 1, sizeof(wchar_t));
if (!woutput) {
ret = -ENOMEM;
goto exit;
}
input = (char *)input_;
inbytes = in_len;
output = (char *)woutput;
outsize = in_len * sizeof(wchar_t);
outbytes = outsize;
sret = iconv(conv, &input, &inbytes, &output, &outbytes);
if (sret == (size_t)-1) {
ret = -errno;
ULOGD("iconv failed with error %s(%d)", strerror(-ret), -ret);
goto exit;
}
/* ret is the number of wide characters written to output_ */
ret = (outsize - outbytes) / sizeof(wchar_t);
exit:
iconv_close(conv);
if (ret < 0)
free(woutput);
else
*output_ = woutput;
return ret;
}
static int to_utf8_string(wchar_t *input_, char *output_, size_t max_output_len)
{
char *input, *output;
size_t inbytes, outbytes, outsize, sret;
iconv_t conv;
int ret = 0;
conv = iconv_open("UTF-8", "WCHAR_T");
if (conv == (iconv_t)-1) {
ULOGD("iconv(UTF-8, WCHAR_T) is not available : %s(%d)",
strerror(errno),
errno);
return -ENOSYS;
}
input = (char *)input_;
inbytes = wcslen(input_) * sizeof(wchar_t);
output = (char *)output_;
outsize = max_output_len - 1;
outbytes = outsize;
sret = iconv(conv, &input, &inbytes, &output, &outbytes);
if (sret == (size_t)-1 && errno != E2BIG) {
/* E2BIG error is expected here as we want to truncate the
* string to max_output_len bytes */
ret = -errno;
ULOGD("iconv failed with error %s(%d)", strerror(-ret), -ret);
goto exit;
}
/* ret is the number of characters written to output_ */
ret = outsize - outbytes;
output_[ret] = '\0';
exit:
iconv_close(conv);
return ret;
}
int futils_string_sanitize_utf8(const char *input,
char *output,
size_t max_output_size,
const wchar_t *forbidden_chars,
wchar_t replacement_char)
{
int ret;
size_t in_len, w_len, i;
wchar_t *winput = NULL;
ULOG_ERRNO_RETURN_ERR_IF(!input, EINVAL);
ULOG_ERRNO_RETURN_ERR_IF(!output, EINVAL);
ULOG_ERRNO_RETURN_ERR_IF(max_output_size < 2, EINVAL);
/* Convert to wchar_t */
in_len = strlen(input);
ret = to_wchar_string(input, in_len, &winput);
if (ret < 0)
goto exit;
w_len = ret;
/* Replace forbidden chars */
if (!forbidden_chars)
goto cut;
for (i = 0; i < w_len; i++) {
if (wcschr(forbidden_chars, winput[i]) == NULL)
continue;
winput[i] = replacement_char;
}
cut:
/* Convert back to utf-8 */
ret = to_utf8_string(winput, output, max_output_size);
if (ret != 0)
goto exit;
exit:
free(winput);
return ret;
}
int futils_string_check_utf8(const char *input,
size_t max_bytes,
size_t max_wchars,
const wchar_t *forbidden_chars)
{
int ret;
size_t in_len, w_len, i;
wchar_t *winput = NULL;
ULOG_ERRNO_RETURN_ERR_IF(!input, EINVAL);
/* Check for max_bytes */
in_len = strlen(input);
if (max_bytes > 0 && in_len >= max_bytes) {
ret = -E2BIG;
goto exit;
}
/* Convert to wchar_t */
ret = to_wchar_string(input, in_len, &winput);
if (ret < 0)
goto exit;
w_len = ret;
ret = 0;
/* Check for max_wchars */
if (max_wchars > 0 && w_len > max_wchars) {
ret = -E2BIG;
goto exit;
}
/* Check for forbidden chars */
if (!forbidden_chars)
goto exit;
for (i = 0; i < w_len; i++) {
if (wcschr(forbidden_chars, winput[i]) == NULL)
continue;
ret = -EPROTO;
goto exit;
}
exit:
free(winput);
return ret;
}
| 2.078125 | 2 |
2024-11-18T17:55:15.930106+00:00 | 2020-10-10T15:45:15 | 1f17ace0199b9efa7e0aa197610dff99f67d5569 | {
"blob_id": "1f17ace0199b9efa7e0aa197610dff99f67d5569",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-10T15:45:15",
"content_id": "6e015a443fd2119f8c8b3a94251ca50774f23ee0",
"detected_licenses": [
"MIT"
],
"directory_id": "303ead3a6f7d3eadee717b9688a8008b1f67cd93",
"extension": "c",
"filename": "USB_functions.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 84308210,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14168,
"license": "MIT",
"license_type": "permissive",
"path": "/8_USB_HID_Mouse/lib/USB_functions.c",
"provenance": "stackv2-0005.json.gz:12142",
"repo_name": "asura6/STM32F103C8T6-from-scratch",
"revision_date": "2020-10-10T15:45:15",
"revision_id": "3855a3e09e07c1df8753b72821b68fba68f43668",
"snapshot_id": "96bee7dbbdb35c5e7e91690c2123e4ef73415606",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/asura6/STM32F103C8T6-from-scratch/3855a3e09e07c1df8753b72821b68fba68f43668/8_USB_HID_Mouse/lib/USB_functions.c",
"visit_date": "2021-01-18T08:56:24.681346"
} | stackv2 | /* Robin Isaksson 2017 */
#include <stm32f10x.h>
#include <stdint.h>
#include "./USB_def.h"
#include "./USB_conf.h"
#include "./USB.h"
#include "./USB_functions.h"
#include "./USART.h"
/************************************************/
/********* PREPROCESSOR DEFINITIONS *********/
/************************************************/
#define EP_STAT_MASK (EP_STAT_TX | EP_STAT_RX)
#define EP_DTOG_MASK (EP_DTOG_TX | EP_DTOG_RX)
#define EP_TOG_MASK (EP_STAT_MASK | EP_DTOG_MASK)
/**********************************************/
/********* PREPROCESSOR FUNCTIONS *********/
/**********************************************/
#define SETUP_Direction_IN() \
(setup_packet.bmRequestType & 0x80)
/* Descriptor booleans */
#define SETUP_Is_Get_Descriptor() \
(setup_packet.bRequest == 0x06)
// These are further checks to isolate which kind of descriptor is requested
#define Is_Device_Descriptor() \
(setup_packet.wValue == 0x01)
#define Is_Configuration_Descriptor() \
(setup_packet.wValue == 0x02)
#define Is_Interface_Descriptor() \
(setup_packet.wValue == 0x04)
#define Is_Endpoint_Descriptor() \
(setup_packet.wValue == 0x05)
#define Is_Device_Qualifier_Descriptor() \
(setup_packet.wValue == 0x06)
#define Is_Speed_Configuration_Descriptor() \
(setup_packet.wValue == 0x07)
#define Is_Interface_Power_Descriptor() \
(setup_packet.wValue == 0x08)
#define Is_HID_Descriptor() \
(setup_packet.wValue == 0x22)
//String descriptors
#define Is_String_Descriptor() \
((setup_packet.wValue & 0x0FU) == 0x03)
#define Is_String_Descriptor_Zero() \
((setup_packet.wValue >> 8U) == 0x00)
#define Is_String_Descriptor_Manufacturer() \
((setup_packet.wValue >> 8U) == 0x01)
#define Is_String_Descriptor_Product() \
((setup_packet.wValue >> 8U) == 0x02)
#define Is_String_Descriptor_Serial() \
((setup_packet.wValue >> 8U) == 0x03)
#define SETUP_Is_Set_Address() \
(setup_packet.bmRequestType == 0x00 && setup_packet.bRequest == 0x05)
#define SETUP_Is_Set_Configuration() \
(setup_packet.bmRequestType == 0x00U \
&& setup_packet.bRequest == 0x09)
#define SETUP_Is_Set_Idle() \
(setup_packet.bmRequestType == 0x21U && setup_packet.bRequest == 0x0a)
#define SETUP_Is_Get_Report() \
(setup_packet.bRequest == 0x01U)
/*******************************/
/********* Globals *********/
/*******************************/
USB_Setup_Packet_t setup_packet;
uint8_t USB_status = USB_STATUS_DEFAULT;
uint8_t addr = 0;
extern HID_report_t HID_report;
/********************************************/
/********* FORWARD DECLARATIONS *********/
/********************************************/
void USB_Parse_SETUP(void);
void USB_Load_Descriptor(uint8_t ep, uint16_t *desc, uint16_t length);
void USB_Load_String_Descriptor(const USB_string_descriptor_t *desc);
void USB_Handle_HID_Interrupt(void);
/******************************************************/
/********* ENDPOINT REGISTER FUNCTIONS ************/
/******************************************************/
/* Set EP number ep TYPE to type */
void USB_EP_Set_Type(uint8_t ep, uint16_t type) {
USB_EP(ep) = (USB_EP(ep) & ~(EP_TOG_MASK | EP_TYPE)) | type;
}
/* Set EP number ep KIND bit to value */
void USB_EP_Set_Kind(uint8_t ep, uint8_t value) {
USB_EP(ep) = (USB_EP(ep) & ~(EP_TOG_MASK | EP_KIND)) | (value << 8U); //At bit place 8
}
/* Set EP number ep STAT RX to rx */
void USB_EP_Set_STAT_RX(uint8_t ep, uint16_t rx) {
USB_EP(ep) = (USB_EP(ep) & ~EP_TOG_MASK) |
((USB_EP(ep) & EP_STAT_RX) ^ (rx << 12U));
}
/* Set EP number ep STAT TX to tx */
void USB_EP_Set_STAT_TX(uint8_t ep, uint16_t tx) {
USB_EP(ep) = (USB_EP(ep) & ~EP_TOG_MASK) |
((USB_EP(ep) & EP_STAT_TX) ^ (tx << 4U));
}
/* Set EP number ep DTOG_RX to value */
void USB_EP_Set_DTOG_RX(uint8_t ep, uint16_t value) {
USB_EP(ep) = (USB_EP(ep) & ~EP_TOG_MASK) |
((USB_EP(ep) & EP_DTOG_RX) ^ (value << 14U));
}
/* Set EP number ep DTOG_TX to value */
void USB_EP_Set_DTOG_TX(uint8_t ep, uint16_t value) {
USB_EP(ep) = (USB_EP(ep) & ~EP_TOG_MASK) |
((USB_EP(ep) & EP_DTOG_TX) ^ (value << 6U));
}
void USB_EP_Clear_CTR_RX(uint8_t ep) {
USB_EP(ep) = (USB_EP(ep) & ~EP_TOG_MASK) & ~EP_CTR_RX;
}
void USB_EP_Clear_CTR_TX(uint8_t ep) {
USB_EP(ep) = (USB_EP(ep) & ~EP_TOG_MASK) & ~EP_CTR_TX;
}
uint16_t USB_EP_Get_RX_Count(uint8_t ep) {
return (USB_BDT(ep)->COUNT_RX & USB_COUNT0_RX_COUNT0_RX);
}
void USB_EP_Set_TX_Count(uint8_t ep, uint16_t count) {
USB_BDT(ep)->COUNT_TX = count & USB_COUNT0_TX_COUNT0_TX;
}
/* Set EP number ep endpoint address (EA) to address */
void USB_EP_Set_EA(uint8_t ep, uint16_t address) {
/* Clear EA bits */
USB_EP(ep) = USB_EP(ep) & ~(EP_TOG_MASK | EP_EA);
/* Set EA bits */
USB_EP(ep) = (USB_EP(ep) & ~(EP_TOG_MASK)) |
address;
}
/*********************************************************/
/********* ENDPOINT TRANSACTION FUNCTIONS ************/
/*********************************************************/
/* Handle a SETUP packet */
void USB_Handle_SETUP(void) {
/* Reject further transaction until decided */
USB_EP_Set_STAT_TX(EP0, EP_NAK);
USB_EP_Set_STAT_RX(EP0, EP_NAK);
/* Set DTOG bits as required for the SETUP transaction */
USB_EP_Set_DTOG_TX(EP0, 1U);
USB_EP_Set_DTOG_RX(EP0, 0U);
/* Loads received values into a setup struct */
USB_Parse_SETUP();
if (SETUP_Direction_IN()) {
if (SETUP_Is_Get_Descriptor()) {
if (Is_Device_Descriptor()) {
/* Transmit the device descriptor */
USB_Load_Descriptor(EP0,
(uint16_t *)&USB_device_descriptor,
USB_device_descriptor.bLength);
USB_EP_Set_STAT_TX(EP0, EP_VALID);
} else if (Is_Configuration_Descriptor()) {
/* If requested length longer than the configuration descriptor
* length then send the combined descriptors in one go otherwise
* just send the configuration descriptor */
if ((setup_packet.wLength >> 8) > USB_combined_descriptor.conf_desc.bLength) {
USB_Load_Descriptor(EP0,
(uint16_t *)&USB_combined_descriptor,
USB_combined_descriptor.conf_desc.wTotalLength0);
} else {
USB_Load_Descriptor(EP0,
(uint16_t *)&USB_combined_descriptor,
USB_combined_descriptor.conf_desc.bLength);
}
USB_EP_Set_STAT_TX(EP0, EP_VALID);
} else if (Is_HID_Descriptor()) {
/* Send the HID Descriptor if requested */
USB_Load_Descriptor(EP0,
(uint16_t *)&HID_report_desc,
50U);
USB_EP_Set_STAT_TX(EP0, EP_VALID);
} else if (Is_String_Descriptor()) {
/* Send any of the string descriptors if requested */
if (Is_String_Descriptor_Zero()) {
USB_Load_String_Descriptor(
&USB_string_descriptor_zero);
} else if (Is_String_Descriptor_Manufacturer()) {
USB_Load_String_Descriptor(
&USB_string_descriptor_manufacturer);
} else if (Is_String_Descriptor_Product()) {
USB_Load_String_Descriptor(
&USB_string_descriptor_product);
} else if (Is_String_Descriptor_Serial()) {
USB_Load_String_Descriptor(
&USB_string_descriptor_serial);
}
USB_EP_Set_STAT_TX(EP0, EP_VALID);
} else {
/* If unrecognized descriptor request then stall. This for
* example can be a device qualifier descriptor which the host
* might ask for to see if the device supports high-speed USB */
USB_EP_Set_STAT_TX(EP0, EP_STALL);
}
} else if (SETUP_Is_Get_Report()) {
/* Send the HID report through the control endpoint instead of the
* interrupt endpoint */
//Reset report as this should not be the report transmit mechanism
HID_report = (HID_report_t){0};
USB_Load_Descriptor(EP0,
(uint16_t *)(&HID_report),
HID_REPORT_SIZE);
USB_EP_Set_STAT_TX(EP0, EP_VALID);
}
} else {
/* Direction OUT */
if (SETUP_Is_Set_Address()) {
/* Set address request. This request should be completed after the
* status stage so the USB_status variable is used as a
* state-variable to complete this task */
USB_status = USB_STATUS_ADDRESS_READY;
/* Load address into a global value, changing the address later */
addr = (setup_packet.wValue >> 8U) & USB_DADDR_ADD;
USB_EP_Set_TX_Count(EP0, 0U);
USB_EP_Set_STAT_TX(EP0, EP_VALID);
} else if (SETUP_Is_Set_Configuration()) {
/* Set configuration request */
USB_EP_Set_TX_Count(EP0, 0U);
USB_EP_Set_STAT_TX(EP0, EP_VALID);
} else if (SETUP_Is_Set_Idle()) {
/* The host requests the device to only update the reports when any
* changes happen. We now activate the interrupt endpoint */
//Successful request
USB_EP_Set_TX_Count(EP0, 0U);
USB_EP_Set_STAT_TX(EP0, EP_VALID);
//Set global status that the USB is ready to transmitt HID reports
USB_status = USB_STATUS_HID_READY;
/* All HID reports have the same size so we set this once here */
USB_EP_Set_TX_Count(EP1, HID_REPORT_SIZE);
}
}
}
void USB_Handle_OUT(void) {
/* OUT transaction. Should not occur in this program */
}
void USB_Handle_IN(void) {
if (USB_status == USB_STATUS_ADDRESS_READY) {
/* If address is ready to be changed then change it */
USB_EP_Clear_CTR_TX(EP0);
USB_status = USB_STATUS_DEFAULT; //Default USB status
USB->DADDR = addr | USB_DADDR_EF;
USB_EP_Set_STAT_TX(EP0, EP_VALID);
USB_EP_Set_STAT_RX(EP0, EP_VALID);
} else if ((USB->ISTR & USB_ISTR_EP_ID) == 0x01U) {
/* Endpoint one completed a transaction */
USB_EP_Clear_CTR_TX(EP1);
USB_EP_Set_STAT_TX(EP1, EP_NAK);
} else {
/* Control endpoint completed an IN transaction */
USB_EP_Clear_CTR_TX(EP0);
USB_EP_Set_STAT_TX(EP0, EP_VALID);
USB_EP_Set_STAT_RX(EP0, EP_VALID);
}
}
/* This function goes through the data contained in the received SETUP packet
* and assigns the values to the setup_packet struct */
void USB_Parse_SETUP(void) {
uint16_t byte_cnt = USB_EP_Get_RX_Count(EP0); //Bytes received
uint16_t word_cnt = (byte_cnt + 1U) >> 1U;
uint32_t addr_offset = USB_BDT(EP0)->ADDR_RX << 1U;
uint16_t *src = (uint16_t *)(PMA_BASE + addr_offset);
uint8_t data[byte_cnt];
uint16_t *dst = (uint16_t *)data;
//Load the received data into a data array
while (word_cnt) {
*dst = *src;
dst += 1U;
src += 2U;
word_cnt --;
}
//Assign the values from the data array
setup_packet.bmRequestType = data[0];
setup_packet.bRequest = data[1];
setup_packet.wValue = (data[2]<<8) | data[3];
setup_packet.wIndex = (data[4]<<8) | data[5];
setup_packet.wLength = (data[6]<<8) | data[7];
}
/* Load the descriptor data into the transmission register */
void USB_Load_Descriptor(uint8_t ep, uint16_t *desc, uint16_t length) {
uint16_t word_cnt = (length + 1U) >> 1U;
uint32_t addr_offset = USB_BDT(ep)->ADDR_TX << 1U;
uint16_t *dst = (uint16_t *)(PMA_BASE + addr_offset);
USB_EP_Set_TX_Count(ep, length);
while (word_cnt) {
*dst = *desc;
dst += 2U;
desc += 1U;
word_cnt--;
}
}
/* Load the string descriptor data into the transmission register */
void USB_Load_String_Descriptor(const USB_string_descriptor_t *desc) {
uint16_t word_cnt = ((desc->bLength + 1U) >> 1U) - 1;
uint32_t addr_offset = USB_BDT(EP0)->ADDR_TX << 1U;
uint16_t *dst = (uint16_t *)(PMA_BASE + addr_offset);
uint16_t *str_src = (uint16_t *)((uint32_t)desc->bString);
USB_EP_Set_TX_Count(EP0, desc->bLength);
//Load the first two bytes
*dst = desc->bLength | desc->bDescriptorType << 8U;
dst += 2U;
//Load the rest of the bytes
while (word_cnt) {
*dst = *str_src;
str_src += 1;
dst += 2U;
word_cnt--;
}
}
/***************************************************/
/********* ENDPOINT DEBUG FUNCTIONS ************/
/***************************************************/
void USB_EP_Debug_Print(uint8_t ep) {
uint16_t reg = USB_EP(ep);
USART_Send_Str("\n\rEP: ");
USART_Send_Integer(ep);
USART_Send_Str(" | DUMP: | ");
for (uint8_t i = 16U; i != 0; i--) {
if (reg & (1U << (i - 1U))) {
USART_Send_Integer(1U);
} else {
USART_Send_Integer(0U);
}
USART_Send_Str(" | ");
}
}
void USB_ISTR_Debug_Print(void) {
uint16_t reg = USB->ISTR;
USART_Send_Str("\n\rISTR: | DUMP: | ");
for (uint8_t i = 16U; i != 0; i--) {
if (reg & (1U << (i - 1U))) {
USART_Send_Integer(1U);
} else {
USART_Send_Integer(0U);
}
USART_Send_Str(" | ");
}
}
void USB_SETUP_Debug_Print(void) {
USART_Send_Str("\n\rSETUP PACKET: | ");
USART_Send_Str("bmRequestType: ");
USART_Send_Integer(setup_packet.bmRequestType);
USART_Send_Str(" | bRequest: ");
USART_Send_Integer(setup_packet.bRequest);
USART_Send_Str(" | wValue: ");
USART_Send_Integer(setup_packet.wValue);
USART_Send_Str(" | wIndex: ");
USART_Send_Integer(setup_packet.wIndex);
USART_Send_Str(" | wLength: ");
USART_Send_Integer(setup_packet.wLength);
}
| 2.140625 | 2 |
2024-11-18T17:55:16.015566+00:00 | 2020-07-03T15:34:19 | 36271af8d5202f4d2530ac30d6e8a735cce7b656 | {
"blob_id": "36271af8d5202f4d2530ac30d6e8a735cce7b656",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-03T15:34:19",
"content_id": "593bc1e6b2898785ec6c64bad01328fd8b4d9bdf",
"detected_licenses": [
"MIT"
],
"directory_id": "fd4ca068d0b831209bf3142c95ae23e573da0092",
"extension": "c",
"filename": "performLocalTranspose.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32469472,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 617,
"license": "MIT",
"license_type": "permissive",
"path": "/performLocalTranspose.c",
"provenance": "stackv2-0005.json.gz:12270",
"repo_name": "ikirker/3dfft",
"revision_date": "2020-07-03T15:34:19",
"revision_id": "aad4f50a185c9220e6fc7dc2faa72cb8ab7d1882",
"snapshot_id": "0de12b8a21cdb641799b967c7c8aeedefef3829f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ikirker/3dfft/aad4f50a185c9220e6fc7dc2faa72cb8ab7d1882/performLocalTranspose.c",
"visit_date": "2021-07-22T13:28:38.056968"
} | stackv2 | /*
* performLocalTranspose.c
* Transposes numberOfSlabs slabs of extent*extent sized
* contiguous arrays of complexType data.
*
* Created by Ian Kirker on 15/04/2008.
*
*/
#include "libDefs.h"
#include "performLocalTranspose.h"
/* Transposes multiple extent*extent 2D complex arrays stored contiguously in memory. */
void performLocalTranspose(complexType *data, int extent, int numberOfSlabs)
{
int i,j,k;
for(i=0;i<numberOfSlabs;i++)
{
for(j=0;j<extent;j++)
{
for(k=0;k<j;k++)
{
complexSwap(&data[i*extent*extent + j*extent + k], &data[i*extent*extent + k*extent + j]);
}
}
}
}
| 2.875 | 3 |
2024-11-18T17:55:16.170701+00:00 | 2022-07-30T22:45:56 | b6e4f01a8492df926f8e03036126b1d021288749 | {
"blob_id": "b6e4f01a8492df926f8e03036126b1d021288749",
"branch_name": "refs/heads/master",
"committer_date": "2022-07-30T22:45:56",
"content_id": "7cfafc17970c5118d1ff0a8f659a7017ddf2f647",
"detected_licenses": [
"MIT"
],
"directory_id": "49abb58c40577ce4470cca16034cf03ff0f94f7c",
"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": 130486168,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 772,
"license": "MIT",
"license_type": "permissive",
"path": "/C/cisco/CLA/lab/cla_lab_6_3_12__2/main.c",
"provenance": "stackv2-0005.json.gz:12527",
"repo_name": "stablestud/trainee",
"revision_date": "2022-07-30T22:45:56",
"revision_id": "72e18117e98ab4854e9271c2534e91cf39c42042",
"snapshot_id": "196c3e64920adc8278bd2f06430b6e357091c2a7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/stablestud/trainee/72e18117e98ab4854e9271c2534e91cf39c42042/C/cisco/CLA/lab/cla_lab_6_3_12__2/main.c",
"visit_date": "2022-08-11T11:52:26.099642"
} | stackv2 | #include <stdio.h>
int getValue(int paramA, float paramB)
{
int result = 0;
if (paramA > 10) {
result += 2;
} else {
result += 1;
}
if (paramB > 5.5) {
result += 4;
} else {
result += 3;
}
return result;
}
int getOneOrTwo(int param)
{
if(param > 5)
return 2;
else
return 1;
}
int main(void)
{
int fiveValue = getValue( 11, 5. );
int sixValue = getValue( 11, 5.6 );
int sevenValue = getValue( 11, 5.6 ) + getOneOrTwo( 1 );
int eightValue = getOneOrTwo( 10 ) * getValue( 3, 2. );
int nineValue = getValue( 1, 1.5 ) * getOneOrTwo( 12 ) + getOneOrTwo( 1 );
printf("Five: %d\n", fiveValue);
printf("Six: %d\n", sixValue);
printf("Seven: %d\n", sevenValue);
printf("Eight: %d\n", eightValue);
printf("Nine: %d\n", nineValue);
return 0;
}
| 3.453125 | 3 |
2024-11-18T17:55:17.406659+00:00 | 2013-05-08T12:40:43 | bd8ff25f55a08e69f8a46399097bd5fafe2ae018 | {
"blob_id": "bd8ff25f55a08e69f8a46399097bd5fafe2ae018",
"branch_name": "refs/heads/master",
"committer_date": "2013-05-08T12:40:43",
"content_id": "4fbeb239d4070a5ef7db69eceb827598021894ea",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "3f32aeab0966883c98198232e2ee83a9f3eb8277",
"extension": "c",
"filename": "hhpc.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": 7142,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/hhpc.c",
"provenance": "stackv2-0005.json.gz:12911",
"repo_name": "stephaneAG/hhpc",
"revision_date": "2013-05-08T12:40:43",
"revision_id": "90e6a9661bb634050b13963cfd69dd6c0411ba11",
"snapshot_id": "e98cf876daa55147cc8e167f232dc8f7ae26d523",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/stephaneAG/hhpc/90e6a9661bb634050b13963cfd69dd6c0411ba11/hhpc.c",
"visit_date": "2021-01-15T15:58:04.441989"
} | stackv2 | /**
* Copyright (c) 2013 Nicolas Hillegeer <nicolas at hillegeer dot com>
* 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 THE AUTHOR ``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 <X11/X.h>
#include <X11/Xlib.h>
#include <sys/select.h>
#include <sys/time.h>
#include <signal.h>
#include <time.h>
#include <getopt.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static int gIdleTimeout = 1;
static int gVerbose = 0;
static sig_atomic_t working;
static void signalHandler(int signo) {
working = 0;
}
static int setupSignals() {
struct sigaction act;
memset(&act, 0, sizeof(struct sigaction));
/* Use the sa_sigaction field because the handles has two additional parameters */
act.sa_handler = signalHandler;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
if (sigaction(SIGTERM, &act, NULL) == -1) {
perror("hhpc: could not register SIGTERM");
return 0;
}
if (sigaction(SIGHUP, &act, NULL) == -1) {
perror("hhpc: could not register SIGHUP");
return 0;
}
if (sigaction(SIGINT, &act, NULL) == -1) {
perror("hhpc: could not register SIGINT");
return 0;
}
if (sigaction(SIGQUIT, &act, NULL) == -1) {
perror("hhpc: could not register SIGQUIT");
return 0;
}
return 1;
}
/**
* milliseconds over 1000 will be ignored
*/
static void delay(time_t sec, long msec) {
struct timespec sleep;
sleep.tv_sec = sec;
sleep.tv_nsec = (msec % 1000) * 1000 * 1000;
if (nanosleep(&sleep, NULL) == -1) {
signalHandler(0);
}
}
/**
* generates an empty cursor,
* don't forget to destroy the cursor with XFreeCursor
*
* do we need to use XAllocColor or will it always just work
* as I've observed?
*/
static Cursor nullCursor(Display *dpy, Drawable dw) {
XColor color = { 0 };
Pixmap pixmap = XCreatePixmap(dpy, dw, 1, 1, 1);
Cursor cursor = XCreatePixmapCursor(dpy, pixmap, pixmap, &color, &color, 0, 0);
XFreePixmap(dpy, pixmap);
return cursor;
}
/**
* returns 0 for failure, 1 for success
*/
static int grabPointer(Display *dpy, Window win, Cursor cursor, unsigned int mask) {
int rc;
/**
* retry until we actually get the pointer (with a suitable delay)
* or we get an error we can't recover from.
*/
while (1) {
rc = XGrabPointer(dpy, win, False, mask, GrabModeAsync, GrabModeAsync, win, cursor, CurrentTime);
switch (rc) {
case GrabSuccess:
if (gVerbose) fprintf(stderr, "hhpc: succesfully grabbed mouse pointer\n");
return 1;
case AlreadyGrabbed:
if (gVerbose) fprintf(stderr, "hhpc: XGrabPointer: already grabbed mouse pointer, retrying with delay\n");
delay(0, 500);
break;
case GrabFrozen:
fprintf(stderr, "hhpc: XGrabPointer: grab was frozen, exiting\n");
return 0;
case GrabInvalidTime:
fprintf(stderr, "hhpc: XGrabPointer: invalid time, exiting\n");
return 0;
default:
fprintf(stderr, "hhpc: XGrabPointer: could not grab mouse pointer (%d), exiting\n", rc);
return 0;
}
}
}
static void waitForMotion(Display *dpy, Window win, int timeout) {
int ready = 0;
int xfd = ConnectionNumber(dpy);
unsigned int mask = PointerMotionMask | ButtonPressMask; /* ButtonPressMask */
fd_set fds;
XEvent event;
Cursor emptyCursor = nullCursor(dpy, win);
working = 1;
if (!setupSignals()) {
fprintf(stderr, "hhpc: could not register signals, program will not exit cleanly\n");
}
while (working) {
if (!grabPointer(dpy, win, emptyCursor, mask)) {
return;
}
/* add the X11 fd to the fdset so we can poll/select on it */
FD_ZERO(&fds);
FD_SET(xfd, &fds);
ready = select(xfd + 1, &fds, NULL, NULL, NULL);
if (ready > 0) {
if (gVerbose) fprintf(stderr, "hhpc: event received\n");
/* event received, release mouse, sleep, and try to grab again */
XUngrabPointer(dpy, CurrentTime);
/* drain events */
while (XPending(dpy)) {
/* XNextEvent(dpy, &event); */
XMaskEvent(dpy, mask, &event);
if (gVerbose) fprintf(stderr, "hhpc: draining event\n");
}
if (gVerbose) fprintf(stderr, "hhpc: ungrabbing and sleeping\n");
delay(timeout, 0);
}
else if (ready == 0) {
if (gVerbose) fprintf(stderr, "hhpc: timeout\n");
}
else {
perror("hhpc: error while select()'ing, retrying");
}
}
XUngrabPointer(dpy, CurrentTime);
XFreeCursor(dpy, emptyCursor);
}
static int parseOptions(int argc, char *argv[]) {
int option = 0;
while ((option = getopt(argc, argv, "i:v")) != -1) {
switch (option) {
case 'i': gIdleTimeout = atoi(optarg); break;
case 'v': gVerbose = 1; break;
default: return 0;
}
}
return 1;
}
static void usage() {
printf("hhpc [-i] seconds [-v]\n");
}
int main(int argc, char *argv[]) {
if (!parseOptions(argc, argv)) {
usage();
return 1;
}
Display *dpy = XOpenDisplay(NULL);
int scr = DefaultScreen(dpy);
Window rootwin = RootWindow(dpy, scr);
if (gVerbose) fprintf(stderr, "hhpc: got root window, screen = %d, display = %p, rootwin = %d\n", scr, (void *) dpy, (int) rootwin);
waitForMotion(dpy, rootwin, gIdleTimeout);
XCloseDisplay(dpy);
if (gVerbose) fprintf(stderr, "hhpc: resources released, exiting...\n");
return 0;
}
| 2.09375 | 2 |
2024-11-18T17:55:17.619889+00:00 | 2023-08-17T09:01:57 | 3d8835b5190e9e0ef25a44e3dc1cf92d0abb44d3 | {
"blob_id": "3d8835b5190e9e0ef25a44e3dc1cf92d0abb44d3",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-17T09:01:57",
"content_id": "34fe7a6b4ddcd4f94b79ff1f908801a6a0071b18",
"detected_licenses": [
"MIT"
],
"directory_id": "9ca19ee62e2c985be413bd12e5eb63b44833750d",
"extension": "c",
"filename": "consoleio.c",
"fork_events_count": 43,
"gha_created_at": "2013-08-12T07:50:31",
"gha_event_created_at": "2023-08-21T16:36:56",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 12050604,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1617,
"license": "MIT",
"license_type": "permissive",
"path": "/src/platform/arm-stm32l1xx-discovery/consoleio.c",
"provenance": "stackv2-0005.json.gz:13167",
"repo_name": "MitchBradley/cforth",
"revision_date": "2023-08-17T09:01:57",
"revision_id": "bae39263f2615e1d260426e3eca0ab32816f54ef",
"snapshot_id": "4cb523847c552b2e32e5e50a328b8e263a074d85",
"src_encoding": "UTF-8",
"star_events_count": 142,
"url": "https://raw.githubusercontent.com/MitchBradley/cforth/bae39263f2615e1d260426e3eca0ab32816f54ef/src/platform/arm-stm32l1xx-discovery/consoleio.c",
"visit_date": "2023-08-31T17:23:00.037535"
} | stackv2 | // #define VCOM
// Character I/O stubs
#include "stm32l1xx_conf.h"
USART_TypeDef *consoleUart;
void raw_putchar(char c)
{
while(!USART_GetFlagStatus(consoleUart, USART_FLAG_TXE))
;
USART_SendData(consoleUart, (uint16_t)c);
}
int kbhit() {
return USART_GetFlagStatus(consoleUart, USART_FLAG_RXNE);
}
int getkey()
{
int c;
while (!kbhit())
;
return USART_ReceiveData(consoleUart);
}
void init_io()
{
consoleUart = USART1;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE); // PA9 and PA10
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1);
GPIO_InitTypeDef gpioInit = {
.GPIO_Mode = GPIO_Mode_AF,
.GPIO_PuPd = GPIO_PuPd_NOPULL,
.GPIO_OType = GPIO_OType_PP,
.GPIO_Speed = GPIO_Speed_400KHz
};
gpioInit.GPIO_Pin = GPIO_Pin_9;
GPIO_Init(GPIOA, &gpioInit);
gpioInit.GPIO_Pin = GPIO_Pin_10;
GPIO_Init(GPIOA, &gpioInit);
USART_InitTypeDef uartInit = {
.USART_BaudRate = 115200,
.USART_WordLength = USART_WordLength_8b,
.USART_StopBits = USART_StopBits_1,
.USART_Parity = USART_Parity_No,
.USART_Mode = USART_Mode_Rx | USART_Mode_Tx,
.USART_HardwareFlowControl = USART_HardwareFlowControl_None
};
USART_Init(consoleUart, &uartInit);
USART_Cmd(consoleUart, ENABLE);
init_systick();
}
void wfi(void)
{
__WFI();
}
extern int ms_tick;
int get_msecs(void)
{
return ms_tick;
}
int spins(int i)
{
while(i--)
asm(""); // The asm("") prevents optimize-to-nothing
}
| 2.203125 | 2 |
2024-11-18T17:55:20.011216+00:00 | 2023-07-04T05:51:52 | a20dc75a674f3d203edae918d34aba329966be11 | {
"blob_id": "a20dc75a674f3d203edae918d34aba329966be11",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-04T06:49:36",
"content_id": "21bf9d8fafcd7858bae754a47833278b941fca15",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "3d7dece5254e42059e8a2cb1e72b295460284983",
"extension": "c",
"filename": "lv_gpu_sdl_draw_arc.c",
"fork_events_count": 0,
"gha_created_at": "2018-09-21T10:56:08",
"gha_event_created_at": "2018-09-21T10:56:09",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 149751180,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5909,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/components/py_engine/engine/lib/lv_bindings/lvgl/src/gpu/sdl/lv_gpu_sdl_draw_arc.c",
"provenance": "stackv2-0005.json.gz:14321",
"repo_name": "windowxia/AliOS-Things",
"revision_date": "2023-07-04T05:51:52",
"revision_id": "a99f20706f9c666903a12a205edce13263b1fadb",
"snapshot_id": "172639d6e0d2b2e2e816bce757cf95e89187c132",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/windowxia/AliOS-Things/a99f20706f9c666903a12a205edce13263b1fadb/components/py_engine/engine/lib/lv_bindings/lvgl/src/gpu/sdl/lv_gpu_sdl_draw_arc.c",
"visit_date": "2023-09-01T06:03:57.853390"
} | stackv2 | /**
* @file lv_gpu_sdl_draw_arc.c
*
* This implementation does not functioning properly so it's not enabled
*
*/
/*********************
* INCLUDES
*********************/
#include "../../lv_conf_internal.h"
#if LV_USE_GPU_SDL
#include "../../hal/lv_hal_disp.h"
#include "../../core/lv_refr.h"
#include "../../draw/lv_draw_arc.h"
#include "lv_gpu_sdl_utils.h"
#include "lv_gpu_sdl_lru.h"
#include "lv_gpu_sdl_texture_cache.h"
#include "lv_gpu_sdl_mask.h"
#ifndef M_PI
#include <math.h>
#endif
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_gpu_cache_key_magic_t magic;
uint16_t radius;
uint16_t angle;
lv_coord_t width;
uint8_t rounded;
} lv_draw_arc_key_t;
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_arc2(lv_coord_t center_x, lv_coord_t center_y, uint16_t radius, uint16_t start_angle, uint16_t end_angle,
const lv_area_t * clip_area, const lv_draw_arc_dsc_t * dsc)
{
lv_disp_t * disp = _lv_refr_get_disp_refreshing();
lv_disp_drv_t * driver = disp->driver;
SDL_Renderer * renderer = (SDL_Renderer *) driver->user_data;
lv_area_t area_out;
area_out.x1 = center_x - radius;
area_out.y1 = center_y - radius;
area_out.x2 = center_x + radius - 1; /*-1 because the center already belongs to the left/bottom part*/
area_out.y2 = center_y + radius - 1;
lv_area_t area_in;
lv_area_copy(&area_in, &area_out);
area_in.x1 += dsc->width;
area_in.y1 += dsc->width;
area_in.x2 -= dsc->width;
area_in.y2 -= dsc->width;
/*Increase 1 px each side to texture, to have better rotation result*/
lv_area_t texture_area_out;
lv_area_copy(&texture_area_out, &area_out);
lv_area_increase(&texture_area_out, 1, 1);
SDL_Rect area_out_rect, clip_rect;
lv_area_to_sdl_rect(&texture_area_out, &area_out_rect);
lv_area_to_sdl_rect(clip_area, &clip_rect);
lv_draw_arc_key_t key = {
.magic = LV_GPU_CACHE_KEY_MAGIC_ARC,
.radius = radius,
.angle = ((end_angle - start_angle) % 360 + 360) % 360,
.width = dsc->width,
.rounded = dsc->rounded,
};
// SDL_Texture *texture = lv_gpu_draw_cache_get(&key, sizeof(key));
SDL_Texture * texture = NULL;
if(texture == NULL) {
/*Create inner the mask*/
lv_draw_mask_radius_param_t mask_in_param;
lv_draw_mask_radius_init(&mask_in_param, &area_in, LV_RADIUS_CIRCLE, true);
int16_t mask_in_id = lv_draw_mask_add(&mask_in_param, NULL);
lv_draw_mask_radius_param_t mask_out_param;
lv_draw_mask_radius_init(&mask_out_param, &area_out, LV_RADIUS_CIRCLE, false);
int16_t mask_out_id = lv_draw_mask_add(&mask_out_param, NULL);
SDL_Surface * ark_mask;
if(key.angle < 360) {
while(start_angle >= 360) start_angle -= 360;
while(end_angle >= 360) end_angle -= 360;
lv_draw_mask_angle_param_t mask_angle_param;
lv_draw_mask_angle_init(&mask_angle_param, center_x, center_y, 0, key.angle);
int16_t mask_angle_id = lv_draw_mask_add(&mask_angle_param, NULL);
ark_mask = lv_sdl_apply_mask_surface(&texture_area_out, NULL, 0);
lv_draw_mask_remove_id(mask_angle_id);
}
else {
ark_mask = lv_sdl_apply_mask_surface(&texture_area_out, NULL, 0);
}
lv_draw_mask_remove_id(mask_out_id);
lv_draw_mask_remove_id(mask_in_id);
if(dsc->rounded) {
SDL_Renderer * mask_renderer = SDL_CreateSoftwareRenderer(ark_mask);
lv_area_t cap_area = {.x1 = 0, .y1 = 0};
lv_area_set_width(&cap_area, dsc->width);
lv_area_set_height(&cap_area, dsc->width);
lv_draw_mask_radius_param_t mask_rout_param;
lv_draw_mask_radius_init(&mask_rout_param, &cap_area, LV_RADIUS_CIRCLE, false);
int16_t mask_rout_id = lv_draw_mask_add(&mask_rout_param, NULL);
SDL_Texture * round_texture = lv_sdl_gen_mask_texture(mask_renderer, &cap_area, &mask_rout_id, 1);
lv_draw_mask_remove_id(mask_rout_id);
SDL_SetTextureBlendMode(round_texture, SDL_BLENDMODE_BLEND);
float mid_point = radius - key.width / 2.0f;
SDL_Rect cap_dst;
cap_dst.w = lv_area_get_width(&cap_area);
cap_dst.h = lv_area_get_height(&cap_area);
cap_dst.x = mid_point + lv_sdl_round(SDL_cos(0) * mid_point);
cap_dst.y = mid_point + lv_sdl_round(SDL_sin(0) * mid_point);
SDL_RenderCopy(mask_renderer, round_texture, NULL, &cap_dst);
cap_dst.x = mid_point + lv_sdl_round(SDL_cos(key.angle * M_PI / 180.0f) * mid_point);
cap_dst.y = mid_point + lv_sdl_round(SDL_sin(key.angle * M_PI / 180.0f) * mid_point);
SDL_RenderCopy(mask_renderer, round_texture, NULL, &cap_dst);
SDL_DestroyTexture(round_texture);
SDL_DestroyRenderer(mask_renderer);
}
texture = SDL_CreateTextureFromSurface(renderer, ark_mask);
SDL_FreeSurface(ark_mask);
SDL_assert(texture);
// lv_gpu_draw_cache_put(&key, sizeof(key), texture);
}
SDL_Color arc_color;
lv_color_to_sdl_color(&dsc->color, &arc_color);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
SDL_SetTextureAlphaMod(texture, dsc->opa);
SDL_SetTextureColorMod(texture, arc_color.r, arc_color.g, arc_color.b);
SDL_RenderSetClipRect(renderer, &clip_rect);
SDL_RenderCopyEx(renderer, texture, NULL, &area_out_rect, start_angle, NULL, SDL_FLIP_NONE);
SDL_DestroyTexture(texture);
}
#endif /*LV_USE_GPU_SDL*/
| 2.453125 | 2 |
2024-11-18T17:55:22.253120+00:00 | 2019-07-21T01:02:33 | 9193b62f1d6f9f6f02c16cf6a1abc3a4869c8791 | {
"blob_id": "9193b62f1d6f9f6f02c16cf6a1abc3a4869c8791",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-21T01:02:33",
"content_id": "afbf61a25db60c980baf83612f106a5e74dc7027",
"detected_licenses": [
"MIT"
],
"directory_id": "d0f2a76f1c235e25f31b6fde48b70f38022712f2",
"extension": "c",
"filename": "0805.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": 729,
"license": "MIT",
"license_type": "permissive",
"path": "/chapter08/exercise/0805.c",
"provenance": "stackv2-0005.json.gz:15219",
"repo_name": "FlatterKang/crash.course.c",
"revision_date": "2019-07-21T01:02:33",
"revision_id": "a7afbdf743fdf4b894c777141eb27433189b1f6f",
"snapshot_id": "068445460406bdb8c3e051126032407b7288e0d4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/FlatterKang/crash.course.c/a7afbdf743fdf4b894c777141eb27433189b1f6f/chapter08/exercise/0805.c",
"visit_date": "2020-06-23T06:05:38.957777"
} | stackv2 | #include <stdio.h>
enum Month {JANUARY = 1, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY,
AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
};
int main(void) {
int month;
printf("请输入月份:"); scanf("%d", &month);
switch (month) {
case MARCH:
case APRIL:
case MAY: printf("%d月是春季\n", month); break;
case JUNE:
case JULY:
case AUGUST: printf("%d月是夏季\n", month); break;
case SEPTEMBER:
case OCTOBER:
case NOVEMBER: printf("%d月是秋季\n", month); break;
case DECEMBER:
case JANUARY:
case FEBRUARY: printf("%d月是冬季\n", month); break;
default: printf("您输入的月份不正确\n"); break;
}
return 0;
} | 3.359375 | 3 |
2024-11-18T17:55:22.792753+00:00 | 2014-10-22T12:37:58 | a3635e000b42480a63ef18a533c391afda646931 | {
"blob_id": "a3635e000b42480a63ef18a533c391afda646931",
"branch_name": "refs/heads/master",
"committer_date": "2014-10-22T12:37:58",
"content_id": "53261367ee736df0782b34b06ef495751050579d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "443b4e8652a8c2c404a56008298efc810214c682",
"extension": "c",
"filename": "gfal_common_err_helpers.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 25583198,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1529,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/core/common/gfal_common_err_helpers.c",
"provenance": "stackv2-0005.json.gz:15603",
"repo_name": "adevress/gfal2",
"revision_date": "2014-10-22T12:37:58",
"revision_id": "ce8945d1c153e26c5d10ad43d1940b8dcace0579",
"snapshot_id": "c52dc63c420748b6bfca239cfe1a73a7c2f9445a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/adevress/gfal2/ce8945d1c153e26c5d10ad43d1940b8dcace0579/src/core/common/gfal_common_err_helpers.c",
"visit_date": "2021-01-01T15:45:10.931412"
} | stackv2 | #include <stdarg.h>
#include <stdio.h>
#include <logger/gfal_logger.h>
#include "gfal_common_err_helpers.h"
#if (GLIB_CHECK_VERSION(2,16,0) != TRUE)
#include "future/glib.h"
#endif
void gfal2_set_error(GError **err, GQuark domain, gint code,
const gchar *function, const gchar *format, ...)
{
char buffer[512];
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
if (gfal_get_verbose() & GFAL_VERBOSE_DEBUG)
g_set_error(err, domain, code, "[%s] %s", function, buffer);
else
g_set_error_literal(err, domain, code, buffer);
}
void gfal2_propagate_prefixed_error_extended(GError **dest, GError *src,
const gchar *function, const gchar *format, ...)
{
if (dest == NULL) {
g_error_free(src);
return;
}
if (gfal_get_verbose() & GFAL_VERBOSE_DEBUG) {
if (src->message[0] == '[')
g_propagate_prefixed_error(dest, src, "[%s]", function);
else
g_propagate_prefixed_error(dest, src, "[%s] ", function);
}
else {
*dest = src;
}
if (format != NULL) {
char buffer[512];
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
g_prefix_error(dest, "%s", buffer);
}
}
void gfal2_propagate_prefixed_error(GError **dest, GError *src,
const gchar *function)
{
gfal2_propagate_prefixed_error_extended(dest, src, function, NULL);
}
| 2.15625 | 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.