Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

151.

Solve : Applet?

Answer»

I am creating an Applet using java. The applet is supposed to get user input to make a rectangle. The user will enter in the height and width, and then click the draw BUTTON to have the rectangle drawn. My code compiles and runs fine, but I am just having some problems with some of the minor details. I am supposed to restrict the maximum and MINIMUM SIZE of the applet such that the user cannot enter a negative number or zero for the min, and limit the max so that the rectangle will be properly displayed in the applet. I'm thinking that this part would be IF statements, but I'm just unsure of how to goabouts in writing the IF statement. Also, I would like to have an image set as my background, but I just can't seem to get it to work right. Here is my code

Code: [SELECT]

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.awt.Graphics;

public class rectangle extends Applet implements ActionListener
{
//declare VARIABLES
Image background; //declare an Image object
int height, width;

//construct components

Label heightLabel = new Label("Enter the height of your rectangle: ");
TextField heightField = new TextField(10);
Label widthLabel = new Label ("Enter the width of your recntagle: ");
TextField widthField = new TextField(10);
Button drawButton = new Button("Draw Rectangle");
Label outputLabel = new Label("Click the Draw Rectangle button to see your rectangle.");
public void init()
{
setMaximumSize(new Dimension(700,700));
setMinimumSize(new Dimension(500,500));
setForeground(Color.green);
add(heightLabel);
add(heightField);
add(widthLabel);
add(widthField);
add(drawButton);
drawButton.addActionListener(this);
add(outputLabel);
setBackground(Color.red);
background = getImage(getCodeBase(), "santa.jpg");


}
public void actionPerformed(ActionEvent e)
{
height = Integer.parseInt(heightField.getText());
width = Integer.parseInt(widthField.getText());
repaint();
}
public void paint(Graphics g)
{
g.setColor(Color.green);
g.drawRect(125,100,width,height);
g.fillRect(125,100,width,height);
g.drawImage(0,0,background);

}
}

152.

Solve : Boolean Operators?

Answer»

I was helping a friend with a Python assignment and in their code I noticed something along the lines of this:

Code: [Select]if x < (y and z):

They were a bit of a novice at PROGRAMMING and I take it that their intention was that they wanted to simply check if x was less than y and z, but when the were getting incorrect SELECTIONS from this conditional, I suggested that they simply change it to

Code: [Select]if x < y and x < z:
which then worked out.

Now here's what I'm curious about. What does a language do when the operands of a boolean operator are not true/false or 1/0?

What does (y and z) equal when y and z are say 1.5 and 0.2? Does it vary from language to language?

I personally have little experience with Python and in other languages like C++ or Java this would simply error. But the very fact that the code ran in Python has me a little confused.1. The word "Boolean" comes from the name of George Boole, so is spelled with a capital B, although many people don't SEEM to bother these days.

2. A Boolean or logical data type can have one of two values (usually denoted true and false). These can be represented with 1 bit which can either be 1 or 0. In most languages when you try to do a Boolean operation on data types of more than 1 bit, a "bitwise" operation is performed, that is, each bit of one number, with each bit of another number, performing a logic operation for every bit.

The boolean math expression below describes this:

e.g.

00001111 AND
00011110
--------  equals
00001110


I don't think it makes sense to try and do Boolean stuff with non integers.
Ah ok. I knew of SEPARATE bitwise operators like & and | in addition to comparison operators like && and || in Java/C++, but I hadn't thought that 'and' and 'or' would automatically do that for inputs with binary representations that require more than 1 bit. This is the first time I've seen it happen.

So for the example I indicated, should I assume that Python took the binary representations of 1.5 and 0.2 and performed bitwise 'and' on them?

Also I'll keep capitalization of Boolean in mind from now on  I'm not sure how Python represents non integer values.Or how it does logical operations on non-Boolean data types, if it does them at all. My example was from FreeBasic. Like I said, I don't think it makes sense to try bitwise operations with non integer values. Did you understand why I wrote that? (Do you know what "floating point" means?)


Well I have some sense of what floating point means. I did recently learn the IEEE representation for floating point numbers, which are essentially decimal values.Some time ago, Bill Gates, or somebody like him, made the run that false would be 0 and true would be -1 using 16 bit integer on the Intel 8080 CPU. the minus one is expressed in binary as:
1111 1111-1111 1111
The Intel CPU can test for zero or non-zero values. Engineers like to use this to read the status of external devices. Thus any value that is not zero is a true value.

In other words, the practice is more practical than pure.


Interesting

153.

Solve : VBS - how to send windows key??

Answer»

Hey does anyone know how to send windows key using VBS?

Thanks,What are you REFERRING to in SEND?

I have a few things that come to mind, but i need more info to know I am on track with what you are trying to do. Are you wanting to send-pass a windows key into a location like an unattended install or send it out from say the REGISTRY using a VBS? Or something ELSE ... registry key alteration etc?Windows Key?
http://www.pcmag.com/article2/0,2817,2384344,00.asp
Nope, not that
http://dltv.wordpress.com/2007/03/12/vbs-script-to-get-windows-xp-cd-key-and-save-to-text-file/
No
Send?
http://www.computerperformance.co.uk/ezine/ezine120.htm

If you're talking about the Windows logo key on the keyboard, you cannot use the sendkeys METHOD in VBScript. This also applies to the context menu, numlock and print screen keys.

If you're not talking about the Windows logo key on the keyboard, then we need more information.

 Correction to above post: The numlock key can can be sent via the sendkeys method.

Sorry for any confusion.  sorry for ambigouity, i want to send the windows logo key using wshshell.sendkeys()

if this isnt possible does anyone know how to move a window in C++ using a handle to fill half the screen, the same as when you PUSH a window in windows 7 to the far side and it auto does it for you?

154.

Solve : C++ Windows Form Application?

Answer»

I am creating a Windows Form Application in Visual C++ 2011 Express and have run into a problem.

To populate a list box, I have used a for loop in Form1.h. This works fine and my program will still build and run, but design view no longer works. I get the following error:

C++ CodeDOM parser error: Line: 368, Column: 9 --- Unexpected token for a 'term'

Line 368 Contains my for loop, as shown here:

Code: [Select] for (INT i = 5; i <= 50; i = i + 5)
{
listBox1->Items->ADD( i );
}
Does anyone know the reason for this? I'm pretty confused as to why I can compile and run the program still, but design view fails to function.Can you share entire source so we can see if we get same error or is source private? Dont have much to work with with a for loop and cant simulate at my END to plug away at this. I haven't played with 2011 yet. I am still using C++ 2010 express. So I will also have to upgrade to 2011 to be apples to apples.A soon as the appearance of C++ language, the standard library goes with it. It contributres to preplace the traditional C functions,for examples the printf and scanf. For this, the standard library turned to be the large QUANTITY of the Standard TEMPLATE Library. So, it known as a hybrid language.

155.

Solve : c++ create a web browser?

Answer»

Hey Guys,

I want to make my own WEB BROWSER, something really basic that you type in a text box and a page appears. Any ideas on where to start, i would PREFER to write this in C++

Thanks in advanceYou are into C++. Good move. 
Surly you understand that a browser can and should be OS independent. At least at the source code level. That is in harmony with the concept of C++ programming. The point is do not ignore the work of others just because its not built  for the OS you presently use. That should not really matter very much.

Look at this:
Quote

...
WebKit is an open source web browser engine. WebKit is also the name of the Mac OS X system framework version of the engine that's used by Safari, Dashboard, Mail, and many other OS X applications. WebKit's HTML and JavaScript code began as a branch of the KHTML and KJS libraries from KDE. This website is also the home of S60's S60 WebKit development.
...
http://www.webkit.org/
Using their work, you can make an outline and project time line for yourself.  Would it make a difference you to know AHEAD of time the project will take you six weeks working n10 hours a day six days a week?
Of course you would look at http://www.mozilla.org/ and I suppose you already did that but had not heard of webkit.

Have Fun   
156.

Solve : VBScript adding TCP/IP port registry help?

Answer»

Hello all,

I am starting to dive headfirst into VBScript, and I am already encountering problems. The following script is designed to run to install some raw TCP/IP ports that can be utilized to install some network computers.

Code: [Select]Set WshShell = CreateObject("WScript.Shell")
myKey = "HKLM\SYSTEM\ControlSet001\Control\Print\Monitors\Standard TCP/IP Port\Ports"
WshShell.RegWrite myKey&"\","10.0.0.1",Nothing

myKey = "HKLM\SYSTEM\ControlSet001\Control\Print\Monitors\Standard TCP/IP Port\Ports\10.0.0.1"
WshShell.RegWrite myKey&"\",Protocol,Nothing
WshShell.RegWrite myKey&"\Protocol",1,"REG_DWORD"
WshShell.RegWrite myKey&"\",Version,Nothing
WshShell.RegWrite myKey&"\Version",2,"REG_DWORD"
WshShell.RegWrite myKey&"\",HostName,Nothing
WshShell.RegWrite myKey&"\HostName","10.0.0.1","REG_SZ"
WshShell.RegWrite myKey&"\",IPAddress,Nothing
WshShell.RegWrite myKey&"\IPAddress",,"REG_SZ"
WshShell.RegWrite myKey&"\",HWAddress,Nothing
WshShell.RegWrite myKey&"\HWAddress",,"REG_SZ"
WshShell.RegWrite myKey&"\",PortMonMibPortIndex,Nothing
WshShell.RegWrite myKey&"\PortMonMibPortIndex",0,"REG_DWORD"
WshShell.RegWrite myKey&"\",PortNumber,Nothing
WshShell.RegWrite myKey&"\PortNumber",9100,"REG_DWORD"
WshShell.RegWrite myKey&"\","SNMP Community",Nothing
WshShell.RegWrite myKey&"\SNMP Community","public","REG_SZ"
WshShell.RegWrite myKey&"\","SNMP Enabled",Nothing
WshShell.RegWrite myKey&"\SNMP Enabled",1,"REG_DWORD"
WshShell.RegWrite myKey&"\","SNMP Index",Nothing
WshShell.RegWrite myKey&"\SNMP Index",1,"REG_DWORD"

Set WshShell = Nothing
Set myKey=Nothing
I've already gone rounds with the server room about setting up a print server and they are not being cooperative (I think they are just being lazy personally), so I've decided to try to do this myself. I do not have full domain admin privileges but I do have enough to do some damage (figuratively speaking.) If anyone has some pointers on what I can do to GO about setting up a print server without help from the server room, that would be helpful as well.

Like I said, I am brand new to VBScript, so please let me know of any blatent syntax errors or any obvious issues that should be addressed. The following is the error that I am getting


Line: 3
Char: 1
Error: Type Mismatch
Code: 800A000D
Source: Microsoft VBScript runtime error
I was able to solve this problem, it seems I MISREAD the usage portion of RegWrite, and I was using "\"s where I shouldn't and not using them where I should. In any CASE, the problem with this method came down to not having permissions to edit the registry this way. Which brings me to my problem. I am an administrator for the LAN within my building, however the parent office has the full administrative rights and responsibilities. They are quick to make sure I don't have any more rights than I absolutely need, but are rather slow when it comes to living up to their responsibilities. The reason I am GOING through all of this trouble with installing printers is that the parent office won't setup a print server for me, nor really help me out with much at all. I have one guy in there who I talk to regularly, and I mentioned to him about GPOs. He told me that if I built the GPO, he could make sure it did it's job on his end, but he wouldn't be able to help me out much more than that. So here is the goal, and possible solution.

Goal: To allow any user within the building the to be able to install any printer in the building.

Issues:
Some printer drivers require administrative priviledges when they are installed onto the system.
Not everyone is an administrator, nor should they be.
Not everyone is tech savvy, so the (almost) COMPLETE automation of the process is desired.

Proposed solution: If there is a way to either write a script that would automate the entire function by them double-clicking the script, that is my ultimate goal. I have been able to do this with some of the machines that are already installed in the .cab file for printer drivers. See below:

Code: [Select]echo off
cscript %windir%\system32\Printing_Admin_Scripts\en-US\prnport.vbs -a -s "%computername%" -r 10.2.0.1 -o raw -n 9100>nul
cscript %windir%\system32\Printing_Admin_Scripts\en-US\prnmngr.vbs -a -p "HP LJ 2025 211 LM" -m "HP Color Laserjet CP2020 Series PCL6" -r "10.2.0.1">nul
exit
But this coding does not work if the printer driver is not available in the .cab file.

So I either need help writing a different script for the printers not in the .cab file, or I need help building a GPO to put those printer drivers into the .cab file. Any help is welcome and appreciated.

157.

Solve : Excel - need to sync two sheets into one master & be able to add rows?

Answer»

Hi there Hope,

I'm a record collector and I need to get my collection insured. For many years I worked on cataloging it all and have them listed in two separate Excel sheets in the same file/workbook. I'm hoping to ENLIST your help with merging (or is it syncing, or consolidating? I don't know?) my LPs sheet and 7" SINGLES sheet into ONE master worksheet, preferably sorted by column header ARTIST, then YEAR.

The idea is that when I enter a newly purchased LP or 7" into its respective sheet by inserting a new row, it will automatically populate into the master, RATHER than me being required to remember to copy and paste it in. Likewise, were I to (for example) change the VALUE (listed in $$$ in a cell) of any given record in the LP or 7" SINGLES sheet, it would automatically change in the master.

I have spent 20+ hours (maybe a lot more, I don't know, have lost track), tried various methods and all have failed. The closest I got was using a MICROSOFT Help page:

http://www.rondebruin.nl/copy2.htm

I've tried using this, followed the instructions to the letter etc, all to no avail:
http://www.rondebruin.nl/code.htm


Here's the Microsoft page that I was directed to and think I got close to successfully completing the task!
http://msdn.microsoft.com/en-us/library/cc793964.aspx

Now I'm turning to you for help! I hope you don't mind!

I'm not sure, but it may be relevant that some of the cells have a CATALOGUE # (and maybe even LABEL) that starts with a zero or other number-only combinations. In the document, the cell would not accept what I entered until I changed the cell format from General to Text. I have read in some areas that all cells must be formatted as "General" but I haven't tried this yet.

All column headers in both sheets are identical, and include a SUM function in the final two columns to keep track of COST and VALUE (ie a repurchase price) The SUM function can be removed if that is creating the problem (I have the total $$$ value being SUM'd at the end of all entries) but it would preferable to keep this.

I'm on Windows XP, using Microsoft Excel 2002

Please help!

Best regards,
SnapsDoes your version of Office have Access (database)?  If so, are you familiar with Access?  Achieving what you want would work quite well with Access. Just checked and yes, I do have Access. Sadly, I have NEVER used this program!

But, if you are convinced it will work best for what I need to do, I'm prepared to give it a go.
That is, as long as I am able to import all the data I have entered into my Excel worksheets (the entering of my record collection has taken 8-9 YEARS to complete!)

Thanks SoybeanYes, Access can import from Excel.  Your LPs sheet and 7" SINGLES sheet would each become a "table" in Access.  Then, you could create another table, Query, or Report.  The third table, or the Query or Report form would pull the data from the main two tables.  Therefore, any updating of the two main tables flows into the other table or the Query form or Report form.

Clearly, using Access will REQUIRE some time to get to know enough about it to use it for your record collection.  If you can get a book or video on Access from a library, that would be quite helpful.  Of course, many references can be found on the Internet, such as Creating a new Access database from an Excel spreadsheet.  My search phrase for finding this was import excel sheet into access, or specify the 2002 version and use import excel sheet into access 2002

Many books on Access can be found on Amazon.com.  I really don't know what book might be the best to recommend.  For as little as $4, you can get a used copy of Microsoft® Access Version 2002 Step by Step (Step by Step (Microsoft)) [Paperback].  Buyers reviews posted on Amazon.com are mixed.  Another book that can be purchased at very low cost by choosing a used one is Teach Yourself Visually Access 2002 [Illustrated] [Paperback].  Buying more than one book can be a good approach, since the strengths in one may offset the weaknesses in another.

By the way, I hope you have all your record collection data backed up on a medium other than your hard drive.  If not and your hard drive failed, I'm sure you'd be very distressed.  Quote from: soybean on November 06, 2011, 09:45:35 AM

Yes, Access can import from Excel.  Your LPs sheet and 7" SINGLES sheet would each become a "table" in Access.  Then, you could create another table, Query, or Report.  The third table, or the Query or Report form would pull the data from the main two tables.  Therefore, any updating of the two main tables flows into the other table or the Query form or Report form.

By the way, I hope you have all your record collection data backed up on a medium other than your hard drive.  If not and your hard drive failed, I'm sure you'd be very distressed. 

Haha! Yes, I have it saved to a flashdrive, regularly send the latest update to myself and save it on my work HD (plus it's then there in my Gmail) and save it to the cloud...

Wow! Such useful information Soybean, thank you so very much.
I have 5 days off work coming up and will tackle the situation then - but you have given me incredible hope!

And, I think the budget can be stretched to allow a $4 outlay...

Greatly appreciated,
Snaps
158.

Solve : quick pdf viewer?

Answer»

Hi,

is there a way to write a simple website/program/app/i dont know that will allow me to click a next BUTTON and view the next file in a folder?

i have hundreds of pdf's i have to view and opening with adobe reader, closing and reopening the next file takes forever.  Im not a coder, but maybe a simple database with path names and an aspx page with frames? i dont know. 

i apologize for my sparratic typing, it has been a long day and my brain is fried.I've been using Foxit Reader on my Windows 7 system.  Foxit is a tabbed reader, meaning it can open multiple PDF documents at the same time.  I just selected 4 PDFs in Windows Explorer, right clicked and selected Open, and all 4 documents OPENED in Foxit Reader.  I'm not aware of Adobe Reader being a tabbed PDF reader, but I'm not sure about this.  If it is, then you should be able to use the same technique.  This still does achieve what you want but it's a GOOD bit better than having to open 1 file at a time. Thanks for the quick response.  I have tried foxit reader before, and it is not bad, but not what I'm looking for.  Where I work, we create WEBSITES that pull from a microsoft access database and display the data via aspx pages.  Unfortunately our original coder is gone so there is no one left to help me.  In one of the aspx pages, there is a frame that has a "next" and "previous" button which very quickly flips between pdfs that are linked in the database.  I can recognize coding to some extent, but our files are very in depth and have many, many more features built in, making it hard to decypher what CODE controls this function.  Also, it is setup to pull from lists housed on a server in SharePoint, and I would like this to be a site that can independently run through IIS localhost on my computer.

159.

Solve : html with JS accessing PHP Help required?

Answer»

Hey folks,

Here's the squeeze... I need to run a js validate function in my html file.  Then after successful validation it should use the form action to access my php file.  I can run this fine without the JS function but when I put a function in it stops working.  I've put the script below with the php code also.  If someone could have a look and get back to me that would be ace.  Thanks in advance for taking the TIME to look at this and hope to hear from someone soon.

HTML code



Chocolate Shop on page 54









Chocolate Shop Order Form




  Real Life sized T-Rex model
  Space Station
  A Cape with matching Mask
  A Plot of land on the Moon
  A Space Shuttle
  One Launch spot from KENNEDY Space centre
  A real dead vampire
  A revolution
  Aid Food Packages
  Plutonium
  Real 3D Glasses



quantity:







PHP code






$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ". $quantity . " " . $item . ".
";
echo "Thank you for ordering from Imaginery!";
?>


Forgot to say I'm running this through wampserver.

Cheers,
B2 Quote

document.formOne.quantity.value==""
This will not reference the form variable you intend.  Give the quantity input an id tag like this:

Code: [Select]<input name ="quantity" id="quantity" type ="text" value="" />
You can then reference it like this:

Code: [Select]var quantity = document.getElementById ('quantity');
if(quantity.value=="") {
...

Remember to "return false;" to ensure the form is not submitted.  Your onsubmit needs to be TWEAKED too (see >this tutorial< and follow it more closely.)

And this is not valid javascript at all:

Code: [Select]action ="my shop process.php" method="POST";

You don't need it, because the form will submit, unless the validation returns false.

FWIW, I wouldn't do it this way, except for very very small projects.  You might want to investigate one of the techniques referred to >here<.

Don't forget your server-side validation.  Javascript validation is no protection against deliberate abuse.Cool, will give this ago and let you know the outcome.  Thanks for the post I'm doing this for college.  So thanks again it's appreciated.

Cheers,
B2Hey there,

Sorry took me a while to get back to you peeps on this.  Just want to say thanks for the help and pointers!!

I've got only got small prob now.  My validation works... but it's not coming up in an alert box.  It's taking it from the IF statement in the php file.  I was told to put an IF statement in there for IF statements sake I think lol... anyway I'm not sure why my alert in the function validation() is not coming up.  If you can see anything I've missed I'd or can't see anything wrong with it could someone let me know.  It's driving me nuts lol

source code below

Cheers,

B2

<html>
<head>
<title>Chocolate Shop on page 54</title>

<script type ="text/JavaScript">



function validate()

{
  If(document.OnlyForm.item.value=="" ||

document.OnlyForm.quantity.value=="")
{
  alert("You need to fill in a quantity number");
  return false;
}

else
  {
    parent.location="my shop process.php";
  }
 
}


</script>
</head>
<body>

<h4>Chocolate Shop Order Form</h4>

<form name="OnlyForm" action="my shop process.php"
method="post" onsubmit="validate()">

<select name = "item">
  <option> </option>
  <option>Real Life sized T-Rex model</option>
  <option>Space Station</option>
  <option>A Cape with matching Mask</option>
  <option>A Plot of land on the Moon</option>
  <option>A Space Shuttle</option>
  <option>One Launch spot from Kennedy Space
  <option>A real dead vampire</option>
  <option>A revolution</option>
  <option>Aid Food Packages</option>
  <option>Plutonium</option>
  <option>Real 3D Glasses</option>
</select>


quantity: <input name ="quantity" type ="text">

<input type ="submit" value="Submit This"

onclick="validate()">
</form>


</body>
</html>
There is a "web design" forum.

Anyway, you still don't appear to be doing what Rob suggested, as in giving the field an ID and use document.getElememtById() to get its value. Also, we can't see the PHP file you're using so can't really help. Quote from: kpac on October 15, 2011, 10:54:14 AM
There is a "web design" forum.

Anyway, you still don't appear to be doing what Rob suggested, as in giving the field an ID and use document.getElememtById() to get its value. Also, we can't see the PHP file you're using so can't really help.

Hi there kpac,

I've added in what Rob suggested and it still doesn't work (could be the way I've added it in though).  I've put the php file on at the bottom of the bold source code.  Sorry for posting in the wrong spot.  You want to move it to the other forum?  I'm not sure if I can or if I even have the privilege to do that.

Cheers,
B2

<html>
<head>
<title>Chocolate Shop on page 54</title>

<script type ="text/JavaScript">




function validate()

var quantity = document.getElementById ("quantity");

var quantity = document.getElementById ("item");


{
  if(item.value=="" || quantity.value=="")
{
  alert("You need to fill in a quantity number")
  return false;
}

else
  {
    parent.location="my shop process.php";
  }
 
}


</script>
</head>
<body>

<h4>Chocolate Shop Order Form</h4>

<form name="OnlyForm" action="my shop process.php"
method="post" onsubmit="validate()">

<select name = "item" id="item">
  <option> </option>
  <option>Real Life sized T-Rex model</option>
  <option>Space Station</option>
  <option>A Cape with matching Mask</option>
  <option>A Plot of land on the Moon</option>
  <option>A Space Shuttle</option>
  <option>One Launch spot from Kennedy Space
  <option>A real dead vampire</option>
  <option>A revolution</option>
  <option>Aid Food Packages</option>
  <option>Plutonium</option>
  <option>Real 3D Glasses</option>
</select>


quantity: <input name="quantity" id="quantity" type="text">

<input type ="submit" value="Submit This" onclick="validate()">
</form>


</body>
</html>




My Shop Process




$item = $_POST['item'];
$quantity = $_POST['quantity'];

   If($item =="" || $quantity =="")
   {
   echo("You need to fill in all the boxes");
   }
else

{

echo "You ordered ". $quantity . " " . $item . ".
";
echo "Thank you for ordering from Imaginery!";

}

?>


Okay...

This is your javascript...
Code: [Select]<script type ="text/JavaScript">

function validate()

var quantity = document.getElementById ("quantity");
var quantity = document.getElementById ("item");


{
  if(item.value=="" || quantity.value=="")
{
  alert("You need to fill in a quantity number")
  return false;
}

else
  {
    parent.location="my shop process.php";
  }
 
}

</script>

Well, you declared the variable quantity twice. If you want the variable quantity to be assigned to the element with ID "quantity", then it can't be assigned to the element with ID "item" as well. You were also missing the opening parentheses of the function.

Code: [Select]<script type ="text/JavaScript">

    function validate() {

        var quantity = document.getElementById("quantity");
        var item = document.getElementById("item");

        if(quantity.value== "" || item.value == "")
        {
            alert("You need to fill in a quantity number.")
            return false;
        }

        else
        {
            window.location="my shop process.php";
        }
         
    }
</script>

Just a suggestion, it's not the best IDEA to have filenames with blank spaces, i.e. "my shop process.php". It's better to use an underscore or hyphen to separate words like so: "my-shop-process.php" or "my_shop_process.php".

As regards the PHP file, a rule of thumb is to make sure every variable you $_GET or $_POST from another page is filtered properly. Also, try using the empty function to check if a variable has any value.

Code: [Select]<?php

$item = strip_tags($_POST['item']);
$quantity = strip_tags($_POST['quantity']);

if(empty($item) || empty($quantity)) {
    echo("You need to fill in all the boxes");
}

else {
    echo "You ordered ". $quantity . " " . $item . ".";
    echo "Thank you for ordering from Imaginery!";
}

?>
One final thing, if you're posting code please use the

Code: [Select][code]
...bbc tag. It's much easier to READ. Hey kpac,

When I leave all fields blank the alert from the JS in the html file is working... however, the alert is coming up twice then it displays the php echo.

Is there a way to just have the alert run once and then stop on the same page (the html one) so the user can fill in the details?

I also tried to add a hyperlink on the php file outside of the php code and it doesn't show up on the page at all.  Is there a way to do it like below.  I renamed my pages with - between the words 

Code: [Select]<?php

$item = strip_tags($_POST['item']);
$quantity = strip_tags($_POST['quantity']);

if(empty($item) || empty($quantity)) {
    echo("You need to fill in all the boxes"[b]A hyperlink in here somewhere???[/b]);
}

else {
    echo "You ordered ". $quantity . " " . $item . ".";
    echo "Thank you for ordering from Imaginery!";
}

?>

<a href="my-shop-validation.html">click to go back</a>Instead of

Code: [Select]<input type ="submit" value="Submit This" onclick="validate()">
use

Code: [Select]<input type="submit" value="Submit This" onclick="validate(); return false;" />
Watch out for spurious spaces in the middle of your HTML attribute declarations (type ="submit"). Quote from: Rob Pomeroy on October 18, 2011, 06:04:05 AM
Instead of

Code: [Select]<input type ="submit" value="Submit This" onclick="validate()">
use

Code: [Select]<input type="submit" value="Submit This" onclick="validate(); return false;" />
Watch out for spurious spaces in the middle of your HTML attribute declarations (type ="submit").

Hi folks,

Just to say that this would have worked but I overlooked one little thing....

Code: [Select]{
  If(document.OnlyForm.item.value=="" ||

document.OnlyForm.amount.value=="")
{
  alert("You need to fill in a quantity number");
  return false;
}
Yup and everyone else overlooked it too lolz  I had a capital "I" for if in my if statement lolz.

Rob - what you posted works as well by the way.  I tried it... after I replaced my "I" with an "i" lolz

Issue resolved !!

Cheers for the time you all took having a look at my code, much appreciated !!

B2  Excellent.  Thanks for the feedback.
160.

Solve : C++ STL Map?

Answer»

My objective to is CREATE a phone book that will receive a name, category, phone number, and address from the user. after the user enters their info, I would like their data to be saved. My code compiles, but i am having problems with some parts of my program. my find, report, and test functions do not work. The find function is suppose to search for a name in the phone book. for example, the user can enter in info for 3 people, and wants to find the info for one of the people entered by the user. the report function is to display all of the people entered into the phone book. the test function is supposed to generate 10 random people, that have a random name, category, phone number, and address, and display them on the screen.  Also, my add function does not seem to work properly either. It just does not seem to be saving any new people the user adds to the phone book. I will include all of my files. There will be 9 files altogether.

Code: [Select]//listing.h

#pragma once
#include "Person.h"
#include <vector>
using namespace std;

enum SortStatus {unsorted,sortedByName,sortedByCode};

class listing
{
public:
unsigned int size() { return vectorOfPerson.size();}
Person getPerson(int i);
void clear(){sortStatus=unsorted;vectorOfPerson.clear();}
void customerList();
void addNewListing(string n, string c, string p, string a);
private:
SortStatus sortStatus;
vector<Person> vectorOfPerson;
};

//listing.cpp


#include "listing.h"
#include <algorithm>
#include <map>


void listing::addNewListing(string n, string c, string p, string a)
{
map<string,Person> phoneData;
Person data(n,c,p,a);
phoneData[n]=data;
}

Person listing::getPerson(int i)
{
return vectorOfPerson[i];
}

//misc.h


#pragma once
#include <string>
using namespace std;

void stringToLower(string & s);
void stringToUpper(string & s);

string padLeft(string s, char fill,  unsigned int size);
string padRight(string s,char fill,  unsigned int size);

string intToString(int x);
int stringToInt(string s);

string intToDollarString(int x);

string randStrings(int numOfChars);
int randInt(int lower,int upper);

//misc.cpp


#include "misc.h"

void stringToLower(string & s)
{
for(unsigned int i=0;i<s.length();i++)
{
s[i]=tolower(s[i]);
}
}

void stringToUpper(string & s)
{
for(unsigned int i=0;i<s.length();i++)
{
s[i]=toupper(s[i]);
}
}


string padLeft(string s,char fill, unsigned int size)
{
while(s.length()<size)
{
s= fill + s;
}
return s;
}

string padRight(string s,char fill,  unsigned int size)
{
while(s.length()<size)
{
s= s + fill;
}
return s;
}

//All of the following would work fine.
//The first two give warnings. Try them out and READ the warnings.
//
//itoa(x,temp,10);
//_itoa(x,temp,10);
//_itoa_s(x,temp,255,10);
//
//The last one is "safe" because it's guaranteed to not go beyond 255 characters.
//In this case it can't happen but it would be safe even if temp was very SMALL array as long as the third parameter was also appropriately small.

string intToString(int x)
{
string result;
char temp[256];
//itoa(x,temp,10);
//_itoa(x,temp,10);
_itoa_s(x,temp,255,10);
result=temp;
return result;
}

int stringToInt(string s)
{
return atoi(s.c_str());
}





string intToDollarString(int x)
{
string result=intToString(x);
result=padLeft(result,'0',3);
result.insert(result.length()-2,".");
return result;
}


//'A' is a char literal for the ascii value of a Capital A. (It's really just a one byte integer.)
//
//Adding a random value between 0 and 25 to the ascii value of A gives you the ascii value of a LETTER between A and Z.
//
//Play with it.
//
//cout<<(char)('A'+2)<<endl;
//
//prints a C on the screen.

string randStrings(int numOfChars)
{
string result;
for(int i=0;i<numOfChars;i++)
{
result+='A'+rand()%26;
}
return result;
}

int randInt(int lower,int upper)
{
if(upper-lower<RAND_MAX)
{
return (rand()%(upper-lower))+lower;
}
else
{
int r=rand()*RAND_MAX+rand();
return (r % (upper-lower))+lower;
}
}

//phoneBook.h
#pragma
#include "listing.h"
using namespace std;

class phoneBook
{

public:

void run();
void ADD();
void HELP();
void FIND();
void REPORT();
void generateRandItems(int num);


private:
listing Listing;
};

//phoneBook.cpp

#include "phoneBook.h"
#include "misc.h"
#include <iostream>
#include <fstream>
#include <map>
using namespace std;

void phoneBook::run()
{
HELP();
string COMMAND=" ";
while((command!="QUIT")&&(command!="8"))
{
cout<<"Enter a command: ";
cin>>command;
if((command=="Add")||(command=="1"))
{
ADD();
}
else if((command=="Find")||(command=="2"))
{
FIND();
}

else if((command=="Report")||(command=="5"))
{
REPORT();
}

else if((command=="TEST")||(command=="7"))
{
generateRandItems(10);
REPORT();

}
else if((command=="QUIT")||(command=="8"))
{
cout <<"Goodbye"<<endl;

}
else if ((command=="HELP")||(command=="0"))
{
HELP();
}
else
{
cout<<"Unrecognized command."<<endl;
}
}
}

void phoneBook::HELP()
{
cout<<"Phone Book Commands"<<endl;
cout<<"----------------------"<<endl;
cout<<" 0) HELP"<<endl;
cout<<" 1) Add"<<endl;
cout<<" 2) Find"<<endl;
cout<<" 5) Report"<<endl;
cout<<" 7) Test"<<endl;
cout<<" 8) Quit"<<endl;
cout<<endl;
}

void phoneBook::ADD()
{
string n;
string c;
string p;
string a;

map<string,Person> phoneData;
cin.ignore();
cout << "Enter your name: ";
getline(cin, n);

cout<<"Enter your category: ";
getline(cin, c);

cout << "Enter your phone number: ";
getline(cin, p);

cout << "Enter your address: ";
getline(cin, a);

Person data(n,c,p,a);
phoneData[p]=data;

}

void phoneBook::FIND()
{
string n;

map<string,Person> phoneData;
cin.ignore();
cout << "Enter a name to find: ";
cin >> n;

map<string,Person>::iterator mapiter;

mapiter=phoneData.begin();

while(mapiter!=phoneData.end())
{
cout<<(*mapiter).first<<" ---  "<<(*mapiter).second<<endl;
mapiter++;
}
}



void phoneBook::REPORT()
{
cout<<Person::HeaderString()<<endl;
for(unsigned int i=0;i<Listing.size();i++)
{
cout<< Listing.getPerson(i).ToString()<<endl;
}
}

void phoneBook::generateRandItems(int num)
{
Person gi;
for(int i=0;i<num;i++)
{
gi.randomize();
//Listing.addNewListing(string n, string c, string p, string a);
}
}

//Person.h
//Person.h
#pragma once
#ifndef Person_h
#define Person_h
#include <string>
using namespace std;


enum PersonIndex{byName,byCategory};




class Person
{
public:
static PersonIndex index;
Person(){}
Person(string n,string c,string p,string a);
string ToString();
static string HeaderString();
void randomize();
bool operator >(const Person & rhs) const;
bool operator ==(const Person & rhs) const;
bool operator >=(const Person & rhs) const {return ((*this) > rhs ) || ((*this) == rhs );}
bool operator <(const Person & rhs)  const {return !((*this) >= rhs );}
bool operator <=(const Person & rhs) const {return !((*this) > rhs );}
bool operator !=(const Person & rhs) const {return !((*this) == rhs );}
friend ostream& operator << (ostream& ostr, const Person& p);

 
public:
string name,category,phone,address;
};


ostream& operator << (ostream& ostr, const Person& p);



#endif

//Person.cpp
//Person.cpp
#include "Person.h"
#include "misc.h"
#include <stdlib.h>
#include <assert.h>
#include <iostream>
#include <iomanip>
using namespace std;


PersonIndex Person::index = byName;



Person::Person(string n, string c, string p, string a)
{
name = n;
category = c;
phone = p;
address = a;
}


bool Person::operator >(const Person & rhs) const
{
if(Person::index == byName)
{
return name>rhs.name;
}
else
{
assert(index == byCategory);
return category>rhs.category;
}
}




// Changed so that BST::find is more practical

bool Person::operator ==(const Person & rhs) const
{
return (name==rhs.name);
}



ostream& operator << (ostream& ostr, const Person& p)
{
// a little example of C++ formated output
ostr<<setiosflags(ios::left);
ostr<<setw(10);
ostr << p.name;
ostr<<setw(22);
ostr << p.category;
ostr<<setw(12);
ostr << p.phone;
ostr<<setw(30);
ostr << p.address;

return ostr;
}

string Person::ToString()
{
string result="";
result+=(name,' ',15);
result+=(category, ' ' , 15);
result+=(phone, ' ' , 15);
result+=(address, ' ' , 15);

return result;
}


string Person::HeaderString()
{
char fill='-';
string result="";
result+=padRight("Name",fill,15);
result+=padLeft("Category",fill,10);
result+=padLeft("Phone Number",fill,8);
result+=padLeft("Address",fill,8);

return result;
}

void Person::randomize()
{
name=randStrings(5);
category=randStrings(15);
phone=randInt(7,10);
address=randStrings(255);
}

//main.cpp
#include <iostream>
#include <string>
#include "phoneBook.h"

int main()
{
phoneBook myphoneBook;
myphoneBook.run();
return 0;
}

161.

Solve : copying something to my website - help pls.?

Answer»

I want to copy the search feature found here.....
Code: [Select]HTTP://www.unlockbase.com/widget/htc.phpto my website but with a different logo.
I have managed to change the logo and copy it to my site, but it doesnt work on my site.
Here is mine....
Code: [Select]http://www.phonezonescotland.co.uk/htctool.htmHow do I get it to actually do its job from my site?

Thanks
TDI assume that there are probably scripts on this site that you do not have access to.Hi,
First of all, Thank You for taking the time to reply. MUCH appreciated. :-)

So basically, are you saying it cant be done?
If its not possible to recreate that serach field on my webpage, then I have no qualms with providing a link to the other site, but I need my 'customers' to return back to my page after they have used the feature.
Is there any workable solution for this?
Sorry for all the noob questions.

TIA

TD.
You could embed that in your site USING an iframe like so:

Code: [Select]<iframe src="http://www.unlockbase.com/widget/htc.php"
width="40%" height="180"
align="left">
</iframe>

More info on IFRAMES here: http://www.cs.tut.fi/~jkorpela/html/iframe.htmlAlternatively on your website, you'd need a script (PHP perhaps) to accept the input from your user, transmit that query to the REMOTE website (using cURL), parse the result and display it on your own website.

Unless you own both websites, this would be considered poor etiquette. Quote

Unless you own both websites, this would be considered poor etiquette.
And illegal, in some cases - depending on how it was done it could be considered plagerism.
162.

Solve : Engine: Word input - Excel processing - pdf output?

Answer»

Hi

For my website I need someone to build an "engine" for me.
The engine should:
1) take in a word document (input - uploaded by the user),
2) run a macro on the contents,
3) send the contents to an MS Excel spreadsheet,
4) run a macro on the spreadsheet, and finally
5) "print" specific cells in the spreadsheet as a pdf (output - downloaded by the user)

Can anyone point me to somewhere relevant?

Kind regards, Kristobal, DenmarkI'm wondering why you want to do this.  It SEEMS like an odd idea since Word normally contains text content and Execl normally contains numeric data.  Can you give an example of such a FILE conversion and why someone might request such a conversion?   

The content of Word files could, of course, widely vary from one user to another.  How do you envision this working at the initial request phase?  Would you specify that the Word document must have a certain layout? A person can USE different types of PDF converter software to convert the file from Portable Document Format into Excel sheet. These tools help you to convert the documents from one format to another. An advanced tool is the one that RETAINS the original formatting during the process of conversion.
pdf to excel
A person can use different types of PDF converter software to convert the file from Portable Document Format into Excel sheet. These tools help you to convert the documents from one format to another. An advanced tool is the one that retains the original formatting during the process of conversion.
pdf to excel

163.

Solve : Nonmember functions vs. member functions.?

Answer»

I am having trouble understanding why a prefix is USED and not used in these coding. The first code will be for a non member function, and the next will be for the member function. There is a prefix that is used in the Member Function code, but not in the NonMember Function code. The prefix that is used in the Member Function code is "Bank_Acct::" This is found in the header of the operator<< function. But this header of the operator<< function in the NonMember Function is not used. I'm trying to figure out why, but I can't seem to figure it out. Also, in the NonMember Function, I am having trouble figuring out the purpose of the Print function.

NonMember Function
Code: [Select]#include <iostream>
#include <string>

using namespace std;

const int SIZE = 10;

class Bank_Acct
{
public:
Bank_Acct( );  //default constructor
Bank_Acct(double new_balance, string Cname); //explicit value
                                             //constructor
void Print(ostream & out); //accessor function

private:
double balance;
string name;
};

Bank_Acct::Bank_Acct()
{
balance = 0;
name = "NONAME";
}

Bank_Acct::Bank_Acct(double amount, string Cname)
{
balance = amount;
name = Cname;

}

void Bank_Acct::Print(ostream & output)
{
output<<endl<<"Object "<<name;
output<<endl<<"The new balance is "<<balance<<endl;
}





ostream & operator<<(ostream & output, Bank_Acct & Org)
{
Org.Print(output);
return output;
}




int main()
{
Bank_Acct my_Acct;

Bank_Acct DrB(2000.87, "Dr. Bullard");

//the following statement contains chaining
cout<<DrB<<endl<<my_Acct<<endl;

return 0;
}

Member Function
Code: [Select]#include <iostream>
#include <string>

using namespace std;

const int SIZE = 10;

class Bank_Acct
{
public:
Bank_Acct( );  //default constructor
Bank_Acct(double new_balance, string Cname); //explicit value    
                                             //constructor
void Print( ); //accessor function
Bank_Acct & operator+(double amount); //mutator function

private:
double balance;
string name;
};



Bank_Acct::Bank_Acct()
{
balance = 0;
name = "NoName";
}

Bank_Acct::Bank_Acct(double amount, string Cname)
{
balance = amount;
name = Cname;

}

void Bank_Acct::Print()
{
cout<<endl<<"Object "<<name;
cout<<endl<<"The new balance is "<<balance<<endl;
}

Bank_Acct & Bank_Acct::operator+(double amount)
{
balance += amount;
return *this;
}

int main()
{
Bank_Acct my_Acct;

cout.setf(ios::showpoint);
cout.setf(ios::fixed);
cout.precision(2);

cout<<"Original balance of my_Acct"<<endl;
my_Acct.Print( );

//the following statement contains chaining
my_Acct + 18.75 + 14.35 + 10054.96;

cout<<"The balance of my_Acct after addition to balance 3 times"<<endl;
my_Acct.Print();

return 0;
}


Sorry I can't help you. What compiler are you using?
Also, your use of WHITE space is confusing.it's nothing along the lines of compiler issues. its just a question. the question is howcome in the member function, there is the "Bank_Acct::" prefixed in front of the header of the operator<< function, but there is none is non-member function? Quote from: helpme101 on November 18, 2011, 09:27:22 PM

it's nothing along the lines of compiler issues. its just a question. the question is howcome in the member function, there is the "Bank_Acct::" prefixed in front of the header of the operator<< function, but there is none is non-member function?

Probably because the member function version doesn't use << on the Bank_Acct type and thus doesn't need one defined. it uses print() instead.ok, yea that makes SENSE. thanks. do u think you can help me out with my other post. not sure if you took a look at it. it's titled C++ STL map.
164.

Solve : JScript Popup Boxes?

Answer»

I have searched and asked this question at multiple sites and can't seem to FIND an answer:

How do I make a JScript file that makes something LIKE a VBScript msgbox? I see that this .js file makes popup boxes. . .so why can't anyone answer my question?Not sure exactly what you mean.

Code: [Select]&LT;script TYPE="text/javascript">
function display_alert(MESSAGE) {
   alert(message);
}
</script>

165.

Solve : Simple example in Python?

Answer»

Hi!
Can someone help me with this example? I KNOW it's quite easy, but I can't find right result. (i'm BEGINNER)
I'll be glad.

I need a program which'll write this:

for N=3

*
**
***
**
*

for n=2

*
**
*

I have found result for the first half:
def pyramid(n):
    result=""
    for X in range(n):
        result=result + "*"
        print(result)

I don't know how to continue, can somebody help?:-)try this:

def pyramid(n):
        for i in range(n):
                row = '*'*(i+1)
                print row
        row = 0
        while i >= 0:
                row = '*'*(i)
                print row
                i -= 1

166.

Solve : [Java]HashTable and HashMap?

Answer»

What are the differences between these two?

From what I gathered from the documentation on both of these ADTs, HashTables map values to keys and HashMaps are a hash implementation of Maps, which also map values to keys.

What are the primary differences in implementation? When would you use each one and why?

I did a bit of Googling on the topic and the only thing I managed to find was that HashTables are synchronized whereas HashMaps are not. I'm not entirely sure what this means.

This question is specifically about the Java implementations of these structures, but I'm open to insight from the perspective of any other language if the basic ideas are the same.Any discussion of Hash on this forum results in endless arguments. Here r is some very relevant background.
Quote

All About Hash
From Wikipedia, the free encyclopedia

Directed by    Edward Cahn
Produced by    Jack Chertok
Distributed by    Metro-Goldwyn-Mayer
Release date(s)    March 20, 1940
Running time    10 minutes
Country    United States
Language    English

All About Hash is a 1940 Our Gang short comedy film directed by Edward Cahn. It was the 189th Our Gang short (190th episode)

Plot
It seems that Mickey is upset over the fact that his parents spend every Monday night arguing. The reason: Mickey's mom invariably serves hash made from the Sunday-dinner leftovers, and Mickey's dad hates hash. To teach the two adults a lesson, the Our Gang kids stage a skit on a local radio program, ending with a HEARTFELT plea by Mickey to stop the quarrelling.
http://en.wikipedia.org/wiki/All_About_Hash

But this is more like what you want
http://en.wikipedia.org/wiki/Hash_table
There are references to Java.
http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html
http://blog.griddynamics.com/2011/03/ultimate-sets-and-maps-for-java-part-i.html
http://www.lampos.net/sort-hashmap

Well I've read the Javadocs on both tables and maps and was just hoping I COULD get a summary of advantages between the two.

But I guess I'll just have to read some more or dig up these endless arguments you speak of Have fun. They do not make a clear distention between tables and maps. The most important feature is the hash generator, or hash function.
A table or map, in a simple form, can be just an array of pointers. With the large amount of memory how available in modern computers, size of the array is less of any issue.
The point is that optimization the table of map is less important than having  a good OVERALL scheme. Especially the Hash maker.

For more tips on Java and hash, go to the website
http://stackoverflow.com/
and find general discussion and specific issues with Java hash.

Hashtable is synchronized on the table, HashMap isn't; you would have to add it yourself using a wrapper class. (or you could probably use the java.util.concurrent.ConcurrentHashMap to get a similar effect). Also, the iterator of the HashMap used in for loops is fail-safe, while the enumerator for the Hastable is not. if you change hashMap while iterating, you'll know; that is, that item will be iterated. if you iterate on a hashTable and add values while iterating, you won't see the new values unless you restart the iterator. Lastly, HashMap permits null values, while Hashtable doesn't.

The actual objects being represented are exactly the same, they just have different names. Hashtable is one of the first classes ADDED to java's collections. Also, it was added  before the introduction of generics and as such HashMap should be heavily favoured. (Hashtable extends from Dictionary, which itself is deprecated, also).

The "distinction" is hard to find, because there quite literally is no distinction, at least data-structure wise. They represent the exact same data structure; hashMap just takes advantage of new language features, such as generics, to support strong typing of it's key's and values, whereas hashtable does not; it (hashMap) also better supports the use of strongly-typed iterators by virtue of generics iterators (such as those used with a FOREACH loop of the style for(value:collection){statements...}).



167.

Solve : Visual Basic problem?

Answer»

Hi, I'm using visual BASIC with .net framework 4, and I made a program that gets the strings from a table in a database and shows them in a listbox, the listbox shows the elements correctly, but when i try to set a variable with the index string (Label1.Text = listbox1.selecteditem() ) I get System.Data.DataRow or something like that, i want to get the string. Can someone help me?
Thank you.listbox1.selecteditem().ToString()

OR get the actual field you want from the DataRow.Label1.Text = ListBox1.SelectedItem().ToString() not working
I get the text "System.Data.DataRowView" instead of the actual string in the DB QUOTE from: alecsillidan on November 11, 2011, 04:13:46 PM

Label1.Text = ListBox1.SelectedItem().ToString() not working
I get the text "System.Data.DataRowView" instead of the actual string in the DB

You'll need to get the field from the DataRow, then.

Code: [SELECT]ListBox1.SelectedItem("fieldname").ToString()It works fine, thank you for helping me.
Solved.
168.

Solve : Computer Logics and Digital Design: Operational Pair Grading System?

Answer»

Objectives

*Use of Boolean Algebra and/or Karnaugh Maps for Simplifications
*Multiple smaller system that builds a large system
*5 or more inputs that allows for mathematical process for simplifications
*Decoder
*Adder/Subtracter
*Storage Medium (Flip-Flops)
*Sequential Circuits (Timing Counter)
*Use of the AND Gate to control smaller system enable/disable

Description
Lippelli Warehouses requires an electrical system for measuring their operational workers whilst they are on the job.
The system is to monitor some specific attributes of each worker and directly use that information to grade the worker in relation to another worker.

Requirements
The system must accept from the user: the quantity produced by the worker, class of work of the worker, the mode of grading scheme to be used and display a Quality Level grade for that worker. It should perform this operation every six (6) seconds and needs to store the information for the last worker in order to get its results.

Inputs from each worker
For each worker the system requires three (3) forms of inputs which becomes that worker's attributes. They include: -

1.Product Quantity (Decimal Integer represented in Binary)
This numeric value represents the amount of units of the products that the worker has produced at the time system INPUT. It is measured in pounds (lbs) and can range from 0 to 25 inclusive.

2.Class of Work (Decimal Integer represented in Binary)
This numeric value represents the class of work that the worker produces. 1 are Technical workers, 2 are Digital workers, 3 are Mechanical workers, 4 are Middleware workers and 5 are Electrical workers.

3.Quality of Work (Letter Value represented in Binary of the previous worker)
This symbol represents the quality of work that the current worker is known for. The values are: A (Best quality), B (Par quality) and C (Poor quality).

OUTPUTS of the system
The system will display an output that will represent the current quality level of a worker based on their attributes as well as the attributes of their peers.
The three different values of the output will represent: -

1.Best Quality (A) – which means that the workers are producing the highest quality products

2.Par Quality (B) – which means that the workers are producing at the global standard level

3.Poor Quality (C) - which means that the workers are producing below Par Quality

Timing Process
The system is to ensure that it checks the current worker's attributes against the last worker's attributes every 6 seconds in order to produce the quality level of the current worker. There must be no other way of producing these results based on the input apart from the six (6) seconds to ensure that the process is periodical and efficient.
At every six second interval the system is to perform one of the three grading schemes listed below based on the inputs and the criteria available to it.

Modes of Grading Schemes
There are three (3) major kinds of grading schemes used by the required system on the inputs/attributes of the workers to make the correct display of Best (A), Par (B) or Poor (C) Quality for the current worker.
In order for the system to grade the current worker it also requires the attributes for the last worker to be processed by the system (i.e. the system must have some way of storing the current worker's attributes to be compared against the next worker).
The first worker to be processed by the system always gets a grade of Par Quality (B) because there is no worker to compare them to.
The following explains how the three (3) different modes of grading schemes work:

1.Class Grading Scheme. This grading scheme focuses of the different classes of the current and previous workers. It uses the following table to determine the grade of the current worker:

Current Worker   Previous Worker                                             Grade

Technical      Technical, Digital, Mechanical, Middleware                         B
Technical      Electrical                     A
Digital      Technical, Digital, Mechanical, Middleware, Electrical                                   A
Mechanical         Technical                                               C
Mechanical   Digital                                                                                      B
Mechanical   Mechanical, Middlewarem Electrical            A
Middleware   Mechanical, Electrical                  A
Middleware   Technical, Middleware               B
Middleware   Digital                     C
Electrical      Electrical, Digital, Mechanical, Middleware                         B
Electrical      Technical                                  A

2.Quality Grading Scheme. This grading scheme focuses on the quality given to the last/previous worker in relation to the current worker. If the previous worker has a Quality Level of Best (A) then the current worker gets a Quality Level of Best (A) if their quantity is greater than 10 lbs. If the previous worker has a Quality Level of Par (B) then the current worker gets a Quality Level of Best (A) if their quantity falls within the range of 5 to 20 inclusive. For all other cases the current worker gets a Quality Level of Poor (C).

3.Quantity Grading Scheme. This grading scheme focuses directly on the amount of production of the current and previous workers. The current worker gets a Quality Level of Best (A) if they produce more lbs than the previous worker; Par (B) if they produce the same amount of lbs as the previous worker and Poor (C) if they produce an amount below the previous worker's.

Deliverables
*Breakdown of the problem(showing how the problem was modularized in to smaller sections)
*SOLUTION of each smaller section in relation to: -
*Truth Table
*Simplification using Boolean Algebra or Karnaugh Maps; or both
*Circuit Design based on simplification
*Solution of the entire problem in the form of working Electronics Workbench file(s)
I really am desparate for help with this project.How many units do hyou need? What is the budget? Deadline?units don't matter but the simplier the better and the deadline is tuesdayDo you have a recommended download for an Electronics Workbench  program? I have not done that stuf in years. Is this a school project?

EDIT: Looking that over, it is too hard to do with traditional logic gates in a short time fram. For me, anyway. Too much abstraction.

You could write a simulation in your favorite computer language. Vatious versions of Microsft Basic can do Boolean operations very well. But making a diagram of conventional small-scale logic gates is a strain on the brain. Sorry, That would tke me over a week to diagram.

The best hyou can do is to divide the whoe thing up into three or four abstarct modules. The refine easch module. And repeat untill it all makes sense.yes i do have one and yes it is a school project.....thnx for TRYING thoughHere are some files i managed to create from wat i understand of my project. I have until 6:45 the latest to had this project...i need urgent help please.....

[regaining space - attachment DELETED by admin]

169.

Solve : bat file to search cmd window?

Answer»

Hello,
I am writing a BATCH file which opens a python file which returns certain text cues. I would LIKE to have my batch file then (depending on the text returned) continue OPERATING or exit. How do I PROGRAM the batch file to search the cmd window for these text cues?You would basically need to write the output of the python program to a text file and then have the batch file PARSE the text file.Or use the FOR batch command to run the python script and capture the output line by line. Your use of "text cues" is not very informative. What exactly are you looking for?

170.

Solve : GNU make dual-core Compilation Optimization?

Answer»

This may be a stupid question (and hopefully it's in the right section, since I associate make and compiling primarily with PROGRAMMING), but does anyone know what would be the best WAY to optimize the make process using "make -j #"?
Right now, I'm using "make -j 2 INSTALL clean" to compile ports on FreeBSD 9.0 RC2 with an AMD Athlon II X2 250  (3.0 GHz) processor, if that helps...

171.

Solve : VB hide toolbar and move page accordingly?

Answer»

Hey Guys,

I have a VB app that has a SECONDARY toolbar with a few buttons, i can easily hide the toolbar using .VISIBLE = false but my TAB panel stays in the same location.

i tried using this on a CLICK event on a certain tab and resizing tab panel and MOVING but it does it for every click ie

if tabpage.selected = true then
tabpanel.height += 30
tabpanel.location.x -= 30

else
tabpanel.height -= 30
tabpanel.location.x += 30

end if

so that works if i click on the tab and click off, but if i click on another tab first it obviously decreases the size.

im thinking i should use something to catch an unselect event of the specific tab to reduce the size and that way it only does it when supposed to, any ideas?

172.

Solve : CREATE A REGISTRY KEY WITH A BATCH FILE??

Answer»

Hey, I was wondering how, or even if, you can make a subkey in the HKCR registry section with a batch FILE.
I've tested a LOT of codes and have failed at them all, so I came here.

This does not work:
echo off
REG ADD "HKCR\batfile\shell\New Key" /F
exit


If I was trying to create the New Key in the CODE above, it wouldn't work.
I'm using Windows Xp OS with 20GB hard drive on PORT "E:\" with 3GB used up.
I don't want to create a seperate .reg file either.
Thanks for your help.                                                                  -NathansswellEDIT: The code above did work, I just needed to logoff to make it work. My new problem is that I need to find out how to edit the (Default) Value in the subkey with a batfile. Please help...
REG ADD "HKCR\batfile\shell\New Key" /F /ve /t reg_sz /d NewValue

173.

Solve : bat file auto capture and webcam?

Answer»

hi all, first of all im just a beginner programmer,

and sorry for my broken english and fail grammar,

as i state at my title, i wonder if there any command or line for bat format for,

1] auto capture (screenshots) and save it as jpeg format,

and

2] autp capture (our webcam) and save it as jpeg format?

thanks in advance, really hope for ur reply. =)Maybe I can help.
Use a PROGRAM already written.
It saves screen shots as a movie.
You can adjust the frame rate.
You can convert file to other formats later.
But it is not a batch program.
http://www.debugmode.com/wink/

Must it be a batch program? Quote from: Geek-9pm on February 17, 2011, 03:55:37 PM

Maybe I can help.
Use a program already written.
It saves screen shots as a movie.
You can adjust the frame rate.
You can convert file to other formats later.
But it is not a batch program.
http://www.debugmode.com/wink/

Must it be a batch program?

thanks for ur reply, but im looking for batch program, or any line, coz im working on my NEW project. THATS why i need that batch program. =) any idea? =)OK
Yes, there are programs that work in DOS.
Some of this are automatic.
They make full-screen capture in DOS.
http://www.screencapture.com/answers.htm Quote from: Geek-9pm on February 17, 2011, 09:51:43 PM
OK
Yes, there are programs that work in DOS.
Some of this are automatic.
They make full-screen capture in DOS.
http://www.screencapture.com/answers.htm

thanks, but im looking for batch program, so any other answer? =)You could write your own CLI program to capture the screen and web cam. I have written a short tutorial on how to capture screen with Delphi codes. Unfortunately atm I have problem with my internet connection. I can not reach the page. Maybe later, if you are interested. Quote from: Luthfi on February 21, 2011, 02:51:27 AM
You could write your own CLI program to capture the screen and web cam. I have written a short tutorial on how to capture screen with Delphi codes. Unfortunately atm I have problem with my internet connection. I can not reach the page. Maybe later, if you are interested.

yeah, i am very interested, cant wait it! thanks man! i'll wait. =)Okay, here is the url to the tutorial: http://forum.codecall.net/pascal-delphi-tutorials/34552-how-capture-screen-delphi-code.htmlthx, but is there any other answer? maybe in c#? or in sh? or in pl? or in bat? =)If you're looking for a really simple command line app to capture a single snapshot from a webcam in Windows, you might be interested in the following post on my blog:

http://batchloaf.wordpress.com/2011/04/06/snapz-a-command-line-cam-image-grabber/

I couldn't find an app to snap webcam images in a batch file, so I wrote this myself. It's very basic - just run it and it snaps a 640x480 image from the default camera device and saves it in the current directory. It should be perfect for including in a batch file. It's free to download and the full source code is included in my blog post. If you really need to capture an image at a different resolution, the program would need to be recompiled to do that (it's compiled using MinGW - a free gcc compiler for Windows).

Hope that helps you with your problem!
Quote from: batchloaf on April 07, 2011, 03:49:50 PM
If you're looking for a really simple command line app to capture a single snapshot from a webcam in Windows, you might be interested in the following post on my blog:

http://batchloaf.wordpress.com/2011/04/06/snapz-a-command-line-cam-image-grabber/

I couldn't find an app to snap webcam images in a batch file, so I wrote this myself. It's very basic - just run it and it snaps a 640x480 image from the default camera device and saves it in the current directory. It should be perfect for including in a batch file. It's free to download and the full source code is included in my blog post. If you really need to capture an image at a different resolution, the program would need to be recompiled to do that (it's compiled using MinGW - a free gcc compiler for Windows).

Hope that helps you with your problem!

NICE coding man, this is what im looking for dude!

btw, need ur little help again, do u mind if i add u on msn or ym? leave ur email or add me at [email protected] or [email protected]

thanks batchloaf!Since a few people found their way from here to the snapz command line image grabber program on my blog, I'm POSTING a link here to the updated DirectShow version that I've just written, CommandCam. It's free and open source and it can be downloaded (either source or binary) from my blog or from github.Updated link for CommandCam command line image grabber: http://batchloaf.wordpress.com/commandcam/Am I the only1 curious about the program op is making?
174.

Solve : Basic C++ Quiz Help.?

Answer»

Hey guys, I was wondering, would it be an OK beginner project to try and make a little 3 question quiz out of C++. I'm moving up from Batch/crap-tons of markup and web scripting languages (HTML, JAVASCRIPT, PHP, VBScript, CSS, mySQL) and I was just wondering if that would be a good first program? Other than hello world of course :3.quiz would be an ok way of getting better with if & else statements but considering that you have already had experience with other languages im betting you already have that mastered, the only thing you'll learn by doing a quiz is more syntax.

If you WANT to learn more about c++ work with functions, pointers and classes.

a fun project could be a sentence encryptor, try the following and LET me know if you get stuck:

create a program to encrypt a sentence including spaces. example

enter message:
hello world

enter number key:
1

your encrypted message:
ifmmp!xpsme

so this would get a string and change value based on a variable, you can take it further by decrypting.

this is a basic encryption but doing this project will GIVE you a pretty good basis for c++

175.

Solve : which is the best programming software to write a simple copy and paste program?

Answer»

Hi all,

I have been collecting CNN news for months.
What I always do is that:
I go to CNN web site, press the WORLD button and copy the news below the "Top World Stories".
Those news are pasted and saved in a EXCEL file.
But sometimes, I got some other work to do and I did not have time to copy the news and PASTE in the EXCEL file.
I am thinking to write a simple PROGRAM that can go to the CNN web site and copy those news for me everytime when launched the program, but I have no idea which programming software is the best.
Microsoft VB.net , Eclipse or NetBeans?
Or could you suggest another tool for me please?

Thank you.

KittyI would use a combination of the cURL libraries and regular expression parsing.  Specifically, I'd use a PHP script to retrieve the CNN page (using cURL) and then parse it (using regular expression pattern MATCHING).  PHP can output into CSV, so that would do for Excel, unless you needed fancy formatting.  If you want to copy images and such like, you're going to find this to be a tough job in almost any programming language.

I WONDER if an RSS feed from CNN might SUIT your needs better?

176.

Solve : Writing an XML code beautifier?

Answer»

Here's the IDEA....

Given an input string containing XML data, without any indentation, output a string of XML with proper indentation.

Example:

Input string:
Code: [Select]<collection><book id="1"><title>Charlie and the Chocolate Factory</title></book><book id="2"><title>C, How to Program</title</book></collection>
Output string:
Code: [Select]<collection>
    <book id="1">
        <title>Charlie and the Chocolate Factory</title>
    </book>
    <book id="2">
        <title>C, How to Program</title
    </book>
</collection>

I've never tried to tackle ANYTHING like this before, so any help is appreciated. I just need a starting point. Think about how you WOULD do it by hand and mimic that process in your code. Start with an indent of zero and add to it every time you encounter an opening tag and subtract every time you encounter a closing one.

Ya, that's what I have kind of started to do. Thanks for the reply  I'm not that good with xml myself but i can get by using an xml editor, try using Liquid XML Editor as it has syntax highlighting, auto code COMPLETION, xml validation ETC etc

177.

Solve : .vbs script help?

Answer»

So I need a script to disable the shutdown button on my laptop. Well I know it's possible to do in .vbs but I GOT no idea how to start. Just some start help would be MUCH obliged. Why don't you just disable it in Power Options? Why do you want to do this? Are you SURE it's your laptop you want to do this on?

How would I be uncertain of it being my laptop or not?
Anyways I tried to check in power options before posting.
Just to be sure that we are on the same page the button I am talking about is the physical one on the exterior of the laptop.
My problem being I don't know what input the button gives or how to block it.In Windows there is an option in Power Options - "What to do when power button is pressed" -

Do Nothing
Sleep
Hibernate
Shut Down


Quote

Just to be sure that we are on the same page the button I am talking about is the physical one on the exterior of the laptop.

I know what page I am on.

In Windows 7/Vista there is an option in Control Panel Power Options - "Choose what the power BUTTONS do" - in XP it's in the Advanced tab - "When I press the power button:"
the powercfg utility MIGHT provide the functionality you seek.Okay Sry Salmon I completely misunderstood
It's working now thank you.
178.

Solve : C++ if - else?

Answer»

I am trying to make this program work and it is not printing - COINS PER DOLLAR CALCULATION will not print. Help, Please.

using std::COUT;
using std::cin;
using namespace std;

;int money;
#define cents_per_dollar   100
#define pennies_per_dollar 100
#define nickels_per_dollar  20
#define dimes_per_dollar    10
#define quarters_per_dollar  4


;int main()//program converts dollars to coins;
{
  int money;   
  const int PENNY = 1;
  const int NICKEL = 5;
  const int DIME = 10;
  const int QUARTER = 25;
  const int DOLLAR = 100;
  int coin;
  int total;
 
  std::cout << " Please enter number: ";
  std::cin >> money
  ; // display number
 
    cout << "choose PENNY, NICKEL, DIME, QUARTER, enter\n"; //display message
   cin >> coin ;
   
/* Coins per Dollar Calculations */
{      
     if (coin == PENNY);
      cout << ("money * 100= PENNY/DOLLAR");  }
       you have SYNTAX errors everywhere, fix them up

also your program seems fairly simple so just use full head

#include
using namespace std;

instead of

using std::cout;
using std::cin;
using namespace std;
Dont really get the program but here's a WORKING version of the CODE Code: [Select]#include <iostream>
using namespace std;

int money;
#define cents_per_dollar   100
#define pennies_per_dollar 100
#define nickels_per_dollar  20
#define dimes_per_dollar    10
#define quarters_per_dollar  4


int main()//program converts dollars to coins;
{
  int money;   
  const int PENNY = 1;
  const int NICKEL = 5;
  const int DIME = 10;
  const int QUARTER = 25;
  const int DOLLAR = 100;
  int coin;
  int total;
 
  cout << " Please enter number: ";
  cin >> money;
   // display number
 
    cout << "choose PENNY, NICKEL, DIME, QUARTER, enter\n"; //display message
   cin >> coin;
   
/* Coins per Dollar Calculations */   
     if (coin == PENNY);
      cout << money * 100 << "= PENNY/DOLLAR";
}

179.

Solve : Need proper syntax for getevn (or set/environ)?

Answer»

trying to get this to print the environment variable "PATH"
 
here is what is in the freebasic compiler
 
#include "crt/stdlib.bi"
Sub main()
 Print getenv("PATH")
End Sub
main()
 
i have also tried to change getenv to environ (i found a few posts for this. fbwiki).
 
tried this as well:
print *getenv("PATH")
 
what am i doing wrong?Both these work fine for me (FreeBASIC version 0.22.0 for win32)

Code: [Select]#include "crt/stdlib.bi"
Sub main()
 Print environ("PATH")
End Sub
main()

Code: [Select]#include "crt/stdlib.bi"
Print *getenv("PATH")
 



maybe something is not configure quite right then as i did the following:
#include "crt/stdlib.bi"
Sub main()
 Print environ("PATH")
End Sub
main()
 
when i run the program, nothing but a blank lf/cf is returned..
 
i checked the freebasic folder and the crt is found under ..\FreeBASIC\inc\crt and i verified that the stdlib.bi exists there and in the ..\inc\crt\win32 folder as well.
 
is it possible that it is not including the .bi file? is there a way to test that it is loading properly?
 
thanks
 
Quote from: Salmon Trout on December 14, 2011, 11:11:53 AM

I just changed getenv to environ and it worked fine.
1. Does the PATH environment string actually have a value? Sometimes people fool around and nuke it.

2. What does this code do?

Code: [Select]#include "crt/stdlib.bi"
Sub main()
 Print "Homedrive: " &AMP; environ("HOMEDRIVE")
 Print "OS:        " & environ("OS")
 Print "PROMPT:    " & environ("PROMPT")
End Sub
main()

You should see something like this

Code: [Select]Homedrive: C:
OS:        Windows_NT
PROMPT:    $p$g
3. If the lib was not found you would get an ERROR message from the compiler and no exe would be produced. Try changing stlib to stdlibb and see what happens!

4. Are you actually looking at the compiler output?



No, i was using FEdit and had inadvertently chosen Windows GUI instead of Windows Console,
 
all is good now.
 
So SalmonTrout, i am now gettig the correct path. many thanks for your astutness 
 
Quote from: Salmon Trout on December 14, 2011, 12:08:14 PM
4. Are you actually looking at the compiler output?
so after some more tweaking, i have things sort of being ported over to the new lang.. again im primarily setting and displaying environment variables.
 
ONE thing that i have not figured out is this:
 
#include "crt/stdlib.bi"
Dim return1 As String, testdir As String
return1 = Environ("return")
testdir = Environ("%cd%")
Print "return is "; return1
Print "testdir is "; testdir
 
return1 is valid and prints out the value
testdir prints out the statement and no value, so somehow the percent signs seem to give the environ command an issue
 
how can i pass the %cd% to the environ function, i have tried quoting, single quoting, with and without %, nothing has worked so far.
 
any thoughts
 Not sure if you need to use th curdir or exepath commands. Not exactly sure which path you are looking for.curdir is the winner....
 
and the answer is... so some more issues with this not working as expected, so i need to learn more...
 
here is what i currently have in the FEDIT console window:
 
#include "crt/stdlib.bi"
Dim return1 As String, currdir As String, newpath As String
return1 = Environ("return")                                 'display the current value of return
currdir = curdir                                                 'set the current directory to currdir
Print "return is "; return1                                    'print the current value of return1 (not slot)
Print "current dir is "; currdir                               'print the current working directory
newpath="return=" + currdir                               'make new path string for setenviron
SetEnviron newpath                                          'setenviron to newpath
Print Environ("return")                                       'print the new value of "return"
 
during runtime, this does exactly what it is supposed to do, set the envvar "return" to the curdir. and it prints out exactly what it is supposed to say, which is the folder where im compiling the program at. all is good to this point.
 
however once it exits the program, the value for "return" is nil or not set.
 
thoughts?The Environment Block of a process is a copy of the environment block of the parent process, or a new, default Environment Block (depending how you spawn the child process).

In this case, the Environment Block your FreeBasic Application receives is a copy of the Environment Block as it exists in the spawning CMD console.

However, because of this, changes will not persist back to the parent processes environment.

With Older MS-DOS programs this wasn't an issue since... it didn't exist. The concept of multiple processes was a foreign one, and there really was only one environment block for each command interpreter that was globally accessible to any applications run within.


Instead you have to write a value to the registry. (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment).

This does that (can be confirmed be via RegEdit) but changes don't take effect until a reboot... (Even though I Broadcast the required WM_SETTINGSCHANGE. Oh well.

Code: [Select]#include once "windows.bi"







'Windows Master Registry Block is stored in the registry,

'at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" as REG_SZ's



Declare Function SetEnvironment(VarName As String, VarValue As String) As Boolean



Const WM_SETTINGSCHANGE = &H1A

Function SetEnvironment(VarName As String,VarValue As String) As Boolean

    Dim UseRoot as HKEY,usekey As String

    Dim hk as HKEY

    Dim returnvalue As Boolean

    returnvalue=False

    UseRoot=HKEY_LOCAL_MACHINE

    UseKey= "SYSTEM\CurrentControlSet\Control\Session Manager\Environment\"

    'Open the key...

    If RegOpenKeyEx(UseRoot,UseKey,0,KEY_ALL_ACCESS,hk) = ERROR_SUCCESS Then

       'hk is a pointer to the key, use it with RegSetValueEx()...

        SetLastError(0)

        if RegSetValueEx(hk,StrPtr(VarName),0,REG_SZ,StrPtr(VarValue),Len(VarValue)+1)<>ERROR_SUCCESS Then

            Print "RegSetValueEx Failed." + "GetLastError returns " + Str(GetLastError())

        End If



        RegCloseKey(hk)

    Else

       

        Print "RegOpenKeyEx Failed. GetLastError() returns " + Str(GetLastError())

    End If

    PostMessage HWND_BROADCAST,WM_SETTINGSCHANGE,0,StrPtr("Environment")

    return returnvalue

End Function





SetEnvironment("Testing","howdy")

I keep wondering why the OP doesn't just use a cmd script ("batch file") to do the things that he wants, and he never answers. This makes me wonder if he is trying to do some kind of script-kiddie thing. Since he steadfastly refuses to tell us, the help he is going to get will not be focused.
i dont' know how much clearer than to post my code to make you happy    (i did post the routine that is not working). Im not a scriptkiddie nor a kid at all, im a director of a marketing firm and have a need to take my batch files (that run on an sql server) and make them faster (and now with more capabilities, having moved to freebasic.)
 
i have been doing things in the batch file with no issue's but wanted to make things faster, so am i allowed by you    to move my batch file into a higher level language? is there some tribunal    that i need to attend prior to GETTING help from you??? is it the fact that my routine is so simple that you can't wrap your head around it and wonder if i have an ulterior motive???    Did I not tip at the gate the proper amount??? Should I move to another forum to get help??? Who's in charge, I want to talk to the management about this!!! Outrageous! Preposterous! Bullocks!!! 
 
Quote from: Salmon Trout on December 15, 2011, 11:02:53 AM
I keep wondering why the OP doesn't just use a cmd script ("batch file") to do the things that he wants, and he never answers. This makes me wonder if he is trying to do some kind of script-kiddie thing. Since he steadfastly refuses to tell us, the help he is going to get will not be focused.
These two statements kind of contradict themselves.
Quote from: skorpio07 on December 13, 2011, 03:04:21 PM
not to hide, but the source file is getting a bit large so as a way of making it run faster.

Quote from: skorpio07 on December 15, 2011, 12:04:08 PM
is it the fact that my routine is so simple that you can't wrap your head around it
Quote from: skorpio07 on December 15, 2011, 12:04:08 PM
i dont' know how much clearer than to post my code to make you happy    (i did post the routine that is not working). Im not a scriptkiddie nor a kid at all, im a director of a marketing firm and have a need to take my batch files (that run on an sql server) and make them faster (and now with more capabilities, having moved to freebasic.)
 
i have been doing things in the batch file with no issue's but wanted to make things faster, so am i allowed by you    to move my batch file into a higher level language? is there some tribunal    that i need to attend prior to getting help from you??? is it the fact that my routine is so simple that you can't wrap your head around it and wonder if i have an ulterior motive???    Did I not tip at the gate the proper amount??? Should I move to another forum to get help??? Who's in charge, I want to talk to the management about this!!! Outrageous! Preposterous! Bullocks!!! 

Oh dear!

Thank you BC for your very detailed response. I appreciate the help that your giving alot. couple of quick questions.
 
in my batch file, when it gets to the part of the code that sets the environment variables, i had to run this:
 
if not "%return%"==""  setx return %cd%  &  set return=%cd%
 
that way i set the new global (via setx for FUTURE windows) envvar and then set the local var for the current (parent) window and it works just fine as a batch file. but if i want to move up to freebasic, how to program the same functionality in it.
 
i knew that there were options to create the regkeys but didnt think i needed that till now, maybe a better solution..
 
but if i use the regkey solution, is there a way to have it promote itself back to the parent window? would need the envvar to "stick" upon program completion.
 
again, many thanks for your detailed explanations, i will learn from this.
 
Quote from: BC_Programmer on December 15, 2011, 10:52:13 AM
The Environment Block of a process is a copy of the environment block of the parent process, or a new, default Environment Block (depending how you spawn the child process).
180.

Solve : Batch file to read from CSV and output multiple files?

Answer»

Hello all, and a first poster here.  I'll be upfront and say I haven't really messed with batch files since editing Autoexec.bat in the 90s. 

Yes, the project I'm working on is technically "for work" but its to make my own life easier, more so than being for anyone's profit.  I'm a man of many hats, so I should be out pulling wire today, but I really need to make some progress on my little project so I'm ready for next week.

Anyway, there's my intro, here's what I'm trying to accomplish:

list.csv contains about 120 lines.   Column A is a text string defining a location.  Column B is an IP address.

What I'm looking for as an end result is to create two files.

1.   filename.bat that has the string:  "tst10.exe /r:filename.txt /o:bench.txt"  Where filename of both the .bat and the .txt are generated from Column A.

2.   filename.txt that has a unique IP string inside that's generated from column B.


Filename.txt will contain the following:

CODE: [Select]192.168.1.2 20000
WAIT "username:"
SEND "name\m"
WAIT "password:"
SEND "pass\m"
WAIT ":"
SEND "command\m"

Where the filename is created from CSV column A, and the IP inside the file is generated from Column B.  Everything else is static and will be the same throughout.

What I have so far:

Code: [Select]SET filename=
For /F "delims=, tokens=2" %%G IN (list.txt) DO SET filename=%%G
echo %filename% > "%filename%.bat"

This outputs Column A of each line on the screen, and only saves a .bat of the last entry of the CSV.

Obviously, I'm missing alot, and scripting is not my forte.

Any help is GREATLY appreciated.  I'm a bit out of my depth on this one, and don't want to have to do all 120ish connections long-form/by hand or try to entrust someone else to do the remote connections and risk breaking anything.Have you come across PowerShell?  Much more powerful string parsing capabilities.Hadn't even heard of it, but after looking at the wikipedia page for it, I think I might look into it more in depth.Am I undestanding you correctly that you want a batch file that creates another batch file as well as a text file?

I am not really following your logic but if you could post a few lines of the list.txt file and show me the intended output I am sure we could figure it out. Quote from: ShaneC on December 21, 2011, 02:33:26 PM

Hadn't even heard of it, but after looking at the wikipedia page for it, I think I might look into it more in depth.

Well worth it.  Once you've got your head around its peculiar syntax, you'll appreciate that power.  It blows the command prompt out of the water.  Here are a couple of quick-starts for string functions:

http://technet.microsoft.com/en-us/library/ee692804.aspx
http://powershell.com/cs/blogs/tips/archive/2009/06/08/using-string-functions.aspxA couple of YEARS ago I started working on PowerShell for a few solid months and then got to caught up in life and stopped.  It definitely has its advantages but I did run into a few problems that still could only be solved with a batch file.  But I did like that I could create GRAPHICAL Interfaces for my powershell scripts.  That was pretty cool.  I had actually started to try and convert some of my batch files into PowerShell scripts.  We had even FIGURED out how to do drag and drop input onto a powershell script. Quote from: Squashman on December 21, 2011, 03:03:27 PM
Am I undestanding you correctly that you want a batch file that creates another batch file as well as a text file?

I am not really following your logic but if you could post a few lines of the list.txt file and show me the intended output I am sure we could figure it out.

Correct on that I'm wanting to use a batch file to create additional batch files and text files.  Essentially I have 121 specialized systems that I need to migrate from a routed network to a VLAN.  Before I can change the IPs, I need to change the encryption keys. 

To do so, I need to Telnet into each device, login to it, issue some special commands, then leave the connection open while sending another batch of commands from a central server.  Once the commands from the central device are processed, then I can close out the remote connections.

So the inital batch file would read from list.csv

(list.txt & list.csv are the same file, just different extensions, both using a , for the delims. - I typo'd the original post)

Code: [Select]Bldg 123 Rm 456,10.1.28.171
Bldg 789 Rm 12,10.1.50.20

and create Bldg 123 Rm 456.bat  and Bldg 123 Rm456.txt

Bldg 123 Rm 456.bat would contain the following:

Code: [Select]"tst10.exe /r:Bldg 123 Rm456.txt /o:bench.txt"

(note:  /o:bench.txt is the output log of the tst10 program, but the log file itself isn't necessary for me to keep, though I believe the switch needs to be there)

and  Bldg 123 Rm456.txt would contain:

Code: [Select]10.1.28.171 20000
WAIT "username:"
SEND "name\m"
WAIT "password:"
SEND "pass\m"
WAIT ":"
SEND "command\m"
IP is the only thing that changes here.  All other text is the same across all devices.

So in the end, I'd end up with 121 batch files, each with the TST10.exe shortcut/parameters, and 121 text files as the command script that will be executed on the remote devices.


I did look into Polyscript for this, but it didn't seem to work on the bench test.  TST10 worked, so it looks like that's the route i'm going.

Code: [Select]For /F "tokens=1,2 delims=," %%G IN (list.txt) DO (
echo "tst10.exe /r:%%G.txt /o:bench.txt">"%%G.bat"
echo %%H 20000>"%%G.txt"
echo WAIT "username:">>"%%G.txt"
echo SEND "name\m">>"%%G.txt"
echo WAIT "password:">>"%%G.txt"
echo SEND "pass\m">>"%%G.txt"
echo WAIT ":">>"%%G.txt"
echo SEND "command\m">>"%%G.txt"
)SWEET!  That looks perfect!

I'll test it out later today to make sure.  Now as long as I didn't fat finger anything on my end, I should be golden.

Thank you so, so much!Oh, I have to ask, cuz this is the one big thing that I've had a hard time wrapping my brain around:



%%G is column A, and %%H is Column B....but why?  What defines it?


My guess at this point would be that the first line with %%G IN (list.txt) sets it up so that %%G = A1, therefore %%H would be A2 and it just works its way down the line, but.....well, is that correct?one flaw, now fixed:

Code: [Select]For /F "tokens=1,2 delims=," %%G IN (list.txt) DO (
   echo tst10.exe /r:%%G.txt /o:bench.txt>"%%G.bat"
   echo %%H 20000>"%%G.txt"
   echo WAIT "username:">>"%%G.txt"
   echo SEND "name\m">>"%%G.txt"
   echo WAIT "password:">>"%%G.txt"
   echo SEND "pass\m">>"%%G.txt"
   echo WAIT ":">>"%%G.txt"
   echo SEND "command\m">>"%%G.txt"
)


Was:  echo "tst10.exe /r:%%G.txt /o:bench.txt">"%%G.bat"
The quotes inside the batch file didn't play nice.  =D


Quote from: ShaneC on December 22, 2011, 07:47:32 AM

%%G is column A, and %%H is Column B....but why?  What defines it?


What defines it is the "tokens=1,2" part of the tokens/delims block of the FOR statement. If you use tokens you can create potential "IMPLICIT" variables that follow the letter you choose for the explicit FOR variable. They are called implicit variables because they are implied by the tokens= section. This part: "tokens=1,2 delims=," %%G tells FOR: "Consider each line read in from list.txt to be a series of tokens separated (delimited) by commas. Assign token number 1 to %%G and assign token number 2 to a variable consisting of two percent signs and the next letter after G (i.e. %%H).

"tokens=1-2" means the same as "tokens=1,2".

It's all in the FOR documentation which you can access by typing FOR /? at the prompt.

tokens   1     2      3       4
string horse,tiger,elephant,sheep
         ^     ^
         |     |
        %%G   %%H

181.

Solve : NetBeans/Java DNS cache??

Answer»

NetBeans seems to use a DNS cache separate from the O/S.  When developing web sites with my laptop in different locations, it would be really handy if I could get this cache flushed (one LAN IP address when at work, one EXTERNAL IP address from a local DNS server when at home).  Windows' own resolver has no problem with this CONCEPT and I can always run ipconfig /flushdns if needs be.  But NetBeans is still looking in the wrong place.

Does anyone know if there's any simple, non-programmatic way of flushing this cache?Just as an aside, when I tried again an hour or so later (in the new location), the DNS lookup was resolved afresh (correctly) so I presume the cached entry had HIT its TTL.  It's a nuisance!I found this:
http://www.rgagnon.com/javadetails/java-0445.html

Since NetBeans is written in Java (as far as I recall) it would be susceptible to this "feature" where the JVM has it's own cache of network addresses, which sounds like it could be the cause of your issue.Indeed, that's my understanding.  I'm not really up to the challenge of hacking the NetBeans code and recompiling to fix this "feature"...  I'm betting there is a way of flushing this cache - but is it private PER application though?  That seems inefficient, but who knows.Hang on - reading that article more closely, there's a suggestion a JRE setting might fix it.  I'll try that.  Thanks! Quote from: Rob Pomeroy on December 13, 2011, 01:56:01 PM

Hang on - reading that article more closely, there's a suggestion a JRE setting might fix it.  I'll try that.  Thanks!

You bet, keep us posted So far so good - thank you!There was a strange twist to this.  The Windows DNS cache operates slightly differently in versions of Windows after XP.  ipconfig /flushdns appears to work properly in an unelevated command prompt.  But it doesn't.  The cache is only properly flushed when the command is run from an elevated prompt.  Anyway, with the settings change and BEARING the above in mind, my multi-location development is proceeding smoothly again.
182.

Solve : MySQL 'Tip'?

Answer»

Just a quick tip: If you are trying to access a MySQL Server remotely (from another machine, say- for example, using the .NET DBConnector on a desktop while using a existing MySQL Install on the laptop) consider the fact that MySQL ships by default so that it doesn't allow remote connections.

Basically, I had everything setup and coded, but I couldn't get it to log on to the database. Finding out how to make MySQL accessible remotely wasn't easy either, I kept finding stuff that  told me to edit logs that didn't exist.

For the record, if you want to make a MySQL Server accessible remotely on Ubuntu or a derivative thereof (in my case, mint) Edit  the file (as root) /etc/mysql/my.cnf, and within the file look for and comment out the line

Code: [Select]bind-address = 127.0.0.1
comments being Hashmarks (#) at the start, btw.

In total I spent about 12 hours total (it's coming up on 6PM, I've been up since... 5AM working on this) converting my .NET database layer from using Access databases to using MySQL. 10 minutes to actually make the required code changes and configuration changes to it''s INI file, about an hour thinking my code was broken, giving up on munging around with it, trying to figure out why MySQL wasn't showing up in a netstat as listening on port 3306, learning through google that it doesn't by default allow remote connections, googling to figure out how to make it accept remote connections, trying to follow tutorials for ancient versions of red hat that try to get me to open files either without giving me a folder- "open your my.cnf file" they say, yes, I would have done that if I knew where it was..., finally finding one that was more modern but still decided that I only needed a filename to find the log file, searching the drive for the file (my.cnf) in question, finding about a half dozen, learning through more googles that there is a special precedence to the my.cnf files and if I edit the wrong one it won't do anything, learning about said precedence Finally making the change, stumbling while trying to restart mysql because I wasn't doing it as root, GOING back to my desktop and my application and trying to undo all the changes I made when I thought the code was wrong, and finally getting it working.

I swear when I was Stepping over the code in the debugger and I got to the line where it establishes the connection (an otherwise innocent looking "CacheCon.Open()" call) the 8 or so seconds it took to establish the connection and succeed felt like an eternity of waiting for what I felt was an inevitable error leading to another sidetrack to googleville. I thought I was dreaming as that line not only worked flawlessly but all my other code and SQL statements didn't throw errors and seemed to do exactly what they were intended to do.

So that's been my day, anyway.Yup, been burnt by this one myself!I have to admit it was fulfilling to watch all my otherwise untested code work perfectly fine and do exactly what I wanted it to. Well, OK, that's a lie, I did have to change a query referring to a field I named "Order" to be in backticks since ORDER is a SQL reserved word.

This "project" really is a bunch of firsts. First actual paid Job in this field, first go at a "real" WPF application, first time using databases from .NET, and first time accessing a remote database in a "distributed" idea (admin and client app on separate machines seeing each others changes) first time using MySQL outside PHP, first time dealing with my own MySQL installation (rather than on a webhost), first time dealing with the UI concern that a touchscreen (and no keyboard) brings to the table. And so on. First time writing a serious "Tiered" application (Client (touchscreen) and Admin applet both use the same DataLayer library which abstracts away most database related tasks), etc. A project of firsts. I've learned more about the involved technologies(WPF, MySQL, MySQL Server administration and ADO.NET)  than I probably would have learned "at my leisure" in the next year. Feels good to work on something for hours on end, learning new technologies, and having something that (IMO) looks pretty damned professional. On an unrelated note I've had to use my laptop for a lot more of the network facing stuff, so I've had to use FTP to upload things to my site for the last week or so, to the point where It's second nature (and I've memorized the randomly generated password for my webhost), Control-Alt-Arrow to switch between desktops for checking E-Mail and so forth, running MYSQLDUMP to get a overview of my database schema to refer to while working on new functionality in the desktop apps, etc.Are you developing in VISUAL Studio?  Can that not handle all the FTP uploads for you? Quote from: Rob Pomeroy on December 19, 2011, 02:44:50 AM

Are you developing in Visual Studio?  Can that not handle all the FTP uploads for you?
The applications I speak of are not web-applications, but client-side programs; my website is PHP/MySQL, running on a webhost. Normally, I would work on my site using Editpad Pro's FTP Panel, which makes dealing with FTP pretty much automatic. The reason I've had to start using the ftp shell on my linux machine is that my only Internet access currently is through wireless and my Wireless-N PCI card appears to have given up the ghost, so my desktop has no internet connection, (I tried learning how to bridge the connections via the laptop but gave up). ftp is still quite workable and in many ways faster to work with, so it's not a huge change. Although now my laptop is tethered to the desktop via a crossover cable for both my own MySQL dev server as well as data transfers through Samba in both directions . Quote from: BC_Programmer on December 17, 2011, 07:02:08 PM
consider the fact that MySQL ships by default so that it doesn't allow remote connections.
Sounds just like SendMail.  You wouldn't believe how long I bitched and screamed at my old linux server when I couldn't receive any email on my server from the outside. SendMail by default just works locally on the machine until you change the config to allow it to receive email from the outside world.In MySQL's case, having it configured that way by default makes more sense, since one of the most common use cases is that the MySQL Server is in fact the same machine that is running apache, so it basically "connects" to itself,so allowing remote connections would just be opening an attack surface. I just found that, even after I knew that was the default setup, I had to do so much googling just to find out how to change it, and it was a bit frustrating.

But it's working quite flawlessly now. Quote from: BC_Programmer on December 19, 2011, 07:03:09 AM
even after I knew that was the default setup, I had to do so much googling just to find out how to change it, and it was a bit frustrating.
Ditto when I setup SendMail the 1st time. I had one of those huge 3 inch hard cover SendMail books and I couldn't find the answer in their.  Then spent a few days Google Searching and finally figured out how to change the SendMail config file. Was literally one line of code to change.  I completely understand why MySQL and Sendmail would be configured out of the box like that.  It is probably a huge security hole if you don't have your server or Network locked down.  You certainly wouldn't want to have an Open Relay setup on your Mail server by accident.Hindsight is wonderful, isn't it!   "telnet aaa.bbb.ccc.ddd 25" (from a remote machine) is our friend.
183.

Solve : Creating a batch file to open programs in order?

Answer»

Hello everyone,
i´m building a FLIGHT simulator, and WANTED for the computer to open programs automatically and seguentially, when the computer starts. I´ve created a file that OPENS the programs, but all at once.
I need to open FSX.exe FIRST, wait for it to load, then open the Simkits software, and then the Instructor software.
So, is there a command where I would open FSX and wait 1 minute for it to load, and open the second file, and so on?

I saw in a website this comand, but cant seem to get it to work .

for /L %%I in (1,1,60) do start "C:\Arquivos de Programa\Mozilla Firefox" firefox.exe

Thank you in advanceI have seen ways to do this in other than batch like C++, but in batch the problem you are probably facing is that until firefox closes does it step to launch the next application right?You COULD use the ping command and set the time it takes for it to load:

ping 1.1.1.1 -n 1 -w 10000 >nul

10000=10 seconds

Good luck, hope it works.would this work as well?
 
ping localhost -n 60 > nul
 
that should do it in one minute increments, create a loop do to more than onceThis thread died in July 2011.
apparently so did i 
 
but i get the drift, i will move on to another forum so as not to offend your turf Quote from: skorpio07 on December 15, 2011, 02:44:27 PM

apparently so did i 
 
but i get the drift, i will move on to another forum so as not to offend your turf

It's nothing about turf. It's about thread necromancy, which is frowned upon by most members of any forum. (unless it's the Original Poster)I agree. Leave a thread alone if the original poster has not come back.  On most of the forums I contribute on if  a new user posts a question I usually answer back with a feeler question to see if they are going to come back.  I don't like wasting my time writing a script if they are never going to come back.
184.

Solve : batch file to check folders if populated?

Answer»

I've DONE very LITTLE with batch files, but I need to check several thousand directories to see whether or not they're populated. My FINAL outcome will be a list of directories that are empty. The folder structure looks like this:
M:\Drafting\DWGS\70-000\70-038\Images

I need to check every "Images" folder below the DWGS folder.

I'm using XP PRO.

Thanks for any help.I think this should work
Code: [Select]PUSHD M:\Drafting\DWGS\
for /f "tokens=*" %%I in ('dir /ad /b /s *images') do (
if EXIST "%%I\nul" if not exist "%%I\*" echo %%I is empty
)

185.

Solve : checkbox problem! need help?

Answer»

I have USE 4 checkbox in one asp.net webpage, say page

1. language used is in c# in visual studio.net 2008.
I want to pass the VALUE of these checkbox to another

asp.net page ,say page 2.
 Its not working.Please correct the code. Here are the

codes.

On page 1.aspx.cs
---------------------
PROTECTED void Button2_Click(object sender, EventArgs e)
{
   string Rating1 = CheckBox1.Checked;
   string Rating2 = CheckBox1.Checked;
   string Rating3 = CheckBox1.Checked;
   string Rating4 = CheckBox1.Checked;
   
   string url;

 if (CheckBox1.Checked)
        { Rating1 = "Best"; }
       
           if (CheckBox2.Checked)
        { Rating2 = "Good"; }
       
                if (CheckBox3.Checked)
        { Rating3 = "Average"; }
       
         if (CheckBox4.Checked)
        { Rating4 = "Not Satisfactory"; }

url = "page2.aspx?RAT1="  + Rating1+ "&rat2=" + Rating2

+ "&rat3=" + Rating3 + "&rat4=" + Rating4 ;
        Response.Redirect(url);

on page2.aspx.cs
----------------------
PUBLIC partial class _Default : System.Web.UI.Page
{
   string RetrievedValue4;
    string RetrievedValue5;
    string RetrievedValue6;
    string RetrievedValue7;
    string RetrievedValue8;

protected void Page_Load(object sender, EventArgs e)
    {
        this.Label14.Text = Request.QueryString["rat1"];
        RetrievedValue5 = this.Label14.Text;


        this.Label15.Text = Request.QueryString["rat2"];
        RetrievedValue6 = this.Label15.Text;

        this.Label16.Text = Request.QueryString["rat3"];
        RetrievedValue7 = this.Label16.Text;

        this.Label17.Text = Request.QueryString["rat4"];
        RetrievedValue8 = this.Label17.Text;
     }


Thanks
God bless you!!

186.

Solve : OS boot problem?

Answer»

i am MAKING an OS (DakOS) and i am having some problems, 1.When i compile the file (i am making an os that will only use the boot LOADER) it YELLS at me that there isn`t any room when i convert the floppy disk to an ISO . 2.It recognizes it but it says "Invalid system disk"  how might i fix this (also it is 512 Bytes)
Commands in linux: mkisofs -o dakos.iso -b dakos.flp cdiso/ (Problem 1)
it is written in Intel x86 ASM (test machine has an Intel PENTIUM 2 processor)
Help plz

187.

Solve : Batch Networking? And a cmd line ASCII graphics engine.?

Answer»

Is it possible to do networking with server in batch? And also, imagine a PROGRAM that allows you to load and move ASCII images for cmd line languages and text based programs. Also, for making text based games, and perhaps later games with minor graphics (like, minecraft low graphics) should I use C++, TorqueScript, Java, or make my own language if so possible?Well, now that you bring Minecraft up, I do think that Bukkit servers run using conhost.exe and cmd.exe from a batch file. So to your first question YES? Quote from: Nathansswell on November 28, 2011, 02:35:19 AM

Well, now that you bring Minecraft up, I do think that Bukkit servers run using conhost.exe and cmd.exe from a batch file. So to your first question Yes?

The batch file in Bukkit contains the following code:
Code: [Select]ECHO OFF
IF /I "%PROCESSOR_ARCHITECTURE:~-2%"=="64" "%ProgramFiles(X86)%\Java\jre6\bin\java.exe" -Xincgc -Xmx1024M -jar "craftbukkit-1.0.1-R2-SNAPSHOT.jar"
IF /I "%PROCESSOR_ARCHITECTURE:~-2%"=="86"  java -Xincgc -Xmx1024M -jar "craftbukkit-1.0.1-R2-SNAPSHOT.jar"
PAUSE
That's just RUNNING the java file and providing a vehicle for you to send and receive text to the server.

Quote from: tommyroyall on November 19, 2011, 08:00:02 PM
Is it possible to do networking with server in batch?
Like a multiplayer game? I don't think that batch is well suited for that. There's one thing that I TRIED, where I set up a website and the batch connected to it using FTP, downloaded
a certain text file that contained information, and uploaded its own version of it if that was needed every two seconds. It was pretty effective for a simple chat script, but actually what the batch file did was launch a DoS attack on my website. D:

For networking, or a GUI game at all, you'd probably need a better programming language. While we're on the subject of minecraft, minecraft uses java.
If you've never learned another programming language, cross C++ right off your list of possibilities. It has DIFFICULT syntax, and something fairly simple requires a large script.
188.

Solve : cs5?

Answer»

So Im trying to learn platform GAMING for fun, cs5 flash AS.3

Followed TUT. Was at it for hours, quit came back next day realized i had missed alot of the tut instructions, can't understand how I could miss it even after reviewing the video 4-6 times. ANYWAY its a simple tutorial but im a simpler man. The ball is supposed to fall on the floor but It doesn't. Its probably something awkwardly simply but I've just started. Also I think I've copied on everything, but I taught so yesterday too...

TUTORIAL LINK: Part1: http://www.youtube.com/watch?v=Z160NtbM6Zs
Part2: http://www.youtube.com/watch?v=LVaEZMiiz7A

My fla. file: http://www.mediafire.com/?hm2q3k2gcdbsmm0
My Code:
Code: [Select]import flash.events.KeyboardEvent;
import flash.events.Event;

var KeyThatIsPressed:uint;
var rightKeyIsDown: Boolean= false;
var leftKeyIsDown: Boolean= false;
var upKeyIsDown: Boolean= false;
var downKeyIsDown: Boolean= false;

var gravity: Number = 1;
var yVelocity: Number = 0;
var canJump: Boolean= false;

stage.addEventListener(KeyboardEvent.KEY_DOWN, PressAKey);
stage.addEventListener(KeyboardEvent.KEY_UP, ReleaseAKey);

function PressAKey(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.RIGHT)
{
rightKeyIsDown = true;
}
if(event.keyCode == Keyboard.LEFT)
{
leftKeyIsDown = true;
}
if(event.keyCode == Keyboard.UP)
{
upKeyIsDown = true;
}
if(event.keyCode == Keyboard.DOWN)
{
downKeyIsDown = true;
}
}

function ReleaseAKey(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.RIGHT)
{
rightKeyIsDown = false;
}
if(event.keyCode == Keyboard.LEFT)
{
leftKeyIsDown = false;
}
if(event.keyCode == Keyboard.UP)
{
upKeyIsDown = false;
}
if(event.keyCode == Keyboard.DOWN)
{
downKeyIsDown = false;
}
}

circle_mc.addEventListener(Event.ENTER_FRAME, moveTheCircle);

function moveTheCircle(event:Event):void
{
if(rightKeyIsDown)
{
circle_mc.x +=5;
}
if(leftKeyIsDown)
{
circle_mc.x -=5;
}
if(upKeyIsDown && canJump)
{
yVelocity = -15;
canJump = false;
}
yVelocity+  gravity;

if(! floor_mc.hitTestPoint(circle_mc.x, circle_mc.y, true))
{
circle_mc.y +  yVelocity;
}
if(yVelocity > 20)
{
yVelocity = 20;
}

for(var i:int = 0; i<10; i++)
{
if(floor_mc.hitTestPoint(circle_mc.x, circle_mc.y, true))
{
circle_mc.y --;
yVelocity = 0;
canJump = true;
}
}
}
Sorry if wrong section

189.

Solve : C++ Floppy to C: tool issues?

Answer»

I have a large amount of floppy disks that I used between 1988 and around 2000 when I finally got a CD Burner. I started manually copying them via xcopy all contents to my C: drive, but after getting through 25 disks in 1 box, I thought there has to be an easier method of passing my disks contents to C: drive.

So I started to write a program in C++ which I want it to create numeric directories on the C: drive at C:\Floppies\   and each time it is executed it first reads in a text file called lastfilename which holds a single integer of the last directory created and written to, so after I have copied disk #25 to the C:\Floppies\25\ it wrote the integer 25 to this text file. So the next time it runs it first loads in this value and increments it via ++ to the integer variable, so that it now creates a directory named 26 at C:\Floppies\26\ and then xcopy's the contents of A: to C:\Floppies\26\ via system("XCOPY A:\*.* c:\Floppies\26\*.* /y ");

Problem is that it does not like system("XCOPY A:\*.* c:\Floppies\26\*.* /y ");

Also I am having issues directly concatenating the 26 from the incremental variable into C:\Floppies\26\*.* /y, and C++ does not like directly passing the string variable into system(" ");

In the END I want to clean this up and have it basically say its running, copy all contents to C:\Floppies\ and then display COPY COMPLETE in the end and ask the user to insert another disk and enter 1 to run again or 0 to quit.

Any suggestions? I will post my code if needed.If you're going to execute system() calls, use a batch file. I've hardly ever seen a case where the main functionality of a so-called C/C++ program used system() and couldn't be made into a far more terse batch.

As to your issues: they are all based on not knowing enough about C/C++. Which probably explains why you would choose it for something like this.

Anyway, I tried to make a C/C++ app but apparently stream i/o won't let me input or output a char*, and I couldn't be bothered to figure out why.

So here's a C# program. haha.

Code: [Select]using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace floppinc
{
    class Program
    {
       //equivalent to C's System() call. ugh.
        private static INT System(String commandline)
        {
            String[] splitarg = commandline.Split(new char[]{' '},2);
           
            Process getprocess = Process.Start(splitarg[0],splitarg[1]);
            getprocess.WaitForExit();
            return getprocess.ExitCode;
        }
        /// <summary>
        /// returns integer equivalent of contents of file +1, or 1, if the file doesn't exist.
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        static int SequenceValue(String filename)
        {
            int intvalue =0;
            //open the file.
            if (File.Exists(filename))
            {
                FileStream fsr = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite);
                StreamReader sr = new StreamReader(fsr);
                //read the first line.
                String lineread = sr.ReadLine();
                //parse it to an integer.
                intvalue = lineread==null?1:int.Parse(lineread) + 1;
                fsr.Close();
            }
            else
            {
                intvalue = 1;
            }
            String strvalue = intvalue.ToString();
            //reopen for truncate.
            FileStream fsout = new FileStream(filename, FileMode.Create);
            StreamWriter sw = new StreamWriter(fsout);
            sw.Write(strvalue);
            sw.Close();
            return intvalue;
        }
        private static String ChoiceInput(String Prompt, String[] valid)
        {
            string currinput=null;
            bool isvalid=false;
            while (!isvalid)
            {
                Console.WriteLine(Prompt + "[" + String.Join("/", valid) + "]");
                currinput = Console.ReadLine();
                isvalid = valid.Any((w) => w.Equals(currinput, StringComparison.OrdinalIgnoreCase));
                if (!isvalid)
                {
                    Console.WriteLine("Invalid option-" + currinput + ".");
                }
            }
            return currinput;
        }
        private static readonly String sequencefile="D:\\sequence.dat";
        private static readonly String commandformat = "XCOPY A:\\*.* C:\\Floppies\\{0}\\*.* /S /Y";
        static void Main(string[] args)
        {
            bool exitloop=false;
            while (!exitloop)
            {
                int sequenceval = SequenceValue(sequencefile);
                String execcmd = String.Format(commandformat, sequenceval);
                System(execcmd);
                exitloop = (ChoiceInput("Copy Another?", new string[] { "Y", "N" }).Equals("N",StringComparison.OrdinalIgnoreCase));
            }
        }
    }
}

I rather like the ChoiceInput() function, myself.

This would be a very short batch file, though, I just don't like messing with batch files.

EDIT: fixed line endings. That's what happens when you copy text files from windows to Linux...Thanks BC... will use your C# program. Should be able to compile it with Express 2008 or 2010 and run it. I have a book on C#, but haven't gotten into it yet other than making your own browser by typing code out of book and then modifying the appearance, but it looks more like a custom IE vs whole new browser.

I was thinking originally batch, but figured C++ or another language (such as C# as you posted) would be better at reading/writing from file and incrementing the folder name 1,2,3,4,5 and so on. And then pick up with 7,8,9,10 on future executions from the original executed location to avoid data merging or overwriting.

Now to compile and try your program out as well as check out your source code in detail. Might have some questions about it since I am new to C#. Many thanks and HAPPY New Year!

190.

Solve : Perform an HTTP/1.1 POST in VBScript?

Answer»

I have had the idea to make a "Chat Autofixer" for XSketch.com, and in order to do this, I basically flood the chat with a message consisting of [ ]. I want to make it distributable, for my XSketch friends, and source-viewable. I'd like to do this using VBScript. Unfortunately, the server running XSketch is using GWT with a POST to send messages, and I don't know how to EXECUTE a POST in VBS. I only NEED to post a string, and I know what URL to post to. Does anyone know the code required to perform such an action?

PS> This will also help in my VB.NET application coming soon that will use POST.Ugh.  I wouldn't use VBScript for this.  Any language that can use a cURL library is a better bet.  But if you're determined, you might find some inspiration here: http://www.motobit.com/tips/detpg_post-binary-data-url/ Code: [Select]'URL to OPEN....
sUrl = "http://www.example.com/page.php"
'POST Request to send.
sRequest = "varname=value&varname=value"

HTTPPost sUrl, sRequest

Function HTTPPost(sUrl, sRequest)
  set oHTTP = CreateObject("Microsoft.XMLHTTP")
  oHTTP.open "POST", sUrl,false
  oHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
  oHTTP.setRequestHeader "Content-Length", Len(sRequest)
  oHTTP.send sRequest
  HTTPPost = oHTTP.responseText
 End Function
Thanks to everyone for your helpfulness. I am now able to do what I was DESIRING to do in the first place. I officially declare this topic solved!

191.

Solve : Timer code that doesnt interupts proceedure?

Answer»

How can i write a timer code like the 1 in Visual Basic
Timer code must be in c++
at the moment i am trying to BUILD a game where i am using a timer for running actions
1.This timer code cannot interupts other code proceedue
2.Logical function and other process will be place inside this timer code

i try writting it but when that timer function is running... my other proceedure stops
I KNOW this is because the process stops and it can only be running again when timer code has finish processing
So how can i avoid having other proceedure stop runningUse a thread, not a timer. Of course you don't present any information on what your target platform is, which makes it a bit difficult to offer much more advice than that.

General advice:

1. Don't use a timer.
2. Don't use a timer.
3. And most importantly- don't use a timer.

A GameProc() routine should run as fast as it possibly can, on a separate thread. It will grab a critical section/mutex, update game state, move objects, etc.  Release the mutex/critical section. Each iteration it should post a message to the main thread (which, for most operating systems would be the one managing the UI) to tell it to repaint, Otherwise, the game loop is throttled by the delay the timer has, which for most systems is at least 53 or so milliseconds. The Paint Message HANDLER (or equivalent) would then deal with grabbing a critical section on the various game objects as needed and drawing with them. Depending on the way the gameproc() messes with the gamestate variables SOMETIMES you can shorten critical SECTIONS so that the painting thread can get a word in edgewise.Thanks for replying

My target platform is window PC
I dont know what you mean by use a thread but i will look it up
Thanks

192.

Solve : shUI builder is a little lost...?

Answer»
shUI is a program built in C++ for those who aren't able to run X window system on linux (and those who can't use anything else than the command prompt in DOS)
and to give them a minimal UI-like interface to browse, edit text and whatever.


This is the installation program, but I need help for a lot of things, like:
1. how to put color in the program.
2. How to make cin scroll horizontally when the text outbounds the specified limit.
3. how to position text on screen
And other things will come over time that my program develops.


This is where i'm stuck: Code: [Select]#include <iostream>
#include <fstream>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
using namespace std;


const unsigned char Key1 = 224;
const unsigned char LEFT = 75;
const unsigned char RIGHT = 77;
const unsigned char UP = 72;
const unsigned char DOWN = 80;




int main(){
int frm1();
frm1();
};
void frm1(){
int frm2();
cout << " ________________________\n";
cout << "|   \\_____Setup______/   |\n";
cout << "| ______________________ |\n";
cout << "||  WELCOME to shUI's   ||\n";
cout << "||installation program! ||\n";
cout << "||                      ||\n";
cout << "||                      ||\n";
cout << "||                      ||\n";
cout << "||______________________||\n";
cout << "| <QUIT |        | NEXT> |\n";
cout << "`------------------------'";
cout << "";stucked


unsigned char choice = getch();
cout << endl;
if (choice == Key1)
    {
        unsigned char choice2 = getch();
        switch(choice2)
        {
            case LEFT:
                system ("CLS");
                cout << "ShUI ended.";
                break;
            case RIGHT:
                system ("cls");
                frm2();
        }
    }


return ;


}
void frm2(){
int frm1();
cout << " ________________________\n";
cout << "|   \\_____Setup______/   |\n";
cout << "| ______________________ |\n";
cout << "||First of all, you     ||\n";
cout << "||need to input some    ||\n";
cout << "||information and       ||\n";
cout << "||settings concerning   ||\n";
cout << "||you, your account     ||\n";
cout << "||data and your         ||\n";
cout << "||computer.             ||\n";
cout << "||______________________||\n";
cout << "| <Back |        | Next> |\n";
cout << "`------------------------'";
cout << "";


unsigned char choice = getch();
cout << endl;
if (choice == Key1)
    {
        unsigned char choice2 = getch();
        switch(choice2)
        {
            case LEFT:
                system ("cls");
                frm1();
        }
    }


return ;

}
193.

Solve : Help me Convert this WPF to Silverlight?

Answer»

I am interested in a CHARLES Petzold C# example that shows how to do a fisheye effect ( http://www.charlespetzold.com/blog/2009/05/Realizing-a-Fisheye-Effect-in-Silverlight.html ).  The XAML code samples are in WPF but I want to try this in Silverlight.

When I try to create the XAML code in Silverlight, the COMPILER complains in TWO locations:

194.

Solve : Think of a number?

Answer»
I'm trying to write a program, that generates a random number, between 1 and 100, then asks the user to guess it. If the user is to high it states 'lower', if the guess is to low it states 'higher', until the correct number id guessed.

I'm have trouble because i seem to keep creating infinite loops, how can i stop this?

Code: [Select]import java.util.Scanner;

public class ThinkOfANumber {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
   
    final int num = 100;
   
    int numgen = (int)(Math.random() + num) +1;
    int count = 0;
   
    System.out.println("Guess any number between 0 and 100");
    int guess = input.nextInt();
   
    while (guess != numgen) {
        if (guess > numgen)
        System.out.println("Lower");
 
    while (guess != numgen) {
        if (guess < numgen)
        System.out.println("Higher");

    while (guess == numgen)
        System.out.println("You've got the right number, Well Done");
    }
}
    }
}your formatting isn't consistent with the actual control structures;

Code: [Select]public class ThinkOfANumber {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
   
    final int num = 100;
   
    int numgen = (int)(Math.random() + num) +1;
    int count = 0;
   
    System.out.println("Guess any number between 0 and 100");
    int guess = input.nextInt();
   
    while (guess != numgen) {
        if (guess > numgen)
            System.out.println("Lower");
 
        while (guess != numgen) {
            if (guess < numgen)
                System.out.println("Higher");

            while (guess == numgen)
                System.out.println("You've got the right number, Well Done");
            }
        }
    }
}basically, your loops are nested.

Additionally, if you want to keep looping then you would need to have a while loop that terminates only when it's correct. All your while loops seem to be attempting to print the same thing as long as the guess is less than , greater than, or equal to the GENERATED number, but within the loops there is no actual change of  that value so the condition remains the same.

Something like this ought to be written with a loop that terminates only when the guess is correct, and reads in the next input at the start. Than if it's too low you print a message, if it's too high you print a message, and outside the loop is where it gets when the guess is correct, so you woul print an appropriate message for that outside the loop.I don't understand the use of all those while loops, you should just have one while loop with the appropriate if statements inside of it.

Maybe something like this. Sorry, I can't actually TEST it because I do not program in java, so you may need a little tweaking.

Code: [Select]public class ThinkOfANumber {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
   
    final int num = 100;
   
    int numgen = (int)(Math.random() + num) +1;
    int count = 0;
    int guess = 0;
   
    while (guess != numgen) {
        System.out.println("Guess any number between 0 and 100");
        guess = input.nextInt();

        if (guess > numgen)
            System.out.println("Lower");
 
        if (guess < numgen)
            System.out.println("Higher");

        count++;
    }
    System.out.println("You guessed it.");
  }
}

And I forgot, you may also want to print out count. I assumed that you wanted to count how many guesses.
Thank BC, after some tweaks (I had the random number generator set to 101, which didn't help) , it was basically like you said. I've learned alot today about the placement of curly brackets. 

Thanks again, everyone.       public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
      
       final int num = 100;
      
      
       double numgen = (Math.random())*100;
      
       int a=(int)numgen;
      
       while (a>100 || a<0)
       {
          numgen = (Math.random())*100;
          a=(int)numgen;
       }
      
      
       int count = 0;
      System.out.println("numgen"+a);
       System.out.println("Guess any number between 0 and 100");
       int guess = input.nextInt();
      
       while (guess != a) {
           if (guess > a)
               System.out.println("Lower");
   
          
            if (guess < a)
                   System.out.println("Higher");

           System.out.println("Guess any number between 0 and 100");
           guess = input.nextInt();
           }
      

        if (guess == a)
        {
               System.out.println("You've got the right number, Well Done");
        }
}you are getting 101...its because the random number generated is becoming 0 each time...its because you made it an int type...

to get the full random value....you should get it in double value....all the numbers are like 0.5677777777
or 0.06777777777....its always in decimal value...so to be able to get a value between 0 and 100....i have multiply the random value by 100...then i cast it to an int...so that the value obtained is not a decimal one...then i have checked it the way u wanted.
QUOTE from: lina19 on January 09, 2012, 02:57:47 AM
you are getting 101...its because the random number generated is becoming 0 each time...its because you made it an int type...

to get the full random value....you should get it in double value....all the numbers are like 0.5677777777
or 0.06777777777....its always in decimal value...so to be able to get a value between 0 and 100....i have multiply the random value by 100...then i cast it to an int...so that the value obtained is not a decimal one...then i have checked it the way u wanted.

Sorry, i should have marks this as solved. As you can see by 'reply 3' it was solved last November. its because...it wasnt marked as solved...and your reply was confusing as well..

Thank BC, after some tweaks (I had the random number generator set to 101, which didn't help) , it was basically like you said. I've learned alot today about the placement of curly brackets. 

I had the random number generator set to 101, which didn't help: what am i supposed to understand about it???"didnt help"....you could have stated that it was solved more clearly....

INSTEAD of asking u....whether it was solved and WAITING for you to reply...it was quicker to give the answer...its ok eventhough the reply is not useful for now...it can be useful for others as well...
195.

Solve : editable Jtree in java?

Answer»

refer to this code for testing:
http://www.java2s.com/Code/Java/Swing-JFC/TreeeditLeafSample.htm


IM not ABLE to edit the value in the jtree even it said its editable is true....


i have looked on the net...every sample of script is the same...im not able to figure out how can i make it work...

i guess its something to do with repainting the panel or the tree...STILL havent got anything...

THANKS beforehand for any helpanyway...i resolve it with....

 tree.setInvokesStopCellEditing(true);

196.

Solve : 16 bit C++ compiler?

Answer»

I've got a 64-bit PC (WINDOWS 7), but I must compile a C++ program for DOS.
What compiler do I need?

Quote

BTW:
I'm using CODE::Blocks.
You could look for an old COPY of BORDERLAND Turbo C++ which might be a free download by now.
But the real issue is running any 16 bit programs in the 64 bit Windows 7 system. You will need to use a virtual machine.

EDIT: This looks like it.
http://www.brothersoft.com/turbo-c-182798.htmlYou can use DOSBox, it's simple to use and works great.
197.

Solve : Help needed in C# - programming?

Answer»

Please I'm a beginer in C#, so if you just can give me a suggestion about how to SOLVE the following problem.

Vehicle manufacturers always offer new saving fuel cars to new DRIVERS. The Renault manufacturer has taken this in consideration and offered new car Renault Clio to a driver Syle LeSylani for one YEAR use. Syle has kept evidence of past kilometers at every fuel filling. He made at least 5 reservoirs filling per year.
 
My duty is to write the C# program that it will accept fuel data (type: double) and past kilometers (type: double) for every fuel filling. The program it needs to process those data in console application, how many kilometers are past in each filling. Also it needs to SHOW overall calculation of past kilometers for all fillings. The calculation must be presented in decimal (real numbers). The class and the program should be in two separate files. 


I have to wirte the pseudocode of this to.

In advance thank you for your reply.
Cheers.Pseudocode is not C#.  You're being asked to express this in simple statements.  It's homework by the looks of it, so your best advantage would come from having a go and then asking for comments.  There are plenty of examples of pseudocode on the internet which will give you a better idea of what you're trying to achieve.  Hint: it's simpler than it sounds.

The idea is that once you've written the pseudocode, converting that to C# (or any other language) is a breeze. ROB Pomeroy
I know that pseudocode isn't in C# but I just explained what I have to do.
About the program, I almost done it, but just asked for the help. It is a little to difficoult to me because I just started learning C#. I know that in the begining fuel and km's must be 0 because it is a new car. At least 5 fuel fillings per year mut be done.
The problem is that I'm stucked in a place where where it is asked to show how many km/one liter.
I get some errors and just fixing them.

Cheers.Where is what you have so far? Quote from: dr_iton on December 27, 2011, 11:03:59 AM

The problem is that I'm stucked in a place where where it is asked to show how many km/one liter.

Is the problem to do with getting the formula correct, or something else?I had a problem on writing the codes, so after a time I solved (learned) it.
Anyway cheers for your help.
198.

Solve : what do u mean by pallindrome?

Answer» SHORT DEFINITION WOULD be fineSorry, we don't do HOMEWORK here
199.

Solve : code to make pyramid shape astersik in c program?

Answer»

please sir give me the simplest code to make pyramid shape astersik using for loopThis comes up froim time to time in programming classes... is this your homework?
QUOTE from: prince soni on January 08, 2012, 11:26:52 AM

please sir

Sunday night, addressed as sir, mentions language in TITLE rather than text as if everyone uses C, specifically needs to use for loop...

Quote from: Salmon Trout on January 08, 2012, 11:44:25 AM
This comes up froim time to time in programming classes... is this your homework?

Gonna agree with that guess.

Code: [Select]    *
   ***
  *****
 *******
*********

Looking for this?

Not going to worry as this has been MARKED as solved...yeah it is my homework.......and at LAST i had managed to make the shape using for loop thnxNo more homework help please.
200.

Solve : please tell me error in this program of prime no.(i had made it )?

Answer»

#include;
#include;
void main(){
int a,B,C,d;
printf("ENTER no.");
scanf("%d",&a);
for(c=2;c<=a;c++){
b=c%a;}
if(b==0){printf("it is not a prime no.");}
else printf("it is prime no.");
getch();
}I told you - no more help with HOMEWORK.