I have this:

$(document).ready(function() {
    $('input[type="button"]').click(function() {
        var sum = 0, count = 0, result;

        $('input[type="text"]').each(function() {
            var val = Number( $(this).val() );
            if (val && val >= 0) {
                sum += Number(val);
                count++;
            }
        });
        the error is that it does not take zero into account,
        for example, 10 and 0 should average out to 5, not 10.
        result = (count > 0) ? sum/count : 'no values found';
        $('#result').html( result );

    });
});

How can I make it account for the number 0 when it figures out averages?

So I have this OpenGL program that displays a cube using

gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

And it allows users to modify/rotate it along the x, y and z axis using input. Right now it looks it works pretty well, however, it terminates once the image is displayed according to the users input (on wether to rotate along the x, y or z axis).

How can I modify this program so you can rotate it without it terminating? As in, displaying only the first rotation during the first input.

Or to put it simply, how can I let the users rotae this cube along the x,y and z axis in real time?

//cube.cpp
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <iostream>
using namespace std;

void init(void) 
{
   glClearColor (0.0, 0.0, 0.0, 0.0);
   glShadeModel (GL_FLAT);
}

void display(void)
{
   glClear (GL_COLOR_BUFFER_BIT);
   glColor3f (1.0, 1.0, 1.0);
   glLoadIdentity ();             /* clear the matrix */
   /* viewing transformation  */
      /* Move about the x, y and z axis*/
   cout << "Type x, y or z to rotatate the cube about that respective axis by 5 degrees." << endl;
   char input;
   cin >> input;
   if (input == 'x')
   {
      gluLookAt (5.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
   }
   else if (input == 'y')
   {
      gluLookAt (0.0, 5.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
   }
   else if (input == 'z')
   {
      gluLookAt (0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
   }
   else
   {
      gluLookAt (0.0, 0.0, 5.0, 0.0, ...
  1. What happens when you add an element to a vector that is already at capacity? Does std::vector have a "capacity"?

  2. In C++ and OOP in general, what do you call a design where a Person class inherits from Head, Arm, Body, Leg classes instead of the other way around? Why would anyone do this?

I think the trouble lies with this section:

$dbid = "";
$binds = array();
$binds[] = array("name" => ":id", "value" => &$dbid, "length" => 128);

I'm not entirely sure how it's setting the id, to be honest.

I tested and successfully used this SQL code below to input data into a database.

    INSERT INTO hraps (id, firstname, lastname, gender, year_of_1st_rappel, count_offset_proficiency, count_offset_operational, spotter) values(111111, 'World', 'Hello', 'Male', '2007', '1', '2', '0')

Now I'm trying to integrate it into PHP like this:

     $query = "INSERT INTO hraps (firstname, lastname, gender, year_of_1st_rappel, count_offset_proficiency, count_offset_operational, spotter) "
    ."values('".$this->firstname."','".$this->lastname."','".$this->gender."','".$this->year_of_1st_rappel."',".$this->count_offset_proficiency.",".$this->count_offset_operational.",".$this->spotter.") returning id into :id";

    $dbid = "";
    $binds = array();
    $binds[] = array("name" => ":id", "value" => &$dbid, "length" => 128);
    //echo $query;              
    $result = mydb::cxn()->query($query, $binds);
    $this->id = $dbid;

But nothing gets inserted and I'm not getting any error. The only difference is that in this one I'm defining id as $dbid, and before I hard-coded it in the "values" section of the query.

Can somebody please point out why this code is not working successfully?
Thank you.

Hello.

I received some code that has a section in which the variable $DB is established.

$DB =& new DB($db_username, $db_password, $db_dsn, false);

It does this by calling a function named DB, which is shown here below.

    /**
    * Constructor
    *
    * will set $DB->error and return false if login fails
    *
    * @param string $user
    * @param string $password
    * @param string $db_name
    * @param bool $persistent Should this be a persistent db connection ?
    * @param integer $int_mode
    * @return bool
    **/
    function DB ( $user, $password, $db_name, $persistent=TRUE, $int_mode=OCI_COMMIT_ON_SUCCESS )
    {
        $this->_valid_connection = false;
        $this->query_count = 0;
        $this->debug = false;
        $this->statement_handle = '';
        $this->int_mode = $int_mode;

        if ( $persistent )
        {
            $this->db_handle = OCIPlogon($user,$password,$db_name, 'AMERICAN_AMERICA.AL32UTF8');
        } else {
            $this->db_handle = OCIlogon($user,$password,$db_name, 'AMERICAN_AMERICA.AL32UTF8');
        }

        if ( !$this->db_handle )
        {
            $this->throwError(OCIerror());
            Message::addAlert('Error: Unable to connect to Database');
            return false;
        }
        return true;
    }

    /**
    * Destructor
    *
    * this will only get called if you call it ( limitation of the current version of PHP )
    * but don't worry... PHP cleans up after us anyway.
    *
    * @return void
    **/
    function _DB ()
    {
        OCILogOff($this->db_handle);
    }

But I'm having trouble understanding exactly what it does and when run all I get is a blank page. Can somebody please explain why the DB function is not working correctly?

Thanks.

Actually, I got this figured out but thanks to both of you guys!

Thanks Stefano Mtangoo,

I don't really have a real "login" method right now, this is mostly experimenting. I'm doing something like this:

<?php
//ini_set('display_errors', 'On');
//error_reporting(E_ALL | E_STRICT);

$userLoggedIn = 0;

if ($userLoggedIn == 1)
{
    include("form.php");
    echo "Logged In == " . $userLoggedIn;
}
else 
{
    include("login.php");
    echo "Logged In == " . $userLoggedIn;
}

?>

Right now, the "login.php" shows up alone and by logging in I can get the "form.php" page to show up by setting $userLoggedIn to 1 in the login function, the only problem is, that even then the "login.php" page shows up at the bottom.

So basically I can see the login page and then when I login I can see the form page...however while the form page is there, I can also see the login section under it.

Any ideas?

Hello, I am just playing around with PHP and I have a silly little little login page, with the username and password hard coded in (not secure, I know).

They are:

username and password, respectively.

Once logged in, there is a message saying I am logged in and a form shows up too.

I'm just curious, how come when I log in, the HTML block that shows the username and password fields does not go away? It stays there even when I'm logged in.

Can somebody please tell me what I'm doing wrong.

<?php
//ini_set('display_errors', 'On');
//error_reporting(E_ALL | E_STRICT);
require_once ("xmlrpc.inc");
require_once ("globals.php");

$logged_in = false;

if ($logged_in == false)
{
  login($_POST['username'], $_POST['passwd']);
  echo "<div class=\"container\">
  <div class=\"hero-unit\"><body><center>
  <body><center><form action=\"" . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] . "\" method=\"post\" style=\"margin:0; padding:0;\">\n"        
  ."  <table style=\"margin:0; padding:0;\">\n"
  ."    <tr><td>Username:</td><td><input name=\"username\" type=\"text\" class=\"loginfield\" value=\"".(isset($_POST['username']) ? $_POST['username'] : "")."\" /></td></tr>\n"
  ."    <tr><td>Password:</td><td><input name=\"passwd\" type=\"password\" class=\"loginfield\" /></td></tr>\n"
  ."    <tr><td>&nbsp;</td><td style=\"text-align:right;\"><input type=\"submit\" value=\"Login\" class=\"form_button\" style=\"margin-right:0;\" /></td></tr>\n"
  ."  </table>\n"
  ."</form></center></body>
  </div>
    <footer>                 
    </footer>
  </div>";
}

function login($user_name = null, $password = null)
{
  if ($user_name == username and $password == password)
  {
    echo 
    "<div class=\"container\">
    <div class=\"hero-unit\"><body><center>\"You ARE logged in!\"
    </div>
    </div>";
    $logged_in = true;
    if ($logged_in == true)
    {
      form();
    }
  }
  else
  {
    echo
    "<div class=\"container\">
    <div class=\"hero-unit\"><body><center>\"You are NOT logged in!\"
    </div>
    </div>";  
  }
}

function form()
{
  ini_set('display_errors', 'On');
  error_reporting(E_ALL | E_STRICT);

  /*
  $conn = oci_connect("user", "password", "//path/to");
  if (!$conn) 
  {
    $m = oci_error();
    echo $m['message'], "\n";
    exit;
  }
  else 
  {
    //print "You ...

Actually I fixed that one, by changing up the insert query a bit, but now I get:

ORA-01031: insufficient privileges

Ideas?

Hey guys, thanks for the help. If anyone's still interested, I got it to produce some errors.

First of all all, it's warning me that there are undefined indexes.

The major error though, is:

Warning: oci_execute(): ORA-00913: too many values in /srv/www/htdocs/vtc/form.php on line 47

Strange. I'll try it both ways. Well, thank you again, diafol.

Weird, I did turn on error reporting and I never got one in the page, the data just never shows up in the database.

Hello everyone, I have a PHP form that connects to an oracle DB and should send data to the database when the form is submitted, but I can't figure out why it's not loading any of the data into the database, everything seems to be correct (though this is my first time attempting something like this, so I am likely wrong).

Is there something wrong with the way in which I've structured this page, or something wrong with the way I'm binding variables? Why isn't this properly working?

Note: I changed the connect string to a fake one for security.

Any tips and helps would be greatly appreciated, thanks!

> <?php
> //ini_set('display_errors', 'On');
> //error_reporting(E_ALL | E_STRICT);
> //include("insert.php");
> 
>   $conn = oci_connect("user", "password", "//path/to");
>   if (!$conn) {
>      $m = oci_error();
>      echo $m['message'], "\n";
>      exit;
>   }
>   else {
>      print "You are connected to the VTC database!<br/>";
>   }
> $issueType = $_POST['issueType'];
> $summary = $_POST['summary'];
> $endPointName = $_POST['endPointName'];
> $contactFirstName = $_POST['contactFirstName'];
> $contactLastName = $_POST['contactLastName'];
> $contactEmail = $_POST['contactEmail'];
> $contactPhone = $_POST['contactPhone'];
> $description = $_POST['description'];
> $solution = $_POST['solution'];
> $ticketNumber = $_POST['ticketNumber'];
> $resolved = $_POST['resolved'];
> $agency = $_POST['agency'];
> 
> $insert = 'INSERT INTO VTC_HELPDESK_ISSUES(ISSUE_TYPE,ISSUE_SHORT,ENDPOINT_NAME,CONTACT_FIRST_NAME,CONTACT_LAST_NAME,CONTACT_EMAIL,CONTACT_PHONE,ISSUE_DESC,SOLUTION,OTHER_COMPANY_TICKET_NUM,RESOLVED,AGENCY  ) '.
>        'VALUES(9, :issueType, :summary, :endPointName, :contactFirstName, :contactLastName, :contactEmail, :contactPhone, :description, :solution, :ticketNumber, :resolved, :agency)';
> 
> $send = oci_parse($conn, $insert);
> 
> //Binding makes it harder to submit anything directly to the Oracle DB
> oci_bind_by_name($send, ...

Diafol, thanks, that helped a lot.

I'm confused though. Does it matter if $item outputs an array? Why use $item['id']?

I'm not trying to step on your shoes, just geniunely curious, since $item seems to work just fine.

Thanks again, friend.

Hello, I am using the tutorial from Oracle's site on how to connect to a database in PHP using code similar to the one shown below.

<?php

// Create connection to Oracle
$conn = oci_connect("phphol", "welcome", "//localhost/orcl");

$query = 'select * from departments';
$stid = oci_parse($conn, $query);
$r = oci_execute($stid);

// Fetch each row in an associative array
print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC)) {
   print '<tr>';
   foreach ($row as $item) {
       print '<td>'.($item !== null ? htmlentities($item, ENT_QUOTES) : '&nbsp').'</td>';
   }
   print '</tr>';
}
print '</table>';

?>

Lets say for example, once I have queried the data I need from the Oracle Database, how can I make it show up in an HTML option list similar to the one shown below?

  <label for="testOption"><b>Test Option</b><br/></label>
  <select name="testOption" id = "testOption">
    <option>Test Option</option>
  </select> 

Thank you in advance for your help.

Weird, I can get this working on a blank page and I see it working on Jfiddle, but I can't get it to work in my established page...

Would you mind showing me an example?

The code below seems to work great in Google Chrome, it hides a question in a div unless the question before it is answered.

However, it doesn't seem to work at all in I.E 8.

Can someone give me a solution on how to make it work in both browswers please?

Thank you in advance

<label for="cell">3. Do you currently have a cell phone? (Y/N)</label>
<input type="checkbox" name="cell" id="cell" data-on="Yes" data-off="No" />

<div class="hide_if_no">
<label for="blackBerry">4. If YES, is the cell phone a BlackBerry? (Y/N)</label>
<input type="checkbox" name="blackBerry" id="blackBerry" data-on="Yes" data-off="No" />
</div>

<style>
input[type=checkbox] ~ div.hide_if_no {display:none}
input[type=checkbox]:checked ~ div.hide_if_no {display:block}
</style>

Nope, didn't work. But don't worry about it, I have no idea why it's not working either, it's logically sound.

Yes, I mean this:

if($row['email'] != $user_name){
   echo '<p style="color: red;">There was an error logging in</p>';
 }else if{
   echo 'login stuff...';
 }

Specifically this part:

    if($row['email'] != $user_name){

This goes right above the if ($v) segment. Sorry I was trying to focus on the part where it fails.

    $c = new xmlrpc_client(XMLRPC_CLIENT_PATH, XMLRPC_CLIENT_SERVER, XMLRPC_CLIENT_PORT);

    $c->return_type = 'phpvals';

    $r = $c->send($m);
    if ( !$r->faultCode() )
    {
        $v = $r->value();

And it does enter the if ($v) segment, and does the login correctly, the section that fails is the the second if statement, where it should print out that the username and password are incorrect.

Here is some code (snippet) from a function I have that takes a users "user_name" and "password" as parameters.

There is an if else statement that triggers along the way, basically, if there is a value $v, then it look ups the users user_name and password in a table and appends the @gmail part to it (so that the input username matches the email in the database) and if they are equal, it will log them in, otherwise it will display a message stating that there was an error while logging in.

The trouble is, I can't get the error message (the second if) to occur, even though the login sections are working fine.

Can anyone spot something obvious in the statment that would cause the error to never show up when a wrong username and password is input?

Thanks in advance.

stuff comes before this...

        if ( $v )
        {
            $email = $user_name . "@gmail.com";
            $query = "SELECT id, email FROM auth WHERE email = '".$email."'";

            $result = mydb::cxn()->query($query);
            $row = $result->fetch_assoc();
            $user_name = $user_name . "@gmail.com";
            if($row['email'] != $user_name)
            {
                echo '<p style="color: red;">There was an error logging in</p>';
            }   

            else {
                login stuff...
            }

No errors at all in Eclipse.

It should take the user's input and check their username and password on the lrpc server, then add "@gmail.com" to it and check if the user exists in the auth table. So it should use the lrpc server to log you in and then the generated username + email to assign you a user role (like admin, member, etc.) based on the one set for you in the database.

So basically if your username is Squidge and your password is XXX then that should log you in, then come back and make you Squidge@gmail.com, look for your email in the auth table and see that you're an admin, then the content available to you on the site is that of an admin.

Definitely not the best way to do it, but it's the way it's got to be. Has to be some logical error...

Not a tutorial, justa personal thing. It's supposed to grab a username, then append "@gmail.com" to the username to compare it to a database table of e-mails and passwords.

I can't see any super obvious errors though.

function put ( $data_name, $data )
{
    $return_result = true;
    if ( isset($data_name) && isset($data) )
    {
        $_SESSION[$data_name] = $data;
    } else {
        $return_result = false;
    }
    return $return_result;
}           

function login( $user_name, $password )
{
    //Take username and password
    //Append @gmail to username to make username value = to an email
    $user_name = $user_name .= "@gmail.com";

    $user_name = strtolower($user_name); //Make username case INSENSITIVE (password is still case sensitive)

    $return_result = false;

    $m = new xmlrpcmsg(
            'ldapxml.authorize'
            , array(
                    new xmlrpcval($user_name, "string")
                    , new xmlrpcval($password, "string")
            )
    );

    //temp server
    $c = new xmlrpc_client(XMLRPC_CLIENT_PATH, XMLRPC_CLIENT_SERVER, XMLRPC_CLIENT_PORT);

    $c->return_type = 'phpvals';

    $r = $c->send($m);
    if ( !$r->faultCode() )
    {
        $v = $r->value();

        if ( $v )
        {
            $query = "SELECT email FROM auth WHERE email = '".$email."'";
            $result = mydb::cxn()->query($query);

            if ($result != $user_name)
            {
                echo '<p style="color: red;">There was an error logging in</p>';
            }

            else {

            $return_result = true;              

            $this->put('username', $user_name);
            $this->put('IP', $_SERVER['REMOTE_ADDR']);
            $this->put($this->_valid_session_flag, 1);

            // grab the users info
            $m = new xmlrpcmsg(
                    'ldapxml.getAttibutes'
                    , array(
                            new xmlrpcval($user_name, "string")
                            , new xmlrpcval($password, "string")
                    )
            );

            $c = new xmlrpc_client(XMLRPC_CLIENT_PATH, XMLRPC_CLIENT_SERVER, XMLRPC_CLIENT_PORT);

            $c->return_type = 'phpvals';

            $r = $c->send($m);
            if ( !$r->faultCode() )
            {
                $v = $r->value();

                if ( $v )
                {
                    $this->put('title', $v['title']);
                    $this->put('email', $v['mail']);
                }
            }
        }
        }
    }

    return $return_result;  
}

Sorry for the silly question but you mean the "put" part of it right?

    function put ( $data_name, $data )
    {
        $return_result = true;
        if ( isset($data_name) && isset($data) )
        {
            $_SESSION[$data_name] = $data;
        } else {
            $return_result = false;
        }
        return $return_result;
    }

Why do you say it's a fragment?

I'm new to PHP and was given a code snippet that looks like this:

{
    $DB = new DB('xxxxxx','oooooo','gggggg');
    $return_result = false;

    $this->clear_data();

    $m = new xmlrpcmsg(
            'ldapxml.authorize'
            , array(
                    new xmlrpcval($user_name, "string")
                    , new xmlrpcval($password, "string")
            )
    );

    // this is just a temp server for now
    $c = new xmlrpc_client(XMLRPC_CLIENT_PATH, XMLRPC_CLIENT_SERVER, XMLRPC_CLIENT_PORT);

    $c->return_type = 'phpvals';

    $r = $c->send($m);
    if ( !$r->faultCode() )
    {
        $v = $r->value();

        if ( $v )
        {

            $return_result = true;              

            $this->put('username', $user_name);
            $this->put('IP', $_SERVER['REMOTE_ADDR']);
            $this->put($this->_valid_session_flag, 1);

            // grab the users info

            $m = new xmlrpcmsg(
                    'ldapxml.getAttibutes'
                    , array(
                            new xmlrpcval($user_name, "string")
                            , new xmlrpcval($password, "string")
                    )
            );

            $query = "SELECT email FROM auth WHERE email = '".$email."'";
            $result = mydb::cxn()->query($query);
            if ($result != $user_name)
            {
                echo '<p style="color: red;">There was an error logging in...</p>';
            }

            $c = new xmlrpc_client(XMLRPC_CLIENT_PATH, XMLRPC_CLIENT_SERVER, XMLRPC_CLIENT_PORT);

            $c->return_type = 'phpvals';

            $r = $c->send($m);
            if ( !$r->faultCode() )
            {
                $v = $r->value();

                if ( $v )
                {
                    $this->put('title', $v['title']);
                    $this->put('email', $v['mail']);
                }
            }
            //}
        }
        else {
            echo '<p style="color: red;">There was an error logging in...</p>';

        }
    }

    return $return_result

What does this code do? Can someone break it down for me, line by line and helpt me wrap my head around it? Will it work?

My code(below) displays only one "message" at a time and then prompts the user to delete the message in order to create a new one.

How can I make it so that the user can constantly add new messages without having to delete the previous message?

[CODE]import java.security.SecureRandom;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.datastore.Text;

// The application design is that authenticated users have zero or one messages.
//
// This class is not thread safe because it is possible to create 2 messages for
// a single user under the right conditions. Also, the static initialization
// code is not thread safe either. These problems can be solved using transactions.
//
// All application messages are placed under a single parent entity.
public class Message {

private static final String parentKind = "messageParent";

private static final String entityKind = "message";
private static final String userIdPropertyName = "userId";
private static final String nicknamePropertyName = "nickname";
private static final String textPropertyName = "text";

private static final String csrfTokenPropertyName = "csrfToken";

private static Key parentKey = null;

private static SecureRandom secureRandom = new SecureRandom();

// Check if message parent exists; if not, then create it.
static {
    Query query = new Query(parentKind);
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity parent = datastore.prepare(query).asSingleEntity();
    if (parent == null) {
        parent = new Entity(parentKind);
        datastore.put(parent);
    }
    parentKey = parent.getKey();
}

private Entity entity = null;

private Message(Entity entity) {
    this.entity = entity; ...

Hi there.

I have a few hundred/thousand macro enabled spreadsheets that need to be uploaded to a database. The spreadsheets have a button that copies the data over to the database and it prompts the user for a username and password in order to do so (same for all files). I am attempting to find a way to write a program that would allow me to access each of the spreadsheets automatically and upload them to the database but I'm not sure how to start and I haven't found a lot of documentation on doing somethings similar.

Can someone get me started, give some idea of how to do this, or point me to some code that does the same thing? Any ideas?

Nevermind, all you have to is replace %d with %lf.