Страницы

Translate

пятница, 19 июня 2015 г.

Создать таблицу средствами php

Этой статьей я начну писать о своих успехах на поприще изучения веб разработки.

Итак начнем.

Я не хочу сказать что мое решение самое правильное, просто это одно из них.
Для начала следует вспомнить как верстается таблица на чистом HTML.

<table>
    <tr>
        <td>...</td>
        <td>...</td>
        <td>...</td>
    </tr>
    <tr>
        <td>...</td>
        <td>...</td>
        <td>...</td>
    </tr>
</table>

Добавим к открывающему тегу table атрибуты - border='1' cellpadding = '5' width='30%', и посмотрим что у нас получилось

.........
.........

Теперь сделаем тоже самое, но с использованием php. Также давайте раскрасим клетки таблицы. Конечно лучше это делать средствами CSS, но попробуем так

index.php:

<?php

$rows = 10;//строки
$cols = 6;//столбцы
$table = "<table border='1' cellpadding = '3' width='50%'>";
$count = 0;//счетчик

for($i = 1; $i < $rows; $i++ ){
 $table .= "<tr align='center'>";
 for($j = 1; $j < $cols; $j++ ){
  $count++;
  if(($count%2)=== 0) {
   $table .= "<td bgcolor='yellow'>$count</td>";
  } else {
   $table .= "<td>$count</td>";
  };
  
 };
 $table .= "</tr>";
};

$table .= "</table>";
echo $table;

?>

А вот что должно получится:

Ну вот как-то так, делитесь своими замечаниями.

вторник, 24 декабря 2013 г.

Exercise 8.8. Write a routine bfree(p,n) that will free any arbitrary block p of n characters into the free list maintained by malloc and free.

Exercise 8.8. Write a routine bfree(p,n) that will free any arbitrary block p of n characters into the free list maintained by malloc and free. By using bfree, a user can add a static or external array to the free list at any time.








unsigned bfree(char *p, unsigned n)
{
    Header *hp;
   
    if(n < sizeof(Header))
        return 0;
    hp = (Header *) p;
    hp->s.size = n / sizeof(Header);
    free((void *) (hp + 1));
    return hp->s.size;
}

Exercise 8.7. malloc accepts a size request without checking its plausibility; free believes that the block it is asked to free contains a valid size field. Improve these routines so they make more pains with error checking.

Exercise 8.7. malloc accepts a size request without checking its plausibility; free believes that the block it is asked to free contains a valid size field. Improve these routines so they  make more pains with error checking.






#include <stdio.h>
#include <stdlib.h>

#define MAXBYT 10240

typedef long Align; //for alignment to long boundary
union header
{
    struct  //block header
    {
        union header *ptr; //next block if on free list
        unsigned size;      //size of this block
    } s;
    Align x; //force alignment of blocks
};

typedef union header Header;

static Header base; //empty list to get started
static Header *freep = NULL; //start of free list
static Header *morecore(unsigned nu);
static Header *freeptr;
static Header *prevptr;
static unsigned maxalloc; //max bytes

/* malloc: universal storage allocator */
void *_malloc(unsigned nbytes)
{
    Header *p, *prevp;
    Header *moreroce(unsigned);
    unsigned nunits;
   
    if(nbytes > MAXBYT)
    {
        fprintf(stderr, "alloc: i can`t allocate more than %d bytes/n",
                    MAXBYT);
        return NULL;
    }   
    nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
    if((prevp = freep) == NULL) //no free list yet
    {
        base.s.ptr = freeptr = prevptr = &base;
        base.s.size = 0;
    }
    for(p = prevp->s.ptr; ;prevp = p, p = p->s.ptr)
    {
        if(p->s.size >= nunits) //big enough
        {
            if(p->s.size == nunits) //exactly
                prevp->s.ptr = p->s.ptr;
            else //allocate tail end
            {
                p->s.size -= nunits;
                p += p->s.size;
                p->s.size = nunits;
            }
            freep = prevp;
            return (void *) (p+1);
        }
        if(p == freep) //wrapped around free list
            if((p = morecore(nunits)) == NULL)
                return NULL; // non left
    }
}

#define NALLOC 1024 //minimum units to request
/* morecore: ask system for more memory */
static Header *morecore(unsigned nu)
{
    char *cp, *sbrk(int);
    Header *up;
   
    if(nu < NALLOC)
        nu = NALLOC;
    cp = sbrk(nu * sizeof(Header));
    if(cp == (char *) -1) //no space at all
        return NULL;
    up = (Header *) cp;
    up->s.size = nu;
    maxalloc = (up->s.size > maxalloc) ? up->s.size : maxalloc;
    free((void *) (up + 1));
    return freep;
}

/* free: put block ap in free list */

void free(void *ap)
{
    Header *bp, *p;
   
    bp = (Header *) ap - 1; // point to block header
    if(bp->s.size == 0 || bp->s.size > maxalloc)
    {
        fprintf(stderr, "alloc: i can`t allocate more than %d bytes/n",
                    MAXBYT);
        return;
    }   
    for (p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
        if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
            break; //freed block at start or end of arena
    if(bp + bp->s.size == p->s.ptr) //join to upper nbr
    {
        bp->s.size +=p->s.ptr->s.size;
        bp->s.ptr = p->s.ptr->s.ptr;
    }
    else
        bp->s.ptr = p->s.ptr;
    if(p + p->s.size == bp) //join to lower nbr
    {
        p->s.size += bp->s.size;
        p->s.ptr = bp->s.ptr;
    }
    else
        p->s.ptr = bp;
    freep = p;
}

Exercise 8.6. The standard library function calloc(n,size) returns a pointer to n objects of size size, with the storage initialized to zero

Exercise 8.6. The standard library function calloc(n,size) returns a pointer to n objects of
size size, with the storage initialized to zero. Write calloc, by calling malloc or by
modifying it.









#include <stdio.h>
#include <stdlib.h>

/* calloc */

void _calloc(unsigned n, unsigned size)
{
    unsigned i, nsize;
    char *p, *q;
   
    nsize = n * size;
    if((p = q = malloc(nsize)) != NULL)
        for(i = 0; i < nsize; i++)
            *q++=0;
    return p;
}

пятница, 20 декабря 2013 г.

Exercise 8.5. Modify the fsize program to print the other information contained in the inode entry



Exercise 8.5. Modify the fsize program to print the other information contained in the inode entry.



#include <stdio.h>
#include <string.h>
#include <sys/stat.h> //structure returned by stat
#include <sys/types.h> //typedefs
#include <sys/syscall.h>
#include <fcntl.h> //flags for read and write
#include <dirent.h>
#include <sys/dir.h> //local directory structure


int stat(char *, struct stat *);
void dirwalk(char *, void (*fcn) (char *));


/* fsize: print file "name" size */
void fsize(char *name)
{
    struct stat stbuf;
   
    stat(name, &stbuf) == -1)
    {
        fprintf(stderr, "fsize: can`t acces %s\n", name);
        return;
    }
    if(stbuf.st_mode & S_IFMT) == S_IFDIR)
        dirwalk(name, fsize);
    printf("%8ld %s\n%u %ld\n", stbuf.st_size, name,  stbuf.st_uid,stbuf.st_mtime);
}

воскресенье, 15 декабря 2013 г.

Exercise 8.4.Write int fseek(FILE *fp, long offset, int origin).



Exercise 8.4. The standard library function int fseek(FILE *fp, long offset, int origin) is identical to lseek except that fp is a file pointer instead of a file descriptor and return value is an int status, not a position. Write fseek.



/* fseek: random access using file pointer */
int _fseek(_FILE *fp, long offset, int origin)
{
    unsigned nc; //discharged characters
    long rc = 0; //return code
   
    if(fp->flag.f_read)
    {
        if(origin == 1)
            offset -= fp->cnt;
        rc = lseek(fp->fd, offset, origin);
        fp->cnt = 0; //buffer is empty
    }
    else if(fp->flag.f_write)
    {
        if((nc = fp->ptr - fp->base) > 0)
            if(write(fp->fd, fp->base, nc) != nc)
                rc = -1;
        if(rc != -1) // no error
            rc = lseek(fp->fd, offset, origin);
    }
    return (rc == -1) ? -1 : 0;
}

Exercise 8.3. Design and write _flushbuf, fflush, and fclose



Exercise 8.3. Design and write _flushbuf, fflush, and fclose.



/* _flushbuf: selects or clears the input buffer */
int _flushbuf(int x, _FILE *fp)
{
    unsigned nc; //amount discharged characters
    int bufsize; //size of the allocated buffer
   
    if (fp < _iob || fp >= _iob + OPEN_MAX)
        return EOF; //wrong pointer
    if(fp->flag.f_write == 0 || fp->flag.f_err == 1)
        return EOF;
    bufsize = (fp->flag.f_unbuf == 1) ? 1 : BUFSIZ;
    if(fp->base == NULL) //buffer is not yet
    {
        if((fp->base = (char *) malloc(bufsize)) == NULL)
        {
            fp->flag.f_err = 1;
            return EOF; //can not takes buffer
        }
    }
    else //buffer is already
    {
        nc = fp->ptr - fp->base;
        if(write(fp->fd, fp->base, nc) != nc)
        {
            fp->flag.f_err = 1;
            return EOF;//error, return EOF
        }
    }
    fp->ptr = fp->base; //beginning of the buffer
    *fp->ptr++=(char)x;
    fp->cnt = bufsize - 1;
    return x;
}

/* fclose: closed the file */
int _fclose(_FILE *fp)
{
    int rc; //return code
   
    if((rc = _fflush(fp)) != EOF)
    {
        free(fp->base); // release memory buffer
        fp->ptr = NULL;
        fp->cnt = 0;
        fp->base = NULL;
        fp->flag.f_unbuf = 0;
        fp->flag.f_buf = 1;
        fp->flag.f_eof = 0;
        fp->flag.f_err = 0;
        fp->flag.f_read = 0;
        fp->flag.f_write = 0; 
    }
    return rc;
}

/* fflush: reset the buffer corresponding to the file */
int _fflush(_FILE *fp)
{
    int rc = 0;
   
    if(fp < _iob || fp >= _iob + OPEN_MAX)
        return EOF; //wrong pointer
    if(fp->flag.f_write)
        rc = _flushbuf(0, fp);
    fp->ptr = fp->base;
    fp->cnt = (fp->flag.f_unbuf == 1) ? 1 : BUFSIZ;
    return rc;
}