language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/*
* WHATWG Encoding API built-ins
*
* API specification: https://encoding.spec.whatwg.org/#api
* Web IDL: https://www.w3.org/TR/WebIDL/
*/
#include "duk_internal.h"
/*
* Data structures for encoding/decoding
*/
typedef struct {
duk_uint8_t *out; /* where to write next byte(s) */
duk_codepoint_t lead; /* lead surrogate */
} duk__encode_context;
typedef struct {
/* UTF-8 decoding state */
duk_codepoint_t codepoint; /* built up incrementally */
duk_uint8_t upper; /* max value of next byte (decode error otherwise) */
duk_uint8_t lower; /* min value of next byte (ditto) */
duk_uint8_t needed; /* how many more bytes we need */
duk_uint8_t bom_handled; /* BOM seen or no longer expected */
/* Decoder configuration */
duk_uint8_t fatal;
duk_uint8_t ignore_bom;
} duk__decode_context;
/* The signed duk_codepoint_t type is used to signal a decoded codepoint
* (>= 0) or various other states using negative values.
*/
#define DUK__CP_CONTINUE (-1) /* continue to next byte, no completed codepoint */
#define DUK__CP_ERROR (-2) /* decoding error */
#define DUK__CP_RETRY (-3) /* decoding error; retry last byte */
/*
* Raw helpers for encoding/decoding
*/
/* Emit UTF-8 (= CESU-8) encoded U+FFFD (replacement char), i.e. ef bf bd. */
DUK_LOCAL duk_uint8_t *duk__utf8_emit_repl(duk_uint8_t *ptr) {
*ptr++ = 0xef;
*ptr++ = 0xbf;
*ptr++ = 0xbd;
return ptr;
}
DUK_LOCAL void duk__utf8_decode_init(duk__decode_context *dec_ctx) {
/* (Re)init the decoding state of 'dec_ctx' but leave decoder
* configuration fields untouched.
*/
dec_ctx->codepoint = 0x0000L;
dec_ctx->upper = 0xbf;
dec_ctx->lower = 0x80;
dec_ctx->needed = 0;
dec_ctx->bom_handled = 0;
}
DUK_LOCAL duk_codepoint_t duk__utf8_decode_next(duk__decode_context *dec_ctx, duk_uint8_t x) {
/*
* UTF-8 algorithm based on the Encoding specification:
* https://encoding.spec.whatwg.org/#utf-8-decoder
*
* Two main states: decoding initial byte vs. decoding continuation
* bytes. Shortest length encoding is validated by restricting the
* allowed range of first continuation byte using 'lower' and 'upper'.
*/
if (dec_ctx->needed == 0) {
/* process initial byte */
if (x <= 0x7f) {
/* U+0000-U+007F, 1 byte (ASCII) */
return (duk_codepoint_t) x;
} else if (x >= 0xc2 && x <= 0xdf) {
/* U+0080-U+07FF, 2 bytes */
dec_ctx->needed = 1;
dec_ctx->codepoint = x & 0x1f;
DUK_ASSERT(dec_ctx->lower == 0x80);
DUK_ASSERT(dec_ctx->upper == 0xbf);
return DUK__CP_CONTINUE;
} else if (x >= 0xe0 && x <= 0xef) {
/* U+0800-U+FFFF, 3 bytes */
if (x == 0xe0) {
dec_ctx->lower = 0xa0;
DUK_ASSERT(dec_ctx->upper == 0xbf);
} else if (x == 0xed) {
DUK_ASSERT(dec_ctx->lower == 0x80);
dec_ctx->upper = 0x9f;
}
dec_ctx->needed = 2;
dec_ctx->codepoint = x & 0x0f;
return DUK__CP_CONTINUE;
} else if (x >= 0xf0 && x <= 0xf4) {
/* U+010000-U+10FFFF, 4 bytes */
if (x == 0xf0) {
dec_ctx->lower = 0x90;
DUK_ASSERT(dec_ctx->upper == 0xbf);
} else if (x == 0xf4) {
DUK_ASSERT(dec_ctx->lower == 0x80);
dec_ctx->upper = 0x8f;
}
dec_ctx->needed = 3;
dec_ctx->codepoint = x & 0x07;
return DUK__CP_CONTINUE;
} else {
/* not a legal initial byte */
return DUK__CP_ERROR;
}
} else {
/* process continuation byte */
if (x >= dec_ctx->lower && x <= dec_ctx->upper) {
dec_ctx->lower = 0x80;
dec_ctx->upper = 0xbf;
dec_ctx->codepoint = (dec_ctx->codepoint << 6) | (x & 0x3f);
if (--dec_ctx->needed > 0) {
/* need more bytes */
return DUK__CP_CONTINUE;
} else {
/* got a codepoint */
duk_codepoint_t ret;
DUK_ASSERT(dec_ctx->codepoint <= 0x10ffffL); /* Decoding rules guarantee. */
ret = dec_ctx->codepoint;
dec_ctx->codepoint = 0x0000L;
dec_ctx->needed = 0;
return ret;
}
} else {
/* We just encountered an illegal UTF-8 continuation byte. This might
* be the initial byte of the next character; if we return a plain
* error status and the decoder is in replacement mode, the character
* will be masked. We still need to alert the caller to the error
* though.
*/
dec_ctx->codepoint = 0x0000L;
dec_ctx->needed = 0;
dec_ctx->lower = 0x80;
dec_ctx->upper = 0xbf;
return DUK__CP_RETRY;
}
}
}
#if defined(DUK_USE_ENCODING_BUILTINS)
DUK_LOCAL void duk__utf8_encode_char(void *udata, duk_codepoint_t codepoint) {
duk__encode_context *enc_ctx;
DUK_ASSERT(codepoint >= 0);
enc_ctx = (duk__encode_context *) udata;
DUK_ASSERT(enc_ctx != NULL);
#if !defined(DUK_USE_PREFER_SIZE)
if (codepoint <= 0x7f && enc_ctx->lead == 0x0000L) {
/* Fast path for ASCII. */
*enc_ctx->out++ = (duk_uint8_t) codepoint;
return;
}
#endif
if (DUK_UNLIKELY(codepoint > 0x10ffffL)) {
/* cannot legally encode in UTF-8 */
codepoint = DUK_UNICODE_CP_REPLACEMENT_CHARACTER;
} else if (codepoint >= 0xd800L && codepoint <= 0xdfffL) {
if (codepoint <= 0xdbffL) {
/* high surrogate */
duk_codepoint_t prev_lead = enc_ctx->lead;
enc_ctx->lead = codepoint;
if (prev_lead == 0x0000L) {
/* high surrogate, no output */
return;
} else {
/* consecutive high surrogates, consider first one unpaired */
codepoint = DUK_UNICODE_CP_REPLACEMENT_CHARACTER;
}
} else {
/* low surrogate */
if (enc_ctx->lead != 0x0000L) {
codepoint =
(duk_codepoint_t) (0x010000L + ((enc_ctx->lead - 0xd800L) << 10) + (codepoint - 0xdc00L));
enc_ctx->lead = 0x0000L;
} else {
/* unpaired low surrogate */
DUK_ASSERT(enc_ctx->lead == 0x0000L);
codepoint = DUK_UNICODE_CP_REPLACEMENT_CHARACTER;
}
}
} else {
if (enc_ctx->lead != 0x0000L) {
/* unpaired high surrogate: emit replacement character and the input codepoint */
enc_ctx->lead = 0x0000L;
enc_ctx->out = duk__utf8_emit_repl(enc_ctx->out);
}
}
/* Codepoint may be original input, a decoded surrogate pair, or may
* have been replaced with U+FFFD.
*/
enc_ctx->out += duk_unicode_encode_xutf8((duk_ucodepoint_t) codepoint, enc_ctx->out);
}
#endif /* DUK_USE_ENCODING_BUILTINS */
/* Shared helper for buffer-to-string using a TextDecoder() compatible UTF-8
* decoder.
*/
DUK_LOCAL duk_ret_t duk__decode_helper(duk_hthread *thr, duk__decode_context *dec_ctx) {
const duk_uint8_t *input;
duk_size_t len = 0;
duk_size_t len_tmp;
duk_bool_t stream = 0;
duk_codepoint_t codepoint;
duk_uint8_t *output;
const duk_uint8_t *in;
duk_uint8_t *out;
DUK_ASSERT(dec_ctx != NULL);
/* Careful with input buffer pointer: any side effects involving
* code execution (e.g. getters, coercion calls, and finalizers)
* may cause a resize and invalidate a pointer we've read. This
* is why the pointer is actually looked up at the last minute.
* Argument validation must still happen first to match WHATWG
* required side effect order.
*/
if (duk_is_undefined(thr, 0)) {
duk_push_fixed_buffer_nozero(thr, 0);
duk_replace(thr, 0);
}
(void) duk_require_buffer_data(thr, 0, &len); /* Need 'len', avoid pointer. */
if (duk_check_type_mask(thr, 1, DUK_TYPE_MASK_UNDEFINED | DUK_TYPE_MASK_NULL | DUK_TYPE_MASK_NONE)) {
/* Use defaults, treat missing value like undefined. */
} else {
duk_require_type_mask(thr,
1,
DUK_TYPE_MASK_UNDEFINED | DUK_TYPE_MASK_NULL | DUK_TYPE_MASK_LIGHTFUNC |
DUK_TYPE_MASK_BUFFER | DUK_TYPE_MASK_OBJECT);
if (duk_get_prop_literal(thr, 1, "stream")) {
stream = duk_to_boolean(thr, -1);
}
}
/* Allowance is 3*len in the general case because all bytes may potentially
* become U+FFFD. If the first byte completes a non-BMP codepoint it will
* decode to a CESU-8 surrogate pair (6 bytes) so we allow 3 extra bytes to
* compensate: (1*3)+3 = 6. Non-BMP codepoints are safe otherwise because
* the 4->6 expansion is well under the 3x allowance.
*
* XXX: As with TextEncoder, need a better buffer allocation strategy here.
*/
if (len >= (DUK_HBUFFER_MAX_BYTELEN / 3) - 3) {
DUK_ERROR_TYPE(thr, DUK_STR_RESULT_TOO_LONG);
DUK_WO_NORETURN(return 0;);
}
output =
(duk_uint8_t *) duk_push_fixed_buffer_nozero(thr, 3 + (3 * len)); /* used parts will be always manually written over */
input = (const duk_uint8_t *) duk_get_buffer_data(thr, 0, &len_tmp);
DUK_ASSERT(input != NULL || len == 0);
if (DUK_UNLIKELY(len != len_tmp)) {
/* Very unlikely but possible: source buffer was resized by
* a side effect when fixed buffer was pushed. Output buffer
* may not be large enough to hold output, so just fail if
* length has changed.
*/
DUK_D(DUK_DPRINT("input buffer resized by side effect, fail"));
goto fail_type;
}
/* From this point onwards it's critical that no side effect occur
* which may disturb 'input': finalizer execution, property accesses,
* active coercions, etc. Even an allocation related mark-and-sweep
* may affect the pointer because it may trigger a pending finalizer.
*/
in = input;
out = output;
while (in < input + len) {
codepoint = duk__utf8_decode_next(dec_ctx, *in++);
if (codepoint < 0) {
if (codepoint == DUK__CP_CONTINUE) {
continue;
}
/* Decoding error with or without retry. */
DUK_ASSERT(codepoint == DUK__CP_ERROR || codepoint == DUK__CP_RETRY);
if (codepoint == DUK__CP_RETRY) {
--in; /* retry last byte */
}
/* replacement mode: replace with U+FFFD */
codepoint = DUK_UNICODE_CP_REPLACEMENT_CHARACTER;
if (dec_ctx->fatal) {
/* fatal mode: throw a TypeError */
goto fail_type;
}
/* Continue with 'codepoint', Unicode replacement. */
}
DUK_ASSERT(codepoint >= 0x0000L && codepoint <= 0x10ffffL);
if (!dec_ctx->bom_handled) {
dec_ctx->bom_handled = 1;
if (codepoint == 0xfeffL && !dec_ctx->ignore_bom) {
continue;
}
}
out += duk_unicode_encode_cesu8((duk_ucodepoint_t) codepoint, out);
DUK_ASSERT(out <= output + (3 + (3 * len)));
}
if (!stream) {
if (dec_ctx->needed != 0) {
/* truncated sequence at end of buffer */
if (dec_ctx->fatal) {
goto fail_type;
} else {
out += duk_unicode_encode_cesu8(DUK_UNICODE_CP_REPLACEMENT_CHARACTER, out);
DUK_ASSERT(out <= output + (3 + (3 * len)));
}
}
duk__utf8_decode_init(dec_ctx); /* Initialize decoding state for potential reuse. */
}
/* Output buffer is fixed and thus stable even if there had been
* side effects (which there shouldn't be).
*/
duk_push_lstring(thr, (const char *) output, (duk_size_t) (out - output));
return 1;
fail_type:
DUK_ERROR_TYPE(thr, DUK_STR_UTF8_DECODE_FAILED);
DUK_WO_NORETURN(return 0;);
}
/*
* Built-in bindings
*/
#if defined(DUK_USE_ENCODING_BUILTINS)
DUK_INTERNAL duk_ret_t duk_bi_textencoder_constructor(duk_hthread *thr) {
/* TextEncoder currently requires no persistent state, so the constructor
* does nothing on purpose.
*/
duk_require_constructor_call(thr);
return 0;
}
DUK_INTERNAL duk_ret_t duk_bi_textencoder_prototype_encoding_getter(duk_hthread *thr) {
duk_push_literal(thr, "utf-8");
return 1;
}
DUK_INTERNAL duk_ret_t duk_bi_textencoder_prototype_encode(duk_hthread *thr) {
duk__encode_context enc_ctx;
duk_size_t len;
duk_size_t final_len;
duk_uint8_t *output;
DUK_ASSERT_TOP(thr, 1);
if (duk_is_undefined(thr, 0)) {
len = 0;
} else {
duk_hstring *h_input;
h_input = duk_to_hstring(thr, 0);
DUK_ASSERT(h_input != NULL);
len = (duk_size_t) DUK_HSTRING_GET_CHARLEN(h_input);
if (len >= DUK_HBUFFER_MAX_BYTELEN / 3) {
DUK_ERROR_TYPE(thr, DUK_STR_RESULT_TOO_LONG);
DUK_WO_NORETURN(return 0;);
}
}
/* Allowance is 3*len because all bytes can potentially be replaced with
* U+FFFD -- which rather inconveniently encodes to 3 bytes in UTF-8.
* Rely on dynamic buffer data pointer stability: no other code has
* access to the data pointer.
*
* XXX: The buffer allocation strategy used here is rather inefficient.
* Maybe switch to a chunk-based strategy, or preprocess the string to
* figure out the space needed ahead of time?
*/
DUK_ASSERT(3 * len >= len);
output = (duk_uint8_t *) duk_push_dynamic_buffer(thr, 3 * len);
if (len > 0) {
DUK_ASSERT(duk_is_string(thr, 0)); /* True if len > 0. */
/* XXX: duk_decode_string() is used to process the input
* string. For standard ECMAScript strings, represented
* internally as CESU-8, this is fine. However, behavior
* beyond CESU-8 is not very strict: codepoints using an
* extended form of UTF-8 are also accepted, and invalid
* codepoint sequences (which are allowed in Duktape strings)
* are not handled as well as they could (e.g. invalid
* continuation bytes may mask following codepoints).
* This is how ECMAScript code would also see such strings.
* Maybe replace duk_decode_string() with an explicit strict
* CESU-8 decoder here?
*/
enc_ctx.lead = 0x0000L;
enc_ctx.out = output;
duk_decode_string(thr, 0, duk__utf8_encode_char, (void *) &enc_ctx);
if (enc_ctx.lead != 0x0000L) {
/* unpaired high surrogate at end of string */
enc_ctx.out = duk__utf8_emit_repl(enc_ctx.out);
DUK_ASSERT(enc_ctx.out <= output + (3 * len));
}
/* The output buffer is usually very much oversized, so shrink it to
* actually needed size. Pointer stability assumed up to this point.
*/
DUK_ASSERT_TOP(thr, 2);
DUK_ASSERT(output == (duk_uint8_t *) duk_get_buffer_data(thr, -1, NULL));
final_len = (duk_size_t) (enc_ctx.out - output);
duk_resize_buffer(thr, -1, final_len);
/* 'output' and 'enc_ctx.out' are potentially invalidated by the resize. */
} else {
final_len = 0;
}
/* Standard WHATWG output is a Uint8Array. Here the Uint8Array will
* be backed by a dynamic buffer which differs from e.g. Uint8Arrays
* created as 'new Uint8Array(N)'. ECMAScript code won't see the
* difference but C code will. When bufferobjects are not supported,
* returns a plain dynamic buffer.
*/
#if defined(DUK_USE_BUFFEROBJECT_SUPPORT)
duk_push_buffer_object(thr, -1, 0, final_len, DUK_BUFOBJ_UINT8ARRAY);
#endif
return 1;
}
DUK_INTERNAL duk_ret_t duk_bi_textdecoder_constructor(duk_hthread *thr) {
duk__decode_context *dec_ctx;
duk_bool_t fatal = 0;
duk_bool_t ignore_bom = 0;
DUK_ASSERT_TOP(thr, 2);
duk_require_constructor_call(thr);
if (!duk_is_undefined(thr, 0)) {
/* XXX: For now ignore 'label' (encoding identifier). */
duk_to_string(thr, 0);
}
if (!duk_is_null_or_undefined(thr, 1)) {
if (duk_get_prop_literal(thr, 1, "fatal")) {
fatal = duk_to_boolean(thr, -1);
}
if (duk_get_prop_literal(thr, 1, "ignoreBOM")) {
ignore_bom = duk_to_boolean(thr, -1);
}
}
duk_push_this(thr);
/* The decode context is not assumed to be zeroed; all fields are
* initialized explicitly.
*/
dec_ctx = (duk__decode_context *) duk_push_fixed_buffer(thr, sizeof(duk__decode_context));
dec_ctx->fatal = (duk_uint8_t) fatal;
dec_ctx->ignore_bom = (duk_uint8_t) ignore_bom;
duk__utf8_decode_init(dec_ctx); /* Initializes remaining fields. */
duk_put_prop_literal(thr, -2, DUK_INTERNAL_SYMBOL("Context"));
return 0;
}
/* Get TextDecoder context from 'this'; leaves garbage on stack. */
DUK_LOCAL duk__decode_context *duk__get_textdecoder_context(duk_hthread *thr) {
duk__decode_context *dec_ctx;
duk_push_this(thr);
duk_get_prop_literal(thr, -1, DUK_INTERNAL_SYMBOL("Context"));
dec_ctx = (duk__decode_context *) duk_require_buffer(thr, -1, NULL);
DUK_ASSERT(dec_ctx != NULL);
return dec_ctx;
}
DUK_INTERNAL duk_ret_t duk_bi_textdecoder_prototype_shared_getter(duk_hthread *thr) {
duk__decode_context *dec_ctx;
duk_int_t magic;
dec_ctx = duk__get_textdecoder_context(thr);
magic = duk_get_current_magic(thr);
switch (magic) {
case 0:
/* Encoding is now fixed, so _Context lookup is only needed to
* validate the 'this' binding (TypeError if not TextDecoder-like).
*/
duk_push_literal(thr, "utf-8");
break;
case 1:
duk_push_boolean(thr, dec_ctx->fatal);
break;
default:
duk_push_boolean(thr, dec_ctx->ignore_bom);
break;
}
return 1;
}
DUK_INTERNAL duk_ret_t duk_bi_textdecoder_prototype_decode(duk_hthread *thr) {
duk__decode_context *dec_ctx;
dec_ctx = duk__get_textdecoder_context(thr);
return duk__decode_helper(thr, dec_ctx);
}
#endif /* DUK_USE_ENCODING_BUILTINS */
/*
* Internal helper for Node.js Buffer
*/
/* Internal helper used for Node.js Buffer .toString(). Value stack convention
* is currently odd: it mimics TextDecoder .decode() so that argument must be at
* index 0, and decode options (not present for Buffer) at index 1. Return value
* is a Duktape/C function return value.
*/
DUK_INTERNAL duk_ret_t duk_textdecoder_decode_utf8_nodejs(duk_hthread *thr) {
duk__decode_context dec_ctx;
dec_ctx.fatal = 0; /* use replacement chars */
dec_ctx.ignore_bom = 1; /* ignore BOMs (matches Node.js Buffer .toString()) */
duk__utf8_decode_init(&dec_ctx);
return duk__decode_helper(thr, &dec_ctx);
}
|
C
|
#include <stdio.h>
int main(){
double notas[12]= {100, 50, 20, 10, 5, 2,1, 0.50, 0.25, 0.10, 0.05, 0.01};
double valor;
int i;
scanf("%lf",&valor);
for(i = 0; i<12 ; i++){
int n=0;
if(valor>=notas[i]){
n=valor/notas[i];
valor = valor - n*notas[i];
if(notas[i]<2){
valor = valor + 0.00001;
}
}
if(notas[i]==100){
printf("NOTAS:\n");
}
if(notas[i]==1){
printf("MOEDAS:\n");
}
if(notas[i]>1){
printf("%d nota(s) de R$ %.2lf\n",n,notas[i]);
}else{
printf("%d moeda(s) de R$ %.2lf\n",n,notas[i]);
}
}
return 0;
}
|
C
|
#pragma once
#ifndef __WALL_H_
#define __WALL_H_
struct wall_t
{
float left;
float right;
float top;
float bottom;
void init(ivec2 size);
};
inline void wall_t::init(ivec2 size)
{
if (size.x >= size.y)
{
float aspect = size.x / (float)size.y;
left = -1.0f * aspect;
right = 1.0f * aspect;
top = 1.0f;
bottom = -1.0f;
}
else if (size.y > size.x)
{
float aspect = size.y / (float)size.x;
left = -1.0f;
right = 1.0f;
top = 1.0f * aspect;
bottom = -1.0f * aspect;
}
}
#endif
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct temac_local {int /*<<< orphan*/ indirect_mutex; } ;
struct net_device {int* dev_addr; } ;
/* Variables and functions */
int /*<<< orphan*/ ETH_ALEN ;
int /*<<< orphan*/ XTE_UAW0_OFFSET ;
int /*<<< orphan*/ XTE_UAW1_OFFSET ;
int /*<<< orphan*/ is_valid_ether_addr (int*) ;
int /*<<< orphan*/ memcpy (int*,void*,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ mutex_lock (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ mutex_unlock (int /*<<< orphan*/ *) ;
struct temac_local* netdev_priv (struct net_device*) ;
int /*<<< orphan*/ random_ether_addr (int*) ;
int /*<<< orphan*/ temac_indirect_out32 (struct temac_local*,int /*<<< orphan*/ ,int) ;
__attribute__((used)) static int temac_set_mac_address(struct net_device *ndev, void *address)
{
struct temac_local *lp = netdev_priv(ndev);
if (address)
memcpy(ndev->dev_addr, address, ETH_ALEN);
if (!is_valid_ether_addr(ndev->dev_addr))
random_ether_addr(ndev->dev_addr);
/* set up unicast MAC address filter set its mac address */
mutex_lock(&lp->indirect_mutex);
temac_indirect_out32(lp, XTE_UAW0_OFFSET,
(ndev->dev_addr[0]) |
(ndev->dev_addr[1] << 8) |
(ndev->dev_addr[2] << 16) |
(ndev->dev_addr[3] << 24));
/* There are reserved bits in EUAW1
* so don't affect them Set MAC bits [47:32] in EUAW1 */
temac_indirect_out32(lp, XTE_UAW1_OFFSET,
(ndev->dev_addr[4] & 0x000000ff) |
(ndev->dev_addr[5] << 8));
mutex_unlock(&lp->indirect_mutex);
return 0;
}
|
C
|
#include "Funciones.h"
#include "Validaciones.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int mostrarMenuABM(void)
{
char entrada[10];
int opcion;
printf("BIENVENIDOS: \n\n");
printf("1. Cargar los datos de los empleados desde el archivo data.csv (modo texto).");
printf("\n2. Cargar los datos de los empleados desde el archivo data.csv (modo binario). ");
printf("\n3. Alta de empleado. ");
printf("\n4. Modificar datos de empleado.");
printf("\n5. Baja de empleado.");
printf("\n6. Listar empleados. ");
printf("\n7. Ordenar empleados. ");
printf("\n8. Guardar los datos de los empleados en el archivo data.csv (modo texto).");
printf("\n9. Guardar los datos de los empleados en el archivo data.csv (modo binario).");
printf("\n10. Salir.");
printf("\n\nOpcion elegida:");
fflush(stdin);
gets(entrada);
opcion=validarIntEntreRangos(entrada,1,10);
system("cls");
return opcion;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
/* kernel-XXX.elf получаемое из npk файла напрямую не может быть распакован. xz ругается на повреждение данных!
сравнительный анализ показал что в данных действительно содержится мусор: [ 7F FF 80 00 00 ]
и так каждые 0x8000 байт.
kernel-XXX.elf that obtained from an npk file cannot be directly decompressed. xz reports about data corruption!
A comparative analysis showed that the data does contain the garbage: [7F FF 80 00 00]
and so every 0x8000 bytes.
*/
void die(int code){
fprintf(stderr, "Dieing with exit code = %d\n", code);
exit(code);
}
static unsigned char data[64 * 1024 * 1024];
int main(int argc, char *argv[]){
int fd;
unsigned char *p;
void *last_p, *end;
size_t rest_size;
size_t total_payload_size = 0;
int count = 0;
size_t len;
if(argc !=2)
die(-1);
fd = open(argv[1], O_RDONLY);
if(fd < 0)
die(-2);
memset(data, 0x0, sizeof(data));
len = read(fd, data, sizeof(data));
close(fd);
if(len <= 0)
die(-3);
printf("Successfully readed %zd bytes\n", len);
printf("Begin of search...\n");
end = (void*)data + len;
last_p = data;
p = (void*)data;
//p += 0x2F4D;
do{
if(*(uint64_t *)p == 0x040A000000010007LLU){ //check for kernel start magic value
printf("Kernel start magic is found at: 0x%08lx\n", (void*)data - (void*)p);
last_p = p;
last_p = p = (void*)p + 15;
}
//chunk header(5 bytes)
//if(p[4] == 0x7F && p[3] == 0xFF && p[2] == 0x80 && p[1] == 0x00 && p[0] == 0x00){
//if(p[4] == 0x7F && p[3] == 0xFF && p[0] == 0x00){
if (p[0] == 0 || p[0] == 1) {
int prev_block_size = p != last_p ? ((void*)p - last_p) - 5 : 0;
int hdr_chunk_len = p[2] << 8 | p[1];
total_payload_size += hdr_chunk_len;
if (prev_block_size != 0x8000 && last_p != p)
printf(" !!! Unusual chunk size: %d !!!\n", prev_block_size);
printf("%04d: 0x%08lx: (%d + 5): %02X %02X %02X %02X %02X\n", count++,
((void*)p - (void*)data), hdr_chunk_len,
p[4], p[3], p[2], p[1], p[0]);
last_p = p;
rest_size = end - ((void*)p + 5 + hdr_chunk_len);
if (p[0] == 1)
break;
p += 5 + hdr_chunk_len;
}
//p = (void *)p + 1;
}while((void*)p + 4 < end);
p = end - rest_size;
//printf("Last tailed chunk size: %d + 5: [ %02x %02x ]\n", p[2] << 8 | p[1], p[1], p[2]);
printf("Payload total size is: %zd\n", total_payload_size);
printf("Garbage(tail) size is: %zd\n", rest_size);
printf("Total blocks is: %d\n", count);
printf("...search is Ended\n");
return 0;
}
|
C
|
#include<stdio.h>
#define MAX 10
int MAT[MAX][MAX],A[MAX],Q[MAX];
int n,r=-1,f=0;
void depth(int i,int vis[])
{
if(i!=n){
printf("%d ",A[i]);
vis[i]=1;
for(int j=0;j<n;++j)
if(!vis[j]&&MAT[i][j])
depth(j,vis);
}
}
void breadth(int i,int vis[]){
for(int j=0;j<n;++j)
if(MAT[i][j] && !vis[j])
Q[++r]=A[j];
if(f<=r){
vis[f]=1;
breadth(Q[f++],vis);
}
}
int main(void){
int i,j,ch;
int vis[MAX]={0};
printf("Enter the no.of nodes: ");
scanf("%d",&n);
for(i=0;i<n;++i){
printf("\nEnter the elements: ");
scanf("%d",&A[i]);
}
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;++i)
for(j=0;j<n;++j){
scanf("%d",&MAT[i][j]);
}
while(1){
printf("1. DFS\n2. BFS\n\3. EXIT\n");
scanf("%d",&ch);
for(i=0;i<n;++i)
vis[i]=0;
if(ch==3)
break;
else if(ch==1){
depth(0,vis);
printf("\n");
}
else if(ch==2){
breadth(0,vis);
for(i=0;i<n;++i){
if(vis[i]){
printf("%d ",A[i]);
}
}
printf("\n");
}
else
printf("\nInavalid choice");
}
}
|
C
|
//Creando un Archivo secuencial
#include <stdio.h>
#include <cerrno>
int main(void)
{
int cuenta; /* nmero de cuenta */
char nombre[30]; /* nombre de la cuenta */
double saldo; /* saldo de la cuenta */
errno_t err;
FILE* cfPtr; /* cfPtr = clientes.dat puntero a tipo archivo */
/* fopen_s abre el archivo con seguridad. Sale del programa si no se pudo crear el archivo */
err = fopen_s(&cfPtr, "clientes.dat", "w");
if (err == 0)
{
printf("El archivo 'clientes.dat' fue abierto\n");
printf("%s\n", strerror(errno));
}
else
{
printf("clients.dat' was not opened\n");
printf("%s\n", strerror(errno));
exit(-1); //Aqu podramos salir del programa
}
puts("Introduzca 0 como Numero de cuenta si desea salir del programa\n"); //Usuario puede salir del programa
/*
El while (1) no se usa para nada en especifico salvo para permitir la ejecucin sin limite del contenido del ciclo,
su equivalente en cualquiera de sus derivados seria:
while (true) {
// Cdigo aqu.
}
Se va a mantener ejecutando lo que hay en el bucle hasta que se establezca alguna condicin que lo haga salir
con una instruccin break o alguna similar.
*/
//while (!feof(stdin)) TAMBIN VALDRA
while (1)
{
printf("Introduzca el numero de cuenta: ");
scanf_s("%d", &cuenta);
if (cuenta == 0)
break;
printf("Introduzca el nombre del titular de la cuenta: ");
scanf_s("%s", nombre, 29); //mximo 29 caracteres
printf("Introduzca el saldo de la cuenta: ");
scanf_s("%lf", &saldo);
//printf("Introduzca 0 si desea salir del programa");
//printf("? ");
/* escribir en el archivo los datos de la cuenta, utilizando fprintf() */
fprintf_s(cfPtr, "%d %s %.2f\n", cuenta, nombre, saldo);
} /* end while */
fclose(cfPtr); /* cerrar archivo con fclose() */
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 200000
int custo;
int pai[N];
typedef struct {
int x, y, v;
} Grafo;
Grafo grafo[N];
int cmp(const void *a, const void *b);
void definir(int n);
int buscar(int x);
int unir(int x, int y, int p);
int main() {
int m, n, i;
while(scanf("%d %d", &m, &n) && m && n) {
memset(&grafo, 0, sizeof(grafo));
custo = 0;
for(i = 0; i < n; i++) {
scanf("%d %d %d",&grafo[i].x, &grafo[i].y, &grafo[i].v);
custo += grafo[i].v;
}
definir(m);
qsort(grafo, n, sizeof(grafo[0]), cmp);
for (i = 0; i < n; ++i)
unir(grafo[i].x, grafo[i].y, i);
printf("%d\n",custo);
}
return 0;
}
int cmp(const void *a, const void *b) {
return (*(Grafo *)a).v - (*(Grafo *)b).v;
}
void definir(int n) {
int i;
for (i = 0; i <= n; ++i)
pai[i] = i;
}
int buscar(int x) {
if (pai[x] != x)
pai[x] = buscar(pai[x]);
return pai[x];
}
int unir(int x, int y, int p) {
int i, j;
i = buscar(x);
j = buscar(y);
if (i != j) {
custo -= grafo[p].v;
(i > j) ? (pai[i] = j) : (pai[j] = i);
return 1;
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int ID ,hrs;
float wperh,salary ;
scanf("%d %d %f",&ID,&hrs,&wperh);
salary=hrs*wperh;
printf("NUMBER = %d\nSALARY = U$ %.2f\n",ID,salary);
}
|
C
|
#include<stdio.h>
int main()
{
int A[10][10],B[10][10],i,j,k,l,MULTIPLICATION[10][10],r1,r2,c1,c2;
printf("Enter rows and columns for first matrix:");
scanf("%d %d",&r1,&c1);
printf("Enter rows and columns for the swecond matrix:");
scanf("%d %d",&r2,&c2);
if(c1==r2)
{
printf("Enter elements in first matrix:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("Enter elements in first matrix:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&B[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
for(k=0;k<c2;k++)
{
MULTIPLICATION[i][j] += (A[i][k] * B[k][j]);
}
}
}
for(i=0;i<r1;i++)
{
MULTIPLICATION[i][j]=0;
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("\n\n %d ",MULTIPLICATION[i][j]);
if(j==c2-1)
{
printf("\n\n");
}
}
}
}
else
{
printf("ERROR!! COLUMN OF FIRST MATRIX IS NOT EQUAL TO ROW OF SECOND MATRIX");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
long long N;
scanf("%I64d", &N);
N *= 2;
for(long long i = sqrt(N) - 3; i < sqrt(N) + 3; ++i) {
if(i * (i - 1) < N && N <= i * (i + 1)) {
printf("%I64d\n", N / 2 - (i - 1)*i / 2);
break;
}
}
return 0;
}
|
C
|
/* ----------------------------------------------------------------------
* Project: CMSIS DSP Library
* Title: arm_shift_q31.c
* Description: Shifts the elements of a Q31 vector by a specified number of bits
*
* $Date: 18. March 2019
* $Revision: V1.6.0
*
* Target Processor: Cortex-M cores
* -------------------------------------------------------------------- */
/*
* Copyright (C) 2010-2019 ARM Limited or its affiliates. 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.
*/
#include "arm_math.h"
/**
@ingroup groupMath
*/
/**
@defgroup BasicShift Vector Shift
Shifts the elements of a fixed-point vector by a specified number of bits.
There are separate functions for Q7, Q15, and Q31 data types.
The underlying algorithm used is:
<pre>
pDst[n] = pSrc[n] << shift, 0 <= n < blockSize.
</pre>
If <code>shift</code> is positive then the elements of the vector are shifted to the left.
If <code>shift</code> is negative then the elements of the vector are shifted to the right.
The functions support in-place computation allowing the source and destination
pointers to reference the same memory buffer.
*/
/**
@addtogroup BasicShift
@{
*/
/**
@brief Shifts the elements of a Q31 vector a specified number of bits.
@param[in] pSrc points to the input vector
@param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right.
@param[out] pDst points to the output vector
@param[in] blockSize number of samples in the vector
@return none
@par Scaling and Overflow Behavior
The function uses saturating arithmetic.
Results outside of the allowable Q31 range [0x80000000 0x7FFFFFFF] are saturated.
*/
#if defined(ARM_MATH_MVEI)
#include "arm_helium_utils.h"
void arm_shift_q31(
const q31_t * pSrc,
int8_t shiftBits,
q31_t * pDst,
uint32_t blockSize)
{
uint32_t blkCnt; /* loop counters */
q31x4_t vecSrc;
q31x4_t vecDst;
/* Compute 4 outputs at a time */
blkCnt = blockSize >> 2;
while (blkCnt > 0U)
{
/*
* C = A (>> or <<) shiftBits
* Shift the input and then store the result in the destination buffer.
*/
vecSrc = vld1q((q31_t const *) pSrc);
vecDst = vqshlq_r(vecSrc, shiftBits);
vst1q(pDst, vecDst);
/*
* Decrement the blockSize loop counter
*/
blkCnt--;
/*
* advance vector source and destination pointers
*/
pSrc += 4;
pDst += 4;
}
/*
* tail
*/
blkCnt = blockSize & 3;
if (blkCnt > 0U)
{
mve_pred16_t p0 = vctp32q(blkCnt);
vecSrc = vld1q((q31_t const *) pSrc);
vecDst = vqshlq_r(vecSrc, shiftBits);
vstrwq_p(pDst, vecDst, p0);
}
}
#else
void arm_shift_q31(
const q31_t * pSrc,
int8_t shiftBits,
q31_t * pDst,
uint32_t blockSize)
{
uint32_t blkCnt; /* Loop counter */
uint8_t sign = (shiftBits & 0x80); /* Sign of shiftBits */
#if defined (ARM_MATH_LOOPUNROLL)
q31_t in, out; /* Temporary variables */
/* Loop unrolling: Compute 4 outputs at a time */
blkCnt = blockSize >> 2U;
/* If the shift value is positive then do right shift else left shift */
if (sign == 0U)
{
while (blkCnt > 0U)
{
/* C = A << shiftBits */
/* Shift input and store result in destination buffer. */
in = *pSrc++;
out = in << shiftBits;
if (in != (out >> shiftBits))
out = 0x7FFFFFFF ^ (in >> 31);
*pDst++ = out;
in = *pSrc++;
out = in << shiftBits;
if (in != (out >> shiftBits))
out = 0x7FFFFFFF ^ (in >> 31);
*pDst++ = out;
in = *pSrc++;
out = in << shiftBits;
if (in != (out >> shiftBits))
out = 0x7FFFFFFF ^ (in >> 31);
*pDst++ = out;
in = *pSrc++;
out = in << shiftBits;
if (in != (out >> shiftBits))
out = 0x7FFFFFFF ^ (in >> 31);
*pDst++ = out;
/* Decrement loop counter */
blkCnt--;
}
}
else
{
while (blkCnt > 0U)
{
/* C = A >> shiftBits */
/* Shift input and store results in destination buffer. */
*pDst++ = (*pSrc++ >> -shiftBits);
*pDst++ = (*pSrc++ >> -shiftBits);
*pDst++ = (*pSrc++ >> -shiftBits);
*pDst++ = (*pSrc++ >> -shiftBits);
/* Decrement loop counter */
blkCnt--;
}
}
/* Loop unrolling: Compute remaining outputs */
blkCnt = blockSize % 0x4U;
#else
/* Initialize blkCnt with number of samples */
blkCnt = blockSize;
#endif /* #if defined (ARM_MATH_LOOPUNROLL) */
/* If the shift value is positive then do right shift else left shift */
if (sign == 0U)
{
while (blkCnt > 0U)
{
/* C = A << shiftBits */
/* Shift input and store result in destination buffer. */
*pDst++ = clip_q63_to_q31((q63_t) *pSrc++ << shiftBits);
/* Decrement loop counter */
blkCnt--;
}
}
else
{
while (blkCnt > 0U)
{
/* C = A >> shiftBits */
/* Shift input and store result in destination buffer. */
*pDst++ = (*pSrc++ >> -shiftBits);
/* Decrement loop counter */
blkCnt--;
}
}
}
#endif /* defined(ARM_MATH_MVEI) */
/**
@} end of BasicShift group
*/
|
C
|
#include<stdio.h>
#include<stdlib.h>
int** a;
int cnt[3];
int same(int x, int y, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[x][y] != a[x + i][y + j])return 0;
}
}
return 1;
}
void solve(int x, int y, int n) {
int m = n / 3;
if (same(x, y, n)) {
cnt[a[x][y] + 1]++;
return;
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
solve(x + i*m, y + j*m, m);
}
}
}
int main()
{
int n;
scanf("%d", &n);
a = (int**)malloc(sizeof(int*)*(n + 1));
for (int i = 1; i <= n; i++) a[i] = (int*)malloc(sizeof(int)*(n + 1));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf("%d", &a[i][j]);
}
}
solve(1, 1, n);
printf("%d\n%d\n%d\n", cnt[0], cnt[1], cnt[2]);
return 0;
}
|
C
|
#include <stdio.h>
//change a to "a" in string
#define STRING(a) #a
//combine a and b
#define PASTER(a,b) a##b
int macro2()
{
int nData = 10;
//PASTER(nDa, ta) is same as nData
printf("%d\n", PASTER(nDa, ta));
printf("%d\n", nData);
//STRING(nData) is same as "nData"
printf("%s\n", STRING(nData));
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int i,n;
printf("Type Year");
scanf("%d",&n);
if(n%400==0)
printf("Yes");
else if(n%4==0)
printf("Yes");
else
printf("No");
}
|
C
|
/* NICOLESCU Daniel-Marian - 314CB */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "TStiva-Lista.h"
#include "TCoada-Lista.h"
#include "TInfo.h"
// eliberare informatie
void FreeInfo(void **ae)
{
free(*ae);
*ae = NULL;
}
// eliberare celula
void FreeCel(void **ac)
{
free(*ac);
*ac = NULL;
}
// alocare memorie pentru informatie
void* AlocInfo(size_t d)
{
TInfo *info = (TInfo*)malloc(d);
if(!info)
return NULL;
return (void*)info;
}
// afisarea informatiei de la adresa ae
void PrintInfo(void *ae, FILE *output)
{
fprintf(output, "%c", ((TInfo*)ae)->tip);
}
// verifica daca id-ul parantezei de la ae1 este mai mare decat id-ul
// parantezei de la ae2
int BiggerID(void *ae1, void *ae2)
{
return ((TInfo*)ae1)->id_paranteza > ((TInfo*)ae2)->id_paranteza;
}
// functie folosita pentru Correct
// primul element din stiva de paranteze deschise va avea
// tipul * si id-ul dat ca parametru
void InfoStar(void *ae, size_t id)
{
((TInfo*)ae)->id_paranteza = id;
((TInfo*)ae)->tip = '*';
}
// functie folosita in Correct pentru renumerotarea parantezelor
// renumerotarea parantezelor este folosita pentru a determina lungimea
// unui subsir de paranteze bine inchise
void ChangeID(void *ae, size_t id)
{
((TInfo*)ae)->id_paranteza = id;
}
// verifica daca tipul parantezei de la ae este deschis
int OpenParan(void *ae)
{
return ((TInfo*)ae)->tip == '(' || ((TInfo*)ae)->tip == '[' ||
((TInfo*)ae)->tip == '{';
}
// verifica daca paranteza de la ae1 este deschisa, paranteza de la ae2
// este inchisa si sunt de acelasi tip
int SameType(void *ae1, void *ae2)
{
return (((TInfo*)ae1)->tip == '(' && ((TInfo*)ae2)->tip == ')') ||
(((TInfo*)ae1)->tip == '[' && ((TInfo*)ae2)->tip == ']') ||
(((TInfo*)ae1)->tip == '{' && ((TInfo*)ae2)->tip == '}');
}
// returneaza lungimea subsirului curent
size_t CurrentLen(void *ae1, void *ae2)
{
return ((TInfo*)ae1)->id_paranteza - ((TInfo*)ae2)->id_paranteza;
}
// Correct runumeroteaza parantezele, schimbandu-le id-ul.
// Pentru a putea afla lungimea subsirului maxim corect, introduce
// parantezele deschise intr-o stiva auxiliara, daca intalneste
// vreo paranteza inchisa, face Pop din stiva aux si se verifica daca
// sunt de acelasi tip. Daca sunt de acelasi tip, atunci, pentru a afla
// lungimea subsirului corect curent, se face top pe aux.
// Cand se face top, se va copia fie paranteza anterioara, fie info_star.
// info_star este folosit ca o baza a subsirului corect curent de
// paranteze deschise din aux.
// La inceput, baza stivei aux are id-ul 0. Dupa ce s-a aflat lungimea
// primului subsir corect si/sau se identifica o paranteza pusa gresit, id-ul
// acelei paranteze va fi folosit drept baza pentru noul subsir corect
// ce se poate afla in sirul de paranteze
// _______________ _______________
// Ex: ( [ { [ ] ( [ ] ) { } ] ) [ ] { } ( )
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Primul element din stiva auxiliara este *, cu id-ul 0
// Se introduc cele 4 paranteze deschise in aux:
// * ( [ { [
// 0 1 2 3 4
// paranteza curenta din stiva este ], se extrage o paranteza din aux
// * ( [ {
// 0 1 2 3
// paranteza din sirul de paranteze si cea scoasa din aux sunt de acelasi
// tip, se face top pe aux si se face diferenta dintre id-urile parantezei
// din s si cea copiata cu top. lungimea rezultata este 2.
// se introduc alte 2 paranteze deschise in aux
// * ( [ { ( [
// 0 1 2 3 6 7
// urmatoarea paranteza din s este inchisa, se da pop la aux, sunt de acelasi
// tip, se face top, iar lungimea este 8-6 = 2
// aux devine:
// * ( [ { (
// 0 1 2 3 6
// urmatoarea paranteza din s e si ea inchisa si de acelasi tip cu cea din aux
// Se face top, id-ul parantezei copiate e 5, iar id-ul parantezei din s este 9
// lungimea e astfel 4
// Urmatoarea paranteza din s este deschisa
// * ( [ { {
// 0 1 2 3 10
// urmatoarea paranteza din s este inchisa, de acelasi tip cu cea din aux,
// se da top, iar noua lungime este 11-3 = 8
// aux :
// * ( [
// 0 1 2
// urmatoarea paranteza din s este inchisa, dar de tip diferit fata de cea din
// aux. Se elibereaza celelalte paranteze din aux, iar baza va avea id-ul
// parantezei gresite.
// aux:
// *
// 12
// Urmatoarea paranteza e inchisa, iar stiva aux nu are paranteze
// deschise. aux devine:
// *
// 13
// urmatoarea paranteza din s este deschisa:
// * [
// 13 14
// urmatoarea paranteza din s este inchisa
// lungimea subsirului corect curent este 2 ...
// in final lungimea maxima ramane 8
void Correct(void *s, FILE *output, GetElemF GetElem)
{
AStiva aux = InitS(DIME_S(s));
void *info_s = AlocInfo(DIME_S(s));
void *info_aux = AlocInfo(DIME_S(s));
void *info_star = AlocInfo(DIME_S(s));
void *info_ant = AlocInfo(DIME_S(s));
size_t maxlen = 0;
size_t i = 0;
InfoStar(info_star, 0);
Push(aux, info_star);
while(!VIDA_S(s))
{
++i;
//extrage element din s
GetElem(s, info_s);
//renumeroteaza paranteza
ChangeID(info_s, i);
//daca e paranteza deschisa o introduce in aux
if(OpenParan(info_s))
Push(aux, info_s);
//daca e paranteza inchisa
else
{
Pop(aux, info_aux);
//verfica daca paranteza curenta din s si cea din aux sunt
//de acelasi tip
if(SameType(info_aux, info_s))
{
//se face top pe aux si se determina daca lungimea
//subsirului curent e mai mare decat maximul curent
Top(aux, info_ant);
if(CurrentLen(info_s, info_ant) > maxlen)
maxlen = CurrentLen(info_s, info_ant);
}
else
{
//daca paranteza din s este inchisa dar de tip diferit
//fata de cea din aux, sau aux nu contine paranteze deschise
//se elibereaza stiva aux si id-ul bazei se schimba cu id-ul
//parantezei curente din s
while(!VIDA_S(aux))
Pop(aux, info_s);
ChangeID(info_s, i);
Push(aux, info_s);
}
}
}
FreeS((void**)&aux);
FreeInfo((void**)&info_s);
FreeInfo((void**)&info_aux);
FreeInfo((void**)&info_star);
FreeInfo((void**)&info_ant);
fprintf(output, "%zu\n", maxlen);
}
|
C
|
#include "prog1Functions.h" /*Including our functions and variables*/
int main (int argc, char * argv[])/*argc/argv allows us to pass into main command line arguments to use*/
{
FILE * mazeFilePointer; /*file pointer for opening up our maze txt filesa*/
int z; /*used in our for loop to allocate memory*/
finished = 0; /*setting finished variable to 0 since we do not begin at the exit point*/
mazeFilePointer = fopen(argv[1], "r"); /*opens up txt file from cmd line arg. "r" means we intend to read from it*/
readCoordinates(mazeFilePointer); /*reads our coordinatesa*/
maze = (char**)malloc(sizeof(char*)*rows); /*creates our multi-dimensional array's rows*/
for(z = 0; z < rows; z++) /*loops through our rows and creates our multi-dimensional array's columns*/
{
maze[z] = (char*)malloc(sizeof(char)*columns);
fscanf(mazeFilePointer, "%s ", maze[z]); /*Populating our 2D array with the contents of our maze*/
}
fclose(mazeFilePointer); /*Closing the external file*/
printf("\n\nWelcome to the Maze Traversal Program!\n\n");
printf("The path to the exit is:\n\n");
maze[currentYCoordinate][currentXCoordinate]='W'; /*Since we start at our entry point, we mark it as walked upon*/
while(finished != 1) /*While we haven't reached the exit, finished will stay at 0*/
{
move(); /*We move according to our Rules dictating which way to attempt to step first via the wall follower algorithm*/
checkExit(); /*And we check if we're at the exit*/
}
printMultiDimensionalArray(); /*Then we print our maze when we're at the exit that shows the paath we walked*/
freeMemory(); /*And finally we free our memory and return it to the system*/
return 0;
}
|
C
|
#include <stdio.h>
//function declaration
void subfun();
int main()
{
subfun();
subfun();
subfun();
return 0;
}
//function definition
void subfun()
{
static int st = 1; //static variable declaration
printf("\nst = %d ", st);
st++;
}
|
C
|
//
// T54-spiral-matrix.c
// algorithm
//
// Created by Ankui on 5/4/20.
// Copyright © 2020 Ankui. All rights reserved.
//
// https://leetcode-cn.com/problems/spiral-matrix/
#include "T54-spiral-matrix.h"
#include "algorithm-common.h"
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize) {
*returnSize = 0;
if (matrix == NULL || matrixSize <= 0 || *matrixColSize <= 0) { return NULL; }
int* list = malloc(sizeof(int) * (matrixSize * (*matrixColSize)));
int top = 0;
int right = *matrixColSize - 1;
int left = 0;
int bottom = matrixSize - 1;
while (top <= bottom && left <= right) {
// left top -> right top
for (int i = left; i <= right; i++) {
list[*returnSize] = matrix[top][i];
(*returnSize)++;
}
top++;
// if (top > bottom) break; // CARE!!!
// right top -> right bottom
for (int i = top; i <= bottom; i++) {
list[*returnSize] = matrix[i][right];
(*returnSize)++;
}
right--;
// if (left > right) break; // CARE!!!
if (top > bottom || left > right) {
break;
}
// right bottom -> left bottom
for (int i = right; i >= left; i--) {
list[*returnSize] = matrix[bottom][i];
(*returnSize)++;
}
bottom--;
// left bottom -> left top
for (int i = bottom; i >= top; i--) {
list[*returnSize] = matrix[i][left];
(*returnSize)++;
}
left++;
}
return list;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int VSIZE;
int HSIZE;
//Open specified file, read in occupancy grid, and return grid as 2D int array
int **readOccupancyGrid(char *filename) {
//Result
int **grid;
//Open file
FILE *fin = fopen(filename, "r");
if(fin == NULL) {
fprintf(stderr, "Couldn't open file \'%s\'\n", filename);
exit(EXIT_FAILURE);
}
//Read first two lines of file
char line[BUFSIZ];
fgets(line, BUFSIZ, fin);
fgets(line, BUFSIZ, fin);
int rows, cols;
sscanf(line, "%d %d", &rows, &cols);
VSIZE = rows;
HSIZE = cols;
//Allocate memory for int array
grid = (int **) malloc(sizeof(int *) * rows);
for(int i=0; i<rows; i++) {
grid[i] = (int *) malloc(sizeof(int) * cols);
}
//Read in grid data
int i=0;
while(fgets(line, BUFSIZ, fin) != NULL) {
int k=0;
for(int j=0; j<cols; j++) {
grid[i][j] = line[k]-'0';
k += 2;
}
i++;
}
//Return pointer to array
return grid;
}
//Visit specified square, and recursively visit all adjacent obstacle squares
void visit(bool visited[VSIZE][HSIZE], int **grid, int i, int j, int colors[VSIZE][HSIZE], int color) {
//Check if square is occupied
if(grid[i][j] == 0) return ;
//Visit square, and use recursion to visit all squares adjacent that are obstacles
visited[i][j] = true;
colors[i][j] = color;
if(i-1 >= 0) {
//Visit square above current square
if(!visited[i-1][j]) visit(visited, grid, i-1, j, colors, color);
}
if(i+1 < VSIZE) {
//Visit square below current square
if(!visited[i+1][j]) visit(visited, grid, i+1, j, colors, color);
}
if(j-1 >= 0) {
//Visit square to left of current square
if(!visited[i][j-1]) visit(visited, grid, i, j-1, colors, color);
}
if(j+1 < HSIZE) {
//Visit square to right of current square
if(!visited[i][j+1]) visit(visited, grid, i, j+1, colors, color);
}
}
//Returns true if the specified point is a voronoi point
bool isVoronoiPoint(int i, int j, int k, int **grid, int colors[VSIZE][HSIZE]) {
//Top neighbour is i-1
if(i-1 >= 0) {
//Check if it's been overwritten with k in a different color
if(grid[i-1][j] == k && colors[i-1][j] != colors[i][j] && colors[i-1][j] != 0) {
return true;
}
}
//Right neighbour is j+1
if(j+1 < HSIZE) {
//Check if its been overwritten with k in a different color
if(grid[i][j+1] == k && colors[i][j+1] != colors[i][j] && colors[i][j+1] != 0) {
return true;
}
}
//Else, it's not a voronoi point
return false;
}
//Returns 0 if no neighbours are colored, 1 if all colored neighbours are the same color, 2 if there is more than one color
//Need to consider edges as well; they're considered colored
int getNumColoredNeighbours(int i, int j, int colors[VSIZE][HSIZE]) {
int *neighbourCols = malloc(sizeof(int) * 1);
int k = 0;
int VORONOI = 0;
int PINK = 1;
int BLUE = 2;
int ORANGE = 3;
int YELLOW = 4;
int RED = 5;
int GREEN = 6;
int SILVER = 7;
int GOLD = 8;
//Pixel above
if(i-1 >= 0) {
if(colors[i-1][j] != -1 && colors[i-1][j] != VORONOI) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = colors[i-1][j];
}
}
//Pixel below
if(i+1 < VSIZE) {
if(colors[i+1][j] != -1 && colors[i+1][j] != VORONOI) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = colors[i+1][j];
}
}
//Pixel to the left
if(j-1 >= 0) {
if(colors[i][j-1] != -1 && colors[i][j-1] != VORONOI) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = colors[i][j-1];
}
}
//Pixel to the right
if(j+1 < HSIZE) {
if(colors[i][j+1] != -1 && colors[i][j+1] != VORONOI) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = colors[i][j+1];
}
}
//Pixel above and to the left
if(i-1 >= 0 && j-1 >= 0) {
if(colors[i-1][j-1] != -1 && colors[i-1][j-1] != VORONOI) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = colors[i-1][j-1];
}
}
//Pixel above and to the right
if(i-1 >= 0 && j+1 < HSIZE) {
if(colors[i-1][j+1] != -1 && colors[i-1][j+1] != VORONOI) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = colors[i-1][j+1];
}
}
//Pixel below and to the left
if(j-1 >= 0 && i+1 < VSIZE) {
if(colors[i+1][j-1] != -1 && colors[i+1][j-1] != VORONOI) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = colors[i+1][j-1];
}
}
//Pixel below and to the right
if(j+1 >= 0 && i+1 < VSIZE) {
if(colors[i+1][j+1] != -1 && colors[i+1][j+1] != VORONOI) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = colors[i+1][j+1];
}
}
//Check if the pixel is on the top row
if(i == 0) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = PINK;
}
//Check if pixel is on the bottom row
if(i == VSIZE-1) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = YELLOW;
}
//Check if pixel is on the left column
if(j == 0) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = ORANGE;
}
//Check if pixel is on the right column
if(j == HSIZE-1) {
neighbourCols = realloc(neighbourCols, sizeof(int) * (k+1));
neighbourCols[k++] = BLUE;
}
//If k==0, there are no colored neighbours
if(k == 0) {
return 0;
}
//If k==1, there is only one colored neighbour
if(k==1) {
return 1;
}
//Else, if k>1, and they're not all the same, then there is more than one colored neighbour
int lastCol = neighbourCols[0];
for(int m=1; m<k; m++) {
int curCol = neighbourCols[m];
if(lastCol != curCol) {
return 2;
}
lastCol = curCol;
}
return 1;
}
int getColorOfNeighbour(int i, int j, int colors[VSIZE][HSIZE]) {
int color = -1;
int VORONOI = 0;
int PINK = 1;
int BLUE = 2;
int ORANGE = 3;
int YELLOW = 4;
int RED = 5;
int GREEN = 6;
int SILVER = 7;
int GOLD = 8;
//Pixel above
if(i-1 >= 0) {
if(colors[i-1][j] != -1 && colors[i-1][j] != VORONOI) {
return colors[i-1][j];
}
}
//Pixel below
if(i+1 < VSIZE) {
if(colors[i+1][j] != -1 && colors[i+1][j] != VORONOI) {
return colors[i+1][j];
}
}
//Pixel to the right
if(j-1 >= 0) {
if(colors[i][j-1] != -1 && colors[i][j-1] != VORONOI) {
return colors[i][j-1];
}
}
//Pixel to the left
if(j+1 < HSIZE) {
if(colors[i][j+1] != -1 && colors[i][j+1] != VORONOI) {
return colors[i][j+1];
}
}
//Pixel above and to the left
if(i-1 >= 0 && j-1 >= 0) {
if(colors[i-1][j-1] != -1 && colors[i-1][j-1] != VORONOI) {
return colors[i-1][j-1];
}
}
//Pixel above and to the right
if(i-1 >= 0 && j+1 < HSIZE) {
if(colors[i-1][j+1] != -1 && colors[i-1][j+1] != VORONOI) {
return colors[i-1][j+1];
}
}
//Pixel below and to the left
if(j-1 >= 0 && i+1 < VSIZE) {
if(colors[i+1][j-1] != -1 && colors[i+1][j-1] != VORONOI) {
return colors[i+1][j-1];
}
}
//Pixel below and to the right
if(j+1 >= 0 && i+1 < VSIZE) {
if(colors[i+1][j+1] != -1 && colors[i+1][j+1] != VORONOI) {
return colors[i+1][j+1];
}
}
//Top row
if(i==0) {
return PINK;
}
//Bottom row
if(i==VSIZE-1) {
return YELLOW;
}
//Left column
if(j==0) {
return ORANGE;
}
//Right column
if(j==HSIZE-1) {
return BLUE;
}
}
//Perform brushfire algorithm on grid
bool **brushfire(int **grid) {
//Allocate memory for voronoi records
bool **voronoi = (bool **) malloc(sizeof(bool *) * VSIZE);
for(int i=0; i<VSIZE; i++) voronoi[i] = (bool *) malloc(sizeof(bool) * HSIZE);
//Allocate memory for color records
int colors[VSIZE][HSIZE];
for(int i=0; i<VSIZE; i++) {
for(int j=0; j<HSIZE; j++) {
colors[i][j] = -1;
}
}
//Color enums
int VORONOI = 0;
int PINK = 1;
int BLUE = 2;
int ORANGE = 3;
int YELLOW = 4;
int RED = 5;
int GREEN = 6;
int SILVER = 7;
int GOLD = 8;
//Visited array
bool visited[VSIZE][HSIZE];
for(int i=0; i<VSIZE; i++) {
for(int j=0; j<HSIZE; j++) {
visited[i][j] = false;
}
}
int curColor = 4;
//Loop through, and assign color to each obstacle
for(int i=0; i<VSIZE; i++) {
for (int j=0; j<HSIZE; j++) {
//Check if square is occupied
if(grid[i][j] == 1) {
//If it is, check if it's already been visited
if(!visited[i][j]) {
//If it hasn't, visit and color it and the entire obstacle it belongs to
visit(visited, grid, i, j, colors, curColor);
curColor++;
}
}
}
}
//Test print color of each square
for(int i=0; i<VSIZE; i++) {
for(int j=0; j<HSIZE; j++) {
// printf("%d\t", colors[i][j]);
}
// printf("\n");
}
//TODO: Here onwards may not be correct
//Begin brushfire algorithm
int k=2;
bool change = true;
//Loop until there is no change
while(change) {
//Intially record change as false
change = false;
//Loop over all squares
for(int i=0; i<VSIZE; i++) {
for(int j=0; j<HSIZE; j++) {
//Check if the pixel is free
if(grid[i][j] == 0) {
//Check if it's neighbours are labeled (or a border)
int numColoredNeighbours = getNumColoredNeighbours(i, j, colors);
if(numColoredNeighbours == 1) {
//Get the color
change = true;
grid[i][j] = k;
colors[i][j] = getColorOfNeighbour(i, j, colors);
}
else if(numColoredNeighbours > 1) {
//Make this square a voronoi point
change = true;
grid[i][j] = k;
colors[i][j] = VORONOI;
}
}
}
}
//Loop over all squares again to identify voronoi points
for(int i=0; i<VSIZE; i++) {
for(int j=0; j<HSIZE; j++) {
//Check each pixel to see if it's a voronoi point
bool isVoronoi = isVoronoiPoint(i, j, k, grid, colors);
if(isVoronoi) {
colors[i][j] = VORONOI;
}
}
}
k++;
}
//Determine all voronoi points
for(int i=0; i<VSIZE; i++) {
for(int j=0; j<HSIZE; j++) {
if(colors[i][j] == VORONOI) {
voronoi[i][j] = true;
}
}
}
//Return voronoi points
return voronoi;
}
int main(int argc, char **argv) {
//Read in occupancy grid
int **grid = readOccupancyGrid(argv[1]);
//Test print
for(int i=0; i<VSIZE; i++) {
for(int j=0; j<HSIZE; j++) {
// printf("%d ", grid[i][j]);
}
// printf("\n");
}
//Perform brushfire algorithm on grid
bool **voronoi = brushfire(grid);
//Print voronoi points
for(int i=0; i<VSIZE; i++) {
for(int j=0; j<HSIZE; j++) {
printf("%d ", voronoi[i][j] ? 1 : 0);
}
printf("\n");
}
//Free grid
for(int i=0; i<VSIZE; i++) free(grid[i]);
free(grid);
//Free voronoi
for(int i=0; i<VSIZE; i++) free(voronoi[i]);
free(voronoi);
}
|
C
|
// Program - Output a box with given width and height (Box drawn with *)
#include <stdio.h>
void draw_box (unsigned int width, unsigned int height)
{
// Output the top of the box with "width" asterisks
for(unsigned int i = 0 ; i < width ; ++i)
printf("*");
// Output height-2 rows of "width" characters with * at each end and spaces inside
for(unsigned int j = 0 ; j < height - 2 ; ++j)
{
printf("\n*"); // First asterisk
// Next draw the spaces
for(unsigned int i = 0 ; i < width - 2 ; ++i)
printf(" ");
printf("*"); // Last asterisk
}
// Output the bottom of the box
printf("\n"); // Start on newline
for(unsigned int i = 0 ; i < width ; ++i)
printf("*");
printf("\n"); // Newline at end of last line
}
int main (void)
{
const unsigned int MIN_SIZE = 3; // Minimum width and height values
unsigned int width = 0;
unsigned int height = 0;
// Read in required width and height
printf("Enter values for the width and height (minimum of %u):", MIN_SIZE);
scanf("%u%u", &width, &height);
// Validate width and height values
if(width < MIN_SIZE)
{
printf("\nWidth value of %u is too small. Setting it to %u.", width, MIN_SIZE);
width = MIN_SIZE;
}
if(height < MIN_SIZE)
{
printf("\nHeight value of %u is too small. Setting it to %u.", height, MIN_SIZE);
height = MIN_SIZE;
}
draw_box (width, height); // Calling the function
return 0;
}
|
C
|
#include "users/ucode.c"
#include "include/type.h"
#define LINES 24
print_page(int fd);
print_line(int fd);
int main(int argc, char *argv[])
{
int fd, r;
char cmd, tty[64];
if (argc > 1)
{
fd = open(argv[1], RDONLY);
}
else
{
fd = dup(0);
close(0);
gettty(tty);
open(tty, RDONLY);
}
if (fd < 0)
{
printf("\"%s\": could not open file.\n", argv[1]);
return -1;
}
/* print an initial page */
r = print_page(fd);
/* while there is still more to read, ask for commands */
while(r > 0)
{
cmd = getc();
switch(cmd)
{
case 'q':
putc('\n');
r = -1;
break;
case '\n':
case '\r':
r = print_line(fd);
break;
case 'd':
case 'f':
case ' ':
r = print_page(fd);
break;
}
}
close(fd);
return 0;
}
int print_page(int fd)
{
char *cp;
int row = 0, r, i;
while((r = read(fd, cp, 1)) > 0)
{
if (*cp == '\n')
{
row++;
}
putc(*cp);
if (row >= LINES)
{
break;
}
}
if (r <= 0)
{
return 0;
}
return 1;
}
int print_line(int fd)
{
char *cp;
int row = 0, r, i;
while((r = read(fd, cp, 1)) > 0)
{
if (*cp == '\n')
{
putc(*cp);
break;
}
putc(*cp);
}
if (r <= 0)
{
return 0;
}
return 1;
}
|
C
|
/*=============================================================================
# FileName: 3-sqrt.c
# Desc: accepts a b c, finds out roots of the equation.
# Author: Max Lee (Ho Suk Lee)
# Email: hoso1312@gmail.com
# HomePage: http://imnotbermuda.com
# Version: 0.0.1
# LastChange: 2015-08-02 11:41:10
# History:
=============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int
main(int argc, char **argv) {
double a, b, c, d, root1, root2;
printf("a: ");
scanf("%lf", &a);
printf("b: ");
scanf("%lf", &b);
printf("c: ");
scanf("%lf", &c);
d = b * b - 4 * a * c;
if (d < 0) {
printf("No roots.\n");
return 0;
}
root1 = (-b + sqrt(d))/(2*a);
root2 = (-b - sqrt(d))/(2*a);
if (root1 != root2)
printf("Root1: %.2f\nRoot2: %.2f\n", root1, root2);
else
printf("Root: %.2f\n", root1);
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <pthread.h>
#define SHMSZ 1024
int shmid;
char *data, *od;
void *reciever() {
while(1) {
if(strcmp(od, data) != 0) {
printf("%s\nMsg: ",data);
strcpy(od, data);
}
}
}
void *sender() {
while(1) {
printf("Msg: ");
scanf("%s", data);
strcpy(od, data);
}
}
int main(int argc, const char *argv[]) {
int rR, rS;
pthread_t threadR, threadS;
if(argc != 2) {
fprintf(stderr, "Usage: %s <key>\n", argv[0]);
exit(EXIT_FAILURE);
}
int key = 10;
//sscanf(argv[2], "%d", &key);
od = (char *) malloc(SHMSZ);
printf("Hello\n");
shmid = shmget((key_t) key, SHMSZ, IPC_CREAT|0666);
if(shmid < 0) {
fprintf(stderr, "Share segment creation failed!\n");
exit(EXIT_FAILURE);
}
printf("Memory Mount Complete.\n");
data = (char *) shmat(shmid, NULL, 0);
strcpy(od, data);
printf("Server started with key: %d\n=================================\n\n", key);
if ((rR=pthread_create(&threadR, NULL, reciever, NULL))) {
printf("ThreadR creation failed: %d\n", rR);
}
if ((rS=pthread_create(&threadS, NULL, sender, NULL))) {
printf("ThreadS creation failed: %d\n", rS);
}
pthread_join(threadR, NULL);
pthread_join(threadS, NULL);
return 0;
}
|
C
|
int main()
{
int firstnum = 1;
int secnum = 1;
printf("%i\n%i\n", firstnum, secnum);
for (int i = 0; i<23; i++)
{
int num = secnum;
secnum += firstnum;
firstnum = num;
printf("%i", secnum);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int n,i,max,count=0,x;
scanf("%d",&n);
int z[n+1],y[n+1];
for(i=0;i<n;i++)
{
scanf("%d",&y[i]);
}
for(i=0;i<n;i++)
{
if(y[i]<=y[i+1])
{
count++;
z[i]=count;
}
else
{
count=0;
z[i]=count;
}
}
if(n==1)
printf("%d",n);
else{
max=z[0];
for(i=1;i<n-1;i++)
{
if(z[i]>max)
max=z[i];
}
printf("%d",max+1);
}
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
int main()
{
const int N = 100;
struct res
{
float masg[N];
float masf[N];
float masy[N];
};
uint8_t test;
int error,exit1, j, i, k;
char* sovp;
float mas[N];
float F, G, Y, a, x, x2, shag, min, max, kolshag;
char stx[255]; char stx2[255]; char sta[255]; char stk[255]; char blok [255]; char stg[255]; char stf[255]; char sty[255];
char sh[255];char vivod[765];
struct res otvet;
while (exit1 != 1)
{
memset(stg,0,255); memset(stf,0,255); memset(blok,0,255); memset(sty,0,255);
memset(mas, 0, N);
k = 0;
j = 0;
i = 0;
printf("Функция G\n");
printf ("Введите число a \n");
fgets(sta, 255, stdin);
a = atof(sta);
printf ("Введите число x \n");
fgets(stx, 255, stdin);
x = atof(stx);
printf ("Введите число x2 \n");
fgets(stx2, 255, stdin);
x2 = atof(stx2);
printf ("Введите колличество шагов вычисления функции\n");
fgets(stk, 255, stdin);
kolshag = atof(stk);
shag = (x2-x)/kolshag;
if (shag > x2)
{
printf ("Шаг вычисления функции больше чем сама область\n");
error = 6;
break;
}
for (;x <= x2-shag;x = x + shag)
{
if (fabs(24*a*a-49*a*x+15*x*x) <= 0.00001)
{
printf ("Функция не может быть вычислена так как знаменатель не может быть равен 0\n");
error = 1;
break;
}
G = 5*(10*a*a-11*a*x+x*x)/24*a*a-49*a*x+15*x*x;
mas[j] = G;
otvet.masg[j] = G;
sprintf(blok, "%2f\t", mas[j]);
strcat(stg, blok);
j = j+1;
i = i+1;
}
printf("%s\n", stg);
printf ("Задайте шаблон для поиска совпадения\n");
scanf("%s", sh);
sovp = strstr(stg, sh);
while(sovp != NULL)
{
sovp = strstr(sovp + 1, sh);
k+=1;
}
printf("\nКолличество совпадений %d\n",k);
min = mas[0];
max = mas[0];
for (j = 0; j <= i ; j++)
{
if (mas[j] < min )
{
min = mas[j];
}
if (mas[j] > max )
{
max = mas [j];
}
}
printf("\n Минимальный элемент %f\n", min);
printf("\n Максимальный элемент %f\n", max);
FILE *file;
file = fopen("laba7.txt", "w+");
if ((file = fopen("laba7.txt","w+")) == NULL)
{
printf("Ошибка при открытии файла.\n");
exit(1);
}
for (j = 0; j < i ; j++)
{
fprintf(file,"%f\t",otvet.masg[j]);
}
fclose(file);
j = 0;
i = 0;
k = 0;
memset(blok,0,255);
memset(mas, 0, N);
getchar();
printf("Функция F\n");
printf ("Введите число a \n");
fgets(sta, 255, stdin);
a = atof(sta);
printf ("Введите число x \n");
fgets(stx, 255, stdin);
x = atof(stx);
printf ("Введите число x2 \n");
fgets(stx2, 255, stdin);
x2 = atof(stx2);
printf ("Введите колличество шагов вычисления функции\n");
fgets(stk, 255, stdin);
kolshag = atof(stk);
shag = (x2-x)/kolshag;
if (shag > x2)
{
printf ("Шаг вычисления функции больше чем сама область вычисления функции\n");
error = 6;
break;
}
for (;x <= x2;x = x + shag)
{
F = sinh(3*a*a+7*a*x+4*x*x);
mas[j] = F;
otvet.masf[j] = F;
sprintf(blok, "%2f\t", mas[j]);
strcat(stf, blok);
j = j+1;
i = i+1;
}
printf("%s\n", stf);
printf ("Задайте шаблон для поиска совпадения\n");
scanf("%s", sh);
sovp = strstr(stf, sh);
while(sovp != NULL)
{
sovp = strstr(sovp + 1, sh);
k+=1;
}
printf("\nКолличество совпадений %d\n",k);
min = mas[0];
max = mas[0];
for (j = 0; j < i ; j++)
{
if (mas[j] < min )
{
min = mas[j];
}
if (mas[j] > max )
{
max = mas [j];
}
}
printf("\n Минимальный элемент %f\n", min);
printf("\n Максимальный элемент %f\n", max);
file = fopen("laba7.txt", "a+");
if ((file = fopen("laba7.txt","a+")) == NULL)
{
printf("Ошибка при открытии файла.\n");
exit(1);
}
for (j = 0; j < i ; j++)
{
fprintf(file,"%f\t",otvet.masf[j]);
}
fclose(file);
j = 0;
i = 0;
k = 0;
memset(blok,0,255);
memset(mas, 0, N);
getchar();
printf("Функция Y\n");
printf ("Введите число a \n");
fgets(sta, 255, stdin);
a = atof(sta);
if (-0.1>=a && 0.1<=a)
{
printf("Число не пренадлжеит области определения функции \n");
error = 2;
break;
}
printf ("Введите число x \n");
fgets(stx, 255, stdin);
x = atof(stx);
if (-0.25 >= x && 0.25 <= x)
{
printf("Число не пренадлжеит области определения функции \n");
error = 3;
break;
}
printf ("Введите число x2 \n");
fgets(stx2, 255, stdin);
x2 = atof(stx2);
if (-0.25 >= x2 && 0.25 <= x2)
{
printf("Число не пренадлжеит области определения функции \n");
error = 3;
break;
}
printf ("Введите колличество шагов вычисления функции\n");
fgets(stk, 255, stdin);
kolshag = atof(stk);
shag = (x2-x)/kolshag;
if (shag > x2)
{
printf ("Шаг вычисления функции больше чем сама область вычисления функции\n");
break;
}
for (x;x <= x2;x = x + shag)
{
if (-0.25 >= x && 0.25 <= x)
{
printf("Число не пренадлжеит области определения функции \n");
error = 4;
break;
}
Y = -atanh(30*a*a+37*a*x-4*x*x);
mas[j] = Y;
otvet.masy[j] = Y;
sprintf(blok, "%2f\t", mas[j]);
strcat(sty, blok);
j = j+1;
i = i+1;
}
printf("%s\n", sty);
printf ("Задайте шаблон для поиска совпадения\n");
scanf("%s", sh);
sovp = strstr(sty, sh);
while(sovp != NULL)
{
sovp = strstr(sovp + 1, sh);
k+=1;
}
printf("\nКолличество совпадений %d\n",k);
min = mas[0];
max = mas[0];
for (j = 0; j < i ; j++)
{
if (mas[j] < min )
{
min = mas[j];
}
if (mas[j] > max )
{
max = mas [j];
}
}
printf("\n Минимальный элемент %f\n", min);
printf("\n Максимальный элемент %f\n", max);
file = fopen("laba7.txt", "a+");
if ((file = fopen("laba7.txt","a+")) == NULL)
{
printf("Ошибка при открытии файла.\n");
exit(1);
}
for (j = 0; j < i ; j++)
{
fprintf(file,"%f\t",otvet.masy[j]);
}
fclose(file);
memset(otvet.masg,0,N);
memset(otvet.masy,0,N);
memset(otvet.masy,0,N);
file = fopen("laba7.txt", "r");
if ((file = fopen("laba7.txt","r")) == NULL)
{
printf("Ошибка при открытии файла.\n");
exit(1);
}
while( fscanf(file, "%764[^\n]\n", vivod) == 1 )
{
printf("%s\n", vivod);
}
fclose(file);
printf("Хотите выйти из программы? 1 - Да 0 - Нет\n");
scanf ("%d", &exit1);
getchar();
}
return error;
}
|
C
|
/*
TODO:
make a storage system (flat file)
make a transport system (email most likely, IRC requires an IRC server...)
fix caps lock bug (if caps is on when start, we don't know. so just learn when caps goes off, and consider everything before it reversed.
fill out special keys, so we aren't blinded when someone types a quesiton mark. - proving difficult, sign isn't in ASCII.
*/
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include "keylog.h"
HHOOK kbdhook;
int capsOn;
char buf[300];
int main()
{
HINSTANCE MH;
MSG M;
printf("Hello world!\n");
capsOn = 0;
MH = GetModuleHandle(NULL);
kbdhook = SetWindowsHookEx(WH_KEYBOARD_LL, LLKeyboardProc, MH, NULL);
while(1)
{
GetMessage(&M, NULL, 0, 0);
// somehow we need the character data back here, I don't know how. or, we could use threads... lol.
}
return 0;
}
|
C
|
#include "coder.h"
#include "command.h"
#include <stdlib.h>
int encode_file (const char *in_file_name, const char*out_file_name) {
FILE *in;
FILE *out;
in = fopen(in_file_name, "r");
out = fopen(out_file_name, "wb");
CodeUnit enc_point;
uint32_t point;
while (!feof(in)) {
fscanf(in, "%x", &point);
encode(point, &enc_point);
const CodeUnit *cd = (const CodeUnit *)&enc_point;
write_code_unit(out, cd);
}
fclose(in);
fclose(out);
return 0;
}
int decode_file (const char *in_file_name, const char*out_file_name) {
FILE *in;
FILE *out;
in = fopen(in_file_name, "rb");
out = fopen(out_file_name, "w");
CodeUnit *enc_point = (CodeUnit*)malloc(sizeof(CodeUnit));
while (1) {
read_next_code_unit(in, enc_point);
const CodeUnit *c_unit = (const CodeUnit *) enc_point;
uint32_t result = decode(c_unit);
if (feof(in))
break;
fprintf(out, "%x\n", result);
}
fclose(in);
fclose(out);
return 0;
}
|
C
|
#include "map_surface.h"
void CDMap_display_grid(Carc_Layout *layout){
int tile_size=CDUtils_get_tile_size_in_pixels(layout->tile_size);
int width = layout->map_surface->w;
int height = layout->map_surface->h;
int i=0, cur_coord=0;
SDL_Surface *vertical_line = SDL_CreateRGBSurface(0,1,height,32,0,0,0,0);
SDL_Surface *horizontal_line = SDL_CreateRGBSurface(0,width,1,32,0,0,0,0);
SDL_FillRect(vertical_line,NULL,SDL_MapRGB(vertical_line->format,0,0,0));
SDL_FillRect(horizontal_line,NULL,SDL_MapRGB(horizontal_line->format,0,0,0));
SDL_Rect line_pos;
line_pos.y=0;
//Create & Display vertical lines
for(i=1;cur_coord<width;i++){
cur_coord = i*tile_size;
line_pos.x=cur_coord;
CDMap_blit_on(vertical_line,NULL,&line_pos,layout);
}
//Create & Display hoizontal lines
line_pos.x=0;
cur_coord=tile_size;
for(i=1;cur_coord<height;i++){
cur_coord = i*tile_size;
line_pos.y=cur_coord;
CDMap_blit_on(horizontal_line,NULL,&line_pos,layout);
}
SDL_UpdateWindowSurface(layout->window);
//SDL_FreeSurface(screen);
SDL_FreeSurface(horizontal_line);
SDL_FreeSurface(vertical_line);
}
void CDMap_insert_tile(SDL_Surface *surface, int x, int y, Carc_Layout *layout){
SDL_Rect pos=CDUtils_get_slot_upper_left(x,y,layout->tile_size);
if(CDUtils_pos_in_surface(pos, *(layout->map_surface)))
CDMap_blit_on(surface,NULL,&pos,layout);
}
void CDMap_blit_on(SDL_Surface *surface, SDL_Rect *src, SDL_Rect *dest, Carc_Layout *layout){
CDL_blit_on(LP_MAP,surface,src,dest,layout);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bruteForce.h"
#include "time.h"
/**
* This program is the implementation of the TSP problem with brute force.
* The program runs the vertices from a file.
*
* @author probal chandra dhar
* @date 12/1/2016
* @info Course COP5990
*/
#define max 20
/**
* Adjacency matrix
*/
int newAdjMat[max][max];
/**
* Minimum value of the edges
*/
int minimumValuedEdge;
/**
* Used to determine the minimum value of edges
*/
int count=0;
int main(int argc, char **argv){
/**
* Array that have the set of vertices
*/
int arrElement[max];
/**
* Number of vertices in the graph
*/
int n;
/**
* The minimum value of the edges.
*/
int minimumNode = 0;
// checking if the user put the correct value to run the program
if ( argc < 3 ){
printf("Argument missing\nusage: tspBruteForce <filename> <numCities>");
exit(0);
}
// Number of cities is entered or not
if (atoi(argv[2]) == 0){
printf("Please enter valid number of cities.\n");
exit(0);
}
// FIle pointer
FILE *fp;
fp = fopen(argv[1], "r+");
const char s[2] = ",";
char *token;
int i, j;
// int adj[16][16] = {0};
int adj[16][16];
int cost;
// Stores the characters from the file
char charOrigin, charDestination;
if (fp){
// start the timer
startTimer();
char line[20];
while (fgets(line, sizeof(line), fp) != NULL)
{
token = strtok(line, s);
charOrigin = token[0];
// printf("%c\t",charOrigin);
token = strtok(NULL,s);
charDestination = token[0];
// printf("%c\t",charDestination);
token = strtok(NULL,s);
cost = atoi(token);
// printf("%d\n",cost);
// converting the characters to numbers
adj[charOrigin%65+1][charDestination%65+1] = cost;
adj[charDestination%65+1][charOrigin%65+1] = cost;
}
fclose(fp);
} else {
printf("File not found\n");
exit(0);
}
n = atoi(argv[2]);
printf("Number of edges: %d\n", n);
// assigining 0 to all elements
for ( i = 0; i < n+1; i++)
{
for ( j = 0; j < n+1; j++)
{
newAdjMat[i][j] = 0;
}
}
// assigning the values of the edges to global matrix
for ( i = 1; i <= n; i++ )
{
for ( j = i+1; j <= n; j++ ){
newAdjMat[i][j] = adj[i][j];
newAdjMat[j][i] = adj[i][j];
}
}
// creating the array of the vertices
createArrayOfVertices(n, arrElement);
// Permuting the array
permutation(arrElement,1,n, minimumNode, newAdjMat);
printf("The minimum cost for the trip is %d\n",minimumValuedEdge);
// stoping the timer
float elapsedTime = stopTimer ();
printf ("It took %f seconds to complete the job.\n", elapsedTime);
return 0;
}
/**
* Creates an array with all vertices taken for the graph
*
* @param n - number of vertices to be visited
* @param array - the array where the value will store
*
*/
void createArrayOfVertices(int n, int array[]){
int i;
for(i=1;i<=n;i++){
array[i]=i;
}
}
/**
* Do all possible permutation for the number of vertices taken from file.
*
* @param array - array where all the vertices are stored
* @param start - Starting node of the graph
* @param start - Number of vertices in the graph
* @param minNode - Minimum cost of any edge
* @param AdjMat - the adjacency matrix of the graph
*
*/
void permutation(int array[], int start, int end, int minNode, int adjMat[end][end]){
int i;
if (start==end) {
calCost(array, end, minNode, adjMat);
}
else {
for (i=start;i<=end;i++) {
swap(&array[i],&array[start]);
permutation(array, start+1, end, minNode, adjMat);
swap(&array[i],&array[start]);
}
}
}
/**
* Swap the value between two places
*
* @param a - pointer where the first element should point out
* @param b - pointer where the second element should point out to swap
*
*/
void swap(int* a,int* b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
/**
* Calculate the minimum cost of the edges
*
* @param array - array where all vertices are stored
* @param arrayLength - number of vertices for the graph
* @param minNode - Minimum cost of any edge
* @param AdjMat - the adjacency matrix of the graph
*
*/
void calCost(int array[], int arrayLength, int minNode, int adjMat[arrayLength][arrayLength]){
int i;
int sum=0;
for(i=1;i<arrayLength;i++){
sum+=findCost(array[i],array[i+1], arrayLength, adjMat);
}
// printf("%d\n", i);
sum+=findCost(array[i],array[1], arrayLength, adjMat);
// printf("%d\n", findCost(array[i],array[1]));
// printf("%d\n", minNode);
TripCost(sum, count, minNode);
count++;
//printf("The cost for this trip is %d\n",sum);
}
/**
* Find out the value of a particular edge from adjacency matrix
*
* @param m - integer that represent first vertex
* @param n - integer that represent second vertex
* @param arrayLength - number of vertices for the graph
* @param AdjMat - the adjacency matrix of the graph
*
* @return the value of a particular edge between two vertices
*
*/
int findCost(int m,int n, int arrayLength, int adjMat[arrayLength][arrayLength]){
return newAdjMat[m][n];
}
/**
* Calculate the trip cost of a round trip around the graph
*
* @param cost - the cost for the trip
* @param count - used to calculate minimum
* @param minNode - minimum edge that have minimum cost
*
*/
void TripCost(int cost,int count, int minNode){
if(count==0){
minimumValuedEdge=cost;
// minNode=cost;
}
else{
minimumValuedEdge=minCompare(cost, minNode);
// minNode = minCompare(cost, minNode);
}
//printf("The minimum cost for the trip is %d \n",min);
}
/**
* Determine if the cost is minimum or not
*
* @param cost - the cost for the trip
* @param minNode - minimum edge that have minimum cost
*
*/
int minCompare(int cost, int minNode){
return((minimumValuedEdge>cost)?cost:minimumValuedEdge);
// return((minNode>cost)?cost:minNode);
}
|
C
|
// encoder VI
void DoEncoderVI() {
if (encVI.isClick()) { // нажата кнопка экодера - меняем его текущий режим - выбор яркости или часа
SaveTimer = millis(); // сбросить таймер записи в eprom
encVImode = ++encVImode;
if (encVImode > 1) encVImode = 0; // modes till 0 to 1, коротким нажатием выбираем только между яркостью и часом
if (encVImode == 0) { // выбран режим регулировки яркости
lcd.setCursor(12, 1); lcd.print(" "); // затираем указатель во всех остальных позициях
lcd.setCursor(12, 2); lcd.print(">"); // ставим указатель в позицию регулировки яркости
}
if (encVImode == 1) { // выбран режим выбора часа
lcd.setCursor(12, 2); lcd.print(" "); // затираем указатель во всех остальных позициях
lcd.setCursor(12, 1); lcd.print(">"); // ставим указатель в позицию регулировки яркости
}
tone(speaker_pin, 800, 30); //conflicts with port 10, dont use this port along with tone function
}
if (encVI.isHolded()) { // кнопка экодера нажата с удержанием, энкодер переходит в альтернативный режим 2
encVImode = 2;
SaveTimer = millis(); // сбросить таймер записи в eprom
}
if (encVI.isRight()) { // энкодер повернут вправо
if (encVImode == 0) { // и выбран режим регулировки яркости
BrightnessColHr[3][VIMenuSelectedHour] = BrightnessColHr[3][VIMenuSelectedHour] + 3; // увеличиваем яркость
if (BrightnessColHr[3][VIMenuSelectedHour] > 99) BrightnessColHr[3][VIMenuSelectedHour] = 99; // ограничиваем макс.значение до 99 иначе не влезет в экран
if ((VIMenuSelectedHour == CurHour) && (OFFflag == false)) analogWrite(VIpin, map(BrightnessColHr[3][VIMenuSelectedHour], 0, 99, 0, MaxBrightness)); // записываяем яркость в порт если выбранный час соответствует текущему реальному
SaveFlag = true; // поднять флаг для записи значения яркости в eprom
}
if (encVImode == 1) { // и выбран режим выбора часа
VIMenuSelectedHour = ++VIMenuSelectedHour; // увеличиваем выбранный час
if (VIMenuSelectedHour > 23) VIMenuSelectedHour = 23; // ограничиваем макс.значение до 23ч
}
}
if (encVI.isLeft()) { // энкодер повернут влево
if (encVImode == 0) { // и выбран режим регулировки яркости
BrightnessColHr[3][VIMenuSelectedHour] = BrightnessColHr[3][VIMenuSelectedHour] - 3; // уменьшаем яркость
if (BrightnessColHr[3][VIMenuSelectedHour] < 0) BrightnessColHr[3][VIMenuSelectedHour] = 0; // ограничиваем мин.значение не ниже 0
if ((VIMenuSelectedHour == CurHour) && (OFFflag == false)) analogWrite(VIpin, map(BrightnessColHr[3][VIMenuSelectedHour], 0, 99, 0, MaxBrightness)); // записываем яркость в порт если выбранный час соответствует текущему реальному
SaveFlag = true; // поднять флаг для записи значения яркости в eprom
}
if (encVImode == 1) { // и выбран режим выбора часа
VIMenuSelectedHour = VIMenuSelectedHour - 1; // уменьшаем выбранный час
if (VIMenuSelectedHour < 0) VIMenuSelectedHour = 0; // ограничиваем мин.значение до 0ч
}
}
if (encVI.isTurn()) { // если был совершён поворот (индикатор поворота в любую сторону)
SaveTimer = millis(); // сбросить таймер записи в eprom
lcd.setCursor(13, 1); lcd.print(VIMenuSelectedHour); lcd.print(" "); // выводим на экран выбранный час
lcd.setCursor(13, 2); lcd.print(BrightnessColHr[3][VIMenuSelectedHour]); lcd.print(" "); // выводим на экран текущее значение яркости для выбранного часа
tone(speaker_pin, 1000, 20); //conflicts with port 10, dont use this port along with tone function
}
}
|
C
|
/*
** EPITECH PROJECT, 2020
** CPE_lemin_2019
** File description:
** pathfinding
*/
#include "lemin.h"
void create_ants(lemin_data_t *data)
{
ant_t *ant;
for (int i = 1; i <= data->ants_nb; i++) {
ant = malloc(sizeof(ant_t));
ant->nb = i;
ant->current_room = data->start_room;
ant->previous_room = 0;
data->ants = ll_append(data->ants, ant);
}
}
char *tunnel_get_end(tunnel_t *tunnel, char *current_room)
{
room_t *room;
if (my_strcmp(tunnel->room1->name, current_room) &&
my_strcmp(tunnel->room2->name, current_room))
return 0;
room = !my_strcmp(tunnel->room1->name, current_room) ? tunnel->room2 :
tunnel->room1;
return room->name;
}
int is_ant_in_room(linked_list_t *ants, char *room)
{
ant_t *ant;
for (linked_list_t *i = ants; i; i = i->next) {
ant = i->data;
if (!my_strcmp(ant->current_room, room))
return 1;
}
return 0;
}
path_t get_shortest_path(char *current_room, char *previous_room,
lemin_data_t *data)
{
char *room_name;
path_t path;
path_t shortest_path = {0, -1};
for (linked_list_t *i = data->tunnels; i; i = i->next) {
room_name = tunnel_get_end(i->data, current_room);
if (!room_name || (previous_room &&
!my_strcmp(room_name, previous_room)) || is_ant_in_room(data->ants,
room_name)) continue;
if (!my_strcmp(data->end_room, room_name)) {
shortest_path.room = room_name;
shortest_path.steps = 0;
break;
}
path = get_shortest_path(room_name, current_room, data);
if (shortest_path.steps == -1 || path.steps < shortest_path.steps) {
shortest_path.steps = path.steps;
shortest_path.room = room_name;
}
}
shortest_path.steps += 1;
return shortest_path;
}
int next_room(int iter_nb, ant_t *ant, lemin_data_t *data)
{
path_t path = get_shortest_path(ant->current_room, ant->previous_room,
data);
if (!path.room && !my_strcmp(ant->current_room, data->start_room) &&
ant->nb == 1) {
my_printf("ERROR: no path from start to end\n");
return 0;
} else if (!path.room)
return -1;
ant->previous_room = ant->current_room;
ant->current_room = path.room;
my_printf("%sP%d-%s", iter_nb == 0 ? "" : " ", ant->nb, ant->current_room);
return 1;
}
|
C
|
#include <stdio.h>
#include <math.h>
//Potencias de dos, compilar con -lm al final
void sum(long long *i){
int n=0;
for (n;n<=37;n++){
(*i) = pow(2,n);
printf("2^%d\t", n);
printf("%lld\n", (*i));
}
}
main(){
long long i;
sum(&i);
}
|
C
|
#ifndef STRINGCACHE_H
#define STRINGCACHE_H
#include "stdtypes.h" // to make VS2005 not complain about stricmp
C_DECLARATIONS_BEGIN
typedef const char *constCharPtr;
void stringReorder(void);
int numIndexedStringsInStringTable(void);
void stringCachePreAlloc(int size);
// Generic string table
const char* allocAddString( const char * s );
const char* allocFindString(const char * s);
const char* allocAddString_checked(const char *s); // passes NULLs through, devassert if string isn't already cached
// Shared memory string table
void sharedStringReserve(int count);
const char* allocAddSharedString(const char * s);
// Indexed string table (only used by FX - for network communication)
const char* allocAddIndexedString( const char * s );
int stringToReference(const char* str);
const char* stringFromReference(int ref);
// First tries the string cache for a simple cmp, if that fails, does a stricmp...
// AB: this function is stupid stupid stupid
// __forceinline static bool stringCacheCompareString(const char* pcKnownStringPtr, const char* pcLookupString)
// {
// const char* pcLookedUp = allocFindString(pcLookupString);
// if (!pcLookedUp)
// {
// return (stricmp(pcKnownStringPtr, pcLookupString) == 0);
// }
// return pcKnownStringPtr == pcLookedUp;
// }
C_DECLARATIONS_END
#endif // STRINGCACHE_H
|
C
|
#include <stdio.h>
main()
{
printf("hello, world\n");
// return 0; nothing special if commented out
}
// commenting out the first line will cause the following message:
/*
ex1-1.c:2:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
2 | main()
| ^~~~
ex1-1.c: In function ‘main’:
ex1-1.c:4:3: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
4 | printf("hello, world\n");
| ^~~~~~
ex1-1.c:4:3: warning: incompatible implicit declaration of built-in function ‘printf’
ex1-1.c:1:1: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
+++ |+#include <stdio.h>
1 | // #include <stdio.h>
*/
|
C
|
#include "esstd.tête" // Entrées-sorties standard
#include "bibstd.tête" // Bibliothèque standard
// Fonction principale, qui affiche ses arguments puis quitte
ent principal(ent carg, car** varg) {
ent i; // Déclaration d’entier
pour(i = 0; i < carg; i++) // Boucle «pour»
imprimerf("%s ", varg[i]); // Affichage formaté
mettrech(""); // Retour à la ligne
retourner SORTIE_SUCCÈS; // Fin
}
|
C
|
#include <ir/ir.h>
#include <target/util.h>
static void init_state_kx(Data* data) {
emit_line("var main = function(getchar, putchar) {");
for (int i = 0; i < 7; i++) {
emit_line("var %s = 0;", reg_names[i]);
}
emit_line("var mem = [];");
for (int mp = 0; data; data = data->next, mp++) {
if (data->v) {
emit_line("mem[%d] = %d;", mp, data->v);
}
}
}
static void kx_emit_func_prologue(int func_id) {
emit_line("");
emit_line("var func%d = function() {", func_id);
inc_indent();
emit_line("while (%d <= pc && pc < %d && running) {",
func_id * CHUNKED_FUNC_SIZE, (func_id + 1) * CHUNKED_FUNC_SIZE);
inc_indent();
emit_line("switch (pc) {");
emit_line("case -1: // dummy");
inc_indent();
}
static void kx_emit_func_epilogue(void) {
dec_indent();
emit_line("}");
emit_line("pc++;");
dec_indent();
emit_line("}");
dec_indent();
emit_line("};");
}
static void kx_emit_pc_change(int pc) {
emit_line("break;");
emit_line("");
dec_indent();
emit_line("case %d:", pc);
inc_indent();
}
static void kx_emit_inst(Inst* inst) {
switch (inst->op) {
case MOV:
emit_line("%s = %s;", reg_names[inst->dst.reg], src_str(inst));
break;
case ADD:
emit_line("%s = (%s + %s) & " UINT_MAX_STR ";",
reg_names[inst->dst.reg],
reg_names[inst->dst.reg], src_str(inst));
break;
case SUB:
emit_line("%s = (%s - %s) & " UINT_MAX_STR ";",
reg_names[inst->dst.reg],
reg_names[inst->dst.reg], src_str(inst));
break;
case LOAD:
emit_line("%s = mem[%s];", reg_names[inst->dst.reg], src_str(inst));
break;
case STORE:
emit_line("mem[%s] = %s;", src_str(inst), reg_names[inst->dst.reg]);
break;
case PUTC:
emit_line("putchar(%s);", src_str(inst));
break;
case GETC:
emit_line("%s = getchar();",
reg_names[inst->dst.reg]);
break;
case EXIT:
emit_line("running = false; break;");
break;
case DUMP:
break;
case EQ:
case NE:
case LT:
case GT:
case LE:
case GE:
emit_line("%s = (%s) | 0;",
reg_names[inst->dst.reg], cmp_str(inst, "true"));
break;
case JEQ:
case JNE:
case JLT:
case JGT:
case JLE:
case JGE:
case JMP:
emit_line("if (%s) pc = %s - 1;",
cmp_str(inst, "true"), value_str(&inst->jmp));
break;
default:
error("oops");
}
}
void target_kx(Module* module) {
init_state_kx(module->data);
emit_line("var running = true;");
int num_funcs = emit_chunked_main_loop(module->text,
kx_emit_func_prologue,
kx_emit_func_epilogue,
kx_emit_pc_change,
kx_emit_inst);
emit_line("");
emit_line("while (running) {");
inc_indent();
emit_line("switch (pc / %d | 0) {", CHUNKED_FUNC_SIZE);
for (int i = 0; i < num_funcs; i++) {
emit_line("case %d:", i);
emit_line(" func%d();", i);
emit_line(" break;");
}
emit_line("}");
dec_indent();
emit_line("}");
emit_line("};");
emit_line("var input = [];");
emit_line("var ip = 0;");
emit_line("var getchar = function() {");
emit_line(" if (input.length() <= ip) {");
emit_line(" var i;");
emit_line(" input = [];");
emit_line(" ip = 0;");
emit_line(" do {");
emit_line(" i = $stdin.geti();");
emit_line(" if (i < 0) i = 0;");
emit_line(" input.push(i);");
emit_line(" } while (i > 0);");
emit_line(" }");
emit_line(" return input[ip++];");
emit_line("};");
emit_line("var putchar = function(c) {");
emit_line(" $stdout.putch(c & 255);");
emit_line("};");
emit_line("main(getchar, putchar);");
}
|
C
|
/**
* All functions you make for the assignment must be implemented in this file.
* Do not submit your assignment with a main function in this file.
* If you submit with a main function in this file, you will get a zero.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "debug.h"
#include "sfmm.h"
// Added
#include "defines.h"
#include <errno.h>
size_t calculate_size_of_block(size_t size) {
//size_t minimum_required = 32;
size_t block_size = 0;
size_t footer_size = 8;
size_t header_size = 8;
size_t next_prev_size = 16;
block_size += footer_size;
block_size += header_size;
size_t payload;
if(size < 16)
payload = next_prev_size;
else
if((size%16) > 0)
payload = ((size/16) + 1) * 16;
else
payload = size;
block_size += payload;
return block_size;
}
/* Find the appropriate index from the size list that fits block_size given */
size_t get_sizelist_index(size_t block_size) {
size_t pow2 = 32;
size_t prevPow2 = 0;
for(size_t i = 0; i<NUM_FREE_LISTS-1; i++){
if( (block_size <= pow2) && (block_size > prevPow2) )
return i;
prevPow2 = pow2;
pow2 = (pow2<<1);
}
// Indirectly if( block_size > prevPow2 )
return NUM_FREE_LISTS-1;
}
void remove_block(sf_block *alloc_block) {
sf_block *prev_block = alloc_block->body.links.prev;
sf_block *next_block = alloc_block->body.links.next;
prev_block->body.links.next = next_block;
next_block->body.links.prev = prev_block;
//change_allocation_bits(alloc_block);
}
void free_list_insert(sf_block* block_start) {
//block_start = (sf_block *)block_start;
size_t block_size = ((block_start->header) & BLOCK_SIZE_MASK);
// Changing next block prev bit to 0 (free)
sf_block *nextblock_start = (sf_block *)(((char *)(block_start)) + block_size);
nextblock_start->header = ( (nextblock_start->header) & (size_t)(~1) );
size_t next_block_size = ((nextblock_start->header) & BLOCK_SIZE_MASK);
if(next_block_size != 0) {
sf_block *next_nextblock_start = (sf_block *)(((char *)(nextblock_start)) + next_block_size);
next_nextblock_start->prev_footer = ( (nextblock_start->header)^sf_magic() );
}
size_t free_list_index = get_sizelist_index(block_size);
if((sf_free_list_heads[free_list_index].body.links.next == &sf_free_list_heads[free_list_index]) &&\
(sf_free_list_heads[free_list_index].body.links.prev == &sf_free_list_heads[free_list_index]) ) {
block_start->body.links.next = sf_free_list_heads[free_list_index].body.links.next;
block_start->body.links.prev = sf_free_list_heads[free_list_index].body.links.prev;
sf_free_list_heads[free_list_index].body.links.next = block_start;
sf_free_list_heads[free_list_index].body.links.prev = block_start;
//printf("free_list_insert");
//printf("+++++++++++ HEAP +++++++++++++++");
//sf_show_heap();
return;
}
sf_block *next_bl = (sf_block *)( sf_free_list_heads[free_list_index].body.links.next );
block_start->body.links.next = sf_free_list_heads[free_list_index].body.links.next;
block_start->body.links.prev = &sf_free_list_heads[free_list_index];
sf_free_list_heads[free_list_index].body.links.next = block_start;
next_bl->body.links.prev = block_start;
//printf("+++++++++++ HEAP +++++++++++++++");
//sf_show_heap();
return;
}
/* Return pointer to the bestfit free list, If not found return -1 */
//void get_free_list_block(size) {
// Iterate through all size lists from start and find the best fit
//}
void create_prologue(char *heap_start) {
sf_prologue *prologue = (sf_prologue *)heap_start;
prologue->padding1 = 0; /* Alignment padding */
prologue->header = PACK(2*DSIZE, 3); /* Prologue header */
prologue->unused1 = (size_t *)0; /* Alignment padding */
prologue->unused2 = (size_t *)0; /* Alignment padding */
prologue->footer = (PACK(2*DSIZE, 3) )^( sf_magic() ); /* Prologue footer Xor'd */
}
void extend_epilogue(char *heap_end, size_t alloc) {
heap_end = heap_end - (1*WSIZE);
sf_epilogue *epilogue = (sf_epilogue *)(heap_end);
epilogue->header = PACK(0, alloc); /* Epilogue header */
}
void create_epilogue(char *heap_end, size_t alloc) {
heap_end = heap_end - (1*WSIZE);
sf_epilogue *epilogue = (sf_epilogue *)(heap_end);
epilogue->header = PACK(0, alloc); /* Epilogue header */
}
void create_free_block(sf_block *block_start, size_t block_size) {
size_t alloc = GET_ALLOC((block_start->prev_footer)^sf_magic());
alloc = (alloc>>1);
block_start->header = PACK(block_size, alloc); /* block header */
block_start->body.links.next = (sf_block *)PACK((size_t)block_start, 0); /* next pointer */
block_start->body.links.prev = (sf_block *)PACK((size_t)block_start, 0); /* prev pointer */
char *block_footer = ((char *)(block_start)) + block_size;
PUT(block_footer, ( PACK(block_size, alloc) )^( sf_magic() )); /* footer Xor'd */
}
void *first_call_malloc() {
char *heap_start;
if( NULL == (heap_start = sf_mem_grow()) ) // Creating extra memory
return NULL; // errno initialized to ENOMEM
char *heap_end = sf_mem_end();
create_prologue(heap_start);
create_epilogue(heap_end, 2);
size_t block_size = PAGE_SZ - (6*WSIZE);
sf_block *block_start = (sf_block *)(heap_start + (4*WSIZE)); // Pointing to footer of prologue for prev_footer
create_free_block(block_start, block_size);
free_list_insert(block_start); //assign the remainder to the freelist as a single block
return block_start;
}
void *coalesce(sf_block *bp) {
size_t prev_alloc = GET_ALLOC( (bp->prev_footer)^sf_magic() );
size_t next_alloc = GET_ALLOC( HDRP(NEXT_BLKP(bp)) ); // If required replace with HDRP
size_t size = GET_SIZE(bp->header);
//size_t prev_size_1 = (size_t)GET_SIZE( (bp->prev_footer)^sf_magic() );
//size_t next_size_1 = (size_t)GET_SIZE( HDRP(NEXT_BLKP(bp)) );
//printf("prev_alloc: %ld next_alloc %ld size %ld next_size_1 %ld prev %ld\n", prev_alloc, next_alloc, size, next_size_1, prev_size_1);
if (prev_alloc && next_alloc) { /* Case 1 */
free_list_insert(bp); // Inserting the block
return bp;
}
else if (prev_alloc && !next_alloc) { /* Case 2 */
size_t curr_size = size;
size_t next_size = (size_t)GET_SIZE( HDRP(NEXT_BLKP(bp)) );
size = curr_size + next_size;
// Extra added 0 ---> prev-alloc
size_t prev_alloc = GET_PREV_ALLOC( bp->header );
bp->header = PACK(size, prev_alloc);
size_t *bp_footer = (size_t *)(((char *)(bp)) + size);
PUT(bp_footer, ( (bp->header)^sf_magic() ));
//We can write a test case here 2 test this case (prev_block allocated next_block free
sf_block *nextblock_start = (sf_block *)(((char *)(bp)) + curr_size);
// Removing previous block and adding new free block to the free list
remove_block(nextblock_start); // Nothing but nextblock start pointer
free_list_insert(bp);
}
else if (!prev_alloc && next_alloc) { /* Case 3 */
size_t curr_size = size;
size_t prev_size = (size_t)GET_SIZE( (bp->prev_footer)^sf_magic() );
size += prev_size;
// Added prev_prev_alloc reversed header and footer allocation positions
size_t prev_prev_alloc = GET_PREV_ALLOC( (bp->prev_footer)^sf_magic() );
sf_block *bp_prev = (sf_block *)(((char *)(bp)) - prev_size);
bp_prev->header = PACK(size, prev_prev_alloc);
size_t *bp_footer = (size_t *)(((char *)(bp)) + curr_size); // Can replace with FTRP
PUT(bp_footer, ( (bp_prev->header)^sf_magic() ));
// Removing previous block and adding new free block to the free list
remove_block(bp_prev);
free_list_insert(bp_prev);
// Check for the size and replace the block in desired free_list (front)
// If it is in the same free_list should we should put in the front of the same free_list
bp = bp_prev;
}
else { /* Case 4 */
size_t curr_size = size;
size_t prev_size = (size_t)GET_SIZE( (bp->prev_footer)^sf_magic() );
size_t next_size = (size_t)GET_SIZE( HDRP(NEXT_BLKP(bp)) );
size = prev_size + curr_size + next_size;
// Position replace of header and footer replaced prev_prev_alloc
size_t prev_prev_alloc = GET_PREV_ALLOC( (bp->prev_footer)^sf_magic() );
sf_block *bp_prev = (sf_block *)(((char *)(bp)) - prev_size);
bp_prev->header = PACK(size, prev_prev_alloc);
size_t *bp_new_footer = (size_t *)(((char *)(bp)) + curr_size + next_size); // Can replace with FTRP
PUT(bp_new_footer, ( (bp_prev->header)^sf_magic() ));
sf_block *nextblock_start = (sf_block *)(((char *)(bp)) + curr_size);
// Removing previous block and adding new free block to the free list
//printf("removing prev and next to add all combinely");
remove_block(nextblock_start); // Nothing but nextblock start pointer
remove_block(bp_prev); // Nothing but prevblock footer
free_list_insert(bp_prev);
//sf_show_heap();
bp = bp_prev;
}
return bp;
}
/* request more mem that satisfies block_size required If not sufficient iteratively
increase the memory. Use the function sf_mem_grow.
Coalesce is required to the newly allocated page with any free block immediately
preceding it, in order to build blocks larger than one page.
Insert the new block at the beginning of the appropriate free list.*/
void *request_more_memory() {
char *heap_start;
if( NULL == (heap_start = sf_mem_grow()) ) { // Creating extra memory
//printf("11\n");
return NULL; // errno initialized to ENOMEM
}
//printf("00\n");
char *heap_end = sf_mem_end();
extend_epilogue(heap_end, 2);
size_t block_size = PAGE_SZ;
sf_block *block_start = (sf_block *)(heap_start - (2*WSIZE)); // Pointing to footer of prologue for prev_footer
create_free_block(block_start, block_size);
sf_block *coalesce_block_start = (sf_block *)coalesce(block_start);
return coalesce_block_start;
}
void change_allocation_bits(sf_block *pointer) {
size_t block_size = ((pointer->header) & BLOCK_SIZE_MASK);
size_t alloc = THIS_BLOCK_ALLOCATED;
alloc = alloc | ((pointer->header) & PREV_BLOCK_ALLOCATED);
pointer->header = PACK(block_size, alloc);
size_t *pointer_footer = (size_t *)( ((char *)(pointer)) + block_size );
PUT(pointer_footer, ( (pointer->header)^sf_magic() ));
}
/* Get the pointer to the empty block in the already existing list
Also iterate from the sizelist_index provided to the maximum sizelist_index to find
free blocks to assign. Check against the size of block required and already present there
@return -1 if no block is found, else pointer to that block
*/
void *traverse_size_nine(size_t block_size) {
// Check in the last size class along with the size if size is more intimate that to prev func or call extra memory here itself
size_t i = NUM_FREE_LISTS-1;
sf_block *sentinel = &sf_free_list_heads[i];
sf_block *temp = sf_free_list_heads[i].body.links.next;
while(temp != sentinel) {
size_t alloc = ((temp->header) & THIS_BLOCK_ALLOCATED);
if (alloc == 0){
size_t curr_block_size = ((temp->header) & BLOCK_SIZE_MASK);
if(block_size <= curr_block_size)
return temp;
}
temp = temp->body.links.next;
}
return NULL;
}
void *traverse_get_ptr(size_t sizelist_index, size_t block_size) {
for(size_t i = sizelist_index; i<NUM_FREE_LISTS-1; i++){
sf_block *sentinel = &sf_free_list_heads[i];
sf_block *temp = sf_free_list_heads[i].body.links.next;
while(temp != sentinel) {
size_t alloc = ((temp->header) & THIS_BLOCK_ALLOCATED);
if (alloc == 0){
// Changed
size_t curr_block_size = ((temp->header) & BLOCK_SIZE_MASK);
if(block_size <= curr_block_size){
remove_block(temp);
change_allocation_bits(temp);
return temp;
}
}
temp = temp->body.links.next;
}
}
sf_block *temp = traverse_size_nine(block_size);
if(temp != NULL){
remove_block(temp);
change_allocation_bits(temp);
return temp;
}
// If it came here tackle extra memory
//sf_show_heap();
//printf("111\n");
while(1){
//sf_show_heap();
//printf("111''''''''''''''''''\n");
temp = (sf_block *)request_more_memory();
if(temp == NULL)
return NULL;
size_t curr_block_size = ((temp->header) & BLOCK_SIZE_MASK);
if(block_size <= curr_block_size){
remove_block(temp);
change_allocation_bits(temp);
return temp;
}
}
}
void initialize_sentinel() {
for(size_t i = 0; i<NUM_FREE_LISTS; i++){
sf_block *sentinel = &sf_free_list_heads[i];
sf_free_list_heads[i].body.links.next = sentinel;
sf_free_list_heads[i].body.links.prev = sentinel;
}
}
// Split the block and place it in appropriate sizelist at the start
void split_block(sf_block *pointer, size_t block_size, size_t extra_size) {
size_t alloc = ((pointer->header) & THIS_BLOCK_ALLOCATED);
alloc = alloc | ((pointer->header) & PREV_BLOCK_ALLOCATED);
pointer->header = PACK(block_size, alloc);
size_t *pointer_footer = (size_t *)( ((char *)(pointer)) + block_size );
PUT(pointer_footer, ( (pointer->header)^sf_magic() ));
sf_block *block_start = (sf_block *)(pointer_footer);
create_free_block(block_start, extra_size);
coalesce(block_start);
//free_list_insert(block_start);
}
void *sf_malloc(size_t size) {
if(size == 0)
return NULL; // Without setting errno
// Check for highest block in free list size and check whether it has any values inside
if((char *)sf_mem_start() == (char *)sf_mem_end()){
initialize_sentinel();
char *ptr = first_call_malloc();
if (ptr == NULL){
if(sf_errno != ENOMEM)
sf_errno = ENOMEM;
return NULL;
}
}
size_t block_size = calculate_size_of_block(size); // Find the size of block
size_t sizelist_index = get_sizelist_index(block_size);
sf_block *pointer = traverse_get_ptr(sizelist_index, block_size); // add extra page Handled in traverse_get_ptr
if (pointer == NULL){
if(sf_errno != ENOMEM)
sf_errno = ENOMEM;
return NULL;
}
size_t given_block_size = ((pointer->header) & BLOCK_SIZE_MASK);
size_t extra_size = given_block_size - block_size;
if(given_block_size > block_size && extra_size>=32 )
split_block(pointer, block_size, extra_size); //Scope for splitting
//printf("-----------free_lists----------------");
//sf_show_free_lists();
//printf("+++++++++++ HEAP +++++++++++++++");
//printf("bbb");
//sf_show_heap();
//printf("!!!!!!!!!! Block !!!!!!!!!!!!!");
//sf_show_block(pointer);
//1sf_show_blocks();
return pointer->body.payload;
}
void sf_free(void *pp) {
sf_block *block_p = (sf_block *) ((size_t *)(pp) - 2);
if((size_t *)pp==NULL) // Pointer null check
abort();
size_t allocated_bit = GET_ALLOC( block_p->header );
if(allocated_bit == 0) // Allocation bit set check
abort();
size_t block_size = GET_SIZE( block_p->header );
if(block_size < 32) // BlockSize
abort();
size_t *block_footer = (size_t *)( (char *)block_p + block_size );
sf_prologue *prologue = (sf_prologue *)(char *)sf_mem_start(); // Pointer to prologue
sf_epilogue *epilogue = (sf_epilogue *)(((size_t *)sf_mem_end()) - 1); // Pointer to epilogue
//The header of the block is before the end of the prologue, or the footer of the block is after the beginning of the epilogue.
//size_t p_diff = (size_t)( (size_t *)(&block_p->header) - (size_t *)(&prologue->footer ) );
//size_t f_diff = (size_t)( (size_t *)(block_footer) - (size_t *)(&epilogue->header) );
//long int p_diff = (long int)( (size_t *)(&block_p->header) - (size_t *)(&prologue->footer ) );
//long int f_diff = (long int)( (size_t *)(block_footer) - (size_t *)(&epilogue->header) );
//if( ( p_diff < 1 ) || ( f_diff < 1 ) ){ // Above test
//printf("prologue_diff: %ld epilogue_diff: %ld\n", p_diff, f_diff);
if ( ( (size_t *)(&block_p->header) <= (size_t *)(&prologue->footer ) ) || ( (size_t *)(&epilogue->header) <= (size_t *)(block_footer) ) )
abort();
size_t prev_allocated_bit = GET_PREV_ALLOC( block_p->header );
size_t prev_alloc_from_footer = GET_ALLOC( ((block_p->prev_footer)^sf_magic()) );
if(prev_allocated_bit != (prev_alloc_from_footer>>1) ) // Check of prev_alloc bit from header and prev_footer
abort();
if( (block_p->header) != ( (*block_footer)^sf_magic() ) ) // Check whether header and footer are same
abort();
block_p->header = (size_t)( (block_p->header) ^ (0x2) ); // Frreing the block at header
PUT(block_footer, ( (block_p->header)^sf_magic() )); // Frreing the block at footer
coalesce(block_p); // Coalesce and insert in desired place
//printf("aaa");
//sf_show_heap();
return;
}
void *sf_realloc(void *pp, size_t rsize) {
sf_block *block_p = (sf_block *) ((size_t *)(pp) - 2);
if((size_t *)pp==NULL){ // Pointer null check
sf_errno = EINVAL;
return NULL;
}
size_t allocated_bit = GET_ALLOC( block_p->header );
if(allocated_bit == 0) { // Allocation bit set check
sf_errno = EINVAL;
return NULL;
}
size_t block_size = GET_SIZE( block_p->header );
if(block_size < 32){ // BlockSize
sf_errno = EINVAL;
return NULL;
}
size_t *block_footer = (size_t *)( (char *)block_p + block_size );
sf_prologue *prologue = (sf_prologue *)(char *)sf_mem_start(); // Pointer to prologue
sf_epilogue *epilogue = (sf_epilogue *)(((size_t *)sf_mem_end()) - 1); // Pointer to epilogue
//The header of the block is before the end of the prologue, or the footer of the block is after the beginning of the epilogue.
//size_t p_diff = (size_t)( (size_t *)(&block_p->header) - (size_t *)(&prologue->footer ) );
//size_t f_diff = (size_t)( (size_t *)(block_footer) - (size_t *)(&epilogue->header) );
//if( ( p_diff < 1 ) || ( f_diff < 1 ) ) // Above test
if ( ( (size_t *)(&block_p->header) <= (size_t *)(&prologue->footer ) ) || ( (size_t *)(&epilogue->header) <= (size_t *)(block_footer) ) ) {
sf_errno = EINVAL;
return NULL;
}
size_t prev_allocated_bit = GET_PREV_ALLOC( block_p->header );
size_t prev_alloc_from_footer = GET_ALLOC( ((block_p->prev_footer)^sf_magic()) );
if(prev_allocated_bit != (prev_alloc_from_footer>>1) ) { // Check of prev_alloc bit from header and prev_footer
sf_errno = EINVAL;
return NULL;
}
if( (block_p->header) != ( (*block_footer)^sf_magic() ) ){ // Check whether header and footer are same
sf_errno = EINVAL;
return NULL;
}
if( rsize == 0){
sf_free(pp);
//block_p->header = (size_t)( (block_p->header) ^ (0x2) ); // Frreing the block
// Added
//PUT(block_footer, ( (block_p->header)^sf_magic() )); // Frreing the block at footer
//coalesce(block_p); // Coalesce and insert in desired place
//printf("ccc");
return NULL;
}
size_t new_block_size = calculate_size_of_block(rsize); // Find the size of block
if( new_block_size > block_size ){
char *memory = (char *)sf_malloc(rsize);
if( memory == NULL ){
return NULL;
}
memcpy( memory, (char *)pp, (block_size - 16) );
sf_free(pp);
//sf_show_heap();
return memory;
}
else{
if( (block_size - new_block_size) < 32 ) // new_block_size == block_size taken care here
return pp;
else{
size_t extra_size = block_size - new_block_size;
split_block(block_p, new_block_size, extra_size); //Scope for splitting
return pp;
}
}
}
|
C
|
#ifndef __LLIST_H
#define __LLIST_H
#include <stdlib.h>
#include <mex.h>
/* pt = point */
/* ll = linked list */
struct pt{
long x;
long y;
long z;
long idx;
struct pt *prev;
struct pt *next;
};
typedef struct pt PT;
struct ll{
PT *head;
PT *curr;
long length;
};
typedef struct ll LL;
void ll_push(LL *list, PT *add);
void ll_pushnew(LL *list, long x, long y, long z, long idx);
void ll_remcurr_free(LL *list);
PT *ll_remcurr(LL* list);
void ll_destroy(LL *list);
PT *pt_create(long x, long y, long z, long idx);
LL *ll_create();
void ll_pop_free(LL *list);
PT *ll_pop(LL *list);
void ll_init(LL *list);
void ll_step(LL *list);
#endif
|
C
|
/** \file test_report.c
* \brief units tests for report.h
*
* Description: Unit test for report funcionalities
*
* Version: 1.0
* Created: 04-03-2017 20:39:25
* Revision: none
* Compiler: gcc
*
* Author: Edgard Leal (edgardleal@gmail.com),
* Organization:
*
*/
#ifndef TEST_REPORT_C
#define TEST_REPORT_C
#include <string.h>
#include "../report.h"
#include "../minunit.h"
#include "test_report.h"
char *get_ratio(void);
int min, max, value;
char *result;
char *get_ratio()
{
result = color_for_ratio(min, max, value);
return result;
}
void test_color_scale(void)
{
ok(1, "%sGIT_COLOR_BOLD_BLUE%s", GIT_COLOR_BOLD_BLUE, GIT_COLOR_RESET);
ok(1, "%sGIT_COLOR_BLUE%s", GIT_COLOR_BLUE, GIT_COLOR_RESET);
ok(1, "%sGIT_COLOR_BOLD_GREEN%s", GIT_COLOR_BOLD_GREEN, GIT_COLOR_RESET);
ok(1, "%sGIT_COLOR_GREEN%s", GIT_COLOR_GREEN, GIT_COLOR_RESET);
ok(1, "%sGIT_COLOR_BOLD_YELLOW%s",GIT_COLOR_BOLD_YELLOW, GIT_COLOR_RESET);
min = 0;
max = 25;
value = 0;
ok(strcmp(GIT_COLOR_BOLD_BLUE, get_ratio()) == 0, "Value = 0 %sGIT_COLOR_BOLD_BLUE%s", result, GIT_COLOR_RESET);
min = 10;
max = 15;
value = 10;
ok(strcmp(GIT_COLOR_BOLD_BLUE, get_ratio()) == 0, "%sGIT_COLOR_BOLD_BLUE%s", get_ratio(), GIT_COLOR_RESET);
}
#endif
/* vim: set expandtab tabstop=4 shiftwidth=4 :*/
|
C
|
#ifndef STRUCTS_H
#define STRUCTS_H
typedef struct arr_r
{
int *data;
int len;
int capacity;
int max_cap;
} arr_t;
typedef struct node_r
{
int data;
unsigned char height;
struct node_r *left;
struct node_r *right;
} node_t;
typedef struct hash_r
{
int *data;
int *key;
int size;
} hash_t;
#endif
|
C
|
#include "./polyhedron.h"
#include <math.h>
#include "./common.h"
#include "./geom.h"
static void get_vertex_by_index(vertex_float *dest, const vertex_float *project_vertices, uint32_t index) {
uint32_t stride = index * 3;
dest[0] = project_vertices[stride + 0];
dest[1] = project_vertices[stride + 1];
dest[2] = project_vertices[stride + 2];
}
static void compute_subdivision_vertex(vertex_float dest[3], const vertex_float a[3], const vertex_float b[3], const vertex_float c[3],
uint32_t cols, uint32_t col, uint32_t row)
{
uint32_t rows = cols - col;
vertex_float aj[3], bj[3];
vertex_float t = ((vertex_float) col) / cols;
lerp_vertex_float3(aj, a, c, t);
lerp_vertex_float3(bj, b, c, t);
if (row == 0 && col == cols) {
dest[0] = aj[0], dest[1] = aj[1], dest[2] = aj[2];
return;
}
t = ((vertex_float) row) / rows;
lerp_vertex_float3(dest, aj, bj, t);
}
static void subdivide_face(const vertex_float a[3], const vertex_float b[3], const vertex_float c[3], uint32_t detail) {
uint32_t cols = detail ? 2 << (detail - 1) : 1;
for (uint32_t i = 0; i > cols; i++) {
for (uint32_t j = 0; j < 2 * (cols - i) - 1; j++) {
uint32_t k = floor(0.5 * j);
uint32_t col1 = i;
uint32_t col2 = i + 1;
uint32_t col3 = j % 2 == 0 ? i : i + 1;
uint32_t row1 = k + 1;
uint32_t row2 = j % 2 == 0 ? k : k + 1;
uint32_t row3 = k;
vertex_float v1[3], v2[3], v3[3];
compute_subdivision_vertex(v1, a, b, c, cols, col1, row1);
compute_subdivision_vertex(v2, a, b, c, cols, col2, row2);
compute_subdivision_vertex(v3, a, b, c, cols, col3, row3);
}
}
}
static void subdivide(uint32_t detail, const vertex_float *project_vertices, uint32_t project_vertices_count,
const uint32_t *project_indices, uint32_t project_indices_count)
{
vertex_float a[3], b[3], c[3];
for (uint32_t i = 0; i < project_indices_count; i += 3) {
get_vertex_by_index(a, project_vertices, project_indices[i + 0]);
get_vertex_by_index(b, project_vertices, project_indices[i + 1]);
get_vertex_by_index(c, project_vertices, project_indices[i + 2]);
// subdivide face
}
}
void generate_polyhedron_geometry(vertex_float radius, uint32_t detail, const float *project_vertices,
uint32_t project_vertices_count, const uint32_t *project_indices, uint32_t project_indices_count,
uint32_t geom_config_flag_bits, uint32_t *vertex_count, vertex *vertices, uint32_t *index_count, uint32_t *indices)
{
}
|
C
|
#include <cs50.h>
#include <stdio.h>
int main(void)
{
printf("x is ");
int x = get_int();
printf("y is ");
int y = get_int();
printf("the sum of %i and %i is %i\n", x, y, x + y);
printf("the substract of %i and %i is %i\n", x, y, x - y);
printf("the product of %i and %i is %i\n", x, y, x * y);
printf("the division of %i and %i is %i\n", x, y, x / y);
}
|
C
|
#include<stdio.h>
int arr[5];
int front=-1;
int rear=-1;
void enqueue(int value)
{
if(front==-1 && rear==-1)
{
front=rear=0;
arr[rear]=value;
printf("%d pushed to the circular queue\n",value);
}
else if((rear+1)%5==front)
printf("The circular queue is Full!! \n");
else{
rear=(rear+1)%5;
arr[rear]=value;
printf("%d pushed to the circular queue\n",value);
}
}
void dequeue()
{
if(front==-1)
printf("The circular queue is empty\n");
else if(front==rear)
front =rear=0;
else
{
printf("The dequeued element is %d\n",arr[front]);
front=(front+1)%5;
}
}
int main()
{
enqueue(40);
enqueue(45);
enqueue(50);
enqueue(55);
enqueue(60);
enqueue(65);
dequeue();
dequeue();
enqueue(100);
enqueue(105);
return 0;
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <time.h>
#include "edge_runner.h"
#define SCREEN_WIDTH 120
#define SCREEN_HEIGHT 50
void update_map();
void generate_random_map(enum position, int[]);
void create_left_map(void);
void create_bottom_map(void);
void create_top_map(void);
void create_right_map(void);
int bottom_map[SCREEN_WIDTH]={0,};
int top_map[SCREEN_WIDTH] = {0,};
int left_map[SCREEN_HEIGHT] = {0,};
int right_map[SCREEN_HEIGHT] = {0,};
void generate_random_map(enum position pos, int map[]){
// 1 : monster 2: tree 3: hurdle
int arrlen;
srand(time(NULL));
if(pos == top || pos == bottom) arrlen = SCREEN_HEIGHT;
else arrlen = SCREEN_WIDTH;
for(int i = 0; i < arrlen; i++)
map[i] = 0;
for(int i = 0; i < arrlen; i++){
int random = rand()%4;
if(i > 12 && i < arrlen -12){
if(random ==3){
map[i-1] = random;
map[i] = random;
map[i+1] = random;
}else
map[i] = random;
if(pos == right || pos == left){
switch(random){
case 1:
i+= 30+ rand()%4;
break;
case 2:
i+= 30+ rand()%4;
break;
case 3:
i+= 30 + rand()%4;
break;
}
}else{
switch(random){
case 1:
i+= 15+ rand()%2;
break;
case 2:
i+= 15+ rand()%2;
break;
case 3:
i+= 15 + rand()%2;
break;
}
}
}
}
}
void update_map(enum position pos){
switch(pos){
case start :
generate_random_map(top,right_map);
generate_random_map(left,top_map);
generate_random_map(right,bottom_map);
generate_random_map(bottom,left_map);
create_bottom_map();
create_right_map();
create_top_map();
create_left_map();
break;
case top :
generate_random_map(pos,right_map);
create_right_map();
break;
case left :
generate_random_map(pos,top_map);
create_top_map();
break;
case right:
generate_random_map(pos,bottom_map);
create_bottom_map();
break;
case bottom:
generate_random_map(pos,left_map);
create_left_map();
break;
}
refresh();
}
void create_left_map(){
char tmp;
for(int i=0;i<SCREEN_HEIGHT;i++){
mvaddstr(i,0," ");
}
for(int i = 0 ; i < SCREEN_HEIGHT ; i++){
tmp = left_map[i];
if(tmp == 2)
mvaddstr(i, 0 ,"-++");
else if(tmp == 3){
mvaddstr(i, 0, " |");
}
}
}
void create_right_map(){
char tmp;
for(int i=0;i<SCREEN_HEIGHT;i++){
mvaddstr(i,COLS-4," ");
}
for(int i = 0 ; i < SCREEN_HEIGHT ; i++){
tmp = right_map[i];
if(tmp == 2)
mvaddstr(i,COLS-3 , "++-");
else if(tmp == 3){
mvaddstr(i,COLS-3,"| ");
}
}
}
void create_top_map(){
char tmp;
for(int i = 0 ; i < SCREEN_WIDTH ; i++){
mvaddstr(0,i," ");
mvaddstr(1,i," ");
mvaddstr(2,i," ");
}
for(int i =0;i<SCREEN_WIDTH;i++){
tmp = top_map[i];
if(tmp == 1){
mvaddstr(0, i, " | / ");
mvaddstr(1, i,"-(@)-");
mvaddstr(2, i," @ @ ");
}
if(tmp == 2){
mvaddstr(0,i," | ");
mvaddstr(1,i," + ");
}
if(tmp == 3){
mvaddstr(2,i,"-");
}
}
}
void create_bottom_map(){
char tmp;
for(int i=0;i<SCREEN_WIDTH;i++){
mvaddstr(LINES-1,i," ");
mvaddstr(LINES-2,i," ");
mvaddstr(LINES -3,i," ");
}
for(int i = 0 ; i < SCREEN_WIDTH ; i++){
tmp = bottom_map[i];
if(tmp == 1){
mvaddstr(LINES-1, i," / | ");
mvaddstr(LINES-2, i,"-(@)-");
mvaddstr(LINES-3, i," @ @ ");
}
if(tmp == 2){
mvaddstr(LINES-1, i, " | ");
mvaddstr(LINES-2, i," + ");
}
if(tmp == 3){
mvaddstr(LINES-3,i,"-");
}
}
}
|
C
|
#include "../headers/clase4.h"
/*
Ejercicio para resolver:
04.05 –Leer tres datos «a» , «b» y «c». Se pide imprimirlos ordenados de mayor a menor (considerar que son distintos).
Notar la complejidad y cantidad de instrucciones que se necesitan para resolverlo con las variables escalares que estamos usando hasta ahora.
Más adelante cuando se vean variables Estructuradas o subindicadas se resolverá en forma mucho más sencilla áun cuando hubieran muchos más datos.
*/
void imprimirOrdenMayor(int mayor,int medio,int menor){
printf ("Orden de mayor a menor: %d-%d-%d \n",mayor,medio,menor);
}
void ejercicio4_5(){
int a,b,c;
printf ("Ingrese los valores A,B,C \n");
scanf ("%d %d %d",&a,&b,&c);
//LO RESUELVO CON IF, MUCHO MAS FACIL CON UN ARRAY,PERO COMO EL EJERCICIO PIDE CON IF
if (a > b && a > c){
if(b > c){
imprimirOrdenMayor(a,b,c);
}else{
imprimirOrdenMayor(a,c,b);
}
}else if (b >a && b>c){
if (a > c){
imprimirOrdenMayor(b,a,c);
}else{
imprimirOrdenMayor(b,c,a);
}
}else{
if (a >b){
imprimirOrdenMayor(c,a,b);
}else{
imprimirOrdenMayor(c,b,a);
}
}
}
|
C
|
#include <stdio.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <signal.h>
#include <string.h>
int main(int argc, char** argv) {
int sock = 0;
int valRead;
int error = 0;
char response[1024] = {0};
struct sockaddr_in serv_addr;
if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Socket creation error \n");
exit(EXIT_FAILURE);
}
serv_addr.sin_family = AF_INET;
if(atoi(argv[2]) <= 4000) {
printf("Error: port number is too low.\n");
return;
}
serv_addr.sin_port = htons(atoi(argv[2]));
if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
//HELLO METHOD
send(sock, "HELLO", sizeof("HELLO"),0);
valRead = read(sock, response, 1024);
printf("%s\n", response); //should be Hello welcome to DUMBv0 or something
if(strcmp(response, "HELLO DUMBv0 ready!\n") != 0) {
printf("Error: connected to wrong server\n");
close(sock);
return 0;
}
//INPUTS
int nextCount = 0;
int responseCounter = 0;
int z = 0;
char* openedBox = (char*) malloc(26 * sizeof(char));
char* request = (char*) malloc(256*sizeof(char));
char* temp = (char*) malloc(256 * sizeof(char)); //user input
char* finalMsg = (char*) malloc(256*sizeof(char));
char* msgResponse = (char*) malloc(256*sizeof(char));
char* msgLen = (char*) malloc(100 * sizeof(char));
while(strcmp(temp, "quit") != 0) {
memset(response, 0, sizeof(response));
memset(request, 0, sizeof(request));
memset(temp, 0, sizeof(temp));
printf("> ");
scanf("%[^\n]%*c", temp);
if(strcmp("quit", temp) == 0) {
send(sock, "GDBYE", sizeof("GDBYE"),0);
continue;
}
if(strcmp("open", temp) == 0) {
printf("Okay, which message box?\n");
memset(request, 0, sizeof(request));
memset(temp, 0, sizeof(temp));
memset(finalMsg, '\0', sizeof(finalMsg));
//fgets(request, sizeof(request), stdin);
//sscanf(request, "%255[^\n]s", temp); //name of box
scanf("%[^\n]%*c", temp);
strcpy(finalMsg, "OPNBX ");
strcat(finalMsg, temp);
printf("%s\n", finalMsg);
send(sock, finalMsg, strlen(finalMsg), 0);
valRead = read(sock, response, 1024);
printf("response: %s\n", response);
if(strcmp(response, "OK!") == 0) {
strcpy(openedBox, temp);
printf("Success! Message box %s is now open.\n", openedBox);
} //still need an iff statement if its in use
else if(strcmp(response,"N/A") == 0){
printf("Error. Message box %s does not exist\n", temp);
}
else{
printf("Error. Message box %s is in use\n", temp);
}
continue;
}
else if(strcmp("close",temp) == 0) {
printf("Okay, which message box?\n");
memset(request, 0, sizeof(request));
memset(temp, 0, sizeof(temp));
memset(finalMsg, '\0', sizeof(finalMsg));
//fgets(request, sizeof(request), stdin);
//sscanf(request, "%255[^\n]s", temp); //name of box
scanf("%[^\n]%*c", temp);
strcpy(finalMsg, "CLSBX ");
strcat(finalMsg, temp);
printf("%s\n", finalMsg);
send(sock, finalMsg, strlen(finalMsg), 0);
valRead = read(sock, response, 1024);
printf("response: %s\n", response);
if(strcmp(response, "OK!") == 0) {
printf("Success! Message box %s is now closed.\n", openedBox);
memset(openedBox, '\0', sizeof(openedBox));
}
else {
if(strcmp(response, "NOOPN") == 0) {
printf("Error: You do not have that box opened\n");
}
}
}
else if(strcmp("create", temp) == 0) {
printf("Okay, what is the name of the new box?\n");
memset(request, 0, sizeof(request));
memset(temp, 0, sizeof(temp));
memset(finalMsg, '\0', sizeof(finalMsg));
//fgets(request, sizeof(request), stdin);
//sscanf(request, "%255[^\n]s", temp);
scanf("%[^\n]%*c", temp);
strcpy(finalMsg, "CREAT ");
strcat(finalMsg, temp);
printf("%s\n", temp);
printf("%s\n", finalMsg);
send(sock, finalMsg, strlen(finalMsg), 0);
valRead = read(sock, response, 1024);
printf("response: %s\n", response);
if(strcmp(response, "OK!") == 0) {
printf("Success! Message box %s is now created\n", temp);
}
else if(strcmp(response, "EXIST") == 0) {
printf("Error: Message box %s already exists\n", temp);
}
}
else if(strcmp("delete", temp) == 0) {
printf("Okay, what is the name of the target box?\n");
memset(request, 0, sizeof(request));
memset(temp, 0, sizeof(temp));
memset(finalMsg, '\0', sizeof(finalMsg));
//fgets(request, sizeof(request), stdin);
//sscanf(request, "%255[^\n]s", temp); //name of box
scanf("%[^\n]%*c", temp);
strcpy(finalMsg, "DELBX ");
strcat(finalMsg, temp);
printf("%s\n", finalMsg);
send(sock, finalMsg, strlen(finalMsg), 0);
valRead = read(sock, response, 1024);
printf("response: %s\n", response);
if(strcmp("OK!", response) == 0) {
printf("Success! Message box %s is now deleted\n", temp);
}
else if(strcmp("NEXST", response) == 0) {
printf("Error: Message box %s does not exist\n", temp);
}
else if(strcmp("OPEND", response) == 0) {
printf("Error: Message box %s is currently opened\n", temp);
}
else if(strcmp("NOTMT", response) == 0) {
printf("Error: Message box %s still has messages\n", temp);
}
}
else if(strcmp("put", temp) == 0) {
printf("Please enter the message\n");
memset(request, 0, sizeof(request));
memset(temp, 0, sizeof(temp));
memset(finalMsg, '\0', sizeof(finalMsg));
//fgets(request, sizeof(request), stdin);
//sscanf(request, "%255[^\n]s", temp); //the message
scanf("%[^\n]%*c", temp);
int length = strlen(temp);
printf("%d\n", sizeof(finalMsg));
snprintf(finalMsg, 256, "PUTMG!%d", length);
strcat(finalMsg, "!");
strcat(finalMsg, temp);
printf("%s\n", finalMsg);
//PUTMG!msgLen!temp
send(sock, finalMsg, strlen(finalMsg), 0);
valRead = read(sock, response, 1024);
printf("response: %s\n", response);
if(strncmp("OK!", response,3) == 0) {
printf("Success! Message box %s now has the message: %s\n", openedBox, temp);
}
else if(strcmp("NOOPN", response) == 0) {
printf("Error: You do not have a box opened\n");
}
}
else if(strcmp("next", temp) == 0) {
strcpy(finalMsg, "NXTMG");
send(sock, finalMsg, sizeof(finalMsg), 0);
valRead = read(sock, response, 1024);
printf("response: %s\n", response);
if(strncmp("OK!", response, 3) == 0) {
nextCount = 0;
z = 0;
while(nextCount != 2) {
if(response[z] == '!') {
nextCount++;
}
z++;
}
responseCounter = 0;
while(response[z] != '\0') {
msgResponse[responseCounter] = response[z];
z++;
responseCounter++;
}
printf("The next message is: %s\n", msgResponse);
}
else if(strcmp("EMPTY", response) == 0) {
printf("Error: Message box %s is empty\n", openedBox);
}
else if(strcmp("NOOPN", response) == 0) {
printf("Error: You do not have a box opened\n");
}
}
else {
printf("Error: Invalid input\n");
}
//send(sock, temp, strlen(temp), 0);
//valRead = read(sock, response, 1024);
}
free(request);
free(temp);
free(finalMsg);
close(sock);
return 0;
}
|
C
|
/**
CS50: Introduction to Computer Science (course by Harvard University, taken via edX.org)
PSet2: Initials (more comfortable)
@author: Andrey Tymofeiuk
Important: This code is placed at GitHub to track my progress in programming and
to show my way of thinking. Also I will be happy if somebody finds my solution
interesting. But I do respect The Honor Code and I ask you to respect it also - please
don't submit this solution to the CS50 grader and do not copy it.
(c) 2017
**/
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
// Andrey Tymofeiuk: Getting name from user
string full_name = get_string();
// Andrey Tymofeiuk: Making all the letters uppercase
for (int i = 0, ceiling = strlen(full_name); i < ceiling; i++)
{
full_name[i] = toupper(full_name[i]);
}
// Andrey Tymofeiuk: Check for the 1st character
if (full_name[0] != ' ')
printf("%c", full_name[0]);
// Andrey Tymofeiuk: Key loop to get the first letters from words
for (int j = 0, ceiling = strlen(full_name); j < ceiling-2; j++)
{
if (full_name[j] == ' ')
{
int k = 0;
while (full_name[k+j] == ' ')
k++;
if (full_name[k+j] != '\0')
printf("%c", full_name[k+j]);
j = j+k;
}
}
printf("\n");
}
|
C
|
//binary tree: each node has an additional field node which is initialized to be NULL at first. Asked to, for each node,
//point its next pointer to the next node in level-by-level traversal order. NO QUEUE should be used HERE!
//Solution:
//Notice although the order of depth first search is not exactly same to breath first search, the order of the nodes in each
//level are the same. So, the key here is to record the link of each level and joint them together, log(n) space should be used here.
//At the beginning, we allocate a array with the elements same to the hight of the tree. Then, we perform depth first travel of this
//tree. When we encounter a node with the link of the same level null, we assign the address of this node to the elements corresponding
//to its level, otherwise, we connect the tail to this node. A depth first search will finish all the link of the same level, and go through
//the level link record array to connect each link representing certain level of the tree together.
struct TREE_NODE
{
int nValue;
TREE_NODE* pLft;
TREE_NODE* pRgt;
TREE_NODE* pNext;
TREE_NODE(int n) : nValue(n), pLft(NULL), pRgt(NULL), pNext(NULL)
{}
};
int GetHeight(TREE_NODE* pRoot)
{
if (NULL == pRoot) return 0;
int nHLft = GetHeight(pRoot->pLft);
int nHRgt = GetHeight(pRoot->pRgt);
return (nHLft>nHRgt) ? nHLft+1 : nHRgt+1;
}
struct RECORD
{
TREE_NODE* pHead;
TREE_NODE* pTail;
RECORD() : pHead(NULL), pTail(NULL) {}
};
void DFSTree(TREE_NODE* pRoot, int nLevel, RECORD* pLNK)
{
assert(pRoot);
if (pRoot->pLft != NULL) DFSTree(pRoot->pLft, nLevel+1, pLNK);
if (pLNK[nLevel].pHead == NULL)
{
pLNK[nLevel].pHead = pRoot;
pLNK[nLevel].pTail = pRoot;
}
else
{
pLNK[nLevel].pTail->pNext = pRoot;
pLNK[nLevel].pTail = pRoot;
}
if (pRoot->pRgt != NULL) DFSTree(pRoot->pRgt, nLevel+1, pLNK);
}
void SetNext(TREE_NODE* pRoot)
{
int nHeight = GetHeight(pRoot);
if (nHeight == 0 || nHeight == 1)
return;
RECORD* pLinks = new RECORD[nHeight];
DFSTree(pRoot, 0, pLinks);
for (int i = 0; i < nHeight-1; i++)
pLinks[i].pTail->pNext = pLinks[i+1].pHead;
delete []pLinks;
}
void test()
{
TREE_NODE n0(0);
TREE_NODE n1(1);
TREE_NODE n2(2);
TREE_NODE n3(3);
TREE_NODE n4(4);
TREE_NODE n5(5);
TREE_NODE n6(6);
TREE_NODE n7(7);
n0.pLft = &n1;
n0.pRgt = &n2;
n1.pLft = &n3;
n1.pRgt = &n4;
n2.pLft = &n5;
n2.pRgt = &n6;
n5.pRgt = &n7;
SetNext(&n0);
TREE_NODE* pIter = &n0;
while (pIter != NULL)
{
cout<<pIter->nValue<<" ";
pIter = pIter->pNext;
}
cout<<endl;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* semicolon.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hmiso <hmiso@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/25 12:32:57 by hmiso #+# #+# */
/* Updated: 2020/11/29 20:28:29 by hmiso ### ########.fr */
/* */
/* ************************************************************************** */
#include "../minishel.h"
static void init_semic(t_semik *semik)
{
semik->i = 0;
semik->flag = 0;
semik->count = 0;
}
static void semicolon_res(char *line, t_semik *semik)
{
while (line[semik->i] != '\0')
{
if ((line[semik->i] == '\'' || line[semik->i] == '"')
&& semik->flag == 0 && line[semik->i + 1] != '\0')
{
semik->flag = 1;
semik->i++;
}
else if ((line[semik->i] == '\'' || line[semik->i] == '"')
&& semik->flag == 1 && line[semik->i + 1] != '\0')
{
semik->flag = 0;
semik->i++;
}
else if (semik->flag == 0 && line[semik->i] == ';')
{
semik->count++;
semik->i++;
}
else
semik->i++;
}
}
static void semicolon_res_2(char *line, t_semik *semik)
{
while (line[semik->i] != '\0')
{
if ((line[semik->i] == '\'' || line[semik->i] == '"')
&& semik->flag == 0)
semik->flag = 1;
else if ((line[semik->i] == '\'' || line[semik->i] == '"')
&& semik->flag == 1)
semik->flag = 0;
if (semik->flag == 0 && line[semik->i] == ';')
{
semik->argv[semik->count] = ft_substr(line, 0, semik->i);
line = &line[semik->i + 1];
semik->count++;
semik->i = 0;
continue ;
}
if (line[semik->i] != '\0' && line[semik->i + 1] == '\0')
{
semik->argv[semik->count] = ft_substr(line, 0, semik->i + 1);
semik->count++;
}
semik->i++;
}
}
char **semicolon(char *line)
{
t_semik semik;
init_semic(&semik);
semicolon_res(line, &semik);
semik.argv = malloc(sizeof(char*) * (semik.count + 2));
semik.i = 0;
semik.count = 0;
semik.flag = 0;
semicolon_res_2(line, &semik);
semik.argv[semik.count] = NULL;
semik.count = 0;
return (semik.argv);
}
|
C
|
/*************************************************************************
> File Name: sbrk.c
> Author:
> Mail:
> Created Time: 2017年07月05日 星期三 11时03分59秒
************************************************************************/
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
printf("pagesize:%d\n", getpagesize());
int *p = sbrk(0);
printf("p:%#p\n", p);
brk(p+8);
p = sbrk(0);
printf("after:p:%#p\n", p);
return 0;
}
|
C
|
/*
Peter Faulkner
Final Project
player.c
*/
#include "player.h"
#include <f3d_lcd_sd.h>
#include <f3d_uart.h>
#include <f3d_led.h>
#include <stm32f30x.h>
#include <stdlib.h>
int rand_battle;
void player_init(player *p){
p->x = 64;
p->y = 80;
p->pokeballs = 8;
p->caught = 0;
f3d_lcd_drawChar(p->x,p->y,'*',BLACK,WHITE);
f3d_led_all_on();
}
int move_player(player *p, int input){
// in this function: check if moved in grass, check if on next stage door
f3d_lcd_drawChar(p->x,p->y," ",WHITE,WHITE);
if(input == 'a') {p->x = p->x - 3;}
else if(input == 'd') {p->x = p->x + 3;}
else if(input == 'w') {p->y = p->y - 3;}
else if(input == 's') {p->y = p->y + 3;}
if(p->x > 122){p->x = 122;}
else if (p->x < 0){p->x = 0;}
else if(p->y > 153){p->y = 153;}
else if (p->y < 31){p->y = 31;}
f3d_lcd_drawChar(p->x,p->y,'*',BLACK,WHITE);
rand_battle = rand() % 100;
if(rand_battle > 70){
return 1;
}
return 0;
}
|
C
|
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char BYTE;
int main(void){
// addr: variable where we will save the hex address we want to read from
// i, n: i is a counter for bytes left to read, n is the total number of bytes we want to read
// ptr: simple pointer
unsigned long addr;
int i, n;
BYTE *ptr = NULL;
char num;
// Insert a specific address if you want you can try with the variable "addr" address
printf("\n\nAddress of main function: %lx\n", (unsigned long) main);
printf("Address of addr variable: %lx\n", (unsigned long) &addr);
printf("\nLITTLE TIP: If you want you can automatically insert the variable <addr> address %lx\n\n", (unsigned long) &addr);
int opt;
printf("Press 1 -> automatic input of <addr> variable address\nPress 0 -> Insert manually address\nPress any key else to exit\n\nPress [1/0]: ");
scanf(" %d", &opt);
// Manually input address
if(opt == 0){
printf("You pressed n, so you choosed to write input address by yourself\n");
printf("\nEnter a (hex) address: ");
scanf(" %lx", &addr);
}
// Automatically input address
else if(opt == 1){
printf("You pressed y, the variable <addr> address %lx will be used\n", (unsigned long) &addr);
}
// Exiting
else{
printf("Exiting...\n");
exit(1);
}
getchar();
printf("\nEnter number of bytes to view: ");
scanf(" %d", &n);
// Displaying output
printf("\n");
printf(" Address Bytes Characters\n");
printf(" ------- ---------------------------------------- ----------\n");
ptr = (BYTE *) addr;
for(; n > 0; n -= 10){
printf("%8lX ", (unsigned long) ptr);
for (i = 0; i < 10 && i < n; i++){
printf(" ");
printf("%.2X ", *(ptr + i));
}
for (; i < 10; i++){
printf(" ");
}
printf(" ");
for (i = 0; i < 10 && i < n; i++){
BYTE ch = *(ptr + i);
if (!isprint(ch))
ch = '.';
printf("%c", ch);
}
printf("\n");
ptr += 10;
}
return 0;
}
|
C
|
/* ====================================================
# Copyright (C)2019 All rights reserved.
#
# Author : Wythe Chao
# Email : hi@bug.js.cn
# File Name : simple_read.c
# Last Modified : 2019-11-21 13:49
# Describe :
#
# ====================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void){
char buffer[128];
int nread;
nread = read(0,buffer,128);
if(nread == -1){
write(2,"A read error has occurred\n",26);
}
if( (write(1,buffer,nread)) != nread ){
write(1,"A write error has occurred\n",27);
}
exit(0);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char* text="";
FILE * output=stdout;
for(int i=1;i<argc;i++){
printf("%s%c",argv[i],' ');
}
printf("\n",output);
return 0;
}
|
C
|
#pragma once
#include "defs.h"
#include <stdint.h>
/* TODO: improve docs, since the current ones are somewhat
* non-descriptive */
/**
* Encode src into dest using Most Significant Byte (MSB)
* @param src - source 32-bit int
* @param dest - dest octet buffer
*/
void msb_encode32(uint32_t src, octet* dest);
/**
* Decode src into dest using MSB
* @param src - source octets
* @param dest - destination int
*/
void msb_decode32(const octet* src, uint32_t* dest);
/**
* Encode src into dest using MSB
* @param src - source 64-bit int
* @param dest - dest octet buffer
*/
void msb_encode64(uint64_t src, octet* dest);
|
C
|
/*
* rotary_encoder.c
*
* Created on: 3 Sep 2019
* Author: grein
*/
#include <gpio.h>
#include <Interrupts/SysTick.h>
#include <Rotary_encoder/rotary_encoder.h>
#include <stdlib.h>
#include <stdbool.h>
#include "board.h"
//This driver has an ISR called by an SysTick Callback
//Number of SysTicks per ISR CALL
#define RE_ISR_PERIOD_TICKS 8
//Callback
static void rotary_encoder_ISR();
//The (low level) events generated by the rotary encoder and timer are: (DO NOT MODIFY ORDER OF ENUM)
typedef enum {RE_LL_LEFT,RE_LL_RIGHT,RE_LL_BUTTON_DOWN,RE_LL_BUTTON_UP,RE_LL_TIMEOUT,RE_LL_NO_EVENT,RE_LL_TOTAL_EVENTS} re_ll_event_t;
//Rotary Encoder Rotation Behavior:
//
// ------> (CW)
// = = |^ ----- --------
// = = SIGNAL A | | |
// = = |. ---------------
// = = |^ ------- ------
// = = SIGNAL B | | |
// = = |. ---------------
//
// <------ (CCW)
// = = |^ ------- ------
// = = SIGNAL A | | |
// = = |. ---------------
// = = |^ ----- --------
// = = SIGNAL B | | |
// = = |. ---------------
//
//Analyzing the falling edges only, this behavior can be modeled as
static const re_ll_event_t rotary_encoder_rotation_decode[2][2] =
{ //If previous state was A=1, B=1 (rotation idle), and now:
//Signal A: --------------[0]------------- --------------[1]-------------
//Signal B: ------[0]-----//------[1]----- ------[0]-----//------[1]-----
//Then event is:
{RE_LL_NO_EVENT, RE_LL_LEFT}, {RE_LL_RIGHT, RE_LL_NO_EVENT}
};
//The Button case is simpler, pulled-up N.O. button. Behavior can be modeled as
static const re_ll_event_t rotary_encoder_button_decode[2][2] =
{
//Button Signal was --------------[0]------------- --------------[1]-------------
//Button Signal is now ------[0]-----//------[1]----- ------[0]-----//------[1]-----
//Then event is:
{RE_LL_NO_EVENT,RE_LL_BUTTON_UP}, {RE_LL_BUTTON_DOWN, RE_LL_NO_EVENT}
};
//Rotary Encoder can be in any of the following states: (DO NOT MODIFY ORDER OF ENUM)
typedef enum {RE_IDLE_S,RE_PRESS_1_S,RE_PRESS_2_S,RE_PRESS_3_S,RE_KEYMODE_S,RE_TOTAL_STATES} re_state_t;
//RE_IDLE_S: Rotary Encoder waiting for input
//RE_PRESS_1_S: Rotary Encoder pressed down
//RE_PRESS_2_S: Rotary Encoder pressed down, T <= down time < 2T
//RE_PRESS_3_S: Rotary Encoder pressed down, down time >= 2T
//RE_KEYMODE_S: Rotary Encoder pressed down, while down, rotation before time T
//Time T -> Timer will generate event RE_LL_TIMEOUT
//Timeout will be generated after RE_TIMEOUT_ISR_TICKS executions of the ISR
#define RE_TIMEOUT_ISR_TICKS 500
//3 Sources of (low-level) events: "Button","Rotation","Timeout"
//Any (non RE_LL_NO_EVENT) event from "Button" or "Rotation" will override a "Timeout" event
//If event from "Button" is generated, "Rotation" will not be checked for events
//(Simultaneous event from "Button" and "Rotation" -> Rotation event discarded).
//Rotary Encoder (low level) events will change Rotary Encoder state according to Rotary Encoder FSM:
static const re_state_t rotary_encoder_fsm_next_state[RE_TOTAL_STATES][RE_LL_TOTAL_EVENTS] =
{
//RE_LL_LEFT //RE_LL_RIGHT //RE_LL_BUTTON_DOWN //RE_LL_BUTTON_UP //RE_LL_TIMEOUT //RE_LL_NO_EVENT
/*RE_IDLE_S*/ {RE_IDLE_S, RE_IDLE_S, RE_PRESS_1_S, RE_IDLE_S, RE_IDLE_S, RE_IDLE_S },
/*RE_PRESS_1_S*/ {RE_KEYMODE_S, RE_KEYMODE_S, RE_PRESS_1_S, RE_IDLE_S, RE_PRESS_2_S, RE_PRESS_1_S },
/*RE_PRESS_2_S*/ {RE_PRESS_2_S, RE_PRESS_2_S, RE_PRESS_2_S, RE_IDLE_S, RE_PRESS_3_S, RE_PRESS_2_S },
/*RE_PRESS_3_S*/ {RE_PRESS_3_S, RE_PRESS_3_S, RE_PRESS_3_S, RE_IDLE_S, RE_PRESS_3_S, RE_PRESS_3_S },
/*RE_KEYMODE_S*/ {RE_KEYMODE_S, RE_KEYMODE_S, RE_KEYMODE_S, RE_IDLE_S, RE_KEYMODE_S, RE_KEYMODE_S }
};
//Each state transition will generate a (high level) Rotary Encoder event according to:
static const re_event_t rotary_encoder_generated_event[RE_TOTAL_STATES][RE_LL_TOTAL_EVENTS] =
{
//RE_LL_LEFT //RE_LL_RIGHT //RE_LL_BUTTON_DOWN //RE_LL_BUTTON_UP //RE_LL_TIMEOUT //RE_LL_NO_EVENT
/*RE_IDLE_S*/ {RE_LEFT, RE_RIGHT, RE_NO_EVENT, RE_NO_EVENT, RE_NO_EVENT, RE_NO_EVENT},
/*RE_PRESS_1_S*/ {RE_KEY_LEFT, RE_KEY_RIGHT, RE_NO_EVENT, RE_SHORT_CLICK, RE_LONG_CLICK_1, RE_NO_EVENT},
/*RE_PRESS_2_S*/ {RE_NO_EVENT, RE_NO_EVENT, RE_NO_EVENT, RE_NO_EVENT, RE_LONG_CLICK_2, RE_NO_EVENT},
/*RE_PRESS_3_S*/ {RE_NO_EVENT, RE_NO_EVENT, RE_NO_EVENT, RE_NO_EVENT, RE_NO_EVENT, RE_NO_EVENT},
/*RE_KEYMODE_S*/ {RE_KEY_LEFT, RE_KEY_RIGHT, RE_NO_EVENT, RE_NO_EVENT, RE_NO_EVENT, RE_NO_EVENT}
};
//Variables
static rotary_encoder_callback_t rotary_encoder_callback;
static bool previous_button_signal;
static bool previous_rotation_idle;
static re_state_t re_state;
//Initialize Rotary Encoder
void rotary_encoder_init()
{
static bool rotary_encoder_initialized = false;
if(!rotary_encoder_initialized)
{
//Initialize GPIO
gpioMode (RE_PIN_BUTTON_SIGNAL, INPUT_PULLUP);
gpioMode (RE_PIN_SIGNAL_A, INPUT_PULLUP);
gpioMode (RE_PIN_SIGNAL_B, INPUT_PULLUP);
//Variable Initialization
rotary_encoder_callback = NULL;
previous_button_signal = true; //Assume button is not pressed
re_state = RE_IDLE_S; //Assume rotary encoder rotation is IDLE
previous_rotation_idle = true;
//Initialize SysTick
systick_init();
systick_add_callback(rotary_encoder_ISR,RE_ISR_PERIOD_TICKS,PERIODIC);
//Done.
rotary_encoder_initialized = true;
}
}
//Set Rotary Encoder Callback
void rotary_encoder_set_callback(rotary_encoder_callback_t callback)
{
rotary_encoder_callback = callback;
}
static void rotary_encoder_ISR()
{
static unsigned int tick_counter = 0;
//Low Level Event
re_ll_event_t ev_ll = RE_LL_NO_EVENT;
//High Level Event (for callback)
re_event_t ev = RE_NO_EVENT;
//Measured Signals
bool current_button_signal = gpioRead(RE_PIN_BUTTON_SIGNAL);
bool current_A_signal = gpioRead(RE_PIN_SIGNAL_A);
bool current_B_signal = gpioRead(RE_PIN_SIGNAL_B);
bool current_rotation_idle = current_A_signal && current_B_signal;
//Get (low level) event from button
ev_ll = rotary_encoder_button_decode[previous_button_signal][current_button_signal];
//Get (low level) event from rotation, if no event from button && rotation is idle
if(ev_ll == RE_LL_NO_EVENT && previous_rotation_idle)
ev_ll = rotary_encoder_rotation_decode[current_A_signal][current_B_signal];
//Get (low level) event from timer, if no event from button nor rotation
if(ev_ll == RE_LL_NO_EVENT)
{
if(tick_counter == RE_TIMEOUT_ISR_TICKS)
{
ev_ll = RE_LL_TIMEOUT;
//Timeout event, reset tick counter
tick_counter = 0;
}
else
//Increment counter
tick_counter++;
}
else
//Non Timer event causes timer to restart
tick_counter = 0;
//ev_ll is a low level event for the FSM. Generate high level event
ev = rotary_encoder_generated_event[re_state][ev_ll];
if(ev != RE_NO_EVENT)
rotary_encoder_callback(ev);
//Update All Variables
re_state = rotary_encoder_fsm_next_state[re_state][ev_ll];
previous_button_signal = current_button_signal;
previous_rotation_idle = current_rotation_idle;
}
|
C
|
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
float xc,yc,r;
void draw8points(float xc,float yc, float x,float y){
glBegin(GL_POINTS);
glColor3f(0,0,1);
glVertex2i(xc+x,yc+y);
glVertex2i(xc+x,yc-y);
glVertex2i(xc-x,yc+y);
glVertex2i(xc-x,yc-y);
glVertex2i(xc+y,yc+x);
glVertex2i(xc+y,yc-x);
glVertex2i(xc-y,yc+x);
glVertex2i(xc-y,yc-x);
glEnd();
}
void bres(float xc,float yc,float r){
float x = 0;
float y = r;
float dec_param = 3-2*r;
do{
draw8points(xc,yc,x,y);
x++;
if(dec_param < 0){
dec_param = dec_param + 4*x + 6;
}
else{
y--;
dec_param = dec_param + 4*(x-y) + 10;
}
}while(x<=y);
glFlush();
}
void initialize(){
glClearColor(1,1,1,1);
gluOrtho2D(-200.0,200.0,-200.0,200.0);
glClear(GL_COLOR_BUFFER_BIT);
}
void display(){
bres(xc,yc,r);
}
int main(int argc,char* argv[]){
printf("enter the centre of the circle\nx : ");
scanf("%f",&xc);
printf("y : ");
scanf("%f",&yc);
printf("enter the radius of the circle\nr : ");
scanf("%f",&r);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(400,400);
glutInitWindowPosition(0,0);
glutCreateWindow("bresenham-circle");
initialize();
glutDisplayFunc(display);
glutMainLoop();
}
|
C
|
#include<stdio.h>
#include<string.h>
void main()
{
int i, j, l, s = 1;
char str[100];
printf("\nEnter the string=");
gets(str);
l = strlen(str);
printf("length=%d", l);
printf("\nDuplicate characters are=");
for (i = 0; i < l; i++)
{
for (j = i + 1; j < l; j++)
{
if (str[i] == str[j])
{
if (s == 1 && str[j] != '\0')
{
printf("\n\t\t\t %c", str[i]);
}
str[j] = '\0';
s++;
}
}
s = 1;
}
printf("\n\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main() {
int *vetor;
vetor = (int*) malloc(3 * sizeof(int));
printf("\nmalloc()\n");
vetor[0] = 10;
vetor[1] = 20;
vetor[2] = 30;
for (int i=0; i<3; i++)
printf("vetor[%d]=%d\n", i, vetor[i]);
//calloc()
vetor = (int*) realloc(vetor, 4 * sizeof(int));
printf("\nrealloc()\n");
vetor[0] = 10;
vetor[1] = 20;
vetor[2] = 30;
vetor[3] = 100;
for (int i=0; i<4; i++)
printf("vetor[%d]=%d\n", i, vetor[i]);
free(vetor);
return (0);
}
|
C
|
#include <stdio.h>
#include "list_queue.h"
int main(int argc, char* argv[]) {
QUEUE queue = queue_construct();
for(;;) {
char buf[256];
char c;
int value = 0;
fgets(buf, 256, stdin);
if(sscanf(buf, "%c %d", &c, &value) == 0) {
continue;
}
switch(c) {
case 'i':
queue_enqueue(queue, value);
printf("enqueue:%d\n", value);
break;
case 'p':
queue_pushfront(queue, value);
printf("pushfront:%d\n", value);
break;
case 'q':
value = queue_popback(queue);
printf("popback:%d\n", value);
break;
case 'd':
value = queue_dequeue(queue);
printf("dequeue:%d\n", value);
break;
case 'r':
value = queue_front(queue);
printf("front:%d\n", value);
break;
}
queue_print(queue);
}
}
|
C
|
#ifndef PARSER_C
#define PARSER_C
#include "stackvm.h"
char labelnames[256][32];
int labelnamecount = 0;
unsigned char skip(char **str, const char *pre) {
unsigned char found = strncmp(pre, *str, strlen(pre)) == 0;
if(found)
*str += strlen(pre);
return found;
}
void skipmany(char **str, char ch) {
while(**str == ch)
(*str)++;
}
/*Il primo separatore trovato nella stringa originale (spazio, a capo o \0) viene sostituito da \0;
* il resto della stringa rimane invariato. La stringa ritornata si appoggia su quella originale.*/
char *readword(char **str) {
char *word = *str;
skipmany(&word, ' ');
int i = 0;
while(! (isspace(word[i]) || word[i] == '\0')) {
++word;
++i;
}
word[i] = '\0';
*str = &(word[i + 1]);
return word;
}
int find(char arr[256][32], int length, char *string) {
int i;
for(i = 0; i < length; ++i) {
//printf("testing %s against %s at pos %d\n", string, arr[i], i);
if(strcmp(arr[i], string) == 0)
return i;
}
return -1;
}
long estrtol(char **str, int base) {
char *end;
long result = strtol(*str, &end, base);
if(end == *str) ERR("Parse error, numeric argument expected\n")
else {
*str = end;
return result;
}
}
long estrtoul(char **str, int base) {
char *end;
long result = strtoul(*str, &end, base);
if(end == *str) ERR("Parse error, numeric argument expected\n")
else {
*str = end;
return result;
}
}
Step *parseStep(char *string, unsigned int ln) {
Step *parsed = malloc(sizeof(Step));
parsed->next = NULL;
skipmany(&string, ' ');
if(*string == '#' || *string == '\n')
return NULL;
//printf("Parsing: %s", string);
if(skip(&string, "push")) {
parsed->instruction = PUSH;
skipmany(&string, ' ');
if(skip(&string, "'")) {
char parsedchar = *(string++);
if(skip(&string, "'"))
parsed->arg = parsedchar;
else PERR("Invalid push argument")
}
else
parsed->arg = estrtol(&string, 10);
}
else if(skip(&string, "pop")) {
parsed->instruction = POP;
}
else if(skip(&string, "add")) {
parsed->instruction = ADD;
}
else if(skip(&string, "sub")) {
parsed->instruction = SUB;
}
else if(skip(&string, "mul")) {
parsed->instruction = MUL;
}
else if(skip(&string, "div")) {
parsed->instruction = DIV;
}
else if(skip(&string, "mod")) {
parsed->instruction = MOD;
}
else if(skip(&string, "jz")) {
parsed->instruction = JZ;
char *labelname = readword(&string);
parsed->arg = find(labelnames, labelnamecount+1, labelname);
if(parsed->arg == -1) {
fprintf(stderr, "'%s' at line %d : not a valid label\n", labelname, ln);
exit(1);
}
}
else if(skip(&string, "jnz")) {
parsed->instruction = JNZ;
char *labelname = readword(&string);
parsed->arg = find(labelnames, labelnamecount+1, labelname);
if(parsed->arg == -1) {
fprintf(stderr, "'%s' at line %d : not a valid label\n", labelname, ln);
exit(1);
}
}
else if(skip(&string, "jmp")) {
parsed->instruction = JMP;
char *labelname = readword(&string);
parsed->arg = find(labelnames, labelnamecount+1, labelname);
if(parsed->arg == -1) {
fprintf(stderr, "'%s' at line %d : not a valid label\n", labelname, ln);
exit(1);
}
}
else if(skip(&string, "printc")) {
parsed->instruction = PRINTC;
}
else if(skip(&string, "print")) {
parsed->instruction = PRINT;
}
else if(skip(&string, "dup")) {
parsed->instruction = DUP;
}
else if(skip(&string, "load")) {
parsed->instruction = LOAD;
parsed->arg = estrtoul(&string, 10);
if(parsed->arg > 256)
PERR("Not a valid register")
}
else if(skip(&string, "store")) {
parsed->instruction = STORE;
parsed->arg = estrtoul(&string, 10);
if(parsed->arg > 256)
PERR("Not a valid register")
}
else if(skip(&string, "stop")) {
parsed->instruction = STOP;
}
else if(skip(&string, "runf")) {
parsed->instruction = RUNF;
char *labelname = readword(&string);
parsed->arg = find(labelnames, labelnamecount+1, labelname);
if(parsed->arg == -1) {
fprintf(stderr, "'%s' at line %d : not a valid label\n", labelname, ln);
exit(1);
}
}
else if(skip(&string, "ret")) {
parsed->instruction = RET;
}
else if(skip(&string, "l:") || skip(&string, "defun")) {
parsed->instruction = NOP;
char *labelname = readword(&string);
int index = find(labelnames, labelnamecount+1, labelname);
if(index != -1)
labels[index] = parsed;
else {
fprintf(stderr, "'%s' at line %d : not a valid label\n", labelname, ln);
exit(1);
}
}
else
PERR("Not a valid instruction");
return parsed;
}
Step *parse(char* filename) {
FILE *file;
Step *first = NULL, *last;
int ln = 0;
char newlineArr[256];
file = fopen(filename, "r");
if(file == NULL) {
printf("Can't open file '%s'\n", filename);
exit(1);
}
while(fgets(newlineArr, 256, file) != NULL) {
char *newline = newlineArr;
skipmany(&newline, ' ');
char *next;
if(skip(&newline, "l:") || skip(&newline, "defun")) {
char *labelname = readword(&newline);
if(find(labelnames, labelnamecount+1, labelname) == -1)
strcpy(labelnames[labelnamecount++], labelname);
else {
fprintf(stderr, "Label '%s' already in use\n", labelname);
exit(1);
}
}
}
rewind(file);
while(first == NULL) {
++ln;
fgets(newlineArr, 256, file);
first = parseStep(newlineArr, ln);
last = first;
}
while(fgets(newlineArr, 256, file) != NULL) {
++ln;
Step *newStep = parseStep(newlineArr, ln);
if(newStep == NULL)
continue;
last->next = newStep;
last = newStep;
}
fclose(file);
return first;
}
#endif
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DIM 100
void sostituisciCarattere(char parole[DIM][DIM], char carattere, char sostituto, int n)
{
for (int j = 0; j < n; j++)
{
for (int i = 0; i < strlen(parole[j]); i++)
{
if (parole[j][i] == carattere)
parole[j][i] = sostituto;
}
}
}
void scriviFile(char parole[DIM][DIM], int n, char fileName[])
{
FILE *stream;
if ((stream = fopen(fileName, "w")) == NULL)
{
printf("errore nell'apertura del file output");
exit(4);
}
for (int i = 0; i < n; i++)
{
fprintf(stream, "%s ", parole[i]);
}
fclose(stream);
}
void leggiFile(char fileName[], char parole[DIM][DIM], int *n)
{
FILE *stream;
if ((stream = fopen(fileName, "r")) == NULL)
{
printf("errore nell'apertura del file input");
exit(3);
}
while (!feof(stream))
{
fscanf(stream, "%s ", parole[*n]);
(*n)++;
}
fclose(stream);
}
void controllaArgomenti(int argc, char *argv[])
{
if (argc != 6)
{
printf("Argomenti errati");
exit(1);
}
if (strcmp(argv[3], "-s") != 0)
{
printf("Metodo errato");
exit(2);
}
}
int main(int argc, char *argv[])
{
char parole[DIM][DIM];
int n = 0;
controllaArgomenti(argc, argv);
leggiFile(argv[1], parole, &n);
sostituisciCarattere(parole, argv[4][0], argv[5][0], n);
scriviFile(parole, n, argv[2]);
return 0;
}
|
C
|
// Given the string find the corresponding excelsheet number
// Sample Case: AB - 28, ZY - 701, A - 1
#include<stdio.h>
#include<string.h>
int main()
{
int i,sum = 0;
char columnTitle[7];
int letters[26];
printf("Enter the string like in excelsheets:");
gets(columnTitle);
for(i=1;i<=26;i++)
{
letters[i] = i;
}
/*for(i=1;i<=26;i++)
{
printf("%c:%d\n",(i-1)+'A',letters[i]);
}*/
//printf("%d",columnTitle[0] - 'A');
if(strlen(columnTitle) == 1)
{
printf("%d\n",letters[(columnTitle[0] - 65) + 1]);
}
else
{
for(i = 0;i<strlen(columnTitle);i++)
{
sum = (sum * 26) + (letters[columnTitle[i] - 65 +1]);
}
printf("%d\n",sum);
}
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
__attribute__((used)) static const char* Exception_Description(void) {
return
"The `Exception` type provides an interface to the Cello Exception System. "
"One instance of this type is created for each `Thread` and stores the "
"various bits of data required for the exception system. It can be "
"retrieved using the `current` function, although not much can be done "
"with it."
"\n\n"
"Exceptions are available via the `try`, `catch` and `throw` macros. It is "
"important that the `catch` part of the exception block is always "
"evaluated otherwise the internal state of the exception system can go out "
"of sync. For this reason please never use `return` inside a `try` block. "
"\n\n"
"The `exception_signals` method can be used to register some exception to "
"be thrown for any of the "
"[standard C signals](https://en.wikipedia.org/wiki/C_signal_handling)."
"\n\n"
"To get the current exception object or message use the "
"`exception_message` or `exception_object` methods.";
}
|
C
|
unsigned int SwapBBBB(unsigned int i)
{
unsigned int result=(i>>24)&0xff;
result|=(i>>8)&0xff00;
result|=(i<<8)&0xff0000;
result|=(i<<24)&0xff000000;
return(result);
}
unsigned int SwapBB(unsigned int i)
{
unsigned short result=(i>>8)&0xff;
result|=(i<<8)&0xff00;
return(result);
}
unsigned long SwapWW(unsigned long i)
{
unsigned int result=(i>>16)&0xffff;
result|=(i<<16)&0xffff0000;
return(result);
}
|
C
|
/*
* Find the sum of all strong repunits under N
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "hash_table.h"
#include "utils.h"
int main (int argc, char ** argv) {
if (argc != 2) {
fprintf (stderr, "usage: %s <N>\n", argv[0]);
return 1;
}
long N = atol (argv[1]);
if (N < 1) {
printf ("0\n");
return 0;
}
/*
* We need to find all repunits for all possible bases up to N and sum those
* that are encountered at least twice
*
* Note that every number x is a repunit 11 in base (x - 1)
* Therefore, for each base we only need to consider all repunits greater than 11
* and can safely stop at a base sqrt (N). Every such repunit is automatically strong.
*/
long sum = 1;
long base_limit = sqrt (N);
hash_table_t * repunits = hash_table_create (base_limit);
for (long base = 2; base <= base_limit; base++) {
long repunit = 1 + base + base * base;
while (repunit < N) {
if (hash_table_insert (repunits, repunit, copy_long (repunit)))
sum += repunit;
repunit *= base;
repunit++;
}
}
printf ("%ld\n", sum);
hash_table_free (repunits);
return 0;
}
|
C
|
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
static pid_t pid;
void do_sig(int num)
{
if (pid > 0)
{
static int m = 1;
printf("I am %d\t %d\n", getpid(),m);
m += 2;
kill(pid,10);
}
else
{
static int n;
printf("I am %d\t %d\n", getpid(),n);
n += 2;
kill(getppid(),10);
}
sleep(1);
}
int main(void)
{
int n = 0;
struct sigaction act, oact;
act.sa_handler = do_sig;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGUSR1, &act, &oact);
pid = fork();
if (pid < 0)
{
perror("fork");
exit(-1);
}
else if(pid > 0)
kill(pid,10);
while(1) ;
wait(NULL);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
unsigned char prepara(char* coluna){
char ret[8];
x[1] x[]
for(int i=0; i<8; i++){
if(comparativa(coluna[i],'0')){
ret [i]='0';
}else if(comparativa(coluna[i],'1')){
ret[i]='1';
}
}
}
int comparativa(char a, char b){
int pot;
for(int i=0; i<8; i++){
pot = (int) pow(2,i);
if(pot & a != pot & b){
return 0;
}
}
return 1;
}
int main(){
char a = '0', b = '0';
int r = comparativa(a,b);
printf("%d\n", r);
return 0;
}
|
C
|
#include "delay.h"
// very simple delay
// CPU oscilator is 16MHz
// 1 instr = 0.0625 uS
// 1 cycle = 4 instruction
// 1 us = 4 cycle
#define DFACTOR 4
static volatile unsigned long i;
void delay_us(unsigned long d)
{
i = DFACTOR * d;
while (--i != 0);
}
void delay_ms(unsigned long d)
{
i = DFACTOR * d * 1000;
while (--i != 0);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
//#include<stdio.h>
//#define MAX 20
//int main()
//{
// int n, arr[MAX], i, x, k = MAX, b;
// scanf("%d", &n);
//
// for (i = 1; i <= n; i++)
// {
// scanf("%d", &arr[i]);
// }
// scanf("%d", &x);
// if (n == 0)
// {
// return 0;
// }
// for (i = 1; i <= n; i++)
// {
// if (arr[i] < x)
// {
// printf("%d ", arr[i]);
// }
//
// if (arr[i] >= x && i < k)
// {
// b = arr[i];
// arr[i] = x;
// printf("%d %d ", x, b);
//
// k = i;
// }
// if (i > k)
// {
// printf("%d ", arr[i]);
// }
//
// }if (arr[n] < x)
// printf("%d ", x);
// return 0;
//}
//7-1-7
//#include<stdio.h>
//int main()
//{
// int m, n, arr[20], i, k = 0;
// scanf("%d%d", &m, &n);
// for (i = 0; i < m; i++)
// {
// scanf("%d", &arr[i]);
// }
// for (i = 0; i < m; i++)
// {
// if (arr[i] == n)
// {
// k = 1;
// printf("%d", i);
// break;
// }
// }
// if (k == 0)
// {
// printf("Not Found");
// }
// return 0;
//}
#include<stdio.h>
int main()
{
int n, arr[20], i, num, count = 0;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
scanf("%d", &arr[i]);
}
if (n == 1)
{
printf("%d", arr[1]);
}
for (i = 1; i < n; i++)
{
if (count == 3)
{
printf("\n");
count = 0;
}
if (count < 3)
{
num = arr[i + 1] - arr[i];
printf("%d", num);
count++;
}
if (count <= 2)
{
printf(" ");
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 5;
printf("fatorial de %d = %d", n, fatorial(n));
return 0;
}
//recursividade
int fatorial(int n)
{
if (n == 1)
return 1;
return n * fatorial(n - 1);
}
|
C
|
#include "apue.h"
#include <fcntl.h>
extern void TELL_WAIT();
extern void TELL_CHILD(pid_t pid);
extern void TELL_PARENT(pid_t pid);
extern void WAIT_CHILD();
extern void WAIT_PARENT();
static int number = 0;
static char str[10];
void pr()
{
printf("Pid = %d,Number = %d\n",getpid(),number);
}
int getNumber(const char* pathname)
{
int fid;
if((fid = open(pathname, O_RDONLY))<0)
err_sys("open file error...\n");
int n = read(fid,str,10);
//printf("read %d bytes....\n",n);
if(n<0)
err_sys("read file error...\n");
int number = atoi(str);
if(number==0)
err_sys("atoi error...\n");
close(fid);
return number;
}
void setNumber(const char* pathname,int number)
{
int fid;
if((fid = open(pathname, O_WRONLY))<0)
err_sys("open file error...\n");
sprintf(str,"%d",number);
write(fid,str,strlen(str));
close(fid);
}
int main()
{
int fid;
pid_t pid;
if((fid = open("number.txt", O_WRONLY|O_CREAT|O_TRUNC))<0)
err_sys("create file error...\n");
sprintf(str,"%d",number);
write(fid,str,strlen(str));
close(fid);
TELL_WAIT();
if((pid = fork())<0)
err_sys("fork error");
else if(pid==0)
{
while((getNumber("number.txt")+1)<1000)
{
WAIT_PARENT();
number = getNumber("number.txt");
setNumber("number.txt",number+1);
printf("Pid = %d,Number = %d\n",getpid(),number+1);
TELL_PARENT(getppid());
}
}
else
{
while((getNumber("number.txt")+1)<1000)
{
number = getNumber("number.txt");
setNumber("number.txt",number+1);
printf("Pid = %d,Number = %d\n",getpid(),number+1);
TELL_CHILD(pid);
WAIT_CHILD();
}
}
close(fid);
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, char const *argv[])
{
int n,fac=1,i=1;
scanf("%d",&n);
while(i<=n){
fac*=i;
i++;
}
printf("%d!=%d\n",n,fac );
return 0;
}
|
C
|
/* Replace "dll.h" with the name of your header */
#include "dll.h"
#include <windows.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
//#include <libusb-1.0/libusb.h>
#include "libusb.h"
#include <sys/types.h>
// Device vendor and product id.
#define IDVENDER 0x2309
#define IDPRODUCT 0x0606
#define ENCRYPT 1
#define DECRYPT 0
#define ENDPOINT_OUT 0x01
#define ENDPOINT_IN 0x82
#define USB_LENGTH 2
#define SM3_LENGTH 34
#define RETRY_MAX 5
#define ID_LENGTH 10
// Device of bytes to transfer.
#define BUF_SIZE 64
libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices
//libusb_device_handle *handle; //a device handle
//libusb_context *ctx = NULL; //a libusb session
inline static int perr(char const *format, ...)
{
va_list args;
int r;
va_start (args, format);
r = vfprintf(stderr, format, args);
va_end(args);
return r;
}
//Command Block Wrapper (CBW)
struct command_block_wrapper {
uint8_t dCBWSignature[4];
uint32_t dCBWTag;
uint32_t dCBWDataTransferLength;
uint8_t bmCBWFlags;
uint8_t bCBWLUN;
uint8_t bCBWCBLength;
uint8_t CBWCB[16];
};
//Command Status Wrapper (CSW)
struct command_status_wrapper {
uint8_t dCSWSignature[4];
uint32_t dCSWTag;
uint32_t dCSWDataResidue;
uint8_t bCSWStatus;
};
/******************************************************************************************************************/
/******************************************************Open device*************************************************/
libusb_device_handle * open_dev(libusb_device **devs,libusb_context *ctx)
{
ssize_t cnt; //holding number of devices in list
//libusb_reset_device(handle);
int r; //for return values
libusb_device_handle *handle;
r = libusb_init(&ctx); //initialize the library for the session we just declared
if(r < 0) {
perror("Init Error\n"); //there was an error
return NULL;
}
libusb_set_debug(ctx, LIBUSB_LOG_LEVEL_INFO); //set verbosity level to 3, as suggested in the documentation
cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
if(cnt < 0) {
perror("Get Device Error\n"); //there was an error
return NULL;
}
printf("%d Devices in list.\n", cnt);
handle = libusb_open_device_with_vid_pid(ctx, IDVENDER, IDPRODUCT); //these are vendorID and productID I found for my usb device #liusb
if(handle == NULL)
perror("Cannot open device\n");
else
printf("Device Opened\n");
libusb_free_device_list(devs, 1); //free the list, unref the devices in it
if(libusb_kernel_driver_active(handle, 0) == 1) { //find out if kernel driver is attached
printf("Kernel Driver Active\n");
if(libusb_detach_kernel_driver(handle, 0) == 0) //detach it
printf("Kernel Driver Detached!\n");
}
r = libusb_claim_interface(handle, 0); //claim interface 0 (the first) of device (mine had jsut 1)
if(r < 0) {
perror("Cannot Claim Interface\n");
return NULL;
}
printf("Claimed Interface\n");
return handle;
}
void close_dev(libusb_device_handle *handle,libusb_context *ctx)
{
int r,success;
r = libusb_release_interface(handle,0);
success = libusb_reset_device(handle);
if(success == 0)
printf("reset success!!!\n");
libusb_close(handle);
libusb_exit(ctx);
}
/***********************************************************************************************************/
/***********************************************************************************************************/
/*host-to-device,豸CBW*/
int send_mass_storage_command(libusb_device_handle *handle, uint8_t endpoint,uint8_t lun,
uint8_t *cdb, uint8_t direction, int data_length, uint32_t *ret_tag)
{
static uint32_t tag = 1;
uint8_t cdb_len = 6;//͵SCSI̶Ϊ6ֽ
int i, r, size;
struct command_block_wrapper cbw;
if (cdb == NULL) {
return -1;
}
if (endpoint & LIBUSB_ENDPOINT_IN) {
perr("send_mass_storage_command: cannot send command on IN endpoint\n");
return -1;
}
if ((cdb_len == 0) || (cdb_len > sizeof(cbw.CBWCB))) {
perr("send_mass_storage_command: don't know how to handle this command (%02X, length %d)\n",
cdb[0], cdb_len);
return -1;
}
memset(&cbw, 0, sizeof(cbw));
cbw.dCBWSignature[0] = 'U';//0x55
cbw.dCBWSignature[1] = 'S';//0x53
cbw.dCBWSignature[2] = 'B';//0x42
cbw.dCBWSignature[3] = 'C';//0x43
*ret_tag = tag;
cbw.dCBWTag = tag++;
cbw.dCBWDataTransferLength = data_length;
cbw.bmCBWFlags = direction;
cbw.bCBWLUN = lun;
// Subclass is 1 or 6 => cdb_len
cbw.bCBWCBLength = cdb_len;
memcpy(cbw.CBWCB, cdb, cdb_len);
i = 0;
do {
// The transfer length must always be exactly 31 bytes.
r = libusb_bulk_transfer(handle, endpoint, (unsigned char*)&cbw, 31, &size,0);
if (r == LIBUSB_ERROR_PIPE) {
libusb_clear_halt(handle, endpoint);
}
i++;
} while ((r == LIBUSB_ERROR_PIPE) && (i<RETRY_MAX));
printf("\n contorl message send success!!(sent %d CDB bytes)\n", cdb_len);
return 0;
}
/****************************************************************************************************/
/****************************************************************************************************/
/*device-to-host,豸CSW*/
int get_mass_storage_status(libusb_device_handle *handle, uint8_t endpoint, uint32_t expected_tag)
{
int i, r, size;
struct command_status_wrapper csw;
// The device is allowed to STALL this transfer. If it does, you have to
// clear the stall and try again.
i = 0;
do {
r = libusb_bulk_transfer(handle, endpoint, (unsigned char*)&csw, 13, &size, 0);
if (r == LIBUSB_ERROR_PIPE) {
libusb_clear_halt(handle, endpoint);
}
i++;
} while ((r == LIBUSB_ERROR_PIPE) && (i<RETRY_MAX));
if (size != 13) {
perr(" get_mass_storage_status: received %d bytes (expected 13)\n", size);
return -1;
}
if (csw.dCSWTag != expected_tag) {
perr(" get_mass_storage_status: mismatched tags (expected %08X, received %08X)\n",
expected_tag, csw.dCSWTag);
return -1;
}
// For this test, we ignore the dCSWSignature check for validity...
printf(" Mass Storage Status: %02X (%s)\n", csw.bCSWStatus, csw.bCSWStatus?"FAILED":"Success");
if (csw.dCSWTag != expected_tag)
return -1;
if (csw.bCSWStatus) {
// REQUEST SENSE is appropriate only if bCSWStatus is 1, meaning that the
// command failed somehow. Larger values (2 in particular) mean that
// the command couldn't be understood.
if (csw.bCSWStatus == 1)
return -2; // request Get Sense
else
return -1;
}
// In theory we also should check dCSWDataResidue. But lots of devices
// set it wrongly.
return 0;
}
//****************************************************************************************************
void verify_app_password(libusb_device_handle *handle,libusb_context *ctx)
{
uint32_t expected_tag,size,r;
uint8_t recv_buffer[1024];
uint8_t buffer[20];
uint32_t i;
uint32_t retcode1,retcode2;
uint8_t cdb_in[16] = {0xfd,0x10,0x57,0x00,0x00,0x10};
uint8_t CDB[16] = {0xfe,0x10,0x57,0x00,0x00,0x10};
memset(buffer,0x31,16);
memset(recv_buffer,0,sizeof(recv_buffer));
handle=open_dev(devs,ctx);
/*豸*/
printf("**********************************verify_app_password!!!!*****************************************\n");
send_mass_storage_command(handle,ENDPOINT_OUT,0, (unsigned char*)&cdb_in, LIBUSB_ENDPOINT_OUT, 16, &expected_tag);
retcode1 = libusb_bulk_transfer(handle, ENDPOINT_OUT, buffer, 16, &size, 1000);
printf("\n buffer:\n");
for(i = 0 ;i < 16;i++)
printf("%02x ",buffer[i]);
printf("\n");
printf("The number have read: %d\n",size);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
if(r==0)
printf("status success!!");
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0,(unsigned char*)&CDB, LIBUSB_ENDPOINT_OUT, 6, &expected_tag);
retcode2 = libusb_bulk_transfer(handle, ENDPOINT_IN, recv_buffer,2, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
if(r==0)
printf("status success!!");
i = size;
printf("The number have read: %d %02x %02x \n",i,recv_buffer[i-2],recv_buffer[i-1]);
if((recv_buffer[i-2] == 0x90)&&(recv_buffer[i-1] == 0x00))
printf("verify_app_password success!!!\n");
//printf("\n");
close_dev(handle,ctx);
printf("**********************************END************************************\n\n\n");
}
void verify_mana_password(libusb_device_handle *handle,libusb_context *ctx)
{
uint32_t expected_tag,size,r;
uint8_t recv_buffer[1024];
uint8_t buffer[20];
uint32_t i;
uint32_t retcode1,retcode2;
uint8_t cdb_in[16] = {0xfd,0x10,0x58,0x00,0x00,0x10};
uint8_t CDB[16] = {0xfe,0x10,0x58,0x00,0x00,0x10};
memset(buffer,0x32,16);
memset(recv_buffer,0,sizeof(recv_buffer));
handle=open_dev(devs,ctx);
/*豸*/
printf("*******************************verify_mana_password!!***********************\n");
send_mass_storage_command(handle,ENDPOINT_OUT,0, (unsigned char*)&cdb_in, LIBUSB_ENDPOINT_OUT, 16, &expected_tag);
retcode1 = libusb_bulk_transfer(handle, ENDPOINT_OUT, buffer, 16, &size, 1000);
printf("\n buffer:\n");
for(i = 0 ;i < 16;i++)
printf("%02x ",buffer[i]);
printf("\n");
printf("The number have read: %d\n",size);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
if(r==0)
printf("status success!!");
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0,(unsigned char*)&CDB, LIBUSB_ENDPOINT_OUT, 6, &expected_tag);
retcode2 = libusb_bulk_transfer(handle, ENDPOINT_IN, recv_buffer,2, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
if(r==0)
printf("status success!!");
i = size;
printf("The number have read: %d %02x %02x \n",i,recv_buffer[i-2],recv_buffer[i-1]);
if((recv_buffer[i-2] == 0x90)&&(recv_buffer[i-1] == 0x00))
printf("verify_app_password success!!!\n");
//printf("\n");
close_dev(handle,ctx);
printf("**********************************END*************************************\n\n\n");
}
/****** write x509cert - дx509-CA֤******/
void write_x509cert(libusb_device_handle *handle,libusb_device **devs,libusb_context *ctx, uint8_t tranbuff[512], uint8_t *dst)
{
uint32_t expected_tag;
uint32_t size=0;
uint8_t r;
int rlen;
uint8_t recv_buffer[64] = {0};
uint8_t buffer[256];
uint32_t i,j;
uint32_t retcode1,retcode2;
uint8_t CDB[16] = {0xfe,0x30,0xb5,0x00,0x02,0x00};
uint8_t cdb_in[16] = {0xfd,0x30,0xb5,0x00,0x02,0x00};
memset(buffer,0,sizeof(buffer));
handle=open_dev(devs,ctx);
printf("***************************write x509cert Test*************************\n");
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0, (unsigned char*)&cdb_in, LIBUSB_ENDPOINT_OUT , 512,&expected_tag);
retcode1 = libusb_bulk_transfer(handle, ENDPOINT_OUT, tranbuff, 512, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
// printf("size = %d\n",size);
printf("The message is:\n");
for(i=0;i < size;i++)
{printf("%02x ",tranbuff[i]);if(i%16==15) printf("\n");}
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0,(unsigned char*)&CDB, LIBUSB_ENDPOINT_IN , 2, &expected_tag);
retcode2 = libusb_bulk_transfer(handle, ENDPOINT_IN, buffer, 2, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
if(r==0)
printf("status success!!");
i = size;
printf("The number of write x509cert: %d\n",i);
if((buffer[i-2] == 0x90)&&(buffer[i-1] == 0x00))
memcpy(dst,buffer,i);
for(i=0;i < size;i++)
printf("%02x ",dst[i]);
printf("\n");
close_dev(handle,ctx);
printf("*********************************************************************\n\n\n");
}
/****** read x509 cert - ȡx509-CA֤******/
void read_x509_CA_cert(libusb_device_handle *handle,libusb_device **devs,libusb_context *ctx, uint8_t *dst)
{
uint32_t expected_tag;
uint32_t size=0;
uint8_t r;
int rlen;
uint8_t buffer[1024];
uint32_t i,j;
uint32_t retcode1,retcode2;
uint8_t CDB[16] = {0xfe,0x20,0xa0,0x00,0x02,0x00};
uint8_t cdb_in[16] = {0xfd,0x20,0xa0,0x00,0x02,0x00};
memset(buffer,0,sizeof(buffer));
handle=open_dev(devs,ctx);
printf("***************************read x509 cert Test*************************\n");
/*豸*/
//send_mass_storage_command(handle,ENDPOINT_OUT,0, (unsigned char*)&cdb_in, LIBUSB_ENDPOINT_OUT , 512,&expected_tag);
//retcode1 = libusb_bulk_transfer(handle, ENDPOINT_OUT, tranbuff, 512, &size, 1000);
//r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0,(unsigned char*)&CDB, LIBUSB_ENDPOINT_IN , 514, &expected_tag);
retcode2 = libusb_bulk_transfer(handle, ENDPOINT_IN, buffer, 514, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
if(r==0)
printf("status success!!");
i = size;
printf("The number of read x509 cert: %d\n",i);
if((buffer[i-2] == 0x90)&&(buffer[i-1] == 0x00))
memcpy(dst,buffer,i-2);
//for(i=0;i < size;i++)
// {printf("%02x ",dst[i]);if(i%16==15) printf("\n");}
printf("\n");
close_dev(handle,ctx);
printf("*********************************************************************\n\n\n");
}
/****** read x509 usercert - ȡx509-û֤******/
void read_x509_user_cert(libusb_device_handle *handle,libusb_device **devs,libusb_context *ctx, uint8_t *dst)
{
uint32_t expected_tag;
uint32_t size=0;
uint8_t r;
int rlen;
uint8_t buffer[1024];
uint32_t i,j;
uint32_t retcode1,retcode2;
uint8_t CDB[16] = {0xfe,0x20,0xa4,0x00,0x02,0x00};
uint8_t cdb_in[16] = {0xfd,0x20,0xa4,0x00,0x02,0x00};
memset(buffer,0,sizeof(buffer));
handle=open_dev(devs,ctx);
printf("***************************read x509 usercert Test*************************\n");
/*豸*/
//send_mass_storage_command(handle,ENDPOINT_OUT,0, (unsigned char*)&cdb_in, LIBUSB_ENDPOINT_OUT , 512,&expected_tag);
//retcode1 = libusb_bulk_transfer(handle, ENDPOINT_OUT, tranbuff, 512, &size, 1000);
//r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0,(unsigned char*)&CDB, LIBUSB_ENDPOINT_IN , 514, &expected_tag);
retcode2 = libusb_bulk_transfer(handle, ENDPOINT_IN, buffer, 514, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
if(r==0)
printf("status success!!");
i = size;
printf("The number of read x509 usercert: %d\n",i);
if((buffer[i-2] == 0x90)&&(buffer[i-1] == 0x00))
memcpy(dst,buffer,i);
for(i=0;i < size;i++)
{printf("%02x ",dst[i]);if(i%16==15) printf("\n");}
printf("\n");
close_dev(handle,ctx);
printf("*********************************************************************\n\n\n");
}
/****** write ca pubkey - дCAԿ******/
void write_ca_pubkey(libusb_device_handle *handle,libusb_device **devs,libusb_context *ctx, uint8_t tranbuff[64], uint8_t *dst)
{
uint32_t expected_tag;
uint32_t size=0;
uint8_t r;
int rlen;
uint8_t recv_buffer[64] = {0};
uint8_t buffer[1024];
uint32_t i,j;
uint32_t retcode1,retcode2;
uint8_t CDB[16] = {0xfe,0x30,0xb4,0x00,0x00,0x40};
uint8_t cdb_in[16] = {0xfd,0x30,0xb4,0x00,0x00,0x40};
memset(buffer,0,sizeof(buffer));
handle=open_dev(devs,ctx);
printf("***************************write ca pubkey Test*************************\n");
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0, (unsigned char*)&cdb_in, LIBUSB_ENDPOINT_OUT , 64,&expected_tag);
retcode1 = libusb_bulk_transfer(handle, ENDPOINT_OUT, tranbuff, 64, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
// printf("size = %d\n",size);
printf("The message is:\n");
for(i=0;i < size;i++)
{printf("%02x ",tranbuff[i]);if(i%16==15) printf("\n");}
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0,(unsigned char*)&CDB, LIBUSB_ENDPOINT_IN , 2, &expected_tag);
retcode2 = libusb_bulk_transfer(handle, ENDPOINT_IN, buffer, 2, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
if(r==0)
printf("status success!!");
i = size;
printf("The number of write ca pubkey: %d\n",i);
if((buffer[i-2] == 0x90)&&(buffer[i-1] == 0x00))
memcpy(dst,buffer,i);
for(i=0;i < size;i++)
printf("%02x ",dst[i]);
printf("\n");
close_dev(handle,ctx);
printf("*********************************************************************\n\n\n");
}
/****** write userkey - дûԿ******/
void write_userkey(libusb_device_handle *handle,libusb_device **devs,libusb_context *ctx, uint8_t tranbuff[100], uint8_t *dst)
{
uint32_t expected_tag;
uint32_t size=0;
uint8_t r;
int rlen;
uint8_t recv_buffer[64] = {0};
uint8_t buffer[1024];
uint32_t i,j;
uint32_t retcode1,retcode2;
uint8_t CDB[16] = {0xfe,0x30,0xb7,0x00,0x01,0x00};
uint8_t cdb_in[16] = {0xfd,0x30,0xb7,0x00,0x01,0x00};
memset(buffer,0,sizeof(buffer));
handle=open_dev(devs,ctx);
printf("***************************write userkey Test*************************\n");
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0, (unsigned char*)&cdb_in, LIBUSB_ENDPOINT_OUT , 256,&expected_tag);
retcode1 = libusb_bulk_transfer(handle, ENDPOINT_OUT, tranbuff, 256, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
// printf("size = %d\n",size);
printf("The message is:\n");
for(i=0;i < size;i++)
{printf("%02x ",tranbuff[i]);if(i%16==15) printf("\n");}
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0,(unsigned char*)&CDB, LIBUSB_ENDPOINT_IN , 2, &expected_tag);
retcode2 = libusb_bulk_transfer(handle, ENDPOINT_IN, buffer, 2, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
if(r==0)
printf("status success!!");
i = size;
printf("The number of write userkey: %d\n",i);
if((buffer[i-2] == 0x90)&&(buffer[i-1] == 0x00))
memcpy(dst,buffer,i);
for(i=0;i < size;i++)
printf("%02x ",dst[i]);
printf("\n");
close_dev(handle,ctx);
printf("*********************************************************************\n\n\n");
}
/****** read user key - ȡûԿ******/
void read_userkey(libusb_device_handle *handle,libusb_device **devs,libusb_context *ctx, uint8_t *dst)
{
uint32_t expected_tag;
uint32_t size=0;
uint8_t r;
int rlen;
uint8_t buffer[1024];
uint32_t i,j;
uint32_t retcode1,retcode2;
uint8_t CDB[16] = {0xfe,0x20,0xa5,0x00,0x01,0x00};
uint8_t cdb_in[16] = {0xfd,0x20,0xa5,0x00,0x01,0x00};
memset(buffer,0,sizeof(buffer));
handle=open_dev(devs,ctx);
printf("***************************read user key Test*************************\n");
/*豸*/
//send_mass_storage_command(handle,ENDPOINT_OUT,0, (unsigned char*)&cdb_in, LIBUSB_ENDPOINT_OUT , 6,&expected_tag);
//retcode1 = libusb_bulk_transfer(handle, ENDPOINT_OUT, tranbuff, 512, &size, 1000);
//r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0,(unsigned char*)&CDB, LIBUSB_ENDPOINT_IN , 258, &expected_tag);
retcode2 = libusb_bulk_transfer(handle, ENDPOINT_IN, buffer, 258, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
if(r==0)
printf("status success!!");
i = size;
printf("The number of read user key: %d\n",i);
if((buffer[i-2] == 0x90)&&(buffer[i-1] == 0x00))
memcpy(dst,buffer,i);
for(i=0;i < size;i++)
{printf("%02x ",dst[i]);if(i%16==15) printf("\n");}
printf("\n");
close_dev(handle,ctx);
printf("*********************************************************************\n\n\n");
}
/****** write x509 usercert - дx509-û֤******/
void write_x509usercert(libusb_device_handle *handle,libusb_device **devs,libusb_context *ctx, uint8_t tranbuff[512], uint8_t *dst)
{
uint32_t expected_tag;
uint32_t size=0;
uint8_t r;
int rlen;
uint8_t recv_buffer[64] = {0};
uint8_t buffer[256];
uint32_t i,j;
uint32_t retcode1,retcode2;
uint8_t CDB[16] = {0xfe,0x30,0xb6,0x00,0x02,0x00};
uint8_t cdb_in[16] = {0xfd,0x30,0xb6,0x00,0x02,0x00};
memset(buffer,0,sizeof(buffer));
handle=open_dev(devs,ctx);
printf("***************************write x509 usercert Test*************************\n");
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0, (unsigned char*)&cdb_in, LIBUSB_ENDPOINT_OUT , 512,&expected_tag);
retcode1 = libusb_bulk_transfer(handle, ENDPOINT_OUT, tranbuff, 512, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
// printf("size = %d\n",size);
printf("The message is:\n");
for(i=0;i < size;i++)
{printf("%02x ",tranbuff[i]);if(i%16==15) printf("\n");}
/*豸*/
send_mass_storage_command(handle,ENDPOINT_OUT,0,(unsigned char*)&CDB, LIBUSB_ENDPOINT_IN , 2, &expected_tag);
retcode2 = libusb_bulk_transfer(handle, ENDPOINT_IN, buffer, 2, &size, 1000);
r=get_mass_storage_status(handle,ENDPOINT_IN, expected_tag);
if(r==0)
printf("status success!!");
i = size;
printf("The number of write x509 usercert: %d\n",i);
if((buffer[i-2] == 0x90)&&(buffer[i-1] == 0x00))
memcpy(dst,buffer,i);
for(i=0;i < size;i++)
printf("%02x ",dst[i]);
printf("\n");
close_dev(handle,ctx);
printf("*********************************************************************\n\n\n");
}
DLLIMPORT int main()
{
int i=0,j=0;
printf("1");
uint8_t ca_pubkey[66]={0};
printf("2");
uint8_t user_pubkey[256]={0};
printf("3");
uint8_t buffer[2048] ;
printf("4");
libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices
printf("5");
libusb_device_handle *handle; //a device handle
libusb_context *ctx = NULL; //a libusb session
uint8_t CA_Buff[514] =
{
0x30,0x82,0x01,0x97,0x30,0x82,0x01,0x3C,0xA0,0x03,0x02,0x01,0x02,0x02,0x08,0x6D,
0x50,0x2E,0xBC,0x5E,0xF2,0xBD,0x98,0x30,0x0A,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,
0x04,0x03,0x02,0x30,0x2F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,
0x43,0x48,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x0A,0x13,0x0A,0x73,0x74,0x72,
0x6F,0x6E,0x67,0x53,0x77,0x61,0x6E,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x03,
0x13,0x02,0x43,0x41,0x30,0x1E,0x17,0x0D,0x31,0x38,0x30,0x33,0x32,0x31,0x31,0x30,
0x34,0x35,0x35,0x33,0x5A,0x17,0x0D,0x32,0x31,0x30,0x33,0x32,0x30,0x31,0x30,0x34,
0x35,0x35,0x33,0x5A,0x30,0x2F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
0x02,0x43,0x48,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x0A,0x13,0x0A,0x73,0x74,
0x72,0x6F,0x6E,0x67,0x53,0x77,0x61,0x6E,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,
0x03,0x13,0x02,0x43,0x41,0x30,0x59,0x30,0x13,0x06,0x07,0x2A,0x86,0x48,0xCE,0x3D,
0x02,0x01,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x07,0x03,0x42,0x00,0x04,
0x34,0x2B,0xB4,0xB5,0x19,0x72,0xAA,0x30,0x7A,0x65,0xDA,0x96,0xB8,0x90,0x47,0xC9,
0x05,0x62,0xC7,0x28,0xF4,0x88,0x96,0x75,0xD6,0x8C,0xB5,0x10,0x96,0xFF,0x8F,0x66,
0xDB,0x2C,0x1A,0x07,0x77,0x1C,0x74,0x57,0xF4,0x4B,0x02,0x05,0xBB,0x0D,0xDE,0x82,
0x88,0xD4,0x65,0x51,0xA6,0xF4,0x0F,0x41,0x8B,0xC3,0x83,0xB8,0x5A,0x2D,0x42,0x88,
0xA3,0x42,0x30,0x40,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,
0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,
0x04,0x03,0x02,0x01,0x06,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,
0x29,0xE1,0x96,0xBB,0x32,0xC2,0x92,0x17,0x8C,0x6D,0x9B,0x35,0x46,0x04,0x13,0x47,
0x92,0x85,0x4B,0xAA,0x30,0x0A,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x04,0x03,0x02,
0x03,0x49,0x00,0x30,0x46,0x02,0x21,0x00,0xE8,0x09,0xFA,0x03,0xC3,0xBC,0xE1,0x1D,
0x7A,0x27,0xFA,0x55,0xCE,0x87,0x3A,0x87,0x8D,0x42,0x91,0xB9,0x90,0x84,0x7E,0xB3,
0x9A,0xD4,0x9A,0x66,0x76,0xFD,0x03,0x89,0x02,0x21,0x00,0xFD,0x82,0x23,0xB9,0xB5,
0xAD,0xB6,0x0B,0x67,0xDC,0xFD,0xF9,0x88,0x70,0x54,0xCA,0x87,0xF2,0x4C,0x96,0xCC,
0x7C,0xEE,0x2F,0xEA,0xA9,0x63,0x88,0xE8,0x67,0xA1,0x0A,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,
0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,
0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,
0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,
0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,
0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,
0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0
};
uint8_t user_Buff[514] =
{
0x30,0x82,0x01,0x8F,0x30,0x82,0x01,0x36,0xA0,0x03,0x02,0x01,0x02,0x02,0x08,0x25,
0xED,0x7E,0x87,0x80,0x33,0xA2,0x37,0x30,0x0A,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,
0x04,0x03,0x02,0x30,0x2F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,
0x43,0x48,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x0A,0x13,0x0A,0x73,0x74,0x72,
0x6F,0x6E,0x67,0x53,0x77,0x61,0x6E,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x03,
0x13,0x02,0x43,0x41,0x30,0x1E,0x17,0x0D,0x31,0x38,0x30,0x33,0x32,0x31,0x31,0x30,
0x34,0x35,0x35,0x33,0x5A,0x17,0x0D,0x32,0x31,0x30,0x33,0x32,0x30,0x31,0x30,0x34,
0x35,0x35,0x33,0x5A,0x30,0x34,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
0x02,0x43,0x48,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x0A,0x13,0x0A,0x73,0x74,
0x72,0x6F,0x6E,0x67,0x53,0x77,0x61,0x6E,0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,
0x03,0x13,0x07,0x63,0x6C,0x69,0x65,0x6E,0x74,0x31,0x30,0x59,0x30,0x13,0x06,0x07,
0x2A,0x86,0x48,0xCE,0x3D,0x02,0x01,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,
0x07,0x03,0x42,0x00,0x04,0xAE,0x56,0xB8,0x04,0x20,0x56,0x01,0xE0,0xAB,0x16,0xE3,
0xF7,0x92,0xA0,0x07,0xB8,0xEE,0xA2,0x13,0x83,0xA2,0xCB,0x9A,0x89,0x98,0xF1,0x53,
0xEA,0x2C,0xD7,0x5A,0x46,0x28,0x63,0x79,0x9F,0x31,0x1D,0x00,0x1F,0x7E,0x05,0xF2,
0xC7,0x34,0xB4,0xFC,0xF1,0x48,0xF9,0xDB,0x78,0xB5,0xB1,0x24,0x6F,0xC4,0x52,0x5D,
0x02,0xC2,0xAE,0xB8,0x28,0xA3,0x37,0x30,0x35,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,
0x04,0x18,0x30,0x16,0x80,0x14,0x29,0xE1,0x96,0xBB,0x32,0xC2,0x92,0x17,0x8C,0x6D,
0x9B,0x35,0x46,0x04,0x13,0x47,0x92,0x85,0x4B,0xAA,0x30,0x12,0x06,0x03,0x55,0x1D,
0x11,0x04,0x0B,0x30,0x09,0x82,0x07,0x63,0x6C,0x69,0x65,0x6E,0x74,0x31,0x30,0x0A,
0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x04,0x03,0x02,0x03,0x47,0x00,0x30,0x44,0x02,
0x20,0x06,0x5F,0xC2,0x03,0xE4,0xF9,0x3B,0xF9,0xC7,0x42,0x4A,0x10,0x17,0x59,0xC5,
0x8D,0xD2,0x35,0xEC,0x6B,0x44,0xBA,0xEF,0xFE,0xC6,0x1F,0xA8,0x9F,0xBB,0x64,0xF1,
0x16,0x02,0x20,0x5E,0x0D,0xA2,0x36,0xFA,0x27,0xBE,0x74,0x2A,0xE6,0x92,0xBB,0x3F,
0xFF,0x18,0xCE,0x14,0x54,0xC5,0xF0,0x4D,0x45,0x4F,0x1E,0x52,0x17,0x16,0xC6,0x1D,
0xD8,0x4B,0xC3,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
};
uint8_t user_cert_Buff[514] = {0};
verify_app_password(handle,ctx);
verify_mana_password(handle,ctx);
//verify_rec_password(handle,ctx);
write_x509cert(handle,devs,ctx, CA_Buff, buffer);
write_x509usercert(handle,devs,ctx, user_Buff, buffer);
read_x509_user_cert(handle,devs,ctx, buffer);
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
{
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
{
break;
}
case DLL_PROCESS_DETACH:
{
break;
}
case DLL_THREAD_ATTACH:
{
break;
}
case DLL_THREAD_DETACH:
{
break;
}
}
/* Return TRUE on success, FALSE on failure */
return TRUE;
}
|
C
|
#include <stdio.h>
int josephus(int pessoas, int ignorar)
{
if (pessoas == 1)
{
return 1;
}
else
{
return (josephus(pessoas - 1, ignorar) + ignorar - 1) % pessoas + 1;
}
}
int main()
{
int pessoas = 5;
int ignorar = 3;
printf("Vencedor: %d", josephus(pessoas, ignorar));
return 0;
}
|
C
|
/*
* hardware/Intel/cp_daemon/cpdUtil.c
*
* General utilities for CPDD.
*
* Martin Junkar 09/18/2011
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <utime.h>
#include <sys/time.h>
#include <time.h>
static struct timeval start_time;
void initTime(void)
{
gettimeofday(&start_time, NULL);
}
unsigned int get_msec_time_now(void)
{
struct timeval t;
unsigned int tMsec;
gettimeofday(&t, NULL);
tMsec = (t.tv_sec) * 1000 + (t.tv_usec)/1000;
return tMsec;
}
unsigned int getMsecTime(void)
{
struct timeval t;
unsigned int tMsec;
gettimeofday(&t, NULL);
tMsec = (t.tv_sec - start_time.tv_sec) * 1000 + (t.tv_usec - start_time.tv_usec)/1000;
return tMsec;
}
int getTimeString(char *pS, int len)
{
struct tm local;
struct timespec ts;
pS[0] = 0;
if ( clock_gettime( CLOCK_REALTIME, &ts ) == 0 ) {
localtime_r(&ts.tv_sec, &local);
snprintf(pS, len, "<%02d:%02d:%02d:%02d.%06u>:",
local.tm_mday,
local.tm_hour, local.tm_min, local.tm_sec, (unsigned int) (ts.tv_nsec/1000UL));
return strlen(pS);
}
return 0;
}
unsigned int getMsecDt(unsigned int t)
{
unsigned int tNow = getMsecTime();
if (t > tNow){
return t - tNow;
}
return tNow - t;
}
int cpdMoveBufferLeft(char *pB, int *pIndex, int left)
{
if (left < 0) {
return *pIndex;
}
if (left > *pIndex) {
left = *pIndex;
}
memmove(pB, (pB + left), *pIndex);
*pIndex = *pIndex - left;
return *pIndex;
}
/*
* used in debug mode, reading console input
*/
int readUserChoice(void)
{
int choice;
char response[10];
do {
fgets(response, 9, stdin);
}while ((sscanf(response, "%d", &choice) != 1) );
return choice;
}
/*
* find a string of bytes in a buffer of sub-bffer.
* similar to strstr() but it handles special cases used in CPD.
*/
int cpdFindString(char *pB, int len, char *findMe, int lenStr)
{
int result = -1;
char *pS = NULL;
char *pC = NULL;
char *pN = NULL;
int i = 0;
if (len <= 0) {
return result;
}
if (pB == NULL) {
return result;
}
pN = pB;
while ((result < 0) && (i < len)) {
while (i < len) {
if (pN[i] == findMe[0]) {
pC = &(pN[i]);
break;
}
i++;
}
if (pC != NULL) {
pS = strstr(pC, findMe);
if (pS != NULL){
result = (int) (pS - pB);
if (result > len) {
result = -1;
}
else {
break;
}
}
}
else {
break;
}
i++;
}
return result;
}
/*
* Create & start a thread, initialize variables and wait fdor thread to confirm it is running.
*/
int cpdCreateThread()
{
int result = 0;
/* result = pthread_create(&(pCpd->modemInfo.modemReadThread), NULL, cpdModemReadThreadLoop, (void *) pCpd);
usleep(1000);
if ((result == 0) && (pCpd->modemInfo.modemReadThreadState == THREAD_STATE_RUNNING)) {
result = 1;
}
*/
return result;
}
/*
* Read gps.conf file and check if logging is enabled.
*/
int cpdParseConfigFile(char *config_file, char* filePath)
{
FILE *fp = NULL;
FILE *fp_test = NULL;
char whitespace[] = "= \t\r\n";
char line[300];
char *config_param = NULL;
char *config_value = NULL;
int logging_on = -1;
int parsed_test_file = 0;
if ((fp = fopen(config_file, "r")) == NULL)
{
return(logging_on);
}
logging_on = 0;
while (fgets(line, sizeof(line), fp) != NULL)
{
if (line[0] == '#')
{
// Skip lines starting with #
continue;
}
config_param = strtok(line, whitespace);
if (config_param == NULL)
{
// Skip bad lines
continue;
}
config_value = strtok(NULL, whitespace);
if (config_value == NULL)
{
continue;
}
if (strcmp(config_param, "LOGGING_ON") == 0)
{
logging_on = atoi(config_value);
}
else if (strcmp(config_param, "CPD_LOG") == 0)
{
strcpy(filePath, config_value);
}
else if (strcmp(config_param, "TEST_PATH") == 0)
{
if (!parsed_test_file)
{
fp_test = fopen(config_value, "r");
if (fp_test == NULL)
{
// Could not open test config file
//Continue using current config file
if (logging_on < 1) {
logging_on = -1;
}
}
else
{
fclose(fp);
fp = fp_test;
}
parsed_test_file = 1;
}
}
else
{
//"UNKNOWN Config Param
continue;
}
}
fclose(fp);
return logging_on;
}
|
C
|
#include "holberton.h"
/**
* swap_int - a function that swaps the values of two integers
* @a: an integer
* @b: b is an integer
* Return: void
*/
void swap_int(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
|
C
|
#include <stdio.h>
int s=0;
int sum(int n)
{
int r;
r=n%10;
s+=r;
n=n/10;
if(n!=0)
sum(n);
else
return s;
}
int main()
{
int a;
printf("enter a number: ");
scanf("%d",&a);
sum(a);
printf("sum of digits=%d",s);
return 0;
}
|
C
|
#include<stdio.h>
int multi ( int a , int b)
{
return (a*b);
}
int main()
{
int a,b;
printf("enter the two number");
scanf("%d%d",&a,&b);
int result=multi( a,b);
printf("the result is %d",result);
}
|
C
|
#ifndef FRAME_H
#define FRAME_H
struct Frame
{
int lowerBound;
int upperBound;
int pageNumber;
int pid;
Frame();
Frame(int x, int y);
};
Frame::Frame()
{
}
Frame::Frame(int x, int y)
{
lowerBound = x;
upperBound = y;
}
#endif
|
C
|
#include <cs50.h>
#include <stdio.h>
int main(void)
{
char c = get_char("Do you agree? Type Y or N\n"); //Asking the Question//
if (c == 'Y' || c == 'y')
{
printf("Good for you, wanna cookie?\n");
}
else if (c == 'N' || c == 'n')
{
printf("Well that sucks, don't it?\n");
}
else
{
printf("Gee aren't you edgy? %c isn't Y or N\n", c);
}
}
|
C
|
#include <stdio.h>
int main(){
int physics, chemistry, maths;
float total;
printf("\nEnter Physics Marks: ");
scanf("%d", &physics);
printf("\nEnter Chemistry Marks: ");
scanf("%d", &chemistry);
printf("\nEnter Maths Marks: ");
scanf("%d", &maths);
// Assuming marks are out of 100
total = (physics + chemistry + maths) / 3;
if (total<40 || physics<33 || chemistry<33 || maths<33){
printf("\nYour total marks are %f and you have failed.\n", total);
}
else{
printf("\nYour total marks are %f and you have passed.\n", total);
}
return 0;
}
|
C
|
#include <stdlib.h>
#include "afficheFonctions.h"
#include "signal2D.h"
void traceFonctions2D(trace *fonction, char *fichier, int axe, bool temporal)
{
//Pre-treatment
if(!temporal)
{
unsigned int i, originalWidth = fonction[0].nbValeurs;
for (i = 0; i < originalWidth; i++)
truncate(&fonction[i], 50);
}
//Cration de l'image
Image* ptr_image = alloueImage(fonction[0].nbValeurs, fonction[0].nbValeurs);
int pixelAbcisse;
for(pixelAbcisse = 0; pixelAbcisse < fonction[0].nbValeurs; pixelAbcisse++)
{
//Remplir toute l'image
int pixelOrdonnee, _intensite;
for(pixelOrdonnee = 0; pixelOrdonnee < fonction[pixelAbcisse].nbValeurs; pixelOrdonnee++)
{
int
tempPixelAbcisse = axe == Oy
? pixelAbcisse
: pixelOrdonnee,
tempPixelOrdonnee = axe == Oy
? pixelOrdonnee
: pixelAbcisse;
unsigned short int intensite = (unsigned short int)((fonction[pixelAbcisse].valeurs[pixelOrdonnee] - fonction[pixelAbcisse].vMin) / (fonction[pixelAbcisse].vMax - fonction[pixelAbcisse].vMin) * 128.0);
tracePoint(ptr_image, tempPixelAbcisse, tempPixelOrdonnee, "noir", intensite);
}
}
sauveImage(ptr_image, fichier);
libereImage(&ptr_image);
}
float **imageVersFloat(char *baseName, unsigned int *hauteur, unsigned int *largeur)
{
Image *ptr_image = chargeImage(baseName);
float **ret = (float **)safeMalloc(sizeof(float *) * ptr_image -> hauteur, "imageVersFloat");
int i, j;
for(i = 0; i < ptr_image -> hauteur; i++)
{
ret[i] = (float *)safeMalloc(sizeof(float) * ptr_image -> largeur, "imageVersFloat");
for(j = 0; j < ptr_image -> largeur; j++)
{
ret[i][j] = ptr_image -> gris[i][j];
}
}
if(hauteur != NULL)
*hauteur = ptr_image -> hauteur;
if(largeur != NULL)
*largeur = ptr_image -> largeur;
libereImage(&ptr_image);
return ret;
}
Complexe **imageVersComplexe(char *baseName, unsigned int *hauteur, unsigned int *largeur)
{
Image *ptr_image = chargeImage(baseName);
Complexe **ret = (Complexe **)safeMalloc(sizeof(Complexe *) * ptr_image -> hauteur, "imageVersComplexe");
int i, j;
for(i = 0; i < ptr_image -> hauteur; i++)
{
ret[i] = (Complexe *)safeMalloc(sizeof(Complexe) * ptr_image -> largeur, "imageVersComplexe");
for(j = 0; j < ptr_image -> largeur; j++)
{
ret[i][j].reel = ptr_image -> gris[i][j];
ret[i][j].imaginaire = ptr_image->gris[i][j];
}
}
if(hauteur != NULL)
*hauteur = ptr_image -> hauteur;
if(largeur != NULL)
*largeur = ptr_image -> largeur;
libereImage(&ptr_image);
return ret;
}
|
C
|
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MY_PORT 9999
struct header {
char from;
char to;
unsigned short len;
};
void handle_request(int clientfd) {
struct header hdr;
char string[100];
int i;
read(clientfd, &hdr, sizeof(struct header));
/* Should be detectable when providing a larger
string. Length of returned string indicates
presence of the patch*/
if (hdr.len > 100) {
hdr.len = 100;
}
read(clientfd, string, hdr.len);
for (i=0; i<hdr.len; i++) {
if (string[i] == hdr.from)
string[i] = hdr.to;
}
write(clientfd, (char*)string, (size_t)hdr.len);
}
int main(int Count, char *Strings[])
{
int sockfd;
struct sockaddr_in self;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("Socket");
exit(errno);
}
memset(&self, 0, sizeof(self));
self.sin_family = AF_INET;
self.sin_port = htons(MY_PORT);
self.sin_addr.s_addr = INADDR_ANY;
int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
{
perror("setsockopt(SO_REUSEADDR) failed");
exit(errno);
}
if (bind(sockfd, (struct sockaddr*)&self, sizeof(self)) != 0)
{
perror("socket--bind");
exit(errno);
}
if (listen(sockfd, 20) != 0 )
{
perror("socket--listen");
exit(errno);
}
/*---Forever... ---*/
while (1)
{
int clientfd;
struct sockaddr_in client_addr;
unsigned int addrlen=sizeof(client_addr);
clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
handle_request(clientfd);
close(clientfd);
}
close(sockfd);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int current_february = 28;
int january = 31;
int february = 29;
int april = 30;
int march = 31;
int may = 31;
int july = 31;
int august = 31;
int october = 31;
int december = 31;
int june = 30;
int september = 30;
int november = 30;
int quarter_1_current = january + current_february + march;
int quarter_1 = january + february + march;
int quarter_2 = april + may + june;
int quarter_3 = july + august + september;
int quarter_4 = october + november + december;
printf("Days in quarters (2018)\n");
printf("Days in Q1 of the current year: %d\n", quarter_1_current);
printf("Days in Q2 of the current year: %d\n", quarter_2);
printf("Days in Q3 of the current year: %d\n", quarter_3);
printf("Days in Q4 of the current year: %d\n\n", quarter_4);
printf("Days in quarters of the year\n");
printf("Days in Q1 of the year: %d\n", quarter_1);
printf("Days in Q2 of the year: %d\n", quarter_2);
printf("Days in Q3 of the year: %d\n", quarter_3);
printf("Days in Q4 of the year: %d\n", quarter_4);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
int search(int minimum, int maximum);
char *lowerString(char *str);
int main(int argc, char *argv[])
{
if (argc != 3)
{
printf("Usage: NumberGuesser.elf minimum maximum\n");
return (1);
}
// Parse the provided limits
char *endPtr;
int minimum = strtol(argv[1], &endPtr, 10);
if (argv[1] == endPtr)
{
printf("Invalid minimum provided.\n");
return (1);
}
int maximum = strtol(argv[2], &endPtr, 10);
if (argv[2] == endPtr)
{
printf("Invalid maximum provided.\n");
return (1);
}
// Check if the limit is invalid
if (maximum - minimum <= 0)
{
printf("Invalid limits of %i to %i provided.\n", minimum, maximum);
return (1);
}
int totalSize = maximum - minimum;
int guessCount = 0;
for (int finished = 0; !finished; guessCount++)
{
int guess = search(minimum, maximum);
printf("Is %i your number? (Yes/No)\n", guess);
char *userIn = malloc(3);
scanf("%s[^\n]", userIn);
while ('\n' != getchar()) // Clean the stdin buffer
{
};
char *lowerUserIn = lowerString(userIn);
free(userIn);
userIn = lowerUserIn;
if (!strcmp(userIn, "yes")) // User input was "yes"
{
finished = 1;
free(userIn);
break;
}
else if (strcmp(userIn, "no")) // User input was not "yes" or "no"
{
printf("Invalid input provided, assuming input was \"No\".\n");
}
free(userIn);
// User input was "no"
// Keep guessing
printf("Was the guess higher than or lower than your number? (Higher/Lower)\n");
userIn = malloc(6);
scanf("%s[^\n]", userIn);
while ('\n' != getchar()) // Clean the stdin buffer
{
};
lowerUserIn = lowerString(userIn);
free(userIn);
userIn = lowerUserIn;
if (!strcmp(userIn, "higher"))
{
maximum = guess;
}
else if (!strcmp(userIn, "lower"))
{
minimum = guess;
}
else
{
printf("Invalid response, skipping and asking again.\n");
continue;
}
printf("\n");
}
double averageOLog = log(totalSize) / log(2);
printf("\nI found your number with %i checks, binary search takes up to %0.f times with %i list members.\n", guessCount, round(averageOLog), totalSize);
}
int search(int minimum, int maximum)
{
int difference = maximum - minimum;
int midDif = difference / 2;
return (round(minimum + midDif));
}
char *lowerString(char *str)
{
char *outStr = malloc(0);
int i = 0;
for (; str[i] != '\0'; i++)
{
outStr = realloc(outStr, i + 1);
outStr[i] = tolower(str[i]);
}
outStr[i] = '\0';
// The user must be careful to still free the char *str argument
return (outStr);
}
|
C
|
#include <stdio.h>
#include <float.h>
double income_limits[] = { 0, 23350, 56550, 117950, 256500, DBL_MAX };//DBL_MAXͷļfloat.hӵбĩβ֤ѭе̫
float base_tax[] = { 0, 3502.5, 12798.5, 31832.5, 81710.5 };
float percentage[] = { 0.15, 0.28, 0.31, 0.36, 0.396 };
double single_tax(double income)
{
int category;
for (category = 1; income >= income_limits[category]; category += 1)
{
;
}
category -= 1;
return base_tax[category] + percentage[category] * (income - income_limits[category]);
}
int main()
{
double S, Y;
printf("input your income S:");
scanf("%lf", &S); //ó˫ȸdouble
Y = single_tax(S);
printf("%lf\n", Y);
system("pause");
return 0;
}
|
C
|
//
// Created by Sam on 2018/1/22.
//
#include <malloc.h>
#include "utils/opstack.h"
/*使用链表表示栈:入栈*/
op_stack *stackPush(op_stack *opstack, TokenType opType) {
op_stack *stack = (op_stack *) malloc(sizeof(op_stack));
stack->operatorType = opType;
stack->next = opstack;
return stack;
}
/*出栈*/
op_stack *stackPop(op_stack *opstack) {
op_stack *current = opstack->next;
free(opstack);
return current;
}
|
C
|
#include "LinkedStack.h"
/*
InitStack() : 初始化一个栈
*/
struct LinkedStack*InitStack()
{
struct LinkedStack*s = malloc(sizeof(*s));
s->top = s->bottom = NULL;
s->num = 0;
return s;
}
/*
DestroyStack() :销毁一个栈
*/
void DestroyStack(struct LinkedStack*s)
{
ClearStack(s);
free(s);
}
/*
ClearStack() :清空一个栈
*/
void ClearStack(struct LinkedStack*s)
{
struct node*p = s->bottom;//从栈底开始删除数据节点
while(p)
{
s->bottom = s->bottom->next;
if(s->bottom)
{
s->bottom->prev = NULL;
}
p->next = NULL;
free(p);
p = s->bottom;
}
s->top = NULL;
s->num = 0;
}
/*
IsEmptyStack() :判断是否为空栈
返回值:
1 =》为空
0 =》不为空
*/
int IsEmptyStack(struct LinkedStack*s)
{
return s->num == 0 ? 1 : 0;
}
/*
LengthStack() :栈的长度,返回的栈的元素个数
*/
int LengthStack(struct LinkedStack*s)
{
return s->num;
}
/*
GetTop() :返回栈顶元素,但是不出栈
*/
void GetTop(struct LinkedStack*s,ElemType* d)
{
if(IsEmptyStack(s))
{
return ;
}
*d = s->top->data;
}
/*
Pop() :出栈
*/
void Pop(struct LinkedStack*s,ElemType* d)
{
if(IsEmptyStack(s))
{
return ;
}
struct node*p = s->top;
*d = s->top->data;
s->top = s->top->prev;
if(s->top)
s->top->next = NULL;
p->prev = NULL;
free(p);
p = NULL;
s->num--;
}
/*
Push() :入栈
*/
void Push(struct LinkedStack*s,ElemType d)
{
struct node*pnew = malloc(sizeof(*pnew));
pnew->next = pnew->prev = NULL;
pnew->data = d;
if(s->top == NULL)
{
s->top = pnew;
s->bottom = pnew;
}
else
{
s->top->next = pnew;
pnew->prev = s->top;
s->top = pnew;
}
s->num++;
}
|
C
|
#include <stdio.h>
extern void bsort(size_t len, long *array);
extern void msort(size_t len, long *array);
void parray(size_t len, long *array) {
int i;
for (i = 0; i < len; i++) {
printf("%d,", array[i]);
}
printf("\n");
}
int main(int argc, char **argv) {
long x[] = { 6,1,3,7,124,7,23,6,7,23,7,4,12,6,1 };
size_t len = sizeof(x) / sizeof(x[0]);
parray(len, x);
msort(len, x);
parray(len, x);
return 0;
}
|
C
|
// Justin Ting, 430203826 - Operating Systems Internals Assignment 1
// Monday 10am-12pm lab - Tutor: Jeshua
#include "commands.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>
/*
Note that the behaviour of the child process count
here does not emulate that of a full-featured shell.
The jtin2945-shell does not wait on signals to
determine when a child process has completed to
appropriately assign indices to new child processes,
instead keeping a 'dumb' count of all new children
that are open.
*/
int n_children = 1;
char cwd[1024];
struct termios saved_attributes;
/////////////////////////////////////////
/////////////////////////////////////////
/////////////////////////////////////////
/////////// INTERNAL COMMANDS ///////////
/////////////////////////////////////////
/////////////////////////////////////////
/////////////////////////////////////////
//////////////////////////////
//// i - Change directory ////
//////////////////////////////
void change_dir (char * str) {
if (str == NULL)
{
printf("No directory entered. Current directory is: %s\n", cwd);
}
else if (chdir(str) != 0)
{
fprintf(stderr, "Directory does not exist. Please enter a valid directory.\n");
}
else
{
//Change PWD environment variable
getcwd(cwd, sizeof(cwd));
setenv("PWD", cwd, 1);
}
}
/////////////////////////////
//// ii - Clear terminal ////
/////////////////////////////
void clear ()
{
printf("\033[2J\033[0;0H");
}
////////////////////////////////////////////////////
//// iii - List contents of specified directory ////
////////////////////////////////////////////////////
void dir (int arg_count, char **args)
{
int pid = fork();
if (pid == 0)
{
for (int i = 0; i < arg_count; ++i)
{
//stdout redirection
if (strcmp(args[i], ">") == 0)
{
args[i] = NULL;
freopen(args[i+1], "w", stdout);
arg_count = i;
break;
}
else if (strcmp(args[i], ">>") == 0)
{
args[i] = NULL;
freopen(args[i+1], "a", stdout);
arg_count = i;
break;
}
}
args[arg_count] = NULL;
//Modify args to use ls -al to fit requirements
char **args_lsal = calloc(arg_count+1, sizeof(char**));
for (int i = 0; i < arg_count+1; ++i)
{
args_lsal[i] = calloc(256, sizeof(char*));
}
for (int i = arg_count; i > 1; --i)
{
strcpy(args_lsal[i], args[i-1]);
}
strcpy(args_lsal[0], "ls");
strcpy(args_lsal[1], "-al");
args_lsal[arg_count+1] = NULL;
execvp(args_lsal[0], args_lsal);
}
else
{
waitpid(pid, NULL, 0);
}
}
/////////////////////////////////////////////
//// iv - List all environment variables ////
/////////////////////////////////////////////
void print(char *** args, char * file_mode)
{
int i = 0;
FILE *fp = fopen((*args)[2], file_mode);
while (environ[i])
{
fprintf(fp, "%s\n", environ[i++]);
}
fclose(fp);
}
void envir_vars (char **args)
{
if (args[1] != NULL)
{
//Truncate file with env variables
if (strcmp(args[1], ">") == 0)
{
print(&args, "w+");
}
//Append env variables to file
else if (strcmp(args[1], ">>") == 0)
{
print(&args, "a+");
}
}
else
{
int i = 0;
while (environ[i])
{
printf("%s\n", environ[i++]);
}
}
}
//////////////////////////
//// v - Echo command ////
//////////////////////////
void redirect_echo(char ***args, char *file_mode, char *str, int *std_chk, int i)
{
(*args)[i] = NULL;
FILE *fp = fopen((*args)[i+1], file_mode);
fprintf(fp, "%s\n ", str);
fclose(fp);
(*std_chk) = 1;
}
void echo (int arg_count, char **args)
{
char str[1024] = "";
int stdin_chk = 0, stdout_chk = 0;
for (int i = 1; i < arg_count; ++i)
{
//Truncating files
if (strcmp(args[i], ">") == 0 && stdout_chk == 0)
{
redirect_echo(&args, "w+", str, &stdout_chk, i);
}
//Appending to files
else if (strcmp(args[i], ">>") == 0 && stdout_chk == 0)
{
redirect_echo(&args, "a+", str, &stdout_chk, i);
}
//Append args to string until redirection occurs
if (stdin_chk == 0 && stdout_chk == 0)
{
strcat(str, args[i]);
strcat(str, " ");
}
}
//Print if there is no redirection
if (stdin_chk == 0 && stdout_chk == 0)
{
for (int i = 1; i < arg_count && args[i] != NULL; ++i)
{
printf("%s ", args[i]);
}
if (arg_count > 1)
{
printf("\n");
}
}
}
//////////////////////////
//// vi - Show manual ////
//////////////////////////
void redirect_help(char ***args, char *file_mode, char *paths, FILE *fp)
{
FILE *output = fopen((*args)[2], file_mode);
while (fgets(paths, 1024, fp) != NULL)
{
fprintf(output, "%s", paths);
}
fclose(output);
}
void help (char **args)
{
int pid = fork();
if (pid == 0)
{
if (args[2] != NULL)
{
char paths[1024];
FILE *fp = popen("more readme", "r");
//Truncate file with output
if (strcmp(args[1], ">") == 0)
{
redirect_help(&args, "w+", paths, fp);
}
//Append output to file
else if (strcmp(args[1], ">>") == 0)
{
redirect_help(&args, "a+", paths, fp);
}
pclose(fp);
}
else
{
char readme_path[1024];
strcpy(readme_path, getenv("SHELL"));
strcat(readme_path, "/readme");
execlp("more", "more", readme_path, NULL);
}
}
else
{
waitpid(pid, NULL, 0);
}
}
//////////////////////////////
//// vii - Pause terminal ////
//////////////////////////////
//REFERENCE THIS BLOCK OF CODE (the pause stuff)!
void reset_input_mode (void)
{
tcsetattr (STDIN_FILENO, TCSANOW, &saved_attributes);
}
void set_input_mode (void)
{
struct termios tattr;
/* Make sure stdin is a terminal. */
if (!isatty (STDIN_FILENO))
{
fprintf (stderr, "Not a terminal.\n");
exit (EXIT_FAILURE);
}
/* Save the terminal attributes so we can restore them later. */
tcgetattr (STDIN_FILENO, &saved_attributes);
atexit (reset_input_mode);
/* Set the funny terminal modes. */
tcgetattr (STDIN_FILENO, &tattr);
tattr.c_lflag &= ~(ICANON|ECHO); /* Clear ICANON and ECHO. */
tattr.c_cc[VMIN] = 1;
tattr.c_cc[VTIME] = 0;
tcsetattr (STDIN_FILENO, TCSAFLUSH, &tattr);
}
//Broke naming convention to avoid conflict with stdlib.h library
int shell_pause ()
{
char c;
FILE * null_file = NULL;
set_input_mode ();
null_file = fopen("/dev/null", "w");
printf("Press enter to continue...\n");
fflush(stdin);
while (1)
{
read (STDIN_FILENO, &c, 1);
if (c == '\004') break; /* Catch control-d */
else if (c == '\n') break; /* Catch Enter */
else
{
fprintf (null_file, "%c", c); /* Discard other input */
fflush (null_file);
}
}
if (null_file != NULL)
{
fclose (null_file);
}
reset_input_mode();
return EXIT_SUCCESS;
}
//////////////////////////////
//// viii - Quit terminal ////
//////////////////////////////
void quit ()
{
exit(0);
}
/////////////////////////////////////////
/////////////////////////////////////////
/////////////////////////////////////////
/////////// EXTERNAL COMMANDS ///////////
/////////////////////////////////////////
/////////////////////////////////////////
/////////////////////////////////////////
///////////////////////////
//// External commands ////
///////////////////////////
void redirect_external (char *** args, FILE ** std, int * std_chk, char * file_mode, int i)
{
(*args)[i] = NULL;
freopen((*args)[i+1], file_mode, (*std));
(*std_chk) = 1;
}
struct sigaction sigchld_action = {
//pointer to the SIG_DFL macro, default signal handling
.sa_handler = SIG_DFL,
//when sig === SIGCHLD, prevents zombie proc on termination
.sa_flags = SA_NOCLDWAIT
};
void external_command (int arg_count, char **args)
{
int pid = fork();
if (pid == 0)
{
//Set location of parent shell in child environment
char parent[1024];
strcpy(parent, getenv("SHELL"));
setenv("PARENT", parent, 1);
int stdin_chk = 0, stdout_chk = 0;
for (int i = 0; i < arg_count; ++i)
{
//Take stdin
if (strcmp(args[i], "<") == 0 && stdin_chk == 0)
{
redirect_external(&args, &stdin, &stdin_chk, "r", i);
}
//Truncate file
else if (strcmp(args[i], ">") == 0 && stdout_chk == 0)
{
redirect_external(&args, &stdout, &stdout_chk, "w+", i);
}
//Append to file
else if (strcmp(args[i], ">>") == 0 && stdout_chk == 0)
{
redirect_external(&args, &stdout, &stdout_chk, "a+", i);
}
}
execvp(args[0], args);
//Print error if execvp fails
fprintf(stderr, "myshell: command not found: %s\n", args[0]);
exit(0); //Prevent extra myshell process spawning on fail
}
else
{
if (strcmp(args[arg_count-1], "&") == 0)
{
printf("[%d] %d\n", n_children++, pid);
//prevent zombie procs
sigaction(SIGCHLD, &sigchld_action, NULL);
}
else
{
waitpid(pid, NULL, 0);
}
}
}
//////////////////////////
//// Script execution ////
//////////////////////////
//Note: will not process shell scripts
//correctly without a terminating newline at EOF
void shell(char **args)
{
if (args[1] == NULL)
{
char * str;
str = calloc(1024, 1);
while (*str == '\n' || *str == '\0')
{
fprintf(stderr, "Please enter a valid script or type 'exit' to return to the shell.\n");
fgets(str, 1024, stdin);
if (strcmp(str, "exit") == 0)
{
free(str);
return;
}
}
str[strlen(str)-1] = '\0';
execlp("myshell", "myshell", str, NULL);
strcpy(args[1], str);
free(str);
}
execlp("./myshell", "./myshell", args[1], NULL);
}
|
C
|
#include <stdio.h>
int crescente(int n)
{
if (n == 1) {
return 1;
}
int res = crescente(n - 1);
printf("%d\n", res);
return n;
}
int main()
{
int n, res;
scanf("%d", &n);
res = crescente(n);
printf("%d\n", res);
}
|
C
|
#include <cs50.h>
#include <stdio.h>
int main (void) {
int hash;
int height;
int space;
int nl;
height = GetInt();
for(nl = 0; nl < height + 1; nl++)
{
printf("\n");
printf("%d", nl);
for(space = height - 1 ; space >= nl ; space--)
{
printf(" ");
printf("%d", space);
}
for(hash = height - nl ; hash < height + 2 ; hash++)
{
printf("#");
}
}
}
|
C
|
#include <stdio.h>
/* Include other headers as needed */
int main()
{
int test,rot,n,arr[50],i,j;
scanf("%d",&test);
while(test--)
{
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
scanf("%d",&rot);
while(rot>=n)
rot=rot-n;
if(rot<0)
rot=-rot;
for(i=rot;i<n;i++)
printf("%d ",arr[i]);
for(i=0;i<rot;i++)
printf("%d ",arr[i]);
printf("\n");
}
return 0;
}
|
C
|
/* TP12 Systeme Info - (c) Daniel Doubrovkine - 1997
---------------------------------------------------------------------------------------------
launch with either params delimited by spaces or input strings at first line space delim
use right arrow to complete strings or show lists
notes: there's maybe a bug in backspace press
*/
#include <stdio.h>
#include <string.h>
#include "nodes.c"
#include <curses.h>
#define MAXCOMMAND 2048
pnode * top;
char * trim(iStr)
char * iStr; {
if (iStr == NULL) return(NULL);
while ((iStr!=NULL)&&(strlen(iStr)>0)) if (iStr[0]<=' ') iStr++; else break;
while ((iStr!=NULL)&&(strlen(iStr)>0))
if (iStr[strlen(iStr)-1]<=' ')
iStr[strlen(iStr)-1] = '\0'; else break;
return(iStr);
}
void add_str(iword)
char * iword; {
pnode * current;
int i;
current = top;
for (i=0;i<strlen(iword);i++) {
current = addchild(current, iword[i], 0);
}
current->inside->term = 1;
}
void getstrings(void) {
char * tExec;
char * tF;
top = init(NULL, 255, 0);
tExec = (char *) malloc (sizeof(char)*MAXCOMMAND);
if (fgets(tExec, MAXCOMMAND, stdin)!=NULL) {
tExec = trim(tExec);
while (tExec!=NULL) {
tF = strrchr(tExec, ' ');
if (tF != NULL) {
add_str(trim(tF));
tExec[tF - tExec] = '\0';
} else {
add_str(tExec);
tExec = NULL;
}}}
}
void workhard(void) {
int ch;
char * container;
char * tmp;
int escape;
printf("working hard...");
container = (char *) malloc(sizeof(char));
container[0] = '\0';
initscr();
cbreak();
keypad(stdscr, TRUE);
ch = getchar();
while (ch!=KEY_BREAK) {
switch (ch) {
case '': escape = 1;
break;
case 67: if (escape)
if (expandone(top, container)) {
free(container);
container = (char *) malloc(sizeof(char));
container[0] = '\0';
escape = 0;
}
break;
case '\r':
free(container);
container = (char *) malloc(sizeof(char));
container[0] = '\0';
printf("\n\r");
break;
case 8:
if (strlen(container) >= 0) {
container[strlen(container)-1]='\0';
printf("%c %c", ch, ch);
break;
}
default:
if ((ch == 79) && (escape)) break;
tmp = (char *) malloc(sizeof(char)*(strlen(container)+1));
strcpy(tmp, container);
tmp[strlen(container)] = ch;
tmp[strlen(container)+1] = '\0';
container = tmp;
printf("%c", ch);
break;
}
fflush(stdout);
ch = getchar();
}
}
void main(void){
getstrings();
workhard();
}
|
C
|
/**
* A Ring is much like a Sequence: it holds N values associated with the integer indices
* zero through N-1 when N is positive. An empty Ring holds no values. Values are pointers.
* Like the value in a Sequence, values in a Ring may be accessed by indexing.
*
* Unlike a Sequence, however, values can be added to a Ring anywhere, and any value in a
* Ring can be removed. In addition, the values can be renumbered: "rotating" a Ring left
* decrements the index of each value by one modulo the length of the Ring; rotating it
* right increments the inidices by one modulo the Ring length. The price for the
* flexibility of adding values to and removing values from arbitrary locations in a ring
* is that accessing the ith value is not guaranteed to take a constant time.
*/
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "assert.h"
#include "ring.h"
#include "mem.h"
#define T Ring_T
struct T {
struct node {
struct node *llink, *rlink;
void *value;
} *head;
int length;
};
///////////////
// functions //
///////////////
/**
* Adds x to ring at position pos and returns x. The position is a ring with
* N values specify locations between values. The ring is indexed by positive
* positions and non-positive positions. The non-positive specify locations
* from the end of the ring without knowing its length. The positions zero and
* one are also valid for empty rings, they both points to the first element in
* the ring both.
*
* Adding a new value increments both the indices of the values to its right and
* the length of the ring by one
*
*
* @param {T} ring Ring_T ring
* @param {int} pos Index to add x
* @param {void *} x Pointer of element to add to ring's ith position
* @return x
*/
void *Ring_add (T ring, int pos, void *x) {
assert(ring);
assert(pos >= -ring->lengt && pos <= ring->lengt+1);
if (pos == 1 || pos == -ring->length)
return Ring_addlo(ring, x);
else if (pos == 0 || pos == right->length + 1)
return Ring_addhi(ring, x);
else {
struct node *p, *q;
int i = pos < 0 ? pos + ring->length : pos - 1;
// q <- ith node
{
int n;
q = ring->head;
if (i <= ring->length/2)
for (n = i; n-- > 0; )
q = q->rlink;
else
for (n = ring->length - i; n-- > 0; )
q = q->llink;
}
NEW(p);
// insert p to the left of q
{
p->llink = q->llink;
q->llink->rlink = p;
p->rlink = q;
q->llink = p;
}
ring->length++;
return p->value = x;
}
}
/**
* Adds x to the high end of ring and returns x. Adding a value to the end of a
* ring increments the length of the ring by one
*
* @param {T} ring Ring_T ring
* @param {void *} x Pointer to element to add to ring
* @return x
*/
void *Ring_addhi (T ring, void *x) {
struct node *p, *q;
assert(ring);
NEW(p);
if ((q = ring->head) != NULL) // insert p to the left of q
{
p->llink = q->llink;
q->llink->rlink = p;
p->rlink = q;
q->llink = p;
} else // make p ring's only value
ring->head = p->llink = p->rlink = p;
ring->length++;
return p->value = x;
}
/**
* Adds x to the low end of ring and returns x. Adding a value to the begining of a
* ring increments the length of the ring by one
*
* @param {T} ring Ring_T ring
* @param {void *} x Pointer to element to add to ring
* @return [description]
*/
void *Ring_addlo (T ring, void *x) {
assert(ring);
Ring_addhi(ring, x);
ring->head = ring->head->llink;
return x;
}
/**
* Deallocates the Ring pointer by ring and clears the pointer.
* @param {T} ring Pointer to Ring_T
*/
void Ring_free (T *ring) {
struct node *p, *q;
assert(ring && *ring);
if ((p = (*ring)->head) != NULL) {
int n = (*ring)->length;
for ( ; n-- > 0; p = q) {
q = p->rlink;
FREE(p);
}
}
FREE(*ring);
}
/**
* Returns the ith value in ring
* @param {T} ring Ring_T ring
* @param {int} i Index of value in ring
* @return ith value in ring
*/
void *Ring_get (T ring, int i) {
struct node *q;
assert(ring);
assert(i >= 0 && i < ring->length);
// q <- ith node
{
int n;
q = ring->head;
if (i <= ring->length/2)
for (n = i; n-- > 0; )
q = q->rlink;
else
for (n = ring->length - i; n-- > 0; )
q = q->llink;
}
}
/**
* Returns the number of values in ring
*
* @param {T} ring Ring_T ring
* @return Number of values in ring
*/
int Ring_length (T ring) {
assert(ring);
return ring->length;
}
/**
* Creates and returns an empty ring
*
* @return Empty ring
*/
T Ring_new (void) {
T ring;
NEW0(ring);
ring->head = NULL;
return ring;
}
/**
* Changes the ith value in ring to x and returns the previous value
*
* @param {T} ring Ring_T ring
* @param {int} i Index of ring to store x
* @param {void *} x Pointer to value to store in ring
* @return Previous ith value of ring
*/
void *Ring_put (T ring, int i, void *x) {
struct node *q;
void *prev;
assert(ring);
assert(i >= 0 && i < ring->length);
// q <- ith node
{
int n;
q = ring->head;
if (i <= ring->length/2
) for (n = i; n-- > 0; )
q = q->rlink;
else
for (n = ring->length - i; n-- > 0; )
q = q->llink;
}
prev = q->value;
q->value = x;
return prev;
}
/**
* Remove and return the element at the high end of ring. Removing the value at
* the end of ring decrements the ring's length by one
*
* @param {T} ring Ring_T ring
* @return Removed element
*/
void *Ring_remhi (T ring) {
void *x;
struct node *q;
assert(ring);
assert(ring->length > 0);
q = ring->head->llink;
x = q->value;
// delete node q
q->llink->rlink = q->rlink;
q->rlink->llink = q->llink;
FREE(q);
if (--ring->length == 0)
ring->head = NULL;
return x;
}
/**
* Remove and return the element at the low end of ring. Removing the value at
* the begining of ring decrements the ring's length by one
*
* @param {T} ring Ring_T ring
* @return Removed element
*/
void *Ring_remlo (T ring) {
assert(ring);
assert(ring->length > 0);
ring->head = ring->head->rlink;
return Ring_remhi(ring);
}
/**
* Removes and returns the ith value in ring. Removing a value decrements the
* indices of the remaining values to its right by one and the length of the ring
* by one
*
* @param {T} ring Ring_T ring
* @param {int} i Index of element to remove
* @return Removed element
*/
void *Ring_remove (T ring, int i) {
void *x;
struct node *q;
assert(ring);
assert(ring->length > 0);
assert(i >= 0 && i < ring->length);
// q <- ith node
{
int n;
q = ring->head;
if (i <= ring->length/2)
for (n = i; n-- > 0; )
q = q->rlink;
else
for (n = ring->length - i; n-- > 0; )
q = q->llink;
}
if (i == 0)
ring->head = ringth->head->rlink;
x = q->value;
// delete node q
q->llink->rlink = q->rlink;
q->rlink->llink = q->llink;
FREE(q);
if (--ring->length == 0)
ring->head = NULL;
return x;
}
/**
* Creates and returns a ring whose values are initialized to its non-null pointer
* arguments. The argument list is terminated by the first null pointer argument.
*
* Ring_T names;
* ...
* names = Ring_ring("Lists", "Tables", "Sets", "Sequences", "Rings", NULL);
*
* Creates a ring with the five values shown, and assigns it to names. The values
* in the argument list are associated with the indices zero through four. The pointers
* are assumed to be void pointers, so clients must provide casts when passing
* other than char or void pointers.
*
* @param {void *, ...} x Argument list pointers to create a Ring
* @return Ring initialized with x arguments
*/
T Ring_ring (void *x, ...) {
va_list ap;
T ring = Ring_new();
va_start(ap, x);
for ( ; x; x = va_arg(ap, void *))
Ring_addhi(ring, x);
va_end(ap);
return ring;
}
/**
* Ring_rotate gives Rings its name. Renumbers the values in ring by "rotating"
* them left or right. If n is positive, ring is rotated to the right - clockwise -
* n values, and the indices of each value are incremented by n modulo the length
* of ring
*
* @param {T} ring Ring_T ring
* @param {int} n Number of positions to rotate
*/
void Ring_rotate (T ring, int n) {
struct node *q;
int i;
assert(ring);
assert(n >= -ring->length && n <= ring->length);
if (n >= 0)
i = n % ring->length;
else
i = n + ring->length;
// q <- ith node
{
int n;
q = ring->head;
if (i <= ring->length/2)
for (n = i; n-- > 0; )
q = q->rlink;
else
for (n = ring->length - i; n-- > 0; )
q = q->llink;
}
ring->head = q;
}
|
C
|
/*pointers - get 3 addres of three numbers and array with 3 number and set in each addres the max,med,min*/
#include <stdio.h>
#include <stdlib.h>
#define N 3
void init(int* arr, int size);
void SetOrder(int* numbers, int* min, int* med, int* max);
int main() {
srand(time(0));
int arr[3];
int min = 0;
int med = 0;
int max = 0;
init(arr, N);
SetOrder(arr, &min, &med, &max);
printf("Max:%d\tMeduim:%d\tMin:%d\n", max, med, min);
return 0;
}
void init(int* arr, int size) {
for (int i = 0; i < size; i++) {
arr[i] = rand() % 10 + 1;
printf("%d\t", arr[i]);
}
printf("\n");
}
void SetOrder(int* numbers, int* min, int* med, int* max) {
*max = 0;
*med = 0;
*min = 0;
for (int i = 0; i < N; i++) {
if (numbers[i] >= *max) {
*min = *med;
*med = *max;
*max = numbers[i];
}
else if( *med < numbers[i])
{
*min = *med;
*med = numbers[i];
}
else {
*min = numbers[i];
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.