dimanche 28 juin 2015

Why is modulus with unsigned int runs faster than with unsigned long long?

Why to test speed of modulus?


I have an app where modulus operation is performed millions times a second. I have to work with very big numbers, so I chose unsigned long long as a data type. About a week ago I've written a new algorithm for my app that required performing modulus operation on numbers which are much less than the numbers I used to work with (e.g. 26 instead of 10000000). I chose to use unsigned int as a data type. The speed increased dramatically while the algorithm is almost the same.

Testing...


I've written two simple programs in C to test the speed of modulus calculation.

#include <stdio.h>

typedef unsigned long long ull;

int main(){
   puts("Testing modulus...");
   ull cnt;
   ull k;
   for(k=1, cnt=98765432;k<=10000000;++k) 
      printf("%u ",cnt%80);
   puts("");
   return 0;
}

The only thing I was changing was the type of the variable called cnt. I added the printf call to be sure that nothing gets optimized away.

I tested these programs with time ./progname > /dev/null and the results were as follows.

  • With unsigned long long: 14.5 sec
  • With unsigned int: 11.2 sec

Note: I'm testing it on a jailbroken iPad, that's why it takes so much time.

Why?


Why does the version with unsigned long long take so much time to run?

Multithreading project structure

I'm developing a project that involves the interaction between three threads. The code of the the thread functions is very long, and put everything in a file does not seem a good idea, because it becomes unmanageable.

Compile separately the threads functions and then link everything is a solution that makes sense?

Obviously there are a lot of data structures shared between threads.

What is the proper way to separate the project into more files?

Can anyone modify the following code to avoid the usage of "if"?

I am working on cuda currently and I got stuck on the code below. The code was originally written in matlab and I am trying to re-write it using cuda:

Pv = 0; Nv =0;
[LOOP]
v1 = l(li);
v2 = l(li+1);
if((v1>0) && (v2>0))
    Pv = Pv + 1;
elseif((v1<0) && (v2<0))
    Nv = Nv +1;
elseif((v1>0) && (v2<0))
    r = v1/(v1-v2);
    Pv = Pv + r;
    Nv = Nv + 1 - r;
elseif((v1<0) && (v2>0))
    r = v2/(v2-v1);
    Pv = Pv + r;
    Nv = Nv + 1 - r;
end
[LOOP END]

But, in cuda architecture, "if" expression is sometimes expensive, and I believe there is some way to avoid the usage of it, although I cannot figure it out now.

The main purpose of the code is to calculate the ratio of positive interval of negative interval and add them up respectively. In most of the situation , v1 and v2 have the same sign, but once they have different sign, I have to use a bunch of "if" or even perhaps "abs()" to handle the situation.

So, can anyone help me to re-write the code using C while using as few "if " as possible?

Is it necessary to close a file number of time it is opened in program?

If file is opened using fopen() and in different mode then is it necessary to close it number of time or it can be closed once at end of code ?

implement the char ' | ' to get a pipe between two processes in C [duplicate]

This question already has an answer here:

I have to implement the pipe char ' | ' in my own mini shell in C (Linux). for exemple.... after compiling file.c and then ./a.out I should be able to digit ls | sort, and the program should be able to work as the main shell. How can I do such a thing? thanks

Function to read sentence from user input [C]

I am trying to read sentence from user input problem with my function is it skips second try when I try to call it... Any solution?

void readString(char *array, char * prompt, int size) {
    printf("%s", prompt);
    char c; int count=0;
    char * send = array;
    while ((c = getchar()) != '\n') {
        send[count] = c; count++;
        if (size < count){ free(array); break; } //lets u reserve the last index for '\0'
        }

    }

Here is how try to call it:

char obligation[1500];
char dodatno[1500];

readString(obligation, "Enter obligation", 1500);
readString(dodatno, "Enter hours", 1500);

Here is example of inputs: "This is some sentence"

so latter I wana do this:

printf(" %s | %s \n",obligation, dodatno);

and get:

This is some sentence|This is another sentence

Finite State Machine In C

I am trying to create a simple finite state machine in C and I'm quite confused on how to get started. I tried looking online but nothing has really cleared this up for me.

My goal is to check if a string is octal, hex or an integer.

My attempt at creating the states would be:

typedef enum  {
   ERROR,
   OCTAL,
   HEX,
   INTEGER
} stringStates;

Now, I would then use a switch statement to go through the entirety of the string and switch between the different states until I have correctly identified which state it belongs to.

 while (current_Position<=end_String-1)
 {
    switch( "input something here")
      {
        case 0:
             //process string
             break;
        case 1:
             //process string
             break;

         case 2:
             //process string
             break;
         case 3:
             //process string
             break;
         default:
             break;
      }
  }

This concept is still very new to me and I'm having hard time understanding its implementation. If anyone can shed some light, it'll be much appreciated.

Accessing individual bytes in PROGMEM on Arduino/AVR

I've read up on accessing PROGMEM for days now, and combed through several other questions, but I still can't get my code working. Any help would be appreciated.

I've included a full test sketch for Arduino below. The majority of it works, but when I loop through each byte of an "alpha" character, as pointed to by "alphabytes", I'm just getting garbage out so I'm obviously not accessing the correct memory location. The problem is, I can't figure out how to access that memory location.

I've seen several other examples of this working, but none that have different sizes of data arrays in the pointer array.

Please see line beginning with ">>>> Question is..."

// Include PROGMEM library
#include <avr/pgmspace.h>

// Variable to hold an alphabet character row
char column_byte;

// Used to hold LED pixel value during display
char led_val;

// Used to hold the screen buffer for drawing the screen
char matrix_screen[64];

/*
  Define Alphabet characters. This should allow for characters of varying byte lengths.
*/
const char alpha_A[] PROGMEM = {0x06, 0x38, 0x48, 0x38, 0x06};
const char alpha_B[] PROGMEM = {0x7E, 0x52, 0x52, 0x2C};
const char alpha_C[] PROGMEM = {0x3C, 0x42, 0x42, 0x24};

/*
  The "alphabytes" contains an array of references (pointers) to each character array.
  Read right-to-left, alphabytes is a 3-element constant array of pointers,
  which points to constant characters

*/
const char* const alphabytes[3] PROGMEM = {
  alpha_A, alpha_B, alpha_C
};

/*
  This array is necessary to list the number of pixel-columns used by each character.
  The "sizeof" function cannot be used on the inner dimension of alphabytes directly
  because it will always return the value "2". The "size_t" data
  type is used because is a type suitable for representing the amount of memory
  a data object requires, expressed in units of 'char'.
*/
const char alphabytes_sizes[3] PROGMEM = {
  sizeof(alpha_A), sizeof(alpha_B), sizeof(alpha_C)
};

/**
 * Code Setup. This runs once at the start of operation. Mandatory Arduino function
 **/
void setup(){

  // Include serial for debugging
  Serial.begin(9600);
}

/**
 * Code Loop. This runs continually after setup. Mandatory Arduino function
 **/
void loop(){

  // Loop through all alphabet characters
  for( int a = 0; a < 3; a++) {

    // Reset screen
    for (int r = 0; r < 64; r++) {
      matrix_screen[r] = 0;
    }

    // This line works to read the length of the selected "alphabyte"
    int num_char_bytes = pgm_read_byte(alphabytes_sizes + a);

    for (int b = 0; b < num_char_bytes; b++){

      // Based on alphabytes definition,
      // Examples of desired value for column_byte would be:
      //
      // When a=0, b=0 -> column_byte = 0x06
      // When a=0, b=1 -> column_byte = 0x38
      // When a=0, b=2 -> column_byte = 0x48
      // When a=0, b=3 -> column_byte = 0x38
      // When a=0, b=4 -> column_byte = 0x06
      // When a=1, b=0 -> column_byte = 0x7E
      // When a=1, b=1 -> column_byte = 0x52
      // When a=1, b=2 -> column_byte = 0x52
      // When a=1, b=3 -> column_byte = 0x2C
      // When a=2, b=0 -> column_byte = 0x3C
      // When a=2, b=1 -> column_byte = 0x42
      // When a=2, b=2 -> column_byte = 0x42
      // When a=2, b=3 -> column_byte = 0x24

      // >>>>> Question is... how to I get that? <<<<<<<
      // column_byte = pgm_read_byte(&(alphabytes[a][b])); // This doesn't work

      // Thought: calculate offset each time
      // int offset = 0;
      // for(int c = 0; c < a; c++){
      //   offset += pgm_read_byte(alphabytes_sizes + c);
      // }
      // column_byte = pgm_read_byte(&(alphabytes[offset])); // This doesn't work

      // column_byte = (char*)pgm_read_word(&alphabytes[a][b]); // Doesn't compile
      column_byte = pgm_read_word(&alphabytes[a][b]); // Doesn't work

      // Read each bit of column byte and save to screen buffer
      for (int j = 0; j < 8; j++) {
        led_val = bitRead(column_byte, 7 - j);
        matrix_screen[b * 8 + j] = led_val;
      }

    }

    // Render buffer to screen
    draw_screen();

    // Delay between frames
    delay(5000);

  }

}

/**
 * Draw the screen. This doesn't have the correct orientation, but
 * that's fine for the purposes of this test.
 **/
void draw_screen(){
  for (int a = 0; a < 8; a++) {
    for (int b = 0; b < 8; b++) {
      Serial.print((int) matrix_screen[a * 8 + b]);
      Serial.print(" ");
    }
    Serial.println();
  }
  Serial.println();
}

What is the difference between ' ' and " "? [duplicate]

This question already has an answer here:

I was creating a simple program to count the words and vowels of a string, and when I try to use double quotes inside of a 'for' or an 'if' statement it gives an erro. But when I change it for a single quote it works pretty good.

I thought they were the same thing, so what is the difference between them and why I cannot use double quotes inside of a statement or single quote inside a 'printf' function?

PS: I'm using code blocks as my IDE.

Here is my code, so you can see an example:

#include <stdio.h>
#include <conio.h>

int main(void){
    // Declaracao de Variaveis
    int cont_p = 0, cont_v = 0, i;
    char frase[1000];

    // Leitura de Dados
    printf("Digite a frase:\n");
    gets(frase);

    // Logica e Contagemm
    for (i=0; frase[i]!='\0';i++){
        if(frase[i] == ' '){
            cont_p = cont_p +1;
        }else if ((frase[i] == 'a') || (frase[i] == 'A')) {
            cont_v = cont_v + 1;
        }else if ((frase[i] == 'e') || (frase[i] == 'E')) {
            cont_v = cont_v + 1;
        }else if ((frase[i] == 'i') || (frase[i] == 'I')) {
            cont_v = cont_v + 1;
        }else if ((frase[i] == 'o') || (frase[i] == 'O')) {
            cont_v = cont_v + 1;
        }else if ((frase[i] == 'u') || (frase[i] == 'U')) {
            cont_v = cont_v + 1;
        }

    }
    cont_p++;

    // Exibindo o Resultado
    printf("\n\nNumero de PALAVRAS: %d\n", cont_p);
    printf("Numero de VOGAIS: %d\n\n\n", cont_v);
    printf("Programa Finalizado!\n");
    getch();
    return 0;
}

Embedding compile time information into binary

Suppose I have a variable date which is defined with extern in source code, i.e, extern date; then I want to assign a value to it at link time getting time from the computer on which it is compiled and assign to date variable. Is there a way to do that for example in gcc?

How to read the gpt partition table

To read the MBR partition table we use an offset of 0x1be , similarly what is the offset for reading the GPT partition table entries (ie, number of partitions and their sizes).

Iam writing a C program using "gdisk" to create the partitions,I need to write the filesystems onto these partitions. So for this i need to read the gpt header to get the number of partitions and their allocated sizes.

how this custom toupper() function works?

I've seen following program that uses custom toupper() function.

#include <stdio.h> 
void my_toUpper(char* str, int index)
{
    *(str + index) &= ~32;
}
int main()
{
    char arr[] = "geeksquiz";
    my_toUpper(arr, 0);
    my_toUpper(arr, 5);
    printf("%s", arr);
    return 0;
}

How this function works exactly? I can't understand logic behind it. It will be good If someone explains it easily.

Scaling an 8-bit Greyscale RAW in C

Currently, I'm trying to scale a 320x200, 8-bit RAW image to whatever size the user specifies as their preferred resolution. If their resolution is 320x200, It simply uses fread to read the data directly to fill it in, otherwise it'll double all pixels horizontally, producing a 640x200 image. However, this isn't what I want to do, I want to scale exactly to the value of PIXX/PIXY, even if it isn't a multiple. How would I do this?

Here's the important part of the code:

FILE    *f;

int x,y;
int x1,y1;

int c;

char    *p;

f = dopen("art",name,"rb");
if (f == 0) GTFO("Unable to open title");

p = vpage;

if ((PIXX == 320) && (PIXY == 200))
{
    fread(vpage,320,200,f);
}
else
{
    for (y1 = 0; y1 < 200; y1++)
    {
        for (x1 = 0; x1 < 320; x1++)
        {
            c = getc(f);

            *p = c;
            *(p + 1) = c;
            p += 2;
        }
    }
}

fclose(f);

If a function or libary exists that can take the image produced by fread, and perform linear scaling, outputting back to 8-bit raw would be excellent. The image gets stored in vpage.

EDIT: Here's my attempt to use the Bresenham algo, it creates garbage for some reason, but scales the garbage correctly, haha.

#include "imgscale.h"

void ScaleLine(unsigned char *Target, unsigned char *Source, int SrcWidth, int TgtWidth)
{
    int NumPixels = TgtWidth;
    int IntPart = SrcWidth / TgtWidth;
    int FractPart = SrcWidth % TgtWidth;
    int E = 0;
    while (NumPixels-- > 0)
    {
        *Target++ = *Source;
        Source += IntPart;

        E += FractPart;
        if (E >= TgtWidth)
        {
            E -= TgtWidth;
            Source++;
        } /* if */
    } /* while */
}

#define average(a, b)   (unsigned char)(( (int)(a) + (int)(b) ) >> 1)
void ScaleLineAvg(unsigned char *Target, unsigned char *Source, int SrcWidth, int TgtWidth)
{
    int NumPixels = TgtWidth;
    int Mid = TgtWidth / 2;
    int E = 0;
    char p;

    if (TgtWidth > SrcWidth)
    {
        NumPixels--;
    }

    while (NumPixels-- > 0)
    {
        p = *Source;

        if (E >= Mid)
        {
            p = average(p, *(Source+1));
        }

        *Target++ = p;
        E += SrcWidth;
        if (E >= TgtWidth)
        {
            E -= TgtWidth;
            Source++;
        } /* if */
    } /* while */

    if (TgtWidth > SrcWidth)
    {
        *Target = *Source;
    }
}

void ScaleRect(unsigned char *Target, unsigned char *Source, int SrcWidth, int SrcHeight, int TgtWidth, int TgtHeight)
{
    int NumPixels = TgtHeight;
    int IntPart = (SrcHeight / TgtHeight) * SrcWidth;
    int FractPart = SrcHeight % TgtHeight;
    int E = 0;
    char *PrevSource;
    while (NumPixels-- > 0)
    {
        if (Source == PrevSource)
        {
            memcpy(Target, Target-TgtWidth, TgtWidth*sizeof(*Target));
        }
        else
        {
            ScaleLine(Target, Source, SrcWidth, TgtWidth);
            PrevSource = Source;
        } /* if */

        Target += TgtWidth;
        Source += IntPart;
        E += FractPart;

        if (E >= TgtHeight)
        {
            E -= TgtHeight;
            Source += SrcWidth;
        } /* if */
    } /* while */
}

Strange Endianness Behaviour in C [duplicate]

This question already has an answer here:

Here's the C code:

/*Creates an integer of size 4 bytes (on my computer)
  and the value of each byte is equal to the ascii
  values of the characters 'A', 'B', 'C', 'D'*/

int num = ('A' << 24) | ('B' << 16) | ('C' << 8) | 'D';
char *pNum = &num;
printf("%c %c %c %c\n", pNum[0], pNum[1], pNum[2], pNum[3]);
printf("%c %c %c %c", *pNum, *pNum++, *pNum++, *pNum++);

The output is:

D C B A

A B C D

Why is there a difference in the output?

Why does (*p=*p) & (*q=*q); in C trigger undefined behavior

Why does (*p=*p) & (*q=*q); in C trigger undefined behavior if p and q are equal.

int f2(int * p, int * q)
{
  (*p=*p) & (*q=*q);
  *p = 1;
  *q = 2;
  return *p + *q;
}

Source (Nice article by the way): http://ift.tt/O82uIo

printing a doubly linked list by passing head argument

This code is not working properly

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

    struct dllnode{
    int data;
    struct dllnode *next;
    struct dllnode *prev;
};
    typedef struct dllnode *Ndptr;

    struct dllist{
    Ndptr head;
    Ndptr tail;
};
    typedef dllist *Dllist;


    void printlist(Dllist L){
    Ndptr p = L->head;
    while(p!=NULL){
        printf("%d\n",p->data);
        p = p->next;
    }
}

    Ndptr newnode(int val){
    Ndptr  pnew = (Ndptr)calloc(1,sizeof(struct dllnode));
    pnew->data = val;
    pnew->next = NULL;
    pnew->prev = NULL;
    return pnew;
}

    Dllist make_list(Ndptr pnew) {
    Dllist L = (Dllist)calloc(1,sizeof(struct dllist)); 
    L->head =L->tail=pnew; 
    if (pnew) { pnew->prev=pnew->next=NULL;}
    return L;
}


    Dllist insert_before_node (Dllist L, Ndptr pcurr, Ndptr pnew){
    if (!L) return  make_list(pnew);
    if (L->head==NULL){ L->head = L->tail = pnew;  return L;}
    if (!pcurr) return L;   /*error*/ 
    pnew->next = pcurr;
    pnew->prev = pcurr->prev;
    if (pcurr->prev ) 
     pcurr->prev->next = pnew;

    else { L->head = pnew;}
    return L; 
}

    int main(){
    int i;
    int n;scanf("%d",&n);
    Ndptr s = NULL;
    Ndptr p;
    Dllist m=NULL;
    while(n--){
        scanf("%d",&i);
        p = newnode(i);
        m = insert_before_node(m,s,p);
        Ndptr s = p;
    }
    printf("\n");
    printlist(m);

}

But this code does work. remaining every thing same just change in main function

    int main(){
    Ndptr p = newnode(4);
    Ndptr s = newnode(5);
    Ndptr k = newnode(8);
    Ndptr l = newnode(12);
    Dllist m = NULL;
    m = insert_before_node(m,s,p);
    m = insert_before_node(m,p,s);
    m = insert_before_node(m,s,k);
    m = insert_before_node(m,k,l);
    printf("\n");
    printlist(m);

}

please explain why? again there is change in only main function.

How to dynamically construct an argument list in C? [duplicate]

I'm building a stack-based virtual machine for fun. I'm trying to implement an instruction to call C library functions. I have the name of the function as a C-string, the arguments to be passed, and the number of arguments. I'd also like to call variadic functions such as printf. If this cannot be done in standard C, platform specific solution is also welcome, either for Windows or for POSIX systems.

I looked at dlsym and GetProcAddress, but still the problem is that the argument list should be known at compile time, just as a normal C function. I need a way to dynamically construct the argument list and call the function with it.

C++ preprocessor--join arguments

Is there a way to make the C++ preprocessor join arguments with a joiner token?

I've learned that I can do:

#include <boost/preprocessor/seq/cat.hpp>
#define arg1 foo
#define arg2 bar
#define arg3 baz
BOOST_PP_SEQ_CAT((arg1)(_)(arg2)(_)(arg3))

to get foo_bar_baz.

I have two questions:

  1. Is there a way to do it for without the repeated explicit joiner characters ((_)) and for an argument list of variadic length?
  2. Is it necessary to pass the arguments like so:

    (arg1)(arg2)(arg3)
    
    

    Can I wrap it in another macro that'll allow me to pass argument normally, i.e.?:

    arg1, arg2, arg3
    
    

scope of function declaration in c

i have read in various places that functions which are declared in main() cannot be called outside main. But in below program fun3() is declared inside main() and called outside main() in other functions, and IT WORKS, giving output 64.here's link http://ift.tt/1eRZPmy .however,if i change fun3() return type int to void ,it fails to compile,whats reason for this behaviour?

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


int main()
{
    void fun1(int);
    void fun2(int);
    int fun3(int); 

    int num = 5;
    fun1(num);
    fun2(num);
}

void fun1(int no)
{
    no++;
    fun3(no);
}

void fun2(int no)
{
    no--;
    fun3(no);

}

int fun3(int n)
{
    printf("%d",n);
}

Why if I enter sentence other scanf is skipped

If I open enter sentence something like this "asdasd asd asdas sad" for any char scanf it will skip other scanfs.

for exapmle if I type for obligation scanf this sentence it will write for obligation scanf this and next scanf will be skipped but automaticly will be field with sentence word...

Here is the code:

while(cont == 1){
    struct timeval tv;
    char str[12];
    struct tm *tm;

    int days = 1;
    char obligation[1500];
    char dodatno[1500];

    printf("Enter number of days till obligation: ");
    scanf(" %d", &days);
    printf("Enter obligation: ");
    scanf(" %s", obligation);
    printf("Sati: ");
    scanf(" %s", dodatno);

    if (gettimeofday(&tv, NULL) == -1)
        return -1; /* error occurred */
    tv.tv_sec += days * 24 * 3600; /* add 6 days converted to seconds */
    tm = localtime(&tv.tv_sec);
    /* Format as you want */

    strftime(str, sizeof(str), "%d-%b-%Y", tm);

    FILE * database;
    database = fopen("database", "a+");
    fprintf(database, "%s|%s|%s \n",str,obligation,dodatno);
    fclose(database);

    puts("To finish with adding enter 0 to continue press 1 \n");
    scanf(" %d", &cont);
    }

"Segmentation fault" when accesing dynamically allocated struct members

I have started to work on a program which implements a structure called "PhoneBook" having two members: "length" and "allocatedSpace", both of type "unsigned int". The structure is dynamically allocated. The two members of the structure are assigned in an external function called "InitializePhoneBook". Now, when I try to print the values of the two members of the structure inside the "main" function I get a "Segmentation fault" error.

PhoneBook.h

#ifndef PHONEBOOK_H
#define PHONEBOOK_H

struct PhoneBook
{   
    unsigned int length;
    unsigned int allocatedSpace;
};

void InitializePhoneBook(struct PhoneBook *phoneBook);
void ClearPhoneBook(struct PhoneBook *phoneBook);

#endif

PhoneBook.c

#include <stdlib.h>

#include "PhoneBook.h"

void InitializePhoneBook(struct PhoneBook *phoneBook)
{
    phoneBook = malloc(sizeof(struct PhoneBook) * 1);

    phoneBook->length = 0;
    phoneBook->allocatedSpace = 1000;
}

void ClearPhoneBook(struct PhoneBook *phoneBook)
{
    free(phoneBook);
}

main.c

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

#include "PhoneBook.h"

int main(void)
{
    struct PhoneBook *phoneBook;

    InitializePhoneBook(phoneBook);

    printf("%d %d\n", phoneBook->length, phoneBook->allocatedSpace);

    ClearPhoneBook(phoneBook);

    return 0;
} 

Running "./a.out" with "gdb" I get:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400621 in main () at ./main.c:12
12      printf("%u %u\n", phoneBook->length, phoneBook->allocatedSpace);

Reading camera input from /dev/video0 in python or c

I want to read from the file /dev/video0 either through c or python,and store the incoming bytes in a different file. Here is my c code:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main()
{
    int fd,wfd;
    fd=open("/dev/video0",O_RDONLY);
    wfd=open("image",O_RDWR|O_CREAT|O_APPEND,S_IRWXU);
    if(fd==-1)
        perror("open");
    while(1)
    {
        char buffer[50];
        int rd;
        rd=read(fd,buffer,50);
        write(wfd,buffer,rd);
    }

    return 0;
}

When i run this code and after some time terminate the program nothing happens except a file name "image" is generated which is usual.

This is my python code:

    image=open("/dev/video0","rb")
    image.read()

and this is my error when my run this snippet:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] Invalid argument

I want to know how to do this using pure c or python code.Please no external library suggestions.

I dont understand the problem in my code.. i m using codeblocks but still it is giving error "undefined reference to maxum" ...the code finds out the maximum of three numbers ..plzz help

#include<stdio.h>
int maxum(int,int,int);

int main(void)
{
int z=0;
z=maxum(1,2,3);
printf("%d",z);
return 0;
}
int maxum(int a,int b,int c)
{
if(a>>b)
   {
       if(a>>c)
        return a;
       else
        return c;
   }
else if(b>>c)
return b;
else
return c;
}

Creating a Client-Server not on same lan

:) I am building a simple server client connection but I wanted to know if there is any way to connect them without them being on the same LAN, like remote client server. I am writing it in C\C++.

Could you please help me with this c source code for lisp interpreter

I have searched in google about lisp compiler and I found out this source code but I can't understand it. Don't think that I'm newbie in C neither a professional but I don't understand it as its long. A diagram and summary about each function will be helpful.

Here is the link to code.

program c - load a string from a file to a list

struct atleta {
int id;
char nation[3];
char cognome[20];
char nome[20];
struct atleta *next;
};
struct atleta *creaLista2(void)
{
struct atleta *p, *paus;
struct atleta atleti;
int num = 0;
fp_atl = fopen("atleti.txt", "r");

//reading from the file
fscanf(fp_atl,"%d\n", &num);
fscanf(fp_atl,"%d ", &atleti.id);
fscanf(fp_atl,"%s ", atleti.nation);
fscanf(fp_atl,"%s ", atleti.cognome);
fscanf(fp_atl,"%s \n", atleti.nome);
// end reading
if(atleti.id==0)
    p = NULL;

else
{   
    p = (struct atleta *)malloc(sizeof(struct atleta));
    p->id = atleti.id;
    strcpy(p->nation, atleti.nation);
    strcpy(p->cognome, atleti.cognome);
    strcpy(p->nome, atleti.nome);
// other code to create the complete list
} 

the file atleti.txt is:
    2
    5 ITA VOLTA ALESSANDRO
    7 ENG TURING ALAN

    i have to load the second and the third line... 
    but the out is :
    5 ITAVOLTA VOLTA ALESSANDRO --> 7 ENGTURING TURING ALAN

    why the program load in the list ITAVOLTA and not ITA? 
    Thanks in advance! 

Maximum vector value function problems

The function I'm making is supposed to return to the maximum value in a vector, and I'm stumped as to why it's not working, here is the code (I'm new to this site so the formatting will be terrible, apologies):

float max(float vec[], int len) {
int i;
float max;
for (i=0; i < len; i++) {
if (vec[i] > max) {
max = vec[i];
}
}
return max;
}

Ways to print a string of an array

#include <stdio.h>

int main(){
    char arr[] = "HelloWorld";

    printf("%s\n", arr+3); //first line
    printf("%s\n", &arr[4]); //second line
    return 0;
}

Can anyone explain to me the following?

1) why is the output of first line = loWorld?

2) Why is the output of second line = oWorld?

3) Why is there a need to put & in second line?

i am getting time limit exceeded.how can i optimize my code?

problem Statement: Your son's birthday is coming soon (assume that you have a son), and you promised to make the best party ever for him. He will be very happy if he can invite all his friends to this party (he has many friends), but unfortunately you can't invite everyone because you have a limited number of candies, and you want everyone to be happy.

As we all know, kids love to eat a lot of candies of the same type, let's say a kid will be happy only if he can eat at least K candies of the same type.

Given K, and the number of available candies of each type, calculate the maximum number of kids where you can make all of them happy by giving each one at least K candies of the same type.

Input Format: Your program will be tested on one or more test cases. The first line of the input will be a single integer T, the number of test cases (1 ≤ T ≤ 100). Followed by the test cases, each test case is on two lines. The first line of each test case contains two integers N, the number of different candies (1 ≤ N ≤ 100), and K, the minimum number of candies which will make a kid happy as described above (1 ≤ K ≤ 100). The second line of each test case contains N integers, separated by a single space, which are the available number of candies of each type. There will be at least 1 candy and at most 100 candies of each type.

 #include<stdio.h>
  #include<math.h>
  int main(void)
  {
     int i,j,n,t,k,count=0,m;
   int a[100];
    scanf("%d",&t);
   while(t>0)
    {
      scanf("%d %d",&n,&k);
       for(i=0;i<n;i++)
  {
  scanf("%d",&a[i]);
  }
   i=0;
   m=1;
   while(i<n)
  {
   j=a[i]/(k^m);
   count=count+j;

  if(j<1)
  {
    i++;
    m=1;
   }


 }
 t--;
 printf("%d/n",count);
 }
  return 0;
 }

Reversing a two dimensional character array in C

i am trying to write a program which reverses a entire string and also may print reversing each word of the string more than one time. For example my string is: "2 Fox jumps over the lazy dog." for this, the output should be: .god .god yzal yzal eht eht revo revo spmuj spmuj xoF xoF. I am trying to store each word in a 2d array and then reverse each word but i am not able to do that. here is my code. kindly help Note: how do we provide EOF in console

`#include <stdio.h>
 #include <stdlib.h>
 int main()
 {
    char string[100][100];
    char ch;
    int i=0,j=0, l=0, count=0, x=0, y=0;
    while((ch=getchar())!=EOF)
    {
        string[i][l++] = ch;
        if(ch==' ')
        {
           string[i][l] = '\n';
           i++;
           l=0;
           count++;
        }
    }
    for(x=0; x<=count; x++)
    {
       int length = strlen(string[x])-1;
       for(y= length; y>=0; --y)
       {
          printf("%s", string[y]);
       }
    }
    return 0;
}`

copy whole of a file into memory using mmap

i want to copy whole of a file to memory using mmap in C.i write this code:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <errno.h>
int main(int arg, char *argv[])
{
    char c ;
    int numOfWs = 0 ;
    int numOfPr = 0 ;
    int numberOfCharacters ;
    int i=0;
    int k;
    int pageSize = getpagesize();
    char *data;
    float wsP = 0;
    float prP = 0;
    int fp = open("2.txt", O_RDWR);
    data = mmap((caddr_t)0, pageSize, PROT_READ, MAP_SHARED, fp,pageSize);
    printf("%s\n", data);
    exit(0);
}

when i execute the code i get the Bus error message. next, i want to iterate this copied file and do some thing on it. how can i copy the file correctly?

When to cast size_t

I'm a little confused as how to use size_t when other data types like int, unsigned long int and unsigned long long int are present in a program. I try to illustrate my confusion minimally. Imagine a program where I use

void *calloc(size_t nmemb, size_t size)

to allocate an array (one- or multidimensional). Let the call to calloc() be dependent on nrow and sizeof(unsigned long int). sizeof(unsigned long int) is obviously fine because it returns size_t. But let nrow be such that it needs to have type unsigned long int. What do I do in such a case? Do I cast nrow in the call to calloc() from unsigned long int to size_t?

Another case would be

char *fgets(char *s, int size, FILE *stream)

fgets() expects type int as its second parameter. But what if I pass it an array, let's say save, as it's first parameter and use sizeof(save) to pass it the size of the array? Do I cast the call to sizeof() to int? That would be dangerous since int isn't guaranteed to hold all possible returns from sizeof().

What should I do in these two cases? Cast, or just ignore possible warnings from tools such as splint?

Here is an example regarding calloc() (I explicitly omit error-checking for clarity!):

long int **arr;
unsigned long int mrow;
unsigned long int ncol;

arr = calloc(mrow, sizeof(long int *));

for(i = 0; i < mrow; i++) {
        arr[i] = calloc(ncol, sizeof(long int));
}

Here is an example for fgets() (Error-handling again omitted for clarity!):

char save[22];
char *ptr_save;
unsigned long int mrow
if (fgets(save, sizeof(save), stdin) != NULL) {
        save[strcspn(save, "\n")] = '\0';
        mrow = strtoul(save, &ptr_save, 10);
}

Save lines from file into new string. C

I need to save lines from a text file into a string and then insert them into a data structure, but with my solution (which I assume is really bad) - I only save words into my line.

    FILE * ifile = fopen("input.txt", "r");
    char line[256];

    while(fscanf(ifile, "%s\n", line) == 1) {
        //inserting "line" into data structure here - no problem with that one
   }

Bitoperation OR vs addition

I am reading an uint16 from a sensor connected to an raspberry (arm). I convert the data from little endian to big endian via:

// result = 0A0B0C0D 0E0F0A0B
// 0E0F0A0B 00000000 | 00000000 0A0B0C0D
((result << 8) & 0xFF00) | (result >> 8);

So 0A0B0C0D 0E0F0A0B is 0E0F0A0B 0A0B0C0D afterwards.

But I also saw people using this:

((result << 8) & 0xFF00) + (result >> 8);

Is there any advantage of using the addition? My guess is, there is no really advantage, it is just a bit slower.

There is a big difference when it comes to sum two numbers for example:

EF10 = 0FF0 + 00FF != 0FF0 | 00FF = 0FFF

Maybe I answered my own question already but it would be nice, if someone could evaluate. Would not be the first time I am tricking myself.

While loop error while implementing 'strend'

I keep getting errors when I run the program I wrote for 'strlen'. (strlen returns 1 when one string appears at the end of another). I guess it's the first while loop that gives the error, because when I put printf("%c\n", *s); instead of empty ;, it just works fine. Is there something wrong with the syntax???

#include <stdio.h>

int strend(char *s, char *t)
{
    int len;
    int dummy;
    while ( *s++ )
        ; // why error???
    while ( *t++ )
        len++;

    for ( ; len>0 ; len--)
    {
        if ( *(s-len) != *(t-len) )
            return 0;
    }
    return 1;
}

int main() {
    char one[] = "I 0dont like youa";
    char two[] = "ke youa";
    printf("%d\n", strend(one, two));
}

"Adress out of bound" when accessing second element of a pointer passed to a function

I have this function:

int scan_arguments(int *words_count, char ***words, char **file)
{
    /* If the first argument is equal to "/f" copy the second argument in the file variable */
    if (*words_count > 2 && !strncmp(*words[0], "/f", 2)) {
        if(!(file = malloc(strlen(*words[1]) + 1))) {
            printf("Allocation error");
            return 1;
        }
        strcpy(*file, *words[1]);
        words += 2;
        words_count -= 2;
}

And I call it this way from my main function:

int main(int argc, char **argc)
{
    char *file = "", **words;
    int words_count;

    /* Copy the arguments and discard the program name */
    words = argv + 1; 
    words_count = argc - 1;

    scan_arguments(&words_count, &words, &file);
}

The purpose of my function is to check if the first argument is "/f" and, if it is, store the second argument in the file string.

The problem is that when execution reaches the strlen(*words[1]) part, the program stops working and from the debugger I get "Adress out of bound". I can't understand what's the problem, because *words[0] gets evalueted correctly.

Sorry if it is maybe a simple question but it's my first serious program with pointers and I still have some difficulties.

Thanks for your help!

Access Violation error. AVL TREE during insertion. C

So I got an AVL tree online for a project. and I am trying to insert elements with a loop to see if it works. obviously its not working. am getting an access violation error.

here is the tree. the code is long. I know. but I can tell you that its in the insert function not the others

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

#define FALSE 0
#define TRUE 1




MY_TREE deldata(MY_TREE pRoot, int, int *);
MY_TREE delete_node(MY_TREE pRoot, MY_TREE hNode, int *);
Node_ptr balright(Node_ptr pRoot, int *);
Node_ptr balleft(Node_ptr pRoot, int *);
void display(MY_TREE pRoot);
void tree_destroy(MY_TREE pRoot);
Node_ptr  balleft(Node_ptr pRoot, int *h);
MY_TREE insert(MY_TREE hRoot, int data, int *h);
void init_tree_functions(Node_ptr pRoot);


struct node
{


    MY_TREE(*deldata)(MY_TREE pRoot, int, int *);
    void(*display)(MY_TREE pRoot);
    void(*tree_destroy)(MY_TREE pRoot);
    MY_TREE(*insert)(MY_TREE hRoot, int data, int *h);



    int data;
    int balfact;
    Node_ptr left;
    Node_ptr right;
};


void init_tree_functions(Node_ptr pRoot){

    pRoot->tree_destroy = tree_destroy;
    pRoot->deldata = deldata;
    pRoot->display = display;
    pRoot->insert = insert;


}


//MY_TREE my_tree_init_default(){
//
//  Node_ptr pRoot;
//
//  pRoot =(Node_ptr) malloc(sizeof(Node));
//  
//  if (pRoot == NULL){
//
//      printf("Bad stuff \n"); 
//
//      exit(1);
//  }
//
//  pRoot->left = NULL;
//  pRoot->right = NULL;
//  pRoot->data = NULL;
//  pRoot->balfact = 0;
//  init_tree_functions(pRoot);
//
//  
//
//  return (MY_TREE)pRoot;
//
//}

MY_TREE insert(MY_TREE hRoot, int data, int *h)
{
    Node_ptr  node1, node2;
    Node_ptr pRoot = (Node_ptr)hRoot;



    if (pRoot==NULL)
    {
        pRoot = (Node_ptr) malloc(sizeof(Node));



        pRoot->data = data;
        pRoot->left = NULL;
        pRoot->right = NULL;
        pRoot->balfact = 0;
        *h = TRUE;



        return ((MY_TREE)pRoot);
    }

    if (data < pRoot->data)
    {
        pRoot->left = insert((MY_TREE)pRoot->left, data, h);

        if (*h)
        {
            switch (pRoot->balfact)
            {
            case 1:
                node1 = pRoot->left;
                if (node1->balfact == 1)
                {

                    pRoot->left = node1->right;
                    node1->right = pRoot;
                    pRoot->balfact = 0;
                    pRoot = node1;
                }
                else
                {

                    node2 = node1->right;
                    node1->right = node2->left;

                    node2->left = node1;
                    pRoot->left = node2->right;
                    node2->right = pRoot;
                    if (node2->balfact == 1)
                        pRoot->balfact = -1;
                    else
                        pRoot->balfact = 0;
                    if (node2->balfact == -1)
                        node1->balfact = 1;
                    else
                        node1->balfact = 0;
                    pRoot = node2;
                }
                pRoot->balfact = 0;
                *h = FALSE;
                break;

            case 0:
                pRoot->balfact = 1;
                break;

            case -1:
                pRoot->balfact = 0;
                *h = FALSE;
            }
        }
    }

    if (data > pRoot->data)
    {
        pRoot->right = insert((MY_TREE)pRoot->right, data, h);

        if (*h)
        {
            switch (pRoot->balfact)
            {
            case 1:
                pRoot->balfact = 0;
                *h = FALSE;
                break;

            case 0:
                pRoot->balfact = -1;
                break;

            case -1:
                node1 = pRoot->right;
                if (node1->balfact == -1)
                {

                    pRoot->right = node1->left;
                    node1->left = pRoot;
                    pRoot->balfact = 0;
                    pRoot = node1;
                }
                else
                {

                    node2 = node1->left;
                    node1->left = node2->right;
                    node2->right = node1;

                    pRoot->right = node2->left;
                    node2->left = pRoot;

                    if (node2->balfact == -1)
                        pRoot->balfact = 1;
                    else
                        pRoot->balfact = 0;
                    if (node2->balfact == 1)
                        node1->balfact = -1;
                    else
                        node1->balfact = 0;
                    pRoot = node2;
                }
                pRoot->balfact = 0;
                *h = FALSE;
            }
        }
    }

    return ((MY_TREE)pRoot);
}


MY_TREE deldata(MY_TREE hRoot, int data, int *h)
{
    Node_ptr pRoot = (Node_ptr)hRoot;
    Node_ptr node;

    if (!pRoot)
    {

        return (pRoot);
    }
    else
    {
        if (data < pRoot->data)
        {
            pRoot->left = deldata((MY_TREE)pRoot->left, data, h);
            if (*h)
                pRoot = balright(pRoot, h);
        }
        else
        {
            if (data > pRoot->data)
            {
                pRoot->right = deldata((MY_TREE)pRoot->right, data, h);
                if (*h)
                    pRoot = balleft(pRoot, h);
            }
            else
            {
                node = pRoot;
                if (node->right == NULL)
                {
                    pRoot = node->left;
                    *h = TRUE;
                    free(node);
                }
                else
                {
                    if (node->left == NULL)
                    {
                        pRoot = node->right;
                        *h = TRUE;
                        free(node);
                    }
                    else
                    {
                        node->right = delete_node((MY_TREE)node->right, node, h);
                        if (*h)
                            pRoot = balleft(pRoot, h);
                    }
                }
            }
        }
    }
    return ((MY_TREE)pRoot);
}

MY_TREE  delete_node(MY_TREE hSucc, MY_TREE hNode, int *h)
{

    Node_ptr node = (Node_ptr)hNode;
    Node_ptr succ = (Node_ptr)hSucc;

    Node_ptr temp = succ;
    if (succ->left != NULL)
    {
        succ->left = delete_node((MY_TREE)succ->left, node, h);
        if (*h)
            succ = balright(succ, h);
    }
    else
    {
        temp = succ;
        node->data = succ->data;
        succ = succ->right;
        free(temp);
        *h = TRUE;
    }
    return ((MY_TREE)succ);
}


Node_ptr balright(Node_ptr pRoot , int *h)
{
    Node_ptr node1, node2;

    switch (pRoot->balfact)
    {
    case 1:
        pRoot->balfact = 0;
        break;

    case 0:
        pRoot->balfact = -1;
        *h = FALSE;
        break;

    case -1:
        node1 = pRoot->right;
        if (node1->balfact <= 0)
        {

            pRoot->right = node1->left;
            node1->left = pRoot;
            if (node1->balfact == 0)
            {
                pRoot->balfact = -1;
                node1->balfact = 1;
                *h = FALSE;
            }
            else
            {
                pRoot->balfact = node1->balfact = 0;
            }
            pRoot = node1;
        }
        else
        {

            node2 = node1->left;
            node1->left = node2->right;
            node2->right = node1;

            pRoot->right = node2->left;
            node2->left = pRoot;

            if (node2->balfact == -1)
                pRoot->balfact = 1;
            else
                pRoot->balfact = 0;
            if (node2->balfact == 1)
                node1->balfact = -1;
            else
                node1->balfact = 0;
            pRoot = node2;
            node2->balfact = 0;
        }
    }
    return (pRoot);
}


Node_ptr  balleft(Node_ptr pRoot, int *h)
{
    Node_ptr  node1, node2;

    switch (pRoot->balfact)
    {
    case -1:
        pRoot->balfact = 0;
        break;

    case 0:
        pRoot->balfact = 1;
        *h = FALSE;
        break;

    case 1:
        node1 = pRoot->left;
        if (node1->balfact >= 0)
        {

            pRoot->left = node1->right;
            node1->right = pRoot;
            if (node1->balfact == 0)
            {
                pRoot->balfact = 1;
                node1->balfact = -1;
                *h = FALSE;
            }
            else
            {
                pRoot->balfact = node1->balfact = 0;
            }
            pRoot = node1;
        }
        else
        {

            node2 = node1->right;
            node1->right = node2->left;
            node2->left = node1;

            pRoot->left = node2->right;
            node2->right = pRoot;

            if (node2->balfact == 1)
                pRoot->balfact = -1;
            else
                pRoot->balfact = 0;
            if (node2->balfact == -1)
                node1->balfact = 1;
            else
                node1->balfact = 0;
            pRoot = node2;
            node2->balfact = 0;
        }
    }
    return (pRoot);
}


void display(MY_TREE hRoot)
{

    Node_ptr pRoot = (Node_ptr)hRoot;
    if (pRoot != NULL)
    {
        display(pRoot->left);
        printf("%d\t", pRoot->data);
        display(pRoot->right);
    }
}


void tree_destroy(MY_TREE hRoot)
{
    Node_ptr pRoot = (Node_ptr)hRoot;
    if (pRoot != NULL)
    {
        tree_destroy(pRoot->left);
        tree_destroy(pRoot->right);
    }
    free(pRoot);
}

this is the loop I have.

MY_TREE pRoot=NULL;

//pRoot = my_tree_init_default();



for (i = 0;  i < 99; i++){
    number = i;
    pRoot=pRoot->insert(pRoot, number, pResult);
    printf("a");


}

its crashing before 1 element is added. however when I do the init function. 1 element is added before it crashes. I think it has to do with the function pointers.

Getting compilation error for dos.h and iostream.h "no such file or directory" in Android JNI

I am working on Android NDK app in which I have to generate a sound. I have written a program in cpp by which I am able to generate a sound. below is my cpp snippet.

#include <dos.h>
#include<iostream.h>
void main()
{
    ...
    sound(1000);
    delay(1000);
    nosound();
    ...
}

So, I have written above code in Android JNI, but getting compilation error for dos.h and iostream.h "no such file or directory". Am I missing something here?

The main task is to play an audio sinewave from c++ by giving a call from android using JNI. The frequency of the sine wave has to be passed from the android code.

File descriptors before fork()

I know that if I call the open function before the fork() the IO pointer is shared between the processes.

My question is: if one of these processes closes the file calling the close(fd) function, will the other processes be still capable of write/read the file or the file will be closed for everyone? Thanks

samedi 27 juin 2015

I don't know how to convert 16 byte hexadecimal to floating point

Probably from the time I am trying to convert and wandering internet solely for the answer of this question but I could not find. I just got I can convert hexadecimal to decimal either by some serious programming or manually through math. I am looking to convert. If there is any way to do that then please share. Well I have searched and found IEEE754 which seems not to be working or I am not comprehending it. Can I do it manually through any equation, I think I heard about it? Or a neat C program which may do it.

Please help! Any help would be highly appreciated.

How can I use Bit-Fields to save memory?

This is about ANSI-C (C90).

This is what i know: I can directly tell the compiler how many bits i want for a specific variable. If I want 1 bit which can have the values zero or one. or 2 bits for the values 0,1,2,3, and so on...;

I'm familiar with the syntax.

I have problem concering bitfields: If I want to define a SET structure. It can have maximum 1024 elements(can have less. but max is 1024 elements) And the domain of the set is from 1 to 1024 . so an element could have value 1-1024.

I'm trying to create a structure for a SET. and it must be efficient as possible, for the memory part.

I tried :

typedef struct set
{
    unsigned int var: 1;
} SET;
//now define an array of SETS
SET array_of_sets[MAX_SIZE]  //didn't define MAX_SIZED , but no more than 1024 elements in each set.

I know this isn't effiecient, maybe its even not good for what I want, that's why I'm looking for help.

thanks.

given a number of characters. how do I make every possible combination into a string. C

first this is part of a much bigger program. so I have a vector of strings. all the strings are of the same size. but their common size can be different. and I have a bunch of letters. and a dash. '-'. its a game that if I explain i'd get [ON HOLD] for being too broad. so I will keep it simple. I input 1 letter. and I make combinations of strings of that letter depending on the common size of strings. say we have strings with size 4 and the first letter is 'a'. the combinations could be a---, aa---,aaa-,aaaa,-a--. etc. you get the point. again the size of the string can be different. lets say now I input a second letter.'b'. the strings could be ab--, abab. a---b. and even a---. the letter doesn't have to be included. even first time. ---- is valid. how do I do that. generate every possible key. current letter doesn't have to be included. and put everyone in a vector of strings.

error: invalid type argument of '->' (have 'int')|

I am getting the following error while creating a function for creating a graph using adjaceny LIST representation:

error: invalid type argument of '->' (have 'int')

I have marked the line (in comments) where I am getting this error as //error. Below is the code:

typedef struct GRAPH
{
    int V;
    int E;
    int *adj; //head pointer to the Linked List
} graph;

typedef struct NODE //Node of the Linked List
{
    int vertexNumber;
    struct NODE *next;
} node;

graph *adjListOfGraph()
{
    int i,x,y;
    node *temp;
    graph *g;
    g = (node *)malloc(sizeof(graph));
    if(!g)
    {
        printf("Memory Error in creating the graph");
        return;
    }
    scanf("Number of Vertex: %d, Number of Edges: %d", &g->V,&g->E);
    g->adj=(node *)malloc(g->V *sizeof(node));
    for(i=0;i<g->V;i++)
    {
        g->adj[i] = (node *)malloc(sizeof(node));
        g->adj[i]->vertexNumber = i;    //error
        g->adj[i]->next = g->adj[i];    //error
    }
    for(i=0;i<g->E;i++)
    { 
        scanf("Reading edges: %d %d", &g->V,&g->E);
        temp = (node *)malloc(sizeof(node));
        temp->vertexNumber = y;
        temp->next = g->adj[x];
        g->adj[x]->next = temp;   //error
        temp = (node *)malloc(sizeof(node));
        temp->vertexNumber =y;
        temp->next = g->adj[y];
        g->adj[y]->next = temp;   //error
    }
    return g;
}

Please have a look at lines commented as error. I have searched a lot and also tried replacing -> by . but useless.

Reading text file of unknown size

I am trying to read in a text file of unknown size into an array of characters. This is what I have so far.

#include<stdio.h>
#include<string.h>

    int main()
    {
            FILE *ptr_file;
            char buf[1000];
        char output[];
            ptr_file =fopen("CodeSV.txt","r");
            if (!ptr_file)
                return 1;   

        while (fgets(buf,1000, ptr_file)!=NULL)
            strcat(output, buf);
        printf("%s",output);

    fclose(ptr_file);

    printf("%s",output);
        return 0;
}

But I do not know how to allocate a size for the output array when I am reading in a file of unknown size. Also when I put in a size for the output say n=1000, I get segmentation fault. I am a very inexperienced programmer any guidance is appreciated :)

The textfile itself is technically a .csv file so the contents look like the following : "0,0,0,1,0,1,0,1,1,0,1..."

Blocking sockets

I'm programing a small c linux local server. I've read a lot of documentation about threads, select function, nonblocking options, etc. But I can't find any documentation about how to deal with client-side failures.

More specifically, working with threads and blocking sockets (not the best idea, I know, but I'm just running some tests), what happens when the client connection goes too slow? or what happens when the client doesn't close the connection properly (or not closing it at all)? Will my socket remain blocked? or the thread will never finish?

How to deal with this situations?

Appending two strings without str functions

I'm having an issue trying to figure out how to append the char pointer c to the existing Struct String. I want to be able to take in input as such (considering a predefined Struct with the value of stuff being "Hello") append(test,"world") When I try to use strcat and strcpy I get an error because the structure String is not a valid type to be used with this function.

How do I append without the use of the str functions?

I currently have code that declares a structure and sets stuff to be the value of the contents of the structure in this case hello I enter my function and check if the data the person is passing is not null. I create a new String Struct called append and realloc memory to the new size of the previous "stuff" plus the value of *c. Should I use a for loop to get the contents of *c at the point [i] into the end of append?

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

typedef struct strstf {
    char   *stuff;   
    size_t  length;   
} String;




 String *append(String *b, const char *c){
        String* append;

         if(!(c = NULL)){
            /*creates memory the size of the original string buffer and the added string*/
                 b->stuff realloc(strlen(c) + strlen(b->stuff) + 1);
                 strcpy(append, b->stuff);
                 strcat(append, c);
                 return append;  
            }
            if (append->stuff == NULL) {
                 free(append);  
                 return NULL;
            }
        return append;
    }

strcpy Signal SIGABRT

I know it's a common question but I didn't find a suitable explanation yet! My project compiles but I keep getting the Thread: signal SIGABRT! - the strcpy function; nothing's written in the debugger window and when I debug step by step the test works perfectly fine and I get success, but when I try to run it again I get that error! How can I fix it?

here's my code :

static char* copyMember(const char* str){
    if(str==NULL){
        return NULL;
    }
    char* newStr=malloc((strlen(str)+1)*sizeof(char));
    if(newStr==NULL){
        return NULL;
    }
    return strcpy(newStr, str);
}

error in creating array of linked list

I have to put nodes of binary search tree of every level in a linked list. That is if the height of the tree is 'h' then 'h+1' linked lists would be created and then each linked list would have all the nodes of each level. For this I have thought of creating an array of linked list. But the nodes are not being inserted in the list I guess. The code is as follows:-

struct node{ 
    int data;
    struct node *left;
    struct node *right;
    };

struct linked_list
{

    int data;
    struct linked_list *next;
};

    linkedlistofbst(struct node *new,struct linked_list *n1[], int level)
    {
    //printf("%d ",new->data);
    if(new==NULL)
    {
        return;
    }

    if(n1[level]==NULL)
    {
        struct linked_list *a =(struct linked_list *)malloc(sizeof(struct linked_list));
        a->data=new->data;
        a->next=NULL;
        n1[level]=a;
        printf("%d ",a->data);
    }
    else
    {
        struct linked_list *b =(struct linked_list *)malloc(sizeof(struct     linked_list));
        while(n1[level]->next!=NULL)
        {
            n1[level]=n1[level]->next;
        }
        b->data=new->data;
        b->next=NULL;
        n1[level]=b;
    }
    linkedlistofbst(new->left,n1,level+1);
    linkedlistofbst(new->right,n1,level+1);
    }

    main()

{
    struct linked_list *l=(struct linked_list *)malloc((a+1)*sizeof(struct    linked_list));//'a' is the height of the tree
    linkedlistofbst(new,&l, 0);//new is the pointer to the root node of the tree.
}

comparing strings to characters and generating keys? [on hold]

ok there is no easy way to put this in the title.

I know I have no code but I have no idea how do this at all.

ok. so here is what I need to do. I have a vector of strings. all of these words are the same length (but the word length can change). and its a contest. the user picks a letter. and I am supposed to find words that have the letter. but its a little more complicated than that. lets say the vector has 4 letter words in it. words such as ball, bell, boby, mark, abba, baab. and the keys for each word in order if I guessed the letter b. b---, b---, b-b-, ----, -bb-, b--b. so you see. basically the key is the word with the letters that are not guessed replaced with a '-'. now lets say that there are 10 words with key b---, 5 word with key b--b, 1 word with key ----, 2 words with key ---b. there are a lot of possibilities for a key depending on how many letters. then I am supposed to delete all the words with the keys that are not the most. so the words with the most frequent key stay. the question is. how do I do all of that.

now I know its easiest to make two vectors. one to keep the keys. and one to keep how many times a key occurs both vectors have corresponding indexes to make my life easier. or I guess I could make a vector that stores a structure of both the key and how many times it occurs. but lets ignore that. how do I generate the keys from the words. and how do I figure out how many times a key occurred. and then how do I delete the words or move the words with the most frequent key somewhere else.

again. I could guess more than once. if I guess with letter c the second time. then the key could be a combination of b and c in words. b--c. bbcc. b-c- but since I had picked b first then b stays in the buffer (except if at first we selected the key ---- as most frequent) then the second guess would basically be the first guess with words that do not contain the letter b. because the most frequent key was ----. this is too long. but I appreciate some help.

edit. I basically need to get the most words with the most common key separated from a vector of strings into their own vector of strings.

subset sum recursive solution producing incorrect output

Followed this method (pdf) to implement a recursive solution, but I think it is buggy. I have exactly implemented it as described in the pdf file.

The output of the code below is wrong. It shows the target locations. The target array contains bit representation of the numbers that should be added to get the sum.

Placing the binary[i] = 1 in else if condition fixes the problem, but it doesn’t make sense. Is it possible to clarify what is the right solution?

#define SIZE(a) sizeof(a)/sizeof(a[0])
int binary[100];
void foo(int target, int i, int sum, int *a, int size) {
    binary[i] = 1;
    if (target == sum+a[i]) {
        int j;
        for (j=0;j<size;j++)
            printf("%d\n", binary[j]);
        return;
    } else if ((i+1 < size) && (sum + a[i] < target)) {
        foo(target, i+1, sum + a[i], a, size);
    }
    if ((i+1 < size) && (sum +a[i+1] <= target)) {
        binary[i] = 0;
        foo(target, i+1, sum, a, size);
    }
}

int main()
{
    int i, target =10,a[] = {1, 2, 3, 5, 100};
    foo(target, 0, 0, a, SIZE(a));
}

Current output: 0 1 1 1 1 Expected output: 0 1 1 1 0

vendredi 29 mai 2015

Get Bot Margin to AddPage - FPDF

My PDF file is a table completed with values from a server.
And if the next line created is too large to display on the end of the page, I want to add a new page, then insert my new line.

I guess I must do some maths with $height_of_cell (which I calculate), getY() and margin-bottom but I don't know, and I didn't find how to get this last value.
Does anyone know ? Thank you !

Laravel 4.2 - PHP Error reporting turned off

My Laravel 4.2 application runs happily with undefined variables or array indexes.

I have placed

ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);

in many places in my code in an attempt to get this happen.

The php.ini contains

error_reporting = E_ALL

Debugging is true in app.php.

I have grep'd all of the Laravel and vendor code and my code to look for locations where error reporting may have been turned off, but none seems relevant.

Non-Laravel web applications on the same server crash and/or report properly for these kinds of errors.

PHP is 5.6.8 on Fedora and 5.5. on Centos.

connecting to MS access with php when defined password for database

I am trying to connect Ms Access DataBase from php . My codes like this in config.php

 define('DBNAMEACCESS',  '\\'."\\xxx.xxx.xxx.xxx\\test\\test.accdb");
        define('DBACCESSPASSWORD', 'mypassword');
        define('DBACCESSUSERNAME', '');

and in process.php like this:

     include './config.php';
   if (!file_exists(DBNAMEACCESS)) {
            die("Could not find database file.");
        }
 try{
            $dbName=DBNAMEACCESS;
            $username=DBACCESSUSERNAME;
            $password=DBACCESSPASSWORD;
             $dba = odbc_connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$dbName",$username, $password);

   if ($dba) {
/*......*/
} else
            {
                die("Could not connect to access database");
            }
             }
        catch (Exception $ex) {
//            var_export($ex);
                setmessage($ex) ;
        }

when the password is defined for access file , I get this error on this line: My error: odbc_connect(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Cannot open database '(unknown)'. It may not be a database that your application recognizes, or the file may be corrupt., SQL state S1000 in SQLConnect in this line

         $dba = odbc_connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$dbName",$username, $password);

and when the password is not defined for access file,My codes execute correctly.

CSS IDs not working when extension is hidden

I developed my site with extensions visible, but when I finished and wanted to make it to production. Now I did a htaccess to hide extensions and add a trailing slash, when people click on a button which redirects/links to #tab1, the url becomes: http://ift.tt/1FHzXSQ

And the CSS ID doesn't open up (the tab).

Is there a way to fix this?

Thanks in advance

zend gdata and google spreadsheet not connecting

ive been using Zend Gdata for a while now, and today im getting an error of

Notice: Undefined offset: ClientLogin.php on line 150

via php, this has been working for a while now, and today without changing anything it stopped working, im guessing some deprecated service on behalf of google with the zend gdata maybe the Zend_Gdata_ClientLogin::getHttpClient( ) method or something, can any one confirm or help me with this issue. the code im using to connect is as follows:

    require_once('Zend/Loader.php');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Docs');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
require_once 'Zend/Gdata.php';
require_once 'Zend/Gdata/AuthSub.php';
require_once 'Zend/Gdata/Spreadsheets.php';
require_once 'Zend/Gdata/Spreadsheets/DocumentQuery.php';
require_once 'Zend/Gdata/Spreadsheets/ListQuery.php';
require_once 'Zend/Loader.php';


$sourceUser = "myemail";
$sourcePass = "mysuperawesomepassword";
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$sourceClient = Zend_Gdata_ClientLogin::getHttpClient($sourceUser, $sourcePass, $service);
$connection = new Zend_Gdata_Spreadsheets($sourceClient);

i am using the zend gdata with the google spreadsheets

also the error points specifically to this line

$sourceClient = Zend_Gdata_ClientLogin::getHttpClient($sourceUser, $sourcePass, $service);

as i said, i was using this for a while now, and nothing has changed on my end

foreach loop in json encode array

I am sending preformatted HTMl with AJAX JSON, JSON have below code,

I am trying pull data array from DB and echoing array data, I am not able to put foreach loop in json_encode, because seems my code is wrong at foreach loop,

How can i achieve that?

echo json_encode(array('returnnews' => '<div class="news-item-page">
                                    <h3 class="text-info" style="margin-top:0">'.$latestnews->news_subject.'</h3>
                                    '.$latestnews->news_content.'


                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <ul class="list-inline blog-tags">
                                            <li>
                                                <i class="fa fa-tags"></i>'.
                                                foreach($news_tag_array as $tag){
                                                <a href="javascript:;">
                                                echo $tag </a>
                                               }

                                            </li>
                                        </ul>
                                    </div>
                               </div>'));

Zend Form ->addValidator('Digits') not working

I am trying to add validator to my Text field as i am expecting user to only enter positive integers. But its not working neither showing any error message if we enter value like '-50'. The code is, $AddInventory = new Zend_Form_Element_Text('AddInventory'); $AddInventory->setAttrib('dojoType',"dijit.form.ValidationTextBox");
$AddInventory->setAttrib('maxlength','40') ->setAttrib('style','width:200px') ->setAttrib('required',"false") ->addValidator('NotEmpty') ->addFilter('StripTags') ->addValidator('Digits')
->removeDecorator("DtDdWrapper") ->removeDecorator("Label") ->removeDecorator('HtmlTag');

Ajax call onSubmit not working

I have a log-in form. Before do the log-in I would like to make sure that username and password are true.. I am trying to achieve this with ajax, but so far it is not working..

in my form I am calling the function check_user onSubmit. This is my code.

    function check_user(e){
        var username = $('#username').val();
        var password = $('#password').val();

        if(username.length>1 && password.length>1){
        e.preventDefault(); // I added this but still it is not working
        alert('alive'); // this is working          

                jQuery.ajax({
                    type : "POST",
                    url : "check_user.php",
                    data : 'username=' + username +"&password=" + password,
                    cache : false,
                    success : function(response) {
                        if (response == 1) {
                        return true;                    
                        } else {        
                        $('#username').css('border', '2px red solid');
                        document.getElementById("username").placeholder = "Wrong username or password";
                        $('#password').css('border', '2px red solid');
                        document.getElementById("password").placeholder = "Wrong username or password";                     
                        return false;                   
                        }
                    }
                });     
        }else{
//this is working
            $('#username').css('border', '2px red solid');
            document.getElementById("username").placeholder = "Wrong username or password";
            $('#password').css('border', '2px red solid');
            document.getElementById("password").placeholder = "Wrong username or password";
            return false;   
        }
    }

In my PHP file check_user.php I have also this code:

$fp = fopen("debug.txt", "a") or die("Couldn't open log file for writing.");
        fwrite($fp, PHP_EOL ."inside");
        fflush($fp);
        fclose($fp);

No debug.txt is created so I assume that the ajax call never happens..

I use the same ajax code when doing the registration to check if the username or email already exists in the database, and the ajax there is working ok. In my example the ajax call never happens and it goes straight to the action="login.php"

Build PHP array with string and result 2 dimensional arrays

I have a smart problem in PHP, I build an array with a string, and at the same time I cut some images. buildProject.php is include in index.php (session_start(); for _session is on the top of it).

buildProject.php

<?php
  $list_projet = array(
    0 => 'img0_pres',
    1 => 'img1_pres',
    2 => 'img2_pres',
  );
  $height_decoup = 500;
  $projet = array();

  foreach ($list_projet as $key => $value) {
    $name_source = $value;
    $img_source_file = 'images/projet/'.$name_source.'.jpg';
    $img_source = imagecreatefromjpeg($img_source_file);

    $width = imagesx($img_source);
    $height = imagesy($img_source);
    $ratio = ceil($height/$height_decoup);
    $img_dest_height = $height_decoup;

    $nb_img_decoup = 1;
    $img_source_y = 0;

    while ($nb_img_decoup <= $ratio) {
      if ($nb_img_decoup == $ratio) {
        $img_dest_height = $height - $height_decoup*($ratio-1);
      }
      $img_dest = imagecreatetruecolor($width,$img_dest_height);
      imagecopy($img_dest, $img_source, 0, 0, 0, $img_source_y, $width, $img_dest_height);
      $img_dest_file = 'images/projet/'.$name_source.'_'.$nb_img_decoup.'.jpg';
      imagejpeg($img_dest, $img_dest_file);

      $projet[$key][$nb_img_decoup] = $img_dest_file; // I SUPPOSE AN ERROR HERE
      $img_source_y += $height_decoup;
      $nb_img_decoup++;
    }
    imagedestroy($img_source);
    imagedestroy($img_dest);
  }
  echo $img_dest_file[0]; // give me an 'i' and suppose give me an error
  echo $projet[0][1][0]; // idem...

  $_SESSION['txt'] = $projet;
?>

After build it, I send it to getProjet.php to find it on main.js with getJSON. My Probleme is $img_dest_file transform alone in array and i need a string!

I thinks the problem is on buildProject.php but I put the other files maybe there are an other error can do that.

getProject.php

<?php
session_start();
$projet = $_SESSION['txt'];

if(isset($_GET['list']) && $_GET['list']>=0){
    echo json_encode($projet[$_GET['list']]);
} ?>

main.js

$.getJSON('php/getProject.php?list=' + index, function(data) {
    length = data.length;
    console.log(data+' //// '+length); // [object object] //// undefined
    console.log(data[1].length); // 29 (total of caracteres...)
    console.log(data[1]); // images/projet/img0_pres_1.jpg
    console.log(data[1][0]); // i
}

So in main.js data=([object object]) and I need data=([object]). I think it's because when i run buildProject.php $img_dest_file transform alone in array and it's normaly just a string not an array.

If someone has an idea why $img_dest_file transform alone in array?

Thanks for reading. If you have question I can specify more.

CSS not being executed in Woocommerce Wordpress template file

I have a fully functional Wordpress custom theme. I have just installed Woocommerce and followed this guide. I have followed the very basic instructions to copy page.php, rename it and modify the loop. I have done this and am able to use Woocommerce, however in the page.php file, I have a

<?php get_header(); ?>

command, which successfully displays that part of the layout in my normal wordpress pages. However, in the direct clone which is now called woocommerce.php, it is not working fully, The links show up, but without any of the associated css which is linked into the header file. Any ideas why two versions of the same file would mean only one correctly imports / interprets the css?

Here are the two web pages:

http://ift.tt/1KhbKno
http://ift.tt/1eCIbmf

Google Calendar API Time

When I try to format 2015-05-29T19:30:00+08:00 from google calendar api;

return \Carbon\Carbon::createFromTimeStamp(
        strtotime('2015-05-29T19:30:00+08:00')
        );

I get the result 2015-05-29 11:30:00 But the start date of the event in my google calendar is exactly 07:30PM One thing is that if I try to add a ->diffForHumans(); I get the result:

16 minutes ago (Note: the time I run the code is 7:46PM)

Can you help me to understand what is going on in here.

DOMDocument cannot change parentNode

I cannot change the DOMDocument parentNode from null. I have tried using both appendChild and replaceChild, but haven't had any luck.

Where am I going wrong here?

   error_reporting(E_ALL);

   function xml_encode($mixed, $DOMDocument=null) {
      if (is_null($DOMDocument)) {
          $DOMDocument =new DOMDocument;
          $DOMDocument->formatOutput = true;
          xml_encode($mixed, $DOMDocument);
          echo $DOMDocument->saveXML();
      } else {
          if (is_array($mixed)) {
              $node = $DOMDocument->createElement('urlset', 'hello');
              $DOMDocument->appendChild($node);
          }
      }
  }

  $data = array();

  for ($x = 0; $x <= 10; $x++) {
      $data['urlset'][] = array(
         'loc' => 'http://ift.tt/1FXudUi',
         'lastmod' => 'YYYY-MM-DD',
         'changefreq' => 'monthly',
         'priority' => 0.5
      );
  }

  header('Content-Type: application/xml');
  echo xml_encode($data);

?>

http://ift.tt/1FHzXCe

ZendX_JQuery_Form_Element_DatePicker doesn´t work

My datepicker doesn't work. I don't get any errors and instead of the datepicker appearing, my field looks like a dropdown and shows the formerly used dates.

I added to my bootstrap:

protected function _InitAutoload()
    {
        $view= new Zend_View();
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
        $view->addHelperPath(’ZendX/JQuery/View/Helper/’, ‘ZendX_JQuery_View_Helper’);
        $viewRenderer->setView($view);
        Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
    }

I changed my datefield in my formclass like follows:

$datum= new ZendX_JQuery_Form_Element_DatePicker("datum", '',
                    array('defaultDate' => date('Y/m/d', time()))); 

My formclass extends ZendX_JQuery_Form.

In my layout.phtml I added:

$this->jQuery()->setLocalPath('http://localhost/zend/js/jquery/jquery-1.2.6.js')
 ->addStylesheet('http://localhost/zend/js/jquery/themes/ui.datepicker.css');
echo $this->jQuery();

Where is my error? Is there something missing somewhere?

Running code on every kernel boot

I would like a bundle to run code on every boot of the Symfony kernel. Is there a way to accomplish this? I need to be able to use the bundle configuration, therefore the constructor of the bundle class is not an option. Adding an event listener to kernel.request would be an option but it does not work for console scripts.

Multi mysql query returns Commands out of sync

i've created below function which include several mysql queries, which seem to create an issue. Cause when i run this function it returns following error:

Errormessage: Commands out of sync; you can't run this command now

i've tried to include next_result(), but does not do any difference?

function retrievePlayerTweets(){
    global $con;
    $query = $con->prepare("Select players.fullname, players.twitter_user, team.id as teamId FROM players, team WHERE players.teamId = team.id");
    $query->execute();
    $query->bind_result($fullname, $twitter_user, $teamId);

    while ($query->fetch()) {

        foreach(retrieveUserTweets($twitter_user) as $twitterData) {
            $id = $twitterData['id_str'];
            $text = $twitterData['text'];
            $name = $twitterData['user']['name'];
            $dateString = $twitterData['created_at'];
            $favoriteCount = $twitterData['favorite_count'];
            $date = date('Y-m-d H:i:s', strtotime($dateString));



                if ($insert_tweet = $con->prepare("INSERT IGNORE INTO tweets (`fullname`, `username`, `text`, `created`, `teamId`, `twitterId`, `favoriteCount`) VALUES (?, ?, ?, ?, ?, ?, ?)")) {

                    $insert_tweet->bind_param("ssssisi", $name, $twitter_user, $text, $date, $teamId, $id, $favoriteCount);
                    $insert_tweet->execute();
                    $con->next_result();

                } else {
                    die("Errormessage: ". $con->error);
                }






}

PHP SQL Server ODBC Driver

Trying to connect to a remote SQL Server (2008) on local network through a PHP (5.6.7) script running with MAMP on Mac OS Yosemite. I ran through the tutorial here.

I am was able to install and configure successfully. I can connect to SQL SErver through terminal services and query and pull data through 'isql'.

However, I can't seem to figure out how to enable the driver in php. I don't see the odbc.so extension file in the extensions folder, where I think it should be (then enabled in .ini file). Any ideas?

function broke after updating PHP

I have a little problem with a function which doesn't seem to fully work in new php version and I receive

Notice: String offset cast occurred in D:\xampp\htdocs\decode\bencoded.php on line 266
Notice: String offset cast occurred in D:\xampp\htdocs\decode\bencoded.php on line 270

Here is my function:

function bdecode($s, &$pos=0) {
  if($pos>=strlen($s)) {
    return null;
  }
  switch($s[$pos]){
  case 'd':
    $pos++;
    $retval=array();
    while ($s[$pos]!='e'){
      $key=bdecode($s, $pos);
      $val=bdecode($s, $pos);
      if ($key===null || $val===null)
        break;
      $retval[$key]=$val;
    }
    $retval["isDct"]=true;
    $pos++;
    return $retval;

  case 'l':
    $pos++;
    $retval=array();
    while ($s[$pos]!='e'){
      $val=bdecode($s, $pos);
      if ($val===null)
        break;
      $retval[]=$val;
    }
    $pos++;
    return $retval;

  case 'i':
    $pos++;
    $digits=strpos($s, 'e', $pos)-$pos;
    // Proger_XP: changed (int) -> (float) to avoid trimming of values exceeding
    //            signed int's max value (2147483647).
    $val=(float)substr($s, $pos, $digits);
    $pos+=$digits+1;
    return $val;

//  case "0": case "1": case "2": case "3": case "4":
//  case "5": case "6": case "7": case "8": case "9":
  default:
    $digits=strpos($s, ':', $pos)-$pos;
    if ($digits<0 || $digits >20)
      return null;
    $len=(float)substr($s, $pos, $digits);
    $pos+=$digits+1;
    $str=substr($s, $pos, $len);
    $pos+=$len;
    //echo "pos: $pos str: [$str] len: $len digits: $digits\n";
    return (string)$str;
  }
  return null;
}

i understand that i get a warning in the new php, but i have no idea how to fix it.

line 266 (before case 'd'): switch($s[$pos]){

line 270 (after case '1'): while ($s[$pos]!='e'){

eajaxupload for Yii always "failed"

We are currently trying to use the extension eajaxupload for Yii but it seems to be outputting failed everytime we try to upload a file.

We have tried

a) editing the file / minimum file sizes

b) playing around with the file path (may still be incorrect, if anyone knows what the path for locally using in xampp would be, let us know. Our uploads folder is in the root of the project.)

c) changing the htiaccess php file

d) permissions

we just don't know if the code itself is appearing wrong.

controller

/* UPLOADER */
    public function actionUpload(){
        Yii::import("ext.EAjaxUpload.qqFileUploader");
//        $folder = '/uploads/';
//        $folder=Yii::getPathOfAlias() .'/upload/';
        $folder=Yii::app()->baseUrl . '/uploads/';
        $allowedExtensions = array("jpg","png");//array("jpg","jpeg","gif","exe","mov" and etc...
        $sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder);
//        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
// 
//        $fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
//        $fileName=$result['filename'];//GETTING FILE NAME
// 
//        echo $return;// it's array

        $result = $uploader->handleUpload($folder);

        $fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
        $fileName=$result['filename'];//GETTING FILE NAME
        $result=htmlspecialchars(json_encode($result), ENT_NOQUOTES);

        echo $result;// it's array
    }

View

*$this->widget('ext.EAjaxUpload.EAjaxUpload',
                array(
                    'id'=>'uploadFile',
                    'config'=>array(
                        'action'=>'/upload/',
//                        'action'=>Yii::app()->createUrl('controllers/uploads/'),
                        'allowedExtensions'=>array("jpg","png"),//array("jpg","jpeg","gif","exe","mov" and etc...
                        'sizeLimit'=>10*1024*1024,// maximum file size in bytes
                        //'minSizeLimit'=>10*1024*1024,// minimum file size in bytes
                        'onComplete'=>"js:function(id, fileName, responseJSON){ alert(fileName); }",
                        'messages'=>array(
                            'typeError'=>"{file} has invalid extension. Only {extensions} are allowed.",
                            'sizeError'=>"{file} is too large, maximum file size is {sizeLimit}.",
                            'minSizeError'=>"{file} is too small, minimum file size is {minSizeLimit}.",
                            'emptyError'=>"{file} is empty, please select files again without it.",
                            'onLeave'=>"The files are being uploaded, if you leave now the upload will be cancelled."
                        ),
                        'showMessage'=>"js:function(message){ alert(message); }"

                    )*

Fullcalendar returning epoch time values to the database

I am using fullcalendar jquery plugin for my page.When i'm inserting new events using the fullcalendar plugin.., its returning me epoch time values instead of UTC timedate values.

Below is the code that inserts new data into the database on clicking a date.

    calendar.fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        editable: true,
        droppable: true, // this allows things to be dropped onto the calendar
        drop: function() {
            // is the "remove after drop" checkbox checked?
            if ($('#drop-remove').is(':checked')) {
                // if so, remove the element from the "Draggable Events" list
                $(this).remove();
            }
        },

        eventSources: [

            {

                url: '/v1/calendar/',
                type: 'GET',
                dataType:'json',


            },
           calendar.fullCalendar( 'addEventSource', response )
        ],

        selectable: true,
        selectHelper: true,
        select: function(start, end, allDay) {

            bootbox.prompt("New Event Title:", function(title) {
                var people_id=1;
                //var title=event.title;
                //var start=event.start;
                //var end=event.end;

                if (title !== null) {
                    calendar.fullCalendar('renderEvent',
                            {
                                people_id:people_id,
                                title: title,
                                start: start,
                                end: end,
                                allDay: allDay
                            },

                    true // make the event "stick"


                            );






                            $.ajax({
                                 url: '/v1/calendar',
                                 data: 'people_id='+people_id+'&title='+title+'&start='+start+'&end='+end,

                                 type: 'POST',
                                 dataType: 'json',
                                 success: function(response){
                                     bootbox.alert("Event Created!");

                                   console.log(response);
                                 },
                                 error: function(e){
                                   console.log(e.responseText);
                                 }
                               });  

                }
            });

The event is successfully added into the database...but the time is in epoch format.

the console response I'm getting is given below:

     {people_id: "1", evt_description: "testing", date1: "1431388800000", date2: "1431475200000", event_id: 4}

I'm using laravel framework at the backend I'm attaching my CalendarController below:

    <?php

class CalendarController extends \BaseController {

/**
 * Display a listing of calendar
 *
 * @return Response
 */
public function index()
{
    $event = DB::table('events')

    ->leftJoin('people','people.people_id','=','events.people_id')  
    ->leftJoin('people_roles','people_roles.people_id','=','events.people_id')      
    ->get(array('events.people_id','events.event_id','events.evt_description','events.date1','events.date2','events.time'));    
    //return View::make('people.show', compact('address'));
    //return Response::json($event);
    $id=array();
    $title=array();
    $start=array();
    $end=array();
    $i=0;
    foreach ($event as $events)
        {

            $id[$i]=$events->event_id;
            $title[$i]=$events->evt_description;
            $start[$i]=$events->date1;
            $end[$i]=$events->date2;
            $i++;           
        }
    return Response::json(array('id'=>$id,'title'=>$title,'start'=>$start,'end'=>$end));
}

/**
 * Show the form for creating a new calendar
 *
 * @return Response
 */
public function create()
{
    return View::make('calendar.create');
}

/**
 * Store a newly created calendar in storage.
 *
 * @return Response
 */
public function store()
{
    $events= Input::get('type');
    $events= new Events;
    $events->people_id = Input::get('people_id');
    $events->evt_description =Input::get('title');
    $events->date1 =Input::get('start');
    $events->date2 =Input::get('end');
    //$events->time =Input::get('time');

    $events->save();


    return Response::json($events);
    //return Redirect::route('calendar.index');
}

/**
 * Display the specified calendar.
 *
 * @param  int  $id
 * @return Response
 */
public function show($id)
{
    $calendar = Calendar::findOrFail($id);

    return View::make('calendar.show', compact('calendar'));
}

/**
 * Show the form for editing the specified calendar.
 *
 * @param  int  $id
 * @return Response
 */
public function edit($id)
{
    $calendar = Calendar::find($id);

    return View::make('calendar.edit', compact('calendar'));
}

/**
 * Update the specified calendar in storage.
 *
 * @param  int  $id
 * @return Response
 */
public function update($id)
{
    //$type=Input::get('type');
    $event_id= Input::get('event_id');
    $title= Input::get('title');
    $roles = DB::table('events')
                ->where('event_id','=',$event_id )
                ->update(array('evt_description' => $title));
    return Response::json(array('id'=>$event_id,'title'=>$title));



}

/**
 * Remove the specified calendar from storage.
 *
 * @param  int  $id
 * @return Response
 */
public function destroy()
{
//  Calendar::destroy($id);
$event_id= Input::get('eventid');
DB::table('events')->where('event_id','=',$event_id)->delete();

return Response::json($event_id);

//  return Redirect::route('calendar.index');
}

}

MySQL query runs ok in phpadmin but hangs in php

I have a fairly simple query which runs okay when I test it in phpMyAdmin:

   SELECT   
        c.customers_id,
        c.customers_cid,
        c.customers_gender,
        c.customers_firstname,
        c.customers_lastname,
        c.customers_email_address,
        c.customers_telephone,
        c.customers_date_added,
        ab.entry_company,
        ab.entry_street_address,
        ab.entry_postcode, 
        ab.entry_city,
        COUNT(o.customers_id) AS orders_number,
        SUM(ot.value) AS totalvalue, 
        mb.bonus_points
   FROM     
        orders AS o,
        orders_total AS ot,
        customers AS c, 
        address_book AS ab, 
        module_bonus AS mb
   WHERE 
        c.customers_id = o.customers_id 
        AND c.customers_default_address_id = ab.address_book_id 
        AND c.customers_id = mb.customers_id    
        AND o.orders_id = ot.orders_id 
        AND ot.class = 'ot_subtotal'    
 **  AND c.customers_gender  = 'm' AND c.customers_lastname LIKE 'Famlex'
    GROUP BY o.customers_id

The row marked with ** changes depending on filtering settings of the application making the query.

Now, when I test this in phpMyAdmin, the query takes a couple of seconds to run (which is fine, since there are thousands of entries and, as far as I know, when using COUNTs and SUMs indexes don't help) and the results are perfect, but when I run the exact same query in PHP (echoed before running), the MySQL thread loads a core to 100% and doesn't stop until I kill it.

If I strip the extra stuff to calculate the COUNT and SUM, the query finishes but the results are useless to me.

EXPLAIN:

1   SIMPLE  mb  ALL     NULL                        NULL        NULL        NULL                                48713       Using temporary; Using filesort
1   SIMPLE  ot  ALL     idx_orders_total_orders_id  NULL        NULL        NULL                                811725      Using where
1   SIMPLE  o   eq_ref  PRIMARY                     PRIMARY     4           db.ot.orders_id                     1           Using where
1   SIMPLE  c   eq_ref  PRIMARY                     PRIMARY     4           db.o.customers_id                   1           Using where
1   SIMPLE  ab  eq_ref  PRIMARY                     PRIMARY     4           db.c.customers_default_address_id   1

EXPLAIN after applying indexes and using joins:

1   SIMPLE  c   ref     PRIMARY,search_str_idx              search_str_idx          98      const                                   1       Using where; Using temporary; Using filesort
1   SIMPLE  mb  ALL     NULL                                NULL                    NULL    NULL                                    48713   Using where
1   SIMPLE  ab  eq_ref  PRIMARY                             PRIMARY                 4       db.c.customers_default_address_id       1    
1   SIMPLE  ot  ref     idx_orders_total_orders_id,class    class                   98      const                                   157004  Using where
1   SIMPLE  o   eq_ref  PRIMARY                             PRIMARY                 4       db.ot.orders_id                         1       Using where

Moving code outside the for statement gives me a white page - PHP

So I've written this code which takes names from a text file and puts it in a table, but my problem is after I put something else below $Data the code stops working and all I get is a white page. I've tried to set all of the errors to true so it displays errors, but with no luck and the PHP error log files is also empty.

If I add this piece of code ($nameParsed = rawurlencode($Data[1]);), or any other below $Data, I get a white page, but if I move it below the $Data to after the table it works and it is still within the for statement.

I'm completely baffled, why does this happen? There is nothing wrong with the variable $nameParsed and everything else seems to be correct.

    <?php
    for ($i = 0; $i <= $totalMembers - 1; $i++) {
        $currentLine = $lines[$i];
        $Data = explode("\t", $currentLine)
    ?>
    <tr>
    <td style='text-align: center;'><?php echo $i + 1; ?></td>
    <td class='member' style='padding-left:16px;'><?php echo $Data[1]; ?></td>
    <td style='padding-left:15px;'>117</td>
    <td class='member' style='text-align: center;'>94</td>
    <td class='member' style='text-align: center;'>94</td>
    <td class='member' style='text-align: center;'>94</td>
    <td class='member' style='text-align: center;'>97</td>
    <td class='member' style='text-align: center;'>92</td>
    <td class='member' style='text-align: center;'>70</td>
    <td class='member' style='text-align: center;'>94</td>
    </tr>
    <?php
    $nameParsed = rawurlencode($Data[1]);
    }

Copying files between two Debian Servers using php

My php website is hosted in Debain Machine and I want to move a file from that Machine to another Debain which is connected through VPN.

I tried shell_exec and scp , as mentioned here.

<?php
    $output = shell_exec('scp file1.txt dvader@deathstar.com:somedir');
    echo "<pre>$output</pre>";
?>

I also tried using SFTP

<?php

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
                                "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.http://sftp$sftp$remote_file", 'w');

        if (! $stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }
}

try
{
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
}
catch (Exception $e)
{
    echo $e->getMessage() . "\n";
}

?>

Simply My problem is that I am not able to move a file from one machine, where my php applicaton is working , to another machine which is connected through VPN.