The new forums will be named Coin Return (based on the most recent vote)! You can check on the status and timeline of the transition to the new forums here.
The Guiding Principles and New Rules document is now in effect.

Giant Programming Clusterfuck++

1246763

Posts

  • stigweardstigweard Registered User regular
    edited January 2009
    So tell me about web frameworks / porgramming. I need to design a pretty simple dynamic site. Basically there's one main script for most of it that will simply grab the required content from a database based on a URL parameter.

    However, a couple pages have very different construction requirements. They will need to display loads of tabular data from certain other database tables, and I will also need special alorithms to display the "in-depth" information on each one of these entries.

    At present I am just writing separate PHP pages to handle all these tasks, but I don't like the lack of unity and code duplication (nav bar, header tags are the same across all pages) at all. Is there any better way of approaching this?

    You could start by breaking it up and using includes. All of your static presentation material can be broken down, top to bottom, and then put into header / nav / footer pages and then linked in. If you want to go further, you could look into mvc, but it is hardly worth the bother on a one use site.

    stigweard on
  • ASimPersonASimPerson Cold... ... and hard.Registered User regular
    edited January 2009
    According to the documentation, as of libcurl 7.17 the strings are copied by curl, thus avoiding the memory leak issue: http://curl.haxx.se/libcurl/c/curl_easy_setopt.html

    ASimPerson on
  • LoneIgadzraLoneIgadzra Registered User regular
    edited January 2009
    stigweard wrote: »
    So tell me about web frameworks / porgramming. I need to design a pretty simple dynamic site. Basically there's one main script for most of it that will simply grab the required content from a database based on a URL parameter.

    However, a couple pages have very different construction requirements. They will need to display loads of tabular data from certain other database tables, and I will also need special alorithms to display the "in-depth" information on each one of these entries.

    At present I am just writing separate PHP pages to handle all these tasks, but I don't like the lack of unity and code duplication (nav bar, header tags are the same across all pages) at all. Is there any better way of approaching this?

    You could start by breaking it up and using includes. All of your static presentation material can be broken down, top to bottom, and then put into header / nav / footer pages and then linked in. If you want to go further, you could look into mvc, but it is hardly worth the bother on a one use site.

    Yeah I don't know why I didn't make it clearer in my post, but I've already done that stuff. Even though all my pages are using common functions, I just can't shake the feeling that the calls of those functions shouldn't have to be duplicated. Also, if my structure is basically
    <body>
        <div id="container">
            <div id="nav">links here</div>
            <div id="content">
                content from database here
            </div>
            <div id="foot"></div>
        </div>
    </body>
    

    There is no nice way to divide that into functions without making the structure of the page incredibly confusing, e.g. this coding of the above is awkward as hell because what if the structure changes (and the structure of this site is a good bit more complicated):
    <html>
        <?php print_head( $_GET['page'] );?>
    <body>
        <div id="container">
            <?php
                 print_nav();
                 echo retrieve_content( $_GET['page'] );
                 print_foot(); 
            ?>
        </div>
    </body>
    </html>
    

    Basically if I roll the whole thing into functions, with calls nested based on the HTML tag nesting (which seems the most logical way to do it) then the structure of the page becomes dependent on really hard-to-follow relationships in my PHP code rather than a clear HTML presentation. But if I write more of the structure in HTML, then it becomes harder to maintain multiple pages in parallel. Gah, I will probably just find some balance like the above and substitute other functions for "retrieve_content" for different scripts that require it.

    LoneIgadzra on
  • zeenyzeeny Registered User regular
    edited January 2009
    ASimPerson wrote: »
    According to the documentation, as of libcurl 7.17 the strings are copied by curl, thus avoiding the memory leak issue: http://curl.haxx.se/libcurl/c/curl_easy_setopt.html

    He has a prior version. The only way he had the bug he described is if the options were not being copied.
    Uuuuuuuuuuuuuupdaaaaaaaaaaaaaaaaate!

    zeeny on
  • NightslyrNightslyr Registered User regular
    edited January 2009
    So tell me about web frameworks / porgramming. I need to design a pretty simple dynamic site. Basically there's one main script for most of it that will simply grab the required content from a database based on a URL parameter.

    However, a couple pages have very different construction requirements. They will need to display loads of tabular data from certain other database tables, and I will also need special alorithms to display the "in-depth" information on each one of these entries.

    At present I am just writing separate PHP pages to handle all these tasks, but I don't like the lack of unity and code duplication (nav bar, header tags are the same across all pages) at all. Is there any better way of approaching this?

    oh and before anyone starts on it YES I KNOW ABOUT SQL INJECTION AND PREPARED STATEMENTS AND INPUT VALIDATION AND ALL THOSE THINGS.

    You need some form of a Front Controller to do what you want. Basically, the values in your query string are commands that you want the script to execute. The content you want is based on those commands. Since most of your pages are the same, you can have one template page for those pages that displays different data based on the value of the query string command. You can see a simple/sloppy version of one with my code below:

    controllertest.php (this is the code that actually uses the Front Controller):
    <?php
       require_once("data/config.php5");
    
       error_reporting(E_ALL);
       ob_start();
    
       MP_controller_Controller::run();
    ?>
    
    <html>
    <head>
       <title>Front Controller and AJAX test</title>
       <script type="text/javascript" src="js/jquery-1.2.6.min.js"></script>
       <script type="text/javascript">
          $(document).ready(function()
          {
             $("#login1").click(function()
             {
                $.post("<?php echo $_SERVER['PHP_SELF']; ?>", {action: "login", user: "Kevin", pass: "1234"}, function(data)
                {
                   $("#results").html(data);
                });
    
                return false;
             });
          });
       </script>
       <style type="text/css">
          #results
          {
             border: 1px solid black;
          }
       </style>
    </head>
    
    <body>
    <div id="results">
    </div>
    
    <a href="controllertest.php5?action=test&name=Kevin&email=blank">TestCommand test</a><br /><br />
    
    <a id="login1" href="controllertest.php5?action=login&user=Kevin&pass=1234">Login/session test</a><br /><br />
    
    <a href="controllertest.php5?action=login&user=Bubba&pass=5678">Login/session test 2</a>
    
    </body></html>
    
    <?php
       ob_end_flush();
    ?>
    

    controller.php (the actual Front Controller object):
    <?php
       class MP_controller_Controller{
          private function __construct(){}
    
          static function run(){
             $instance = new MP_controller_Controller();
             $instance->init();
             $instance->handleRequest();
             $instance->display();
          }
    
          private function init(){}
    
          private function handleRequest(){
             $request = new MP_controller_Request();
             $commandFactory = new MP_command_CommandFactory();
             $command = $commandFactory->getCommand($request);
             $command->execute($request);
          }
    
          private function display(){
             $sessReg = MP_base_SessionRegistry::getInstance();
    
             if(!$sessReg->isEmpty()){
                $user = $sessReg->getUser();
    
                if($user){
                   echo "Welcome back, {$user->getName()}<br /><br />\n\n";
                }
             }
          }
       }
    ?>
    

    request.php (helper object that gives us cleaner access to the $_REQUEST array):
    <?php
       class MP_controller_Request{
          private $properties;
    
          function __construct(){
             $this->init();
             MP_base_RequestRegistry::getInstance();
             MP_base_RequestRegistry::setRequest($this);
          }
    
          function init(){
             if($_SERVER['REQUEST_METHOD']){
                $this->properties = $_REQUEST;
                return;
             }
    
             foreach($_SERVER['argv'] as $arg){
                if(strpos($arg, '=')){
                   list($key, $value) = explode('=', $arg);
                   $this->setProperty($key, $value);
                }
             }
          }
    
          function getProperty($key){
             if(is_array($this->properties) && isset($this->properties[$key])){
                return $this->properties[$key];
             }
          }
    
          function setProperty($key, $value){
             $this->properties[$key] = $value;
          }
       }
    ?>
    

    commandfactory.php (an object that creates a command object based on the query string value):
    <?php
       class MP_command_CommandFactory{
          private static $baseCommand;
          private static $defaultCommand;
    
          function __construct(){
             if(!self::$baseCommand){
                self::$baseCommand = new ReflectionClass("MP_command_Command");
                self::$defaultCommand = new MP_command_DefaultCommand();
             }
          }
    
          function getCommand(MP_controller_Request $request){
             $command = $request->getProperty('action');
    
             if(!$command){
                return self::$defaultCommand;
             }
    
             $command = ucfirst(strtolower(str_replace(array('.', '/'), '', $command))) . "Command";
             $path = "MP/command/$command.php5";
             $className = "MP_command_$command";
    
             if(file_exists($path) && class_exists($className)){
                $commandClass = new ReflectionClass($className);
    
                if($commandClass->isSubClassOf(self::$baseCommand)){
                   return $commandClass->newInstance();
                } else{
                   throw new MP_exception_CommandNotFoundException();
                }
             }
    
             return clone self::$defaultCommand;
          }
       }
    ?>
    

    Abstract base command class - command.php:
    <?php
       abstract class MP_command_Command{
          final function __construct(){}
    
          function execute(MP_controller_Request $request){
             $this->doExecute($request);
          }
    
          abstract function doExecute(MP_controller_Request $request);
       }
    ?>
    

    And an example login command - logincommand.php:
    <?php
       class MP_command_LoginCommand extends MP_command_Command{
          public function doExecute(MP_controller_Request $request){
             $loginRec = MP_base_ReceiverFactory::getLoginReceiver();
             $loginRec->login($request);
          }
       }
    ?>
    

    As you can see, this makes use of another object, the Receiver Factory. A receiver is that part of the system that should execute that command. In my example above, it's hard-coded to the command itself, which is probably not the best idea.

    Admittedly, this code isn't great, but it should illustrate what I was talking about. The controller sits at the top of your application and filters the query string. It passes that result to the command factory, which retrieves the proper command (if it exists...if not a default/generic command is retrieved instead). The command itself is then executed. This execution method is where the 'magic' happens. In my example, I retrieved an object representing the login mechanism for an example site, then logged the user into the system. It shouldn't be a problem for you to run specific database queries for a specific page's content, then load a generic template page that can display those results.

    The biggest hurdle are the pages that vary, but the biggest problem there is figuring out their display templates. The actual data processing will be placed within each command object. And, if most of those queries are the same, you can group them into functions, reducing code duplication even further.

    I hope this made some kind of sense.

    Note: the code above will only work with PHP 5+. Avoid PHP 4 like the plague.

    Nightslyr on
  • GnomeTankGnomeTank What the what? Portland, OregonRegistered User regular
    edited January 2009
    On the libcurl thing:

    My question would be: You are obviously using a C++ compiler, because you are using nested scope. In that case, why are you using character pointers at all? Step up to the plate and learn how to use std::string and save yourself the headache of worrying about this crap again. You'll have to store the std::string references you return the c_str() pointer from, but that's much easier than the headache of C string manipulation, which is antiquated and mostly worthless if you are working in an environment that has the C++ standard library.

    GnomeTank on
    Sagroth wrote: »
    Oh c'mon FyreWulff, no one's gonna pay to visit Uranus.
    Steam: Brainling, XBL / PSN: GnomeTank, NintendoID: Brainling, FF14: Zillius Rosh SFV: Brainling
  • Randall_FlaggRandall_Flagg Registered User regular
    edited January 2009
    question: is there a standard definition for the "width" of a binary tree

    Randall_Flagg on
  • stigweardstigweard Registered User regular
    edited January 2009
    question: is there a standard definition for the "width" of a binary tree

    IIRC, it is the number of nodes in the longest path. (leaf to leaf)

    stigweard on
  • jackaljackal Fuck Yes. That is an orderly anal warehouse. Registered User regular
    edited January 2009
    I'm not sure if there is a standard definnition. I would think the width of a binary tree would either be:
    The maximum of the number of nodes for each level
    or
    2^(n-1) where n is the number of levels.

    So this would be three or eight.
       0
       / \
       0  0
     / \   \
     0  0  0
           / \
           0  
    

    jackal on
  • InfidelInfidel Heretic Registered User regular
    edited January 2009
    The only real use for finding the width of a binary tree is for rendering a printable version. Do it recursively.

    The width of a leaf node is 1. The width of a parent node is leftChildWidth + 1 + rightChildWidth. Do this recursively and the width of the root node will be how wide your tree is.

    Infidel on
    OrokosPA.png
  • jackaljackal Fuck Yes. That is an orderly anal warehouse. Registered User regular
    edited January 2009
    Wouldn't that just be the number of nodes in the tree? (unless that is what width means in the context of binary trees)

    jackal on
  • InfidelInfidel Heretic Registered User regular
    edited January 2009
    Yes, the global width of the tree is the number of nodes in the tree, the local width is also important though (and of course is the number of nodes in the subtree, etc.)

    Like I said it's only use in calling it the width is in rendering the tree. If you know the width of children you can figure out where to lay out the nodes. If the root node width is 10, you need 10 columns, where do the left child and right child belong and where does the root node start?

    Fear my quick mspaint skills!

    treewidth.gif

    The leaf nodes are obviously width 1, the non-leaf nodes have their width marked. Using those numbers you can determine where you would put each node when trying to render the tree top down without any collisions and no wasted space.

    Infidel on
    OrokosPA.png
  • Randall_FlaggRandall_Flagg Registered User regular
    edited January 2009
    that helps, I think

    thanks

    Randall_Flagg on
  • EvigilantEvigilant VARegistered User regular
    edited January 2009
    Nevermind, I figured it out and I realized I was thinking of it incorrectly.

    Evigilant on
    XBL\PSN\Steam\Origin: Evigilant
  • LoneIgadzraLoneIgadzra Registered User regular
    edited January 2009
    Does anyone here know much about Windows Forms programming with a database? My situation is a little tricky because I'm using MySQL (so the data is more compatible with web servers) and reliant on the MySQL.NET connector which really only has reference documentation rather than anything explaining how to use it well.

    Since I couldn't quite figure out what Visual Studio data sources were about or how to customize them at all (and I think I couldn't get updating to work), I ended up programmatically populating my DataGridView with the relevant data using classes provided by the MySQL connector, such as MySqlDataAdapter and MySqlCommandBuilder. Then, to make searches work, I wrote algorithms to build SQL queries based on the GUI state. When a new query is built, I manually do a bunch of stuff to re-populate the DataSet using the MySql connector classes and the results of running the query.

    This is ridiculously cumbersome of course (though on the plus side I will be able to make the database connection, schema, and expected table names / setups not hard-coded if I ever get around to it), so I've been working on a "DataGridViewManager" class to encapsulate all these issues with programmatically populating a DataGridView from MySQL. (Since I have multiple forms using the old methodology, rolling all the code up into one class will be a godsend.) Trouble is, I can't think of a good way to provide some kind of generic search interface.

    What I want to know is, from anyone who has done this kind of programming before, are there facilities in .NET to automate data synchronization (between a DataGridView and a database) and query building that I'm not aware of? .NET is a monster and I don't own any good books on it, and Microsoft's examples are pretty basic sometimes (or over-numerous and hard to navigate to the most-relevant one).

    LoneIgadzra on
  • InfidelInfidel Heretic Registered User regular
    edited January 2009
    You're using direct MySQL interfaces and that's causing you some trouble? What about using some implementation-neutral interface (ODBC etc.) for the connectors if that's the case. I haven't done any .NET database work so I'm not too sure where to point you on the rest. :)

    Infidel on
    OrokosPA.png
  • LoneIgadzraLoneIgadzra Registered User regular
    edited January 2009
    Infidel wrote: »
    You're using direct MySQL interfaces and that's causing you some trouble? What about using some implementation-neutral interface (ODBC etc.) for the connectors if that's the case. I haven't done any .NET database work so I'm not too sure where to point you on the rest. :)

    I'll look into that (not that the wikipedia explanation of ODBC made any sense to my beer-addled mind the last time I tried to read it). I chose MySQL initially because web-server compatibility was important. (The data needs to be able to be easily mirrored on a web server that is.) But I think MySQL also has an ODBC connector, so if I can work with something Visual Studio can automate a little better it will be wonderful.

    Edit: ODBC is a no-go. The connector seems hopelessly buggy, at least in Visual Studio. The IDE constantly crashes and doesn't show any tables. Oh well, the programmatic MySQL query thing has some advantages, especially now that I've finally got a lot of the bullshit encapsulated. I am still curious about ease of moving between Microsoft SQL server (lite or express or whatever) and MySQL though.

    LoneIgadzra on
  • PantsBPantsB Fake Thomas Jefferson Registered User regular
    edited January 2009
    question: is there a standard definition for the "width" of a binary tree

    Another big concern is whether we're talking a balanced binary tree or not (assuming we're talking about printing, it is either way though). If you're printing a balanced binary tree, you can stick the head node in the middle, and then recursively print without worry with each child dedicated to 0-N/2-1 and N/2 - N-1.

    If its an unbalanced binary tree
       A
     /   \
    B     C
          /  \ 
        D     G
      /   \       \ 
    E     F        J
         /   \        \
       H      I        K
                 
    
    (etc) is more complicated. It can be done obviously but its more annoying (as I found when doing a personal project trying to create an ancestry chart, which can't be balanced without losing its meaning). If sufficiently large and unbalanced, you'll eventually either run out of space faster than the total amount of data would suggest or have to violate rules so a child leaf/node with stray to the wrong "side" of a grandparent node. The problem is that while balanced trees are intended to minimize the height of a tree, for printing each level of height in a tree implies greater width as well.

    PantsB on
    11793-1.png
    day9gosu.png
    QEDMF xbl: PantsB G+
  • FagadabaFagadaba Registered User regular
    edited January 2009
    Sup guys, I'm trying to get a little C thing running which asks for a number and gives you back the square root of it.
    
    #include <stdio.h>  /** for printf and scanf **/
    #include <conio.h>  /** for getch **/
    
    void main(void)  /** first thing run **/
    {  /** begin **/
    	int numberOne;  /** declare variable numberOne **/
    	printf("Saisissez un nombre: ")  /** Enter a number **/
    	scanf("&#37;d", numberOne);  /** input numberOne, real **/
    	printf("%d", sqrt (&numberOne));  /** give back square root there **/
    	getch();  /**wait for enter to be pressed **/
    }  /** end **/
    
    

    It's giving me an error:
    "Failed to load and parse the manifest. The system cannot find the file specified."

    I have no idea what step I skipped or what I typoed.
    Help please!

    Fagadaba on
  • Mr.FragBaitMr.FragBait Registered User regular
    edited January 2009
    Fagadaba wrote: »
    Sup guys, I'm trying to get a little C thing running which asks for a number and gives you back the square root of it.
    #include <stdio.h>  /** for printf and scanf **/
    #include <conio.h>  /** for getch **/
    //did not include math.h for sqrt
    
    void main(void)  /** first thing run **/ //while void is sometimes accepted, int return type is the platform independent way
    {  /** begin **/
    	int numberOne;  /** declare variable numberOne **/
    	printf("Saisissez un nombre: ")  /** Enter a number **/ //missing ;
    	scanf("&#37;d", numberOne);  /** input numberOne, real **/ //needs to give address of numberOne variable with &
    	printf("%d", sqrt (&numberOne));  /** give back square root there **/ 
            //sqrt takes a value, not a address. No & needed. But sqrt returns a double, so %f is needed.
    	getch();  /**wait for enter to be pressed **/
            //return 0 to show successful run if this is in a int main(void)  
    }  /** end **/
    
    

    It's giving me an error:
    "Failed to load and parse the manifest. The system cannot find the file specified."

    I have no idea what step I skipped or what I typoed.
    Help please!

    The problem is not the code (though there are several syntax errors), the problem is how you are running it. What IDE are you using and how are you attempting to run it?

    Mr.FragBait on
  • ecco the dolphinecco the dolphin Registered User regular
    edited January 2009
    Fagadaba wrote: »
    Sup guys, I'm trying to get a little C thing running which asks for a number and gives you back the square root of it.
    
    #include <stdio.h>  /** for printf and scanf **/
    #include <conio.h>  /** for getch **/
    
    void main(void)  /** first thing run **/
    {  /** begin **/
    	int numberOne;  /** declare variable numberOne **/
    	printf("Saisissez un nombre: ")  /** Enter a number **/
    	scanf("%d", numberOne);  /** input numberOne, real **/
    	printf("%d", sqrt (&numberOne));  /** give back square root there **/
    	getch();  /**wait for enter to be pressed **/
    }  /** end **/
    
    

    It's giving me an error:
    "Failed to load and parse the manifest. The system cannot find the file specified."

    I have no idea what step I skipped or what I typoed.
    Help please!

    Sounds like you're using Visual Studio 2005 or later. It's not a typo in your code, but something going slightly wrong with your build settings.

    If you go into your project properties (Alt+F7), then Configuration Properties -> Linker -> Manifest File, do you have:

    Generate Manifest: Yes
    Manifest File: $(IntDir)\$(TargetFileName).intermediate.manifest
    Additional Manifest Dependencies:

    ?

    ecco the dolphin on
    Penny Arcade Developers at PADev.net.
  • FagadabaFagadaba Registered User regular
    edited January 2009
    Fagadaba wrote: »
    Sup guys, I'm trying to get a little C thing running which asks for a number and gives you back the square root of it.
    
    #include <cstdlib>  /** do I need this? **/
    #include <iostream>  /** and this? **/
    #include <stdio.h>  /** for printf and scanf **/
    #include <conio.h>  /** for getch **/
    #include <math.h> /** for sqrt **/
    
    int main(void)  /** first thing run **/
    {  /** begin **/
    	int numberOne;  /** declare variable numberOne **/
    	printf("Saisissez un nombre: ");  /** Enter a number **/
    	scanf("&#37;d", &numberOne);  /** input numberOne, real **/
    	printf("%d", sqrt (numberOne));  /** give back square root there **/ 
    	getch();  /**wait for enter to be pressed **/
                return 0;
    }  /** end **/
    
    

    It's giving me an error:
    "Failed to load and parse the manifest. The system cannot find the file specified."

    I have no idea what step I skipped or what I typoed.
    Help please!

    The problem is not the code (though there are several syntax errors), the problem is how you are running it. What IDE are you using and how are you attempting to run it?

    Sounds like you're using Visual Studio 2005 or later. It's not a typo in your code, but something going slightly wrong with your build settings.

    If you go into your project properties (Alt+F7), then Configuration Properties -> Linker -> Manifest File, do you have:

    Generate Manifest: Yes
    Manifest File: $(IntDir)\$(TargetFileName).intermediate.manifest
    Additional Manifest Dependencies:

    ?

    I'm using Dev C++. I get the same thing in Visual C++ or Delphi 2007.

    [EDIT] Ok! Now I get a console thing asking to enter a number(Saisissez un nombre) but whatever number I give it, I get 0 in return.

    Oh ho! So I'm on Visual Studio 2008, and I went there(alt+F7) and I seem to have this:

    Manifest File

    Here's my code as of now:
    
    #include <cstdlib>  /** do I need this? **/
    #include <iostream>  /** and this? **/
    #include <stdio.h>  /** for printf and scanf **/
    #include <conio.h>  /** for getch **/
    #include <math.h> /** for sqrt **/
    
    int main(void)  /** first thing run **/
    {  /** begin **/
    	int numberOne;  /** declare variable numberOne **/
    	printf("Saisissez un nombre: ");  /** Enter a number **/
    	scanf("%d", &numberOne);  /** input numberOne, real **/
    	printf("La racine carr&#233;e de %d est: %d",numberOne, numberOne*numberOne);  /** give back square root there **/ 
    	getch();  /**wait for enter to be pressed **/
        return 0;
    }  /** end **/
    
    

    I get a window(console?) that asks to enter a number(Saisissez un nombre) and gives back that number to itself(numberOne*numberOne). I need the exact opposite. For it to ask a number then give me back the square root(racine carrée). Also, does anyone know how to get weird characters(lol french) to show in the console? I get zeros where "é" should be.

    Fagadaba on
  • EvigilantEvigilant VARegistered User regular
    edited January 2009
    I can't figure out why my array in the neighbor() method keeps giving me an ArrayIndexOutOfBoundsException: -1 error.

    I can get it to run if I have it start at the end and work backwards, but it screws up my results or my logic/method to get my results is flawed. I can't figure it out.
    import java.io.*;
    import java.util.*;
    
    public class Proj180224 
    {
    	public static int[][] coord;
    	public static BufferedReader br;
    	public static Scanner scanUser, scan;
    	public static int count;
    	public static void main(String[] args)throws Exception
    	{
    		if(args.length ==1) //test to see if filename is on command line
    		{
    			try
    			{
    				br = new BufferedReader(new FileReader(args[0]));
    				scan = new Scanner(br);
    				scanUser = new Scanner(System.in);
    				runProj();
    
    			}
    			catch (IOException e)
    			{
    				System.err.println("Error: "+e);
    			}
    		}
    		else  //else prompt user to enter filename to be used
    		{
    			try
    			{
    				System.out.println("Unable to read from file");
    				System.out.println("Please enter a text file now: ");
    				scanUser = new Scanner(System.in);
    				String input = scanUser.nextLine();
    				br = new BufferedReader(new FileReader(input));
    				scan = new Scanner(br);
    				runProj();	
    			}
    			catch (IOException e)
    			{
    				System.err.println("Error: "+e);
    			}
    		}
    	}//end main
    	
    	/*-----------------------------------------
    	 * Method runProj
    	 * 1. Will scan the integers to be used for program
    	 * 2. Prints out the initial table
    	 * 3. Runs the getNeighbor() method
    	 * 4. quits after 20 generations
    	 * 5. For testing purposes, the file used, 
    	 * 		after 20 gen's, should look like a heart.
    	 ----------------------------------------*/
    	
    	public static void runProj()
    	{
    		System.out.println("Project 1");
    	 	System.out.println("Edward Albrecht\n");
    		int row = scan.nextInt();
    		int column = scan.nextInt();
    		int generation = scan.nextInt();
    		coord = new int[row][column];
    		while(scan.hasNext())  //as long as there is another item to be scanned, add that to the array as a point
    		{
    			coord[scan.nextInt()][scan.nextInt()] = 1;
    		}
    		int genCount = 1;
    		System.out.println("Please press enter now...");
    		String reader = scanUser.next();
    			while(!reader.equalsIgnoreCase("quit") && genCount !=20)//need to alter to eventually check just for enter key press
    			{
    				printTop(column);
    				printSides(row, column);
    				printTop(column);
    				System.out.println("Generation "+genCount);
    				System.out.println("Please press enter now...");
    				reader = scanUser.next();
    				neighbor(row, column);
    				genCount++;
    			}
    		System.out.println("Thank you");
    		//after 20 generations, quit program
    		System.exit(0);
    	}//end runProj
    	/*-----------------------------------------
    	 * Method neighbor
    	 * 1. starting from coord[0][0] check all the way to end of table
    	 * 		for neighbors
    	 * 2. at each cell, based on number of neighbors in 8 neighboring cells, count++
    	 * 3. at each cell, based on count, perform method
    	 ----------------------------------------*/
    	public static void neighbor(int row, int column)
    	{
    		for(int index = 1; index < row-1; index++)
    		{
    			for(int index2 = 1; index2 < column - 1; index2++)
    			{
    				int count = 0;
    				if(coord[index][index2+1] == 1)//right
    				{ 
    					count++;
    				}
    				if(coord[index+1][index2+1] == 1)//bottom right
    				{ 
    					count++;
    				}
    				if(coord[index+1][index2] == 1)//bottom mid
    				{ 
    					count++;
    				}
    				if(coord[index+1][index2-1] == 1)//bottom left
    				{ 
    					count++;
    				}	
    				if(coord[index][index2-1] == 1)//left
    				{ 
    					count++;
    				}
    				if(coord[index-1][index2-1] == 1)//top left
    				{ 
    					count++;
    				}
    				if(coord[index-1][index2] == 1)//top mid
    				{ 
    					count++;
    				}
    				if(coord[index-1][index2+1] == 1)//top right
    				{ 
    					count++;
    				}
    				survive(index, index2);
    				death(index, index2);
    				birth(index, index2);			
    			}
    		}//end for loop
    	}//end neighbor
    	
    	public static void birth(int r, int c)
    	{
    		if(count == 3)
    		{
    			coord[r][c] = 1;
    		}
    	}//end birth
    	public static void death(int r, int c)
    	{
    		if(count >=4 || count < 2)
    		{
    			coord[r][c] = 0;
    		}
    	}//end death
    	public static void survive(int r, int c)
    	{
    		if(count == 2)
    		{
    			coord[r][c] = 1;
    		}
    	}//end survive
    	
    	public static void printTop(int c)
    	{
    		System.out.print("+");
    		 for(int top = 0; top < c-2; top++)
    		 {
    		 	System.out.print("-");
    		 }
    		System.out.println("+");
    	}//end printTop
    	public static void printSides(int r, int c)
    	{
    		for(int side = 0; side < r; side++)
    		{
    			System.out.print("|");
    				for(int rSide = 0; rSide < c-2; rSide++) 
    				{
    					if(coord[side][rSide] == 1)
    					{
    						System.out.print("X");
    					}
    					else
    					System.out.print(" ");
    				}
    				System.out.println("|");
    		}
    
    	}//end printSides
    }//end class
    

    Evigilant on
    XBL\PSN\Steam\Origin: Evigilant
  • zeenyzeeny Registered User regular
    edited January 2009
    I have just skimmed over your code. You add 1 to index that sends row out of bounds. Probably there are other bugs as well.

    zeeny on
  • iTunesIsEviliTunesIsEvil Cornfield? Cornfield.Registered User regular
    edited January 2009
    Anybody here good with Win32? I've got a .NET (C#, Framework 2.0) application that calls some Win32 functions via p/invoke, and I'm having some issues.

    One of the options of this program is to capture a window that the user specifies with a mouse click. So the user clicks on a window, and then I get the top-most window where the click occurred using the WindowFromPoint function. My issue is that depending on where the click occurs in the window sometimes I won't get the handle of the window itself, I'll get a handle to a control or container that is a child of the window I'm actually wanting to get. If the click occurs on the title-bar of the window things go fine 99% of the time. So I know I'm having an issue with windows, child windows, and containers in some manner, but I can't exactly figure out what is going on and how I can solve the issue.

    Example in spoiler (sorry bout the semi-large images):
    So, I want to take a screen cap of this explorer window that's open:
    vc_targetwin.jpg

    If I click the title-bar, w00t, all is well. I get the full window:
    vc_goodwin.jpg

    But if I click in the area where each drive is listed in the detail view I get this:
    vc_badwin.jpg

    I get the feeling I could try a while loop where I go up the chain calling GetParent until I get the desktop (hWnd = 0, I think) or a null handle and then use the last good value I got, but I dont know if that would work or if it'd be accurate. Does anyone have any ideas as to what I'm screwing up here or what I can do about it? Sorry if this is unclear, if anyone can help I can provide plenty more detail.

    iTunesIsEvil on
  • EvigilantEvigilant VARegistered User regular
    edited January 2009
    zeeny wrote: »
    I have just skimmed over your code. You add 1 to index that sends row out of bounds. Probably there are other bugs as well.

    yea, that was the problem. However, now the issue is getting it to work properly.

    What is supposed to happen is, given a range of coords, the object mutates based on how many neighbors it has for that generation and then shows that mutation in the next generation:

    exactly 3, the cell gives birth to another organism
    2 - 3, the organism survives to the next generation
    >4 or <2 the organism dies

    However, I can't seem to find a proper way to do this. Right now, I can check if the cell has any neighbors and tally a total, but I'm lost on how to make it do those statements. For example, if a cell is empty and has 3 neighbors, it'll give birth to a new organism. However, all the remaining cells see this and continue to use this new organism in their current calculations, when it shouldn't appear until the next generation. That's where I'm stuck at right now.

    Evigilant on
    XBL\PSN\Steam\Origin: Evigilant
  • JHunzJHunz Registered User regular
    edited January 2009
    Evigilant wrote: »
    zeeny wrote: »
    I have just skimmed over your code. You add 1 to index that sends row out of bounds. Probably there are other bugs as well.

    yea, that was the problem. However, now the issue is getting it to work properly.

    What is supposed to happen is, given a range of coords, the object mutates based on how many neighbors it has for that generation and then shows that mutation in the next generation:

    exactly 3, the cell gives birth to another organism
    2 - 3, the organism survives to the next generation
    >4 or <2 the organism dies

    However, I can't seem to find a proper way to do this. Right now, I can check if the cell has any neighbors and tally a total, but I'm lost on how to make it do those statements. For example, if a cell is empty and has 3 neighbors, it'll give birth to a new organism. However, all the remaining cells see this and continue to use this new organism in their current calculations, when it shouldn't appear until the next generation. That's where I'm stuck at right now.
    Right now you're using the number 1 to represent an organism that is alive, and 0 (or uninitialized, which is ugly) to represent not alive. What you need to do, is use a couple more ints to represent the states "alive after this generation" and "dead after this generation". Then, at the end of processing this generation, you can iterate through again to set those to what they now should be.

    Edit: For clarity, I recommend using a few final static ints as constants to represent the states rather than continuing to use the numbers directly.

    JHunz on
    bunny.gif Gamertag: JHunz. R.I.P. Mygamercard.net bunny.gif
  • EtheaEthea Registered User regular
    edited January 2009
    or use an enum.

    Ethea on
  • ASimPersonASimPerson Cold... ... and hard.Registered User regular
    edited January 2009
    Ethea wrote: »
    or use an enum.

    This. Typesafe enums are awesome.
    Fagadaba wrote: »
    Here's my code as of now:
    #include <cstdlib>  /** do I need this? **/
    #include <iostream>  /** and this? **/
    #include <stdio.h>  /** for printf and scanf **/
    #include <conio.h>  /** for getch **/
    #include <math.h> /** for sqrt **/
    
    int main(void)  /** first thing run **/
    {  /** begin **/
    	int numberOne;  /** declare variable numberOne **/
    	printf("Saisissez un nombre: ");  /** Enter a number **/
    	scanf("&#37;d", &numberOne);  /** input numberOne, real **/
    	printf("La racine carr&#233;e de %d est: %d",numberOne, numberOne*numberOne);  /** give back square root there **/ 
    	getch();  /**wait for enter to be pressed **/
        return 0;
    }  /** end **/
    
    

    I get a window(console?) that asks to enter a number(Saisissez un nombre) and gives back that number to itself(numberOne*numberOne). I need the exact opposite. For it to ask a number then give me back the square root(racine carrée). Also, does anyone know how to get weird characters(lol french) to show in the console? I get zeros where "é" should be.

    1) Since you're using just C code you don't need those C++ headers (cstdlib and iostream).
    2) You, um, don't ever actually calculate the square root anywhere. It's doing exactly what you're telling it to do: print the number and the number times itself.
    3) As for the French characters, you may want to google this but you can try messing with the Regional and Language Settings in the control panel.

    ASimPerson on
  • jackaljackal Fuck Yes. That is an orderly anal warehouse. Registered User regular
    edited January 2009
    Or just create a second 2d array to store the results.
    Read from original, write results to second array, replace original with second array.

    jackal on
  • EvigilantEvigilant VARegistered User regular
    edited January 2009
    I just found that my neighbor method isn't really doing anything. It's not doing it's neighbor check and I can't figure out why.
    public static final int alive = 1;
    public static final int dead = 2;
    
    public static void neighbor(int row, int column)
    	{
    		for(int index = 1; index < row -1; index++)
    		{
    			for(int index2 = 1; index2 < column - 1; index2++)
    			{
    				int count = 0;
    				if(coord[index][index2+1] == 1)//right
    				{ 
    					count++;
    				}
    				if(coord[index+1][index2+1] == 1)//bottom right
    				{ 
    					count++;
    				}
    				if(coord[index+1][index2] == 1)//bottom mid
    				{ 
    					count++;
    				}
    				if(coord[index+1][index2-1] == 1)//bottom left
    				{ 
    					count++;
    				}	
    				if(coord[index][index2-1] == 1)//left
    				{ 
    					count++;
    				}
    				if(coord[index-1][index2-1] == 1)//top left
    				{ 
    					count++;
    				}
    				if(coord[index-1][index2] == 1)//top mid
    				{ 
    					count++;
    				}
    				if(coord[index-1][index2+1] == 1)//top right
    				{ 
    					count++;
    				}
    				birth(index, index2);
    				death(index, index2);
    				survive(index, index2);
    			}
    		}//end for loop
    	}//end neighbor
    
    	public static void birth(int r, int c)
    	{
    		if(count == 3)
    		{
    			coord[r][c] = alive;
    		}
    	}//end birth
    	public static void death(int r, int c)
    	{
    		if(count >=4)
    		{
    			coord[r][c] = dead;
    		}
    		if(count < 2)
    		{
    			coord[r][c] = dead;
    		}
    	}//end death
    	public static void survive(int r, int c)
    	{
    		if(count == 2)
    		{
    			coord[r][c] = alive;
    		}
    	}//end survive
    
    
    

    I had the known points being printed off as well as their count. In the first generation, the neighbor method did not tally the count at all.
    After the first generation, everything goes to 0 and all the points cease to exist.
    If I comment out the death(index, index2); then everything stays where they are.
    However, the birth method isn't doing what it's supposed to do either, which goes back to the neighbor method not properly checking anything at all.

    What's supposed to happen is, each point has 8 neighbors. If that point has exactly 3 alive neighbors, that empty spot gives birth. If that point has more than 4 or less than 2, that point dies, and if that point has exactly 2 or 3, that point survives through till the next generation.

    So my neighbor method starts at 1,1 and checks on that row for each column all 8 neighbors (index + or - 1) for left and right and (index2 + or -1) for up or down. At least I thought that's how I'm supposed to do it, but it doesn't seem to function at all.

    Evigilant on
    XBL\PSN\Steam\Origin: Evigilant
  • jackaljackal Fuck Yes. That is an orderly anal warehouse. Registered User regular
    edited January 2009
    count is in scope only in the inner for loop. I don't know what scope the count variable(s) in birth, death and survive is/are in, but it isn't certainly not the same variable you are incrementing in neighbor.

    jackal on
  • FagadabaFagadaba Registered User regular
    edited January 2009
    ASimPerson wrote: »
    Ethea wrote: »
    or use an enum.

    This. Typesafe enums are awesome.
    Fagadaba wrote: »
    Here's my code as of now:
    
    #include <cstdlib>  /** do I need this? **/
    #include <iostream>  /** and this? **/
    #include <stdio.h>  /** for printf and scanf **/
    #include <conio.h>  /** for getch **/
    #include <math.h> /** for sqrt **/
    
    int main(void)  /** first thing run **/
    {  /** begin **/
    	int numberOne;  /** declare variable numberOne **/
    	printf("Saisissez un nombre: ");  /** Enter a number **/
    	scanf("&#37;d", &numberOne);  /** input numberOne, real **/
    	printf("La racine carr&#233;e de %d est: %d",numberOne, numberOne*numberOne);  /** give back square root there **/ 
    	getch();  /**wait for enter to be pressed **/
        return 0;
    }  /** end **/
    
    

    I get a window(console?) that asks to enter a number(Saisissez un nombre) and gives back that number to itself(numberOne*numberOne). I need the exact opposite. For it to ask a number then give me back the square root(racine carrée). Also, does anyone know how to get weird characters(lol french) to show in the console? I get zeros where "é" should be.

    1) Since you're using just C code you don't need those C++ headers (cstdlib and iostream).
    2) You, um, don't ever actually calculate the square root anywhere. It's doing exactly what you're telling it to do: print the number and the number times itself.
    3) As for the French characters, you may want to google this but you can try messing with the Regional and Language Settings in the control panel.

    Thanks for telling me about those C++ headers! I'm guessing I have to use math to get a square root right? Like, I can't write "numberOne = numberTwo*numberTwo;", so I need to get Two on the other side, with just One and something something on the other side? Arg, I'm not good at this. Is it "numberTwo = 1/numberOne;"? Nope, don't think so. Help?

    Fagadaba on
  • EvigilantEvigilant VARegistered User regular
    edited January 2009
    jackal wrote: »
    count is in scope only in the inner for loop. I don't know what scope the count variable(s) in birth, death and survive is/are in, but it isn't certainly not the same variable you are incrementing in neighbor.

    That was exactly it. The count I was using was not the same count used in the other methods. The last thing I have an issue is, is with scanning for the key press enter. I'm not sure how I set up scanner or another method to check just for that keypress.

    EDIT:
    Disregard. I created a string to use the scanner; but then had that turn into an empty string.
    System.out.println("Please press enter now...");
    		String reader = scanUser.nextLine();
    		reader = "";
    

    I just needed it to pause and wait for the enter key to be pressed. Seems to work perfectly. Thanks everyone for all of your help.

    Evigilant on
    XBL\PSN\Steam\Origin: Evigilant
  • EtheaEthea Registered User regular
    edited January 2009
    Fagadaba wrote: »
    ASimPerson wrote: »
    Ethea wrote: »
    or use an enum.

    This. Typesafe enums are awesome.
    Fagadaba wrote: »
    Here's my code as of now:
    
    #include <cstdlib>  /** do I need this? **/
    #include <iostream>  /** and this? **/
    #include <stdio.h>  /** for printf and scanf **/
    #include <conio.h>  /** for getch **/
    #include <math.h> /** for sqrt **/
    
    int main(void)  /** first thing run **/
    {  /** begin **/
    	int numberOne;  /** declare variable numberOne **/
    	printf("Saisissez un nombre: ");  /** Enter a number **/
    	scanf("%d", &numberOne);  /** input numberOne, real **/
    	printf("La racine carrée de %d est: %d",numberOne, numberOne*numberOne);  /** give back square root there **/ 
    	getch();  /**wait for enter to be pressed **/
        return 0;
    }  /** end **/
    
    

    I get a window(console?) that asks to enter a number(Saisissez un nombre) and gives back that number to itself(numberOne*numberOne). I need the exact opposite. For it to ask a number then give me back the square root(racine carrée). Also, does anyone know how to get weird characters(lol french) to show in the console? I get zeros where "é" should be.

    1) Since you're using just C code you don't need those C++ headers (cstdlib and iostream).
    2) You, um, don't ever actually calculate the square root anywhere. It's doing exactly what you're telling it to do: print the number and the number times itself.
    3) As for the French characters, you may want to google this but you can try messing with the Regional and Language Settings in the control panel.

    Thanks for telling me about those C++ headers! I'm guessing I have to use math to get a square root right? Like, I can't write "numberOne = numberTwo*numberTwo;", so I need to get Two on the other side, with just One and something something on the other side? Arg, I'm not good at this. Is it "numberTwo = 1/numberOne;"? Nope, don't think so. Help?

    Yes use the included math library in C to calculate out the square root. A okay reference is http://www.cplusplus.com/reference/clibrary/cmath/

    Ethea on
  • FagadabaFagadaba Registered User regular
    edited January 2009
    Ethea wrote: »
    Fagadaba wrote: »
    ASimPerson wrote: »
    Ethea wrote: »
    or use an enum.

    This. Typesafe enums are awesome.
    Fagadaba wrote: »
    Here's my code as of now:
    
    #include <cstdlib>  /** do I need this? **/
    #include <iostream>  /** and this? **/
    #include <stdio.h>  /** for printf and scanf **/
    #include <conio.h>  /** for getch **/
    #include <math.h> /** for sqrt **/
    
    int main(void)  /** first thing run **/
    {  /** begin **/
    	int numberOne;  /** declare variable numberOne **/
    	printf("Saisissez un nombre: ");  /** Enter a number **/
    	scanf("%d", &numberOne);  /** input numberOne, real **/
    	printf("La racine carrée de %d est: %d",numberOne, numberOne*numberOne);  /** give back square root there **/ 
    	getch();  /**wait for enter to be pressed **/
        return 0;
    }  /** end **/
    
    

    I get a window(console?) that asks to enter a number(Saisissez un nombre) and gives back that number to itself(numberOne*numberOne). I need the exact opposite. For it to ask a number then give me back the square root(racine carrée). Also, does anyone know how to get weird characters(lol french) to show in the console? I get zeros where "é" should be.

    1) Since you're using just C code you don't need those C++ headers (cstdlib and iostream).
    2) You, um, don't ever actually calculate the square root anywhere. It's doing exactly what you're telling it to do: print the number and the number times itself.
    3) As for the French characters, you may want to google this but you can try messing with the Regional and Language Settings in the control panel.

    Thanks for telling me about those C++ headers! I'm guessing I have to use math to get a square root right? Like, I can't write "numberOne = numberTwo*numberTwo;", so I need to get Two on the other side, with just One and something something on the other side? Arg, I'm not good at this. Is it "numberTwo = 1/numberOne;"? Nope, don't think so. Help?

    Yes use the included math library in C to calculate out the square root. A okay reference is http://www.cplusplus.com/reference/clibrary/cmath/

    Oh ho I got it! Here's the almost final code:
    #include <stdio.h>  /** for printf and scanf **/
    #include <conio.h>  /** for getch **/
    #include <math.h> /** for sqrt **/
    
    int main(void)  /** first thing run **/
    {  /** begin **/
    	int numberOne;  /** numberOne is going to be the one that needs to be squared **/
    	int numberTwo;  /** numberTwo will be used to get the square root of numberOne **/
    	printf("Enter a number here please: ");  /** numberOne used to get square root out **/
    	scanf("%d", &numberOne);  /** input numberOne, real **/
    	numberTwo = sqrt (numberOne);  /** get square root **/
    	printf("The square root of %d is the mighty: %d.",numberOne, numberTwo);  /** give back square root there **/ 
    	getch();  /**wait for enter to be pressed **/
        return 0;
    }  /** end **/
    
    

    Fagadaba on
  • Mr.FragBaitMr.FragBait Registered User regular
    edited January 2009
    Evigilant wrote: »
    I just needed it to pause and wait for the enter key to be pressed. Seems to work perfectly. Thanks everyone for all of your help.

    Well then, just call the method, why save the returned String if you don't need it?
    System.out.println("Please press enter now...");
    scanUser.nextLine();//get the user input and don't use it
    

    Mr.FragBait on
  • KrisKris Registered User regular
    edited January 2009
    Fagadaba: Glad you got it figured out. :) One thing though, beware you don't get into the habit of over-commenting. Comments are good to explain things that may not be too clear by themselves, but commenting every single thing in your code takes away more than it adds.

    Kris on
  • LednehLedneh shinesquawk Registered User regular
    edited January 2009
    Sigh. Spent the entire workday trying to track down a C++ pointer bug causing a random-as-fuck malloc() failure right at the end of a 5-minute run program. Starting dbx, waiting for five minutes for it to reach your pre-fucked breakpoint, stepping over, and watching it break AGAIN despite fixing like five more double-deletes and delete-instead-of-delete[]s wears on the fucking soul, let me tell you.

    And I never found it. In fact, it took me most of the afternoon just to get dbx to start up it's access-check and memleak functionality. Fuck me sideways, what a waste.

    I wonder how feasible it would be to change the hundreds of raw pointers in this thing into boost::shared_ptrs and just be fucking done with it. :|

    (edit) And the malloc() failure happens somewhere in the middle of a fstream::write call. Seriously, what the fuck.

    (edit 2) And THEN you realize that one of those double-deletes you fixed wasn't a double delete at all and you've just caused a new leak! JOY! :x

    (edit 3) AND WHY THE FUCK ISN'T lint INSTALLED ON THE DEV SERVER ROOOARHAHGHGHGHHGJHFDKJGHLK$EUYGL#gh

    (edit the last) Oh yeah, the actual question. Besides lint (whenever I can get ahold of it :x) for static analysis and dbx's access-check for dynamic analysis, and finally stepping through the debugger piece by tiny sodding piece, are there any tools I'm forgetting for tracking down memory leaks, double deletes, etc that could be the cause of my malloc-in-the-middle-of-an-fstream-call error?

    Ledneh on
  • ASimPersonASimPerson Cold... ... and hard.Registered User regular
    edited January 2009
    Valgrind, if you're on Linux:
    valgrind --leak-check=yes --show-reachable=yes yourprogram [args]
    

    ASimPerson on
This discussion has been closed.