language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#ifndef _INCLUDED_QUADTREE_H #define _INCLUDED_QUADTREE_H typedef struct _quadtree_node_t { struct _quadtree_node_t *parent; float side_length; // cells are square int num_items; // if 1, this node is a leaf, else an internal node float mass; // total mass of this cell (sum of all children) float x; // centre of mass float y; // centre of mass /* OBSOLETE float fx; // net force on this cell float fy; // net force on this cell */ union { struct { // for a leaf float radius; // radius of item void *item; // pointer to actual item }; struct { // for an internal node struct _quadtree_node_t *q0; struct _quadtree_node_t *q1; struct _quadtree_node_t *q2; struct _quadtree_node_t *q3; }; }; } quadtree_node_t; typedef struct _quadtree_pool_t { int num_nodes_alloc; int num_nodes_used; quadtree_node_t *nodes; struct _quadtree_pool_t *next; } quadtree_pool_t; typedef struct _quadtree_t { struct _quadtree_pool_t *quad_tree_pool; double min_x; double min_y; double max_x; double max_y; quadtree_node_t *root; } quadtree_t; quadtree_t *quadtree_new(); void quadtree_build(layout_t *layout, quadtree_t *qt); #endif // _INCLUDED_QUADTREE_H
C
#pragma once #include "Types.h" #include <math.h> #define M_PI 3.1415926535897932 #define M_DEG_TO_RAD(deg) deg/180 * M_PI #define M_RAD_TO_DEG(rad) rad/M_PI * 180 union v2 { v2() : x(0.0f), y(0.0f) {} v2(r32 x, r32 y) : x(x), y(y) {} struct { r32 x; r32 y; }; struct { r32 u; r32 v; }; inline v2 operator-(const v2& vec) const { return v2(x - vec.x, y - vec.y); } }; struct quat; union v3 { v3() : x(0.0f), y(0.0f), z(0.0f) {} v3(r32 x, r32 y, r32 z) : x(x), y(y), z(z) {} inline r32 Dot(const v3& vec) const { return x * vec.x + y * vec.y + z * vec.z; } inline r32 Length() const { return sqrtf(Dot(*this)); } inline v3 Cross(const v3& vec) const { return v3(y * vec.z - z * vec.y, z * vec.x - x * vec.z, x * vec.y - y * vec.x); } inline v3 Normalized() const { r32 len = Length(); return v3(x / len, y / len, z / len); } inline v3 Rotate(const v3& axis, r32 deg) const { r32 rad = M_DEG_TO_RAD(deg); r32 sinAngle = sinf(-rad); r32 cosAngle = cosf(-rad); return Cross(axis * sinAngle) + (*this * cosAngle) + (axis * Dot(axis * (1.0f - cosAngle))); } v3 Rotate(const quat& rot) const; inline v3 operator*(r32 scaler) const { return v3(x * scaler, y * scaler, z * scaler); } inline v3 operator*(const v3& vec) const { return v3(x * vec.x, y * vec.y, z * vec.z); } inline v3 operator+(const v3& vec) const { return v3(x + vec.x, y + vec.y, z + vec.z); } inline v3 operator-(const v3& vec) const { return v3(x - vec.x, y - vec.y, z - vec.z); } inline v3& operator+=(const v3& vec) { x += vec.x; y += vec.y; z += vec.z; return *this; } inline v3& operator*=(r32 scaler) { x *= scaler; y *= scaler; z *= scaler; return *this; } inline v3& operator*=(const v3& vec) { x *= vec.x; y *= vec.y; z *= vec.z; return *this; } struct { r32 x; r32 y; r32 z; }; struct { r32 r; r32 g; r32 b; }; }; union m4 { m4() : m00(0.0f), m01(0.0f), m02(0.0f), m03(0.0f), m10(0.0f), m11(0.0f), m12(0.0f), m13(0.0f), m20(0.0f), m21(0.0f), m22(0.0f), m23(0.0f), m30(0.0f), m31(0.0f), m32(0.0f), m33(0.0f) {} m4(r32 m00, r32 m01, r32 m02, r32 m03, r32 m10, r32 m11, r32 m12, r32 m13, r32 m20, r32 m21, r32 m22, r32 m23, r32 m30, r32 m31, r32 m32, r32 m33) : m00(m00), m01(m01), m02(m02), m03(m03), m10(m10), m11(m11), m12(m12), m13(m13), m20(m20), m21(m21), m22(m22), m23(m23), m30(m30), m31(m31), m32(m32), m33(m33) {} struct { r32 m00; r32 m01; r32 m02; r32 m03; r32 m10; r32 m11; r32 m12; r32 m13; r32 m20; r32 m21; r32 m22; r32 m23; r32 m30; r32 m31; r32 m32; r32 m33; }; struct { r32 m[4][4]; }; inline r32* operator[](u32 index) { return m[index]; } inline const r32* operator[](u32 index) const { return m[index]; } inline m4 operator*(const m4& mat) const { m4 res; for (u32 i = 0; i < 4; i++) { for (u32 j = 0; j < 4; j++) { res[i][j] = m[i][0] * mat[0][j] + m[i][1] * mat[1][j] + m[i][2] * mat[2][j] + m[i][3] * mat[3][j]; } } return res; } inline void InitIdentity() { for (u32 i = 0; i < 4; i++) for (u32 j = 0; j < 4; j++) m[i][j] = i == j ? 1.0f : 0.0f; } inline m4 Transposed() const { m4 res; for (u32 i = 0; i < 4; i++) for (u32 j = 0; j < 4; j++) res[i][j] = m[j][i]; return res; } inline static m4 CreateIdentity() { return m4(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } inline static m4 CreateTranslation(const v3& translation) { return m4(1.0f, 0.0f, 0.0f, translation.x, 0.0f, 1.0f, 0.0f, translation.y, 0.0f, 0.0f, 1.0f, translation.z, 0.0f, 0.0f, 0.0f, 1.0f); } inline static m4 CreateScale(const v3& scale) { return m4(scale.x, 0.0f, 0.0f, 0.0f, 0.0f, scale.y, 0.0f, 0.0f, 0.0f, 0.0f, scale.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } inline static m4 CreateRotationX(r32 deg) { r32 rad = M_DEG_TO_RAD(deg); r32 cosAngle = cosf(deg); r32 sinAngle = sinf(deg); return m4(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, cosAngle, -sinAngle, 0.0f, 0.0f, sinAngle, cosAngle, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } inline static m4 CreateRotationY(r32 deg) { r32 rad = M_DEG_TO_RAD(deg); r32 cosAngle = cosf(deg); r32 sinAngle = sinf(deg); return m4(cosAngle, 0.0f, -sinAngle, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, sinAngle, 0.0f, cosAngle, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } inline static m4 CreateRotationZ(r32 deg) { r32 rad = M_DEG_TO_RAD(deg); r32 cosAngle = cosf(deg); r32 sinAngle = sinf(deg); return m4(cosAngle, -sinAngle, 0.0f, 0.0f, sinAngle, cosAngle, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } inline static m4 CreateRotation(const v3& deg) { return CreateRotationX(deg.x) * (CreateRotationY(deg.y) * CreateRotationZ(deg.z)); } inline static m4 CreateRotation(const v3& forward, const v3& up, const v3& right) { return m4(right.x, right.y, right.z, 0.0f, up.x, up.y, up.z, 0.0f, forward.x, forward.y, forward.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } inline static m4 CreateRotation(const v3& forward, const v3& up) { v3 right = up.Cross(forward); v3 newUp = forward.Cross(right); return CreateRotation(forward, newUp, right); } inline static m4 CreateTransformation(const v3& pos, const v3& scale, const v3& rot) { return CreateTranslation(pos) * (CreateRotation(rot) * CreateScale(scale)); } inline static m4 CreateOrthographic(r32 left, r32 right, r32 bottom, r32 top, r32 n, r32 f) { return m4(2.0f / (right - left), 0.0f, 0.0f, -(right + left) / (right - left), 0.0f, 2.0f / (top - bottom), 0.0f, -(top + bottom) / (top - bottom), 0.0f, 0.0f, -2.0f / (f - n), -(f + n) / (f - n), 0.0f, 0.0f, 0.0f, 1.0f); } inline static m4 CreatePerspective(r32 width, r32 height, r32 fov, r32 znear, r32 zfar) { r32 ar = width / height; r32 tanHalfFov = tanf(M_DEG_TO_RAD(fov) / 2.0f); r32 zrange = znear - zfar; return m4(1.0f / (ar * tanHalfFov), 0.0f, 0.0f, 0.0f, 0.0f, -1.0f / tanHalfFov, 0.0f, 0.0f, 0.0f, 0.0f, (-znear - zfar) / zrange, 2 * zfar * znear / zrange, 0.0f, 0.0f, 1.0f, 0.0f); } }; struct quat { inline quat(r32 x, r32 y, r32 z, r32 w) : x(x), y(y), z(z), w(w) {} inline quat() : x(0.0f), y(0.0f), z(0.0f), w(1.0f) {} inline quat(const v3& axis, r32 deg) { r32 halfAngle = M_DEG_TO_RAD(deg) / 2.0f; r32 sinHalfAngle = sinf(halfAngle); r32 cosHalfAngle = cosf(halfAngle); x = axis.x * sinHalfAngle; y = axis.y * sinHalfAngle; z = axis.z * sinHalfAngle; w = cosHalfAngle; } inline quat(const m4& rotation) { w = sqrtf(1.0f + rotation[0][0] + rotation[1][1] + rotation[2][2]) / 2.0f; r32 w4 = w * 4.0f; x = (rotation[2][1] - rotation[1][2]) / w4; y = (rotation[0][2] - rotation[2][0]) / w4; z = (rotation[1][0] - rotation[0][1]) / w4; } inline quat Conjugate() const { return quat(-x, -y, -z, w); } inline r32 Dot(const quat& q) const { return x * q.x + y * q.y + z * q.z + w * q.w; } inline r32 Length() const { return sqrtf(Dot(*this)); } inline quat Normalized() const { r32 len = Length(); return quat(x / len, y / len, z / len, w / len); } inline quat Lerp(const quat& q, r32 t) const { return *this * t + q * (1.0f - t); } inline quat Slerp(const quat& q, r32 t) const { quat q3; r32 dot = Dot(q); if (dot < 0.0f) { dot = -dot; q3 = q * -1.0f; } else { q3 = q; } if (dot < 0.95f) { r32 angle = acosf(dot); return (*this * sinf(angle + (1.0f - t)) + q3 * sinf(angle * t)) * (1.0f / sinf(angle)); } else { return Lerp(q3, t); } } inline m4 CreateRotationMatrix() const { v3 forward(2.0f * (x * z - w * y), 2.0f * (y * z + w * x), 1.0f - 2.0f * (x * x + y * y)); v3 up(2.0f * (x * y + w * z), 1.0f - 2.0f * (x * x + z * z), 2.0f * (y * z - w * x)); v3 right(1.0f - 2.0f * (y * y + z * z), 2.0f * (x * y - w * z), 2.0f * (x * z + w * y)); return m4::CreateRotation(forward, up, right); } inline v3 GetForward() const { return v3(0, 0, 1).Rotate(*this); } inline v3 GetBack() const { return v3(0, 0, -1).Rotate(*this); } inline v3 GetUp() const { return v3(0, 1, 0).Rotate(*this); } inline v3 GetDown() const { return v3(0, -1, 0).Rotate(*this); } inline v3 GetRight() const { return v3(1, 0, 0).Rotate(*this); } inline v3 GetLeft() const { return v3(-1, 0, 0).Rotate(*this); } inline quat operator+(const quat& q) const { return quat(x + q.x, y + q.y, z + q.z, w + q.w); } inline quat operator*(r32 scaler) const { return quat(x * scaler, y * scaler, z * scaler, w * scaler); } inline quat operator*(const quat& q) const { return quat(x * q.w + w * q.x + y * q.z - z * q.y, y * q.w + w * q.y + z * q.x - x * q.z, z * q.w + w * q.z + x * q.y - y * q.x, w * q.w - x * q.x - y * q.y - z * q.z); } inline quat operator*(const v3& vec) const { return quat(w * vec.x + y * vec.z - z * vec.y, w * vec.y + z * vec.x - x * vec.z, w * vec.z + x * vec.y - y * vec.x, -x * vec.x - y * vec.y - z * vec.z); } r32 x; r32 y; r32 z; r32 w; };
C
#include<stdio.h> #include<stdlib.h> #define LOAD_FACTOR 20 struct ListNode { int key; int data; struct ListNode *next; }; struct HashTableNode { int bcount; struct ListNode *next; }; struct HashTable { int tsize; int count; struct HashTableNode **Table; }; struct HashTable* CreateHashTable(int size) { struct HashTable *h; h = (struct HashTable*)malloc(sizeof(struct HashTable)); if(!h) { return NULL; } h->tsize = size/LOAD_FACTOR; h->count = 0; h->Table = (struct HashTableNode **)malloc(sizeof(struct HashTableNode *)*h->tsize); for(int i=0;i<h->tsize;i++) { h->Table[i]->next = NULL; h->Table[i]->bcount = 0; } return h; } int HashSearch(struct HashTable *h,int data) { struct ListNode *temp; temp = h->Table[Hash(data,h->tsize)]->next; while(temp) { if(temp->data == data) { return 1; } temp = temp->next; } return 0; } int HashInsert(struct HashTable *h,int data) { int index; struct ListNode *temp,*newNode; if(HashSearch(h,data)) { return 0; } index = Hash(data,h->tsize); temp = h->Table[index]->next; newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); newNode->key = index; newNode->data = data; newNode->next = h->Table[index]->next; h->Table[index]->next = newNode; h->Table[index]->bcount++; h->count++; if(h->count/h->tsize>LOAD_FACTOR) { ReHash(h); } return 1; } int HashDelete(struct HashTable *h,int data) { int index; struct ListNode *temp,*prev; index = Hash(data,h->tsize); for(temp = h->Table[index]->next,prev = NULL;temp;prev = temp,temp = temp->next) { if(temp->data == data) { if(prev!=NULL) { prev->next = temp->next; } free(temp); h->Table[index]->bcount--; h->count--; return 1; } } return 0; } void ReHash(struct HashTable *h) { int oldsize,i,index; struct ListNode *p,*temp,*temp2; struct HashTableNode **oldTable; oldsize = h->tsize; oldTable = h->Table; h->tsize = h->tsize*2; h->Table = (struct HashTableNode **)malloc(sizeof(struct HashTableNode *)*h->tsize); for(i=0;i<oldsize;i++) { for(temp = oldTable->next;temp;temp = temp->next) { index = Hash(temp->data,h->tsize); temp2 = temp; temp = temp->next; temp2->next = h->Table[index]->next; h->Table[index]->next = temp2; } } }
C
#include <mpi.h> #include <stdio.h> int main(int argc, char *argv[]) { int rank; MPI_Comm cart; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int dims[] = {4, 3}; int periods[] = {1, 0}; MPI_Cart_create(MPI_COMM_WORLD, 2, dims, periods, 1, &cart); int coords[2]; for (int i = 0; i < 12; i++) { if (i == rank) { int computed; int dest; MPI_Cart_coords(cart, rank, 2, coords); printf("I am process no. %d and my coordinates are (%d, %d)\n", i, coords[0], coords[1]); MPI_Cart_rank(cart, coords, &computed); printf("Dually, my computed rank is %d\n", computed); MPI_Cart_shift(cart, 1, -1, coords, &dest); if (dest == MPI_PROC_NULL) { printf("I have no neighbor :(\n"); } else { printf("My upmost neighbor is (%d)\n", dest); } } MPI_Barrier(MPI_COMM_WORLD); } MPI_Finalize(); return 0; }
C
#pragma once #define MAX_BUFF_SIZE 4096 typedef struct buffer_s { unsigned char* bytes; size_t size; unsigned int r_point; unsigned int w_point; } buffer; int read_from_buffer(void* stream, void* to, size_t r_size); int write_to_buffer(void* stream, const void* from, size_t w_size); int skip_buffer_r(void* stream, int amount); int skip_buffer_w(void* stream, int amount); int init_buffer(buffer** buff, size_t size); void free_buffer(buffer* buff);
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* process_map.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cdelaby <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/06 18:13:52 by cdelaby #+# #+# */ /* Updated: 2020/02/06 18:13:53 by cdelaby ### ########.fr */ /* */ /* ************************************************************************** */ #include "cube3d.h" t_spec *set_dir(t_spec *inf, double dir_x, double dir_y) { inf->dir_x = dir_x; inf->dir_y = dir_y; return (inf); } t_spec *set_plane(t_spec *inf, double plane_x, double plane_y) { inf->plane_x = plane_x; inf->plane_y = plane_y; return (inf); } t_spec *set_player(t_spec *inf) { inf = get_letter(inf); if (inf->orien == 'N') { inf = set_dir(inf, 0, -1); inf = set_plane(inf, 0.66, 0); } if (inf->orien == 'S') { inf = set_dir(inf, 0, 1); inf = set_plane(inf, -0.66, 0); } if (inf->orien == 'E') { inf = set_dir(inf, 1, 0); inf = set_plane(inf, 0, 0.66); } if (inf->orien == 'W') { inf = set_dir(inf, -1, 0); inf = set_plane(inf, 0, -0.66); } if (valid_map(inf->map) == -1) return (free_all_spec(inf, "use an invalid map")); return (inf); }
C
uint32_t reverseBits(uint32_t n) { uint32_t counter = 0; int multi = 31; while(multi > -1) { counter += (n % 2) * (uint32_t)pow(2, multi); n = n >> 1; multi--; } return counter; }
C
#include<stdio.h> int main(void){ int i,x,y,tmp_x,x2,y2; scanf("%d %d",&x,&y); scanf("%d %d",&x2,&y2); tmp_x=x; for(i=1;tmp_x>=y-x;x=x*i) i++; printf("%d %d",i,y-x); return 0; }
C
#include <stdio.h> #define LIMIT 1000 int wordlength(int natural); int main() { long sum; int i; i = 0; sum = 0; while (++i <= LIMIT) { printf("%d\n", wordlength(i)); sum += (long) wordlength(i); if (!(i%10)) { printf("--- br ---\n"); } } printf("The sum is: %ld\n", sum); return 0; } int wordlength(int natural) { char *ones = "335443554"; char *tens = "366555766"; char *teens = "668877988"; int temp, length; temp = natural; length = 0; if ((temp % 10)) { length += ones[(temp%10)-1] - '0'; } temp /= 10; if (temp%10 > 1) { length += tens[(temp%10)-1] - '0'; } else if (temp%10 == 1) { if (natural%10) { length = teens[(natural%10)-1] - '0'; } else { length = tens[(natural%10)] - '0'; } } else { /* do nothing */ } temp /= 10; if (temp%10) { if (length) length += 3; /* and */ length += ones[(temp%10)-1]-'0'; length += 7; /* hundred */ } temp /= 10; if (temp == 1) { length = 11; } return length; }
C
#include <stdio.h> #include <stdlib.h> void print_matrix(int** A, int col, int row); //Функция для печати матрицы int main(int argc, char *argv[]) { if (argc!=3){ printf("A data-entry error. \n"); //Проверка количества данных, введеных через консоль return EXIT_FAILURE; } FILE* matrix_1 = fopen (argv[1],"r"); FILE* matrix_2 = fopen (argv[2],"r"); if ((!matrix_1)||(!matrix_2)){ //Проверка самих файлов printf("Bug with files. \n"); return EXIT_FAILURE; } int col_1,row_1,col_2,row_2; // Ввод количества строк и столбцов певрой и второй матрицы fscanf(matrix_1,"%i",&col_1); fscanf(matrix_1,"%i",&row_1); fscanf(matrix_2,"%i",&col_2); fscanf(matrix_2,"%i",&row_2); if(row_1!=col_2){ printf("Error in matrix. They are not consisent. \n"); //Проверяется возоможность умножения матриц return EXIT_FAILURE; } int** m_1=(int**)malloc(sizeof(int*)*col_1); //Выделение памяти под строки и проверка(m_1) if(!m_1){ printf("Bug with memory allocation in m_1. \n"); return EXIT_FAILURE; } for(int i=0;i<col_1;i++){ //Выделение памяти под столцы (+заполнение 0) и проверка (m_1) m_1[i]=(int*)calloc(row_1,sizeof(int)); if(!m_1[i]){ printf("Bug with memory allocation in m_1[%d]. \n",i); return EXIT_FAILURE; } } int** m_2=(int**)malloc(sizeof(int*)*col_2); //Выделение памяти под строки и проверка (m_2) if(!m_2){ printf("Bug with memory allocation in m_2. \n"); return EXIT_FAILURE; } for(int i=0;i<col_2;i++){ //Выделение памяти под столбцы (+заполнение 0) и проверка (m_2) m_2[i]=(int*)calloc(row_2,sizeof(int)); if(!m_2[i]){ printf("Bug with memory allocation in m_2[%d]. \n",i); return EXIT_FAILURE; } } int** m_res=(int**)malloc(sizeof(int*)*col_1); //Выделение памяти под строки и проверка (m_res) if(!m_res){ printf("Bug with memory allocation in m_res. \n"); return EXIT_FAILURE; } for(int i=0;i<col_1;i++){ //Выделение памяти под столбцы (+заполнение 0) и проверка (m_res) m_res[i]=(int*)calloc(row_2,sizeof(int)); if(!m_res[i]){ printf("Bug with memory allocation in m_res[%d]. \n",i); return EXIT_FAILURE; } } for (int i=0; i<col_1;i++) //Считывание значений с файла и заполнение m_1 for(int j=0;j<row_1;j++) fscanf(matrix_1,"%i",&m_1[i][j]); fclose(matrix_1); for (int i=0; i<col_2;i++) //Считывание значений с файла и заполнение m_2 for(int j=0;j<row_2;j++) fscanf(matrix_2,"%i",&m_2[i][j]); fclose(matrix_2); for (int i=0;i<col_1;i++) //Перемножение матриц (m_1,m_2) и последующая запись результата в матрицу m_res for (int j=0; j<row_2; j++){ m_res[i][j]=0; for(int k=0;k<row_1;k++) m_res[i][j]=m_res[i][j]+m_1[i][k]*m_2[k][j]; } print_matrix(m_1,col_1,row_1); //Печать всех матриц free(m_1); print_matrix(m_2,col_2,row_2); free(m_2); print_matrix(m_res,col_1,row_2); free(m_res); return 0; } void print_matrix(int** A, int col, int row){ int i, j; for (i = 0; i < col; i++){ for (j = 0; j < row; j++) printf("%5d", A[i][j]); printf("\n"); } printf("\n"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* utils2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mspinnet <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/01 16:10:39 by mspinnet #+# #+# */ /* Updated: 2021/04/10 15:54:36 by mspinnet ### ########.fr */ /* */ /* ************************************************************************** */ #include "header.h" void if_died(t_all *all) { int i; i = -1; sem_wait(all->sem->sem_died); sem_wait(all->sem->sem_print); usleep(10); printf("%lld %s died\n", current_time() - all->args->time, all->philo->name); if (all->args->num_eat != 0) while (++i < all->args->num_philo) sem_post(all->sem->sem_num); else if (all->args->num_eat == 0) sem_post(all->sem->sem_kill); } void *died_check(void *args) { t_all *all; int i; all = (t_all *)args; i = -1; while (1) { if ((current_time() - all->philo->eat > all->args->time_to_die) && all->args->flag == 0) { if_died(all); return (NULL); } } } void eat_sem(t_all *all) { long long int time; long long int time2; sem_wait(all->sem->sem_eat); print_it(all, all->philo->name, " has taken a fork\n"); sem_wait(all->sem->sem_eat); print_it(all, all->philo->name, " has taken a fork\n"); all->philo->eat = current_time(); print_it(all, all->philo->name, " is eating\n"); all->args->flag = 1; time2 = current_time() - all->args->time; time = current_time() - all->args->time; while (time < time2 + all->args->time_to_eat) { time = current_time() - all->args->time; usleep(100); } sem_post(all->sem->sem_eat); sem_post(all->sem->sem_eat); all->args->flag = 0; if (all->args->num_eat != 0) all->philo->num_eating--; if (all->philo->num_eating == 0) sem_post(all->sem->sem_num); } void *eat(t_all *all) { long long int time; long long int time2; time = 0; while (1) { usleep(100); eat_sem(all); print_it(all, all->philo->name, " is sleeping\n"); time2 = current_time() - all->args->time; while (time < time2 + all->args->time_to_sleep) { time = current_time() - all->args->time; usleep(100); } usleep(10); print_it(all, all->philo->name, " is thinking\n"); } return (NULL); } void print_it(t_all *all, char *name, char *message) { long long int time; sem_wait(all->sem->sem_print); time = current_time(); time = time - all->args->time; ft_putnbr_fd(time, 1); write(1, " ", 1); write(1, name, ft_strlen(name)); write(1, message, ft_strlen(message)); sem_post(all->sem->sem_print); }
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 */ typedef scalar_t__ uint8_t ; typedef int uint16_t ; struct usb_quirk_entry {int vid; int pid; int lo_rev; int hi_rev; } ; /* Variables and functions */ int /*<<< orphan*/ MA_OWNED ; int USB_DEV_QUIRKS_MAX ; int /*<<< orphan*/ USB_MTX_ASSERT (int /*<<< orphan*/ *,int /*<<< orphan*/ ) ; int /*<<< orphan*/ usb_quirk_mtx ; struct usb_quirk_entry* usb_quirks ; __attribute__((used)) static struct usb_quirk_entry * usb_quirk_get_entry(uint16_t vid, uint16_t pid, uint16_t lo_rev, uint16_t hi_rev, uint8_t do_alloc) { uint16_t x; USB_MTX_ASSERT(&usb_quirk_mtx, MA_OWNED); if ((vid | pid | lo_rev | hi_rev) == 0) { /* all zero - special case */ return (usb_quirks + USB_DEV_QUIRKS_MAX - 1); } /* search for an existing entry */ for (x = 0; x != USB_DEV_QUIRKS_MAX; x++) { /* see if quirk information does not match */ if ((usb_quirks[x].vid != vid) || (usb_quirks[x].pid != pid) || (usb_quirks[x].lo_rev != lo_rev) || (usb_quirks[x].hi_rev != hi_rev)) { continue; } return (usb_quirks + x); } if (do_alloc == 0) { /* no match */ return (NULL); } /* search for a free entry */ for (x = 0; x != USB_DEV_QUIRKS_MAX; x++) { /* see if quirk information does not match */ if ((usb_quirks[x].vid | usb_quirks[x].pid | usb_quirks[x].lo_rev | usb_quirks[x].hi_rev) != 0) { continue; } usb_quirks[x].vid = vid; usb_quirks[x].pid = pid; usb_quirks[x].lo_rev = lo_rev; usb_quirks[x].hi_rev = hi_rev; return (usb_quirks + x); } /* no entry found */ return (NULL); }
C
#include <stdio.h> int main() { int arr[] = {1,2,3,4,5,6,34,52,20,45,33}; //to get the sizeof arr int n = sizeof(arr)/sizeof(arr[0]); printf("Size of an array:%d",n); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa_other.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbelondr <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/08 19:19:56 by sbelondr #+# #+# */ /* Updated: 2019/04/08 10:48:33 by sbelondr ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int ft_len_unsigned(unsigned long long n) { int cnt; cnt = 0; while (n != 0) { cnt++; n /= 10; } return (cnt); } int ft_len_long(long long n) { int cnt; cnt = 0; while (n != 0) { cnt++; n /= 10; } return (cnt); } char *ft_itoa_long(long long n) { unsigned long long nbr; int size; int negatif; char *str; negatif = (n < 0) ? 1 : 0; nbr = (negatif) ? -(long long)n : (long long)n; size = ft_len_long(nbr) + negatif; if (!(str = (char*)malloc(sizeof(char) * size + 1))) return (0); str[size] = '\0'; while (size-- > 0) { str[size] = (nbr % 10) + '0'; nbr /= 10; } (negatif) ? str[0] = '-' : 0; str[ft_strlen(str)] = '\0'; return (str); } char *ft_itoa_s(short n) { int nbr; int size; int negatif; char *str; negatif = (n < 0) ? 1 : 0; nbr = (negatif) ? -(int)n : (int)n; size = ft_numlen(nbr) + negatif; if (!(str = (char*)malloc(sizeof(char) * size + 1))) return (0); str[size] = '\0'; while (size-- > 0) { str[size] = (nbr % 10) + '0'; nbr /= 10; } (negatif) ? str[0] = '-' : 0; str[ft_strlen(str)] = '\0'; return (str); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fill_objects_part2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gwaymar- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/22 03:54:45 by gwaymar- #+# #+# */ /* Updated: 2019/10/25 03:45:36 by gwaymar- ### ########.fr */ /* */ /* ************************************************************************** */ #include "rtv1.h" void fill_plane(char **split, t_plane *new_plane, int *i) { t_plane pars_pla; char **s; *i -= 1; s = ft_strsplit(split[1], ','); pars_pla.line = vec_new(ft_atof(s[0]), ft_atof(s[1]), ft_atof(s[2])); free_split_vec3_true(&s); s = ft_strsplit(split[2], ','); pars_pla.norm = vec_new(ft_atof(s[0]), ft_atof(s[1]), ft_atof(s[2])); free_split_vec3_true(&s); pars_pla.blesk = valid_blesk(ft_atof(split[3])); s = ft_strsplit(split[4], ','); pars_pla.color = vec_new(ft_atof(s[0]), ft_atof(s[1]), ft_atof(s[2])); free_split_vec3_true(&s); new_plane[*i] = plane_new(pars_pla.norm, pars_pla.line, pars_pla.blesk, pars_pla.color); return ; } void fill_cone(char **split, t_cone *new_cone, int *i) { t_cone pars_con; char **s; *i -= 1; s = ft_strsplit(split[1], ','); pars_con.center = vec_new(ft_atof(s[0]), ft_atof(s[1]), ft_atof(s[2])); free_split_vec3_true(&s); s = ft_strsplit(split[2], ','); pars_con.vector = vec_new(ft_atof(s[0]), ft_atof(s[1]), ft_atof(s[2])); free_split_vec3_true(&s); pars_con.vector = unit_vector(pars_con.vector); pars_con.ang = ft_atof(split[3]); pars_con.blesk = valid_blesk(ft_atof(split[4])); s = ft_strsplit(split[5], ','); pars_con.color = vec_new(ft_atof(s[0]), ft_atof(s[1]), ft_atof(s[2])); free_split_vec3_true(&s); new_cone[*i] = cone_new(pars_con); return ; } void fill_cylin(char **split, t_cylin *new_cylinder, int *i) { t_cylin pars_cyl; char **s; *i -= 1; s = ft_strsplit(split[1], ','); pars_cyl.center = vec_new(ft_atof(s[0]), ft_atof(s[1]), ft_atof(s[2])); free_split_vec3_true(&s); s = ft_strsplit(split[2], ','); pars_cyl.vector = vec_new(ft_atof(s[0]), ft_atof(s[1]), ft_atof(s[2])); free_split_vec3_true(&s); pars_cyl.vector = unit_vector(pars_cyl.vector); s = ft_strsplit(split[5], ','); pars_cyl.color = vec_new(ft_atof(s[0]), ft_atof(s[1]), ft_atof(s[2])); free_split_vec3_true(&s); pars_cyl.blesk = valid_blesk(ft_atof(split[4])); pars_cyl.radius = valid_radius(ft_atof(split[3])); new_cylinder[*i] = cylin_new(pars_cyl); return ; }
C
#include<stdio.h> main( ) {int a,b=0,c,d=1,e,n,i; scanf("%d",&n); for(a=n;a>=1;a--) { b=b+1; for(i=1;i<=a-1;i++) {printf(" "); } for(c=b;c>=1;c--) { printf("%d",d); d++; printf(" "); } printf("\n"); }}
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> //project includes #include <persist.h> int createDb() { int cr; cr = sqlite3_open(DB, &db); if (cr) { fprintf(stderr, "%s %s\n", CNTCREATE, sqlite3_errmsg(db)); sqlite3_close(db); return 0; } char *zErrMs = 0; if(!createBookTable(zErrMs)){ return 0; } sqlite3_close(db); return 1; } int checkDbExist() { if ((fopen(DB, "r")) != NULL) { return 1; } return 0; } int main(int argc, char **argv) { if (!checkDbExist()) { char word[3]; printf("%s\n%s", NODB, NEEDTOCREATE); fgets(word, 2, stdin); if ((toupper(word[0]) == YES) && (createDb())) { printf("%s %s\n", DB, CREATEDSUCC); printf("%s %s\n", "All tables", CREATEDSUCC); } else { exit(0); } } else { sqlite3_open(DB, &db); countTableValues(); sqlite3_close(db); //printf("%s",OPTIONS1); system("tput setaf 2"); printf("%s",OPTIONS2); system("tput setaf 1"); printf("%s",OPTIONEXIT); system("tput sgr0"); } //char *zErrMsg = 0; /* int rc; if (argc != 3) { fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]); return (1); } rc = sqlite3_open(argv[1], &db); if (rc) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return (1); } rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } sqlite3_close(db);*/ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <fcntl.h> #include <ctype.h> #include "board.h" #include "play.h" int main(int argc, char * argv[]){ srand(time(NULL)); printf("\x1b[2J"); printf("Have you played before (y/n)? "); char ans[5]; fgets(ans,sizeof(ans), stdin); struct player playerOne; char username[20]; if(!strncmp(ans,"y",1)){ printf("What is your username? "); fgets(username, 256, stdin); username[strlen(username) - 1] = '\0'; printf("%s\n", username); playerOne = findPlayer(username); }else{ printf("What would you like your username to be? "); fgets(username, 256, stdin); username[strlen(username) - 1] = '\0'; playerOne = makePlayer(username); } printPlayer(playerOne); char diff[10]; struct Minesweeper *currentgame; printf("Enter a difficulty (easy, medium, hard, or other):\n"); fgets(diff,sizeof(diff),stdin); printf("\x1b[2J"); if(!strncmp(diff, "easy", 4)){ currentgame = makeBoard(1); } else if(!strncmp(diff, "medium", 6)){ currentgame = makeBoard(2); } else if(!strncmp(diff, "hard", 4)){ currentgame = makeBoard(3); } //else if (!strncmp(diff, "other", 1)){ else{ currentgame = makeBoard(4); } placeMines(currentgame); findMineCounts(currentgame); showAns(currentgame); printf("\n"); printf("\n"); //printf("\n"); printBoard(currentgame); int x, y, i, j; int turns = 0; char choice[5]; while (1){ printf("Enter an x-coor: "); scanf("%d", &x); printf("Enter a y-coor: "); scanf("%d", &y); j = x - 1; i = currentgame->rows - y; printf("flag or uncover (f/u)? "); getchar(); fgets(choice,sizeof(choice), stdin); if(!strncmp(choice,"u",1)){ if (currentgame->board[i][j].revealed){ //bruh printf("uncover the damn thing"); uncoverCheat(currentgame, i, j); } else{ uncoverSpace(currentgame, i, j); } } else{ flagSpace(currentgame, i, j); } turns ++; printBoard(currentgame); if (checkDone(currentgame) == 1){ break; } } printf("YOU WIN!!!!!!!! YAYAYAYAYAYYAYAYAYAYAYYAYAYY\n"); showAns(currentgame); printf("Congrats! turn counter: %d turns!!\n", turns); addPlayer(playerOne); freeBoard(currentgame); return 0; }
C
#ifndef FORCES_H #define FORCES_H #include "Kernels.h" #include "Globals.h" // -------------------------------------------------------------------------- __device__ __forceinline__ void applyMassScaling(float4& predictedPosition) { predictedPosition.w = (M_E, -5 * predictedPosition.y); } // -------------------------------------------------------------------------- __device__ __forceinline__ void confineToBox(float4& position, float4& predictedPosition, float4& velocity, bool& updatePosition) { const float velocityDamping = params.enclosureVelocityDamping; const float positionDamping = params.enclosurePositionDamping; if( predictedPosition.x < params.bounds.x.min ) { velocity.x = velocityDamping * velocity.x; predictedPosition.x = params.bounds.x.min + 0.001f; updatePosition = true; } else if( predictedPosition.x > params.bounds.x.max ) { velocity.x = velocityDamping * velocity.x; predictedPosition.x = params.bounds.x.max - 0.001f; updatePosition = true; } if( predictedPosition.y < params.bounds.y.min ) { velocity.y = velocityDamping * velocity.y; predictedPosition.y = params.bounds.y.min + 0.001f; updatePosition = true; } else if( predictedPosition.y > params.bounds.y.max ) { velocity.y = velocityDamping * velocity.y; predictedPosition.y = params.bounds.y.max - 0.001f; updatePosition = true; } if( predictedPosition.z < params.bounds.z.min ) { velocity.z = velocityDamping * velocity.z; predictedPosition.z = params.bounds.z.min + 0.001f; updatePosition = true; } else if( predictedPosition.z > params.bounds.z.max ) { velocity.z = velocityDamping * velocity.z; predictedPosition.z = params.bounds.z.max - 0.001f; updatePosition = true; } if( updatePosition ) { position += positionDamping * (predictedPosition - position); } } // -------------------------------------------------------------------------- __global__ void applyForces(float4* externalForces) { const unsigned int numberOfParticles = params.numberOfParticles; const unsigned int textureWidth = params.textureWidth; const float deltaT = params.deltaT; const unsigned int idx = threadIdx.x + (((gridDim.x * blockIdx.y) + blockIdx.x) * blockDim.x); const unsigned int x = (idx % textureWidth) * sizeof(float4); const unsigned int y = idx / textureWidth; if( idx < numberOfParticles ) { const float inverseMass = 1.0f; const float gravity = params.gravity; float4 velocity; surf2Dread(&velocity, velocities4, x, y); velocity.y += inverseMass * gravity * deltaT; velocity += externalForces[idx] * deltaT; float4 position; surf2Dread(&position, positions4, x, y); float4 predictedPosition = position + velocity * deltaT; bool updatePosition = false; confineToBox(position, predictedPosition, velocity, updatePosition); surf2Dwrite(velocity, velocities4, x, y); predictedPosition.w = 1.0f; // Set mass surf2Dwrite(predictedPosition, predictedPositions4, x, y); if( updatePosition ) { surf2Dwrite(position, positions4, x, y); } } } void cudaCallApplyForces() { applyForces<<<FOR_EACH_PARTICLE>>>(d_externalForces); } // -------------------------------------------------------------------------- #endif // FORCES_H
C
#include <stdio.h> #include <stdbool.h> #include <math.h> bool validatedata(int a, int b) { if (a <= 0 || b <= 0) { printf("Do dai 1 canh khong the bang 0\n"); return false; } else { return true; } } float tinhcanhhuyen(int a, int b) { return (float) (sqrt(a * a + b * b)); } int main() { int a, b; printf("Nhap vao 2 canh goc vuong cua tam giac: \n"); scanf("%d", &a); scanf("%d", &b); bool isvalidatedata = validatedata(a, b); if (isvalidatedata) { printf("Chieu dai canh huyen cua tam giac co 2 canh goc vuong la %d va %d la : %.2f", a, b, tinhcanhhuyen(a, b)); } return 0; }
C
void selectSort(int array[], int size) { for ( int i = 0; i < size; i++ ) { int min = i; for ( int j = i + 1; j < size; j++ ) { if ( array[j] < array[min] ) { min = j; } } if ( min != i ) { int temp = array[i]; array[i] = array[min]; array[min] = temp; } } }
C
#include <stdio.h> int count=0; int ismulti(char *inp); int main() { char inp[1010]; register int res; while(scanf(" %[^\n]",inp)!=EOF) { if(inp[0]=='0' && inp[1]==0) break; count = 0; res = ismulti(inp); if(res>=0) printf("%s is a multiple of 9 and has 9-degree %d.\n",inp,res); else printf("%s is not a multiple of 9.\n"); } return 0; } int ismulti(char *inp) { register int i,sum; for(i=0,sum=0; inp[i]!=0; i++) sum+=inp[i]-'0'; ++count; if(sum<9 || sum!=(sum/9)*9) return -1; if(sum>9) { char tmp[30]; sprintf(tmp,"%d",sum); return ismulti(tmp); } return count; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <ctype.h> #include "shared.h" #include "parser_types.h" #include "parser_utils.h" static char * get_path(char * prototype_path, char * client_number); int strcicmp(char const *a, char const *b) { bool is_a_null = a == NULL; bool is_b_null = b == NULL; if ((is_a_null && !is_b_null) || (!is_a_null && is_b_null)) return 1; if (is_a_null && is_b_null) return 0; for (;; a++, b++) { int d = tolower(*a) - tolower(*b); if (d != 0 || !*a) return d; } } char * allocate_for_string(char * str) { return (char *)malloc((strlen(str) + 1) * sizeof(char)); } void get_env_vars(char **filter_medias, char **filter_message, char **pop3_filter_version, char **pop3_server, char **pop3_username, char **client_number) { *client_number = getenv("CLIENT_NUM"); *filter_medias = getenv("FILTER_MEDIAS"); *filter_message = getenv("FILTER_MSG"); *pop3_filter_version = getenv("POP3FILTER_VERSION"); *pop3_server = getenv("POP3_SERVER"); *pop3_username = getenv("POP3_USERNAME"); } void print_env_vars(char *filter_medias, char *filter_message, char *pop3_filter_version, char *pop3_server, char *pop3_username, char *client_number) { printf("\n[[PRINTING ENV VARIABLES FOR DEBUGGING PURPOSES]]\n"); if (client_number != NULL) { printf("CLIENT_NUM: %s\n", client_number); } if (filter_medias != NULL) { printf("FILTER_MEDIAS: %s\n", filter_medias); } if (filter_message != NULL) { printf("FILTER_MSG: %s\n", filter_message); } if (pop3_filter_version != NULL) { printf("POP3FILTER_VERSION: %s\n", pop3_filter_version); } if (pop3_server != NULL) { printf("POP3_SERVER: %s\n", pop3_server); } if(pop3_username != NULL) { printf("POP3_USERNAME: %s\n", pop3_username); } printf("[[END PRINT ENV VARS]]\n\n"); } static char * get_path(char * prototype_path, char * client_number) { char * new_path = malloc(strlen(prototype_path) + 1); strcpy(new_path, prototype_path); #define MAIL_CLIENT_INDEX 15 #define FIRST_N_INDEX 12 // Replaces "nnnn" for client id int num_size = strlen(client_number); for (int q = MAIL_CLIENT_INDEX; q >= FIRST_N_INDEX; q--) { if (num_size > 0) { new_path[q] = client_number[num_size - 1]; num_size--; } else { new_path[q] = '0'; } } new_path[strlen(prototype_path)] = '\0'; return new_path; } char * get_retrieved_mail_file_path(char * client_number) { return get_path("./retr_mail_nnnn", client_number); } char * get_transformed_mail_file_path(char * client_number) { return get_path("./resp_mail_nnnn", client_number); }
C
// p_3.c // cl p_3.c #include <stdio.h> int main() { int i = 10; int* pi = &i; printf("%d \n", i); *pi = 999; printf("%d \n", i); return 0; }
C
#include "headers/sdl.h" #include "headers/openal.h" #include "headers/maze.h" #include <math.h> #define MIN(a,b) (((a)<(b))?(a):(b)) #define MAX(a,b) (((a)<(b))?(b):(a)) // OpenAL global variables ALuint source; ALuint buffer; EFXEAXREVERBPROPERTIES reverb; void action(int** maze, t_position player) { // On bouge le joueur à sa nouvelle position movePlayer(maze, SIZE, player); // On rectifie l'orientation du joueur //setOrientation((int)player.d); // On va chercher la distance entre le joueur et chaque mur distances d = distancesToWall(maze, player); // On modifie le reverb en conséquence float yReverb = (float) (d.sud-d.nord)/SIZE; float xReverb = (float) (d.est-d.ouest)/SIZE; reverb.flReflectionsPan[0] = xReverb * 1.1f; reverb.flReflectionsPan[2] = yReverb * 1.1f; reverb.flLateReverbPan[0] = (float) xReverb * 1.5f; reverb.flLateReverbPan[2] = (float) yReverb * 1.5f; reverb.flDecayTime = ((float) (d.nord + d.sud + d.est + d.ouest) * 20.0f / SIZE) + 0.1f; printf("Coordonnées joueur : x:%d y:%d d:%d\n", player.x, player.y, player.d); printf("reflexionPan Sud-Nord : %lf\n", reverb.flReflectionsPan[0]); printf("reflexionPan Est-Ouest : %lf\n", reverb.flReflectionsPan[2]); printf("reflexionPan tardive axe X : %lf\n", reverb.flLateReverbPan[0]); printf("reflexionPan tardive axe Y : %lf\n\n", reverb.flLateReverbPan[2]); printf("decay time : %lf\n\n", reverb.flDecayTime); // On joue le son avec le reverb approprié playSourceWithReverb(source, reverb); } void runner(int** maze, t_position player, t_position exit) { static SDL_Event event; static const Uint8 *currentKeyStates = NULL; currentKeyStates = SDL_GetKeyboardState(NULL); while (!(currentKeyStates[SDL_SCANCODE_RETURN]) && !(player.x == exit.x && player.y == exit.y)) { SDL_WaitEvent(&event); SDL_PumpEvents(); if (currentKeyStates[SDL_SCANCODE_UP] && maze[player.x][player.y - 1]) { player.y = MAX(0, player.y - 1); player.d = NORD; action(maze, player); } else if (currentKeyStates[SDL_SCANCODE_DOWN] && maze[player.x][player.y + 1]) { player.y = MIN(SIZE - 1, player.y + 1); player.d = SUD; action(maze, player); } else if (currentKeyStates[SDL_SCANCODE_LEFT] && maze[player.x - 1][player.y]) { player.x = MAX(0, player.x - 1); player.d = OUEST; action(maze, player); } else if (currentKeyStates[SDL_SCANCODE_RIGHT] && maze[player.x + 1][player.y]) { player.x = MIN(SIZE - 1, player.x + 1); player.d = EST; action(maze, player); } } } int main() { // Initialisation labyrinthe int** maze = readMaze(); // Initialisation OpenAL initOpenAL(&buffer, &source, &reverb); // Initialisation SDL initSDL(SIZE); initGrid(maze, SIZE); // Initialisation position joueur t_position player; player.x = 0; player.y = 0; // Initialisation position sortie t_position exit; exit.x = 13; exit.y = 14; movePlayer(maze, SIZE, player); runner(maze, player, exit); closeOpenAL(&source, &buffer); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include "cliente.h" #include "funciones.h" static int proximoId(); static int buscarLugarLibre(Cliente* clientes,int limiteC); /** \brief Inicia cliente array * \param clientes Cliente* array clientes * \param limiteC cantidad de elementos de array cliente * \return Si devuelve 0 para ok, retorna -1 si hay error * */ int cliente_init(Cliente* clientes,int limiteC) { int retorno = -1; int i; if(limiteC > 0 && clientes != NULL) { retorno = 0; for(i=0; i<limiteC; i++) { clientes[i].isEmpty=1; } } return retorno; } /** \brief muestra todos los clientes activos * \param clientes Cliente* array clientes * \param limiteC cantidad de elementos de array cliente * \return Si devuelve 0 para ok, retorna -1 si hay error * */ int cliente_mostrar(Cliente* clientes,int limiteC) { int retorno = -1; int i; // float promedio; if(limiteC > 0 && clientes != NULL) { retorno = 0; printf("---------LISTADO DE CLIENTES--------- \n"); printf("-IDc\t-NOMBRE\t\t-APELLIDO\t-CUIT\n"); for(i=0; i<limiteC; i++) { if(!clientes[i].isEmpty) { printf("%d\t%-12.12s\t%-12.12s\t%s\n",clientes[i].idCliente, clientes[i].nombre,clientes[i].apellido, clientes[i].cuit); } } } return retorno; } /** \brief imorime cliente segun id * \param clientes Cliente* array clientes * \param limiteC cantidad de elementos de array cliente * \param id numero de ID cliente a consultar * \return Si devuelve 0 para ok, retorna -1 si hay error * */ int cliente_mostrarClientePorId(Cliente* clientes,int limiteC,int id) { int retorno = -1; if(limiteC > 0 && clientes != NULL) { retorno = 0; printf("-IDc:%d\t-NOMBRE: %s\t-APELLIDO: %s\t-CUIT: %s\n",clientes[id].idCliente, clientes[id].nombre,clientes[id].apellido,clientes[id].cuit); } return retorno; } /** \brief alta de cliente ingresaado por usuario * \param clientes Cliente* array clientes * \param limiteC cantidad de elementos de array cliente * \return Si devuelve 0 para ok, retorna -1 si hay error * */ int cliente_alta(Cliente* clientes,int limiteC) { int retorno = -1; int i; char nombre[50]; char apellido[50]; char cuit[20]; if(limiteC > 0 && clientes != NULL) { i = buscarLugarLibre(clientes,limiteC); if(i >= 0) { if(!getValidString("\nNombre? ","\nEso no es un nombre","El maximo es 50",nombre,50,2)) { if(!getValidString("\nApellido? ","\nEso no es un Apellido","El maximo es 50",apellido,50,2)) { if(!getValidCuit("\nCuit sin guiones? ","\nEso no es un Cuit","El maximo es 11 digitos",cuit,12,2)) { retorno = 0; strcpy(clientes[i].nombre,nombre); strcpy(clientes[i].apellido,apellido); strcpy(clientes[i].cuit,cuit); //clientes[i].cantidadPublicaciones = 0; //------------------------------ //------------------------------ clientes[i].idCliente = proximoId(); clientes[i].isEmpty = 0; } } } } else { retorno = -3; } } else { retorno = -2; } printf("\n"); return retorno; } /** \brief da de baja a un usuario por id * \param clientes Cliente* array clientes * \param limiteC cantidad de elementos de array cliente * \param id numero de ID cliente a bajar * \return Si devuelve 0 para ok, retorna -1 si hay error * */ int cliente_baja(Cliente* clientes,int limiteC, int id) { int retorno = 0; int indiceAEliminar = cliente_buscarPorId(clientes, limiteC, id); if(indiceAEliminar>=0) { printf("\nindice a eliminar: %d\n",indiceAEliminar); clientes[indiceAEliminar].isEmpty = 1; } else { retorno=indiceAEliminar; } return retorno; } /** \brief modificacion cliente por id * \param clientes Cliente* array clientes * \param limiteC cantidad de elementos de array cliente * \param id numero de ID cliente a modificar * \return Si devuelve 0 para ok, retorna -1 si hay error * */ int cliente_modificacion(Cliente* clientes,int limiteC, int id) { int retorno = -1; int indiceAModificar; char nombre[50]; char apellido[50]; char cuit[20]; indiceAModificar = cliente_buscarPorId(clientes, limiteC, id); if(indiceAModificar>=0) { if(!getValidString("\nNuevo Nombre? ","\nEso no es un nombre","El maximo es 50",nombre,50,2)) { strcpy(clientes[indiceAModificar].nombre,nombre); if(!getValidString("\nNuevo Apellido? ","\nEso no es un Apellido","El maximo es 50",apellido,50,2)) { strcpy(clientes[indiceAModificar].apellido,apellido); if(!getValidCuit("Nuevo Cuit sin guiones? ","\nEso no es un Cuit\n","El maximo es 11 digitos",cuit,12,2)) { retorno=0; strcpy(clientes[indiceAModificar].cuit, cuit); } else { retorno=-3; } } } else { retorno = -2; } } return retorno; } /** \brief ordenar array cliente por nombre ascendente * \param clientes Cliente* array clientes * \param limiteC cantidad de elementos de array cliente * \param orden 0 para ascendente 1 para descendente * \return Si devuelve 0 para ok, retorna -1 si hay error * */ int cliente_ordenar(Cliente* clientes,int limiteC, int orden) { int retorno = -1; int i; int flagSwap; Cliente auxiliarEstructura; if(limiteC > 0 && clientes != NULL) { do { flagSwap = 0; for(i=0; i<limiteC-1; i++) { if(!clientes[i].isEmpty && !clientes[i+1].isEmpty) { if((strcmp(clientes[i].nombre,clientes[i+1].nombre) > 0 && orden) || (strcmp(clientes[i].nombre,clientes[i+1].nombre) < 0 && !orden)) //****** { auxiliarEstructura = clientes[i]; clientes[i] = clientes[i+1]; clientes[i+1] = auxiliarEstructura; flagSwap = 1; } } } } while(flagSwap); } return retorno; } /** \brief Busca un lugar libre en array clientes * \param clientes Cliente* array clientes * \param limiteC cantidad de elementos de array cliente * \return Si devuelve 0 para ok, retorna -1 si hay error * */ static int buscarLugarLibre(Cliente* clientes,int limiteC) { int retorno = -1; int i; if(limiteC > 0 && clientes != NULL) { for(i=0; i<limiteC; i++) { if(clientes[i].isEmpty==1) { retorno = i; break; } } } return retorno; } /** \brief crea un proximo id clientes * \return Devuelve el numero de proximo id clientes * */ static int proximoId() { static int proximoId = -1; proximoId++; return proximoId; } /** \brief Busca por cleintes Activas por id de cleintes * \param clientes Cliente* array clientes * \param limite cantidad de elementos del array clientes * \param limiteC cantidad de elementos de array cliente * \return Si devuelve 0 para ok, retorna -1 si hay error * */ int cliente_buscarPorId(Cliente* clientes,int limiteC, int id) { int retorno = -1; int i; if(limiteC > 0 && clientes != NULL) { retorno = -2; for(i=0; i<limiteC; i++) { if(!clientes[i].isEmpty && clientes[i].idCliente==id) { retorno=i; break; } } } return retorno; } /** \brief Da de alta clientes hardcode * \param clientes Cliente* array clientes * \param limiteC cantidad de elementos del array cl * \param nombre del cliente * \param apellido del cliente * \param cuit del cliente * \return Si devuelve 0 para ok, retorna -1 si hay error * */ int cliente_altaForzada(Cliente* clientes,int limiteC,char* nombre,char* apellido,char* cuit) { int retorno = -1; int i; if(limiteC > 0 && clientes != NULL) { i = buscarLugarLibre(clientes,limiteC); if(i >= 0) { retorno = 0; strcpy(clientes[i].nombre,nombre); strcpy(clientes[i].apellido,apellido); strcpy(clientes[i].cuit,cuit); //clientes[i].cantidadPublicaciones = 0; //------------------------------ //------------------------------ clientes[i].idCliente = proximoId(); clientes[i].isEmpty = 0; } retorno = 0; } return retorno; }
C
#include "CmacAes.h" #include "CmacAesOps.h" #include <string.h> int CmacAes_Calculate(CMAC_AES_CALCULATE_PARAMS *params, uint8_t aes_cmac[16], size_t aes_cmac_len) { unsigned char K1[16] = {0}; unsigned char K2[16] = {0}; size_t n_blocks; bool is_complete_block; int ret; uint8_t iv[16] = {0}; // CMAC uses an IV of zeros. AES128_HANDLE aes_handle = {0}; AES128_CREATE_PARAMS create_params = { .key = params->key, .key_len = params->key_len, .iv = iv, .iv_len = sizeof(iv), }; Aes128_Initialize(); Aes128_Create(&create_params, &aes_handle); // Step 1 ret = CmacAesOps_GenerateSubkeys( aes_handle, K1, sizeof(K1), K2, sizeof(K2) ); // Step 2 n_blocks = CmacAesOps_GetNBlocks(params->message_len); // Step 3 is_complete_block = CmacAesOps_GetIsCompleteBlock(params->message_len); // Step 4 // Given a message of n blocks, get the nth block. // For now we have a zero-length message, so it will be all padding. unsigned char M_n[16] = {0}; unsigned char M_last[16] = {0}; ret = CmacAesOps_GetNthBlock(params->message, params->message_len, M_n); if (is_complete_block) { ret = CmacAesOps_SetLastBlockForComplete(M_n, K1, M_last); } else { ret = CmacAesOps_SetLastBlockForIncomplete(M_n, K2, M_last); } // Step 5 unsigned char X[16] = {0}; // Step 6 unsigned char Y[16] = {0}; ret = CmacAesOps_ApplyCbcMac(params->key, params->message, n_blocks, X, Y); ret = CmacAesOps_FinishCbcMac1(M_last, X, Y); unsigned char T[16] = {0}; ret = CmacAesOps_FinishCbcMac2(aes_handle, Y, T, sizeof(T)); Aes128_Destroy(&aes_handle); // Step 7 memcpy(aes_cmac, T, 16); return 0; }
C
/* * network.c * * TM4C network driver * For use by the Serial Token Ring protocol * * Written by Tianshu Huang, April 2018 */ #include "network.h" #include "uart.h" #include "c_client.h" #include "../tm4c123gh6pm.h" #include "fifo.h" #include "../display/ST7735.h" #include "../controller/controller.h" // Game ID ifndef for testing #ifndef GAME_ID #define GAME_ID 0x42 #endif // Peer tracking uint8_t peers[16]; uint8_t numPeers; // ----------getAddress---------- // Initialize the network // Read the network address from PC6, PC7, PD6, PD7 // Returns: // uint8_t: address |0000|PC6|PC7|PD6|PD7| uint8_t getAddress(void) { // Enable ports C and D SYSCTL_RCGCGPIO_R |= 0x0C; __asm{NOP}; __asm{NOP}; // PC6, PC7, PD6, PD7 digital in GPIO_PORTC_AMSEL_R &= ~0xC0; GPIO_PORTD_AMSEL_R &= ~0xC0; GPIO_PORTC_PUR_R &= 0xC0; GPIO_PORTD_PUR_R &= 0xC0; GPIO_PORTC_DIR_R &= ~0xC0; GPIO_PORTD_DIR_R &= ~0xC0; GPIO_PORTC_AFSEL_R &= ~0xC0; GPIO_PORTD_AFSEL_R &= ~0xC0; GPIO_PORTC_DEN_R |= 0xC0; GPIO_PORTC_DEN_R |= 0xC0; // Read address return( (GPIO_PORTC_DATA_R & 0xC0) >> 4 | (GPIO_PORTD_DATA_R & 0xC0) >> 6); } // ----------networkInit---------- // Initialize the network // Gets the network address from PC6, PC7, PD6, PD7 void networkInit(void) { ipConfig(getAddress(), &uartWrite); numPeers = 0; } // ----------outHex---------- // Helper function to print out a one byte hex value // Parameters: // uint8_t data: hex value const char hexString[16] = "0123456789ABCEDF"; void outHex(uint8_t data) { ST7735_OutChar(hexString[(data & 0xF0) >> 4]); ST7735_OutChar(hexString[data & 0x0F]); } // ----------discoverPeers---------- // Run peer discovery void discoverPeers(void) { // Clear screen ST7735_FillScreen(0); ST7735_SetTextColor(0x0000); ST7735_SetCursor(0,0); // Show IP address ST7735_OutString("Your IP:"); ST7735_SetCursor(1,8); outHex(getAddress()); // Show start message ST7735_SetCursor(0,0); ST7735_OutString("Press red to start"); // Show lobby ST7735_SetCursor(2,0); ST7735_OutString("Current Lobby"); for(int i = 0; controllerRead() & 0x1000; i++) { // Clear previous members for(uint8_t i = 0; i < 16; i++) { ST7735_SetCursor(i + 4, 0); ST7735_OutString(" "); } // Draw members for(uint8_t i = 0; i < numPeers; i++) { ST7735_SetCursor(i+2, 0); outHex(peers[i]); } // Send broadcast once every 255 loops if(i == 0) { uint8_t message[1]; message[0] = GAME_ID; sendMessage(0x00, message, 1); } } }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #define PORT 8880 //端口号 #define BUFFER_SIZE 1024 //缓冲区大小 #define LISTEN_Q 20 //监听的队列数 int main(int argc, char *argv[]) { struct sockaddr_in server_addr,client_addr; //服务器和客户机的地址结构 int listenfd,connfd; //设置两个套接字,服务器的监听套接字和为客户机分配接收套接字 socklen_t client_addr_len=sizeof(struct sockaddr); //客户端地址长度,后面使用 char buf[BUFFER_SIZE+1]; //声明缓冲区数组 int n; //用于存储接收的字节数 //设置监听套接字 listenfd = socket(AF_INET, SOCK_STREAM, 0);//IPV4(AF_INET),TCP(SOCK_STREAM) if (listenfd == -1) { //创建套接字失败 perror("****Create TCP socket"); exit(1); } //服务器地址结构清零及赋值 bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr("0.0.0.0"); server_addr.sin_port = htons(PORT); //绑定套接字与IP、端口号 if (bind(listenfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) { perror("Bind the IP and PORT"); exit(1); } //监听客户机请求 listen(listenfd, LISTEN_Q); //设置接收请求套接字 connfd = accept(listenfd, (struct sockaddr*)&client_addr, &client_addr_len); if (connfd < 0) { //创建失败 perror("Accept the connection"); exit(1); } //循环接收客户端消息和发送键盘输入消息 while (1) { memset(buf, 0, BUFFER_SIZE+1); //buf指向内存空间全部初始化为指定值 n = recv(connfd, buf, BUFFER_SIZE, 0); //接受客户端发来的消息,返回值为消息字节数 if (n == -1) { perror("Receive "); exit(1); } if (strcmp(buf, "exit\n") == 0) { //如果客户机要求关闭,退出循环 break; } else { buf[n] = '\0'; //字符串尾设置为空字符 printf("Client says : %s\n",buf); //打印客户机消息 printf("You would say :"); //接收服务器的键盘输入 fgets(buf, sizeof(buf), stdin); n = send(connfd, buf, strlen(buf), 0); //将服务器的键盘输入发送到客户端 if (n == -1) { //发送失败 perror("Reply sent"); exit(1); } } } if (close(listenfd) == -1) { //关闭监听套接字 perror("Close"); exit(1); } puts("TCP Server has been closed"); return 0; }
C
// Khoa Tran // CSE 374 HW 5 // 05/11/2020 // Purpose of main.c: // From words in a dictionary, match each word into // a numbered key sequence with letters representing // numbers from 2-9 and storing this data in a trie // data structure in order to preserve memory and // maintain common prefixes. Also, ask the user for // number sequence inputs, search through the trie, // and print out the associated word with the potential // of printing all the words #include "makeTrie.h" // Takes in one file as an argument. Use file as // a dictionary, building and inserting each word // into the trie. Prompting the user for a number // sequence to print the associated word // until exit is entered. int main(int argc, char * argv[]) { if (argc == 1) { fprintf(stderr, "File argument missing."); return EXIT_FAILURE; } FILE *f = fopen(argv[1], "r"); if (!f) { fprintf(stderr, "File doesn't exit."); return EXIT_FAILURE; } Node *overallRoot = buildTrie(f); fclose(f); void * temp = (char *) malloc(MAXIMUM_WORD_LENGTH); if (!temp) { fprintf(stderr, "Failed to allocate memory. Closing program."); return EXIT_FAILURE; } char *wordInput = temp; Node *nodeWord = NULL; printf("Enter \"exit\" to quit.\n"); printf("Enter Key Sequence (or \"#\" for next word):\n"); while (fgets(wordInput, MAXIMUM_WORD_LENGTH, stdin) && strncmp("exit\n", wordInput, strlen(wordInput))) { if (isdigit(wordInput[0])) { nodeWord = searchDict(wordInput, overallRoot); } char * poundCheck = strstr(wordInput, "#"); while (nodeWord && poundCheck && *poundCheck == '#') { nodeWord = nodeWord->next; poundCheck++; } if (!nodeWord) { printf("Number sequence doesn't have a " "word assocaited or any left\n"); } if (nodeWord && nodeWord->word) { printf("'%s'\n", nodeWord->word); } else { printf("There are no more T9onyms for this particular number\n"); } printf("Enter Key Sequence (or \"#\" for next word):\n"); } totalFree(overallRoot); free(wordInput); return 0; }
C
#ifndef ORDERED_WINDOW_SEQUENTIAL_DEPENDENCE_H_GUARD #define ORDERED_WINDOW_SEQUENTIAL_DEPENDENCE_H_GUARD #include <stdlib.h> #include "scorer/ScoringFunction.h" int* countOD(int** positions, int qlength, int gap) { int* tf = (int*) calloc(qlength - 1, sizeof(int)); int i, j, k; for(i = 0; i < qlength - 1; i++) { int* p = &positions[i][1]; int* pn = &positions[i + 1][1]; for(j = 0; j < positions[i][0]; j++) { for(k = 0; k < positions[i + 1][0]; k++) { if(pn[k] > p[j] && (pn[k] - p[j] - 1) <= gap) { tf[i]++; break; } } } } return tf; } float computeOrderedWindowSDFeature(int** positions, int* query, int qlength, int docid, Pointers* pointers, ScoringFunction* scorer) { if(qlength == 1) { return 0; } int* tf = countOD(positions, qlength, scorer->phrase); float score = 0; int i; for(i = 0; i < qlength - 1; i++) { score += computePhraseScoringFunction(scorer, docid, tf[i], pointers); } free(tf); return score; } #endif
C
#pragma once #include "Matrix3.h" struct Matrix4 { public: float _11, _12, _13, _14; float _21, _22, _23, _24; float _31, _32, _33, _34; float _41, _42, _43, _44; public: Matrix4() : _11(0), _12(0), _13(0), _14(0), _21(0), _22(0), _23(0), _24(0), _31(0), _32(0), _33(0), _34(0), _41(0), _42(0), _43(0), _44(0) {}; Matrix4(int a) : _11(11), _12(12), _13(13), _14(14), _21(21), _22(22), _23(23), _24(24), _31(31), _32(32), _33(33), _34(34), _41(41), _42(42), _43(43), _44(44) {}; Matrix4(float _Line1x , float _Line1y, float _Line1z, float _Line1w, float _Line2x, float _Line2y, float _Line2z, float _Line2w, float _Line3x, float _Line3y, float _Line3z, float _Line3w, float _Line4x, float _Line4y, float _Line4z, float _Line4w) { _11 = _Line1x; _12 = _Line1y; _13 = _Line1z; _14 = _Line1w; _21 = _Line2x; _22 = _Line2y; _23 = _Line2z; _24 = _Line2w; _31 = _Line3x; _32 = _Line3y; _33 = _Line3z; _34 = _Line3w; _41 = _Line4x; _42 = _Line4y; _43 = _Line4z; _44 = _Line4w; } Matrix4(const Matrix4 * m) { _11 = m->_11; _12 = m->_12; _13 = m->_13; _14 = m->_14; _21 = m->_21; _22 = m->_22; _23 = m->_23; _24 = m->_24; _31 = m->_31; _32 = m->_32; _33 = m->_33; _34 = m->_34; _41 = m->_41; _42 = m->_42; _43 = m->_43; _44 = m->_44; } ~Matrix4() {}; Matrix4 operator * (CONST Matrix4 m) { Matrix4 result; result._11 = (_11 * m._11) + (_12 * m._21) + (_13 * m._31) + (_14 * m._41); result._12 = (_11 * m._12) + (_12 * m._22) + (_13 * m._32) + (_14 * m._42); result._13 = (_11 * m._13) + (_12 * m._23) + (_13 * m._33) + (_14 * m._43); result._14 = (_11 * m._14) + (_12 * m._24) + (_13 * m._34) + (_14 * m._44); result._21 = (_21 * m._11) + (_22 * m._21) + (_23 * m._31) + (_24 * m._41); result._22 = (_21 * m._12) + (_22 * m._22) + (_23 * m._32) + (_24 * m._42); result._23 = (_21 * m._13) + (_22 * m._23) + (_23 * m._33) + (_24 * m._43); result._24 = (_21 * m._14) + (_22 * m._24) + (_23 * m._34) + (_24 * m._44); result._31 = (_31 * m._11) + (_32 * m._21) + (_33 * m._31) + (_34 * m._41); result._32 = (_31 * m._12) + (_32 * m._22) + (_33 * m._32) + (_34 * m._42); result._33 = (_31 * m._13) + (_32 * m._23) + (_33 * m._33) + (_34 * m._43); result._34 = (_31 * m._14) + (_32 * m._24) + (_33 * m._34) + (_34 * m._44); result._41 = (_41 * m._11) + (_42 * m._21) + (_43 * m._31) + (_44 * m._41); result._42 = (_41 * m._12) + (_42 * m._22) + (_43 * m._32) + (_44 * m._42); result._43 = (_41 * m._13) + (_42 * m._23) + (_43 * m._33) + (_44 * m._43); result._44 = (_41 * m._14) + (_42 * m._24) + (_43 * m._34) + (_44 * m._44); return result; } operator Matrix4* () { Matrix4* result = new Matrix4(this); result->_11 = _11; result->_12 = _12; result->_13 = _13; result->_14 = _14; result->_21 = _21; result->_22 = _22; result->_23 = _23; result->_24 = _24; result->_31 = _31; result->_32 = _32; result->_33 = _33; result->_34 = _34; result->_41 = _41; result->_42 = _42; result->_43 = _43; result->_44 = _44; return new Matrix4(this); } public: void SetIdentity() { _11 = 1.0f; _12 = 0.0f; _13 = 0.0f; _14 = 0.0f; _21 = 0.0f; _22 = 1.0f; _23 = 0.0f; _24 = 0.0f; _31 = 0.0f; _32 = 0.0f; _33 = 1.0f; _34 = 0.0f; _41 = 0.0f; _42 = 0.0f; _43 = 0.0f; _44 = 1.0f; } // // tutorial Link : http://planning.cs.uiuc.edu/node102.html // void SetRotation(float yaw, float pitch, float roll) { SetIdentity(); float sinY = sinf(yaw); float sinP = sinf(pitch); float sinR = sinf(roll); float cosY = cosf(yaw); float cosP = cosf(pitch); float cosR = cosf(roll); _11 = cosY *cosP; _12 = cosY * sinP *sinR - sinY * cosR; _13 = cosY * sinP*cosR + sinY * sinR; _14 = 0.0f; _21 = sinY * cosP; _22 = sinY * sinP * sinR + cosY * cosR; _23 = sinY * sinP * cosR - cosY * sinR; _24 = 0.0f; _31 = -sinP; _32 = cosP * sinR; _33 = cosP * cosR; _34 = 0.0f; _41 = 0.0f; _42 = 0.0f; _43 = 0.0f; _44 = 1.0f; } void SetRotationY(float Angle) { SetIdentity(); _11 = cosf(Angle); _13 = -sinf(Angle); _31 = sinf(Angle); _33 = cosf(Angle); } void SetMatrixPerspectiveFovLH(FLOAT fovY, FLOAT Aspect, FLOAT zn, FLOAT zf) { //ٹ //http://createcode.tistory.com/entry/Direct3D-%ED%88%AC%EC%98%81%EB%B3%80%ED%99%98%ED%96%89%EB%A0%AC //https://msdn.microsoft.com/ko-kr/library/windows/desktop/bb205350(v=vs.85).aspx float yScale = 1 / tanf(fovY / 2); float xScale = yScale / Aspect; _11 = xScale; _12 = 0.0f; _13 = 0.0f; _14 = 0.0f; _21 = 0.0f; _22 = yScale; _23 = 0.0f; _24 = 0.0f; _31 = 0.0f; _32 = 0.0f; _33 = zf /(zf-zn); _34 = 1.0f; _41 = 0.0f; _42 = 0.0f; _43 = -zn*zf/(zf-zn); _44 = 0.0f; } void SetMatrixOrthoLH(FLOAT w, FLOAT h, FLOAT zn, FLOAT zf) { SetIdentity(); // //https://msdn.microsoft.com/ko-kr/library/windows/desktop/bb204940(v=vs.85).aspx _11 = 2 / w; _22 = 2 / h; _33 = 1 / (zf - zn); _43 = zn / (zn - zf); } };
C
ElemType Comm_Ancestor(SqTree T, int i, int j){ if(T[i]!='#'&&T[j]!='#'){ while(i!=j){ if(i>j) i=i/2; else j=j/2; } return T[i]; } }
C
#include "symtab.h" #include<stdlib.h> #include<string.h> #include<stdio.h> extern Global_element* global; extern Function *funcs; Function * insert_Function_safe(char *name) { Function * aux; Function * new_Function = malloc(sizeof(Function)); new_Function->down = NULL; new_Function->name = strdup(name); new_Function->name_no_params = strdup(name); new_Function->next = NULL; new_Function->visited = 0; new_Function->invalid = 0; if(funcs == NULL) { funcs = new_Function; return new_Function; } for (aux = funcs; aux->down; aux = aux->down); aux->down = new_Function; return new_Function; } Function * insert_Function(char * name) { Global_element * aux = global; while(aux) { if(strcmp(name, aux->name) == 0) return NULL; aux = aux->next; } return insert_Function_safe(name); } Function_element * search_Element(Function * func, char * name) { Function_element * aux = func->next; while(aux) { if(strcmp(aux->name, name) == 0) { return aux; } aux = aux->next; } return NULL; } Global_element * search_Global(char * name, int is_func) { Global_element * aux = global; while(aux) { if(strcmp(aux->name, name) == 0) { if (aux->params == NULL) return aux; else if (is_func) return aux; } aux = aux->next; } return NULL; } Function* search_Function_by_name(char * name) { Function * aux = funcs; while(aux) { char *clean_name = calloc(strlen(aux->name), sizeof(char)); int i = 0; while (aux->name[i] != '(') { clean_name[i] = aux->name[i]; i++; } clean_name[i] = '\0'; if(strcmp(clean_name, name) == 0) { free(clean_name); return aux; } aux = aux->down; free(clean_name); } return NULL; } int check_if_param_Already_Defined(Function * to_return, char * param_id) { Function_element * aux = to_return->next; while(aux) { if(strcmp(aux->name, param_id) == 0) { return 1; } aux = aux->next; } return 0; } Function* search_Function(char * name) { Function * aux = funcs; while(aux) { if(strcmp(aux->name, name) == 0 && !aux->invalid) { return aux; } aux = aux->down; } return NULL; } Function* get_Function(char * name) { Function * aux = funcs; while(aux) { if(strcmp(aux->name, name) == 0) { return aux; } aux = aux->down; } return NULL; } void set_as_Used(Function_element * f) { f->used = 1; } Function_element * insert_Func_element(char * name, char * type, char * param, Function * func) { Function_element * aux; Function_element * new_func_el = malloc(sizeof(Function_element)); new_func_el->next = NULL; new_func_el->name = NULL; new_func_el->param = NULL; new_func_el->type = NULL; new_func_el->used = 0; if(name != NULL) new_func_el->name = strdup(name); if(type != NULL) new_func_el->type = strdup(type); if(param != NULL) new_func_el->param = strdup(param); if(func->next == NULL) { func->next = new_func_el; return new_func_el; } for (aux = func->next; aux; aux = aux->next) { if(strcmp(aux->name, name) == 0) return NULL; if(aux->next == NULL) break; } aux->next = new_func_el; return new_func_el; } Global_element * insert_Global_element(char * name, char * type, char * params) { Global_element * aux; Global_element * new_global_el = malloc(sizeof(Global_element)); new_global_el->name = strdup(name); new_global_el->type = strdup(type); new_global_el->params = NULL; new_global_el->next = NULL; if(params != NULL) new_global_el->params = strdup(params); if(global == NULL) { global = new_global_el; return new_global_el; } for(aux = global; aux; aux = aux->next) { if(strcmp(aux->name, name) == 0) return NULL; if(aux->next == NULL) break; } aux->next = new_global_el; return new_global_el; } /* int check_if_global_element_exists(char * name) { Global_element * aux; while(aux) { if(strcmp(aux->name, name) == 0) return 0; aux = aux->next; } return 0; }*/ void show_Global_table() { Global_element * aux = global; printf("===== Global Symbol Table =====\n"); while(aux) { printf("%s\t", aux->name); if(aux->params != NULL) printf("%s\t", aux->params); else printf("\t"); printf("%s\n", aux->type); aux = aux->next; } printf("\n"); } char * get_Func_Type(Function * f) { char * return_type = NULL; if(f->next->type != NULL) { return_type = strdup(f->next->type); } return return_type; } void show_Functions_table() { Function * aux = funcs; while(aux) { print_Function_table(aux); aux = aux->down; } } void print_Function_table(Function * func) { Function_element * aux = func->next; // ex function name -> factorial ( int ) // func name já terá de vir formatado correctamente printf("===== Function %s Symbol Table =====\n",func->name); while(aux) { printf("%s\t\t%s", aux->name, aux->type); if(aux->param != NULL) printf("\tparam\n"); else { printf("\n"); } aux = aux->next; } printf("\n"); } /* void clean_table() { // TODO } */
C
#include<stdio.h> #include"binary_tree.h" int main() { TreeNode *tree = CreateTree("5", NULL, NULL); char arr[100]; while (1) { scanf("%s", arr); insertNode(arr, tree); traversal_inorder(tree); puts(""); traversal_inorder(LeftTree(tree)); puts(""); traversal_inorder(RightTree(tree)); puts(""); } }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int count = 0; int avg = 0; double stdev(int seq[]); double dist(int seq[], double dev); void read(int N) { FILE *ptr; ptr = fopen("data", "r"); size_t nr; int seq[N]; int num; while(1) { nr = fread(&num, sizeof(int), 1, ptr); if (nr == 0) { break; } seq[count] = num; count++; avg += num; } avg = avg/count; double dev = stdev(seq); printf("\n"); printf("The average of the sequence is %d\n", avg); printf("The standard deviation of the sequence is %f\n", dev); printf("%f percent of the sequence is within the first std dev\n", dist(seq, dev)); fclose(ptr); } double stdev(int seq[]) { double sum = 0; double hold, root; for (int i = 0; i < count; i++) { hold = seq[count] - avg; if (hold < 0) hold = hold*-1; root = sqrt(hold); sum = root + sum; } double dev = sum/count; if (dev < 0) dev = dev*-1; return sqrt(dev); } double dist(int seq[], double dev) { int bell = 0; int hold; if (dev < 0) { dev = dev * -1; } for (int i =0; i < count; i++) { hold = avg - seq[i]; if (hold < 0) { hold = hold * -1; } if (hold <= dev) { bell++; } } return (bell/count) * 100; }
C
// C Primer Plus // Chapter 13 Exercise 6: // Programs using command-line arguments rely on the user’s memory of how to // use them correctly. Rewrite the program in Listing 13.2 so that, instead of // using command-line arguments, it prompts the user for the required // information. #include <stdio.h> #include <stdlib.h> #include <string.h> #define SLEN 81 void get(char * string, int n); int main(void) { FILE *in; FILE *out; char source[SLEN]; char dest[SLEN]; int ch; unsigned int count = 0; printf("Enter a file to reduce: "); get(source, SLEN - 5); if ((in = fopen(source, "r")) == NULL) { fprintf(stderr, "Could not open file %s.\n", source); exit(EXIT_FAILURE); } strcpy(dest, source); strcat(dest, ".red"); if ((out = fopen(dest, "w")) == NULL) { fprintf(stderr, "Could not open file %s.\n", dest); exit(EXIT_FAILURE); } while ((ch = getc(in)) != EOF) if (count++ % 3 == 0) putc(ch, out); if (fclose(in) != 0) printf("Error in closing file %s.\n", source); if (fclose(out) != 0) printf("Error in closing file %s.\n", dest); return 0; } void get(char * string, int n) { // wrapper for fgets - read from stdin and replace // first newline with null character fgets(string, n, stdin); while (*string != '\0') { if (*string == '\n') { *string = '\0'; break; } string++; } }
C
#include <stdio.h> #include <stdlib.h> #include "ships.h" const unsigned int xsize = 10; const unsigned int ysize = 10; const unsigned int shiplen = 3; /* implement these functions */ /* Task a: Place <num> ships on the game map. */ void set_ships(unsigned int num) { unsigned int x; unsigned int y; unsigned int dir; for (int i = 0; i < num; i++) { while (1) { x = rand() % 10; y = rand() % 10; dir = rand() % 2; if (place_ship(x, y, dir) == 1) { break; }; } } } /* Task b: print the game field */ void print_field(void) { for (int y = 0; y < ysize; y++) { for (int x = 0; x < xsize; x++) { if (is_visible(x, y) == 0) { printf("?"); } else { printf("%c", is_ship(x, y)); } } printf("\n"); } } /* Task c: Ask coordinates (two integers) from user, and shoot the location. * Returns -1 if user gave invalid input or coordinates, 0 if there was no ship * at the given location; and 1 if there was a ship hit at the location. */ int shoot(void) { unsigned int x, y; char space; int ret_x = scanf("%u", &x); int ret_space = scanf("%c", &space); int ret_y = scanf("%u", &y); if (ret_x == 0 || ret_y == 0 || ret_space == 0) { return -1; } if (x > xsize || y > ysize) { return -1; } checked(x, y); if (is_ship(x, y) == '+') { hit_ship(x, y); return 1; } return 0; } /* Task d: Returns 1 if game is over (all ships are sunk), or 0 if there * still are locations that have not yet been hit. <num> is the number of * ships on the game map. It is assumed to be the same as in the call to * set_ships function. */ int game_over(unsigned int num) // this could be also implement by having a global variable int hits = 0; // the var would be increased by one when is_ship in function shoot(void) is true // the game breaks when hits == num * 3 { int hits = 0; for (int i = 0; i < xsize; i++) { for (int j = 0; j < ysize; j++) { if (is_ship(i, j) == '#') { hits++; } } } if (hits == num * 3) { return 1; } return 0; }
C
/** Write a C program to input the base and sides of a triangle. Calculate the hypotenuse upto 2 decimal place. */ #include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argn, char *argv[]) { int side1, side2; float hyp; if (argn != 3) { printf("Error: Needed lengths of both sides\n"); exit(0); } side1 = atoi(argv[1]); side2 = atoi(argv[2]); hyp = sqrt(side1*side1 + side2*side2); printf("Hyp = %.2f units\n", hyp); return 0; }
C
#include <stdio.h> int main(void) { int height = 0, width = 0; FILE *fp = fopen("linux.bmp", "r"); fseek(fp, 0x12, SEEK_SET); fread(&width, 4, 1, fp); printf("Width of image is : %d\n", width); fclose(fp); }
C
#include "tags.h" #include <stdlib.h> #include <string.h> const struct object_vtable tag_vtable = { (void (*) (void *)) tag_delete, (void * (*) (const void *)) tag_copy, (int (*) (const void *, const void *)) tag_cmp }; struct tag * tag_create (const char * name, int type) { struct tag * tag = malloc(sizeof(struct tag)); object_init(&(tag->oh), &tag_vtable); tag->name = strdup(name); tag->type = type; return tag; } struct tag * tag_create_uint64 (const char * name, uint64_t uint64) { struct tag * tag = tag_create(name, TAG_UINT64); tag->uint64 = uint64; return tag; } struct tag * tag_create_string (const char * name, const char * string) { struct tag * tag = tag_create(name, TAG_STRING); tag->string = strdup(string); return tag; } struct tag * tag_create_object_ (const char * name, void * object) { struct tag * tag = tag_create(name, TAG_OBJECT); tag->object = object; return tag; } struct tag * tag_create_object (const char * name, const void * obj) { return tag_create_object_(name, OCOPY(obj)); } void tag_delete (struct tag * tag) { free(tag->name); switch (tag->type) { case TAG_UINT64 : break; case TAG_STRING : free(tag->string); break; case TAG_OBJECT : ODEL(tag->object); break; } free(tag); } struct tag * tag_copy (const struct tag * tag) { switch (tag->type) { case TAG_UINT64 : return tag_create_uint64(tag->name, tag->uint64); case TAG_STRING : return tag_create_string(tag->name, tag->string); case TAG_OBJECT : return tag_create_object(tag->name, tag->object); } return NULL; } int tag_cmp (const struct tag * lhs, const struct tag * rhs) { return strcmp(lhs->name, rhs->name); } int tag_type (const struct tag * tag) { return tag->type; } uint64_t tag_uint64 (const struct tag * tag) { return tag->uint64; } const char * tag_string (const struct tag * tag) { return tag->string; } void * tag_object (struct tag * tag) { return tag->object; } const struct object_vtable tags_vtable = { (void (*) (void *)) tags_delete, (void * (*) (const void *)) tags_copy, NULL }; struct tags * tags_create () { struct tags * tags = malloc(sizeof(struct tags)); object_init(&(tags->oh), &tags_vtable); tags->tags = tree_create(); return tags; } void tags_delete (struct tags * tags) { ODEL(tags->tags); free(tags); } struct tags * tags_copy (const struct tags * tags) { struct tags * copy = tags_create(); ODEL(copy->tags); copy->tags = OCOPY(tags->tags); return copy; } int tag_exists (const struct tags * tags, const char * name) { if (tags_tag((struct tags *) tags, name)) return 1; return 0; } struct tag * tags_tag (struct tags * tags, const char * name) { struct tag * needle = tag_create_uint64(name, 0); struct tag * tag = tree_fetch(tags->tags, needle); ODEL(needle); return tag; } int tags_set_uint64 (struct tags * tags, const char * name, uint64_t uint64) { struct tag * tag = tag_create_uint64(name, uint64); /* remove this tag if it exists */ tree_remove(tags->tags, tag); tree_insert_(tags->tags, tag); return 0; } int tags_set_string (struct tags * tags, const char * name, const char * string) { struct tag * tag = tag_create_string(name, string); /* remove this tag if it exists */ tree_remove(tags->tags, tag); tree_insert_(tags->tags, tag); return 0; } int tags_set_object_ (struct tags * tags, const char * name, void * obj) { struct tag * tag = tag_create_object_(name, obj); /* remove this tag if it exists */ tree_remove(tags->tags, tag); tree_insert_(tags->tags, tag); return 0; } int tags_set_object (struct tags * tags, const char * name, const void * obj) { return tags_set_object_(tags, name, OCOPY(obj)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* msh_handle_quote.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dhasegaw <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/12 01:56:20 by dhasegaw #+# #+# */ /* Updated: 2020/12/30 13:08:18 by dhasegaw ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** get env in quatation ** \ in env should be handled in the same way of without quote */ static ssize_t get_env_quote(t_mshinfo *mshinfo, char *save, ssize_t len, char **content) { ssize_t begin; ssize_t ret; char *key; char *val; if ((ret = msh_handle_dollars(save, len, &content, 1))) return (ret); begin = ++len; if ((ret = msh_handle_special_var(mshinfo, save, &content, len)) < 0) return (-1); if (ret) return (ret); while (ft_isalnum(save[len])) len++; if (!(key = ft_substr(save, begin, len - begin))) return (-1); val = msh_get_value_from_envlst(mshinfo, &key, 1); if (msh_store_val_content(&val, content, 1)) return (-1); return (len - (begin - 1)); } /* ** function handling "" case */ static ssize_t handle_empty_quote(ssize_t len, ssize_t begin, char **content) { char *val; val = NULL; if (!(len - begin)) { if (!(val = ft_strdup(""))) return (-1); if (msh_store_val_content(&val, content, 1)) return (-1); } return (0); } /* ** get argv in double quotation */ static ssize_t get_argv_quote(t_mshinfo *mshinfo, char *save, ssize_t len, char **content) { ssize_t begin[2]; ssize_t ret; char *val; val = NULL; begin[0] = len; while (msh_check_operator(save, len, "\"")) { ret = 0; begin[1] = len; while (msh_check_operator(save, len, "$\"")) len++; if (!(val = ft_substr(save, begin[1], len - begin[1]))) return (-1); if (msh_store_val_content(&val, content, 2)) return (-1); if (save[len] == '$' && ((ret = get_env_quote(mshinfo, save, len, &content[0])) < 0)) return (-1); len += ret; } if (handle_empty_quote(len, begin[0], content)) return (-1); return (len - begin[0]); } /* ** handle single and double quatation ** for single, store argv to arglst here ** for double call func to store argv */ ssize_t msh_handle_quote(t_mshinfo *mshinfo, char *save, ssize_t len, char **content) { ssize_t ret; ssize_t begin; char *val; val = NULL; if (!ft_strchr("\'\"", save[len])) return (0); if (save[len] == '\'') { begin = ++len; while (save[len] && save[len] != '\'') len++; if (!(val = ft_substr(save, begin, len++ - begin))) return (-1); if (msh_store_val_content(&val, content, 1)) return (-1); return (len - (begin - 1)); } ret = 0; begin = ++len; if ((ret = get_argv_quote(mshinfo, save, len, content)) < 0) return (msh_puterr(MSH_NAME, "malloc", -1)); len += ret; return (++len - (begin - 1)); }
C
#include<stdio.h> int main() { struct SB { char num[100]; char c[100]; char name[100]; double grade1,grade2,grade3,ave; }hehe[500]; int i,N,max=0,count; scanf("%d",&N); for(i=0;i<N;i++) { scanf("%s%s%s%lf%lf%lf",hehe[i].num,hehe[i].c,hehe[i].name,&hehe[i].grade1,&hehe[i].grade2,&hehe[i].grade3); } for(i=0;i<N;i++) { hehe[i].ave=(hehe[i].grade1+hehe[i].grade2+hehe[i].grade3)/3.0; } for(i=0;i<N;i++) { printf("%s %.1f\n",hehe[i].name,hehe[i].ave); } for(i=0;i<N;i++) { if(max<hehe[i].ave) { max=hehe[i].ave; count=i; } } printf("%s %s %s %.1lf %.1lf %.1lf %.1lf\n",hehe[count].num,hehe[count].c,hehe[count].name,hehe[count].grade1,hehe[count].grade2,hehe[count].grade3,hehe[count].ave); return 0; }
C
#include<stdio.h> // ./first_line filename int main(int argc, char **argv) { // 0. Check that there are correct # of args. if (argc != 2) { fprintf(stderr, "Usage: %s <filename>\n", argv[0]); return 1; } // 1. Open the file. FILE *stream = fopen(argv[1], "r"); if (stream == NULL) { perror(argv[1]); return 1; } // 2. Read the first line and print it. int ch = fgetc(stream); while (ch != '\n' || ch != EOF) { fputc(ch, stdout); ch = fgetc(stream); } // 3. Close the file. fclose(stream); return 0; }
C
#ifndef __OPENCL_VERSION__ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <float.h> #endif #include <sdirk.h> #define sdirk_uround() ( DBL_EPSILON ) /*void sdirk_setewt (__global const sdirk_t *sdirk, __global const double *y, __global double *ewt) { const int neq = sdirk->neq; for (int k = 0; k < neq; k++) { const double ewt_ = (sdirk->s_rtol * fabs(y[__getIndex(k)])) + sdirk->s_atol; ewt[k] = 1.0 / ewt_; } }*/ inline double sdirk_getewt (__global const sdirk_t *sdirk, const int k, __global const double *y) { const double ewtk = (sdirk->s_rtol * fabs(y[__getIndex(k)])) + sdirk->s_atol; return (1.0/ewtk); } inline double sdirk_wnorm (__global const sdirk_t *sdirk, __global const double *x, __global const double *y) { const int neq = sdirk->neq; double sum = 0; for (int k = 0; k < neq; k++) { const double ewtk = sdirk_getewt(sdirk, k, y); double prod = x[__getIndex(k)] * ewtk; sum += (prod*prod); } return sqrt(sum / (double)neq); } inline void sdirk_dzero (const int len, __global double x[]) { #ifdef __INTEL_COMPILER #pragma ivdep #endif for (int k = 0; k < len; ++k) x[__getIndex(k)] = 0.0; } inline void sdirk_dcopy (const int len, const __global double src[], __global double dst[]) { #ifdef __INTEL_COMPILER #pragma ivdep #endif for (int k = 0; k < len; ++k) dst[__getIndex(k)] = src[__getIndex(k)]; } /*inline void dcopy_if (const int len, const MaskType &mask, const __global double src[], __global double dst[]) { #ifdef __INTEL_COMPILER #pragma ivdep #endif for (int k = 0; k < len; ++k) dst[k] = if_then_else (mask, src[k], dst[k]); }*/ inline void sdirk_dscal (const int len, const double alpha, __global double y[]) { // Alpha is scalar type ... and can be easily checked. if (alpha == 1.0) return; else { #ifdef __INTEL_COMPILER #pragma ivdep #endif for (int k = 0; k < len; ++k) y[__getIndex(k)] = alpha * y[__getIndex(k)]; } } inline void sdirk_daxpy (const int len, const double alpha, const __global double x[], __global double y[]) { // Alpha is scalar type ... and can be easily checked. if (alpha == 1.0) { #ifdef __INTEL_COMPILER #pragma ivdep #endif for (int k = 0; k < len; ++k) y[__getIndex(k)] += x[__getIndex(k)]; } else if (alpha != 0.0) { #ifdef __INTEL_COMPILER #pragma ivdep #endif for (int k = 0; k < len; ++k) y[__getIndex(k)] += alpha * x[__getIndex(k)]; } } /*template <typename T1, typename T2> inline void sdirk_daxpy (const int& len, const T1& alpha, const T2 x[], T2 y[], vector_type) { // Alpha is SIMD type -- hard to switch on value. #ifdef __INTEL_COMPILER #pragma ivdep #endif for (int k = 0; k < len; ++k) y[k] += (alpha * x[k]); }*/ /* inline int _find_pivot (const int n, const int k, __global const double *A_k, int *piv) { // Find the row pivot *piv = k; for (int i = k+1; i < n; ++i) { if (fabs(A_k[i]) > fabs(A_k[*piv])) *piv = i; } // Test for singular value ... if (A_k[*piv] == 0.0) return (k+1); else return 0; }*/ /*template <typename ValueType, typename PivotType> inline int _find_pivot (const int &n, const int &k, ValueType *A_k, PivotType &piv, vector_type) { // Make sure the simd's are equal width! { typedef typename enable_if< (ValueType::width == PivotType::width), bool>::type cond_type; } const int width = ValueType::width; // Find the row pivot for each element ... for (int elem = 0; elem < width; ++elem) { int ipiv = k; for (int i = k+1; i < n; ++i) { if (fabs(A_k[i][elem]) > fabs(A_k[ipiv][elem])) ipiv = i; } // Test for singular value ... if (A_k[ipiv][elem] == 0.0) return(k+1); piv[elem] = ipiv; } return 0; }*/ // Pivot is a vector /*template <typename ValueType, typename PivotType> inline void swap (const int &k, const PivotType &piv, ValueType *A, vector_type) { // Make sure the simd's are equal width! { typedef typename enable_if< (ValueType::width == PivotType::width), bool>::type cond_type; } const int width = ValueType::width; // Find the row pivot for each element ... for (int elem = 0; elem < width; ++elem) { const int ipiv = piv[elem]; if (ipiv != k) std::swap(A[ipiv][elem], A[k][elem]); } } // Pivot is a scalar ... simple template <typename ValueType, typename PivotType> inline void swap (const int &k, const PivotType &piv, ValueType *A, scalar_type) { std::swap (A[piv], A[k]); } template <typename ValueType, typename PivotType> inline void swap (const int &k, const PivotType &piv, ValueType *A) { swap (k, piv, A, typename is_scalar_or_vector<PivotType>::type()); } // Pivot is a scalar ... simple inline void _swap (const int k, const int piv, __global const double *A) { const double tmp = A[piv]; A[piv] = A[k]; A[k] = tmp; }*/ int sdirk_ludec (const int n, __global double *A, __global int *ipiv) { int ierr = SDIRK_SUCCESS; /* k-th elimination step number */ for (int k = 0; k < n; ++k) { __global double *A_k = A + __getIndex(k*n); // pointer to the column /* find pivot row number */ //ipiv[k] = k; int pivk = k; for (int i = k+1; i < n; ++i) { //if (fabs(A_k[i]) > fabs(A_k[ipiv[k]])) ipiv[k] = i; if (fabs(A_k[__getIndex(i)]) > fabs(A_k[__getIndex(pivk)])) pivk = i; } ipiv[__getIndex(k)] = pivk; // Test for singular value ... //if (A_k[ipiv[k]] == 0.0) if (A_k[__getIndex(pivk)] == 0.0) { //return (k+1); ierr = (k+1); break; } //ierr = _find_pivot (n, k, A_k, ipiv[k]); //if (ierr) break; /* swap a(k,1:N) and a(piv,1:N) if necessary */ //if (any(ipiv[k] != k)) //if (ipiv[k] != k) if (pivk != k) { //swap_rows (n, k, ipiv[k], A, n); __global double *A_i = A; // pointer to the first column //for (int i = 0; i < n; ++i, A_i += n) for (int i = 0; i < n; ++i, A_i += __getIndex(n)) { //double tmp = A_i[k]; //A_i[k] = A_i[ipiv[k]]; //A_i[ipiv[k]] = tmp; const double tmp = A_i[__getIndex(k)]; A_i[__getIndex(k)] = A_i[__getIndex(pivk)]; A_i[__getIndex(pivk)] = tmp; } } /* Scale the elements below the diagonal in * column k by 1.0/a(k,k). After the above swap * a(k,k) holds the pivot element. This scaling * stores the pivot row multipliers a(i,k)/a(k,k) * in a(i,k), i=k+1, ..., M-1. */ const double mult = 1.0 / A_k[__getIndex(k)]; for (int i = k+1; i < n; ++i) A_k[__getIndex(i)] *= mult; /* row_i = row_i - [a(i,k)/a(k,k)] row_k, i=k+1, ..., m-1 */ /* row k is the pivot row after swapping with row l. */ /* The computation is done one column at a time, */ /* column j=k+1, ..., n-1. */ for (int j = k+1; j < n; ++j) { __global double *A_j = A + __getIndex(j*n); const double a_kj = A_j[__getIndex(k)]; /* a(i,j) = a(i,j) - [a(i,k)/a(k,k)]*a(k,j) */ /* a_kj = a(k,j), col_k[i] = - a(i,k)/a(k,k) */ if (a_kj != 0.0) { //if (any(a_kj != 0.0)) { for (int i = k+1; i < n; ++i) { A_j[__getIndex(i)] -= a_kj * A_k[__getIndex(i)]; } } } } return ierr; //if (ierr) //{ // fprintf(stderr,"Singular pivot j=%d\n", ierr-1); // exit(-1); //} } void sdirk_lusol (const int n, __global double *A, __global int *ipiv, __global double *b) { /* Permute b, based on pivot information in p */ // Difficult to do with SIMDvectors ... for (int k = 0; k < n; ++k) { //if (any(ipiv[k] != k)) const int pivk = ipiv[__getIndex(k)]; //if (ipiv[k] != k) if (pivk != k) { //double tmp = b[k]; //b[k] = b[ipiv[k]]; //b[ipiv[k]] = tmp; double tmp = b[__getIndex(k)]; b[__getIndex(k)] = b[__getIndex(pivk)]; b[__getIndex(pivk)] = tmp; } } /* Solve Ly = b, store solution y in b */ for (int k = 0; k < n-1; ++k) { //__global double *A_k = &A[(k*n)]; __global double *A_k = A + __getIndex(k*n); //const double bk = b[k]; const double bk = b[__getIndex(k)]; for (int i = k+1; i < n; ++i) b[__getIndex(i)] -= A_k[__getIndex(i)]*bk; //b[i] -= A_k[i]*bk; //b[i] -= A_k[i]*b[k]; } /* Solve Ux = y, store solution x in b */ for (int k = n-1; k > 0; --k) { //__global double *A_k = &A[(k*n)]; __global double *A_k = A + __getIndex(k*n); //b[k] /= A_k[k]; b[__getIndex(k)] /= A_k[__getIndex(k)]; //const double bk = b[k]; const double bk = b[__getIndex(k)]; for (int i = 0; i < k; ++i) b[__getIndex(i)] -= A_k[__getIndex(i)]*bk; //b[i] -= A_k[i]*bk; //b[i] -= A_k[i]*b[k]; } //b[0] /= A[0]; b[__getIndex(0)] /= A[__getIndex(0)]; } int sdirk_hin (__global const sdirk_t *sdirk, const double t, double *h0, __global double* y, __global double *rwk, SDIRK_Function_t func, __private void *user_data) { //value_type tround = tdist * this->uround(); //double tdist = t_stop - t; //double tround = tdist * sdirk_uround(); // Set lower and upper bounds on h0, and take geometric mean as first trial value. // Exit with this value if the bounds cross each other. //sdirk->h_min = fmax(tround * 100.0, sdirk->h_min); //sdirk->h_max = fmin(tdist, sdirk->h_max); const int neq = sdirk->neq; __global double *ydot = rwk; __global double *y1 = ydot + __getIndex(neq); __global double *ydot1 = y1 + __getIndex(neq); int need_ydot = 1; // Adjust upper bound based on ydot ... /* if (0) { need_ydot = false; // compute ydot at t=t0 func (neq, y, ydot); ++this->nfe; for (int k = 0; k < neq; k++) { value_type dely = 0.1 * fabs(y[k]) + this->atol; value_type hub0 = hub; if (hub * fabs(ydot[k]) > dely) hub = dely / fabs(ydot[k]); //printf("k=%d, hub0 = %e, hub = %e\n", k, hub0, hub); } }*/ double hlb = sdirk->h_min; double hub = sdirk->h_max; double hg = sqrt(hlb*hub); if (hub < hlb) { *h0 = hg; return SDIRK_SUCCESS; } // Start iteration to find solution to ... {WRMS norm of (h0^2 y'' / 2)} = 1 const int miters = 10; int hnew_is_ok = 0; double hnew = hg; int iter = 0; int ierr = SDIRK_SUCCESS; // compute ydot at t=t0 if (need_ydot) { //func(neq, 0.0, y, ydot, user_data); cklib_callback(neq, 0.0, y, ydot, user_data); //sdirk->nfe++; need_ydot = 0; } while(1) { // Estimate y'' with finite-difference ... //double t1 = hg; #ifdef __INTEL_COMPILER #pragma ivdep #endif for (int k = 0; k < neq; k++) y1[__getIndex(k)] = y[__getIndex(k)] + hg * ydot[__getIndex(k)]; // compute y' at t1 //func (neq, 0.0, y1, ydot1, user_data); cklib_callback (neq, 0.0, y1, ydot1, user_data); //sdirk->nfe++; // Compute WRMS norm of y'' #ifdef __INTEL_COMPILER #pragma ivdep #endif for (int k = 0; k < neq; k++) y1[__getIndex(k)] = (ydot1[__getIndex(k)] - ydot[__getIndex(k)]) / hg; double yddnrm = sdirk_wnorm (sdirk, y1, y); //std::cout << "iter " << iter << " hg " << hg << " y'' " << yddnrm << std::endl; //std::cout << "ydot " << ydot[neq-1] << std::endl; // should we accept this? if (hnew_is_ok || iter == miters) { hnew = hg; //if (iter == miters) fprintf(stderr, "ERROR_HIN_MAX_ITERS\n"); ierr = (hnew_is_ok) ? SDIRK_SUCCESS : SDIRK_HIN_MAX_ITERS; break; } // Get the new value of h ... hnew = (yddnrm*hub*hub > 2.0) ? sqrt(2.0 / yddnrm) : sqrt(hg * hub); // test the stopping conditions. double hrat = hnew / hg; // Accept this value ... the bias factor should bring it within range. if ( (hrat > 0.5) && (hrat < 2.0) ) //if ( all(hrat > 0.5) && all(hrat < 2.0) ) hnew_is_ok = 1; // If y'' is still bad after a few iterations, just accept h and give up. //if ( (iter > 1) && all(hrat > 2.0) ) { if ( (iter > 1) && (hrat > 2.0) ) { hnew = hg; hnew_is_ok = 1; } //printf("iter=%d, yddnrw=%e, hnew=%e, hlb=%e, hub=%e\n", iter, yddnrm, hnew, hlb, hub); hg = hnew; iter ++; } // bound and bias estimate *h0 = hnew * 0.5; *h0 = fmax(*h0, hlb); *h0 = fmin(*h0, hub); //printf("h0=%e, hlb=%e, hub=%e\n", h0, hlb, hub); return ierr; } int sdirk_lenrwk (__global const sdirk_t *sdirk) { int lenrwk = 0; lenrwk += sdirk->neq; // fy lenrwk += sdirk->neq; // del & yerr lenrwk += (sdirk->neq * sdirk->neq); // Jy lenrwk += (sdirk->neq * sdirk->neq); // M lenrwk += (sdirk->neq * sdirk->numStages); // z lenrwk += sdirk->neq; // g return lenrwk; } int sdirk_leniwk (__global const sdirk_t *sdirk) { int leniwk = sdirk->neq; // ipiv return leniwk; } #define __matrix_index(_i,_j,_var) (sdirk->_var[(_i)][(_j)]) #define A_(_i,_j) ( __matrix_index(_i,_j,A) ) #define Theta_(_i,_j) ( __matrix_index(_i,_j,Theta) ) #define Alpha_(_i,_j) ( __matrix_index(_i,_j,Alpha) ) // 4th/3rd-order L-stable SDIRK method with 5 stages. // -- E. Hairer and G. Wanner, "Solving ordinary differential equations II: // stiff and differential-algebraic problems," Springer series in // computational mathematics, Springer-Verlag (1990). void sdirk_S4a (__global sdirk_t *sdirk) { sdirk->solverTag = S4a; sdirk->numStages = 5; sdirk->ELO = 4; // Constant diagonal sdirk->gamma = 8.0 / 30.0; //0.2666666666666666666666666666666667; // A and C are lower-triangular matrices in column-major order!!!! // -- A(i,j) = [(i)*(i+1)/2 + j] ... A(1,0) = A[0], A(2,0) = A[1] for (int i = 0; i < sdirk_maxStages; ++i) for (int j = 0; j < sdirk_maxStages; ++j) A_(i,j) = 0.0; A_(0,0) = sdirk->gamma; A_(1,0) = 0.5; A_(1,1) = sdirk->gamma; A_(2,0) = 0.3541539528432732316227461858529820; A_(2,1) =-0.05415395284327323162274618585298197; A_(2,2) = sdirk->gamma; A_(3,0) = 0.08515494131138652076337791881433756; A_(3,1) =-0.06484332287891555171683963466229754; A_(3,2) = 0.07915325296404206392428857585141242; A_(3,3) = sdirk->gamma; A_(4,0) = 2.100115700566932777970612055999074; A_(4,1) =-0.7677800284445976813343102185062276; A_(4,2) = 2.399816361080026398094746205273880; A_(4,3) =-2.998818699869028161397714709433394; A_(4,4) = sdirk->gamma; sdirk->B[0] = 2.100115700566932777970612055999074; sdirk->B[1] =-0.7677800284445976813343102185062276; sdirk->B[2] = 2.399816361080026398094746205273880; sdirk->B[3] =-2.998818699869028161397714709433394; sdirk->B[4] = sdirk->gamma; sdirk->Bhat[0] = 2.885264204387193942183851612883390; sdirk->Bhat[1] =-0.1458793482962771337341223443218041; sdirk->Bhat[2] = 2.390008682465139866479830743628554; sdirk->Bhat[3] =-4.129393538556056674929560012190140; sdirk->Bhat[4] = 0.; sdirk->C[0] = 8.0 / 30.0; //0.2666666666666666666666666666666667; sdirk->C[1] = 23.0 / 30.0; // 0.7666666666666666666666666666666667; sdirk->C[2] = 17.0 / 30.0; // 0.5666666666666666666666666666666667; sdirk->C[3] = 0.3661315380631796996374935266701191; sdirk->C[4] = 1.; // Ynew = Yold + h*Sum_i {rkB_i*k_i} = Yold + Sum_i {rkD_i*Z_i} sdirk->D[0] = 0.; sdirk->D[1] = 0.; sdirk->D[2] = 0.; sdirk->D[3] = 0.; sdirk->D[4] = 1.; // Err = h * Sum_i {(rkB_i-rkBhat_i)*k_i} = Sum_i {rkE_i*Z_i} sdirk->E[0] =-0.6804000050475287124787034884002302; sdirk->E[1] = 1.558961944525217193393931795738823; sdirk->E[2] =-13.55893003128907927748632408763868; sdirk->E[3] = 15.48522576958521253098585004571302; sdirk->E[4] = 1.; // h*Sum_j {rkA_ij*k_j} = Sum_j {rkTheta_ij*Z_j} for (int i = 0; i < sdirk_maxStages; ++i) for (int j = 0; j < sdirk_maxStages; ++j) Theta_(i,j) = 0.0; Theta_(1,0) = 1.875; Theta_(2,0) = 1.708847304091539528432732316227462; Theta_(2,1) =-0.2030773231622746185852981969486824; Theta_(3,0) = 0.2680325578937783958847157206823118; Theta_(3,1) =-0.1828840955527181631794050728644549; Theta_(3,2) = 0.2968246986151577397160821594427966; Theta_(4,0) = 0.9096171815241460655379433581446771; Theta_(4,1) =-3.108254967778352416114774430509465; Theta_(4,2) = 12.33727431701306195581826123274001; Theta_(4,3) =-11.24557012450885560524143016037523; // Starting value for Newton iterations: Z_i^0 = Sum_j {rkAlpha_ij*Z_j} for (int i = 0; i < sdirk_maxStages; ++i) for (int j = 0; j < sdirk_maxStages; ++j) Alpha_(i,j) = 0.0; Alpha_(1,0) = 2.875000000000000000000000000000000; Alpha_(2,0) = 0.8500000000000000000000000000000000; Alpha_(2,1) = 0.4434782608695652173913043478260870; Alpha_(3,0) = 0.7352046091658870564637910527807370; Alpha_(3,1) =-0.09525565003057343527941920657462074; Alpha_(3,2) = 0.4290111305453813852259481840631738; Alpha_(4,0) =-16.10898993405067684831655675112808; Alpha_(4,1) = 6.559571569643355712998131800797873; Alpha_(4,2) =-15.90772144271326504260996815012482; Alpha_(4,3) = 25.34908987169226073668861694892683; } int sdirk_create (__global sdirk_t *sdirk, const int neq, sdirk_solverTags solver_tag)//, const int itol, const double *rtol, const double *atol) { sdirk->neq = neq; //sdirk->lenrwk = 8*neq; //sdirk->rwk = (double *) aligned_malloc(sizeof(double)* sdirk->lenrwk); sdirk->max_iters = 10000; sdirk->min_iters = 1; //sdirk->h = 0.; sdirk->h_max = 0.; sdirk->h_min = 0.; sdirk->adaption_limit = 5; // sdirk->itol = itol; //sdirk->v_rtol = NULL; //sdirk->v_atol = NULL; // assert (itol == 1); // sdirk->s_rtol = *rtol; // sdirk->s_atol = *atol; sdirk->itol = 1; sdirk->s_rtol = 1.0e-11; sdirk->s_atol = 1.0e-9; //sdirk->iter = 0; //sdirk->nst = 0; //sdirk->nfe = 0; if (solver_tag == S4a) sdirk_S4a(sdirk); else { fprintf(stderr,"Invalid solver_tag = %d, using default %d\n", solver_tag, S4a); sdirk_S4a(sdirk); return SDIRK_ERROR; } return SDIRK_SUCCESS; } int sdirk_destroy (__global sdirk_t *sdirk) { //free (sdirk->rwk); //if (sdirk->v_rtol) free(sdirk->v_rtol); //if (sdirk->v_atol) free(sdirk->v_atol); return SDIRK_SUCCESS; } int sdirk_init (__global sdirk_t *sdirk, double t0, const double t_stop) { sdirk->t_stop = t_stop; sdirk->h_min = 0.0; sdirk->h_max = 0.0; const double t_dist = sdirk->t_stop - t0; sdirk->t_round = t_dist * sdirk_uround(); if (t_dist < (sdirk->t_round * 2.0)) { //fprintf(stderr, "error: tdist < 2.0 * tround %e\n", tdist); return SDIRK_TDIST_TOO_SMALL; } if (sdirk->h_min < sdirk->t_round) sdirk->h_min = sdirk->t_round * 100.0; if (sdirk->h_max < sdirk->t_round) sdirk->h_max = t_dist / (double)sdirk->min_iters; //sdirk->NewtonThetaMin = 0.001; //sdirk->NewtonTolerance = 0.03; return SDIRK_SUCCESS; // Estimate the initial step size ... //if (sdirk->h < sdirk->h_min) // ierr = sdirk_hin (sdirk, t, t_stop, &sdirk->h, y, func, user_data); //printf("hin = %e %e\n", t_stop, sdirk->h); //return ierr; } void sdirk_fdjac (__global const sdirk_t *sdirk, const double tcur, const double hcur, __global double *y, __global double *fy, __global double *Jy, SDIRK_Function_t func, __private void *user_data) { const int neq = sdirk->neq; // Norm of fy(t) ... double fnorm = sdirk_wnorm( sdirk, fy, y ); // Safety factors ... const double sround = sqrt( sdirk_uround() ); double r0 = (1000. * sdirk_uround() * neq) * (hcur * fnorm); if (r0 == 0.) r0 = 1.; // Build each column vector ... for (int j = 0; j < neq; ++j) { const double ysav = y[__getIndex(j)]; const double ewtj = sdirk_getewt(sdirk, j, y); const double dely = fmax( sround * fabs(ysav), r0 / ewtj ); y[__getIndex(j)] += dely; __global double *jcol = &Jy[__getIndex(j*neq)]; //func (neq, tcur, y, jcol, user_data); cklib_callback (neq, tcur, y, jcol, user_data); const double delyi = 1. / dely; for (int i = 0; i < neq; ++i) jcol[__getIndex(i)] = (jcol[__getIndex(i)] - fy[__getIndex(i)]) * delyi; y[__getIndex(j)] = ysav; } } int sdirk_solve (__global const sdirk_t *sdirk, double *tcur, double *hcur, __private sdirk_counters_t *counters, __global double y[], __global int iwk[], __global double rwk[], SDIRK_Function_t func, SDIRK_Jacobian_t jac, __private void *user_data) { int ierr = SDIRK_SUCCESS; #define nst (counters->nst) #define nfe (counters->nfe) #define nje (counters->nje) #define nlu (counters->nlu) #define nni (counters->nni) #define iter (counters->niters) #define h (*hcur) #define t (*tcur) #define neq (sdirk->neq) #define InterpolateNewton (0) // Start at zero (0) or interpolate a starting guess (1) #define MaxNewtonIterations (8) // Max number of newton iterations #define NewtonThetaMin (0.005) // Minimum convergence rate for the Newton Iteration (0.001) #define NewtonThetaMax (0.999) // Maximum residual drop acceptable #define NewtonTolerance (0.03) // Convergence criteria #define Qmax (1.2) // Max h-adaption to recycle M #define Qmin (1.) // Min "" //printf("h = %e %e %e %f\n", h, sdirk->h_min, sdirk->h_max, y[__getIndex(neq-1)]); // Estimate the initial step size ... if (h < sdirk->h_min) { ierr = sdirk_hin (sdirk, t, hcur, y, rwk, func, user_data); if (ierr != SDIRK_SUCCESS) return ierr; } //printf("hin = %e %e %e %f\n", h, sdirk->h_min, sdirk->h_max, y[__getIndex(neq-1)]); // Zero the counters ... nst = 0; nfe = 0; nlu = 0; nje = 0; nni = 0; iter = 0; // Set the work arrays ... __global double *fy = rwk; __global double *del = fy + __getIndex(neq); __global double *Jy = del + __getIndex(neq); __global double *M = Jy + __getIndex(neq*neq); __global double *z = M + __getIndex(neq*neq); __global double *g = z + __getIndex(neq*sdirk->numStages); __global double *yerr = del; //__global double *ewt = &Jy[neq*neq]; int ComputeJ = 1; int ComputeM = 1; while (fabs(t - sdirk->t_stop) > sdirk->t_round) { // Set the error weight array. //sdirk_setewt (sdirk, y, ewt); // Construct the Iteration matrix ... if needed. if (ComputeM) { // Compute the Jacobian matrix or recycle an old one. if (ComputeJ) { //if (jac == NULL) { // Compute the RHS ... the fd algorithm expects it. //func (neq, t, y, fy, user_data); cklib_callback (neq, t, y, fy, user_data); nfe++; sdirk_fdjac (sdirk, t, h, y, fy, Jy, func, user_data); nfe += neq; } //else //{ // jac (neq, t, y, Jy, user_data); //} nje++; } // Compute M := 1/(gamma*h) - J const double one_hgamma = 1.0 / (h * sdirk->gamma); for (int j = 0; j < neq; ++j) { __global double *Mcol = &M[__getIndex(j*neq)]; __global double *Jcol = &Jy[__getIndex(j*neq)]; for (int i = 0; i < neq; ++i) Mcol[__getIndex(i)] = -Jcol[__getIndex(i)]; Mcol[__getIndex(j)] += one_hgamma; } // Factorization M sdirk_ludec(neq, M, iwk); nlu++; } int Accepted; double HScalingFactor; double NewtonTheta = NewtonThetaMin; for (int s = 0; s < sdirk->numStages; s++) { // Initial the RK stage vectors Z_i and G. __global double *z_s = &z[__getIndex(s*neq)]; sdirk_dzero (neq, z_s); sdirk_dzero (neq, g); if (s) { for (int j = 0; j < s; ++j) { // G = \Sum_j Theta_i,j*Z_j = h * \Sum_j A_i,j*F(Z_j) __global double *z_j = &z[__getIndex(j*neq)]; sdirk_daxpy (neq, Theta_(s,j), z_j, g); // Z_i = \Sum_j Alpha(i,j)*Z_j if (InterpolateNewton) sdirk_daxpy (neq, Alpha_(s,j), z_j, z_s); } } // Solve the non-linear problem with the Newton-Raphson method. Accepted = 0; HScalingFactor = 0.8; NewtonTheta = NewtonThetaMin; double NewtonResidual; for (int NewtonIter = 0; NewtonIter < MaxNewtonIterations && !(Accepted); NewtonIter++, nni++) { // 1) Build the RHS of the root equation: F := G + (h*gamma)*f(y+Z_s) - Z_s for (int k = 0; k < neq; ++k) del[__getIndex(k)] = y[__getIndex(k)] + z_s[__getIndex(k)]; //func (neq, t, ynew, fy, user_data); cklib_callback (neq, t, del, fy, user_data); nfe++; const double hgamma = h*sdirk->gamma; for (int k = 0; k < neq; ++k) del[__getIndex(k)] = g[__getIndex(k)] + hgamma * fy[__getIndex(k)] - z_s[__getIndex(k)]; //del[__getIndex(k)] = g[__getIndex(k)] - z_s[__getIndex(k)] + hgamma * fy[__getIndex(k)]; // 2) Solve the linear problem: M*delz = (1/hgamma)F ... so scale F first. sdirk_dscal (neq, 1.0/hgamma, del); sdirk_lusol (neq, M, iwk, del); // 3) Check the convergence and convergence rate // 3.1) Compute the norm of the correction. double dnorm = sdirk_wnorm (sdirk, del, y); // 3.2) If not the first iteration, estimate the rate. if (NewtonIter > 1) { NewtonTheta = dnorm / NewtonResidual; if (NewtonTheta < NewtonThetaMax) { double ConvergenceRate = NewtonTheta / (1.0 - NewtonTheta); Accepted = (ConvergenceRate * dnorm < NewtonTolerance); //printf("miter=%d, norm=%e, rate=%f\n", NewtonIter, dnorm, ConvergenceRate); // Predict the error after the maximum # of iterations. double PredictedError = dnorm * pow(NewtonTheta, (MaxNewtonIterations-NewtonIter)/(1.0-NewtonTheta)); if (PredictedError > NewtonTolerance) { // Error is probably too large, shrink h and try again. double QNewton = fmin(10.0, PredictedError / NewtonTolerance); HScalingFactor = 0.9 * pow( QNewton, -1.0 / (1.0 + MaxNewtonIterations - NewtonIter)); fprintf(stderr,"PredictedError > NewtonTolerance %e %f %f %d %d %d %d\n", h, HScalingFactor, PredictedError, nst, iter, s, NewtonIter); break; } } else { //fprintf(stderr,"NewtonTheta >= NewtonThetaMax %e %e %d %d %d %d\n", h, NewtonTheta, nst, iter, s, NewtonIter); break; } } // Save the residual norm for the next iteration. NewtonResidual = dnorm; // 4) Update the solution: Z_s <- Z_s + delta sdirk_daxpy (neq, 1.0, del, z_s); } if (!Accepted) { //printf("failed to converge %d %d.\n", iter, s); ComputeJ = 0; // Jacobian is still valid ComputeM = 1; // M is invalid since h will change (perhaps) drastically. break; //return 0; } } // ... stages if (Accepted) { // Compute the error estimation of the trial solution. sdirk_dzero (neq, yerr); for (int j = 0; j < sdirk->numStages; ++j) { __global double *z_j = &z[__getIndex(j*neq)]; if (sdirk->E[j] != 0.0) sdirk_daxpy (neq, sdirk->E[j], z_j, yerr); } //const double hgamma = h*sdirk->gamma; //sdirk_dscal (neq, 1.0/hgamma, yerr); //sdirk_lusol (neq, M, iwk, yerr); double herr = fmax(1.0e-20, sdirk_wnorm (sdirk, yerr, y)); // Is there error acceptable? //int accept = (herr <= 1.0) || (h <= sdirk->h_min); //if (accept) Accepted = (herr <= 1.0) || (h <= sdirk->h_min); if (Accepted) { // If stiffly-accurate, Z_s with s := numStages, is the solution. // Else, sum the stage solutions: y_n+1 <- y_n + \Sum_j D_j * Z_j for (int j = 0; j < sdirk->numStages; ++j) { __global double *z_j = &z[__getIndex(j*neq)]; if (sdirk->D[j] != 0.0) sdirk_daxpy (neq, sdirk->D[j], z_j, y); } t += h; nst++; } HScalingFactor = 0.9 * pow( 1.0 / herr, (1.0 / sdirk->ELO)); // Reuse the Jacobian if the Newton Solver is converging fast enough. ComputeJ = (NewtonTheta > NewtonThetaMin); // Don't refine if it's not a big step and we could reuse the M matrix. int recycle_M = !(ComputeJ) && (HScalingFactor >= Qmin && HScalingFactor <= Qmax); if (recycle_M) { ComputeM = 0; HScalingFactor = 1.0; } else ComputeM = 1; } // Restrict the rate of change in dt HScalingFactor = fmax( HScalingFactor, 1.0 / sdirk->adaption_limit); HScalingFactor = fmin( HScalingFactor, sdirk->adaption_limit); if (iter % 10 == 0 && 0) printf("iter = %d: passed=%d ... t = %e, HScalingFactor = %f %f %e\n", iter, (Accepted ? (h <= sdirk->h_min ? -1 : 1) : 0), t, HScalingFactor, y[__getIndex(neq-1)], h); // Apply grow/shrink factor for next step. h *= HScalingFactor; // Limit based on the upper/lower bounds h = fmin(h, sdirk->h_max); h = fmax(h, sdirk->h_min); // Stretch the final step if we're really close and we didn't just fail ... //if (herr <= 1.0 && fabs((t + h) - sdirk->t_stop) < sdirk->h_min) if (Accepted && fabs((t + h) - sdirk->t_stop) < sdirk->h_min) { h = sdirk->t_stop - t; //fprintf(stderr,"fabs((t + h) - sdirk->t_stop) < sdirk->h_min: %d %d %e\n", nst, iter, h); ComputeM = 1; } // Don't overshoot the final time ... if (t + h > sdirk->t_stop) { //fprintf(stderr,"t + h > sdirk->t_stop: %d %d %e %e\n", nst, iter, h, sdirk->t_stop - t); h = sdirk->t_stop - t; ComputeM = 1; } ++iter; if (sdirk->max_iters && iter > sdirk->max_iters) { ierr = SDIRK_TOO_MUCH_WORK; //printf("(iter > max_iters)\n"); break; } } //printf("nst=%d nit=%d nfe=%d nje=%d nlu=%d nni=%d (%4.1f, %3.1f)\n", nst, iter, nfe, nje, nlu, nni, (double)(nfe-nje*(neq+1)) / nst, (double)nni / (nst*sdirk->numStages)); return ierr; #undef nst #undef nfe #undef nje #undef nlu #undef nni #undef iter #undef h #undef t #undef neq #undef InterpolateNewton #undef MaxNewtonIterations #undef Qmax #undef Qmin #undef NewtonThetaMin #undef NewtonThetaMax #undef NewtonTolerance } #undef __matrix_index #undef A_ #undef Theta_ #undef Alpha_
C
/******************************************** NAME : Jagajeevan.S DATE : 09.08.2021 DESCRIPTION : To take 8 consecutive bytes in memory. Provide a menu to manipulate or display the value of variable of type t (input) & indexed at i (i/p) INPUT & OUTPUT : Menu : 1. Add element 2. Remove element 3. Display element 4. Exit from the program Choice ---> 1 Enter the type you have to insert: 1.int 2.char 3.short 4.float 5.double choice -----> 2 Enter the character : k k Menu : 1. Add element 2. Remove element 3. Display element 4. Exit from the program Choice ---> 3 [0] -> k [char_type] Menu : 1. Add element 2. Remove element 3. Display element 4. Exit from the program Choice ---> 1 Enter the type you have to insert: 1.int 2.char 3.short 4.float 5.double choice -----> 1 Enter the integer : 10 10 Menu : 1. Add element 2. Remove element 3. Display element 4. Exit from the program Choice ---> 3 [0] -> k [char_type] [1] -> 10 [int_type] Menu : 1. Add element 2. Remove element 3. Display element 4. Exit from the program Choice ---> 2 [0] -> k [1] -> 10 Enter the index value to be deleted : 0 Index 0 is successfully deleted Menu : 1. Add element 2. Remove element 3. Display element 4. Exit from the program Choice ---> 4 *********************************************/ // #include<stdio.h> #include<stdlib.h> int main() { int choice, option, index; // VARIABLE DECLARATION int pos[5]; int c_flag = 0, s_flag = 0, i_flag = 0, f_flag = 0, d_flag = 0; void *ptr; ptr = malloc ( 8 * sizeof(char)); // ALLOCATING 8 BYTES CONTINOUSLY while (1) { printf("\nMenu :\n1. Add element\n2. Remove element\n3. Display element\n4. Exit from the program\n\nChoice ---> "); scanf("%d",&choice); // READ CHOICE FROM USER switch(choice) { case 1: // ADD ELEMENT { printf("Enter the type you have to insert:\n1.int\n2.char\n3.short\n4.float\n5.double\n"); printf("\nchoice -----> "); scanf("%d",&option); // READ CHOICE FROM USER switch (option) { case 1: if ( i_flag == 0 && f_flag == 0 && d_flag == 0) { i_flag++; printf("Enter the integer : "); scanf("%d",((int*)ptr) + 1); // READ INT FROM USER AND STORE IT IN SECOND SET OF 4 BYTES printf("%d",*(((int*)ptr) + 1) ); } else printf("Memory is occupied\n"); break; case 2: if( c_flag < 2 && d_flag == 0 ) { printf("Enter the character : "); scanf(" %c",((char*)ptr) + c_flag); // READ CHAR FROM USER AND STORE IT IN SET OF FIRST 2 BYTES printf("%c\n",*(((char*)ptr)+ c_flag) ); c_flag++; } else printf("Memory is occupied\n"); break; case 3: if ( s_flag == 0 && d_flag == 0 ) { s_flag++; printf("Enter the integer (short) : "); scanf("%hd",((short*)ptr) + 1); // READ SHORT FROM USER AND STORE IT IN SECOND SET OF 2 BYTES printf("%hd",*(((short*)ptr) + 1) ); } else printf("Memory is occupied\n"); break; case 4: if ( i_flag == 0 && f_flag == 0 && d_flag == 0) { f_flag++; printf("Enter the float value : "); scanf("%f",((float*)ptr) + 1); // READ FLOATT FROM USER AND STORE IT IN SECOND SET OF 4 BYTES printf("%f",*(((float*)ptr) + 1) ); } else printf("Memory is occupied\n"); break; case 5: if ( c_flag == 0 && i_flag == 0 && s_flag == 0 && f_flag == 0 && d_flag == 0) { d_flag++; printf("Enter the double value : "); scanf("%lf",((double*)ptr) ); // READ DOUBLE FROM USER AND STORE IT IN 8 BYTES MEMORY ALLOCATED printf("%lf",*((double*)ptr) ); } else printf("Memory is occupied\n"); break; default : printf("Invalid option"); } break; } case 2: // REMOVE ELEMENT { index = 0; // PRINTING ELEMENT WITH POSITION IN THAT 8 BYTES MEMORY ALLOCATED if ( c_flag > 0 ) { printf("[%d] -> %c\n",index, *((char*)ptr)); // 1ST CHARACTER pos[index++] = 1; if ( c_flag > 1 ) { printf("[%d] -> %c\n",index, *(((char*)ptr)+ 1) ); // 2ND CHARACTER pos[index++] = 1; } } if ( s_flag == 1 ) { printf("[%d] -> %hd\n",index, *(((short*)ptr) + 1) ); // 1 SHORT (AT 3RD AND 4TH BYTE) TOTALLY 2 BYTES FOR SHORT pos[index++] = 2; } if ( i_flag == 1 ) { printf("[%d] -> %d\n",index, *(((int*)ptr) + 1) ); // 1 INT (AT 5TH TO 8TH BYTE ) TOTALLY 4 BYTES FOR INT pos[index++] = 3; } if ( f_flag == 1 ) { printf("[%d] -> %f\n",index, *(((float*)ptr) + 1) ); // 1 FLOAT (AT 5TH TO 8TH BYTE ) TOTALLY 4 BYTES FOR FLOAT pos[index++] = 4; } if ( d_flag == 1 ) { printf("[%d] -> %lf\n",index, *((double*)ptr) ); // 1 DOUBLE ENTIRE 8 BYTES ALLOCATED pos[index++] = 5; } printf("Enter the index value to be deleted : "); scanf("%d",&index); // READ INDEX FROM USER switch ( pos[index] ) { case 1 : //REMOVE CHARACTER if ( c_flag > 0 ) { if ( index == 0 ) { *((char*)ptr) = *(((char*)ptr)+ 1); c_flag--; } if ( index == 1 ) { c_flag--; } printf("Index %d is successfully deleted \n",index); } else printf("Already deleted\n"); break; case 2: // REMOVE SHORT if ( s_flag == 1 ) { s_flag--; printf("Index %d is successfully deleted \n",index); } else printf("Already deleted\n"); break; case 3: // REMOVE INT if ( i_flag == 1 ) { i_flag--; printf("Index %d is successfully deleted \n",index); } else printf("Already deleted\n"); break; case 4: //REMOVE FLOAT if ( f_flag == 1 ) { f_flag--; printf("Index %d is successfully deleted \n",index); } else printf("Already deleted\n"); break; case 5: //REMOVE DOUBLE if ( d_flag == 1 ) { d_flag--; printf("Index %d is successfully deleted \n",index); } else printf("Already deleted\n"); break; default : printf("Invalid option"); } break; } case 3: // DISPLAY ELEMENT { index = 0; printf("\n"); if ( c_flag > 0 ) { printf("\n[%d] -> %c\t[char_type]\n",index++, *((char*)ptr)); if ( c_flag > 1 ) printf("[%d] -> %c\t[char_type]\n",index++, *(((char*)ptr)+ 1) ); } if ( s_flag == 1 ) printf("[%d] -> %hd\t[short_type]\n",index++, *(((short*)ptr) + 1) ); if ( i_flag == 1 ) printf("[%d] -> %d\t[int_type]\n",index++, *(((int*)ptr) + 1) ); if ( f_flag == 1 ) printf("[%d] -> %f\t[float_type]\n",index++, *(((float*)ptr) + 1) ); if ( d_flag == 1 ) printf("[%d] -> %lf\t[double_type]\n",index++, *((double*)ptr) ); if ( c_flag == 0 && i_flag == 0 && s_flag == 0 && f_flag == 0 && d_flag == 0) printf("Nothing available all indexes are empty\n"); break; } case 4 : // EXIT FROM PROGRAM free(ptr); ptr = NULL; exit(1); break; default : printf("Invalid option\n"); } } }
C
#include <stdlib.h> #include "../../infrastructure/dbg/dbg.h" #include "../../infrastructure/mem/mem.h" #include "../../infrastructure/validation/validation.h" #include "../../web_api/services/update_order_request.h" #include "../../web_api/services/update_order_request_order_item.h" // allocates an update order request order item update_order_request_order_item_t *update_order_request_order_item_malloc( int *order_item_id, char *name, double *quantity) { update_order_request_order_item_t *update_order_request_order_item = calloc(1, sizeof(update_order_request_order_item_t)); check_mem(update_order_request_order_item); check_result(malloc_memcpy_int(&(update_order_request_order_item->order_item_id), order_item_id), 0); check_result(malloc_memcpy_string(&(update_order_request_order_item->name), name), 0); check_result(malloc_memcpy_double(&(update_order_request_order_item->quantity), quantity), 0); return update_order_request_order_item; error: if (update_order_request_order_item != NULL) { update_order_request_order_item_free(update_order_request_order_item); } return NULL; } // validates an update order request order item int update_order_request_order_item_validate( update_order_request_order_item_t *update_order_request_order_item, int index, validation_error_t ***validation_errors, int *validation_errors_allocated_count, int *validation_errors_used_count) { check_not_null(validation_errors); check_not_null(validation_errors_allocated_count); check_not_null(validation_errors_used_count); if (update_order_request_order_item != NULL) { int validate_order_item_id_result = validate_int(update_order_request_order_item->order_item_id, 0, 1, 999999); if (validate_order_item_id_result != 0) { check_result( validation_errors_add_level_2( validation_errors, validation_errors_allocated_count, validation_errors_used_count, UPDATE_ORDER_REQUEST_ORDER_ITEMS, index, UPDATE_ORDER_REQUEST_ORDER_ITEM_ID, -1, validate_order_item_id_result), 0); } int validate_name_result = validate_string(update_order_request_order_item->name, 1, 1, 100); if (validate_name_result != 0) { check_result( validation_errors_add_level_2( validation_errors, validation_errors_allocated_count, validation_errors_used_count, UPDATE_ORDER_REQUEST_ORDER_ITEMS, index, UPDATE_ORDER_REQUEST_ORDER_ITEM_NAME, -1, validate_name_result), 0); } int validate_quantity_result = validate_double(update_order_request_order_item->quantity, 1, 1, 999999); if (validate_quantity_result != 0) { check_result( validation_errors_add_level_2( validation_errors, validation_errors_allocated_count, validation_errors_used_count, UPDATE_ORDER_REQUEST_ORDER_ITEMS, index, UPDATE_ORDER_REQUEST_ORDER_ITEM_QUANTITY, -1, validate_quantity_result), 0); } } else { check_result( validation_errors_add_level_1( validation_errors, validation_errors_allocated_count, validation_errors_used_count, UPDATE_ORDER_REQUEST_ORDER_ITEMS, index, VALIDATION_RESULT_REQUIRED), 0); } return 0; error: return -1; } // frees an update order request order item void update_order_request_order_item_free(update_order_request_order_item_t *update_order_request_order_item) { if (update_order_request_order_item == NULL) { return; } if (update_order_request_order_item->order_item_id != NULL) { free(update_order_request_order_item->order_item_id); } if (update_order_request_order_item->name != NULL) { free(update_order_request_order_item->name); } if (update_order_request_order_item->quantity != NULL) { free(update_order_request_order_item->quantity); } free(update_order_request_order_item); } // frees an array of update order request order items void update_order_request_order_items_free(update_order_request_order_item_t **update_order_request_order_items, int count) { if (update_order_request_order_items == NULL) { return; } for (int i = 0; i < count; i++) { update_order_request_order_item_free(update_order_request_order_items[i]); } free(update_order_request_order_items); }
C
#include <stdio.h> #include <stdlib.h> int main() { int i, sum=0, sqsum=0; for(i=1; i<=100; i++) { sum += i; printf("%d\t", sum); sqsum += i*i; printf("%d\n", sqsum); } sum = sum * sum; int res = ((sum-sqsum)>=0) ? sum - sqsum : sqsum - sum; printf("\n%d\n", res); return 0; }
C
#include <stdio.h> int main() { int n, c, k; printf("Enter an integer in decimal number system\n"); scanf("%d", &n); printf("%d in binary number system is:\n", n); for (c = 31; c >= 0; c--) { k = n >> c; if (k & 1) printf("1"); else printf("0"); } printf("\n"); return 0; }
C
////////////////////////////////////////////////////////////////////////////// // // Filename: eeprom_bsp.c // // Description: Control driver for the PIC18F4550's internal EEPROM // // Author(s): Trevor Parsh (Embedded Wizardry, LLC) // // Modified for ASL on Date: // ////////////////////////////////////////////////////////////////////////////// /* ************************** Header Files *************************** */ // NOTE: This must ALWAYS be the first include in a file. #include "device.h" // from stdlib #include <stdint.h> #include <stdbool.h> #include <stddef.h> #include "user_assert.h" // from project #include "common.h" #include "rtos_app.h" // from local #include "eeprom_bsp.h" /* ****************************** Macros ****************************** */ #define EEPROM_SIZE_OF_EEPROM ((uint16_t)256) /* *********************** File Scope Variables *********************** */ static volatile uint8_t data_lock_mutex; /* *********************** Function Prototypes ************************ */ static bool writeBuffer(uint8_t start_address, uint8_t num_bytes_to_write, uint8_t *data, uint16_t timeout_ms); static void writeByte(uint8_t address, uint8_t data); static bool waitForEepromToBeWritable(uint16_t timeout_ms); static void readIntoBuffer(uint8_t start_address, uint8_t num_bytes_to_read, uint8_t *buffer); /* ******************* Public Function Definitions ******************** */ //------------------------------- // Function: eepromBspInit // // Description: Initializes this module // //------------------------------- void eepromBspInit(void) { data_lock_mutex = 1; } //------------------------------- // Function: eepromBspWriteByte // // Description: Writes a single byte to the internal EEPROM // // timeout_ms: Time to wait before giving up on waiting for EEPROM write access to be available. // //------------------------------- bool eepromBspWriteByte(uint8_t address, uint8_t byte_to_write, uint16_t timeout_ms) { UNUSED(timeout_ms); rtosAppSemTake(&data_lock_mutex); bool ret_val = writeBuffer(address, 1, &byte_to_write, timeout_ms); rtosAppSemGive(&data_lock_mutex); return ret_val; } //------------------------------- // Function: waitForEepromToBeReady // // Description: Writes an entire buffer to the internal EEPROM // // timeout_ms: Time to wait before giving up on waiting for EEPROM write access to be available. // //------------------------------- bool eepromBspWriteBuffer(uint8_t start_address, uint8_t num_bytes_to_write, uint8_t *data, uint16_t timeout_ms) { ASSERT(((uint16_t)start_address + (uint16_t)num_bytes_to_write) < (uint16_t)EEPROM_SIZE_OF_EEPROM); ASSERT(data != NULL); UNUSED(timeout_ms); rtosAppSemTake(&data_lock_mutex); bool ret_val = writeBuffer(start_address, num_bytes_to_write, data, timeout_ms); rtosAppSemGive(&data_lock_mutex); return ret_val; } //------------------------------- // Function: eepromBspReadSection // // Description: Reads a section of data from internal EEPROM into a data buffer // // buffer: Buffer that stores data read from the EEPROM. // timeout_ms: Time to wait before giving up on waiting for EEPROM read access to be available. // //------------------------------- bool eepromBspReadSection(uint8_t start_address, uint8_t num_bytes_to_read, uint8_t *buffer, uint16_t timeout_ms) { ASSERT(((uint16_t)start_address + (uint16_t)num_bytes_to_read) < (uint16_t)EEPROM_SIZE_OF_EEPROM); ASSERT(buffer != NULL); UNUSED(timeout_ms); rtosAppSemTake(&data_lock_mutex); readIntoBuffer(start_address, num_bytes_to_read, buffer); rtosAppSemGive(&data_lock_mutex); return true; } //------------------------------- // Function: eepromBspSizeOfEeprom // // Description: Returns the total number of available bytes in the EEPROM. // //------------------------------- uint16_t eepromBspSizeOfEeprom(void) { return EEPROM_SIZE_OF_EEPROM; } /* ******************** Private Function Definitions ****************** */ //------------------------------- // Function: writeBuffer // // Description: Writes a buffer full of data to the internal EEPROM. // // NOTE: Bounds checking is performed by the calling function. // //------------------------------- static bool writeBuffer(uint8_t start_address, uint8_t num_bytes_to_write, uint8_t *data, uint16_t timeout_ms) { UNUSED(timeout_ms); bool no_timeout = true; // TODO: Add timeout and feedback on failure. for (int i = 0; i < num_bytes_to_write; i++) { no_timeout = waitForEepromToBeWritable(timeout_ms); if (!no_timeout) { // EEPROM has been unable to be written to for too long, bounce. break; } writeByte(start_address + i, data[i]); } return no_timeout; } //------------------------------- // Function: writeByte // // Description: Writes a single byte to the internal EEPROM // //------------------------------- static void writeByte(uint8_t address, uint8_t data) { // Address and data are 8-bit write_eeprom(address, data); } //------------------------------- // Function: waitForEepromToBeWritable // // Description: Waits for the internal EEPROM to be ready for a write. // // timeout_ms: Time to wait before giving up on waiting for EEPROM write access to be available. // // NOTE: There is no way to probe the ready status with CCS. // //------------------------------- static bool waitForEepromToBeWritable(uint16_t timeout_ms) { UNUSED(timeout_ms); return true; } //------------------------------- // Function: readIntoBuffer // // Description: Reads a section of data from internal EEPROM into a data buffer // // buffer: Buffer that stores data read from the EEPROM. // //------------------------------- static void readIntoBuffer(uint8_t start_address, uint8_t num_bytes_to_read, uint8_t *buffer) { for (uint8_t i = 0; i < num_bytes_to_read; i++) { // Address and return is 8-bit buffer[i] = read_eeprom((start_address + i)); } } // end of file. //-------------------------------------------------------------------------
C
#include<stdio.h> int * abc(void); main() { int *ptr; ptr=abc(); printf("%d\n",*ptr); } int * abc(void) { int number=10; return &number; }
C
#include <poyoio.h> void digital_write(int pin, int vol) { volatile char* output_addr = GPO_WRADDR; volatile int* input_addr = GPO_RDADDR; // 0ビット目は0ピンの状態、1ビット目は1ピンの状態というように値を格納しているので、 // ピンの値に応じたビットのみを変更する if (vol == 1) { *output_addr = (*input_addr | (1 << pin)); } else if (vol == 0) { *output_addr = (*input_addr & ~(1 << pin)); } } int digital_read(int pin) { volatile int* input_addr = GPI_ADDR; int vol; // 0ビット目は0ピンの状態、1ビット目は1ピンの状態というように値を格納しているので、 // ピンの値に応じて特定ビットを読み出す vol = (*input_addr >> pin) & 1; return vol; } void serial_write(char c) { volatile char* output_addr = UART_TX_ADDR; delay(UART_TX_DELAY_TIME); *output_addr = c; } char serial_read() { volatile int* input_addr = UART_RX_ADDR; char c; c = *input_addr; return c; } void delay(unsigned int time) { volatile unsigned int* input_addr = HARDWARE_COUNTER_ADDR; unsigned int start_cycle = *input_addr; while (time > 0) { while ((*input_addr - start_cycle) >= HARDWARE_COUNT_FOR_ONE_MSEC) { time--; start_cycle += HARDWARE_COUNT_FOR_ONE_MSEC; } if (*input_addr < start_cycle) { start_cycle = *input_addr; } } }
C
#include <stdio.h> double cube(double value); int main(void) { double input = 0.0; printf("Enter floating point value: "); while (scanf("%lf", &input) != 1) { while (getchar() != '\n'); printf("Enter floating point value: "); } printf("cube: %.2f\n", cube(input)); return 0; } double cube(double value) { return value * value * value; }
C
/** * @file stack.c - Ficheiro que contém todas as funções relacionadas com a stack * @copyright Copyright (c) 2021 */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <stdarg.h> #include <math.h> #include "stack.h" #include "array.h" stack create() { stack myStack; // Inicialização da stack myStack.size = SIZE; // Tamanho da stack igual a 100 myStack.pointer = -1; // O stack pointerinicializado com o valor -1 myStack.elems = (stack_elem *)malloc(myStack.size * sizeof(stack_elem)); // Alocação de memória para guardar os elementos return myStack; } int stackStatus(stack *s) { int r; if (s->pointer == -1) r = 0; // 0 for empty else if (s->pointer == SIZE) r = 1; // 1 for full else r = 2; // 2 for not !full or !empty return r; } void push(stack *s, const enum stack_type type, ...) { // Estado da stack int status = stackStatus(s); if (status == 1) // Se a stack estiver cheia. { // Realocar a memória para ser possivel meter todos os valores. stack_elem *tmp = (stack_elem *)realloc(s->elems, s->size * sizeof(stack_elem)); // Verificamos se foi possível realocar mais memória. if (tmp == NULL) fprintf(stderr, "Limite de memória excedido.\n"); else s->elems = tmp; } va_list ap; va_start(ap, type); // Push do elemento de acordo com o seu tipo relativo à stack. switch (type) { case STACK_CHAR: s->pointer++; s->elems[s->pointer].data.char_value = (char)va_arg(ap, int); s->elems[s->pointer].type = type; break; case STACK_INT:; s->pointer++; s->elems[s->pointer].data.int_value = va_arg(ap, int); s->elems[s->pointer].type = type; break; case STACK_FLOAT: s->pointer++; s->elems[s->pointer].data.float_value = (float)va_arg(ap, double); s->elems[s->pointer].type = type; break; case STACK_STRING: s->pointer++; s->elems[s->pointer].data.string_value = va_arg(ap, char *); s->elems[s->pointer].type = type; break; case STACK_ARRAY: s->pointer++; s->elems[s->pointer].data.array_value = va_arg(ap, stack *); s->elems[s->pointer].type = type; break; case STACK_BLOCK: s->pointer++; s->elems[s->pointer].data.string_value = va_arg(ap, char *); s->elems[s->pointer].type = type; break; default: fprintf(stderr, "O tipo não existe!\n"); // Erro caso o tipo não exista. exit(EXIT_FAILURE); } } stack_elem pop(stack *s) { // Estado da stack. int status = stackStatus(s); if (status != 0) { stack_elem elem = s->elems[s->pointer]; s->pointer--; return elem; } else { fprintf(stderr, "A stack está vazia!\n"); exit(EXIT_FAILURE); } } void dumpStack(stack *s) { // printf("Stack Dump: "); for (int i = 0; i < s->pointer + 1; i++) { stack_elem elem = s->elems[i]; stack_type type = elem.type; switch (type) { case STACK_CHAR: printf("%c", elem.data.char_value); break; case STACK_INT: printf("%d", elem.data.int_value); break; case STACK_LONG: printf("%ld", elem.data.long_value); break; case STACK_FLOAT:; printf("%g", elem.data.float_value); break; case STACK_DOUBLE: printf("%g", elem.data.double_value); break; case STACK_STRING: printf("%s", elem.data.string_value); break; case STACK_ARRAY: printArray(elem.data.array_value); break; case STACK_BLOCK: printf("%s", elem.data.block_value); break; default: fprintf(stderr, "unknown"); exit(EXIT_FAILURE); } } printf("\n"); // Retirar o "\n" para evitar breaks ao dar print de um array, pois é recursivo. } stack_elem peek(stack *s) { return s->elems[s->pointer]; } void pushVar(stack *s, char var_letter) { // Ao retirar 65 à letra (ASCII) obtemos o seu índice no array. // Por exemplo : A = 65, 65 - 65 = 0 | B = 66, 66 - 65 = 1 int index = var_letter - 65; stack_elem var_element = peek(s); // Queremos copiar o elemento no topo para a variável. s->vars[index] = var_element; } void varStart(stack *stack) { // Inicialização das variáveis default da linguagem. stack_elem a, b, c, d, e, f, n, s, x, y, z; // Valores default de cada variável a.type = STACK_INT; a.data.int_value = 10; b.type = STACK_INT; b.data.int_value = 11; c.type = STACK_INT; c.data.int_value = 12; d.type = STACK_INT; d.data.int_value = 13; e.type = STACK_INT; e.data.int_value = 14; f.type = STACK_INT; f.data.int_value = 15; n.type = STACK_CHAR; n.data.char_value = '\n'; s.type = STACK_CHAR; s.data.char_value = ' '; x.type = STACK_INT; x.data.int_value = 0; y.type = STACK_INT; y.data.int_value = 1; z.type = STACK_INT; z.data.int_value = 2; // Atribuição de cada variável a um indice do array das variaveis. stack->vars[0] = a; stack->vars[1] = b; stack->vars[2] = c; stack->vars[3] = d; stack->vars[4] = e; stack->vars[5] = f; stack->vars[13] = n; stack->vars[18] = s; stack->vars[23] = x; stack->vars[24] = y; stack->vars[25] = z; } void getVar(stack *s, char var_letter) { // Segue o mesmo raciocínio da função pushVar. int index = var_letter - 65; // O valor da variável que cuja letra cooresponde ao índice var_letter - 65. // Por exemplo, var_letter = S => index = 85 - 65 = 18 = índice do S no array das variáveis definido na estrutura da stack. stack_elem onVariable = s->vars[index]; // Um caso para cada tipo. switch(onVariable.type) { case STACK_INT: push(s, STACK_INT, onVariable.data.int_value); break; case STACK_FLOAT: push(s, STACK_FLOAT, onVariable.data.float_value); break; case STACK_DOUBLE: push(s, STACK_DOUBLE, onVariable.data.double_value); break; case STACK_CHAR: push(s, STACK_CHAR, onVariable.data.char_value); break; case STACK_STRING: push(s, STACK_STRING, onVariable.data.string_value); break; default: fprintf(stderr, "Erro ao adicionar elemento!\n[function::getVar]"); break; } } stack_type getSecondType(stack *s) { stack_type type; // Pop do topo; peek do topo; push do topo. stack_elem elem = s->elems[s->pointer - 1]; type = elem.type; return type; } void copyVarStack(stack *s) { // Copiar as variáveis da stack para o array. stack_elem array = peek(s); for (int i = 0; i < 26; i++) { array.data.array_value->vars[i] = s->vars[i]; } } void copyVarArray(stack *s) { // Fazer o inverso da função de cima, queremos passar as variaveis do Array para as da stack. stack_elem array = peek(s); for (int i = 0; i < 26; i++) { s->vars[i] = array.data.array_value->vars[i]; } }
C
/* * Copyright 2015 Joseph Landry */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "list.h" struct list { void **buf; int size; int count; }; struct list *newList(){ struct list *list; list = calloc(1, sizeof(*list)); list->size = 32; list->count = 0; list->buf = calloc(list->size, sizeof(void *)); return list; } void freeList(struct list *list){ free(list->buf); list->buf = NULL; free(list); } static int listIncreaseSize(struct list *list){ int newSize; void **newBuf; newSize = list->size * 2; newBuf = realloc(list->buf, newSize * sizeof(void *)); assert(newBuf != NULL); list->buf = newBuf; list->size = newSize; return 0; } int listPush(struct list *list, void *item){ if(list->size <= list->count){ listIncreaseSize(list); } assert(list->count < list->size); list->buf[list->count] = item; list->count += 1; return 0; } int listPop(struct list *list, void **itemOut){ if(list->count > 0){ if(itemOut){ *itemOut = list->buf[list->count - 1]; } list->count -= 1; return 0; } else { *itemOut = NULL; return -1; } } int listPopPeek(struct list *list, void **itemOut){ if(list->count > 0){ *itemOut = list->buf[list->count - 1]; return 0; } else { *itemOut = NULL; return -1; } } int listEnqueue(struct list *list, void *item){ if(list->size <= list->count){ listIncreaseSize(list); } assert(list->count < list->size); /* if(list->count == 0){ list->buf[0] = item; list->count += 1; return 0; } else { memmove(list->buf+1, list->buf, list->count * sizeof(void *)); list->buf[0] = item; list->count += 1; return 0; } */ return listPush(list, item); } int listDequeue(struct list *list, void **itemOut){ if(list->count > 0){ if(itemOut){ *itemOut = list->buf[0]; } memmove(list->buf, list->buf+1, (list->count - 1) * sizeof(void *)); list->count -= 1; return 0; } else { *itemOut = NULL; return -1; } //return listPop(list, itemOut); } int listDequeuePeek(struct list *list, void **itemOut){ return listItemAtIndex(list, 0, itemOut); } int listItemAtIndex(struct list *list, int index, void **itemOut){ assert(0 <= index && index < list->count); *itemOut = list->buf[index]; return 0; } int listItemCount(struct list *list){ return list->count; } int listUnshift(struct list *list, void *item){ if(list->count >= list->size){ listIncreaseSize(list); } assert(list->count < list->size); memmove(list->buf + 1, list->buf, list->count * sizeof(void *)); list->buf[0] = item; return 0; } int listUnshiftList(struct list *dst, struct list *src){ while(dst->size <= dst->count + src->count){ listIncreaseSize(dst); } assert(dst->count + src->count < dst->size); memmove(dst->buf + src->count, dst->buf, dst->count * sizeof(void*)); memcpy(dst->buf, src->buf, src->count * sizeof(void*)); dst->count += src->count; return 0; } #ifdef TESTING char *testStrings[] = { "racecar", "watch", "worm", "rates", "hate", "charge", "free", "pie", "never", "monkey", "shift", "make", NULL, }; void test_listQueue(){ struct list *list; int i; char *s; list = newList(); assert(list != NULL); assert(listDequeue(list, (void**)&s) != 0); i = 0; while(testStrings[i]){ assert(listEnqueue(list, testStrings[i]) == 0); i += 1; } i = 0; while(testStrings[i]){ listDequeuePeek(list, (void**)&s); assert(strcmp(s, testStrings[i]) == 0); s = NULL; listDequeue(list, (void**)&s); assert(strcmp(s, testStrings[i]) == 0); i += 1; } freeList(list); } void test_listStack(){ struct list *list; int i; char *s; list = newList(); assert(list != NULL); assert(listPop(list, (void **)&s) != 0); i = 0; while(testStrings[i]){ assert(listPush(list, testStrings[i]) == 0); i += 1; } i -= 1; while(i >= 0){ assert(listPopPeek(list, (void**)&s) == 0); assert(strcmp(s, testStrings[i]) == 0); s = NULL; assert(listPop(list, (void**)&s) == 0); assert(strcmp(s, testStrings[i]) == 0); i -= 1; } } int main(int argc, char *argv[]){ test_listQueue(); test_listStack(); //test_listArray(); printf("OK\n"); return 0; } #endif
C
#include "list_de_listNodes.h" /***********************AJOUTE**************************/ void list2N_insert(list2N **l,int nodeid, listeNodes *peres) { list2N *tmp=malloc(sizeof(list2N)); if(!tmp) { printf("erreur de creation de la liste\n"); exit(-5); } tmp->values.node=nodeid; tmp->values.x=0; tmp->values.y=0; tmp->values.z=0; tmp->peres=Nullptr(listeNodes); listeNodes_copy(&tmp->peres,peres); tmp->suiv=*l; *l=tmp; } void list2N_insert_values(list2N **l, int nodeid, double x, double y, double z, listeNodes *peres) { list2N *tmp=malloc(sizeof(list2N)); if(!tmp) { printf("erreur de creation de la liste\n"); exit(-5); } tmp->values.node=nodeid; tmp->values.x=x; tmp->values.y=y; tmp->values.z=z; tmp->peres=Nullptr(listeNodes); listeNodes_copy(&tmp->peres,peres); tmp->suiv=*l; *l=tmp; } void list2N_insert_element(list2N **l, element node, listeNodes *peres) { list2N *tmp=malloc(sizeof(list2N)); if(!tmp) { printf("erreur de creation de la liste\n"); exit(-5); } tmp->values.node=node.node; tmp->values.x=node.x; tmp->values.y=node.y; tmp->values.z=node.z; tmp->peres=Nullptr(listeNodes); listeNodes_copy(&tmp->peres,peres); tmp->suiv=*l; *l=tmp; } /***********************AFFICHAGE**************************/ void list2N_affiche(list2N *l) { while(l) { printf("%d\t",l->values.node); listeNodes_affiche(l->peres); l=l->suiv; } printf("\n\n"); } /***********************TAILLE**************************/ int list2N_taille(list2N *l) { int nbr=0; while(l) { nbr++; l=l->suiv; } return nbr; } /***********************DESTRUCTION**************************/ void list2N_detruire(list2N **l) { list2N *tmp=*l; while(*l) { tmp = (*l)->suiv; listeNodes_detruire(&(*l)->peres); free(*l); *l = tmp; } } /***********************RECHERCHE**************************/ int list2N_recherche(list2N *l,int val) { int bol=0; while(l&&!bol) { if(l->values.node==val) bol=1; l=l->suiv; } return bol; } int list2N_recherche_pere(list2N *l,int val) { int bol=0; while(l) { if(listeNodes_recherche(l->peres,val)) bol++; l=l->suiv; } return bol; } /*********************************COPIER*******************************/ void list2N_copy(list2N **des,list2N *src) { while(src) { list2N_insert(des,src->values.node,src->peres); src=src->suiv; } } /*************************************SUPPRIME***********************/ int list2N_delete(list2N **l, int val) { if(!list2N_recherche(*l,val)) return 0; if((*l)->values.node ==val) { list2N *tmp=*l; *l=(*l)->suiv; listeNodes_detruire(&tmp->peres); free(tmp); return 1; } else { list2N *tmp=*l; while(tmp->suiv->values.node!=val) tmp=tmp->suiv; list2N *tmp2=tmp->suiv; tmp->suiv=tmp->suiv->suiv; listeNodes_detruire(&tmp2->peres); free(tmp2); return 1; }//*/ return 1; } //supression d'un pere int list2N_delete_pere_from_fils(list2N *l,int fils, int pere) { if(!list2N_recherche_pere(l,pere)) return 0; while(l) { if(l->values.node==fils) listeNodes_delete(&l->peres,pere); l=l->suiv; } return 1; }
C
/*************************************************************************** main.c - description ------------------- begin : Mon Oct 21 09:41:54 CEST 2013 copyright : (C) 2013 by Brandon Warhurst email : roboknight AT gmail dot com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 as * * published by the Free Software Foundation. * * * ***************************************************************************/ /* TODO: - Ability to find device by PID/VID, product name or serial TODO nice-to-have: - Out-of-the-box compatibility with FTDI's eeprom tool configuration files */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <confuse.h> #include <libusb-1.0/libusb.h> #include <libftdi1/ftdi.h> #include <getopt.h> #include <ctype.h> /** * @brief Convert driver options strings to a value * * \param str pointer to driver option string to convert * * Function will return the value of the option string. * This is used to determine the correct values to set for * drivers. * **/ static int str_to_drvr(char *str) { const int max_options = 4; int cmp_len=0,i; const char* options[] = { "D2XX", "VCP", "RS485" }; for(i = 0; i < max_options; i++) { cmp_len = (strlen(str) >= strlen(options[i])) ? strlen(options[i]) : strlen(str); if(!strncmp(str,options[i],cmp_len)) break; } return i; } /** * @brief Convert CBUS options strings to an index * * \param str pointer to CBUS option string to index * \param max_allowed last CBUS option to allow in returned index * * Function will return 0 if no options are found. A message * will be sent to the terminal. **/ static int str_to_cbus(char *str, int max_allowed) { #define MAX_OPTION 14 const char* options[MAX_OPTION] = { "TXDEN", "PWREN", "RXLED", "TXLED", "TXRXLED", "SLEEP", "CLK48", "CLK24", "CLK12", "CLK6", "IO_MODE", "BITBANG_WR", "BITBANG_RD", "SPECIAL"}; int i; max_allowed += 1; if (max_allowed > MAX_OPTION) max_allowed = MAX_OPTION; for (i=0; i<max_allowed; i++) { if (!(strcmp(options[i], str))) { return i; } } printf("WARNING: Invalid cbus option '%s'\n", str); return 0; } /** * @brief Set eeprom value * * \param ftdi pointer to ftdi_context * \param value_name Enum of the value to set * \param value Value to set * * Function will abort the program on error **/ static void eeprom_set_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int value) { if (ftdi_set_eeprom_value(ftdi, value_name, value) < 0) { printf("Unable to set eeprom value %d: %s. Aborting\n", value_name, ftdi_get_error_string(ftdi)); exit (-1); } } /** * @brief Get eeprom value * * \param ftdi pointer to ftdi_context * \param value_name Enum of the value to get * \param value Value to get * * Function will abort the program on error **/ static void eeprom_get_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int *value) { if (ftdi_get_eeprom_value(ftdi, value_name, value) < 0) { printf("Unable to get eeprom value %d: %s. Aborting\n", value_name, ftdi_get_error_string(ftdi)); exit (-1); } } /** * @brief Detect eeprom type * * \param ftdi pointer to ftdi_context * \param eeprom_type eeprom type to set if failure occurs * * Function will return the eeprom type detected or * the eeprom_type if detection failed. **/ static int detect_eeprom(struct ftdi_context *ftdi, int eeprom_type) { int i, f; f = ftdi_erase_eeprom(ftdi); /* needed to determine EEPROM chip type */ if (ftdi_get_eeprom_value(ftdi, CHIP_TYPE, &i) <0) { fprintf(stderr, "ftdi_get_eeprom_value: %d (%s)\n", f, ftdi_get_error_string(ftdi)); fprintf(stderr, "using configuration value = 0x%02x\n",eeprom_type); i = eeprom_type; } else { if (i == -1) fprintf(stderr, "No EEPROM\n"); else if (i == 0) fprintf(stderr, "Internal EEPROM\n"); else fprintf(stderr, "Found 93x%02x\n", i); if(i != eeprom_type && eeprom_type != 0) { printf("Unmatched EEPROM type 0x%02x. Using configuration value = 0x%02x\n",i, eeprom_type); i = eeprom_type; } } return i; } /** * @brief locate an ftdi device based on vid/pid values * * \param ftdi pointer to ftdi_context * \param primary_vid vid to try first * \param primary_pid pid to try first * \param fallback_vid vid to try if primary fails * \param fallback_pid pid to try if primary fails * * Function will attempt to locate the device with * primary_vid/primary_pid and fallback to fallback_vid/fallback_pid * if primary_vid/primary_pid can't be found. Returns the * status of the ftdi_usb_open routine. **/ static int locate_ftdi_device(struct ftdi_context *ftdi, int primary_vid, int primary_pid, int fallback_vid, int fallback_pid) { int i; i = ftdi_usb_open(ftdi, primary_vid, primary_pid); if(i!=0) { printf("Unable to find FTDI devices under given vendor/product id: 0x%X/0x%X\n", primary_vid, primary_pid); printf("Error code: %d (%s)\n", i, ftdi_get_error_string(ftdi)); if(primary_vid != fallback_vid || primary_pid != fallback_pid) { printf("Retrying with fallback vid=%#04x, pid=%#04x.\n", fallback_vid, fallback_pid); i = ftdi_usb_open(ftdi, fallback_vid, fallback_pid); if (i != 0) { printf("Error: %s\n", ftdi->error_str); } else { printf("Alternate device (%04x,%04x) located.\n",fallback_vid,fallback_pid); } } } else { printf("Device (%04x,%04x) located.\n",primary_vid,primary_pid); } return i; } /** * @brief Display usage information * * \param prog_name pointer command line program name * usually argv[0]. * * Function will provide a short summary of program usage * to the command line. **/ static void usage(char *prog_name) { printf("%s <command> [options]\n",prog_name); printf("commands (must choose one):\n"); printf("-h\t\t\tthis help.\n"); printf("-e\t\t\terase configuration eeprom.\n"); printf("-f <config filename>\tprogram configuration eeprom using <config filename>.\n"); printf("-r <config binary>\tread configuration eeprom and write it to <config binary>.\n"); printf("-s\t\t\tscan for default FTDI devices.\n"); printf("options:\n"); printf("-o <filename>\t\twrite binary configuration to <filename> after read command.\n"); printf("-d\t\t\tread and decode eeprom.\n"); printf("-D\t\t\tdisplay hexdump of eeprom during decoding.\n"); printf("-p <pid>\t\tuse pid <pid> for operation.\n"); printf("-v <vid>\t\tuse vid <vid> for operation.\n"); printf("NOTE 1: FTDI default vid is 0x403 and default pid is 0x6001\n"); printf(" All other vid and pid values should be specified in the configuration file\n"); printf(" or on the command line with -v and -p.\n"); printf("NOTE 2: -o option is equivalent to 'filename' configuration file parameter, but for reading.\n"); exit(-1); } /** * @brief Read and decode EEPROM information * * \param ftdi pointer to ftdi_context * \param debug value indicating whether more output is wanted. * 0 = standard output * 1 = debug output * * Function will provide the decoded EEPROM information * to the command line. The debug output is the byte * buffer, displayed as a hex dump. **/ int read_decode_eeprom(struct ftdi_context *ftdi, int debug) { int i, j, f; int value; int size; unsigned char buf[256]; ftdi_get_eeprom_value(ftdi, CHIP_SIZE, &value); if (value <0) { fprintf(stderr, "No EEPROM found or EEPROM empty\n"); return -1; } fprintf(stderr, "Chip type %d ftdi_eeprom_size: %d\n", ftdi->type, value); if (ftdi->type == TYPE_R) size = 0xa0; else size = value; if(debug > 0) { ftdi_get_eeprom_buf(ftdi, buf, size); for (i=0; i < size; i += 16) { fprintf(stdout,"0x%03x:", i); for (j = 0; j< 8; j++) fprintf(stdout," %02x", buf[i+j]); fprintf(stdout," "); for (; j< 16; j++) fprintf(stdout," %02x", buf[i+j]); fprintf(stdout," "); for (j = 0; j< 8; j++) fprintf(stdout,"%c", isprint(buf[i+j])?buf[i+j]:'.'); fprintf(stdout," "); for (; j< 16; j++) fprintf(stdout,"%c", isprint(buf[i+j])?buf[i+j]:'.'); fprintf(stdout,"\n"); } } f = ftdi_eeprom_decode(ftdi, 1); if (f < 0) { fprintf(stderr, "ftdi_eeprom_decode: %d (%s)\n", f, ftdi_get_error_string(ftdi)); return -1; } return 0; } #define QUIT return_code = 1; goto cleanup; int main(int argc, char *argv[]) { /* configuration options */ cfg_opt_t opts[] = { CFG_INT("target_vendor_id", 0x403, 0), CFG_INT("target_product_id", 0x6001, 0), CFG_INT("vendor_id", 0, 0), CFG_INT("product_id", 0, 0), CFG_BOOL("self_powered", cfg_true, 0), CFG_BOOL("remote_wakeup", cfg_true, 0), CFG_BOOL("in_is_isochronous", cfg_false, 0), CFG_BOOL("out_is_isochronous", cfg_false, 0), CFG_BOOL("suspend_pull_downs", cfg_false, 0), CFG_BOOL("use_serial", cfg_false, 0), CFG_BOOL("change_usb_version", cfg_false, 0), CFG_INT("usb_version", 0, 0), CFG_INT("default_pid", 0x6001, 0), CFG_INT("max_power", 0, 0), CFG_STR("manufacturer", "Acme Inc.", 0), CFG_STR("product", "USB Serial Converter", 0), CFG_STR("serial", "08-15", 0), CFG_INT("eeprom_type", 0x00, 0), CFG_STR("filename", "", 0), CFG_BOOL("flash_raw", cfg_false, 0), CFG_BOOL("high_current", cfg_false, 0), CFG_STR_LIST("cbus0", "{TXDEN,PWREN,RXLED,TXLED,TXRXLED,SLEEP,CLK48,CLK24,CLK12,CLK6,IO_MODE,BITBANG_WR,BITBANG_RD,SPECIAL}", 0), CFG_STR_LIST("cbus1", "{TXDEN,PWREN,RXLED,TXLED,TXRXLED,SLEEP,CLK48,CLK24,CLK12,CLK6,IO_MODE,BITBANG_WR,BITBANG_RD,SPECIAL}", 0), CFG_STR_LIST("cbus2", "{TXDEN,PWREN,RXLED,TXLED,TXRXLED,SLEEP,CLK48,CLK24,CLK12,CLK6,IO_MODE,BITBANG_WR,BITBANG_RD,SPECIAL}", 0), CFG_STR_LIST("cbus3", "{TXDEN,PWREN,RXLED,TXLED,TXRXLED,SLEEP,CLK48,CLK24,CLK12,CLK6,IO_MODE,BITBANG_WR,BITBANG_RD,SPECIAL}", 0), CFG_STR_LIST("cbus4", "{TXDEN,PWRON,RXLED,TXLED,TX_RX_LED,SLEEP,CLK48,CLK24,CLK12,CLK6}", 0), CFG_BOOL("invert_txd", cfg_false, 0), CFG_BOOL("invert_rxd", cfg_false, 0), CFG_BOOL("invert_rts", cfg_false, 0), CFG_BOOL("invert_cts", cfg_false, 0), CFG_BOOL("invert_dtr", cfg_false, 0), CFG_BOOL("invert_dsr", cfg_false, 0), CFG_BOOL("invert_dcd", cfg_false, 0), CFG_BOOL("invert_ri", cfg_false, 0), CFG_STR("channel_a_driver", "VCP", 0), CFG_STR("channel_b_driver", "VCP", 0), CFG_STR("channel_c_driver", "VCP", 0), CFG_STR("channel_d_driver", "VCP", 0), CFG_BOOL("channel_a_rs485", cfg_false, 0), CFG_BOOL("channel_b_rs485", cfg_false, 0), CFG_BOOL("channel_c_rs485", cfg_false, 0), CFG_BOOL("channel_d_rs485", cfg_false, 0), CFG_END() }; cfg_t *cfg; /* normal variables */ int _decode = 0, _scan = 0, _read = 0, _erase = 0, _flash = 0, _debug = 0; const int max_eeprom_size = 256; int my_eeprom_size = 0; unsigned char *eeprom_buf = NULL; char *filename=NULL, *cfg_filename=NULL; int size_check; int option_vid=0x403, option_pid=0x6001; int i, f, return_code=0; FILE *fp; struct ftdi_context *ftdi = NULL; printf ("\nftdi-flash-tool %s\n", EEPROM_VERSION_STRING); printf ("\nAn FTDI eeprom generator\n"); printf ("(c) Brandon Warhurst\n"); /* Check the options */ while ((i = getopt(argc, argv, "dDef:ho:rv:p:s")) != -1) { switch(i) { case 'd': /* decode */ _decode = 1; break; case 'D': /* debug */ _debug = 1; break; case 'v': /* VID */ option_vid = strtoul(optarg, NULL, 0); break; case 'p': /* PID */ option_pid = strtoul(optarg, NULL, 0); break; case 'o': /* output (for read) */ filename = optarg; break; case 'r': /* read command */ _flash = 0; _read = 1; _erase = 0; break; case 'e': /* erase command */ _flash = 0; _read = 0; _erase = 1; cfg_filename = NULL; filename = NULL; break; case 'f': /* flash command */ _flash = 1; _read = 0; _erase = 0; filename = NULL; cfg_filename = optarg; break; case 's': /* scan command (currently not really useful) */ _scan = 1; break; case 'h': /* help */ default: usage(argv[0]); } } /* Allocate the ftdi structure */ if ((ftdi = ftdi_new()) == 0) { fprintf(stderr, "Failed to allocate ftdi structure :%s \n", ftdi_get_error_string(ftdi)); return EXIT_FAILURE; } if(_scan > 0) { /* If we are scanning, do this stuff here. */ /* Currently doesn't really do anything useful. */ struct ftdi_device_list *devlist; int res; if ((res = ftdi_usb_find_all(ftdi, &devlist, 0, 0)) < 0) { fprintf(stderr, "No FTDI with default VID/PID found\n"); return_code = -1; } printf("Found %d default FTDI devices\n",res); goto cleanup; } /* Check to make sure a command was provided */ if(_read == 0 && _flash == 0 && _erase == 0) usage(argv[0]); if(_flash > 0) { /* if we are flashing... */ printf("Writing...\n"); if ((fp = fopen(cfg_filename, "r")) == NULL) { printf ("Can't open configuration file\n"); return -1; } fclose (fp); cfg = cfg_init(opts, 0); cfg_parse(cfg, cfg_filename); filename = cfg_getstr(cfg, "filename"); if (cfg_getbool(cfg, "self_powered") && cfg_getint(cfg, "max_power") > 0) printf("Hint: Self powered devices should have a max_power setting of 0.\n"); int vendor_id = cfg_getint(cfg, "vendor_id"); int product_id = cfg_getint(cfg, "product_id"); i = locate_ftdi_device(ftdi,vendor_id,product_id,option_vid,option_pid); int target_vid = cfg_getint(cfg, "target_vendor_id"); int target_pid = cfg_getint(cfg, "target_product_id"); if(i && (target_vid != option_vid || target_pid != option_pid)) locate_ftdi_device(ftdi,target_vid, target_pid, option_vid, option_pid); if(i != 0) { QUIT; } if((f=ftdi_read_eeprom(ftdi))) { fprintf(stderr, "FTDI read eeprom: %d (%s)\n", f, ftdi_get_error_string(ftdi)); } i = detect_eeprom(ftdi,cfg_getint(cfg,"eeprom_type")); ftdi_eeprom_initdefaults (ftdi, cfg_getstr(cfg, "manufacturer"), cfg_getstr(cfg, "product"), cfg_getstr(cfg, "serial")); eeprom_set_value(ftdi, CHIP_TYPE, i); eeprom_get_value(ftdi, CHIP_SIZE, &my_eeprom_size); if(my_eeprom_size < 0) { if ((i == 0x56) || (i == 0x66)) my_eeprom_size = 0x100; else my_eeprom_size = 0x80; } printf("EEPROM size: %d\n",my_eeprom_size); eeprom_set_value(ftdi, VENDOR_ID, cfg_getint(cfg, "vendor_id")); eeprom_set_value(ftdi, PRODUCT_ID, cfg_getint(cfg, "product_id")); eeprom_set_value(ftdi, SELF_POWERED, cfg_getbool(cfg, "self_powered")); eeprom_set_value(ftdi, REMOTE_WAKEUP, cfg_getbool(cfg, "remote_wakeup")); eeprom_set_value(ftdi, MAX_POWER, cfg_getint(cfg, "max_power")); eeprom_set_value(ftdi, IN_IS_ISOCHRONOUS, cfg_getbool(cfg, "in_is_isochronous")); eeprom_set_value(ftdi, OUT_IS_ISOCHRONOUS, cfg_getbool(cfg, "out_is_isochronous")); eeprom_set_value(ftdi, SUSPEND_PULL_DOWNS, cfg_getbool(cfg, "suspend_pull_downs")); eeprom_set_value(ftdi, USE_SERIAL, cfg_getbool(cfg, "use_serial")); eeprom_set_value(ftdi, USE_USB_VERSION, cfg_getbool(cfg, "change_usb_version")); eeprom_set_value(ftdi, USB_VERSION, cfg_getint(cfg, "usb_version")); eeprom_set_value(ftdi, HIGH_CURRENT, cfg_getbool(cfg, "high_current")); eeprom_set_value(ftdi, CBUS_FUNCTION_0, str_to_cbus(cfg_getstr(cfg, "cbus0"), 13)); eeprom_set_value(ftdi, CBUS_FUNCTION_1, str_to_cbus(cfg_getstr(cfg, "cbus1"), 13)); eeprom_set_value(ftdi, CBUS_FUNCTION_2, str_to_cbus(cfg_getstr(cfg, "cbus2"), 13)); eeprom_set_value(ftdi, CBUS_FUNCTION_3, str_to_cbus(cfg_getstr(cfg, "cbus3"), 13)); eeprom_set_value(ftdi, CBUS_FUNCTION_4, str_to_cbus(cfg_getstr(cfg, "cbus4"), 9)); int invert = 0; if (cfg_getbool(cfg, "invert_rxd")) invert |= INVERT_RXD; if (cfg_getbool(cfg, "invert_txd")) invert |= INVERT_TXD; if (cfg_getbool(cfg, "invert_rts")) invert |= INVERT_RTS; if (cfg_getbool(cfg, "invert_cts")) invert |= INVERT_CTS; if (cfg_getbool(cfg, "invert_dtr")) invert |= INVERT_DTR; if (cfg_getbool(cfg, "invert_dsr")) invert |= INVERT_DSR; if (cfg_getbool(cfg, "invert_dcd")) invert |= INVERT_DCD; if (cfg_getbool(cfg, "invert_ri")) invert |= INVERT_RI; eeprom_set_value(ftdi, INVERT, invert); eeprom_set_value(ftdi, CHANNEL_A_DRIVER, str_to_drvr(cfg_getstr(cfg,"channel_a_driver")) ? DRIVER_VCP : 0); eeprom_set_value(ftdi, CHANNEL_B_DRIVER, str_to_drvr(cfg_getstr(cfg,"channel_b_driver")) ? DRIVER_VCP : 0); eeprom_set_value(ftdi, CHANNEL_C_DRIVER, str_to_drvr(cfg_getstr(cfg,"channel_c_driver")) ? DRIVER_VCP : 0); eeprom_set_value(ftdi, CHANNEL_D_DRIVER, str_to_drvr(cfg_getstr(cfg,"channel_d_driver")) ? DRIVER_VCP : 0); eeprom_set_value(ftdi, CHANNEL_A_RS485, cfg_getbool(cfg,"channel_a_rs485")); eeprom_set_value(ftdi, CHANNEL_B_RS485, cfg_getbool(cfg,"channel_b_rs485")); eeprom_set_value(ftdi, CHANNEL_C_RS485, cfg_getbool(cfg,"channel_c_rs485")); eeprom_set_value(ftdi, CHANNEL_D_RS485, cfg_getbool(cfg,"channel_d_rs485")); size_check = ftdi_eeprom_build(ftdi); if (size_check == -1) { printf ("Sorry, the eeprom can only contain 128 bytes (100 bytes for your strings).\n"); printf ("You need to short your string by: %d bytes\n", size_check); QUIT; } else if (size_check < 0) { printf ("ftdi_eeprom_build(): error: %d\n", size_check); } else { printf ("Used eeprom space: %d bytes\n", my_eeprom_size-size_check); } if (cfg_getbool(cfg, "flash_raw")) { if (filename != NULL && strlen(filename) > 0) { eeprom_buf = malloc(max_eeprom_size); FILE *fp = fopen(filename, "rb"); if (fp == NULL) { printf ("Can't open eeprom file %s.\n", filename); QUIT; } my_eeprom_size = fread(eeprom_buf, 1, max_eeprom_size, fp); fclose(fp); if (my_eeprom_size < 128) { printf ("Can't read eeprom file %s.\n", filename); QUIT; } ftdi_set_eeprom_buf(ftdi, eeprom_buf, my_eeprom_size); } } if((f=ftdi_write_eeprom(ftdi))) printf ("FTDI write eeprom: %d (%s)\n", f,ftdi_get_error_string(ftdi)); libusb_reset_device(ftdi->usb_dev); if(_decode > 0) read_decode_eeprom(ftdi,_debug); cfg_free(cfg); } else { i = locate_ftdi_device(ftdi,option_vid,option_pid, 0x403, 0x6001); if(i != 0) { QUIT; } if (_read > 0) { /* if we are reading... */ printf("Reading...\n"); if((f=ftdi_read_eeprom(ftdi))) { fprintf(stderr, "FTDI read eeprom: %d (%s)\n", f, ftdi_get_error_string(ftdi)); } eeprom_get_value(ftdi, CHIP_SIZE, &my_eeprom_size); if(my_eeprom_size > 0) printf("EEPROM size: %d\n", my_eeprom_size); else { printf("No EEPROM or EEPROM not programmed.\n"); QUIT; } if(_decode > 0) read_decode_eeprom(ftdi,_debug); eeprom_buf = malloc(my_eeprom_size); ftdi_get_eeprom_buf(ftdi, eeprom_buf, my_eeprom_size); if (eeprom_buf == NULL) { fprintf(stderr, "Malloc failed, aborting\n"); goto cleanup; } if (filename != NULL && strlen(filename) > 0) { FILE *fp = fopen (filename, "wb"); printf("Writing eeprom data to %s\n",filename); fwrite (eeprom_buf, 1, my_eeprom_size, fp); fclose (fp); } } else { /* if we are erasing... */ printf("Erasing..."); if((f = ftdi_erase_eeprom(ftdi))) { printf("\n"); fprintf(stderr,"FTDI erase eeprom: %d (%s)\n",f, ftdi_get_error_string(ftdi)); QUIT; } } } /* Finish up here */ cleanup: printf("command complete.\n"); if (eeprom_buf) free(eeprom_buf); if((f=ftdi_usb_close(ftdi))) printf("FTDI close: %d (%s)\n", f, ftdi_get_error_string(ftdi)); ftdi_deinit (ftdi); ftdi_free (ftdi); printf("\n"); return return_code; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ int d1,d2; srand(time(NULL)); char name[20]; d1=rand()%6+1; d2=rand()%6+1; printf("What is your name?\n>"); scanf(" %s",name); printf("Hello, %s!\n",name); printf("Rolling the dice...\n"); printf("Dice1: %d \n",d1); printf("Dice2: %d \n",d2); printf("Total value: %d \n",d1+d2); if(d1+d2>7) printf("%s won!\n",name); else printf("%s lost!\n",name); return 0; }
C
#include <stdio.h> #include <string.h> int main(void) { char frase[50]; int espacos = 0; int palavras = 0; int i; printf("Digite uma frase: "); fgets(frase, 50, stdin); // Pegar a frase da string int tamanho = strlen(frase); // Contar o numero de caracteres da string for(i = 0; i < tamanho; i++) { if(frase[i] == ' ') { espacos++; } } palavras = espacos + 1; printf("Há %i palavras na frase.", palavras); return 0; }
C
int Partition(SqList &L, int low, int high) //改进版 { KeyType pivotkey; pivotkey = L.r[low].key; L.r[0] = L.r[low]; while(low < high) { while(low<high && L.r[high].key>=pivotkey) high--; L.r[low] = L.r[high]; //将比关键字小的记录移到低端,曲轴在[0]不动. while(low<high && L.r[low].key<=pivotkey) low++; L.r[high] = L.r[low]; } L.r[low] = L.r[0]; //曲轴记录到位 // int i; // printf("--------------------\n"); // for(i=1; i<=L.length; i++) // printf("%d ", L.r[i].key); // printf("--------------------\n"); return low; }
C
#include <stdio.h> #include <windows.h> #include <assert.h> // 开启 N-API 实验性功能,如:多线程 napi_threadsafe_function #define NAPI_EXPERIMENTAL #include <node_api.h> typedef struct{ napi_async_work work; // 保存线程任务的 napi_threadsafe_function tsfn; // 保存回调函数的 }Addon; /** 调试报错用的 */ static void catch_err(napi_env env, napi_status status) { if (status != napi_ok) { const napi_extended_error_info* error_info = NULL; napi_get_last_error_info(env, &error_info); printf("%s\n", error_info->error_message); exit(0); } } /** 调用 js-callback 用的 */ static void call_js(napi_env env, napi_value js_cb, void* context, void* data) { (void)context; // 用不到它 (void)data; // 用不到它 if (env != NULL) { napi_value undefined, js_prime; napi_get_undefined(env, &undefined); // 创建一个 js 的 undefined catch_err(env, napi_call_function(env, undefined, // js 回调的 this 对象 js_cb, // js 回调函数句柄 0, // js 回调函数接受参数个数 NULL, // js 回调函数参数数组 NULL)); // js 回调函数中如果有 retrun,将会被 result 接受到,NULL 代表忽略 } } /** 执行线程 */ static void execute_work(napi_env env, void* data) { Addon* addon = (Addon*)data; // 拿到 js-callback 函数 catch_err(env, napi_acquire_threadsafe_function(addon->tsfn)); // 延迟四秒执行 Sleep(4000); // 调用 js-callback 函数 catch_err(env, napi_call_threadsafe_function( addon->tsfn, // js-callback 函数 NULL, // call_js 的第四个参数 napi_tsfn_blocking)); // 阻塞模式调用 // 释放句柄 catch_err(env, napi_release_threadsafe_function(addon->tsfn, napi_tsfn_release)); } /** 线程执行完成 */ static void work_complete(napi_env env, napi_status status, void* data) { Addon* addon = (Addon*)data; // 释放句柄 catch_err(env, napi_release_threadsafe_function(addon->tsfn, napi_tsfn_release)); // 回收任务 catch_err(env, napi_delete_async_work(env, addon->work)); addon->work = NULL; addon->tsfn = NULL; } /** * start_thread 启动线程 * 关于 static 关键字用不用都行的,官方的例子有用到 static * 以我 js 的能力我猜的可能是开多个线程下,可以公用一个函数,节约内存开销 (欢迎大神来讨论 😭) */ static napi_value start_thread(napi_env env, napi_callback_info info) { size_t argc = 1; // js 传进来的参数个数 napi_value js_cb; // js 传进来的回调函数 napi_value work_name; // 给线程起个名字 Addon* addon; // “实例化” 结构体 (个人理解是取出了传进来的 js-cabllback 地址指针,期待大神来讨论 😭) napi_status sts; // 程序执行状态 sts = napi_get_cb_info( env, // 执行上下文,可以理解为 js 那个 “事件环” info, // 上下文信息 &argc, // 收到参数的个数 &js_cb, // 接收 js 参数 NULL, // 接收 js 的 this 对象 (void**)(&addon) // 取得 js 传进来的 callback 的指针地址 ); catch_err(env, sts); // 打酱油的 ^_^ assert(addon->work == NULL && "Only one work item must exist at a time"); // 创建线程名字 catch_err(env, napi_create_string_utf8(env, "N-API Thread-safe Call from Async Work Item", NAPI_AUTO_LENGTH, &work_name)); // 把 js function 变成任意线程都可以执行的函数 // 酱紫我们就可以在开出来的子线程中调用它咯 sts = napi_create_threadsafe_function(env, // 其他线程的 js 函数 // call_js 的第二个参数 // 也就是我们 addon.start(function) 传进来的 function js_cb, // 可能传递给一些异步任务async_hooks钩子传递初始化数据 (期待大神讨论 😊) // 个人理解 N-API 中的 async 指的就是多线程任务 // 一个线程任务,在 N-API 中由 async work 调用 NULL, work_name, // 给线程起个名字,给 async_hooks 钩子提供一个标识符 0, // (官网直译)最大线程队列数量,0 代表没限制 1, // (官网直译)初始化线程数量,其中包括主线程 NULL, // (官网直译)线程之间可以传递数据(官网直译) NULL, // (官网直译)线程之间可以传递函数,函数注销时候被调用 NULL, // (官网直译)附加给函数的执行上下文,应该就是 call_js, // call_js 的第三个参数 &(addon->tsfn)); // js 传进来的函数,可以理解为真实的 js 函数所在内存地址 (期待大神讨论 😊) catch_err(env, sts); // 负责执行上面创建的函数 sts = napi_create_async_work(env, NULL, // 可能传递 async_hooks 一些初始化数据 work_name, // 给线程起个名字,给 async_hooks 钩子提供一个标识符 execute_work, // 线程执行时候执行的函数 (与主线程并行执行) work_complete, // 线程执行完时候的回调 addon, // 既 execute_work、work_complete 中的 void* data &(addon->work)); // 线程句柄 catch_err(env, sts); // 将线程放到待执行队列中 sts = napi_queue_async_work(env, // 要执行线程的句柄 addon->work); catch_err(env, sts); return NULL; // 这个貌似是返回给 js-callback 的返回值 } napi_value init(napi_env env, napi_value exports) { // 这里等价于 const obj = new Object(); // 这回知道面向对象是咋来的了吧 😁 // 类的本质就是“结构体”演化而来的,new(开辟堆内存空间) 关键字是 malloc(申请内存空间) 变种过来的 Addon* addon = (Addon*)malloc(sizeof(*addon)); // 等价于 obj.work = null; addon->work = NULL; // 个人 js 水平有限,Object 类研究的不深 // 可以说,精通 Object 类的小伙伴可以自己想想咯,反正给对象挂一个属性、函数需要的东东,都在这里了 // 相等于 const fun = () => {}, attr = 'Hello'; napi_property_descriptor desc = { "start", // 属性名称 NULL, // -- 没想明白 start_thread, // 函数体 NULL, // 属性 getter NULL, // 属性 setter NULL, // 属性描述符 napi_default, addon // (官网直译)也可以写 NULL,调用 getter 时候返回的数据 }; // 相当于 const obj = { fun, attr }; napi_define_properties(env, exports, 1, &desc); // 将属性挂载到 exports 上面 } NAPI_MODULE(NODE_GYP_MODULE_NAME, init) // 配合另一种导出模块用的 //static void addon_getting_unloaded(napi_env env, void* data, void* hint) { // Addon* addon = (Addon*)data; // assert(addon->work == NULL && "No work in progress at module unload"); // free(addon); //} // 另一种导出模块的宏定义(有空再研究🙃) //NAPI_MODULE_INIT() { // Addon* addon = (Addon*)malloc(sizeof(*addon)); // addon->work = NULL; // // napi_property_descriptor desc = { // "start", // NULL, // start_thread, // NULL, // NULL, // NULL, // napi_default, // addon // }; // // napi_define_properties(env, exports, 1, &desc); // napi_wrap(env, exports, addon, addon_getting_unloaded, NULL, NULL); // // return exports; // 可写可不写 //}
C
//#include<iostream> //using namespace std; #include"heap.h" //void Swap(int* p1, int* p2) //{ // int tmp = *p1; // *p1 = *p2; // *p2 = tmp; //} // //void AdjustDown(int* a, int n, int parent) //{ // int child = parent * 2 + 1; // while (child < n) // { // //ѡҺСǸ // if (child+1 < n && a[child + 1] > a[child]) // { // child++;//ѡұߵ // }//ߵ // if (a[parent] < a[child]) // { // Swap(&a[parent], &a[child]); // parent = child;// // child = parent * 2 + 1;// // } // else // { // break;//Ѿ // } // } //} // 򽨴 //void HeapSort(int* a, int n) //{ // //--ʱ临ӶO(N) // for (int i = (n - 1 - 1) / 2; i >= 0; i--) // { // AdjustDown(a, n, i); // } // int end = n - 1; // while (end>0) // { // Swap(&a[0], &a[end]); // //ѡδ // AdjustDown(a, end, 0); // end--; // } //} //void TopK() //{ // //ҳnСǰk // //} int main() { //int a[] = { 27,15,19,18,28,34,65,49,25,37 }; int a[] = { 15,18,28,34,65,19,49,25,37,27 }; int n = sizeof(a) / sizeof(a[0]); //AdjustDown(a, n, 0); // //for (int i = (n - 1 - 1) / 2; i >= 0; i--) //{ // AdjustDown(a, n, i); //} //HeapSort(a, n); HP hp; HeapInit(&hp, a, n); HeapPrint(&hp); HeapPush(&hp, 8); HeapPrint(&hp); HeapPush(&hp, 88); HeapPrint(&hp); HeapPop(&hp); HeapPrint(&hp); HeapDestroy(&hp); return 0; }
C
/** * generate.c * * Generates pseudorandom numbers in [0,MAX), one per line. * * Usage: generate n [s] * * where n is number of pseudorandom numbers to print * and s is an optional seed */ #define _XOPEN_SOURCE #include <cs50.h> #include <stdio.h> #include <stdlib.h> #include <time.h> // upper limit on range of integers that can be generated #define LIMIT 65536 int main(int argc, string argv[]) { // condition to check for correct input from user, and to print correct usage instructions otherwise if (argc != 2 && argc != 3) { printf("Usage: ./generate n [s]\n"); return 1; } // converts the string passed from main into an integer in order to generate n numbers int n = atoi(argv[1]); // checks if the user specified a seed and initialises the random function to be used with the specified seed in the command line(if provdided) else uses the time function if (argc == 3) { srand48((long) atoi(argv[2])); } else { srand48((long) time(NULL)); } // will loop until n numbers have been generated while printing each iteration of random numbers (these are checked against the limit defined at the top and also converted to integers since drand48 returns floating point numbers) for (int i = 0; i < n; i++) { printf("%i\n", (int) (drand48() * LIMIT)); } // success return 0; }
C
#include <led_driver.h> #include <error_handler.h> #include <stdint.h> #include <stdbool.h> const int LED_MIN = 0; const int LED_MAX = 16; static uint16_t *g_address; static uint16_t g_image = 0; static bool isValidLed(unsigned ledNumber) { return (ledNumber >= 0) && (ledNumber < 16); } void LED_Create(uint16_t *address) { g_image = 0; g_address = address; *g_address = g_image; } void LED_On(unsigned ledNumber) { if (isValidLed(ledNumber)) { g_image |= (1 << ledNumber); } else { ERROR("LED out of bounds", ledNumber); } *g_address = g_image; } void LED_Off(unsigned ledNumber) { if (isValidLed(ledNumber)) { g_image &=~ (1 << ledNumber); } else { ERROR("LED out of bounds", ledNumber); } *g_address = g_image; } bool LED_IsOn(unsigned ledNumber) { if (isValidLed(ledNumber)) { return g_image & (1 << ledNumber); } else { ERROR("LED out of bounds", ledNumber); return false; } }
C
#include <stdio.h> #include "stack.h" void parse(char *str); int indexn = 0; int i = 0; stack_256 st; char program[30000] = {0}; char current; int main(int argc, char *argv[]) { if (argc == 2) { parse(argv[1]); } printf("\n"); return 0; } void parse(char *str) { while ((current = str[i])) { if (current == '>') indexn++; else if (current == '<') indexn--; else if (current == '+') program[indexn]++; else if (current == '-') program[indexn]--; else if (current == '.') printf("%c", program[indexn]); else if (current == '[') { push(i++, &st); int end; while (program[indexn]) { parse(str); end = pop(&st); i = pop(&st); } i = end; } else if (current == ']') { push(i, &st); return; } i++; } }
C
#include "minishell.h" void sig_int(int code) { (void)code; if (g_sig.pid == 0) { ft_putstr_fd("\b\b ", STDERR); ft_putstr_fd("\n", STDERR); ft_putstr_fd("\033[0;36m\033[1mminishell ▸ \033[0m", STDERR); g_sig.exit_status = 1; } else { g_sig.exit_status = 130; } g_sig.sigint = 1; } void sig_quit(int code) { char *nbr; nbr = ft_itoa(code); if (g_sig.pid != 0) { ft_putstr_fd("Quit: ", STDERR); ft_putendl_fd(nbr, STDERR); g_sig.exit_status = 131; g_sig.sigquit = 1; } else ft_putstr_fd("\b\b \b\b", STDERR); free(nbr); } void sig_init(void) { g_sig.sigint = 0; g_sig.sigquit = 0; g_sig.pid = 0; g_sig.exit_status = 0; }
C
/**************************************************************************** Elaine Ha Teresa Truong CSE 12, Fall 2019 December 1, 2019 cs12fa19ep cs12fa19cv Assignment Nine File Name: Tree.c Description: This program is an implementation of a binary tree on disk. Unlike the binary tree data structure where TNodes go in the heap, the nodes are held in an immediate search path in memory and everything else is in the filesystem. ****************************************************************************/ #include <stdlib.h> #include <string.h> #include "Tree.h" // Debug messages static const char ALLOCATE[] = " - Allocating]\n"; static const char COST_READ[] = "[Cost Increment (Disk Access): Reading "; static const char COST_WRITE[] = "[Cost Increment (Disk Access): Writing "; static const char DEALLOCATE[] = " - Deallocating]\n"; static const char TREE[] = "[Tree "; template <class Whatever> int Tree<Whatever>::debug_on = 0; template <class Whatever> long Tree<Whatever>::cost = 0; template <class Whatever> long Tree<Whatever>::operation = 0; #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #define THRESHOLD 2 /*========================================================================= Tree Description: This struct includes the constructor to initialize the data fields of a tree and the destructors to delete all TNodes in the tree. It also includes the functions called when the user wants to insert, lookup, remove, and output the TNodes to a tree. Data Fields: friend struct TNode<Whatever> : the TNode struct occupancy: number of nodes that the tree has root: the tree's root tree_count: the tree number debug: whether debug mode is on or off Public functions: Tree(void) - initializes each object in the TNode ~Tree (void) - destructor function to deallocate tree and all the TNodes Set_Debug_On - turns debug on Set_Debug_Off - turns debug off Insert - inserts a TNode Lookup - searches for a TNode Remove - removes a TNode ostream & Write - displays all the TNodes ==========================================================================*/ template <class Whatever> ostream & operator << (ostream &, const TNode<Whatever> &); /*========================================================================= TNode Description: This struct includes the constructor to initialize the data fields of a TNode and the destructors to decrease the occupancy. It also includes the functions called when the user wants to insert, lookup, remove, and output the TNodes in the tree. Data Fields: balance: left child's height - right child's height data: the data to be inserted height: 1 + height of tallest child or 0 for leaf left: left node occupancy: number of nodes that the tree has right: right node tree_count: the tree number Public functions: TNode(const Whatever & element, Tree<Whatever> & theTree) - initializes each object in the TNode for an empty tree TNode(const Whatever & element, TNode<Whatever> & parentTNode) - initializes each object in the TNode for a tree with a root ~TNode (void) - destructor function to decrement occupancy data delete_allTNodes - deletes all nodes of tree Insert - inserts the TNode into the tree Lookup - searches for the TNode ReplaceAndRemoveMin - reorganizes Tree if a TNode has a balance greater than two Remove - Removes the TNode SetHeightAndBalance - calculates height and balance for each TNode ostream & WriteAllTNodes - displays all the TNodes ==========================================================================*/ template <class Whatever> struct TNode { // Friends: // Data fields: Whatever data; // Whatever data long height; // 1 + height of tallest child long balance; // Left child height - right child height offset left; // Left TNode offset right; // Right TNode offset this_position; // Current position // Function fields: TNode () : height (0), balance (0), left (0), right (0), this_position (0) {} // To declare the working TNode in Tree's Remove TNode (Whatever & element) : data (element), height (0), balance (0), left (0), right (0), this_position (0) {} TNode (Whatever &, fstream *, long &); // To add new node to disk TNode (const offset &, fstream *); // To read node from disk unsigned long Insert (Whatever &, fstream *, long &, offset &); // Optional recursive Lookup declaration would go here void Read (const offset &, fstream *); // Read node from disk unsigned long Remove (TNode<Whatever> &, fstream *, long &, offset &, long fromSHB = FALSE); void ReplaceAndRemoveMin (TNode<Whatever> &, fstream *, offset &); void SetHeightAndBalance (fstream *, offset &); void Write (fstream *) const; // Update node to disk ostream & Write_AllTNodes (ostream &, fstream *) const; unsigned long Lookup(Whatever &, fstream *) const; // Look ups a node }; template <class Whatever> void Tree<Whatever> :: Set_Debug_Off(void) /*************************************************************************** % Routine Name : Tree <Whatever> :: Set_Debug_Off % File : Tree.c % % Description : This function sets debug mode off % ***************************************************************************/ { debug_on = FALSE; } template <class Whatever> void Tree<Whatever> :: Set_Debug_On(void) /*************************************************************************** % Routine Name : Tree <Whatever>:: Set_Debug_On % File : Tree.c % % Description : This function sets debug mode on % ***************************************************************************/ { debug_on = TRUE; } template <class Whatever> unsigned long Tree<Whatever> :: Insert (Whatever & element) /*************************************************************************** % Routine Name : Tree <Whatever> :: Insert % File : Tree.c % % Description : This function will insert create the root if it does not % exist. If root already exists, then it will call % TNode's Insert. % % Parameters descriptions : % % name description % ------------------ ------------------------------------------------------ % element The element to insert. % <return> 1 or 0 indicating success or failure of insertion ***************************************************************************/ { // Determines if tree is empty if (occupancy <= 0) { // Creates new node if tree is empty TNode<Whatever>rootTNode(element, fio, occupancy); } else { // If tree is not empty, insert a node under root TNode<Whatever>rootTNode(root, fio); rootTNode.Insert(element, fio, occupancy, root); } // Call IncrementOperation Tree<Whatever>::IncrementOperation(); return 1; } template <class Whatever> unsigned long TNode<Whatever> :: Lookup(Whatever & element, fstream * fio) const /*************************************************************************** % Routine Name : TNode <Whatever>:: Lookup % File : Tree.c % % Description : This function will lookup the element in the binary tree. If % element is found then lookup was successful. % % Parameters descriptions : % % name description % ------------------ ------------------------------------------------------ % element The element to lookup. % <return> 1 or 0 depending on success status of lookup ***************************************************************************/ { // Save the success of lookup long status; // Determine if the element is found if (data == element) { // Update data element = data; return 1; } else { // If element is alphanumerically less than data if (element < data) { // Determine if left node exists if (left){ TNode<Whatever> leftTNode(left, fio); status = leftTNode.Lookup(element, fio); } else { return 0; } // If element is alphanumerically greater than data } else { // Determine if right node exists if (right) { TNode<Whatever> rightTNode(right, fio); status = rightTNode.Lookup(element, fio); } else { return 0; } } } return status; } template <class Whatever> void TNode<Whatever> :: ReplaceAndRemoveMin (TNode<Whatever> & targetTNode, fstream * fio, offset & PositionInParent) /*************************************************************************** % Routine Name : TNode<Whatever> :: ReplaceAndRemoveMin % File : Tree.c % % Description : This function will replace the TNode that is removed % with the minimum TNode. It will find first find the % minimum TNode by recursing to the most left node and % update the POinterInParent and replace the data of the % node with the successor node's data. Finally, it will % delete the successor node. % % Parameters descriptions : % % name description % -------------------------------------------------------------------- % targetTNode TNode to remove % PointerInParent pointer in the parent TNode used to get to the % current node ***************************************************************************/ { // Determines if left node exists if (left) { TNode<Whatever>leftTNode(left,fio); leftTNode.ReplaceAndRemoveMin(targetTNode, fio, left); SetHeightAndBalance(fio, PositionInParent); } else { // Determines if right node exists if (right) { // Update PositionInParent PositionInParent = right; } else { // Update PositionInParent PositionInParent = 0; } // Replace data of node deleted with successor data targetTNode.data = data; } } template <class Whatever> unsigned long TNode<Whatever> :: Remove (TNode<Whatever> & elementTNode, fstream * fio, long & occupancy, offset & PositionInParent, long fromSHB) /*************************************************************************** % Routine Name : TNode<Whatever> :: Remove % File : Tree.c % % Description : This function will remove the element from the binary % tree. If element is found, delete it and then reset % the data. If element is alphabetically greater than % the temporary, then check the right node. If % element is alphabetically greater than the node being % checked, then right node will be checked. Continues % checking until there is nothing under that node. % % Parameters descriptions : % % name description % ------------------ ------------------------------------------------- % elementTNode The element to be removed. % PointerInParent TNode pointer in the parent TNode used to get to % to the current TNode % fromSHB keeps track of whether Remove was called from % SetHeightAndBalance or Remove % <return> 1 if removed, else 0 ***************************************************************************/ { // Saves the success of the Remove long status= 0; // Determines if the node to be removed is found if (elementTNode.data == data) { // Decrement occupancy occupancy--; // If leaf node if (!left && !right) { // Update output parameter and PositionInParent elementTNode.data = data; PositionInParent = 0; return 1; // If only left child exists } else if (left && !right) { // Update output parameter and PositionInParent elementTNode.data = data; PositionInParent = left; return 1; // If only right child exists } else if (!left && right) { // Update output parameter and PositionInParent elementTNode.data = data; PositionInParent = right; return 1; // If both children exist } else if (left && right) { // Update output parameter elementTNode.data = data; // Call RARM TNode<Whatever>rightTNode(right, fio); rightTNode.ReplaceAndRemoveMin(*this, fio, right); // If called from SHAB if (fromSHB == FALSE) { SetHeightAndBalance(fio, PositionInParent); } else { Write(fio); } return 1; } } else { // If alphanumerically greater than current node if (data < elementTNode.data) { // Determines if right node exists if (right) { TNode<Whatever>rChild(right, fio); status = rChild.Remove(elementTNode, fio, occupancy, right); } else { return 0; } // If alphanumerically less than current node } else { // Determines if left node exists if (left) { TNode<Whatever>lChild(right, fio); status = lChild.Remove(elementTNode, fio, occupancy, left); } else { return 0; } } } // Call SHAB if (fromSHB == FALSE) { SetHeightAndBalance(fio, PositionInParent); } return status; } template <class Whatever> unsigned long Tree<Whatever> :: Remove (Whatever & element) /*************************************************************************** % Routine Name : Tree <Whatever>:: Remove % File : Tree.c % % Description : This function will remove the element in the binary tree. If % it is not an empty tree, call TNode's Remove method and % update the output parameter % % Parameters descriptions : % % name description % ------------------ ------------------------------------------------------ % element The element to remove. % <return> 1 or 0 depending on success of removal ***************************************************************************/ { // Success of remove long status = 0; // Determines if list is empty if (occupancy > 0) { // Create a new TNode with the element and call Remove TNode <Whatever> tmp (element); TNode<Whatever> rootTNode(root, fio); status = rootTNode.Remove(tmp, fio, occupancy, root, 0); // Updates the output parameter element = tmp.data; } // If root is removed if (occupancy == 0) { ResetRoot(); } // Call IncrementOperation Tree<Whatever>::IncrementOperation(); return status; } template <class Whatever> void TNode<Whatever> :: SetHeightAndBalance (fstream * fio, offset & PositionInParent) /*************************************************************************** % Routine Name : TNode<Whatever> :: SetHeightAndBalance % File : Tree.c % % Description : This function calculates the height and the balanced % depending on the number of children the node has. It % makes adjustments if the balance is greater than two. % % Parameters descriptions : % % name description % ------------------------------------------------------------------- % PointerInParent TNode pointer in the parent TNode used to get % to the current node ***************************************************************************/ { // Initialize fakeOccupancy local variable long fakeOccupancy = 0; // If only right node exists if (!left && right) { TNode<Whatever>rightTNode(right, fio); // Calculate height and balance balance = -1 - rightTNode.height; height = 1 + rightTNode.height; // If only left node exists } else if (!right && left) { TNode<Whatever>leftTNode(left, fio); // Calculate height and balance balance = leftTNode.height - -1; height = 1 + leftTNode.height; // If both children exist } else if (left && right) { TNode<Whatever>leftTNode(left, fio); TNode<Whatever>rightTNode(right, fio); // Calculate balance balance = leftTNode.height - rightTNode.height; // Calculate height if (leftTNode.height >= rightTNode.height) { height = 1 + leftTNode.height; } else if (leftTNode.height < rightTNode.height) { height = 1 + rightTNode.height; } // If leaf node } else if (!right && !left) { // Set height and balance to 0 balance = 0; height = 0; } // Checks if threshold is violated if (abs(balance) > THRESHOLD) { // Saves the current node Whatever savedElement = data; // Removes the node Remove(*this, fio, fakeOccupancy, PositionInParent, TRUE); // Reinserts the node TNode<Whatever>parentTNode(PositionInParent,fio); parentTNode.Insert(savedElement, fio, fakeOccupancy, PositionInParent); // Write to file } else { Write(fio); } } template <class Whatever> long Tree <Whatever> :: GetCost () /*************************************************************************** % Routine Name : Tree <Whatever> :: GetCost % File : Tree.c % % Description : This function returns the value of the Tree<Whatever>::cost % variable. % % Parameters descriptions : % % name description % ------------------------------------------------------------------------ % <return> Value of cost ***************************************************************************/ { return cost; } template <class Whatever> long Tree <Whatever> :: GetOperation () /*************************************************************************** % Routine Name : Tree <Whatever> :: GetOperation % File : Tree.c % % Description : This function returns the value of the % Tree<Whatever>::operation variable. % % Parameters descriptions : % % name description % ------------------------------------------------------------------------ % <return> Value of operation ***************************************************************************/ { return operation; } template <class Whatever> void Tree <Whatever> :: IncrementCost () /*************************************************************************** % Routine Name : Tree <Whatever> :: IncrementCost % File : Tree.c % % Description : This function increments the value of the % Tree<Whatever>::cost variable. This function should be called % when a read or write to disk occurs. % % Parameters descriptions : % % name description % ------------------------------------------------------------------------ % <return> Void ***************************************************************************/ { cost++; } template <class Whatever> void Tree <Whatever> :: IncrementOperation () /*************************************************************************** % Routine Name : Tree <Whatever> :: IncrementOperation % File : Tree.c % % Description : This function increments the value of the % Tree<Whatever>::operation variable. This function should % be called when a read or write to disk occurs. % % Parameters descriptions : % % name description % ------------------------------------------------------------------------ % <return> Void ***************************************************************************/ { operation++; } template <class Whatever> void Tree <Whatever> :: ResetRoot () /*************************************************************************** % Routine Name : Tree <Whatever> :: ResetRoot % File : Tree.c % % Description : This function resets the root datafield of this tree to % be at the end of the datafile. This should be called when % the last TNode has been removed from the Tree. % % Parameters descriptions : % % name description % ------------------------------------------------------------------------ % <return> Void ***************************************************************************/ { // Move root field to point to EOF fio->seekp(0, ios::end); root = fio->tellp(); } template <class Whatever> unsigned long TNode<Whatever> :: Insert (Whatever & element, fstream * fio, long & occupancy, offset & PositionInParent) /*************************************************************************** % Routine Name : TNode <Whatever>:: Insert % File : Tree.c % % Description : This function will insert the element in the hash table. % If element is on the tree, update it. If element is not on % the tree, call the function recursively until it reaches % the appropriate location and insert the new node after. % Finally, update the height and the balance. % % Parameters descriptions : % % name description % ------------------ ------------------------------------------------------ % element The element to insert. % PointerInParent pointer to parent TNode used to get the current TNode % <return> 1 or 0 indicating success or failure of insertion ***************************************************************************/ { // If element is found if (data == element) { // Update data data = element; // Find } else { // If element is alphanumerically less than data if (element < data) { // If left exists, recursively call Insert if (left) { TNode<Whatever>leftTNode(left, fio); leftTNode.Insert(element, fio, occupancy, left); // If left does not exist, insert new node } else { TNode<Whatever>leftTNode(element, fio, occupancy); left = leftTNode.this_position; } // If element is alphanumerically greater than data } else { // If right exists, recursively call Insert if (right) { TNode<Whatever>rightTNode(right, fio); rightTNode.Insert(element, fio, occupancy, right); // If right does not exist, insert new node } else { TNode<Whatever>rightTNode(element, fio, occupancy); right = rightTNode.this_position; } } } // Call SHAB SetHeightAndBalance(fio, PositionInParent); return 1; } template <class Whatever> unsigned long Tree<Whatever> :: Lookup (Whatever & element) const /*************************************************************************** % Routine Name : Tree <Whatever>:: Lookup % File : Tree.c % % Description : This function will lookup the element in the binary tree. % If it is not an empty tree, call TNode's Lookup method. % % Parameters descriptions : % % name description % ------------------ ------------------------------------------------------ % element The element to lookup. % <return> 1 or 0 depending on success of lookup ***************************************************************************/ { // Initialize local variables long status = 0; // Call IncrementOperation Tree<Whatever>::IncrementOperation(); // Determines if tree is empty if (occupancy > 0) { TNode<Whatever>rootTNode(root, fio); status = rootTNode.Lookup(element, fio); } return status; } template <class Whatever> void TNode<Whatever> :: Read (const offset & position, fstream * fio) /*************************************************************************** % Routine Name : TNode<Whatever> :: Read % File : Tree.c % % Description : This functions reads a TNode which is present on the % datafile into memory. The TNode is read from position. % The TNode's information in the datafile overwrites this % TNode's data. % % Parameters descriptions : % % name description % ------------------------------------------------------------------- % PointerInParent TNode pointer in the parent TNode used to get % to the current node ***************************************************************************/ { // Read from file fio->seekg(position); fio->read((char *) this, sizeof(*this)); Tree < Whatever> :: IncrementCost(); // Debug message: cost read if (Tree<Whatever>::debug_on) { cerr << COST_READ << (const char *) data << "]" << endl; } } template <class Whatever> // read constructor TNode<Whatever> :: TNode (const offset & position, fstream * fio) /*************************************************************************** % Routine Name : TNode<Whatever> :: TNode read constructor % File : Tree.c % % Description : Called when reading a TNode present on disk into memory ***************************************************************************/ { Read (position, fio); } template <class Whatever> //write TNode<Whatever> :: TNode (Whatever & element, fstream * fio, long & occupancy): data (element), height (0), balance (0), left (0), right (0) /*************************************************************************** % Routine Name : TNode<Whatever> :: TNode write constructor % File : Tree.c % % Description : Called when creating a TNode for the first time. ***************************************************************************/ { // Increment occupancy occupancy++; // Write to file fio->seekp(0, ios :: end); this_position = fio->tellp(); Write(fio); } template <class Whatever> void TNode<Whatever> :: Write (fstream * fio) const /*************************************************************************** % Routine Name : TNode<Whatever> :: Write % File : Tree.c % % Description : This functions writes this TNode object to disk at this_position in the datafile. % Parameters descriptions : % % name description % ------------------------------------------------------------------- % PointerInParent TNode pointer in the parent TNode used to get % to the current node ***************************************************************************/ { // Debug message: cost write if (Tree<Whatever>::debug_on) { cerr << COST_WRITE << (const char *) data << "]" << endl; } // Seek and write this fio->seekp(this_position); fio->write( (const char *) this, sizeof(*this) ); Tree< Whatever> :: IncrementCost(); } template <class Whatever> Tree<Whatever> :: Tree (const char * datafile) : fio (new fstream (datafile, ios :: out | ios :: in)) /*************************************************************************** % Routine Name : Tree<Whatever> :: Tree (public) % File : Tree.c % % Description : Allocates the tree object. Checks the datafile to see if % it contains Tree data. If it is empty, root and occupancy % fields are written to the file. If there is data in the % datafile, root and occupancy fields are read into memory. ***************************************************************************/ { // Tree count static long counter; tree_count = ++counter; // Debug message: allocate if (debug_on) { cerr << TREE << tree_count << ALLOCATE; } // Check for empty file fio->seekg (0, ios::beg); offset begin = fio->tellg(); fio->seekg (0, ios::end); offset ending = fio->tellg(); // File is empty if (begin == ending) { // Initialize local variables root = 0; occupancy = 0; // Reserve space for root and occupancy fio->seekp(0, ios::beg); fio->write( (const char*) &root, sizeof(root) ); fio->write( (const char*) &occupancy, sizeof(occupancy) ); root = fio->tellp(); } else { // File has contents // Read root and occupancy fio->seekg (0, ios::beg); fio->read ( (char*) &root, sizeof(root) ); fio->read ( (char*) &occupancy, sizeof(occupancy) ); } } template <class Whatever> Tree<Whatever> :: ~Tree (void) /*************************************************************************** % Routine Name : Tree<Whatever> :: ~Tree (public) % File : Tree.c % % Description : Deallocates memory associated with the Tree. It % will also delete all the memory of the elements within % the table. ***************************************************************************/ { // Write root and occupancy fio->seekp (0, ios::beg); fio->write( (const char *) &root, sizeof(root) ); fio->write( (const char *) &occupancy, sizeof(occupancy) ); // Deallocate fio fio->flush(); delete fio; // Debug message: deallocate if (debug_on) { cerr << TREE << tree_count << DEALLOCATE; } } template <class Whatever> ostream & operator << (ostream & stream, const TNode<Whatever> & nnn) { stream << "at height: :" << nnn.height << " with balance: " << nnn.balance << " "; return stream << nnn.data << "\n"; } template <class Whatever> ostream & Tree<Whatever> :: Write (ostream & stream) const /*************************************************************************** % Routine Name : Tree :: Write (public) % File : Tree.c % % Description : This funtion will output the contents of the Tree table % to the stream specificed by the caller. The stream could be % cerr, cout, or any other valid stream. % % Parameters descriptions : % % name description % ------------------ ------------------------------------------------------ % stream A reference to the output stream. % <return> A reference to the output stream. ***************************************************************************/ { long old_cost = cost; stream << "Tree " << tree_count << ":\n" << "occupancy is " << occupancy << " elements.\n"; fio->seekg (0, ios :: end); offset end = fio->tellg (); // check for new file if (root != end) { TNode<Whatever> readRootNode (root, fio); readRootNode.Write_AllTNodes (stream, fio); } // ignore cost when displaying nodes to users cost = old_cost; return stream; } template <class Whatever> ostream & TNode<Whatever> :: Write_AllTNodes (ostream & stream, fstream * fio) const { if (left) { TNode<Whatever> readLeftNode (left, fio); readLeftNode.Write_AllTNodes (stream, fio); } stream << *this; if (right) { TNode<Whatever> readRightNode (right, fio); readRightNode.Write_AllTNodes (stream, fio); } return stream; }
C
/* * File Name: lisenGetIP.c * Author: sunowsir * Mail: [email protected] * GitHub: github.com/sunowsir * Created Time: 2018年11月16日 星期五 16时37分43秒 */ #include "../include/CreateConnect.h" typedef struct args { LinkList **list; int listNum; } Args; Args arg; void *startListen(void *None) { /* 从配置文件中获取本机IP */ char *localIP = getConf("localIP", CONF_MASTER); if (localIP == NULL) { perror("master.conf error (don't have localIP)"); return NULL; } /* 从配置文件中获取本机监听开启哪个端口 */ char *strLocalPort = getConf("localPort", CONF_MASTER); if (strLocalPort == NULL) { perror("master.conf error (don't have localPort)"); free(localIP); return NULL; } int localPort = StrtoInt(strLocalPort); free(strLocalPort); /* 从配置文件中获取连接上限 */ char *strConnectMax = getConf("connectMax", CONF_MASTER); if (strConnectMax == NULL) { perror("master.conf error (don't have connectMax)"); free(localIP); return NULL; } int connectMax = StrtoInt(strConnectMax); free(strConnectMax); /* 开启监听,等待服务器端连入*/ int sockFd, sockSon; struct sockaddr_in addrSon; char IP[20] = {'\0'}; sockFd = sockServer(localIP, localPort); socklen_t addrSonLen = sizeof(addrSon); free(localIP); while (1) { /* 读取所有链表的长度,获取最短链表(minLenList)和总共连接数(nowConnectNum)。*/ LinkList *minLenList = arg.list[0]; int nowConnectNum = arg.list[0]->length; for (int i = 1; i < arg.listNum; i++) { nowConnectNum += arg.list[i]->length; minLenList = (arg.list[i]->length < minLenList->length ? arg.list[i] : minLenList); } if (nowConnectNum >= connectMax) { sleep(1); continue; } /* 调用accept接受连入 */ sockSon = accept(sockFd, (struct sockaddr *)&addrSon, &addrSonLen); if (sockSon < 0) { break; } memset(IP, '\0', sizeof(IP)); sockGetFromIP(IP, (struct sockaddr_in *)&addrSon); /* 将新建连接插入链表 */ linkInsert(minLenList, IP, sockSon); } close(sockFd); return NULL; } pthread_t CreateConnect(LinkList **list, int num) { pthread_t thread; arg.list = list; arg.listNum = num; if (pthread_create(&thread, NULL, (void *)startListen, NULL)) { perror("listenGetIP : \033[1;31mcreate thread error\033[0m"); return -1; } return thread; }
C
#include <stdio.h> #include <stdlib.h> struct Object { int *nums; int len; }; struct ListNode { int val; struct ListNode *next; }; struct ListNode *make_list(int *nums, int size) { int i; struct ListNode dummy; struct ListNode *prev = &dummy; dummy.next = NULL; for (i = 0; i < size; i++) { struct ListNode *node = malloc(sizeof(*node)); node->val = nums[i]; node->next = NULL; prev->next = node; prev = node; } return dummy.next; } void print_list(struct ListNode *head) { char *s = ""; while (head != NULL) { printf("%s%d", s, head->val); s = "->"; head = head->next; } } void free_list(struct ListNode *head) { struct ListNode *tmp; while (head != NULL) { tmp = head; head = head->next; free(tmp); } } void traverse(struct ListNode *dummy, struct ListNode *end) { if (dummy == NULL || dummy->next == end) { return; } struct ListNode *pivot = dummy->next; struct ListNode *prev = pivot; struct ListNode *p = pivot->next; struct ListNode *first = NULL; while (p != end) { if (p->val >= pivot->val) { if (first == NULL && p->val > pivot->val) { first = prev; } prev = p; p = p->next; } else { prev->next = p->next; p->next = dummy->next; dummy->next = p; p = prev->next; } } traverse(dummy, pivot); traverse(first, end); } struct ListNode *sort_list(struct ListNode *head) { struct ListNode dummy; dummy.next = head; traverse(&dummy, NULL); return dummy.next; } int main(int argc, char **argv) { int nums1[] = { 4, 2, 1, 3 }, len1 = sizeof(nums1) / sizeof(int); int nums2[] = { -1, 5, 3, 4, 0 }, len2 = sizeof(nums2) / sizeof(int); struct Object inputs[] = { { .nums = nums1, .len = len1 }, { .nums = nums2, .len = len2 }, }; int i, len = sizeof(inputs) / sizeof(struct Object); for (i = 0; i < len; i++) { int *nums = inputs[i].nums; int size = inputs[i].len; struct ListNode *head = make_list(nums, size); printf("\n Input: "); print_list(head); head = sort_list(head); printf("\n Output: "); print_list(head); printf("\n"); free_list(head); } return EXIT_SUCCESS; }
C
/* Author : Naoki Kishi (KUEE 2T13) GitHub URL : https://github.com/naoki-kishi/cpro2018 */ #include <stdio.h> #include <stdlib.h> //プロトタイプ宣言 int input(char str); int cnr(int n,int r); int main(void){ int n = input('n'); int r = input('r'); int ans = cnr(n,r); printf("%d",ans); return 0; } int input(char str){ int count = 0; int n = 0; int error = 0; do{ printf("%c = ",str); count = scanf("%d",&n); //エラー処理 if(count != 1){ scanf("%*s"); error = 1; }else if(n < 0){ error = 1; }else{ error = 0; } if(error){ printf("Invalid input\n"); } }while(error); return n; } int cnr(int n,int r) { if(r == 0 || (n-r == 0)){ return 1; }else{ return cnr(n-1,r-1) + cnr(n-1,r); } }
C
/* 1- typedef struct Nodo_ .... Nodo 2- definire la lista come puntatore al primo nodo Nodo *lista; 3- passare l'indirizzo della lista alla funzione crea lista e aggiungi elemento &lista 4- definire tutte le funzioni con il doppio puntatore **lista 5- se si devono fare modifiche al primo elemento HEAD modificare il contenuto della variabile lista (*lista) con l'indirizzo della variabile nuovo_nodo 6- PROFIT, senza uso di return,strutture wrapper e altre shenanigans, è necessario di tenere conto di altre variabili nel main */ #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Nodo_ { int id; char *Nome; struct Nodo_ *next; struct Nodo_ *last; } Nodo; int inserimento_ordinato_id(Nodo **lista, int num_elementi, int id, char *Nome); void stampa_lista(Nodo **lista, int num_elementi); int main() { Nodo *lista; //creiamo una lista vuota con un nodo allocato, server pe far funzionare la mancanza di un puntatore testa con wrapper int id; char Nome[10]; //esempio di inseritmento_in_coda int num_elementi = 0; printf("Inserisci ID e il Nome, quando vuoi terminare scrivi id e Nome (0)\n"); while (1) { puts("ID:"); scanf("%d", &id); if (id == 0) { break; } puts("Nome:"); scanf("%s", Nome); num_elementi = inserimento_ordinato_id(&lista,num_elementi,id,Nome); //inserisci gli elementi nella lista e ritorna per comodità il numero di elementi puts("\n"); } //stampiamo la lista stampa_lista(&lista,num_elementi); return 0; } //ordinamento è piu' complicato rispetto all'uso di una struttura wrapper int inserimento_ordinato_id(Nodo **lista, int num_elementi, int id, char *Nome) { Nodo *nuovo_nodo = malloc(sizeof(Nodo)); nuovo_nodo->id=id; nuovo_nodo->Nome=strdup(Nome); if (num_elementi == 0) { nuovo_nodo->next=NULL; //modifico il contenuto della variabile lista con l'indirizzo della variabile nuovo_nodo *lista = nuovo_nodo; return num_elementi+1; } Nodo *elemento_corrente = *lista; Nodo *elemento_precedente = NULL; int a = 0; for (a=0; a<num_elementi; a++) { if (id < elemento_corrente->id) { break; } elemento_precedente = elemento_corrente; elemento_corrente = elemento_corrente->next; } if ( elemento_corrente==NULL) { //in questo caso sarebbe l'ultimo elemento elemento_precedente->next=nuovo_nodo; } else { //in questo caso sarebbe il penultimo elemento if (elemento_precedente==NULL) { nuovo_nodo->next=elemento_corrente; //modifico il contenuto della variabile lista con l'indirizzo della variabile nuovo_nodo *lista=nuovo_nodo; return num_elementi+1; } elemento_precedente->next = nuovo_nodo; nuovo_nodo->next=elemento_corrente; } return num_elementi+=1; } void stampa_lista(Nodo **lista, int num_elementi) { Nodo *elemento_corrente = *lista; puts("\n"); if (num_elementi == 0) { puts("Lista Vuota\n"); } for (int a=0; a<num_elementi; a++) { printf("ID: %d - Nome: %s\n", elemento_corrente->id, elemento_corrente->Nome); elemento_corrente=elemento_corrente->next; } puts("\n"); }
C
#include <stdio.h> #include <stdlib.h> // gcc -o out.bin arrayptr.c -Wall /* prints: p = ffffcc20 a = &a = &a[0] = ffffcc20 ffffcc20 ffffcc20 &p = ffffcc18 p = ffffcc28 */ int main() { int a[] = { 1, 2, 3, 4, 5 }; int * p; p = a; printf("p = %08x\n", p); printf("a = &a = &a[0] = %08x %08x %08x\n", a, &a, &a[0]); printf("&p = %08x &p[0] = %08x &p[1] = %08x\n", &p, &p[0], &p[1]); printf("&p = %08x &p + 1 = %08x &p + 2 = %08x\n\n", &p, &p + 1, &p + 2); // Wrong! I'm screwed. I thought this would store // the address of a[2] into p but instead // it stored the value at a[2]. As in the // C book: p[i] is the same as *(p + i) p = a[2]; // p is no longer storing an address! FUCKED p = &a[2]; // ok! printf("p = %08x\n", p); }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> #include <openssl/conf.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/aes.h> #include <openssl/bio.h> #include <openssl/hmac.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <assert.h> #include <error.h> //Global unsigned char key[32], iv[32]; /*Function definitions*/ int aes_init(unsigned char* pwd, unsigned int pwd_len, unsigned char *salt,EVP_CIPHER_CTX *e_ctx, EVP_CIPHER_CTX *d_ctx); void readable(char *str); void write_file_plaintext(); unsigned int hash(const char *mode, const char* dataToHash, size_t dataSize, unsigned char* outHashed); void handle_errors(); /*********************/ /*generating key and IV*/ int aes_init(unsigned char* pwd, unsigned int pwd_len, unsigned char *salt,EVP_CIPHER_CTX *e_ctx, EVP_CIPHER_CTX *d_ctx) { int i, rounds = 1; /* rounds */ //unsigned char key[32], iv[32]; i = EVP_BytesToKey(EVP_aes_256_cbc(),EVP_sha1(),salt,pwd,pwd_len,rounds,key,iv); if(i != 32) //256 bits { printf("\n Error,Incorrect key size generated:%d:\n",i); return -1; } printf("IV is : "); //want to see randomness then use -> printf("IV is : %s\n",iv); readable(iv); printf("Key is : "); readable(key); EVP_CIPHER_CTX_init(e_ctx); EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), NULL, key, iv); EVP_CIPHER_CTX_init(d_ctx); EVP_DecryptInit_ex(d_ctx, EVP_aes_256_cbc(), NULL, key, iv); return 0; } /*******************/ /*Hashing the passphrase to generate salt*/ unsigned int hash(const char *mode, const char* dataToHash, size_t dataSize, unsigned char* outHashed) { unsigned int md_len = -1; const EVP_MD *md = EVP_get_digestbyname(mode); if(NULL != md) { EVP_MD_CTX mdctx; EVP_MD_CTX_init(&mdctx); EVP_DigestInit_ex(&mdctx, md, NULL); EVP_DigestUpdate(&mdctx, dataToHash, dataSize); EVP_DigestFinal_ex(&mdctx, outHashed, &md_len); EVP_MD_CTX_cleanup(&mdctx); } return md_len; } /*******************/ /*generating plaintext user input file*/ void write_file_plaintext() { char junk[10]; char data[200]; FILE *fp; printf("Give the file contents and hit enter when you are done.."); gets(junk); //such pathetic \n char ! gets(data); fp = fopen("plaintext","w+"); if (fp == NULL) { printf("\nFailed to open or create file.\n"); fclose(fp); exit(0); } fprintf(fp,"%s",data); printf("File created!\n"); fclose(fp); } /*******************/ /*Make things visible convert things to base 64*/ void readable(char *str) { BIO *bio, *b64; b64 = BIO_new(BIO_f_base64()); bio = BIO_new_fp(stdout, BIO_NOCLOSE); BIO_push(b64, bio); BIO_write(b64, str, strlen(str)); BIO_flush(b64); BIO_free_all(b64); } /*******************/ /*Make things visible and store in file*/ void readable1(char *str) { FILE *try; try = fopen("hmac1","w+"); BIO *bio, *b64; b64 = BIO_new(BIO_f_base64()); //bio = BIO_new_fp(stdout, BIO_NOCLOSE); bio = BIO_new_fp(try, BIO_NOCLOSE); BIO_push(b64, bio); BIO_write(b64, str, strlen(str)); BIO_flush(b64); BIO_free_all(b64); fclose(try); } /*******************/ /******Calculating HMAC of non encrypted data*******/ calc_hmac(char *str1,char *key) { int i; char temp[200]; strncpy(temp,str1,200); // Be careful of the length of string with the choosen hash engine. SHA1 needed 20 characters. // Change the length accordingly with your choosen hash engine. unsigned char* result; unsigned int len = 20; result = (unsigned char*)malloc(sizeof(char) * len); HMAC_CTX ctx; HMAC_CTX_init(&ctx); // Using sha1 hash engine here. // You may use other hash engines. e.g EVP_md5(), EVP_sha224, EVP_sha512, etc HMAC_Init_ex(&ctx, key, strlen(key), EVP_sha1(), NULL); HMAC_Update(&ctx, (unsigned char*)&temp, strlen(temp)); HMAC_Final(&ctx, result, &len); HMAC_CTX_cleanup(&ctx); printf("HMAC digest: "); for (i = 0; i != len; i++) printf("%02x", (unsigned int)result[i]); printf("\n"); free(result); } /****************************/ /************Decrypt Engine***************/ int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,unsigned char *iv, unsigned char *plaintext) { EVP_CIPHER_CTX *ctx; int len; int plaintext_len; /* Create and initialise the context */ if(!(ctx = EVP_CIPHER_CTX_new())) { printf("Error in context initialization step 1!\n"); exit(0); } /* Initialise the decryption operation. IMPORTANT - ensure you use a key * and IV size appropriate for your cipher * In this example we are using 256 bit AES (i.e. a 256 bit key). The * IV size for *most* modes is the same as the block size. For AES this * is 128 bits */ if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) { printf("Error in context initialization step 2!\n"); exit(0); } /* Provide the message to be decrypted, and obtain the plaintext output. * EVP_DecryptUpdate can be called multiple times if necessary */ if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) { printf("Error in context initialization step 3!\n"); exit(0); } plaintext_len = len; //EVP_CIPHER_CTX_set_padding(&de, 0); /* Finalise the decryption. Further plaintext bytes may be written at * this stage. */ if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) { printf("Error in context initialization step 4!\n"); //Check this it fails here. //handle_errors(); //exit(0); } plaintext_len += len; /* Clean up */ EVP_CIPHER_CTX_free(ctx); return plaintext_len; } /*****************************************/ /*Main Function*/ int main() { OpenSSL_add_all_algorithms(); int i=0; int decryptedtext_len, ciphertext_len; FILE *p; char passphrase[10],passphrase_check[15]; unsigned char salt[20],ciphertext[128],decryptedtext[128],e_fc[128]; int passphrase_check_len = 0 , passphrase_len=0 , fd=0; //fd --> file descriptor EVP_CIPHER_CTX en,de; /* The EVP structure which keeps track of all crypt operations see evp.h for details */ int big_match_salt = 0; int big_match_hmac = 0; printf("Enter the passphrase (len < 10): "); scanf("%s",passphrase_check); passphrase_check_len = strlen(passphrase_check); if(passphrase_check_len < 10) { strncpy(passphrase,passphrase_check,10); passphrase_len = strlen(passphrase); printf("Your passphrase is : %s\n",passphrase); } else { printf("Passphrase length increased over limit. Exiting now. . .\n"); exit(1); } //generating salt hash("SHA1", passphrase, passphrase_len, salt); printf("Salt is SHA1(Passphrase) : "); for(i=0; i<sizeof(salt)/sizeof(salt[0]); i++) { printf("%02x", salt[i]); } printf("\n"); unsigned char temp_salt[20],temp_base64[200]; //Reading the saved SALT. FILE *fp3; fp3 = fopen("salt","rb+"); if(fp3 == NULL) { printf("Unable to check salt value."); fclose(fp3); exit(1); } else { while(!feof(fp3)) { fread(temp_salt,20,1,fp3); } } fclose(fp3); //printf("Salt old : %s\n",temp_salt); //printf("Salt new : %s\n",salt); int l,g=0,h=0; for(l=0;l<strlen(salt);l++) { if(salt[l]!=temp_salt[l]) { //printf("Not Equal\n"); g++; //break; } else { //printf("Equal\n"); } } if(g<=1) { printf("Salts match!\n"); big_match_salt = 1; } else { printf("Salts don't match!\n"); } /////////////Checking the integrity of file///////////// //reading the ciphertext contents. p=fopen("ciphertext","rb+"); if(p == NULL) { printf("Unable to open file."); exit(1); } else { do { fread(e_fc,128,1,p); }while(!feof(p)); } fclose(p); readable1(e_fc); //hmac encryption wali side se. FILE *fp4; unsigned char base64[200]; fp4 = fopen("hmac","rb+"); if(fp4 == NULL) { printf("Unable to check salt value."); fclose(fp4); exit(1); } else { while(!feof(fp4)) { fread(base64,200,1,fp4); } } fclose(fp4); //hmac of this file FILE *fp7; fp7 = fopen("hmac1","rb+"); if(fp7 == NULL) { printf("Unable to check salt value."); fclose(fp7); exit(1); } else { while(!feof(fp7)) { fread(temp_base64,200,1,fp7); } } fclose(fp7); for(l=0;l<strlen(salt);l++) { if(base64[l]!=temp_base64[l]) { //printf("Not Equal\n"); h++; } else { //printf("Equal\n"); } } if(h<=1) { printf("HMAC matched!\n"); big_match_hmac = 1; } else { printf("HMAC don't match!\n"); } //////////////////////////////////////////////////////// int len_of_e_fc=0,k; if((big_match_hmac && big_match_salt)==1) { printf("+------------------------------------------------+\n"); printf("...Decryption Allowed...\n"); printf("+------------------------------------------------+\n"); //now generating key and IV if(aes_init(passphrase,passphrase_len,(unsigned char*) salt,&en,&de)) /* Generating Key IV and set EVP struct */ { perror("\n Error, Cant initialize key and IV:"); return -1; } //calc length of the e_fc printf("cipher from file --> %s\n",e_fc); /* for(k=0;k<strlen(e_fc);k++) { printf("%02x",(unsigned int)e_fc[k]); len_of_e_fc++; } printf("\nLen is : %d\n",len_of_e_fc); */ //decrypt the contents now decryptedtext_len = decrypt(e_fc,112, key, iv,decryptedtext); //printf("len of decrypt:%d\n",decryptedtext_len); //decrypt(e_fc,128, key, iv,decryptedtext); /* Add a NULL terminator. We are expecting printable text */ //decryptedtext[decryptedtext_len] = '\0'; decryptedtext[16] = '\0'; /* Show the decrypted text */ printf("Decrypted text is : "); printf("%s\n", decryptedtext); EVP_CIPHER_CTX_cleanup(&en); EVP_CIPHER_CTX_cleanup(&de); } else { printf("...Sorry Decryption is not allowed...\n"); } return 0; } void handle_errors() { FILE *fp10; char buf[50]; fp10 = fopen("plaintext","r+"); if(fp10 == NULL) { //printf("Unable to check salt value."); fclose(fp10); exit(1); } else { while(!feof(fp10)) { fread(buf,50,1,fp10); } } fclose(fp10); printf("Decrypted text is:"); printf("%s\n", buf); exit(0); } //http://stackoverflow.com/questions/10391610/issues-with-encrypting-a-file-using-openssl-evp-apiaes256cbc
C
//Write a C Program to arrange the elements in ascending order. #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int i,j,temp,n,a[10]; scanf("%d", &n); for (i = 0; i < n; i++) scanf("%d", &a[i]); for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } for (i = 0; i < n; i++) printf("%d ",a[i]); return 0; }
C
#ifndef __LINK_H__ #define __LINK_H__ #include <stdio.h> #include <stdlib.h> typedef int DataType; typedef struct node { DataType Data; struct node * pNext; }LinkNode; typedef struct list { LinkNode *pHead; int cLen; }LinkList; #endif
C
// // Created by souso on 12/12/2017. // #include <stdio.h> #include "SortingFunc.h" #include "../Helpers.h" void bubble_sort(int *arr) { printf("Sorting using Bubble Sort"); int num = sizeof(arr) - 1; for (int i = 0; i < num; ++i) { for (int j = 0; j < num - i - 1; ++j) { if (arr[j] > arr[j + 1]) { swap(&arr[j], &arr[j + 1]); } } } } void selection_sort(int *arr) { printf("Sorting using Selection Sort"); int big, key; int n = sizeof(arr) - 1; for (key = n - 1; key >= 1; key--) { big = find_max(arr, key); swap(&arr[big], &arr[key]); } } int find_max(int *arr, int key) { int max = 0; for (int i = 0; i <= key; ++i) { if (arr[i] > arr[max]) max = i; } return max; } void merge_sort(int *arr) { printf("Sorting using Selection Sort"); int curr_size; int left_start; int n = sizeof(arr) - 1; for (curr_size = 1; curr_size <= n - 1; curr_size = 2 * curr_size) { for (left_start = 0; left_start < n - 1; left_start += 2 * curr_size) { int mid = left_start + curr_size - 1; int right_end = min(left_start + 2 * curr_size - 1, n - 1); merge(arr, left_start, mid, right_end); } } } int min(int x, int y) { return (x < y) ? x : y; } void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; int L[n1], R[n2]; for (int n = 0; n < n1; ++n) { L[n] = arr[l + n]; } for (int i1 = 0; i1 < n2; ++i1) { R[i1] = arr[m + 1 + i1]; } i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void insertion_sort(int *arr) { printf("Sorting using Insertion Sort"); int tmp, k, j; for (k = 0; k < sizeof(arr) - 1; ++k) { tmp = arr[k]; j = k - 1; while (tmp < arr[j] && j >= 0) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = tmp; } } void quick_sort(int *arr) { printf("Sorting using Quick Sort"); int low = 0, high = sizeof(arr) - 2; int stack[high - low + 1]; int top = -1; stack[++top] = low; stack[++top] = high; while (top >= 0) { high = stack[top--]; low = stack[top--]; int p = partition(arr, low, high); if (p - 1 > low) { stack[++top] = low; stack[++top] = p - 1; } if (p + 1 < high) { stack[++top] = p + 1; stack[++top] = high; } } } int partition(int *arr, int low, int high) { int pivot = arr[high]; int i = (low - 1); for (int j = low; j < high; ++j) { if (arr[j] <= pivot) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return i + 1; }
C
#define MASK 0b11011111 int nc_toupper(int c) { char tmp = (char)c; if (tmp >= 'a' && tmp <= 'z') tmp &= MASK; return tmp; }
C
#include <stdio.h> #include "fdl_file.h" #include "fdl.tab.h" fdl_file add_to_file(fdl_file file, token token) { fdl_file new = (fdl_file)malloc(sizeof(struct fdl_file_s)); new->next = file; new->head = token; return new; } void print_parse(fdl_file file) { while(file->next != NULL) { print_tree(file->head,0); printf("\n"); file = file->next; } }
C
/**Write a function to compute the value of the derivative of a polynomial, P(x), of degree n, in a given point x=x0. The degree, and the coefficients of the polynomial, and the point, x0, will be passed as parameters. You must use pointers */ #include <stdio.h> #include <stdlib.h> #include <math.h> void read(int *vect, int size, int *x) { printf("Read the value x: "); vscanf("%d", &x); printf("Read the coefficients of the polynomial: "); for(int i = 0; i <= size; i++) { scanf("%d", &vect[i]); } } void valueDev(int *pol, int degree, int x, double *valueX) { for(int i = 0; i <= degree - 1; i++) { *valueX = *valueX + (double)(((i + 1) * pol[i + 1]) * pow(x, i)); } } int main() { int degree, x; double val = 0; printf("Read the degree of the polynomial: "); scanf("%d", &degree); int *pol = (int *)malloc(sizeof(int) * (degree + 1)); read(pol, degree, &x); printf("%d\n\n\n", x); valueDev(pol, degree, x, &val); printf("The value is: %lf", val); return 0; }
C
//dang in ra phu thuoc vao dac ta #include <stdio.h> main(){ int x = 360, y= -1; long yl=-11; char *vb = "pro\0grammer"; double dx= 3.14159265; printf("\nx= %010d\nx=%-010d\nx=%10o\nx%010o",x,x,x,x); printf("\nx=%-10d\nx=-010x",x,x); printf("\n\yl=%ld\ny=%10u\ny%10o\ny=%10x",y,y,y,y); printf("\n\nyl=%ld\nyl=%10lu\lyl=%10lo\ny=%-10lx",yl,yl,yl,yl); printf("\n\ndx=%010f\ndx=%010.3f\ndx=%-010.3f",dx,dx,dx); printf("\n\ndx=%10.8f\ndx=%10.0f\ndx%10g",dx,dx,dx); printf("\ndx=%10e\ndx=%10.2e",dx,dx); printf("\n\n%10s\n%10.7s\n%-10.7s\n%010.4s\n%10.0s",vb,vb,vb,vb,vb); printf("\n%0.3s\n%-010.3s",vb,vb); printf("%s",vb); }
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 */ typedef struct TYPE_4__ TYPE_1__ ; /* Type definitions */ struct TYPE_4__ {scalar_t__ lookahead; scalar_t__ tok; int /*<<< orphan*/ lookaheadval; int /*<<< orphan*/ tokval; int /*<<< orphan*/ linenumber; int /*<<< orphan*/ lastline; } ; typedef TYPE_1__ LexState ; /* Variables and functions */ scalar_t__ LJ_LIKELY (int) ; scalar_t__ TK_eof ; scalar_t__ lex_scan (TYPE_1__*,int /*<<< orphan*/ *) ; void lj_lex_next(LexState *ls) { ls->lastline = ls->linenumber; if (LJ_LIKELY(ls->lookahead == TK_eof)) { /* No lookahead token? */ ls->tok = lex_scan(ls, &ls->tokval); /* Get next token. */ } else { /* Otherwise return lookahead token. */ ls->tok = ls->lookahead; ls->lookahead = TK_eof; ls->tokval = ls->lookaheadval; } }
C
#include "mpi.h" #include <stdio.h> enum { false, true }; enum { EX_TAG, INTERCOMM_TAG, INTERCOMM_P2P }; int main (int argc, char* argv[]) { int numprocs, rank; MPI_Init (&argc, &argv); MPI_Comm_size (MPI_COMM_WORLD, &numprocs); MPI_Comm_rank (MPI_COMM_WORLD, &rank); printf ("world procs = %d, world rank = %d\n", numprocs, rank); MPI_Group group0, group01, group23, group12; MPI_Comm comm0; MPI_Comm comm01; MPI_Comm comm23; MPI_Comm comm12; MPI_Group groupWorld; int ranks0[1] = {0}; int ranks01[2] = {0, 1}; int ranks23[2] = {2, 3}; int ranks12[2] = {1, 2}; // get the universal group from MPI_COMM_WORLD MPI_Comm_group (MPI_COMM_WORLD, &groupWorld); // create groups from the universal group MPI_Group_incl (groupWorld, 1, ranks0, &group0); MPI_Group_incl (groupWorld, 2, ranks01, &group01); MPI_Group_incl (groupWorld, 2, ranks23, &group23); MPI_Group_incl (groupWorld, 2, ranks12, &group12); // show that the first group size = 2 irregardless of the rank int size; MPI_Group_size (group01, &size); printf ("group01 size = %d from rank %d\n", size, rank); // get the relative rank number of the first group int g01_rank; MPI_Group_rank (group01, &g01_rank); // get the relative rank number of the second group int g23_rank; MPI_Group_rank (group23, &g23_rank); // get the relative rank number of the third group int g12_rank; MPI_Group_rank (group12, &g12_rank); if (g12_rank == MPI_UNDEFINED) { printf ("third group rank is undefined for absolute rank %d\n", rank); } else { printf ("group rank = %d for absolute rank %d\n", g12_rank, rank); } int g0_rank; MPI_Group_rank (group0, &g0_rank); // union groups 1 and 3 MPI_Group group01u12; int g1u3_rank; MPI_Group_union (group01, group12, &group01u12); MPI_Group_rank (group01u12, &g1u3_rank); if (g1u3_rank != MPI_UNDEFINED) printf ("group01u12 contains absolute rank %d via relative rank %d\n", rank, g1u3_rank); // union groups 1 and 2 MPI_Group group01u23; int g1u2_rank; MPI_Group_union (group01, group23, &group01u23); MPI_Group_rank (group01u23, &g1u2_rank); if (g1u2_rank != MPI_UNDEFINED) printf ("group01u23 contains absolute rank %d via relative rank %d\n", rank, g1u2_rank); // intersect groups 1 and 3 MPI_Group group01n13; int g1n3_rank; MPI_Group_intersection (group01, group12, &group01n13); MPI_Group_rank (group01n13, &g1n3_rank); if (g1n3_rank != MPI_UNDEFINED) printf ("group01n13 contains absolute rank %d via relative rank %d\n", rank, g1n3_rank); MPI_Group group0u23; int g0u23_rank; MPI_Group_union (group0, group23, &group0u23); MPI_Group_rank (group0u23, &g0u23_rank); if (g0u23_rank != MPI_UNDEFINED) printf ("group0u23 contains absolute rank %d via relative rank %d\n", rank, g0u23_rank); // create a communicator for the first group MPI_Comm_create (MPI_COMM_WORLD, group01, &comm01); MPI_Comm_create (MPI_COMM_WORLD, group0, &comm0); // create a communicator for the second group MPI_Comm_create (MPI_COMM_WORLD, group23, &comm23); // create a communicator for the third group MPI_Comm_create (MPI_COMM_WORLD, group12, &comm12); // display that this is a null communicator for the other ranks not in group 1 if (comm01 == MPI_COMM_NULL) { printf ("comm01 is a null communicator for rank %d\n", rank); } // intra-communication within group 3 float pi = 3.141592f; float e = 2.718281f; float buf; MPI_Status stat; if (g12_rank == 0) MPI_Send (&pi, 1, MPI_FLOAT, 1, EX_TAG, comm12); if (g12_rank == 1) { MPI_Recv (&buf, 1, MPI_FLOAT, 0, EX_TAG, comm12, &stat); printf ("group 3 rank 1 received pi = %f\n", buf); } // identify this communicator as an intra-communicator int test; if (g01_rank != MPI_UNDEFINED) MPI_Comm_test_inter (comm01, &test); if (g01_rank != MPI_UNDEFINED) if (test == true) printf ("communicator 1 is an inter-communicator\n"); if (g01_rank != MPI_UNDEFINED) if (test == false) printf ("communicator 1 is an intra-communicator\n"); // create intra-communicator for group 1 union 2 MPI_Comm intraComm01u23; MPI_Comm_create (MPI_COMM_WORLD, group01u23, &intraComm01u23); MPI_Comm intraComm0u23; MPI_Comm_create (MPI_COMM_WORLD, group0u23, &intraComm0u23); // verify that the intra-communicator is an intra-communicator if (g01_rank != MPI_UNDEFINED) MPI_Comm_test_inter (intraComm01u23, &test); if (g01_rank != MPI_UNDEFINED) if (test == true) printf ("intra-communicator 1 union 2 is an inter-communicator\n"); if (g01_rank != MPI_UNDEFINED) if (test == false) printf ("intra-communicator 1 union 2 is an intra-communicator\n"); MPI_Comm interComm01to23; MPI_Comm interComm23to01; MPI_Comm interComm0to23; MPI_Comm interComm23to0; // group 1 communicates with group 2 if (g01_rank != MPI_UNDEFINED) MPI_Intercomm_create (comm01, 0, intraComm01u23, 2, INTERCOMM_TAG, &interComm01to23); if (g01_rank != MPI_UNDEFINED) printf ("%d created inter communicator from world rank %d from communicator containing ranks starting from %d to starting world rank %d at tag %d\n", __LINE__, rank, g01_rank, 2, INTERCOMM_TAG); // group 2 communicates with group 1 if (g23_rank != MPI_UNDEFINED) MPI_Intercomm_create (comm23, 0, intraComm01u23, 0, INTERCOMM_TAG, &interComm23to01); if (g23_rank != MPI_UNDEFINED) printf ("%d created inter communicator from world rank %d from communicator containing ranks starting from %d to starting world rank %d at tag %d\n", __LINE__, rank, g23_rank, 2, INTERCOMM_TAG); if (g0_rank != MPI_UNDEFINED) MPI_Intercomm_create (comm0, 0, intraComm0u23, 1, INTERCOMM_TAG, &interComm0to23); if (g0_rank != MPI_UNDEFINED) printf ("%d created inter communicator from world rank %d from communicator containing ranks starting from %d to starting world rank %d at tag %d\n", __LINE__, rank, g0_rank, 2, INTERCOMM_TAG); if (g23_rank != MPI_UNDEFINED) MPI_Intercomm_create (comm23, 0, intraComm0u23, 0, INTERCOMM_TAG, &interComm23to0); if (g23_rank != MPI_UNDEFINED) printf ("%d created inter communicator from world rank %d from communicator containing ranks starting from %d to starting world rank %d at tag %d\n", __LINE__, rank, g23_rank, 2, INTERCOMM_TAG); // identify this communicator as an inter-communicator if (g01_rank != MPI_UNDEFINED) MPI_Comm_test_inter (interComm01to23, &test); if (g01_rank != MPI_UNDEFINED) if (test == true) printf ("communicator 1 to 2 is an inter-communicator\n"); if (g01_rank != MPI_UNDEFINED) if (test == false) printf ("communicator 1 to 2 is an intra-communicator\n"); // identify this communicator as an intra-communicator if (g23_rank != MPI_UNDEFINED) MPI_Comm_test_inter (interComm23to01, &test); if (g23_rank != MPI_UNDEFINED) if (test == true) printf ("communicator 2 to 1 is an inter-communicator\n"); if (g23_rank != MPI_UNDEFINED) if (test == false) printf ("communicator 2 to 1 is an intra-communicator\n"); // send a value from group 1 to group 2 via inter-communication between groups buf = 0.0f; if (g01_rank == 0) MPI_Send (&e, 1, MPI_FLOAT, 0, INTERCOMM_P2P, interComm01to23); if (g23_rank == 0) MPI_Recv (&buf, 1, MPI_FLOAT, 0, INTERCOMM_P2P, interComm23to01, &stat); if (g23_rank == 0) printf ("group 2 relative rank 0 received e = %f from group 1 relative rank 0\n", buf); // verify that the group associated with the inter communicators are identical to their intra-communicator counterparts MPI_Group testGroup; if (g01_rank != MPI_UNDEFINED) MPI_Comm_group (interComm01to23, &testGroup); if (g01_rank != MPI_UNDEFINED) MPI_Group_compare (group01, testGroup, &test); if (g01_rank != MPI_UNDEFINED && test == MPI_IDENT) printf ("the group for inter communication handle from group 1 to 2 is identical to communicator 1's group\n"); if (g01_rank != MPI_UNDEFINED && test == MPI_SIMILAR) printf ("the group for inter communication handle from group 1 to 2 is similar to communicator 1's group\n"); if (g01_rank != MPI_UNDEFINED && test == MPI_UNEQUAL) printf ("the group for inter communication handle from group 1 to 2 is unequal to communicator 1's group\n"); if (g23_rank != MPI_UNDEFINED) MPI_Comm_group (interComm23to01, &testGroup); if (g23_rank != MPI_UNDEFINED) MPI_Group_compare (group23, testGroup, &test); if (g23_rank != MPI_UNDEFINED && test == MPI_IDENT) printf ("the group for inter communication handle from group 2 to 1 is identical to communicator 2's group\n"); if (g23_rank != MPI_UNDEFINED && test == MPI_SIMILAR) printf ("the group for inter communication handle from group 2 to 1 is similar to communicator 2's group\n"); if (g23_rank != MPI_UNDEFINED && test == MPI_UNEQUAL) printf ("the group for inter communication handle from group 2 to 1 is unequal to communicator 2's group\n"); // free the groups MPI_Group_free (&group01); MPI_Group_free (&group23); MPI_Group_free (&group12); MPI_Group_free (&group01u12); MPI_Group_free (&group01n13); MPI_Group_free (&testGroup); // free the communicator handles if (g01_rank != MPI_UNDEFINED) { MPI_Comm_free (&comm01); MPI_Comm_free (&interComm01to23); } if (g23_rank != MPI_UNDEFINED) { MPI_Comm_free (&comm23); MPI_Comm_free (&interComm23to01); } if (g12_rank != MPI_UNDEFINED) { MPI_Comm_free (&comm12); } // finalize MPI MPI_Finalize (); printf ("done, with absolute rank %d\n", rank); return 0; }
C
/*TAD: Minha biblioteca para o SIG-car */ #ifndef MYLIB_H #define MYLIB_H /* Função get menu ** Operação que abre uma nova página de acordo com a entrada do usuário */ void get_menu( int n ); /* Função input ** Operação que obtém a entrada do usuário e aloca corretamente */ char* entr_str( char* frase ); /* Função escolha de menu ** Recebe um número de opções e valida se a escolha do usuário está dentro ** das opções; retorna a escolha do usuário como inteiro */ int menu_escolha( int n); /* Função formata preco ** Função que retorna o valor de um float a partir ** de uma string */ float form_preco( char* ); /* Função formata CPF ** Coloca os pontos e o hífen na posição correta */ char* form_cpf( char* entrada ); /* Função formata data ** Coloca as barras nas posições corretas */ char* form_data( char* entrada); /* Função formata número ** Retorna um novo vetor de caracteres com ou sem formatação ** depende da variável mostrar */ char* form_numero( char* entrada, int mostrar ); /* Função ano atual ** Retorna o ano em que o usuário está */ int ano_atual( void ); /* Função mes atual ** Retorna o mes em que o usuário está */ int mes_atual( void ); /* Função dia atual ** Retorna o dia em que o usuário está */ int dia_atual( void ); /* Função voltar ** Operação que solicita ao cliente se ele deseja voltar */ void voltar( void ); /* Função obtem resposta ** Operação que retorna 1 se a resposta do usuário for sim */ int get_resposta( char* ); void flush_in(void); #endif
C
#ifdef PLAN9 #include <u.h> #include <libc.h> #else #include "linux.h" #endif #include "dat.h" #include "pstring.h" #include "hash.h" /* Bernstein's hash */ uint hash(unsigned char *buf, int len) { unsigned int hash = 5381; while (len--) hash = ((hash << 5) + hash) + (*buf++); /* hash * 33 + c */ return hash; } htable* inittable(uint size) { htable *ht; ht = mallocz(sizeof(htable), 1); ht->tab = mallocz(size*sizeof(hentry*), 1); ht->size = size; return ht; } /* Returns the hash */ uint set(htable *ht, pstring *key, pstring *value) { uint h; int cmp; hentry *entry; hentry *p; pstring *k, *v; uint ret = 0; pstring *old; // by doing this, the caller can safely free the arguments that were passed to us k = clonepstring(key); v = clonepstring(value); entry = mallocz(sizeof(hentry), 1); h = hash(key->data, key->length); // Lock the hash table for writing wlock(&ht->l); if (ht->tab[h%ht->size] == nil) { entry->key = k; entry->value = v; entry->next = entry->prev = nil; ht->tab[h%ht->size] = entry; ret = h; } else { // traverse the list p = ht->tab[h%ht->size]; for (;;) { cmp = pstringcmp(k, p->key); if (!cmp) { // the key already exists, replace it old = p->value; p->value = v; freepstring(old); free(entry); freepstring(k); ret = h; break; } if (p->next) { p = p->next; } else { entry->key = k; entry->value = v; entry->next = entry->prev = nil; p->next = entry; entry->prev = p; ret = h; break; } } } // unlock the table wunlock(&ht->l); return ret; } pstring* get(htable *ht, pstring *key) { uint h; hentry *p; int cmp; pstring *ret = nil; h = hash(key->data, key->length); // Lock for reading rlock(&ht->l); p = ht->tab[h%ht->size]; for (; p != nil;) { cmp = pstringcmp(key, p->key); if (!cmp) { ret = clonepstring(p->value); // return a *copy* to avoid nasty frees } p = p->next; } // unlock runlock(&ht->l); return ret; }
C
#include "unity_fixture.h" #undef free // because we don't want Unity's version of free #include "prime_factors.h" TEST_GROUP(PrimeFactors); TEST_SETUP(PrimeFactors) {} TEST_TEAR_DOWN(PrimeFactors) {} TEST(PrimeFactors,FactorsOfOne) { int *actual = prime_factors_of(1); TEST_ASSERT_NULL(actual); } TEST(PrimeFactors,FactorsOfOne_Alt) { int *actual; int count = alt_prime_factors_of(1, &actual); TEST_ASSERT_EQUAL(0,count); TEST_ASSERT_NULL(actual); } TEST(PrimeFactors,FactorsOfTwo) { int expected[] = { 2 }; int *actual = prime_factors_of(2); TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, 1); free(actual); } TEST(PrimeFactors, FactorsOfTwo_Alt) { int expected[] = { 2 }; int *actual; int count = alt_prime_factors_of(2, &actual); TEST_ASSERT_EQUAL(1,count); TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, count); free(actual); } TEST(PrimeFactors,FactorsOfThree) { int expected[] = { 3 }; int *actual = prime_factors_of(3); TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, 1); free(actual); } TEST(PrimeFactors,FactorsOfThree_Alt) { int *actual = NULL; int expected[] = { 3 }; int count = alt_prime_factors_of(3, &actual); TEST_ASSERT_EQUAL(1,count); TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, count); free(actual); } TEST(PrimeFactors,FactorsOfFour) { int expected[] = { 2, 2 }; int *actual = prime_factors_of(4); TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, 2); free(actual); } TEST(PrimeFactors,FactorsOfFour_Alt) { int *actual = NULL; int expected[] = { 2, 2 }; int count = alt_prime_factors_of(4, &actual); TEST_ASSERT_EQUAL(2,count); TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, count); free(actual); } TEST(PrimeFactors,FactorsOfFive) { int expected[] = { 5 }; int *actual = prime_factors_of(5); TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, 1); free(actual); } TEST(PrimeFactors,FactorsOfFive_Alt) { int *actual = NULL; int expected[] = { 5 }; int count = alt_prime_factors_of(5, &actual); TEST_ASSERT_EQUAL(1, count); TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, count); free(actual); } TEST(PrimeFactors,FactorsOfEight) { int expected[] = { 2, 2, 2 }; int *actual = prime_factors_of(8); TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, 3); free(actual); } TEST(PrimeFactors,FactorsOfEight_Alt) { int *actual = NULL; int expected[] = { 2, 2, 2 }; int count = alt_prime_factors_of(8, &actual); TEST_ASSERT_EQUAL(3, count); TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, count); free(actual); } TEST(PrimeFactors,FactorsOfTweleve) { int expected[] = { 2, 2, 3 }; int *actual = prime_factors_of(12); TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, 3); free(actual); } TEST(PrimeFactors,FactorsOfTweleve_Alt) { int *actual = NULL; int expected[] = { 2, 2, 3 }; int count = alt_prime_factors_of(12, &actual); TEST_ASSERT_EQUAL(3, count); TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, count); free(actual); } TEST(PrimeFactors,FactorsOfTwentyFour) { int expected[] = { 2, 2, 2, 3 }; int *actual = prime_factors_of(24); TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, 4); free(actual); } TEST(PrimeFactors,FactorsOfTwentyFour_Alt) { int *actual = NULL; int expected[] = { 2, 2, 2, 3 }; int count = alt_prime_factors_of(24, &actual); TEST_ASSERT_EQUAL(4, count); TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, count); free(actual); } TEST_GROUP_RUNNER(PrimeFactors) { RUN_TEST_CASE(PrimeFactors,FactorsOfOne); RUN_TEST_CASE(PrimeFactors,FactorsOfOne_Alt); RUN_TEST_CASE(PrimeFactors,FactorsOfTwo); RUN_TEST_CASE(PrimeFactors,FactorsOfTwo_Alt); RUN_TEST_CASE(PrimeFactors,FactorsOfThree); RUN_TEST_CASE(PrimeFactors,FactorsOfThree_Alt); RUN_TEST_CASE(PrimeFactors,FactorsOfFour); RUN_TEST_CASE(PrimeFactors,FactorsOfFour_Alt); RUN_TEST_CASE(PrimeFactors,FactorsOfFive); RUN_TEST_CASE(PrimeFactors,FactorsOfFive_Alt); RUN_TEST_CASE(PrimeFactors,FactorsOfEight); RUN_TEST_CASE(PrimeFactors,FactorsOfEight_Alt); RUN_TEST_CASE(PrimeFactors,FactorsOfTweleve); RUN_TEST_CASE(PrimeFactors,FactorsOfTweleve_Alt); RUN_TEST_CASE(PrimeFactors,FactorsOfTwentyFour); RUN_TEST_CASE(PrimeFactors,FactorsOfTwentyFour_Alt); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #ifdef __GNUG__ #include <std.h> #endif #ifdef MSDOS #include <stdlib.h> #include <malloc.h> #endif #include "Global.h" #include "Variable.h" typedef struct _StrElement{ char *value; struct _StrElement *next; } StrElement; void var_delete_vlist(StrElement*); StrElement* var_new_element(char*); struct { char* name; StrElement* vlist; StrElement* point; } var[MAX_VAR]; void var_init() { var[0].name = NULL; var[0].vlist = NULL; } void var_end() { int i; for(i = 0; var[i].name; i++){ free(var[i].name); var_delete_vlist(var[i].vlist); } } void var_delete_vlist(StrElement* p) { for (;p; p = p->next){ free(p->value); } } void var_clear(char* name) { int i; for (i = 0; var[i].name; i++){ if (!strcmp(var[i].name, name)){ var_delete_vlist(var[i].vlist); var[i].vlist = var[i].point = NULL; return; } } if (i >= MAX_VAR-1){ term_error("ѿο¿ޤ"); } if (!(var[i].name = (char*)malloc(sizeof(char) * strlen(name) + 1))){ fprintf(stderr, "Out of memory!\n"); exit(1); } strcpy(var[i].name, name); var[i].vlist = var[i].point = NULL; var[i+1].name = NULL; var[i+1].vlist = NULL; } void var_set(char* name, char* value) { int i; StrElement* p; for (i = 0; var[i].name; i++){ if (!strcmp(var[i].name, name)){ break; } } if (!var[i].name){ term_error("顼:ѿ"); return; } if (! var[i].vlist){ var[i].vlist = var[i].point = var_new_element(value); } else { for (p = var[i].vlist; p->next; p = p->next); p->next = var_new_element(value); } } StrElement* var_new_element(char* value) { StrElement* p; if (!(p = (StrElement*)malloc(sizeof(StrElement)))){ fprintf(stderr, "Out of memory!\n"); exit(1); } if (!(p->value = (char*)malloc(sizeof(char)*strlen(value)+1))){ fprintf(stderr, "Out of memory!\n"); exit(1); } strcpy(p->value, value); p->next = NULL; return p; } char* ref(char* name) { ref_top(name); return ref_now(name); } int ref_i(char* name) { return (atoi(ref(name))); } Bool ref_top(char* name) { int i; for (i = 0; var[i].name; i++){ if (!strcmp(var[i].name, name)){ var[i].point = var[i].vlist; return TRUE; } } sprintf(global_tmp, "ѿ %s Ƥޤ", name); term_error(global_tmp); return FALSE; } char* ref_now(char* name) { int i; char *p; for (i = 0; var[i].name; i++){ if (!strcmp(var[i].name, name)){ if (var[i].point){ p = var[i].point->value; var[i].point = var[i].point->next; return p; } else { return NULL; } } } sprintf(global_tmp, "ѿ %s Ƥޤ", name); term_error(global_tmp); return FALSE; } void var_disp_table() { int i; for(i = 0; var[i].name; i++){ printf("%10s:%50s\n", var[i].name, var[i].vlist->value); } }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int vize[4]; int sayac,ortalama; int toplam; for(sayac=0;sayac<4;sayac++) { printf("notlari giriniz\n"); scanf("%d",&vize[sayac]); toplam+=vize[sayac]; } ortalama=toplam/4; FILE*dosya; dosya=fopen("sonuc.txt","w"); fprintf(dosya,"\ndizi elemanlari\n"); for(sayac=0;sayac<4;sayac++){ fprintf(dosya,"%d\n",vize[sayac]); } fprintf(dosya,"\n\n vize ortalamasi : %d",ortalama); getch(); }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* devide_ants.c :+: :+: */ /* +:+ */ /* By: eutrodri <[email protected]> +#+ */ /* +#+ */ /* Created: 2020/05/18 16:48:09 by eutrodri #+# #+# */ /* Updated: 2020/06/19 16:05:34 by eutrodri ######## odam.nl */ /* */ /* ************************************************************************** */ #include "../includes/lem_in.h" int choose_path(t_link *tmp, t_link *tmp2, int i, t_link *p) { if (tmp != p && p->visited <= tmp->visited && p->visited <= tmp2->visited) { p->visited++; p->next->visited++; i = 0; } else if (tmp->visited <= tmp2->visited) { tmp->visited++; tmp->next->visited++; } else { tmp2->visited++; tmp2->next->visited++; i++; } return (i); } void reset_vst(t_path *p) { int i; i = 0; while (p->array[i]) { p->array[i]->visited = 0; i++; } } void all_instruction(t_path *p) { int i; int instr; i = 0; instr = 0; while (p->array[i] && p->array[i]->prev && p->array[i]->next->visited > 0) { if (instr == 0 || instr <= p->array[i]->visited) instr = p->array[i]->visited; i++; } p->instruction = instr; } void devide_ants(t_path *p, int ants) { t_link *tmp; t_link *tmp2; int i; i = 0; if (!(p->array[i + 1] && p->array[i + 1]->prev)) { p->array[i]->next->visited = ants; p->instruction = p->array[i]->visited + ants; return ; } while (ants != 0) { tmp = p->array[i]; if (!(p->array[i + 1] && p->array[i + 1]->prev)) { i = 0; tmp2 = p->array[i]; } else tmp2 = p->array[i + 1]; i = choose_path(tmp, tmp2, i, p->array[0]); ants--; } all_instruction(p); }
C
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char** argv) { if(argc!=2) { perror("executable <key file>"); exit(1); } int fdKey=open(argv[1],O_WRONLY|O_CREAT); if(fdKey==-1) { perror("open"); exit(1); } int i,nbByte; unsigned int for( i=0 ; i<4 ;i++) { nbByte = write(fdKey, ,sizeof(unsigned int)); if(nbByte == -1) { perror("write"); exit(1); } return EXIT_SUCCESS; }
C
// Name: p12.c // Purpose: Evaluates an expression entered by the user // Author: EM #include <stdio.h> int main(void) { float value = 0.0f; char ch; float i = 1.0f; float num = 0.0f; char operator; printf("Enter an expression: "); while ((ch = getchar()) != '\n') { if (ch == '.') { i = 0.1; } else if ((ch >= '0') && (ch <= '9')) { if (i == 1) { num *= 10; num += ch - '0'; } else { num += (ch - '0') * i; i /= 10; } } else if ((ch == '+') || (ch == '-') || (ch == '*') || (ch == '/')) { operator = ch; } switch (operator) { case '+': value = num + value; num = 0.0f; break; case '-': value = num - value; num = 0.0f; break; case '*': value = num * value; num = 0.0f; break; case '/': value = num / value; num = 0.0f; break; } } printf("Value of expression: %.2f\n", value); return 0; }
C
#include <stdio.h> #include<stdlib.h> struct node { int data;struct node *next;}; struct node *head=NULL; int l=0; void create() {struct node* temp =(struct node *) malloc (sizeof (struct node)); struct node* p=head; printf("ENTER THE DATA: "); scanf ("%d",&temp->data); if (head == NULL) {head=temp;temp->next=NULL;} else {while (p->next!= NULL) { p = p->next; } p->next=temp; temp->next=NULL;} } void length() {int len=1; struct node *p=head; if(head==NULL) printf("ITS IS AN EMPTY LIST \n"); else { while(p!=NULL) { len++;l++; p=p->next;} } printf("THE LENGTH OF THE LIST IS :%d \t no.of nodes:%d",len,l);} void insert_AT_AFTER() { struct node *p=head; ; struct node *new=(struct node*)malloc(sizeof(struct node)); int position; printf("ENTER THE DATA OF THE NEW NODE:");scanf("%d",&new->data); printf("\nENTER THE POSITION OF THE DATA AFTER TO BE INSERTED "); scanf("%d",&position); while(p->data!=position) {p=p->next;} new->next=p->next; p->next=new; } void insert_AT_BEFORE() { struct node *p=head; struct node *pre_p=p; struct node *new=(struct node*)malloc(sizeof(struct node)); int position; printf("ENTER THE DATA OF THE NEW NODE:");scanf("%d",&new->data); printf("\n ENTER THE DATA OF THE NODE BEFORE TO BE INSERTED "); scanf("%d",&position); while(p->data!=position) {pre_p=p; p=p->next;} pre_p->next=new; new->next=p; } void insert_AT_BEGINNING() { struct node *p=head; struct node *new=(struct node*)malloc(sizeof(struct node)); printf("ENTER THE DATA OF THE NEW NODE:"); scanf("%d",&new->data); new->next=p ; head=new; } void insert_AT_END() { struct node *p=head; struct node *new=(struct node*)malloc(sizeof(struct node)); printf("ENTER THE DATA OF THE NEW NODE:"); scanf("%d",&new->data); while(p->next!=NULL) p=p->next; p->next=new; ; new->next=NULL; } void delete_AT_AFTER() { struct node *p=head; struct node *pre_p=p; int position; printf("ENTER THE POSITION OF THE NODE TO BE DELETED :"); scanf("%d",&position); while(pre_p->data!=position) {pre_p=p;p=p->next;} pre_p->next=p->next; free(p); } void delete_AT_BEFORE() { struct node *p=head; struct node *pre_p=p; struct node *pre_pre_p=pre_p; int position; printf("ENTER THE POSITION OF THE NODE TO BE DELETED "); scanf("%d",&position); while(p->data!=position) {pre_pre_p=pre_p;pre_p=p; p=p->next;} pre_pre_p->next=p; free(pre_p); } void delete_AT_BEGINNING() { struct node *p=head; head=head->next; free(p); } void delete_AT_END() { struct node *p=head; struct node *pre_p=p; while(p!=NULL) {p=p->next;} pre_p->next=NULL; free(p); } void search() {int searchelement,posi=1,f=0;printf("ENTER THE SEARCH ELEMENT :"); scanf("%d",&searchelement); struct node *p=head; while(p!=NULL) { if(p->data==searchelement) { f=1 ;break;} p=p->next; posi++;} if(f==1) printf("THE ELEMENT FOUND!! at node : %d",posi); else printf("ELEMENT NOT FOUND!!!!!!"); } void display() {struct node *p=head; while(p!=NULL) { printf("%d\t",p->data); p=p->next; } } void main() { int choice; do { printf ("\n\n 1.Create \n 2.Length \n 3.Insert_at_beginning \n 4.Insert_at_end \n 5.Insert_at_before \n 6.Insert_at_after \n 7.Delete_at_beginning \n 8.Delete_at_end \n 9.Delete_at_before \n 10.Delete_at_after \n 11.Search \n 12.Display \n\n TO END THE PROGRAM PRESS 0"); printf("\n ENTER THE CHOICE :");scanf ("%d",&choice); switch (choice) { case 1: create(); break; case 2: length(); break; case 3: insert_AT_BEGINNING(); break; case 4: insert_AT_END(); break; case 5: insert_AT_BEFORE(); break; case 6: insert_AT_AFTER(); break; case 7: delete_AT_BEGINNING(); break; case 8: delete_AT_END(); break; case 9: delete_AT_BEFORE(); break; case 10: delete_AT_AFTER(); break; case 11: search(); break; case 12: display(); break; default: if(choice!=0) printf("GIVE A NO WITHIN A CHOICE 1-12 \n"); } } while(choice!=0); printf("END OF THE PROGRAM!!!"); }
C
#include "xlist.h" int main(void) { int y=0,m=0,yd=0,md=0,d=31,gre=1,dotw=1,i=0; char e[9][100]={ /*0*/"\n=========================Error========================\n", /*1*/"\n=========================x=========================\n", /*2*/"̃vOł͐0NIO`Ă܂B", /*3*/"̒lɕsȒl͂܂B", /*4*/"OSI͖2621NɈƌĂ܂B\n\\ꂽJ_[͎QlxɂlB", /*5*/"\n======================================================\n", /*6*/"IɂEnterL[Ă..."}; printf("J_[ v1.00\n"); printf("N >>>");xscanf(&y); if(y<1){//1N printf("%s%s%s%s",e[0],e[2],e[5],e[6]); getchar();return -1;} printf(" >>>");xscanf(&m); if(m<1||m>12){//1,12 printf("%s%s%s%s",e[0],e[3],e[5],e[6]); getchar();return -1;} //tOB0=EX,1=OSI,2=(1582/10) if(y<1582){gre=0;} else if(y==1582&&m<10){gre=0;} else if(y==1582&&m==10){gre=2;} if(y>=2621){//2621N1鎖̌x printf("%s%s%s",e[1],e[4],e[5]);} /**********************************EX**********************************/ if(gre==0||gre==2){//1̗jZo yd = (y-1)*365 + (y-1)/4; md = (m-1)*31; if(m>2){md-=3; if(y%4==0){md+=1;}} if(m>4){md--;} if(m>6){md--;} if(m>9){md--;} if(m>11){md--;} dotw=(yd+md+6)%7; } /******************************************************************************/ /*********************************OSI*********************************/ else if(gre==1){//1̗jZo yd = (y-1)*365 + (y-1)/4 - (y-1)/100 + (y-1)/400; md = (m-1)*31; if(m>2){md-=3; if(y%4==0){md+=1;} if(y%100==0){md-=1;} if(y%400==0){md+=1;}} if(m>4){md--;} if(m>6){md--;} if(m>9){md--;} if(m>11){md--;} dotw=(yd+md+8)%7; } /******************************************************************************/ switch(gre){ case 0: printf("EXgpĂ܂B\n\n");break; case 1: printf("OSIgpĂ܂B\n\n");break; case 2: printf("EXƃOSI̋ڂ̌łB\n\n");break; default: printf("G[܂B\nG[R[h:G-%d\n\n%s",gre,e[6]);getchar();return 0; } printf("%4dN %2d\n",y,m); printf(" y\n"); if(m==4||m==6||m==9||m==11){d--;}//31̖(2) if(y%4!=0&&m==2){d=28;}//2N if(y%4==0&&m==2){d=29;}//2[N if(gre==1&&y%100==0&&y%400!=0&&m==2){d=28;}//OSI100NN(400N) for(i=dotw;i>0;i--){//ŏ̗j܂ŋ󔒏o printf(" ");} for(i=1;i<=d;i++){//J_[to if(y==1582&&m==10&&i==5){i+=10;dotw+=4;}//莞̓tƗj΂B printf("%2d",i); if((i+dotw)%7==0){printf("\n");}//yj̎ɉs else{printf(" ");}//̗j̎͋ } if((d+dotw)%7!=0){printf("\n");}//ŌオyjłȂȂs printf("\n%s",e[6]); getchar();return 0;}
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strmap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ftothmur <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/18 14:51:48 by ftothmur #+# #+# */ /* Updated: 2019/07/18 14:51:50 by ftothmur ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /* ** Allocates space on the heap with the required size to fit the src and the ** final zero byte. The byte by byte content of the source string is played in ** the destination string. Function fills the destination string with the ** appropriate elements of the source string after converting each of them ** with a function passed by the pointer. ** If successful, returns a pointer to the destination string, otherwise NULL. */ char *ft_strmap(char const *src, char (*fptr)(char)) { char *dst; char *d; dst = NULL; if (src && fptr && (dst = (char *)ft_memalloc(ft_strlen(src) + 1))) { d = dst; while (*src != '\0') { *d = (*fptr)(*src++); d++; } *d = '\0'; } return (dst); }
C
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. #include <math.h> #include <stdio.h> #include <visit-config.h> #include <string.h> #include <iostream> using std::cerr; using std::endl; #ifndef _WIN32 #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #endif // suppress the following since silo uses char * in its API #if defined(__clang__) # pragma GCC diagnostic ignored "-Wdeprecated-writable-strings" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wwrite-strings" #endif static const float minvals[] = {10.,10.,10.}; static const float maxvals[] = {20.,20.,20.}; static const int bx = 17; static const int by = 23; static const int bz = 29; static const int nx = bx * 4; static const int ny = by * 5; static const int nz = bz * 3; static const int full_size[] = {nx, ny, nz}; static const int bricklet_size[] = {bx, by, bz}; static int nels = nx * ny * nz; static const int offset = 16; typedef float BOV_t; template <class T> void write_BOV_data(const char *filename, const T *data, int nels) { FILE *fp = fopen(filename, "wb"); fwrite((void *)data, sizeof(T), nels, fp); fclose(fp); } void write_BOV_header(const char *tname, const char *sname, int nc, const char *header, const char *bovfile, int offset_bytes, bool subdiv, bool bt) { // Write the BOV header. FILE *fp = fopen(header, "wt"); fprintf(fp, "TIME: 0\n"); fprintf(fp, "DATA_FILE: %s\n", bovfile); fprintf(fp, "DATA_SIZE: %d %d %d\n", full_size[0], full_size[1], full_size[2]); fprintf(fp, "DATA_FORMAT: %s\n", sname); if(strcmp(tname, "COMPLEX") == 0) { fprintf(fp, "DATA_COMPONENTS: COMPLEX\n"); } else if(nc > 1) { fprintf(fp, "DATA_COMPONENTS: %d\n", nc); } fprintf(fp, "VARIABLE: myvar\n"); #ifdef WORDS_BIGENDIAN fprintf(fp, "DATA_ENDIAN: BIG\n"); #else fprintf(fp, "DATA_ENDIAN: LITTLE\n"); #endif fprintf(fp, "CENTERING: zonal\n"); fprintf(fp, "BRICK_ORIGIN: %g %g %g\n", minvals[0], minvals[1], minvals[2]); fprintf(fp, "BRICK_SIZE: %g %g %g\n", maxvals[0]-minvals[0], maxvals[1]-minvals[1], maxvals[2]-minvals[2]); if(offset_bytes > 0) fprintf(fp, "BYTE_OFFSET: %d\n", offset_bytes); if(subdiv) { fprintf(fp, "DIVIDE_BRICK: true\n"); fprintf(fp, "DATA_BRICKLETS: %d %d %d\n", bricklet_size[0], bricklet_size[1], bricklet_size[2]); } if(bt) { fprintf(fp, "VARIABLE_MIN: 10.\n"); fprintf(fp, "VARIABLE_MAX: 50.\n"); } fclose(fp); } template <class T> void fill_BOV_indices(T *data, const int *full_size) { T index = 0; T *ptr = data; for(int k = 0; k < full_size[2]; ++k) { for(int j = 0; j < full_size[1]; ++j) { for(int i = 0; i < full_size[0]; ++i) { *ptr++ = index; index = index + 1; } } } } // Template specialization for unsigned char. void fill_BOV_indices(unsigned char *data, const int *full_size) { unsigned char *ptr = data; float root3 = sqrt(3.); for(int k = 0; k < full_size[2]; ++k) { float z = float(k) / float(full_size[2]-1); for(int j = 0; j < full_size[1]; ++j) { float y = float(j) / float(full_size[1]-1); for(int i = 0; i < full_size[0]; ++i) { float x = float(i) / float(full_size[0]-1); float r = sqrt(x*x + y*y + z*z); unsigned char c = (unsigned char)((int)(255.* r / root3)); *ptr++ = c; } } } } // Template specialization for unsigned short. void fill_BOV_indices(unsigned short *data, const int *full_size) { unsigned short *ptr = data; float root3 = sqrt(3.); for(int k = 0; k < full_size[2]; ++k) { float z = float(k) / float(full_size[2]-1); for(int j = 0; j < full_size[1]; ++j) { float y = float(j) / float(full_size[1]-1); for(int i = 0; i < full_size[0]; ++i) { float x = float(i) / float(full_size[0]-1); float r = sqrt(x*x + y*y + z*z); unsigned short c = (unsigned short)((int)((65536./2.-1.)* r / root3)); *ptr++ = c; } } } } template <class T> void write_BOV_types(const char *tname, const char *sname, int nc, T *data, bool bt) { char filename[1000], headername[1000]; // // Populate the array with indices and save out BOV. // snprintf(filename, 1000, "%s_indices.values", tname); printf("Creating %s\n", filename); fill_BOV_indices(data, full_size); write_BOV_data(filename, data, nx*ny*nz); snprintf(headername, 1000, "%s_indices.bov", tname); write_BOV_header(tname, sname, nc, headername, filename, 0, false, bt); // Write another header where the object is divided. snprintf(headername, 1000, "%s_indices_div.bov", tname); write_BOV_header(tname, sname, nc, headername, filename, 0, true, bt); // // Do the same thing but give the file a 16 element header // that we'll have to skip when we read it. // snprintf(filename, 1000, "%s_indices_div_with_header.values", tname); printf("Creating %s\n", filename); unsigned char *cptr = (unsigned char *)data; fill_BOV_indices(data + offset, full_size); for(size_t i = 0; i < offset * sizeof(T); ++i) cptr[i] = (unsigned char)i; write_BOV_data(filename, data, nx*ny*nz + offset); snprintf(headername, 1000, "%s_indices_div_with_header.bov", tname); write_BOV_header(tname, sname, nc, headername, filename, offset * sizeof(T), true, bt); } class complex_t { public: complex_t() { real = 0; imag = 0; } complex_t(int v) { real = v; imag = 2*v; } complex_t(const complex_t &obj) { real = obj.real; imag = obj.imag; } ~complex_t() { ; } complex_t operator = (const complex_t &obj) { real = obj.real; imag = obj.imag; return *this; } complex_t operator + (int val) { real += val; imag = real * 2; return *this; } double real, imag; }; class triple_t { public: triple_t() { data[0] = data[1] = data[2] = 0; } triple_t(int v) { data[0] = data[1] = data[2] = v; } triple_t(const triple_t &obj) { data[0] = obj.data[0]; data[1] = obj.data[1]; data[2] = obj.data[2]; } ~triple_t() { ; } triple_t operator = (const triple_t &obj) { data[0] = obj.data[0]; data[1] = obj.data[1]; data[2] = obj.data[2]; return *this; } triple_t operator + (int val) { data[0] += val; data[1] += val; data[2] += val; return *this; } int data[3]; }; class my_quad_t { public: my_quad_t() { data[0] = data[1] = data[2] = data[3] = 0; } my_quad_t(int v) { data[0] = data[1] = data[2] = data[3] = v; } my_quad_t(const my_quad_t &obj) { data[0] = obj.data[0]; data[1] = obj.data[1]; data[2] = obj.data[2]; data[3] = obj.data[3]; } ~my_quad_t() { ; } my_quad_t operator = (const my_quad_t &obj) { data[0] = obj.data[0]; data[1] = obj.data[1]; data[2] = obj.data[2]; data[3] = obj.data[3]; return *this; } my_quad_t operator + (int val) { data[0] += val; data[1] += val; data[2] += val; data[3] += val; return *this; } int data[4]; }; // **************************************************************************** // Function: write_multi_bov // // Purpose: // Writes out a multiblock BOV dataset. // // Programmer: Brad Whitlock // Creation: Fri Oct 20 15:47:31 PST 2006 // // Modifications: // // **************************************************************************** void write_multi_bov() { int ncomps = 1; float *data = new float[20 * 30 * 40 * ncomps]; char filename[100]; printf("Creating multi*.bov\n"); // Write the BOV files. int findex = 0; for(int k = 0; k < 2; ++k) { int start_k = k * 40; for(int j = 0; j < 2; ++j) { int start_j = j * 30; for(int i = 0; i < 2; ++i) { int start_i = i * 20; for(int kk = 0; kk < 40; ++kk) { float k_val = start_k + kk; float dZ = 40. - k_val; float dZ2 = dZ * dZ; for(int jj = 0; jj < 30; ++jj) { float j_val = start_j + jj; float dY = 30. - j_val; float dY2 = dY * dY; for(int ii = 0; ii < 20; ++ii) { unsigned int index = (kk*20*30 + jj*20 + ii)*ncomps; float dX = 20. - (start_i + ii); data[index] = sqrt(dX*dX + dY2 + dZ2); } } } snprintf(filename, 100, "multi%04d.values", findex); write_BOV_data(filename, data, 20 * 30 * 40 * ncomps); findex++; } } } // Write the BOV header. FILE *fp = fopen("multi.bov", "wt"); fprintf(fp, "TIME: 0\n"); fprintf(fp, "DATA_FILE: multi%%04d.values\n"); fprintf(fp, "DATA_SIZE: 40 60 80\n"); fprintf(fp, "DATA_FORMAT: FLOAT\n"); fprintf(fp, "DATA_COMPONENTS: %d\n", ncomps); fprintf(fp, "VARIABLE: vec\n"); #ifdef WORDS_BIGENDIAN fprintf(fp, "DATA_ENDIAN: BIG\n"); #else fprintf(fp, "DATA_ENDIAN: LITTLE\n"); #endif fprintf(fp, "CENTERING: zonal\n"); fprintf(fp, "BRICK_ORIGIN: 0. 0. 0.\n"); fprintf(fp, "BRICK_SIZE: 20. 30. 40.\n"); fprintf(fp, "DATA_BRICKLETS: 20 30 40\n"); fclose(fp); delete [] data; } // **************************************************************************** // Method: write_nodal_multi_bov // // Purpose: // // // Arguments: // // Returns: // // Note: // // Programmer: Brad Whitlock // Creation: Thu Jun 25 10:41:07 PDT 2009 // // Modifications: // // **************************************************************************** void write_nodal_multi_bov() { const int X_DOMAINS = 20; const int Y_DOMAINS = 30; const int Z_DOMAINS = 40; const int X_CELLS = 10; const int Y_CELLS = 10; const int Z_CELLS = 10; const float cX = float(X_DOMAINS) / 2.f; const float cY = float(Y_DOMAINS) / 2.f; const float cZ = float(Z_DOMAINS) / 2.f; float *data = new float[X_CELLS * Y_CELLS * Z_CELLS]; char filename[100]; printf("Creating nodal_multi*.bov\n"); #ifndef _WIN32 if ( (mkdir("nodal_bov", S_IRUSR | S_IWUSR | S_IXUSR) && (errno!=EEXIST)) || chdir("nodal_bov") ) { cerr << "ERROR: failed to cd to nodal_bov" << endl; } #endif // Write the BOV files. int findex = 0; for(int k = 0; k < Z_DOMAINS; ++k) { for(int j = 0; j < Y_DOMAINS; ++j) { for(int i = 0; i < X_DOMAINS; ++i) { float *fptr = data; for(int kk = 0; kk < Z_CELLS; ++kk) { float tz_val = float(kk) / float(Z_CELLS-1); float z_val = float(k) + tz_val; float dZ = z_val - cZ; float dZ2 = dZ * dZ; for(int jj = 0; jj < Y_CELLS; ++jj) { float ty_val = float(jj) / float(Y_CELLS-1); float y_val = float(j) + ty_val; float dY = y_val - cY; float dY2 = dY * dY; for(int ii = 0; ii < X_CELLS; ++ii) { float tx_val = float(ii) / float(X_CELLS-1); float x_val = float(i) + tx_val; float dX = x_val - cX; *fptr++ = sqrt(dX*dX + dY2 + dZ2); } } } snprintf(filename, 100, "multi%05d.values", findex); write_BOV_data(filename, data, X_CELLS * Y_CELLS * Z_CELLS); findex++; } } } delete [] data; #ifndef _WIN32 if (chdir("..")) { cerr << "ERROR: failed to cd .." << endl; } #endif // Write the BOV header. FILE *fp = fopen("nodal_multi.bov", "wt"); fprintf(fp, "TIME: 0\n"); #ifndef _WIN32 fprintf(fp, "DATA_FILE: nodal_bov/multi%%05d.values\n"); #else fprintf(fp, "DATA_FILE: multi%%05d.values\n"); #endif fprintf(fp, "DATA_SIZE: %d %d %d\n", X_CELLS * X_DOMAINS, Y_CELLS * Y_DOMAINS, Z_CELLS * Z_DOMAINS); fprintf(fp, "DATA_FORMAT: FLOAT\n"); fprintf(fp, "DATA_COMPONENTS: 1\n"); fprintf(fp, "VARIABLE: vec\n"); #ifdef WORDS_BIGENDIAN fprintf(fp, "DATA_ENDIAN: BIG\n"); #else fprintf(fp, "DATA_ENDIAN: LITTLE\n"); #endif fprintf(fp, "CENTERING: nodal\n"); fprintf(fp, "BRICK_ORIGIN: 0. 0. 0.\n"); fprintf(fp, "BRICK_SIZE: %d %d %d\n", X_DOMAINS, Y_DOMAINS, Z_DOMAINS); fprintf(fp, "DATA_BRICKLETS: %d %d %d\n", X_CELLS, Y_CELLS, Z_CELLS); fclose(fp); } // **************************************************************************** // Purpose: This program writes out a couple of different BOV files. // // Programmer: Brad Whitlock // Creation: Fri Mar 17 16:48:31 PST 2006 // // Modifications: // Brad Whitlock, Thu May 4 12:21:18 PDT 2006 // I made it write out int and double data also. // // Brad Whitlock, Fri Oct 20 15:48:01 PST 2006 // I made it write out a multiblock dataset. // // Thomas R. Treadway, Mon Jul 16 13:45:29 PDT 2007 // quad_t conflicts with quad_t in #include <sys/types.h> // // Brad Whitlock, Wed Apr 8 09:57:28 PDT 2009 // I added short data. // // Brad Whitlock, Tue Jun 23 16:33:57 PDT 2009 // I made it write a nodal multiblock dataset with 24K domains. // // **************************************************************************** int main(int argc, char *argv[]) { bool writeNodal = false; for(int i = 1; i < argc; ++i) { if(strcmp(argv[i], "-writenodal") == 0) writeNodal = true; } unsigned short *sdata = new unsigned short[nels + offset]; write_BOV_types("SHORT", "SHORT", 1, sdata, false); delete [] sdata; int *idata = new int[nels + offset]; write_BOV_types("INT", "INT", 1, idata, false); delete [] idata; float *fdata = new float[nels + offset]; write_BOV_types("FLOAT", "FLOAT", 1, fdata, false); delete [] fdata; double *ddata = new double[nels + offset]; write_BOV_types("DOUBLE", "DOUBLE", 1, ddata, false); delete [] ddata; complex_t *cdata = new complex_t[nels + offset]; write_BOV_types("COMPLEX", "DOUBLE", 2, cdata, false); delete [] cdata; triple_t *tdata = new triple_t[nels + offset]; write_BOV_types("TRIPLE", "INT", 3, tdata, false); delete [] tdata; my_quad_t *qdata = new my_quad_t[nels + offset]; write_BOV_types("QUAD", "INT", 4, qdata, false); delete [] qdata; unsigned char *ucdata = new unsigned char[nels + offset]; write_BOV_types("BYTE", "BYTE", 1, ucdata, true); delete [] ucdata; // Write out a multiblock dataset. write_multi_bov(); // Write out a nodal multiblock dataset. if(writeNodal) write_nodal_multi_bov(); return 0; }
C
#include<stdio.h> int main() { char input[999]; printf("Enter the value\n"); scanf("%s",input); int n; n=0; int c1=0,c2=0; while(input[n]!='\0') { if(input[n]=='.') { c1++; if(input[n+1]!='\0') c2=1; } n++; } if(c1==1 && c2==1){ printf("Valid\n"); } else{ printf("Invalid\n"); } return 0; }
C
/* * image.c * * Created on: May 7, 2014 * Author: palotasb */ #include "glcd.h" #include "image_font.h" #include "image.h" Image const Image_Empty = { .size.x = 0, .size.y = 0, .getPixel = Image_Empty_zeroFunction, .getPixelByte = Image_Empty_zeroFunction }; /** * Calculates the buffer offset for a pixel in an ImageData structure with a * specified size. * * @param imageData: the structure * @param pixelCoord: the coordinate * @return: the buffer index */ inline uint32_t ImageData_GetBufferIndexFromPixelCoord(ImageData* imageData, Coord pixelCoord) { return pixelCoord.y / 8 * imageData->size.x + pixelCoord.x; } /** * Returns the bit mask for a specific coordinate in an image. * * @param imageData: the image * @param pixelCoord: the coordinate * @return: the bit mask */ inline uint8_t ImageData_BufferBitMaskFromPixelCoord(Coord pixelCoord) { return 0x01 << (pixelCoord.y % 8); } /** * Returns the bit index for a specific coordinate in an image. * @param imageData: the image * @param pixelCoord: the coordinate * @return: the bit index (0-7) */ inline uint8_t ImageData_BufferBitIndexFromPixelCoord(Coord pixelCoord) { return pixelCoord.y % 8; } /** * Creates a Coord structure * @param x: x coordinate or width * @param y: y coordinate or height * @return: the Coord struct */ inline Coord coord(int16_t x, int16_t y) { Coord c = { .x = x, .y = y }; return c; } /** * Initializes an ImageData structure. * * @param imageData: the structure. * @param size: the size of the image in pixels * @param data: pointer to an array where each bit can represent a pixel */ void ImageData_Init(ImageData* imageData, Coord size, uint8_t* data) { imageData->size = size; imageData->data = data; imageData->getPixel = ImageData_GetPixel; imageData->getPixelByte = ImageData_GetByte; } /** * Sets a pixel of an ImageData structure to a specific value. * * @param imageData: the structure containing the image data and the pixel to set. * @param pixelCoord: the coordinate of the pixel. * @param data: value of 0 or 1. */ void ImageData_SetPixel(ImageData* imageData, Coord pixelCoord, uint8_t data) { if (imageData->size.x < pixelCoord.x || imageData->size.y < pixelCoord.y || pixelCoord.x < 0 || pixelCoord.y < 0) return; if (data) { imageData->data[ImageData_GetBufferIndexFromPixelCoord(imageData, pixelCoord)] |= ImageData_BufferBitMaskFromPixelCoord( pixelCoord); } else { imageData->data[ImageData_GetBufferIndexFromPixelCoord(imageData, pixelCoord)] &= ~ImageData_BufferBitMaskFromPixelCoord( pixelCoord); } } /** * Returns the pixel value of an ImageData structure at a specified coordinate. * * @param imageData: the object * @param pixelCoord: the coordinate * @return: 0 or 1, the pixel value */ uint8_t ImageData_GetPixel(ImageData* imageData, Coord pixelCoord) { if (imageData->size.x < pixelCoord.x || imageData->size.y < pixelCoord.y || pixelCoord.x < 0 || pixelCoord.y < 0) return 0; return imageData->data[ImageData_GetBufferIndexFromPixelCoord(imageData, pixelCoord)] & ImageData_BufferBitMaskFromPixelCoord(pixelCoord) ? 1 : 0; } /** * Sets a byte of pixels (1-by-8 size) the value specified. * * @param imageData: the image whose data is to be set. * @param byteCoord: the pixel coordinate of the byte * @param data: the data */ void ImageData_SetByte(ImageData* imageData, Coord byteCoord, uint8_t data) { if (imageData->size.x < byteCoord.x || imageData->size.y < byteCoord.y || byteCoord.x < 0 || byteCoord.y < 0) return; uint8_t bit0index = ImageData_BufferBitIndexFromPixelCoord(byteCoord); uint32_t bufferIndex = ImageData_GetBufferIndexFromPixelCoord(imageData, byteCoord); imageData->data[bufferIndex] &= 0xff >> (8 - bit0index); imageData->data[bufferIndex] |= data << bit0index; if (bit0index) { // If the bit index is not zero, then the 8 bits are from two different buffers. // Ignore second buffer if out of range. if (imageData->size.y < byteCoord.y + 7) return; bufferIndex = ImageData_GetBufferIndexFromPixelCoord(imageData, coord(byteCoord.x, byteCoord.y + 7)); imageData->data[bufferIndex] &= 0xff << bit0index; imageData->data[bufferIndex] |= data >> (8 - bit0index); } } /** * Returns a byte of pixels (1-by-8 size) as one byte starting at the specified coordinate. * * @param imageData: the image * @param byteCoord: the pixel coordinate. * @return */ uint8_t ImageData_GetByte(ImageData* imageData, Coord byteCoord) { if (imageData->size.x < byteCoord.x || imageData->size.y < byteCoord.y || byteCoord.x < 0 || byteCoord.y < 0) return 0; uint8_t ret = imageData->data[ImageData_GetBufferIndexFromPixelCoord( imageData, byteCoord)]; uint8_t bit0index = ImageData_BufferBitIndexFromPixelCoord(byteCoord); if (bit0index) { // If the bit index is not zero, then the 8 bits are from two different buffers. // 1. shift lower bytes from the first buffer into place ret >>= bit0index; // If the second buffer would be out of range, this makes it like 0 if (imageData->size.y < byteCoord.y + 7) return ret; // 2. get the second 8 bytes from the second buffer // 3. shift into place by shifting them up (8 - bit0index) // 4. clear the lower bit0index number of bits (& 0xff>>bit0index) // 5. combine the lower and upper parts by OR-ing them ret |= (imageData->data[ImageData_GetBufferIndexFromPixelCoord( imageData, coord(byteCoord.x, byteCoord.y + 7))] << (8 - bit0index)) & (0xff >> bit0index); } return ret; } /** * Initializes a virtual image. * * @param virtualImage: the struct to initialize * @param size: the size of the virtual image canvas * @param imageA: the first image (by default: background) composing the virtual image * @param imageB: the second image (by default: overlay) composing the virtual image * @param offsetA: the offset of the first image from the (0,0) point of the virtual image * @param offsetB: the offset of the second image from the (0,0) point of the virtual image */ void VirtualImage_Init(VirtualImage* virtualImage, Coord size, Image* imageA, Image* imageB, Coord offsetA, Coord offsetB) { virtualImage->combinator = VIC_JUST_B; virtualImage->func = 0; virtualImage->getPixel = VirtualImage_GetPixel; virtualImage->getPixelByte = VirtualImage_GetByte; virtualImage->imageA = imageA; virtualImage->imageB = imageB; virtualImage->offsetA = offsetA; virtualImage->offsetB = offsetB; virtualImage->size = size; } /** * Returns the pixel value of the virtual image at a specified coordinate. * * @param virtualImage: the image * @param pixelCoord: the pixel coordinate * @return: the pixel value, 0 or 1; */ uint8_t VirtualImage_GetPixel(Image* virtualImage, Coord pixelCoord) { VirtualImage* vi = (VirtualImage*) virtualImage; Coord ca = pixelCoord, cb = pixelCoord; uint8_t a, b, res, combinator; ca.x += vi->offsetA.x; ca.y += vi->offsetA.y; cb.x += vi->offsetB.x; cb.y += vi->offsetB.y; a = vi->imageA->getPixel(vi->imageA, ca); if (vi->combinator & VIC_NEGATE_A) a = ~a; b = vi->imageB->getPixel(vi->imageB, cb); if (vi->combinator & VIC_NEGATE_B) b = ~b; combinator = vi->combinator & 0xf0; switch (combinator) { case VIC_AND: res = a & b; break; case VIC_OR: res = a | b; break; case VIC_XOR: res = a ^ b; break; case VIC_EQUAL: res = ~(a ^ b); break; case VIC_JUST_A: if (0 <= ca.x && ca.x < vi->imageA->size.x && 0 <= ca.y && ca.y < vi->imageA->size.y) res = a; else res = b; break; case VIC_JUST_B: if (0 <= cb.x && cb.x < vi->imageB->size.x && 0 <= cb.y && cb.y < vi->imageB->size.y) res = b; else res = a; break; case VIC_CUSTOM_FUNC: if (vi->func) res = vi->func(vi, pixelCoord); break; default: res = 0; } if (vi->combinator & VIC_NEGATE_RESULT) res = ~res; // The lowest bit carries the value, the rest is just overhead. return res & 0x01; } /** * Returns a byte of pixels (1-by-8 size) as one byte starting at the specified coordinate. * * @param virtualImage: the virtual image * @param pixelCoord: the pixel coordinate * @return: the byte */ uint8_t VirtualImage_GetByte(Image* virtualImage, Coord pixelCoord) { VirtualImage* vi = (VirtualImage*) virtualImage; Coord ca = pixelCoord, cb = pixelCoord; uint8_t a, b, res, combinator; ca.x += vi->offsetA.x; ca.y += vi->offsetA.y; cb.x += vi->offsetB.x; cb.y += vi->offsetB.y; a = vi->imageA->getPixelByte(vi->imageA, ca); if (vi->combinator & VIC_NEGATE_A) a = ~a; b = vi->imageB->getPixelByte(vi->imageB, cb); if (vi->combinator & VIC_NEGATE_B) b = ~b; combinator = vi->combinator & 0xf0; switch (combinator) { case VIC_AND: res = a & b; break; case VIC_OR: res = a | b; break; case VIC_XOR: res = a ^ b; break; case VIC_EQUAL: res = ~(a ^ b); break; case VIC_JUST_A: if (0 <= ca.x && ca.x < vi->imageA->size.x && 0 <= ca.y && ca.y < vi->imageA->size.y) res = a; else res = b; break; case VIC_JUST_B: if (0 <= cb.x && cb.x < vi->imageB->size.x && 0 <= cb.y && cb.y < vi->imageB->size.y) res = b; else res = a; break; case VIC_CUSTOM_FUNC: if (vi->func) res = vi->func(vi, pixelCoord); break; default: res = 0; } if (vi->combinator & VIC_NEGATE_RESULT) res = ~res; return res; } /** * Helper function for using an empty image. * * @param i * @param c * @return */ inline uint8_t Image_Empty_zeroFunction(Image* i, Coord c) { return 0; } /** * Displays an image on the 128x64 LCD. * * @param image: the image to display * @param xy1: the upper left coordinate of the pixels to display * @param xy2: the lower right coordinate of the pixels to display */ void Image_DisplayOnLCD(Image* image, Coord xy1, Coord xy2) { uint8_t x, y; for (y = xy1.y / 8; y <= xy2.y / 8; y++) for (x = xy1.x; x <= xy2.x; x++) { GLCD_Write_Block(image->getPixelByte(image, coord(x, y * 8)), y, x); } }
C
#include<stdio.h> int algarismo (int a) {//Essa função printa um algarismo da Dezena ou da Unidade, considerando a definição diferenciada dos teens switch (a) { // case 0: // printf("zero"); // break; // Zero foi desconsiderado pois não se pronuncia ele. case 1: printf("um"); break; case 2: printf("dois"); break; case 3: printf("tres"); break; case 4: printf("quatro"); break; case 5: printf("cinco"); break; case 6: printf("seis"); break; case 7: printf("sete"); break; case 8: printf("oito"); break; case 9: printf("nove"); break; case 10: printf("dez"); break; case 11: printf("onze"); break; case 12: printf("doze"); break; case 13: printf("treze"); break; case 14: printf("quatorze");//catorze break; case 15: printf("quinze"); break; case 16: printf("dezesseis");//dez e seis break; case 17: printf("dezessete");//dez e sete break; case 18: printf("dezoito");//dez oito break; case 19: printf("dezenove");//dez e nove break; case 20: printf("vinte"); break; case 30: printf("trinta"); break; case 40: printf("quarenta"); break; case 50: printf("cinquenta"); break; case 60: printf("sessenta"); break; case 70: printf("setenta"); break; case 80: printf("oitenta"); break; case 90: printf("noventa"); break; case 100: printf("cem"); break;//embora seja diferente da ideia geral da função // printar o cem, quando solitário, reduz processamento do Cento default: return 0; // caso não dê para printar } return 1; } void extenso (int n) { if (n>=1000000) { extenso(n/1000000); if (n<2000000) printf("milhao "); else printf("milhoes "); n = n%1000000; if(n==0) printf("d"); // de reais if(n<=100000 && (n/1000)*(n%1000)==0) //n%1000<=100 printf("e "); } if (n>=1000) { if(n/1000 > 1) // para não escrever UM MIL extenso(n/1000); printf("mil "); n = n%1000; if(n<=100 && n>0) printf("e "); } // if(n==0) return; if(n>100) { switch (n/100) { case 9: printf("novecentos"); break; case 8: printf("oitocentos"); break; case 7: printf("setecentos"); break; case 6: printf("seiscentos"); break; case 5: printf("quinhentos"); break; case 4: printf("quatrocentos"); break; case 3: printf("trezentos"); break; case 2: printf("duzentos"); break; case 1: // caso seja exatamente 100, 100 não é maior que 100, portanto será printado abaixo, e não aqui printf("cento"); // devido a isso, este 100 será para quando há algum valor nas unidades e/ou dezenas. } printf(" "); n %= 100; if (n>0) // caso haja algum valor após as centenas, ele deverá ser precedido de E printf("e "); } if (algarismo(n) == 0) // se não foi possível printar, pois é um número com dezena > 1 e unidade > 0 if (algarismo(n-n%10) == 1) // se foi possível printar a dezena, { printf(" e "); algarismo(n%10); // printa a unidade. } if(n>0) printf(" "); } void moeda (float v) { int reais = (int) v; int centavos = (int)100*(v-reais); // possivelmente impreciso // printf("%d.%02d = ",reais,centavos); if(reais > 0) { extenso(reais); if(reais>1) printf("reais"); else printf("real"); } if (reais*centavos != 0) printf(" e "); if(centavos > 0) { extenso(centavos); if(centavos==1) printf("centavo"); else printf("centavos"); } // return 100*(v-reais) - centavos; } int main () { float valor = 0; /* for(valor=200;valor<=1111;valor++) { printf("\nR$%d\t",(int)valor); moeda(valor); } */ do { moeda(valor); printf("\nR$"); scanf("%f",&valor); } while (valor != 0); return 0;//(int) valor; }
C
#include "st-unicode.h" #include "st-utils.h" #include <string.h> st_unichar st_utf8_get_unichar (const char *p) { st_unichar ch; if (p == NULL) return 0x00; if ((p[0] & 0x80) == 0x00) { ch = p[0]; } else if ((p[0] & 0xe0) == 0xc0) { ch = ((p[0] & 0x1f) << 6) | (p[1] & 0x3f); } else if ((p[0] & 0xf0) == 0xe0) { ch = ((p[0] & 0xf) << 12) | ((p[1] & 0x3f) << 6) | (p[2] & 0x3f); } else if ((p[0] & 0xf8) == 0xf0) { ch = ((p[0] & 0x7) << 18) | ((p[1] & 0x3f) << 12) | ((p[2] & 0x3f) << 6) | (p[3] & 0x3f); } else ch = 0x00; /* undefined */ return ch; } /* * Copyright (C) 2008 Colin Percival */ #if 0 #define ONEMASK ((size_t)(-1) / 0xFF) size_t st_utf8_strlen(const char * _s) { const char * s; size_t count = 0; size_t u; unsigned char b; /* Handle any initial misaligned bytes. */ for (s = _s; (uintptr_t)(s) & (sizeof(size_t) - 1); s++) { b = *s; /* Exit if we hit a zero byte. */ if (b == '\0') goto done; /* Is this byte NOT the first byte of a character? */ count += (b >> 7) & ((~b) >> 6); } /* Handle complete blocks. */ for (; ; s += sizeof(size_t)) { /* Prefetch 256 bytes ahead. */ __builtin_prefetch(&s[256], 0, 0); /* Grab 4 or 8 bytes of UTF-8 data. */ u = *(size_t *)(s); /* Exit the loop if there are any zero bytes. */ if ((u - ONEMASK) & (~u) & (ONEMASK * 0x80)) break; /* Count bytes which are NOT the first byte of a character. */ u = ((u & (ONEMASK * 0x80)) >> 7) & ((~u) >> 6); count += (u * ONEMASK) >> ((sizeof(size_t) - 1) * 8); } /* Take care of any left-over bytes. */ for (; ; s++) { b = *s; /* Exit if we hit a zero byte. */ if (b == '\0') break; /* Is this byte NOT the first byte of a character? */ count += (b >> 7) & ((~b) >> 6); } done: return ((s - _s) - count); } #endif /* Derived from FontConfig * Copyright (C) 2006 Keith Packard */ int st_unichar_to_utf8 (st_unichar ch, char *outbuf) { int bits; char *d = outbuf; if (ch < 0x80) { *d++ = ch; bits = -6; } else if (ch < 0x800) { *d++ = ((ch >> 6) & 0x1f) | 0xc0; bits = 0; } else if (ch < 0x10000) { *d++ = ((ch >> 12) & 0x0f) | 0xe0; bits = 6; } else if (ch < 0x200000) { *d++ = ((ch >> 18) & 0x07) | 0xf0; bits = 12; } else if (ch < 0x4000000) { *d++ = ((ch >> 24) & 0x03) | 0xf8; bits = 18; } else if (ch < 0x80000000) { *d++ = ((ch >> 30) & 0x01) | 0xfC; bits = 24; } else return 0; for (; bits >= 0; bits -= 6) { *d++= ((ch >> bits) & 0x3F) | 0x80; } return d - outbuf; } /** * st_utf8_validate * @utf: Pointer to putative UTF-8 encoded string. * * Checks @utf for being valid UTF-8. @utf is assumed to be * null-terminated. This function is not super-strict, as it will * allow longer UTF-8 sequences than necessary. Note that Java is * capable of producing these sequences if provoked. Also note, this * routine checks for the 4-byte maximum size, but does not check for * 0x10ffff maximum value. * * Return value: true if @utf is valid. **/ /* Derived from eglib, libxml2 * Copyright (C) 2006 Novell, Inc. * Copyright (C) 1998-2003 Daniel Veillard */ bool st_utf8_validate (const char *string, ssize_t max_len) { int ix; if (max_len == -1) max_len = strlen (string); /* * input is a string of 1, 2, 3 or 4 bytes. The valid strings * are as follows (in "bit format"): * 0xxxxxxx valid 1-byte * 110xxxxx 10xxxxxx valid 2-byte * 1110xxxx 10xxxxxx 10xxxxxx valid 3-byte * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx valid 4-byte */ for (ix = 0; ix < max_len;) { /* string is 0-terminated */ st_uchar c; c = string[ix]; if ((c & 0x80) == 0x00) { /* 1-byte code, starts with 10 */ ix++; } else if ((c & 0xe0) == 0xc0) {/* 2-byte code, starts with 110 */ if (((ix+1) >= max_len) || (string[ix+1] & 0xc0 ) != 0x80) return false; ix += 2; } else if ((c & 0xf0) == 0xe0) {/* 3-byte code, starts with 1110 */ if (((ix + 2) >= max_len) || ((string[ix+1] & 0xc0) != 0x80) || ((string[ix+2] & 0xc0) != 0x80)) return false; ix += 3; } else if ((c & 0xf8) == 0xf0) {/* 4-byte code, starts with 11110 */ if (((ix + 3) >= max_len) || ((string[ix+1] & 0xc0) != 0x80) || ((string[ix+2] & 0xc0) != 0x80) || ((string[ix+3] & 0xc0) != 0x80)) return false; ix += 4; } else {/* unknown encoding */ return false; } } return true; } /** * st_utf8_strlen: * @utf: a sequence of UTF-8 encoded bytes * * compute the length of an UTF8 string, it doesn't do a full UTF8 * checking of the content of the string. * * Returns the number of characters in the string or -1 in case of error */ /* Derived from libxml2 * Copyright (C) 1998-2003 Daniel Veillard */ int st_utf8_strlen (const char *string) { int ret = 0; if (string == NULL) return(-1); while (*string != 0) { if (string[0] & 0x80) { if ((string[1] & 0xc0) != 0x80) return(-1); if ((string[0] & 0xe0) == 0xe0) { if ((string[2] & 0xc0) != 0x80) return(-1); if ((string[0] & 0xf0) == 0xf0) { if ((string[0] & 0xf8) != 0xf0 || (string[3] & 0xc0) != 0x80) return(-1); string += 4; } else { string += 3; } } else { string += 2; } } else { string++; } ret++; } return(ret); } const char * st_utf8_offset_to_pointer (const char *string, st_uint offset) { const char *p = string; for (st_uint i = 0; i < offset; i++) p = st_utf8_next_char (p); return p; } st_unichar * st_utf8_to_ucs4 (const char *string) { const st_uchar *p = string; st_unichar *buffer, c; st_uint index = 0; if (string == NULL) return NULL; buffer = st_malloc (sizeof (st_unichar) * (st_utf8_strlen (string) + 1)); while (p[0]) { if ((p[0] & 0x80) == 0x00) { c = p[0]; p += 1; } else if ((p[0] & 0xe0) == 0xc0) { c = ((p[0] & 0x1f) << 6) | (p[1] & 0x3f); p += 2; } else if ((p[0] & 0xf0) == 0xe0) { c = ((p[0] & 0xf) << 12) | ((p[1] & 0x3f) << 6) | (p[2] & 0x3f); p += 3; } else if ((p[0] & 0xf8) == 0xf0) { c = ((p[0] & 0x7) << 18) | ((p[1] & 0x3f) << 12) | ((p[2] & 0x3f) << 6) | (p[3] & 0x3f); p += 4; } else break; buffer[index++] = c; } buffer[index] = 0; return buffer; } #if 0 char * st_ucs4_to_utf8 (const st_unichar *string) { int bits; char *d = outbuf; if (ch < 0x80) { *d++ = ch; bits = -6; } else if (ch < 0x800) { *d++ = ((ch >> 6) & 0x1f) | 0xc0; bits = 0; } else if (ch < 0x10000) { *d++ = ((ch >> 12) & 0x0f) | 0xe0; bits = 6; } else if (ch < 0x200000) { *d++ = ((ch >> 18) & 0x07) | 0xf0; bits = 12; } else if (ch < 0x4000000) { *d++ = ((ch >> 24) & 0x03) | 0xf8; bits = 18; } else if (ch < 0x80000000) { *d++ = ((ch >> 30) & 0x01) | 0xfC; bits = 24; } else return 0; for (; bits >= 0; bits -= 6) { *d++= ((ch >> bits) & 0x3F) | 0x80; } return d - outbuf; } #endif
C
#include <xinu.h> #include <future.h> #include <stdio.h> int de_Q(Future_queue*); void en_Q(Future_queue*, pid32); void print_Q(Future_queue*); //Allocate memmory to the future. future_t* future_alloc(future_mode_t mode) { future_t *future_element; future_element = (future_t *)getmem(sizeof(future_t)); switch(mode) { case FUTURE_EXCLUSIVE : future_element->mode = mode; future_element->state = FUTURE_EMPTY; break; case FUTURE_SHARED : future_element->get_queue = (Future_queue *)getmem(sizeof(Future_queue)); future_element->mode = mode; future_element->state = FUTURE_EMPTY; future_element->get_queue->qfirst = NULL; future_element->get_queue->qlast = NULL; break; case FUTURE_QUEUE : future_element->set_queue = (Future_queue *)getmem(sizeof(Future_queue)); future_element->get_queue = (Future_queue *)getmem(sizeof(Future_queue)); future_element->mode = mode; future_element->state = FUTURE_EMPTY; future_element->set_queue->qfirst = NULL; future_element->set_queue->qlast = NULL; future_element->get_queue->qfirst = NULL; future_element->get_queue->qlast = NULL; //future_element->get_queue = NULL; break; } return future_element; } //Freeing the future syscall future_free(future_t *future_element) { int status; if ((status = freemem((char *)future_element, sizeof(future_t))) != OK ) { return SYSERR; } return OK; } //Getting the future value syscall future_get(future_t *future_element , int* value) { int status; switch(future_element->mode) { case FUTURE_EXCLUSIVE : /* This will wait till the state of the future is changed to Ready.*/ while (future_element->state!=FUTURE_READY) { printf(""); continue; } *value = future_element->value; if ((status=future_free(future_element)) != OK) { return SYSERR; } break; case FUTURE_SHARED : /* The consumer will check if the state of the future is ready. It will consume if and only if the state of the future is ready.*/ if (future_element->state!=FUTURE_READY) { pid32 cons_proc_id = getpid(); en_Q(future_element->get_queue, cons_proc_id); suspend(cons_proc_id); } *value = future_element->value; break; case FUTURE_QUEUE : /* The consumer will check if there are any producers waiting to produce the value.*/ if(future_element->set_queue->qlast != NULL) { resume(de_Q(future_element->set_queue)); *value = future_element->value; } else { future_element->state = FUTURE_WAITING; pid32 cons_proc_id = getpid(); en_Q(future_element->get_queue, cons_proc_id); suspend(cons_proc_id); *value = future_element->value; } break; } return OK; } /*Setting the future value*/ syscall future_set(future_t *future_element, pid32 value) { switch(future_element->mode) { case FUTURE_EXCLUSIVE : /* The producer will produce the value if and only if the state of the future is EMPTY.*/ if (future_element->state == FUTURE_EMPTY) { future_element->value = value; future_element->state = FUTURE_READY; } else { printf("Only one thread can produce in Exclusive mode. "); return SYSERR; } break; case FUTURE_SHARED : /* The producer will produce the value if and only if the state of the future is EMPTY.*/ if (future_element->state == FUTURE_EMPTY) { future_element->value = value; future_element->state = FUTURE_READY; } else { printf("Only one thread can produce in Shared Mode. "); return SYSERR; } while(future_element->get_queue->qlast != NULL) { resume(de_Q(future_element->get_queue)); } break; case FUTURE_QUEUE : /* The producer will check of there are any consumers waiting to consume the value.*/ if(future_element->get_queue->qlast != NULL) { future_element->value = value; future_element->state = FUTURE_READY; resume(de_Q(future_element->get_queue)); } else { pid32 prod_proc_id = getpid(); en_Q(future_element->set_queue, prod_proc_id); suspend(prod_proc_id); future_element->value = value; future_element->state = FUTURE_READY; } break; } return OK; }
C
#include <stdio.h> int main(int argc, char const *argv[]) { if (argc != 3) { printf("The operands number is %d and should be 2!\n", argc - 1); return -1; } if (strlen(argv[1]) != strlen(argv[2])) { printf("The lengths of two operands should be the same!\n"); return -2; } int arr[256] = {0}; for (int i = 0; i < strlen(argv[1]); i++) { arr[argv[1][i]]++; if (arr[argv[1][i]] > 1) { printf("The '%c' character is duplicate in the first operand.\n", argv[1][i]); return -3; } } int c; while((c = getchar()) != EOF) { if (arr[c] > 0) { for (int i = 0; i < strlen(argv[1]); i++) { if (c == argv[1][i]) { putchar(argv[2][i]); break; } } } else { putchar(c); } } }