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.

351.

Solve : music license override?

Answer»

i need HELP overriding  the license agreement  on some music i am trying to transfer from one laptop to another via FLASH drive. both LAPTOPS are mine. the music was downloaded from the internet. but my OLD laptop was currupted and the license agreements were lost.But wouldn't that technically be illegal...?

352.

Solve : Runing a batch file without the command window?

Answer»

Can some ONE tell me how to run a batch file wthout opening the command window.

thanksProvided the batch file PRODUCES no console interrupts, you can use:

start /MIN batchfile.bat

The batch file still NEEDS the command shell to run but running it minimized will make it less obvious.

Hope this helps. what is your OS?

353.

Solve : Batch file problems, concerning files?

Answer»

Okay .. Here it is:

I just started messing around with batch files etc, and i just ran into a problem ..
I've made a fine menu (according to myself ), from wich i can execute some programs ..

I write for instance 1 and then i hit enter, and winamp opens .. No PROBLEMS there..
I've set it to go back to the front menu, when i've launched one of the programs .. And when i hit for instance 3 it starts rcon, and it SAYS RCON IS LOADING, which is fine ..
But then after like 5 seconds i would want it to go back to main menu .. But, it doesn't .. I have to shut down rcon, before it goes back..

Is there any kind of command i can put in to make it go back after like 5 seconds, and not when the program is shutted down again?
You GOT my problem?well i think if you  post your script it would be easy to figure out besides just guessing whats wrong.ECHO off
:start
CLS
ECHO /     Welcome
ECHO \     Choose a number below
ECHO /     and hit enter..
ECHO \    
ECHO /     1. Start winamp
ECHO \     2. Start lectio
ECHO /     3. Start rcon
ECHO \     4. Start xfire
ECHO /     5. Start Ad-Aware
ECHO \     6. Start explorer
ECHO /     7. Start PeerGuardian
ECHO \     8. Start Photoshop
ECHO /     9. Start SPYBOT
ECHO \     10. Start avast!
ECHO /     11. Exit
set choice=
set /p choice=Type the number to print text.      
if not '%choice%'=='' set choice=%choice:~0,1%
if '%choice%'=='1' goto ONE
if '%choice%'=='2' goto TWO
if '%choice%'=='3' goto THREE
if '%choice%'=='4' goto FOUR
if '%choice%'=='5' goto FIVE
if '%choice%'=='6' goto SIX
if '%choice%'=='7' goto SEVEN
if '%choice%'=='8' goto EIGHT
if '%choice%'=='9' goto NINE
if '%choice%'=='10' goto TEN
if '%choice%'=='11' goto end
ECHO "%choice%" is not valid please try again
ECHO.
goto start
:ONE
cls
ECHO WINAMP LOADING
win /m "C:\Program Files\Winamp\winamp.exe"
goto start
:TWO
cls
ECHO LECTIO LOADING
win /m "http://www.lectio.dk/lectio/54/SkemaGenerator.aspx?type=elev&id=1367103984"
goto start
:THREE
cls
ECHO RCON LOADING
win /m "C:\Program Files\Rcon Unlimited\Rcon Unlimited.exe"
goto start
:FOUR
cls
ECHO XFIRE LOADING
win /m "C:\Program Files\Xfire\Xfire.exe"
goto start
:FIVE
cls
ECHO AD-AWARE LOADING
win /m "C:\Program Files\Lavasoft\Ad-Aware SE Personal\Ad-Aware.exe"
goto start
:SIX
cls
ECHO EXPLORER LOADING
win /m "C:\Program Files\Internet Explorer\IEXPLORE.EXE"
goto start
:SEVEN
cls
ECHO PEERGUARDIAN LOADING
win /m "C:\Program Files\PeerGuardian2\pg2.exe"
goto start
:EIGHT
cls
ECHO PHOTOSHOP CS2 LOADING
win /m "C:\Program Files\Graphics\Photoshop.exe"
goto start
:NINE
cls
ECHO SPYBOT LOADING
win /m "C:\Program Files\Spybot - Search & Destroy\SpybotSD.exe"
goto start
:TEN
cls
ECHO AVAST! ANTIVIRUS LOADING
win /m "C:\Program Files\Alwil Software\Avast4\ashAvast.exe"
goto start
:end

Okay .. i need it to go back to the main menu after it has done the ECHO LOADING .. After 5 seconds or such .. NOT when i close the program i chose to load..Try replacing win /m with the start command.

Ex:

start "C:\Program Files\Rcon Unlimited\Rcon Unlimited.exe"

The program will open in a separate address space and your batch file should continue back to the menu. (no 5 sec delay). If any of your options launch a 16-bit program, use the /separate switch with the start command to force a new address space.

Hope this helps. Hmm .. now i think i did as you suggested .. But when i try to load a program i just get this:


It does go back to the main screen, yes, but it doesn't start the program  
So i thought ... got more ideas?  
It should be possible...

Heres the new code:
ECHO off
:begin
CLS
ECHO /   Welcome
ECHO \   Choose a number below
ECHO /   and hit enter..
ECHO \    
ECHO /     1. Start winamp
ECHO \     2. Start lectio
ECHO /     3. Start rcon
ECHO \     4. Start xfire
ECHO /     5. Start Ad-Aware
ECHO \     6. Start explorer
ECHO /     7. Start PeerGuardian
ECHO \     8. Start Photoshop
ECHO /     9. Start Spybot
ECHO \     10. Start avast!
ECHO /     11. Exit
set choice=
set /p choice=Type the number to print text.      
if not '%choice%'=='' set choice=%choice:~0,1%
if '%choice%'=='1' goto ONE
if '%choice%'=='2' goto TWO
if '%choice%'=='3' goto THREE
if '%choice%'=='4' goto FOUR
if '%choice%'=='5' goto FIVE
if '%choice%'=='6' goto SIX
if '%choice%'=='7' goto SEVEN
if '%choice%'=='8' goto EIGHT
if '%choice%'=='9' goto NINE
if '%choice%'=='10' goto TEN
if '%choice%'=='11' goto end
ECHO "%choice%" is not valid please try again
ECHO.
goto begin
:ONE
cls
ECHO WINAMP LOADING
start "C:\Program Files\Winamp\winamp.exe"
goto begin
:TWO
cls
ECHO LECTIO LOADING
start "http://www.lectio.dk/lectio/54/SkemaGenerator.aspx?type=elev&id=1367103984"
goto begin
:THREE
cls
ECHO RCON LOADING
start "C:\Program Files\Rcon Unlimited\Rcon Unlimited.exe"
goto begin
:FOUR
cls
ECHO XFIRE LOADING
start "C:\Program Files\Xfire\Xfire.exe"
goto start
:FIVE
cls
ECHO AD-AWARE LOADING
start "C:\Program Files\Lavasoft\Ad-Aware SE Personal\Ad-Aware.exe"
goto begin
:SIX
cls
ECHO EXPLORER LOADING
start "C:\Program Files\Internet Explorer\IEXPLORE.EXE"
goto begin
:SEVEN
cls
ECHO PEERGUARDIAN LOADING
start "C:\Program Files\PeerGuardian2\pg2.exe"
goto begin
:EIGHT
cls
ECHO PHOTOSHOP CS2 LOADING
start "C:\Program Files\Graphics\Photoshop.exe"
goto begin
:NINE
cls
ECHO SPYBOT LOADING
start "C:\Program Files\Spybot - Search & Destroy\SpybotSD.exe"
goto begin
:TEN
cls
ECHO AVAST! ANTIVIRUS LOADING
start "C:\Program Files\Alwil Software\Avast4\ashAvast.exe"
goto begin
:end
endMany (if not most) Windows programs have components that must be loaded with the main program

Code: [Select]
:NINE
cls
ECHO SPYBOT LOADING
cd /d "C:\Program Files\Spybot - Search & Destroy"
start SpybotSD.exe
goto start


The strange thing is that the START works fine from the command line (go figure). I picked option nine since that was the only program we had in common but changes will have to be made for all the options.

Note: options 10 & 11 will give unpredictable results since your IF NOT statement restricts the length of the prompt reply to one byte!!

Good luck.

354.

Solve : How can I install a scheduled task??

Answer»

Greetings

I have a particularly difficult problem that needs a skilled programmer's attention. After a series of failed attempts, I decided to turn to you guys.

The point is this:

1. I'm a fairly computer-literate person with a keen interest in graphic design. Additionally I serve as my whole family's computer technician, which bothers me immensely. To remedy this I decided to create a sort of "reminder/maintenance" program to encourage them to do things for themselves and perform routine maintenance without my help.

2. Since I know absolutely nothing about real programming, I have created a standalone projector in Flash that enables the user to install freeware such as Spybot, Ad-aware, a backup program, an antivirus etc.

3. I have created another standalone projector that enables the user to click a series of links to perform maintenance tasks such as backup and cleaning. Each link points to a file that starts the desired program, such as Ad-aware. This standalone projector (and additional files) is copied via a batch file to C:\Program Files\Maintenance from the install CD.

4. Now the only thing I need is an executable\batch file that schedules this standalone projector to open once every month. I've tried a few things but I cannot create a scheduled task via a batch file, and more annoyingly, hide (or exit) the *censored* CMD window after the projector has been started. Each time I use the START command the CMD window won't hide. And for some reason the switches won't work properly, just generate errors, such as "Not a recognized switch command". (Hehe, listen to me rambling on using terminology I have barely any concept of). However, I'm sure that 20 webpages on swiches can't all be wrong, so it must be something I'm doing wrong.


Any ideas on how I can get this thing to work? The path to the file that I want started should be

"C:\Program Files\Maintenance\Maintenance.exe" .


I have READ other postings which I found insightful, but not helpful as such. I'm using Windows XP Professional SP2.

Any help WOULD be greatly appreciated.

Best regards

MrFrost from IcelandYou can use the AT command:

Code: [Select]
AT 8:00PM /every:15  "C:\Program Files\Maintenance\Maintenance.exe"

will schedule a job to run at 8:00PM on the fifteenth of every month. Primitive, but it gets the job DONE. Change the parameters to your situation.

XP Pro (not HOME) users can also use the SCHTASKS command.

All Windows users can use the task scheduler found in system tools. This uses a GUI that makes this chore an idiots delight (I use this method all the time )

Windows users can also write a WinScript, but this is problematical as there are two API's for scheduled jobs and neither can see what the other has done!

One question: How are you going to schedule the job that puts the job on the schedule?  Hi there, and thanks for the reply.

I have considered the at command and tried to implement it with my limited knowledge, using echo and such commands but with limited results. The task scheduler is of course a good solution, but for some of my family, even that is too
"technical". Also, I was considering PUTTING the package on the net and offering it for free download.

Thus, it would need a idiot-proof interface. I have already constructed a free rescue disk that needs very little basic forehand knowledge to use. The applications are launched via the fscommand and a small tool from Flashgeek (http://www.flashgeek.com/tutorials/flashgeek.ZIP). The applications include a free tutorial on basic data rescue, a HDD repair tool, INSERT Linux Repair disk image  (www.insert.de), etc. Of course you need to have access to another computer to view the disk but that is a minor problem, since most people have access to a netcafe or a friends PC.

My plan is this:

1. Create an install disk to install the applications on the HDD. Then the user clicks a link that activates a bat file that copies the Maintenance.exe package to the HDD The package is ready to run as is. Then the same file activates a file that can install the scheduled task. Then the bat file exits.

2. The Maintenance package is activated once every month to remind people to backup their files and run maintanance programs. Since I know the location of each .exe file that I want activated, it is no problem to insert that path into the Flashgeek tool and have that little program run Ad-aware, Spybot, Backup etc. The Flashgeek tool is activated via a FSCommand in the Flash Projector.


As I said before, now the only thing I need is the file that can install the scheduled task on the user's computer. But I have no idea on how to write the code. All efforts I have made using the bat file code have failed.

Any ideas?

Best regards
MrFrostMr Frost,

I seem to be missing something here. Can you not simply include the appropriate AT command in the batch file that installs maintenance.exe?

Scheduling a job for execution is a one shot deal. Once scheduled, a job will run at the scheduled time and the schedule will be updated to reflect the next time to be run (ad infinitum).

Hope this helps. Hi again... the problem is twofold...

Firstly, I was not sure that using the AT command would be possible in a bat file since I tried prograsmming it but it alwys turned out wrong. Now that you've answered that question, it brings be to the second one.

Secondly, what should the code look like? After all my trying, I'm fairly convinced that I don't have a clue what I'm doing. Any pointers?

Also... I have access to a bat2exe program... do you recommend converting the file to exe? Or perhaps it doesn't make any difference?

Best regards
MrFrostBasically a installation file is just a REVERSE of what you did to create the install disk.

Code: [Select]
md C:\Program Files\Maintenance
copy Maintenance.exe C:\Program Files\Maintenance
copy flash1.exe C:\Program Files\Maintenance
copy flash2.exe C:\Program Files\Maintenance
AT 8:00PM /every:15  "C:\Program Files\Maintenance\Maintenance.exe"


Obviously this is very crude. If the flash files go into a different directory than the maint program you would need to create the directory ahead of the copies.

Using a directory list of the install disk will give you the files locations for the first paramter of the copy (best not to hardcode a drive). The second parameter of each copy would be where you want the files after the install.

If the disk you're referring to is a cd, you can also create an autorun.inf file on the disk which will kick everything off and all your users would need to do is insert the disk.

autorun.inf:
Code: [Select]
[autorun]
open=yourinstallprogram.bat


Many ways to do this from simple to complex. Best thing is to have your batch file do everything you would have to do if you were installing it manually (file by file).

Hope this gives you some ideas. YESSSSSSS!!!!

It works perfectly. I couldn't believe that it was this simple, I was sure that there had to be some command before the whole AT command string. I'm such an idiot, I should have tried it all along.

Sindewinder, you're the best!  I've added you into the credits  on the maintenance interface. PM me with your email for screenshots :)

355.

Solve : new to batch files?

Answer»

ok i am learning to make batch files and i was bored and i desided to see if i could make a batch file to run my aim,msn messenger and yahoo messenger all at the same time, but for some reason the yahoo messenger will not work, i am running windows xp pro and this is the code:

echo off
:start

:aim
start aim.exe
GOTO msn

:msn
start msnmsgr.exe
goto yahoo

:yahoo
start ypager.exe
exit
:end

i am new so this might be a stupid question sorry

p.s. i am aware of programs like trillian and i don't realy want to use it or any others, i just want to be able to start all three programs at the same time, this is simply just to see if i can do it, so its not realy too important, but it has been bugging me becuase i can't get it

thanks in advance for any helpIt would have been HELPFUL if you had posted an error message or any other indication of why it failed.

The system may not be able to FIND YPAGER (not in current directory or a directory on the PATH). Either include a path on the start COMMAND or use a CHDIR (CD works too) command before issuing the START YPAGER.EXE.

i got it, i didn't think of the cd command untill you mentioned it thank you


this is wat i changed the code to:

echo off
:start

:aim
cd\
cd program files
cd aim
start aim.exe
goto msn

:msn
cd\
cd program files
cd msn messenger
start msnmsgr.exe
goto yahoo

:yahoo
cd\
cd program files
cd yahoo!
cd messenger
start ypager.exe
exit
:end


and it works fine now

thanks againok well i ran into another problem, this should be the last for awhile i hope:

ok well wenever i TRY to use the start command to start a program that has a space in the name such as "space test.txt" it gives an error saying it can not find the file called space, this is the code i have been using:

start space test.txt

i have also tried:

start "space test.txt"
witch just opens command prompt with the root to the batch file but it doesn't open the .txt file

is there anything i can do to get it to pick up on the space?

thanks again in advanceYou had the right idea about the quotes. Non-executable file types need to be opened with another program (usually the program that created them). Check your file associations for text files (TXT extensions) and see what program is setup to open it.

My Computer-->Tools>--Folder Options-->File Types

Scroll down to TXT and see what's listed. The program assigned to TXT files may no longer be on your system.

Just my 2½ cents worth. thanks


but wat i mean is, when i run a program with command prompt it opens up like normal if i had clicked on it with my mouse, i am trying to acheive the same thing,

but i will just keep trying things, and hopefully i will get it working

thanks againo sorry, when i said program i meant all things, like .wma and .txt and .jpg and others
Code: [Select]echo off
rem this will open any file with the default program

"file name.extention"

exit
http://wow Code: [Select]echo off
rem this will open any file with the default program

"file name.extention"

exit


Good Luck
         Sigma thanks i got it

356.

Solve : Can 2 threads run simultaneously in HT processor??

Answer» HAI,

     Can anyone explain the following?

     Can two threads run simultaneously in Intel
     PENTIUM 4  Processor with Hyper Threading, BASE PC
     (Windows 2000 OS) without timeslicing???I'm not sure what PIV means, but this site will explain all.

Hyperthreading

Good reading on a cold NIGHT.
357.

Solve : Testing Strategy, Test Cases?

Answer»

Hi,

Do anyone have examples of a Testing Strategy or Test Cases ? Doing Testing for HNC and didn't get any examples or told what these are so if anyone can tell me what they are or GIVE me an EXAMPLE that WOULD be great,

thanks

358.

Solve : Help fine tuning batch file?

Answer»

im having TROUBLE setting my default printer depending on the IP address of my machines. Below is the code i have so far and i was wondering if anyone new where i was GOING WRONG.


echo off
if %ip%==192.168.32.144 RUNDLL32 PRINTUI.DLL,PrintUIEntry /y /N "A4 Black & White"

359.

Solve : Transforming image to text?

Answer»

Hi, I'm trying to make a program in VISUAL Basic 6.0 that will be able to take a picture and break it into text. I also want it to be as SMALL a file as possible so I'm trying to convert the IMAGE into GREYSCALE with 10 shades of light (white to black) and each pixel is represented by a number 0-9. If anybody has any IDEA how to do this it'll be a huge help. Thanks

360.

Solve : Text size some how changes on users computers?

Answer»

Hello Everyone,

I hope I'm posting this in the right forum. I have a problem with a VB.net application where out of THOUSANDS of users, only the people at two SPECIFIC COMPANIES experience extra large text that displaces other objects and makes things  ppear where they shouldn't. I am clueless as to how to fix this. I can't even recreate it on my side. If anyone has  xperienced SIMILAR problems I would greatly appreciate HEARING how you fixed things.

Paul

361.

Solve : DOS Batch File text processing query?

Answer»

Can anyone tell me how to extract some information contained in a text file called dircount.txt and place it in an environment variable ? I want to be able to extract the number 5 from the text file contents as shown below. I want to do this using DOS batch files.

The file contents of dircount.txt is as follows;

---------- DIRLIST.TXT: 5


This is OS dependent. The easiest WAY is to parse the line by reading it and defining the parsing template with the for /f instruction.

If your OS does not support the /f switch you may be SOL.

Hope this helps. Hmm THANKS I was wondering about that command. I'm using Windows 98 - DOS  It does seem to support the command, but UNFORTUNATELY not the /f parameter

:/  

cheers
check out what it has though, sometimes you will find that under different versions there is different parts to it that accomplish the same thing, such as instead of /f it MIGHT be something else... (annoying but TRUE)

362.

Solve : Send file as an attachment from the command line?

Answer»

Is there any way to send an email attachment from the command line?  I have tried Blat and have used it on our LAN but it dies during dial up connection for our remote clients.  There must be a way to send an email attachment from the command line by using vbscript or jscript.  Any HELP with this would be greatly appreciated.Code: [Select]
Set objEmail = CreateObject("CDO.Message")
objEmail.From = "FromAddress"
objEmail.To = "ToAddress"
objEmail.Subject = "Subject"
objEmail.Textbody = "Body"
objEmail.HTMLBody= "HTML Code Goes Here"
objEmail.AddAttachment "FileName Goes Here"
objEmail.Configuration.FIELDS.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "SMTPServerName"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send


All fields must be quoted. Change From & To Address, Body and Subject; HTMLBody parameter is optional, delete if not needed; AddAttachment is name of file to attach; SMTPServerName is your mail server, CHECK with ISP if necessary. The rest of the parameters should not be changed.

Save script with a vbs extension and run as:

cscript scriptname.vbs

Good luck.  Thanks for the reply.  I am getting the following error:  The transport failed to connect to the server.  
My SMTP Server requires authentication - I think this why I received the error.  How would I code this information.Are you using your network server for mail or a web server? If your ISP needs credentials, you may not want to script this, since everything sent out is text. On the other hand, if you need to send data to a secure page (better security), you would need to know the form name, the id and password field names in order to script your browser prior to sending the email.

I'm a little suprised since ISP mail servers rarely ask for credentials when sending mail. Tells us more about your mail server. Note: If you're using Outlook, you'd need to script Outlook for this, not the browser.

Let us know.  Thanks for the reply.
Our email server is a network smtp server. It is a secure server and requires authentication so we have to enter a userid and password.  We use Outlook Express to send and receive our email, but we can log in through the web and retrieve it as well.  I have tried Blat to send email from the command line - it WORKS great on our network.  However when I try to use it on dialup, it dies.To the script above you might try adding:

Code: [Select] objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate ") = 0


AND/OR

Code: [Select]
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60


which will turn off any authentication and/or increase the timeout value.

The best I could find on BLAT was to use -ti 90 on the command line. Presumably this increases the time out value.

This network mail server of yours wouldn't by any chance be Exchange?

Good luck. Our E-mail software is WorldClient for MDaemon.  I have tried to utilize your suggestions and am still getting the same error.  I will try the suggestion for Blat and see if I can get it to work.

363.

Solve : Making a game..sorta?

Answer»

I had a few questions about Virtual Basic and was WONDERING if anyone could help.... To begin with I have two forms..One called children and the other called game.Game has three option buttons on it and so does game. both of them also have a label.I also have a command box.The label would be where I put the question and the option buttons where I put the answers.the command box is called answer...I want to make it so when I click the answer Paris it will log my answer and open the other form children..I TRIED doing it but I didn't know the extension for the option buttons,to link a form, or a label...I do not understand how to do this..PLEASE help..thank YouIn the click event for the Paris option, you could Unload Me and Children.Show.

There are many ways to do this THOUGH. When Me is unloaded in will fire the Unload Event for the form and you could do some processing there. If you want both forms visible, do not unload anything, but you would have to account for which form has focus and code accordingly.

Note: Me refers to the active form.

Good luck. Whenever I push play it gives me an error saying "Compil eerror: Expected Variable or Funtion."
The line Private Sub Paris_Click() is in Yellow.This is the very first line.Under that I have Unload Game And children.Show..I don't know the extension for game(which is a form) or Paris (which is a choice) I also needed to know how to log the results so they can be displayed in the end..Thanks..Well I figured out how to make it link but now I need to know how to make my results show in the ending....I messed with the msgbox but I still don't know how..Thanks for the other problem..The easiest way is to store your responses in an array and dump the array to a msgbox or another form when you want to display them. You could also use a FILE or database to hold your responses, but I/O is not one of VB's strong points and a DB is overkill.

If you do decide to use a file, define a reference to the Microsoft Scripting Runtime (Project-->References) and use the FileSystemObject to do your reads and writes.

Good luck. Could you please go into a little bit more detail about the two ways..I wated it to store the USERS answers and then display them back...According to what they pick..Thanks..Sorry Im new at thisA forum may not be the best way to learn VB. A general overview would be:

1. Create a public array
2. Have each event handler update the array with the question number and the answer
3. Iterate the array to a msgbox at the end

OR

1. Create a public array
2. Create a pubic sub to update the array
3. Have each event handler pass the Q&A to the sub, which updates the array (all the code for the array update is isolated)
4. Iterate the array to a msgbox at the end

If this is a multiplayer game, you would also have to have an array for each user or make room in your array for a userid.

An array is the best way to go. Using a file adds complexity and would only be needed if your concerned about a power failure.

I made a group of arrays like this....
Dim Where(3) As String

Where(0) = "You are going to goto Switzerland for your honeymoon with"
Where(1) = "You are going to goto Hawaii for your honeymoon with"
Where(2) = "You are going to goto Paris for your honeymoon with"

Dim WithWho(6) As String
WithWho(0) = "Muqdisa and have "
WithWho(1) = "Marina and have"
WithWho(2) = "Sadaf and have"
WithWho(3) = "Suman and have"
WithWho(4) = "Balqis and have"
WithWho(5) = "Ruccsana and have"

Dim Children(3) As String
Children(0) = "1 child :) ENJOY!"
Children(1) = "2 children :) ENJOY!"
Children(2) = "3 children :) ENJOY!"


I have 4 forms.... Where, WithWho,Children,and Results
I put the above Array in Results...In the form Where there are three option button(Switzerland,Hawaii,Paris) In the Form WithWho there are numbers 1-6  done by option buttons.. 1-6 are peoples names...My last form is children which are option buttons 1-3..How would I make this program so that if someone clikcs on Paris from the form Where, 1 from the form WithWho, and 1 from the form children it will display You are going to goto Paris for your honeymoon with Muqdisa and have 1 child :) ENJOY!Define RESULTS as an array. In the _click event for each button, push the answer into the array. (ie. If Paris is chosen for question 1, then result(0) = "Paris", if Hawaii is chosen then result(0) = "Hawaii". If question 2 is answered with "Muqdisa" then that goes into result(1).

Once all the questions are answered, you can build the output, which is mostly a literal.

"You are going to goto " result(0) & " for your honeymoon with " & result(1) & " and have " & result(2) & " child."

The literal could be dumped into a label on the form, a msgbox, a file, sent across the net. Your choices are limited only by your imagination.

Good luck.

364.

Solve : languages?

Answer»

How would I go about CREATING my own language/compiler?What do you know so far?

www.google.com
"compiler" I know concepts involved, but not the actual coding. What would be a GOOD language to write the compiler with?C+ or C++ok, now an interpreter would be easier, a compiler has to COMPILE a set of instructions and then run  them, as opposed to executing one statement as it comes to it, how do I GET the compiler to generate an exe, the binary CODE?You guys need to get a book, or take a web based tutorial or something!

Convert your parsed language into machine code. (Or if you want to do it the easy way, convert it into an assembly syntax and assemble it with your favorite assembler)

Of course theres more to it than that but that's a rough sketch and most likely the most explination I think you will get.Thanks

365.

Solve : Logging into Windows XP Home?

Answer»

I had a few questions about Visual Basic and was wondering if anyone could help....to begin with I made a program that asks for a user/password...It had no toolbar so you cant close it..I needed help to make it so that you cant do anything ( WINDOWS KEY or Ctrl+Alt+Del) To get out of it...I WANTED to make this my Screen when I log on to windows replacing the other one..I've seen many people do this but don't know how.I heard you have to replace some file or something...I also needed the program to be like this: If you log on with the main(admin) pass then you have full rights while if you log on with a temp user and pass you only have 10 MINUTES to do what you want (internet acces restriced) before it shuts down..So I NEED help with the timer in VB and also how to make a Temp user and pass...I have a windows XP home...Any help will be appreciated...Thanks

366.

Solve : How to make an object move a direction?

Answer»

I'm working in Visual Basic 6.0 and I'm trying to figure out how to MOVE an object a distance based on a number of degrees (Like moving an object 1 unit to the left, except left=80Degrees and I want it to be able to calculate all 360 degrees.)
ANYBODY know how to do this, prbably involves trig.Not necessarily trig, but a little geometry wouldn't HURT. This is too involved to answer in a FORUM, whole books have been written on the subject.

You can either reference the VB openGL API 1.2 in your program and go from there (difficult) or use a Picturebox and use the PSet method to loop thru mapping coordinates and redrawing your object (less difficult).

Computers are very fast, so you'll probably need a timer event to slow things down to give the illusion of a smoother movement.

Good LUCK.

367.

Solve : .exe file?

Answer»

::) I NEED help viewing a EXE file as text? This file is a utility file on a Domain? Anybody know how to send the results as text for viewing?What do you mean???  

You can use type at the command prompt e.g. type filename and the result will be what the prog can interpret into text but not a LOT can be interpreted, the rest will look like mumbo jumbo or spaces.   You could try a hex editor & that will ALLOW you to alter the .exe prog but do so at your own peril.  .exe files "cannot" be retro'd to the source coding which has been compiled & linked to produce the .exe

368.

Solve : visual basic combobox?

Answer» HELP please
i don't KNOW how to use a combobox in VISUAL basic 2005 EXPRESS edition beta
369.

Solve : IF statement in Batch File Help?

Answer»

Here is the command I'm trying to make work....


If EXIST \\TECH88\My Documents\Practice\%userdomain% (copy C:\practice\test.txt "\\TECH88\My Documents\Practice\%userdomain%") ELSE MD "\\TECH88\My Documents\Practice\%userdomain%" copy C:\practice\test.txt "\\TECH88\My Documents\Practice\%userdomain%"

My question is... can I double up the commands after ELSE?

I need it to CREATE a directory and copy a file over after that directory is created.

Can I do that together after else?  Or do I have to write the first part of the IF statement to check to see if it's created already again.  

So how do I do the MD and the COPY both after the ELSE?  Or can you not in a simple Batch file?Put the copy command on a seperate line following the IF/ElSE statement.But then it will execute even if the IF statement is true right?  

I don't want it to run if it copied once already, know what I mean?

How can I place it on a seperate line but still KEEP it apart of that IF statement?If NOT EXIST \\TECH88\My Documents\Practice\%userdomain% MD "\\TECH88\My Documents\Practice\%userdomain%"
copy C:\practice\test.txt "\\TECH88\My Documents\Practice\%userdomain%"


This is only 2 lines (line wrapping in post) with the copy command being line 2. If the target directory does not exist, it will make the directory and then copy the files. If the target does exist, it will fall through to the copy command.Ok thanks great idea!  But now I have a new problem....


This doesn't work...

IF NOT EXIST \\TECH88\My Documents\Practice\Silly (copy c:\practice\test.txt "\\TECH88\My Documents\Practice")

The folder Silly does not really exist...

But this won't work... as soon as it sees that that path does not exist on the network it says "The system cannot find the path specified." and then doesn't copy the file.

But this does work...

If NOT EXIST c:\practice\test\text\silly (copy c:\practice\test.txt "\\TECH88\My Documents\Practice")

Here Test\text\silly do not exist, but it copies the test.txt file to the other computer.

So the only difference between the TWO is that one is checking to see if a path EXISTS on the other computer and the other checks to see if a path exists locally.

So for some reason I can't get it to check a bad path on the other computer only locally.  Any suggestions?UPDATE>>>>.


Solved that last problem, it works this way...


IF NOT EXIST "\\TECH88\My Documents\Practice\Silly" (copy c:\practice\test.txt "\\TECH88\My Documents\Practice")


All I changed was adding quotation marks around

\\TECH88\My Documents\Practice\Silly

It SEEMS that for some commands it wants quotes, and other times it doesn't care.   But that fixed it.

Thanks for your help!

370.

Solve : Log in Program...?

Answer»

I had a few questions about Visual Basic and was wondering if anyone could help....to begin with I made a program that asks for a user/password...It had no toolbar so you cant close it..I needed help to make it so that you cant do anything ( WINDOWS key or Ctrl+Alt+Del) To get out of it...I wanted to make this my SCREEN when I log on to windows replacing the other one..I've seen many PEOPLE do this but don't know how.I heard you have to replace some file or something...I ALSO needed the program to be like this: If you log on with the main(admin) pass then you have full rights while if you log on with a temp user and pass you only have 10 minutes to do what you want (internet acces restriced) before it shuts down..So I need help with the TIMER in VB and also how to make a Temp user and pass...I have a windows XP HOME...Any help will be appreciated...Thanks

371.

Solve : working with Radiobutton in JBuilder2005?

Answer»

Hi everyone. I am USING JBuilder 2005 on windows XP Professional. I shall be very thankfull to you, if you can let me know how to work with radiobutton while using JBuilder. I have created two radio buttons. Add them in a buttongroup and when I RUN my program they behaves exactly like radio buttons. Next, how to add code to them? I do hope that you have GOT my point.
Bye....

372.

Solve : Detecting System Shutdown?

Answer»

Is there anyway in visual basic I can detect if the my PC is shutting down,is there any code I can use?I'd like my vb application to detect my computer's state,if it is shuting down,please I really need a very QUICK help,thanks for the time....Trying monitoring the SYSTEM event log. When event #1074 is posted, you'll know shutdown has begun.

Note: The actual event # may be different on various OSes. 1074 applies to XP.

Hope this helps. Yes I am using XP but  how will I use it?What is the specific code to do?Sorry I am not yet familiar with such detection,please tell me how can I do it....Can you give a quick reply I have deadline this day so I really need to ACCOMPLISH this THING....Hoping for understanding...thanks..
You might define a Form_QueryUnload event to determine what is causing your application to shut down.  A value of 2 means that the OS is shutting down. It's problematic what you would do with this piece of information.

You can ALSO do this with a simple VBScript:

Code: [Select]
Set WshShell = CreateObject("WScript.Shell")
n = 0
While n = 0
    FoundShutdown = WshShell.AppActivate("System Shutdown")
    If FoundShutdown Then
         WScript.Echo "Shutdown started"
    End If
    WScript.Sleep 500
Wend


If you really want to go all out, you can use the WMI service to query the event log directly.

Let us know how you make out.

373.

Solve : Delete multiple files?

Answer»

Can anyone help me?? What I am trying to do is Wright a Vbscript that will loop through a LIST of files and delete them. Does any one have any suggestion? I was trying to use loop but I can’t get it to work.Where is this list of files coming from? If an external source, you can read the file and delete the files as you GO. If coming from the same directory you can get a collection of file names and loop thru the collection.

This example will loop thru a collection of files from a directory. There is no filter to keep files you may need so be very careful.

Code: [Select]
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set f = fso.GetFolder(folderspec)
  Set fc = f.Files
  For Each fs in fc
     fso.DeleteFile fs, TRUE
  Next


Just change folderspec to SOMETHING valid.

Hope this HELPS.

374.

Solve : How to automatically overwrite???

Answer»

This is the first BATCH file I have written. It is a simple xcopy routine, moving two files from ONE location to another over night as part of a back-up.
When I ran it under Win98 the files were overwritten with no intervention.
I now use XP Pro and am asked if I want to overwrite Y/N/ALL for each file.

Which COMMAND overwrites without asking?

Thanks in advanceTry USING the /y SWITCH for XCOPY.

Thanks Sidewinder.

Easy when you know how , eh!  

Nel

375.

Solve : For geek-9pm :D?

Answer»

FORTRAN IDE BUILT on ECLIPSE!

HTTP://www.eclipse.org/photran/


What can I say!

376.

Solve : Linking issues while migrating code from SUN CC 4.3 to SUN CC 5.8?

Answer»

Hello,

I am migrating code written in SUN CC 4.3 to SUN CC 5.8
I have compiled entire code with SUN CC 5.8 with -compact=4 option ,on machine with OS SunOS 5.8 Generic_Virtual sun4v sparc sun4v.

during linking phase i am facing issues like

(cd msggen; MAKE CG="-fast -O3 -compat=4 -lC -features=extensions -i" all)
/opt/SUNWspro/bin/CC -o msggen msggen.o licensemessage.o ../../../../libs/lib/libgeneral.a
Undefined first referenced
symbol in file
cerr ../../../../libs/lib/libgeneral.a(string.o)
unsafe_ostream::operator&LT;<(long) ../../../../libs/lib/libgeneral.a(string.o)
operator delete(void*) msggen.o
operator new(unsigned INT) licensemessage.o
Iostream_init::Iostream_init(void) msggen.o
Iostream_init::~Iostream_init(void) msggen.o
istream::operator>>(char*) ../../../../libs/lib/libgeneral.a(string.o)
setw(int) ../../../../libs/lib/libgeneral.a(string.o)
unsafe_ostream::outstr(const char*, const char*) ../../../../libs/lib/libgeneral.a(string.o)
_ex_rethrow_q msggen.o
ld: fatal: Symbol REFERENCING errors. No output written to msggen

I felt like these issues are due to the standard header files. I am including the headers which comes with SUN CC 5.8 and I am using ROGUE Wave rwav/ver09.1.

I am not getting any pointers to solve this issue,any pointer will be highly appriciated.

Thanks in advance,
Revathi R
 
 

377.

Solve : Password Validation?

Answer»

So I have an MS Access db application that I'm working on. The part that i need help with, is validating password strings for the new user function. Simply, the add user form passes all the info to the SQL db. I ran into the problem of password strings containing symbols not wanting to work at all, though it WOULD pass to the db just fine, wouldn't allow logging in with them. Also, if the initial character was a number, it didn't like that either. As long as these two conditions weren't there, then it works perfectly. Creates the user and their credentials are READY for use in <30s. But if it starts with numbers or contains symbols - merp. no work. 

So, the thing that I'm going for is one of two option; A) a functioning string VALIDATION technique that find prohibited characters in string, and checks to make sure the first char is alpha only; B) a way to get it to accept any password regardless of what characters it contains (no nulls and 6+ char).

I started trying us instr and like in if statements, but neither of them works right. They don't stop the process or EVEN display their msgbox correctly. Even though they should, they don't.

Anyway, all help is appreciated. Alright, I partially figured this out... just a little more tuning needed.

Code: [Select]Option Compare Database
'textbox check function
Public Function IsAlphaNum(ByVal sString As String) As Boolean
     If Nos sString Like "*[!0-9A-z]*" Then IsAlphaNum = True
     ' This is the part that needs tuning.
     If Not sString Like "#*" Then IsAlphaNum = True
     'Basically this is attempting to prohibit the first char from being a number.
End Function
'----------------------
Private Sub Test_Click()
If IsAlphaNum(Me.BoxTest) = False Then
     MsgBox "Password must be alphanum and can't start with a num."
     Exit Sub
Else
     MsgBox "password accepted."
End If
End Sub


The code, as shown above, doesn't stop numbers from being the first char. It blocks symbols just fine, but not initial numbers... I've tried a few different methods to get it to accept both if statements, but it hasn't wanted to work. I've tried Or, And, AndAlso (which i think it correct), and even a nested-if... none of them seem to want to work, so i must be doing something wrong... 

Thanks in advance.
 - kyle_engineerWow... so sorry I solved my own problem... but here's what worked for me! I hope people in the community use this.

Code: [Select]Option Compare Database
'---------------------------------------------------------
'textbox check function
Public Function IsAlphaNum(ByVal sString As String) As Boolean
Dim strFirstChar As String
     If Not sString Like "*[!0-9A-z]*" Then IsAlphaNum = True
     strFirstChar = Left(Me.BoxPassword, 1)
     If IsNumeric(strFirstChar) Then IsAlphaNum = False     
End Function
'----------------------
Private Sub Test_Click()
If IsAlphaNum(Me.BoxPassword) = False Then
     MsgBox "Password must be alphanum and can't start with a num."
     Exit Sub
Else
     MsgBox "password accepted."
End If
End Sub

378.

Solve : Game Coding Starter?

Answer»

I was wondering if anybody can link me to like a started pack for GAME coding. Like all the software I need and recommend a language. I already know a bit of java, but I heard c# is really good. Any help is appreciated THANKS!You can keep you Java skills. Yes,Java s having some  times right now. But it is a security issue, not about the power of Java.

Do you want free material? Some institutions TEACH video game  programming in  Java. Just Google it.
Here is one you will FIND:

Learn Video Game Programming. Get Started at Westwood College


I have already googled this stuff, but i was looking for more opinions/help

379.

Solve : Please HELP with '.xml' file extension!?

Answer»

Hi, first off, I simply wanted to THANK all of you for taking the time to look into this minor problem. A while BACK, I did some meandering on my laptop and aimlessly clicked through different programs, checking, un-checking, deleting, and what not. Now, I recently purchased Sony's ACID Music Studio 9.0, every time I MAKE an attempt to double-click the '.xml' files (which I believe are also the music riffs) I get the following:

     "This file cannot be added to ACID Music Studio projects. The File type may not be supported.

     Would you like to open the file using the associated application?"

 I have also made an attempt to click and drag the '.xml' files into the music timeline, but nothing happens!
 I do not know if it was because of my whimsical clicking through my laptop, and I cannot seem to remember what I've DONE to my laptop. I have Windows 7 with familiar experience with computers.
 I have also made searches for help through online search engines to no avail and now have pretty much lost all hope! So, I find myself here.
 Could anyone possibly help me find a way to get my laptop to get these '.xml' files to work? Because, I surely want the best out of my purchase, and I want to be well on my way into making music!
 Once again, I thank all of you for your views and help into this situation Have a spectacular one!In the years I have used PCs, I never had a good reason to run a .XML file.
The XML is a special  computer code  used by programs. Seldom, if ever would a user want to do anything with it.
It may or may not be a part of the music. Who knows?
Quote

As of 2009, hundreds of document formats using XML syntax have been developed,[7] including RSS, Atom, SOAP, and XHTML. XML-based formats have become the default for many office-productivity tools, including Microsoft Office (Office Open XML), OpenOffice.org and LibreOffice (OpenDocument), and Apple's IWORK. XML has also been employed as the base language for communication protocols, such as XMPP.
http://en.wikipedia.org/wiki/XML
From the above you can see it is not tied to music. It is a common code used to 'glue'  pats of internal stuff that makes sense only to advanced software people.

Do not alter the XML things. For more information, rared the documentation of
 Sony's ACID Music Studio 9.0,
http://www.sonycreativesoftware.com/download/manuals/acidfamily
Hope this helps. 
Please come back an d let all know if you like ACID Music Studio.
  Geek-9pm, I appreciate your reply! I'll take a look into it! And, I'll definitely let you all know how well ACID Music Studio is! Be safe!
380.

Solve : help me..why my program get"expected class delegate enum interface or struct"???

Answer» USING System;
using System.Collections.Generic;

using System.Runtime.Serialization.Formatters .Binary; //namespace to use Serialization
 
class Record
{     
    private string name;

    public string Name
    {
        get { return name; }
        SET { name = value; }
    }
       
    private double homeNumber;

    public double HomeNumber
    {
        get { return homeNumber; }
        set { homeNumber = value; }
    }

    private double mobNumber;

    public double MobNumber
    {
        get { return mobNumber; }
        set { mobNumber = value; }
    }

    private string address;

    public string Address
    {
       get { return address; }
       set { address = value; }
    }

    // Default Constructor
    public Record()
    {
       this.name = string.Empty;
       this.homeNumber =  0000;
       this.MobNumber = 0000;
       this.address = "Fake";
    }

    // Parameterized Constructor
    public Record(string n, double hNum, double mobNum, string add)
    {
       this.name = n;
       this.homeNumber = hNum;
       this.mobNumber = mobNum;
       this.address = add;
    }

    public void print()
    {
      System.Console.WriteLine("The Name Is : " + this.name);
      System.Console.WriteLine(" Home Phone No. Is : " + this.homeNumber);
      System.Console.WriteLine(" Mobile Phone No. Is : " + this.mobNumber);
      System.Console.WriteLine(" Address Is : " + this.address);
    }
}

// Add a new Record first to ArrayList(recordList) and then in file
public void addNewRecord()
{
   
   recordList = new ArrayList();
   records = new Record();

   // Here Adding Record to ArrayList         
   recordList.Add(new Record("osama", 36887676, 3333003212,"Lahore"));
   recordList.Add(new Record("saad", 4234234, 33330065656, "Ali Park"));
   recordList.Add(new Record("bilal", 2123456, 0456123232, "Multan"));
   recordList.Add(new Record("maryam", 1312312, 33330032121,"Karachi"));
             
   FILESTREAM fs = new FileStream("data.txt", FileMode.Create, FileAccess.Write);
   BinaryFormatter bf = new BinaryFormatter();

}

// Loads the all reocrds from file and add to ArrayList(recordList)
public void loadRecord()
{           
   
recordList = new ArrayList();
FileStream fs = new FileStream("data.txt", FileMode.Open, FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter();
    try
      {
        while (fs.CanRead)//Reading the FileStream
        {
           Record R = (Record)bf.Deserialize(fs);//De-Serialize the each object
           recordList.Add(r); //And Add to ArrayList
           r.print(); //Printing the each record from the file to console
        }
      }
       catch (Exception e) {}             
   fs.Close();
}

// Saving the record to file.
public void saveRecord()
{
     
   FileStream fs = new FileStream("data.txt", FileMode.Create, FileAccess.Write);
   BinaryFormatter bf = new BinaryFormatter();

   for (int i = 0; i < recordList.Count; i++)
   {
       record = (Record)recordList;
       bf.Serialize(fs, record);
       fs.Flush();
   }
           
 fs.Close();   

     
}

public void enterInPhoneDirectory()
{
   
   record = new Record();
   loadRecord();

   Console.WriteLine("Enter Your Home Number/ Mobile Number : ");
   double number = double.Parse(Console.ReadLine()); // User to enter his/her Home/mobile no.

   for (int j = 0; j < recordList.Count; j++)
   {
       record = (Record)recordList[j];
   
        if (record.HomeNumber == number || record.MobNumber == number)
         {
            Console.WriteLine("Welcome , " + record.Name.ToUpper());
            record.print();
       
            Console.WriteLine("Press 1 to Change Home Number");
            Console.WriteLine("Press 2 to Change Mobile Number");
            Console.WriteLine("Press 3 to Change Address");
            Console.WriteLine("Press 4 to exit this menu");
            int option = int.Parse(Console.ReadLine());
                 
              switch (option)
               {
                     case 1:
                       Console.WriteLine("Enter Your New Home Number");
                       double hNum = double.Parse(Console.ReadLine());
                       record.HomeNumber = hNum;
                     break;

                     case 2:
                       Console.WriteLine("Enter Your New Mobile Number");
                       double mNum = double.Parse(Console.ReadLine());
                       record.MobNumber = mNum;
                     break;
                           
                     case 3:
                       Console.WriteLine("Enter Your New Address");
                       string add = Console.ReadLine();
                       record.Address = add;
                     break;
                           
                     case 4:
                       Console.Clear();
                       Main(new string[]{"s"});
                     break;
              }
                                   
          saveRecord();
        }             
    }
 }

public static void Main(string[] args)
{


    // Front end menu
    Console.WriteLine("----------Menu----------");
    Console.WriteLine("Press 1 to enter number (home / mobile)");
    Console.WriteLine("Press 2 to exit");

    int input = int.Parse(Console.ReadLine());

    switch (input)
    {
         case 1:
            enterInPhoneDirectory();
         break;

         case 2:
            Environment.Exit(0);
         break;
    }
 }
Move of the methods are instance methods that aren't declared inside a class definition (and are thus invalid). Several variables aren't declared anywhere, and the aforementioned methods are instance methods rather than static methods.

Fixed VERSION:
Code: [Select]using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace testapp
{
    using System.Runtime.Serialization.Formatters.Binary; //namespace to use Serialization
    public static class Program
    {
        static ArrayList recordList;
        static Record records;
        class Record
        {
            private string name;

            public string Name
            {
                get { return name; }
                set { name = value; }
            }

            private double homeNumber;

            public double HomeNumber
            {
                get { return homeNumber; }
                set { homeNumber = value; }
            }

            private double mobNumber;

            public double MobNumber
            {
                get { return mobNumber; }
                set { mobNumber = value; }
            }

            private string address;

            public string Address
            {
                get { return address; }
                set { address = value; }
            }

            // Default Constructor
            public Record()
            {
                this.name = string.Empty;
                this.homeNumber = 0000;
                this.MobNumber = 0000;
                this.address = "Fake";
            }

            // Parameterized Constructor
            public Record(string n, double hNum, double mobNum, string add)
            {
                this.name = n;
                this.homeNumber = hNum;
                this.mobNumber = mobNum;
                this.address = add;
            }

            public void print()
            {
                System.Console.WriteLine("The Name Is : " + this.name);
                System.Console.WriteLine(" Home Phone No. Is : " + this.homeNumber);
                System.Console.WriteLine(" Mobile Phone No. Is : " + this.mobNumber);
                System.Console.WriteLine(" Address Is : " + this.address);
            }
        }
       
        // Add a new Record first to ArrayList(recordList) and then in file
        public static void addNewRecord()
        {

            recordList = new ArrayList();
            records = new Record();

            // Here Adding Record to ArrayList         
            recordList.Add(new Record("osama", 36887676, 3333003212, "Lahore"));
            recordList.Add(new Record("saad", 4234234, 33330065656, "Ali Park"));
            recordList.Add(new Record("bilal", 2123456, 0456123232, "Multan"));
            recordList.Add(new Record("maryam", 1312312, 33330032121, "Karachi"));

            FileStream fs = new FileStream("data.txt", FileMode.Create, FileAccess.Write);
            BinaryFormatter bf = new BinaryFormatter();

        }

        // Loads the all reocrds from file and add to ArrayList(recordList)
        public static void loadRecord()
        {

            recordList = new ArrayList();
            FileStream fs = new FileStream("data.txt", FileMode.Open, FileAccess.Read);
            BinaryFormatter bf = new BinaryFormatter();
            try
            {
                while (fs.CanRead)//Reading the FileStream
                {
                    Record r = (Record)bf.Deserialize(fs);//De-Serialize the each object
                    recordList.Add(r); //And Add to ArrayList
                    r.print(); //Printing the each record from the file to console
                }
            }
            catch (Exception e) { }
            fs.Close();
        }

        // Saving the record to file.
        public static void saveRecord()
        {

            FileStream fs = new FileStream("data.txt", FileMode.Create, FileAccess.Write);
            BinaryFormatter bf = new BinaryFormatter();

            for (int i = 0; i < recordList.Count; i++)
            {
                var record = (Record)recordList[i];
                bf.Serialize(fs, record);
                fs.Flush();
            }

            fs.Close();


        }

        public static void enterInPhoneDirectory()
        {

           var record = new Record();
            loadRecord();

            Console.WriteLine("Enter Your Home Number/ Mobile Number : ");
            double number = double.Parse(Console.ReadLine()); // User to enter his/her Home/mobile no.

            for (int j = 0; j < recordList.Count; j++)
            {
                record = (Record)recordList[j];

                if (record.HomeNumber == number || record.MobNumber == number)
                {
                    Console.WriteLine("Welcome , " + record.Name.ToUpper());
                    record.print();

                    Console.WriteLine("Press 1 to Change Home Number");
                    Console.WriteLine("Press 2 to Change Mobile Number");
                    Console.WriteLine("Press 3 to Change Address");
                    Console.WriteLine("Press 4 to exit this menu");
                    int option = int.Parse(Console.ReadLine());

                    switch (option)
                    {
                        case 1:
                            Console.WriteLine("Enter Your New Home Number");
                            double hNum = double.Parse(Console.ReadLine());
                            record.HomeNumber = hNum;
                            break;

                        case 2:
                            Console.WriteLine("Enter Your New Mobile Number");
                            double mNum = double.Parse(Console.ReadLine());
                            record.MobNumber = mNum;
                            break;

                        case 3:
                            Console.WriteLine("Enter Your New Address");
                            string add = Console.ReadLine();
                            record.Address = add;
                            break;

                        case 4:
                            Console.Clear();
                            Main(new string[] { "s" });
                            break;
                    }

                    saveRecord();
                }
            }
        }

        public static void Main(string[] args)
        {


            // Front end menu
            Console.WriteLine("----------Menu----------");
            Console.WriteLine("Press 1 to enter number (home / mobile)");
            Console.WriteLine("Press 2 to exit");

            int input = int.Parse(Console.ReadLine());

            switch (input)
            {
                case 1:
                    enterInPhoneDirectory();
                    break;

                case 2:
                    Environment.Exit(0);
                    break;
            }
        }
    }
}
381.

Solve : header link?

Answer»

I am a BEGINNER programmer. I am STUDYING style sheets. My question is...if I have the image of a header that I want to use that I have placed  in an IMAGES folder, what is the link format to link to it and where do I put the link? In the header, the css folder or the body?

Thank you
oprime77Two weeks old I know but:

Any WINDOWS or Unix-style directory browsing format works with CSS.
The easiest path to use for the image would just be: "images/mypic.jpg"

Depending on whether you're using HTML/CSS or whatever, the format for displaying it will be different.

382.

Solve : c# add new line to listbox?

Answer»

What my program does and is download a string from and uploaded FILE. I need to ADD a new line to the listbox for every line of string in the downloaded string.

so for example

downloaded string =
firstlineofstring
secondlineofstring

I need to add
listbox1.items.add(downloaded string); //add line 1 of string,  add line 2 of string,  add any other lines

if I just do listbox1.items.add(download string); it will wrap the text and not PAY attention to the newline thats in the string.


so the listbox will look like:

firstlineofstring
secondlineofstring


any help WOULD be great.
If I understand what you're trying to do, you'll have to SPLIT the downloaded string first before adding it.
Something like:
Code: [Select]listbox1.Items.AddRange(downloadedString.Split('\n'));if AddRange is unavailable (I don't remember if you can use it on listbox item collections), then you can alternatively loop through the lines and add each one:
Code: [Select]foreach (string line in downloadedString.Split('\n'))
   listbox1.Items.Add(line);

You may also need to tweak the arguments to the String.Split method above (see http://msdn.microsoft.com/en-us/library/y7h14879.aspx) Quote from: TechnoGeek on March 25, 2013, 05:01:48 PM

If I understand what you're trying to do, you'll have to split the downloaded string first before adding it.
Something like:
Code: [Select]listbox1.Items.AddRange(downloadedString.Split('\n'));if AddRange is unavailable (I don't remember if you can use it on listbox item collections), then you can alternatively loop through the lines and add each one:
Code: [Select]foreach (string line in downloadedString.Split('\n'))
   listbox1.Items.Add(line);

You may also need to tweak the arguments to the String.Split method above (see http://msdn.microsoft.com/en-us/library/y7h14879.aspx)
Second one worked, thanks a lot.
383.

Solve : Problem in changing Date and Time...?

Answer»

I want to change my Date and Time...
Because,when i search via Facebook and Twitter.
It always doesn't appear normally,it is all because of wrong setup of Date and Time..

When i was TRYING to change it and this will be appear on my screen...

"You do not have a proper privilege level to change the System time"

what will im going to do???

PLEASE ANYONE help me regarding to my problem...
Tnx a lot.
  My OS was WindowsXP..
and i need to fix this for my NetCafe..
my COSTUMER wants to view some site...
but it was disable..

please help me...

  Quote

"You do not have a proper privilege level to change the System time"

You need to be the admin of the local computer to change the system time. Is this your computer in which you should be the admin, but are not?
384.

Solve : java working unexpectedly?

Answer»

I want the cyan rectangle to move but it don't.

Code: [Select]package circlegame.MAIN;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.geom.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class game extends JFrame {

Rectangle R1  = new Rectangle(30,50,30,40);
Rectangle r2  = new Rectangle(300,150,30,40);
move1 m1 = new move1();
private JPanel contentPane;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
game frame = new game();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//thread
public class move1 extends Thread
{
public void run(){
//infinate loop
while(true)
{
try
{
repaint();
Thread.sleep(100);
}
catch(Exception e)
{
break;
}
}
}
}
public void paint(Graphics frame){
super.paint(frame);
frame.setColor(Color.CYAN);

frame.fill3DRect(r1.x, r1.y, r1.width, r1.height,true);
frame.setColor(Color.BLUE);
frame.fill3DRect(r2.x, r2.y, r2.width, r2.height,true);

}
public void move(){
try
{
r1.x +=(int)r1.x;
r1.setLocation(r1.x, r1.y);
}
catch(Exception e)
{
System.out.print("Error");
}
}


/**
* Create the frame.
*/
public game() {
super("Circlegame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 400, 350);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 255, 255));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
m1.start();
}

}why doesn't it work?
Quote

      EventQueue.invokeLater(new Runnable() {
         public void run() {
            try {
               game frame = new game();
               frame.setVisible(true);
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      });
* MAYBE this is correct for Java syntax, but I am use to seeing a function called that is independent of being enclosed within ( ...... ); multilines, and not structured how you have it with everything contained within a spanned multiline (  ...... ); as I highlighted.

I don't program in Java so this may be valid syntaxWell it doesn't show anything as is. I had to change the paint method to get them to show up at all:

Code: [Select]public void paint(Graphics frame){
System.out.println("paint");
//super.paint(frame);
Rectangle clip = frame.getClipBounds();
frame.clearRect(clip.x,clip.y,clip.width,clip.height);
frame.setColor(Color.CYAN);

frame.fill3DRect(r1.x, r1.y, r1.width, r1.height,true);
frame.setColor(Color.BLUE);
frame.fill3DRect(r2.x, r2.y, r2.width, r2.height,true);
}


The cyan rectangle (r1) doesn't move because the move() method is never called. add move(); before repaint() in the run method.

Quote from: DaveLembke on March 05, 2013, 05:04:41 PM
* Maybe this is correct for Java syntax, but I am use to seeing a function called that is independent of being enclosed within ( ...... ); multilines, and not structured how you have it with everything contained within a spanned multiline (  ...... ); as I highlighted.

I don't program in Java so this may be valid syntax

It's correct. In fact, the original code could be refactored to completely eliminate move1. right now they are subclassing Thread. this is bad. Don't do this. First, what they ought to be doing is creating a class that implements Runnable, and passing an instance of that class to the Thread constructor. Thread should only be subclassed if you want to add new Thread functionality, not to implement the Run method. Right now:

Code: [Select]Thread move1 = new Move1();

My version:

Code: [Select]Thread move1 = new Thread(new Runnable() {public void run(){
//infinite loop
while(true)
{
try
{
move();
//invalidate();
repaint();
Thread.sleep(100);
}
catch(Exception e)
{
break;
}
}}});

This BASICALLY moved the implementation within the class they had that derived from Thread to here. to explain more simply the part that got you confused: that would be the anonymous interface implementation feature of Java. In this case, it's implementing Runnable. A simple example:

Code: [Select]private void somemethod(Runnable runner){
runner.run();
}
private void main(String[] args){
somemethod(new Runnable(){
public void run(){System.out.println("howdy!");}
}
);
}

(Not formatted well). basically, you can use new with an interface type and define the interface implementation in-line. The DOCUMENTATION is perhaps a more heady source of information.
385.

Solve : Excel - Add ribbon toolbar to rename files based on filepath?

Answer»

Hi,

I work with thousands of pdf files that I constantly need to rename.  I have a batch file that will pull the full path of every pdf file and files in all subfolers and put it into an excel sheet, column A.  I would like to be able to have the full path in column A and type a new filename in column B, then push a button and have that actual file name change within the folder.  This was QUITE the puzzle. With the help of Microsoft Support and my own cockeyed view of scripting in general, I came up with this: a single VBScript to replace your batch file. This will recursively add full file names to column A of an Excel worksheet, create a Custom toolbar on the Excel Addins toolbar, and create a button (with a palm icon) to rename the PDF files based on column B of the worksheet.

Code: [Select]'List All Files Recursively
'
strFolder = "c:\temp"   'change to LOCAL folder

Set fso = CreateObject("Scripting.FileSystemObject")
Set fc = fso.GetFolder(strFolder).Files

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add()
Set xlSheet = xlBook.Worksheets(1)

xlRow = 0
RecurseFolders fso.GetFolder(strFolder)
ExcelStuff()

Set xlRange = xlSheet.UsedRange
xlRange.Columns.Autofit

Set xlRange = xlSheet.Columns("B:B")
xlRange.ColumnWidth = 25

xlApp.Visible = True

Sub RecurseFolders(Folder)
  Set fc = Folder.files
  For Each fs In fc
    If LCase(fso.GetExtensionName(fs)) = "pdf" Then
      xlRow = xlRow + 1
      xlSheet.Cells(xlRow, 1).Value = fs.Path
    End If
  Next

  For Each objFolder In Folder.subFolders
    RecurseFolders objFolder
  Next
End Sub

Sub ExcelStuff()
  ' Create Module & Macro
  '
  Set xlModule = xlBook.VBProject.VBComponents.Add(1)
 
  strCode = _
    "Sub NewNames()"                                                                     & vbCrLf & _
    "  Dim xlSheet As Worksheet"                                                         & vbCrLf & _
    "  Dim fso As Object"                                                                & vbCrLf & _
    "  Set fso = CreateObject(" & chr(34) & "Scripting.FileSystemObject" & chr(34) & ")" & vbCrLf & _
    "  Range(" & chr(34) & "A1" & chr(34) & ").Select"                                   & vbCrLf & _     
    "  Do Until IsEmpty(ActiveCell)"                                                     & vbCrLf & _
    "    If Not IsEmpty(ActiveCell.Offset(0, 1)) Then"                                   & vbCrLf & _
    "      Set fs = fso.getfile(ActiveCell.Value)"                                       & vbCrLf & _
    "      fx = ActiveCell.Offset(0, 1).Value"                                           & vbCrLf & _
    "      fs.Name = fx"                                                                 & vbCrLf & _
    "    End If"                                                                         & vbcrlf & _
    "    ActiveCell.Offset(1, 0).Select"                                                 & vbCrLf & _
    "  Loop"                                                                             & vbCrLf & _
    "End Sub"                                                                            & vbCrLf
     
  xlmodule.CodeModule.AddFromString strCode
 
  ' Create a new toolbar
  '
  Set cbs = xlapp.CommandBars
  Set cb = cbs.Add("Special", 1, , True)
  cb.Visible = True

  ' Create a button & assign to macro
  '
  Set cbc = cb.Controls.Add(1)
  With cbc
    .OnAction = "NewNames"
    .Caption = "NewNames"
    .ToolTipText = "PDF Renames"
    .FaceId = 51
  End with
End Sub

The script writes the VBA module script and attaches it to the worksheet. Check Macro Security on the Excel Developer toolbar. The "Enable All Macros" radio button must be selected and the "Trust Access To VBA Project Object Model" checkbox must be ticked. If you save the workbook, use file type of "Excel Macro-Enabled Workbook (*.xlsm).

Save the script with a VBS extension and run from the command line as: wscript scriptname.vbs. When the script runs, column A is filled with the file names. After you finish filling column B with new names, click the Excel Add-Ins toolbar and in the Custom Toolbars, click the hand icon. The renames iterates column A until it finds a blank cell then quits. If column B is empty, the file in column A is not renamed.

I wasn't sure how to end everything, so after the renames, the spreadsheet just sort of lies there. Feel free to manually close it.

Good luck.

Thanks for the quick response, Sidewinder, I greatly appreciate all the work you put into this!  So far, I've been able to execute the command which entered all of my filenames in column A as is supposed to.  I typed a few new names in column B for testing purposes (do I have to include any of the path or .pdf extension? or can it just simply be a "name"?)

When I click the add-ins toolbar and the palm icon, I get a vb compile error, highlighting the set "fs =" part of the Sub NewNames () script.  The error says "Variable not Defined". 

In terms of 'feature requests', is it possible to have an address bar in the add-ins ribbon to set the location?  Vs. manually entering the location in the script?  On our server, we have several job folders, each containing the thousands of pdf's i MENTIONED.  I only work on 1 job at a time, but do move around, being able to quickly define my starting location would be great.

Thanks again for you're help! much much appreciated

[recovering disk space, attachment deleted by admin]I can't reproduce your error. I made a fix to what the message indicates is the error. You'll have to do the actual test on your machine.

A prompt has been added to retrieve the PDF folder. It is no longer hard coded in the script.

The palm icon has been changed to a happy face (don't ask). I still haven't figured out how to have text with the icon.

Column B will accept file names with or without EXTENSIONS. File names without extensions default to .pdf
Do not use path names in column B.

Column C is used as an indicator that the renames has been processed for each file. This is simply FYI.

Code: [Select]'
'Plug PDF Files Into XLS
'
Set fso = CreateObject("Scripting.FileSystemObject")

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add()
Set xlSheet = xlBook.Worksheets(1)

Do
strFolder = InputBox("Enter PDF Folder:", "Recursive PDF Finder")
Loop Until fso.FolderExists(strFolder)

Set fc = fso.GetFolder(strFolder).Files

xlRow = 0
RecurseFolders fso.GetFolder(strFolder)
ExcelStuff()

Set xlRange = xlSheet.UsedRange
xlRange.Columns.Autofit

Set xlRange = xlSheet.Columns("B:B")
xlRange.ColumnWidth = 25
xlRange.Cells.NumberFormat = ""

Set xlRange = xlSheet.Columns("C:C")
xlRange.ColumnWidth = 25
xlRange.Cells.NumberFormat = ""
xlApp.Visible = True

Sub RecurseFolders(Folder)
  Set fc = Folder.files
  For Each fs In fc
    If LCase(fso.GetExtensionName(fs)) = "pdf" Then
      xlRow = xlRow + 1
      xlSheet.Cells(xlRow, 1).Value = fs.Path
    End If
  Next

  For Each objFolder In Folder.subFolders
    RecurseFolders objFolder
  Next
End Sub

Sub ExcelStuff()
  ' Create Module & Macro
  '
  Set xlModule = xlBook.VBProject.VBComponents.Add(1)
 
  strCode = _
    "Sub NewNames()"                                                                     & vbCrLf & _
    "  Dim xlSheet As Worksheet"                                                         & vbCrLf & _
    "  Dim fso As Object"                                                                & vbCrLf & _
    "  Dim fs As Object"                                                                 & vbCrLf & _
    "  Dim fx As String"                                                                 & vbCrLf & _
    "  Set fso = CreateObject(" & Chr(34) & "Scripting.FileSystemObject" & Chr(34) & ")" & vbCrLf & _
    "  Range(" & Chr(34) & "A1" & Chr(34) & ").Select"                                   & vbCrLf & _     
    "  Do Until IsEmpty(ActiveCell)"                                                     & vbCrLf & _
    "    If Not IsEmpty(ActiveCell.Offset(0, 1)) Then"                                   & vbCrLf & _
    "      Set fs = fso.getfile(ActiveCell.Value)"                                       & vbCrLf & _
    "      fx = ActiveCell.Offset(0, 1).Value"                                           & vbCrLf & _
    "      If fso.GetExtensionName(fx) = "  & Chr(34) & Chr(34) & "Then"                 & vbCrLf & _
    "        fs.Name = fx &" & Chr(34) & ".pdf" & Chr(34)                                & vbCrLf & _
    "      Else"                                                                         & vbCrLf & _
    "        fs.Name = fx"                                                               & vbCrLf & _
    "      End If"                                                                       & vbCrLf & _
    "      ActiveCell.Offset(0, 2).Value = " & Chr(34) &  "File Renamed" & Chr(34)       & vbcrlf & _
    "    End If"                                                                         & vbcrlf & _
    "    ActiveCell.Offset(1, 0).Select"                                                 & vbCrLf & _
    "  Loop"                                                                             & vbCrLf & _
    "End Sub"                                                                            & vbCrLf
     
  xlmodule.CodeModule.AddFromString strCode
 
  ' Create a new toolbar
  '
  Set cbs = xlapp.CommandBars
  Set cb = cbs.Add("Special", 1, , True)      ' Command Bar Temporary
  cb.Visible = True

  ' Create a button & assign to macro
  '
  Set cbc = cb.Controls.Add(1)
  With cbc
    .OnAction = "NewNames"
    .Caption = "PDF Renames"
    .FaceId = 59
  End with
End Sub

In my previous post I mentioned you could save the workbook with a XLSM extension and work with it later. Not true! The VBA macro is temporary and even if you use a XLSM extension, the macro disappears anyway. To make the macro permanent is an easy tweak but the change is global for all future workbooks you may work with. Not sure you wanted that.

Good Luck.  This is exactly what I was looking for! Thank you soo much!

I have a preexisting xlbs file in my appdata excel start folder containing several other macro's.  Is it possible to add this to that so that It is an option in the ribbon anytime I have excel open?

Also, is it possible to put a browse location button in the drop down when it asks for the folder location?

Thank you very much!cincyshirm61,

XLSB files appear to be a global repositories for Excel macros. The snippet below is the VBA code generated by the VBScript. This link should help you add the macro to your XLSB file.

VBA Macro:
Code: [Select]Sub NewNames()
  Dim xlSheet As Worksheet
  Dim fso As Object
  Dim fs As Object
  Dim fx As String
  Set fso = CreateObject("Scripting.FileSystemObject")
  Range("A1").Select
  Do Until IsEmpty(ActiveCell)
    If Not IsEmpty(ActiveCell.Offset(0, 1)) Then
      Set fs = fso.getfile(ActiveCell.Value)
      fx = ActiveCell.Offset(0, 1).Value
      If fso.GetExtensionName(fx) = "" Then
        fs.Name = fx & ".pdf"
      Else
        fs.Name = fx
      End If
      ActiveCell.Offset(0, 2).Value = "File Renamed"
    End If
    ActiveCell.Offset(1, 0).Select
  Loop
End Sub

Once you've done that, much of the VBScript code can be eliminated:

Code: [Select]'Plug PDF Files Into XLS
'
Const RETURN_ONLY_FOLDERS = &H0001
Const WINDOW_HANDLE = 0
Const MY_COMPUTER = 17

Set objShell  = CreateObject( "Shell.Application" )
Set objFolder = objShell.BrowseForFolder( WINDOW-HANDLE, "Select Folder", RETURN_ONLY_FOLDERS, MY_COMPUTER )
If TypeName(objFolder) = "Nothing" Then
  WScript.Echo "User Cancelled Script"
  WScript.Quit
End If
Set objFolder = objFolder.Self
strFolder = objFolder.Path

Set fso = CreateObject("Scripting.FileSystemObject")
Set fc = fso.GetFolder(strFolder).Files

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add()
Set xlSheet = xlBook.Worksheets(1)

xlRow = 0
RecurseFolders fso.GetFolder(strFolder)

Set xlRange = xlSheet.UsedRange
xlRange.Columns.Autofit

Set xlRange = xlSheet.Columns("B:B")
xlRange.ColumnWidth = 25
xlRange.Cells.NumberFormat = ""

Set xlRange = xlSheet.Columns("C:C")
xlRange.ColumnWidth = 25
xlRange.Cells.NumberFormat = ""
xlApp.Visible = True

Sub RecurseFolders(Folder)
  Set fc = Folder.files
  For Each fs In fc
    If LCase(fso.GetExtensionName(fs)) = "pdf" Then
      xlRow = xlRow + 1
      xlSheet.Cells(xlRow, 1).Value = fs.Path
    End If
  Next

  For Each objFolder In Folder.subFolders
    RecurseFolders objFolder
  Next
End Sub

When you run the script, the spreadsheet will be created with the PDF files listed in column A. No longer will the VBA macro and button (happy face) be created. After filling in column B, you can run the VBA macro from the ribbon as you would any other personal macro.

The InputBox (prompt) has been replaced with the standard Windows BrowseForFolder control.

Happy Days.  Am I correct that in order to use this, I must always first run the script file, browse for my location, then that will import the paths into a new excel sheet, then run the macro?  I pasted the rename macro into my personal.xlsb file and it works great!  Instead of using the script you've provided, I find it would be easier to pair with my existing method.  Most of our work is done on a network drive, and for whatever folder I need the pathnames on I drag and drop a simple batch file to the folder, and this spits out a notepad file of the names.

Code: [Select]echo on

set pth = %~dp0

dir /s /b %pth%*.pdf >%pth%names.txt

end
from here I paste the names into column A, my renames in column B, then run your macro and Im good!

Thank you for the link to the post explaining putting macro's in the ribbon, did this with all of them, much more convenient, thank you very much!After my last reply, the sequence of events changed:

1. Run the VBScript to fill the spreadsheet with PDF file names
2. Fill in column B with the new names
3. Run the NewNames macro attached to the ribbon

You can replace step 1 above with your original batch file method. Results will be the same.

 

I'd like to mention that the (already FIXED) "Variable not defined" Error was the result of "Option Explicit" being automatically inserted into every Module that is added.

386.

Solve : How to make a batch file that gives an 'Enter' as a result?

Answer»

Hello good morning everyone.

This is my first post and I hope I'm doing it in the right area. I'll try to explain what I need:
I'm working with some Panasonic tough tablets, these tablets come with Windows PRO and with 5 buttons, 4 of them are ALREADY SETUP by the application but the 5th is an open button where you can choose an OPTION for the button to run or you can choose a program to be launched.
I'm not a programmer and MAYBE that's why my question will look dumb (sorry).

I need to create a batch file that performs an , that's it, it's all I need, sadly because of my lack of knowledge in programming I'm having troubles to get to this result.

Could you please guide in the right direction?

Best regardsI use JitBit Macro Recorder to make quick programs like this. With this tool you can create this in less than a minute and have a stand alone compiled exe file that will pass the instruction of enter key entered. This software is very powerful for automation of KEYBOARD and mouse controls. You can program a redundant process, and compile it, and then trigger the exe to run and sit back and everything runs on its own. Mouse pointer moves where needed at correct time and selects whatever it needs to and processes whatever it needs to.

387.

Solve : need help makeing a batch file to play older games.?

Answer»

Hello all,

    I am trying to make a batch file to play starcraft 1 on my computer's Windows 7 ultimate x64bit OS.

The problem with this particular game is that Explorer.exe conflicts with starcraft causing pixelation, terrible discoloring, and crashes.  I have solved the problem by ending explorer.exe via task manager.  Also for some reason windows 7 makes me run the game twice inorder to bring it to focus.  this causes mass system rescourses to be used and causes my CPU to over heat.  It is harder on my computer to play a game from the 90's that it is to play Crysis 3 for what thats worth.  This problem is also remedied via task Manager by ending the "rundll32.exe" process.  The game works perfect after that.  I have a batch file made to deal with discoloration  it goes like this:

echo off
taskkill /f /IM explorer.exe
start /wait StarCraft.exe
start C:\Windows\explorer.exe

What I need to add to this is a way to killtask rundll32.exe.  Here is the kicker though,  I need this batch file to run starcraft twice and THEN kill rundll in order to play the game properly.  I am just now starting to learn working with batch files, and I would appreciate any help on this.  the game plan is this:

Echo off
Kill explorer
Run Starcraft
Run Starcraft (I will more that likely need a timer to run starcraft a second time like 5 seconds to ensure the first loads)
Kill rundll32 (which will in turn automatically close the first starcraft so it dosnt eat my system rescourses.)
Run Explorer.exe (AFTER I kill the game so I can have my desktop back instead of having to run explorer.exe via task manager)

so yeah  A timer to load starcraft.exe a 2nd time.  and possibly a timer to close rundll32.exe if thats what you guys think is best.  Thanks in advance for any and all help guys.  ^_^  If you need additional information,  please let me know,  but I dont think that my computer specs will help in this situation other than my OS.run:

Code: [Select]regsvr32 /u C:\windows\system32\GameUX.dll
regsvr32 /u C:\windows\sysWOW64\GameUX.dll

This should fix the issue with RunDLL32. Note that this component is used by Games Explorer and could even be required by the shortcuts of some games. From my testing, running the Games Explorer Applet re-registers these components.


GameUX.dll is supposed to be a game manager, and 'injects' itself into the launch process of any DX game. However, the problem is that, if there is either no outbound connection or you have a firewall installed, it will actually hang in an infinite loop waiting for a response from "http://www.microsoft.com/WindowsMedia/Services/2003/10/10/common" and "http://www.microsoft.com/WindowsMedia/Services/2003/10/10/games".

The computer that I am making the Batch file for is not currently connected to the internet.   As there will be no in/outbound CONNECTIONS, will the .dll's you listed will hang in an infinite loop?  If so,  is there any other remedy you can think of to prevent the need for two instances of the same game to run in win7 due to rundll32.exe?What if I modify "block service providers" to where it can not send to microsoft, will that prevent an infinite loop? QUOTE from: Makomea on April 11, 2013, 04:48:09 AM

The computer that I am making the Batch file for is not currently connected to the internet.
Then it's exactly the same as the computer I diagnosed this issue with.
Quote
As there will be no in/outbound connections
There will. The functionality will be the same. It will still try to connect, and it will still fail waiting for a response.

Quote
will the .dll's you listed will hang in an infinite loop?
Yes

Quote
If so,  is there any other remedy you can think of to prevent the need for two instances of the same game to run in win7 due to rundll32.exe?
The infinite loop is caused by the dlls. Unregistering them prevents them from causing this problem.run:

Code: [Select]

regsvr32 /u C:\windows\system32\GameUX.dll
regsvr32 /u C:\windows\sysWOW64\GameUX.dll


Do I paste these into the batch file or do I run them?Either way works. I just ran them at the command line in my situation, but it ought to have the same effect.

In my case I don't have Starcraft so this is mostly guesswork based on uncannily similar problems I had with a good number of games when my desktop machine didn't have an Internet Connection. Some of the games I recall having the problem with are from the same era as StarCraft (I BELIEVE the oldest was the Original Command & Conquer), so hopefully your issue is caused by the same thing.

Either way, if you ever want to re-register Games Explorer, I think it does so when you launch the Games Explorer, or you can run the same commands but remove the /u switch.Hey,  thanks for the help bub  ^_^  I was on auto pilot last night.  Sleep deprivation  and SB DOUBLE shots wouldn't let me accomplish simple tasks.  Anyways,  I ran the codes via CMDp and they unregistered as you said.  I ran Starcraft as usual,  but WIN7 is still forcing me to use dual instances of the game before it can be brought to focus.  I have installed a couple oldie but goldie games like Warlords battlecry III,  C&D,  Warcraft III,  and still the same deal,  all dual instances and I have to Alt-Tab to task manager to kill Rundll32.exe so it will close the first instance of the game and not eat my CPU.  I tell you bub,  I can have Starcraft II,  Dawn of War II,  and TES: Skyrim running at the same time,  no lag to each other and all three games do not produce over 45 degrees Celsius.  This is on my AMD Phenom II 965 BE on STOCK cooler. (cherri wewt!)  But if I got to run a single game game from the 90's my CPU is hitting 60c on loading the game,  and 65-70 while playing the game unless I kill rundll32.exe.  Even then it is still running in the 50's for these old games.  If you can think of a for starcraft as said originally,  the .bat is a bit more complicated as it needs to both end explorer and kill rundll32,  but for the other old games,  I need only kill rundll32 via batch file just to make my gaming a bit easier.  So if you know a way to make a batch file that can accomplish this task,  I would be very grateful for the information.  ^_^  Either way,  I do really appreciate all the advice.  I will know what to do in the future if I run into the infinite loop issue in the future.You could always figure out what the rundll32.exe is for, hopefully it could give a clue as to an underlying CAUSE.

In Task Manager, you can add the "Command Line" column; this column on rundll32.exe will tell you/us exactly what dll is involved. In my investigations of my issue, it was GameUX.dll; but if you unregistered that it shouldn't be appearing, so it must be something else. Also double check the path of the rundll32.exe file, and make sure it is in C:\Windows\System32 or C:\Windows\SysWOW64.

You can kill rundll32.exe in a batch file the same way you kill explorer. The problem is it probably doesn't appear until after you've launched it, and by that time the batch is no longer in control (I imagine you have it wait for the program to exit so that you can launch explorer again). I suppose you could  delay using ping.

Either way I imagine there is an underlying cause, and the command line of the pegging rundll32 process can be useful to find out why.
388.

Solve : [VB .Net] Pick a random entry in a List(string)?

Answer»

Pretty much I have:

Code: [Select]Dim LI as List(string)
li.add("I'm good")
li.add("I'm better")
li. add("I'm best")
How do i randomly select one of these entries? Code: [Select]li.Item(Int(Rnd() * (li.Count - 1)))

will pick a random item.
I ever told you, BC_Programmer, I love you

Another quick question --

If i have the code: Code: [Select]Dim di As New IO.DirectoryInfo("C:\music")
How do i get di to include all sub-directories? Code: [Select]Sub Main()


        Dim dirs As IO.DirectoryInfo()
        Dim loopdir As IO.DirectoryInfo
        dirs = New IO.DirectoryInfo("C:\music").GetDirectories
        For Each loopdir In dirs
            Console.WriteLine(loopdir.FullName)


        Next
        Console.ReadKey()
    End Sub



It's a bit more involved; in this case I didn't bother STORING a directoryInfo for the "C:\Music" directory, rather opting to directly acquire it's subdirs. The "GetDirectories" Method of the DirecoryInfo Class returns an array of DirectoryInfo classes that you can enumerate using a For...Each Loop; in my example above it SIMPLY prints off each directory name, but you can do whatever you wish with them.I realise this is an old thread but I was wondering what  ('* li.Count - 1)))' did in the code above..... Quote from: finchy109 on April 10, 2013, 08:52:04 AM

I realise this is an old thread but I was wondering what  ('* li.Count - 1)))' did in the code above.....
the value used is li.Count-1 because the Items Accessor is zero-based. However, even so there is actually a bug in the original solution that prevents the last element of a list from ever being chosen.

It's actually a bug, somewhat. I used -1 because the Item accessor method takes a zero-based index and li.Count retrieves the total NUMBER of elements, so a 4-item list would return 4 for Count, but the fourth item would be accessed with li.Items(3).

However, the "bug" is because rnd returns a number between 0 and 1 exclusive- that is, the resulting value will never be 1. The Int function truncates the value, so the resulting index will never actually be the last index of the list.

The bugfix would be to use Math.Round instead of Int():

Code: [Select]li.Item(Math.Round(Rnd() * (li.Count - 1)))


Full disclosure, I didn't actually use the original code, so it wasn't fully tested. My preferred method of choosing an Item from an Array or other collection is a Generic Method I wrote in C#.

To make ammends for my 4 year old transgression, I will post that here, after porting it to VB.NET. The original C# implementation was called "Choose" and so was my VB.NET version until I noticed the existence of the legacy Choose() Function from VB6, when I renamed it to "Pick":

Code: [Select]    Public Function Pick(Of T)(ChooseArray As IEnumerable(Of T)) As T
        If rgen Is Nothing Then rgen = New Random()

        Dim sorttest As SortedList(Of Double, T) = New SortedList(Of Double, T)()
        For Each loopvalue As T In ChooseArray
            Dim rgg As Double = rgen.NextDouble()
            Do While sorttest.ContainsKey(rgg)
                rgg = rgen.NextDouble()
            Loop
            sorttest.Add(rgg, loopvalue)

        Next

        Return sorttest.First().Value
    End Function

As a generic method, it works with an Array of Any type, and Any collection, because it accepts any IEnumerable implementation.

If one is targeting VB11, you can even use the ported version of the method that acts as an Iterator Method:

Code: [Select]    Public Iterator Function Pick(Of T)(ChooseArray As IEnumerable(Of T), NumItems As Integer) As IEnumerable(Of T)
        If rgen Is Nothing Then rgen = New Random()

        Dim sorttest As SortedList(Of Double, T) = New SortedList(Of Double, T)()
        Dim ResultTest As List(Of T) = New List(Of T)

        For Each loopvalue As T In ChooseArray
            Dim rgg As Double = rgen.NextDouble()
            Do While sorttest.ContainsKey(rgg)
                rgg = rgen.NextDouble()
            Loop
            sorttest.Add(rgg, loopvalue)

        Next

        Dim I As Integer

        Dim DictEnumerator As IEnumerator(Of KeyValuePair(Of Double, T)) = sorttest.GetEnumerator()

        Do While DictEnumerator.MoveNext() And NumItems > (I)
            Yield DictEnumerator.Current.Value
            I = I + 1
        Loop

    End Function

The test Code I used that shows these methods being used:
Code: [Select]  Sub Main()

        Dim SelectFrom As Integer() = Enumerable.Range(0, 100).ToArray()
        For I As Integer = 0 To 100
            Console.WriteLine(Pick(SelectFrom))
        Next

        For I As Integer = 0 To 100

            For Each iterate In Pick(SelectFrom, 4)
                Console.Write(Str(iterate) + ",")
            Next
            Console.WriteLine()

        Next

        Console.ReadKey()
    End Sub

389.

Solve : Problem getting loop to restart on error Javascript?

Answer»

I am trying to get my loop to go back to the beginning on the first error.

Code: [Select]{
    VAR validInput = true;
    var start = confirm('Add item to shoping cart');
    if (start == true) {

        // ask first question
        var orderProductCodeArr = parseInt(prompt('Enter input: '), 10);
 
        if (isNaN(orderProductCodeArr)) {
            alert("input is not a valid number");
            validImput = false

        } else if (orderProductCodeArr < 0 || orderProductCodeArr &GT;= PRODUCT_LIST.length) {
            alert("code does not match any item");
            validInput = false;
        }
 
        // ask SECOND question

         else if(validInput == true) {
            var item = PRODUCT_LIST[orderProductCodeArr];
            alert("item is: " + item);
}
            // get quantity input
           
            // this is pseudocode
var quanityArr = parseInt (prompt('Enter quality amount'),10);
            if (isNaN(quanityArr)) {
            alert("input is not a valid number");
            validInput = false;

        }
       
       
     
       
    } else {
        document.writeln('still to come')
    }
 
}

  Quote from: sonya1m on April 14, 2013, 10:08:03 PM

I am trying to get my loop to go back to the beginning on the first error.

 It has been pointed out to me that I have no loop so I guess I NEED to ask, how do I make it into one loop first before I get to my next question.

Code: [Select]{
    var validInput = true;
    var start = confirm('Add item to shoping cart');
    if (start == true) {

        // ask first question
        var orderProductCodeArr = parseInt(prompt('Enter input: '), 10);
 
        if (isNaN(orderProductCodeArr)) {
            alert("input is not a valid number");
            validImput = false

        } else if (orderProductCodeArr < 0 || orderProductCodeArr >= PRODUCT_LIST.length) {
            alert("code does not match any item");
            validInput = false;
        }
 
        // ask second question

         else if(validInput == true) {
            var item = PRODUCT_LIST[orderProductCodeArr];
            alert("item is: " + item);
}
            // get quantity input
           
            // this is pseudocode
var quanityArr = parseInt (prompt('Enter quality amount'),10);
            if (isNaN(quanityArr)) {
            alert("input is not a valid number");
            validInput = false;

        }
       
       
     
       
    } else {
        document.writeln('still to come')
    }
 
}

 
390.

Solve : modify batch script to delete files?

Answer»

So Sidewinder helped me create a .bat and .vbs script that work like a charm. But now I need to modify it to delete all .zip files older than a week old. I have tried various methods and i seen the main method is to use forfiles but i can not install that on any computers. So doing it via batch would be perfect if i have to use another .vbs script that is fine to but prefer .bat

Batch file code
echo Backing up your Database....This may take awhile.....
sqlcmd -S ServerName -i backupDBscript.sql
SET MY_Path=pathtofiles
set mydate=%date:~4,2%%date:~7,2%%date:~10,4%
for %%x in (*.bak) do cscript "%MY_PATH%\zip.vbs" "%MY_PATH%\%%x" "%MY_PATH%\DB_%mydate%.zip"
del "%MY_PATH%\*.bak
exit

.vbs file to compress database
Set oFSO = CreateObject("Scripting.FileSystemObject")
ToZip    = oFSO.GetAbsolutePathName(WScript.Arguments.Item(0))
ZipName  = oFSO.GetAbsolutePathName(WScript.Arguments.Item(1))

d=WindowsZip(ToZip, ZipName)

Function WindowsZip(sFile, sZipFile)
  Set oZipShell = CreateObject("WScript.Shell")
  Set oZipFSO   = CreateObject("Scripting.FileSystemObject")
  If Not oZipFSO.FileExists(sZipFile) Then
    NewZip(sZipFile)
  End If
  Set oZipApp = CreateObject("Shell.Application")
  sZipFileCount = oZipApp.NameSpace(sZipFile).items.Count
      aFileName = Split(sFile, "\")
      sFileName = (aFileName(Ubound(aFileName)))
          sDupe = False
  For Each sFileNameInZip In oZipApp.NameSpace(sZipFile).items
    If LCase(sFileName) = LCase(sFileNameInZip) Then
        sDupe = TRUE
        Exit For
    End If
  Next
  If Not sDupe Then
        wscript.echo "Adding " & sfile
        oZipApp.NameSpace(sZipFile).Copyhere sFile
        On Error Resume Next
        Do Until sZipFileCount < oZipApp.NameSpace(sZipFile).Items.Count
            Wscript.Sleep(100)
        Loop
        On Error GoTo 0
  End If
End Function

Sub NewZip(sNewZip)
  Set oNewZipFSO  = CreateObject("Scripting.FileSystemObject")
  Set oNewZipFile = oNewZipFSO.CreateTextFile(sNewZip)
  oNewZipFile.Write Chr(80) & Chr(75) & Chr(5) & Chr(6) & String(18, 0)
  oNewZipFile.Close
  Set oNewZipFSO = Nothing
  Wscript.Sleep(500)
End Sub
May I ask a question?
Is thee a good REASON not to use Vb Script?
I have read that it can be used with remote assistance,  so I don't undersand why you would prefer batch.
Just curious. Quote from: Geek-9pm on September 04, 2013, 02:28:38 PM

May I ask a question?
Is thee a good reason not to use Vb Script?
I have read that it can be used with remote assistance,  so I don't undersand why you would prefer batch.
Just curious.

For less clutter. Thats why if it can be added to the zip.vbs that would be awesome if not in the batch that is fine too. been researching this like crazy.Here is a post that might be relevant to what your want.
Need a VBScript that calls a batch file to run on remote computers
Hope that helps some.  Quote from: Geek-9pm on September 04, 2013, 03:18:55 PM
Here is a post that might be relevant to what your want.
Need a VBScript that calls a batch file to run on remote computers
Hope that helps some. 

What I am working on is not for remote. Thanks for the assistance. I think this is what you need. The only issue is it will not look for files in subfolders. You just need to uncomment the deletefile part and change the path.

Code: [Select]Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "D:\htdocs"

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files
nowDate = Date
For Each objFile in colFiles
fileDate = objFile.DateLastModified
howLong = DateDiff("w", fileDate, nowDate)
If howLong > 1 then
wscript.Echo objFile.Path
'objFSO.DeleteFile objFile.Path
End If
Next
Quote from: Linux711 on September 04, 2013, 07:06:08 PM
I think this is what you need. The only issue is it will not look for files in subfolders. You just need to uncomment the deletefile part and change the path.

Code: [Select]Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "D:\htdocs"

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files
nowDate = Date
For Each objFile in colFiles
fileDate = objFile.DateLastModified
howLong = DateDiff("w", fileDate, nowDate)
If howLong > 1 then
wscript.Echo objFile.Path
'objFSO.DeleteFile objFile.Path
End If
Next

Should I add this to the zip.vbs file or create  a new file and add the code there?
391.

Solve : Asm+batch??

Answer»

Help, computer problem after file recovery(pictures), bios takes longer to load and windows too, when computer is idle cpu and gpu GOES to 100%, mouse click 2 times sometimes... I once see a question mark in hex editor in between hex of a HARD drive mft then format and it was gone.
 

http://www.youtube.com/watch?v=uAA26HSPTL4




Beginning of my master boot record starts at offset 55 on my hard drive it should be on offset 0, every time i test ports in dos debug some of values CHANGE. This happened after doing file recovery of some old hard drive.
 
In every computer i plugged in this hard drive, when i view the picture recovered with file recovery same thing happens. Tried low lvl format, cmos reset, batery out, different battery, flash bios. Bios got bricked then i reset cmos (battery out) and dual bios write original bios but still same problem.
 



Specs of one of the computers:
 
 OS Version: Microsoft Windows 7 Ultimate, Service Pack 1, 64 bit
 Processor: AMD Phenom(tm) II X2 550 Processor, AMD64 Family 16 Model 4 Stepping 2
 Processor Count: 2
 RAM: 4094 Mb
 Graphics Card: ATI Radeon HD 5700 SERIES, 1024 Mb
 Hard Drives: C: Total - 476832 MB, Free - 93325 MB;
 Motherboard: Gigabyte Technology Co., Ltd., GA-770TA-UD3Is this a home brew?
You should have in your resource chest:
1. A Live Linux CD or a AV rescue CD
2. A spare Power supply
3. A spare tested Hard drive, preferably with a system image
4. All the CDs needed for a fresh install. Or Flash drives.

When you do a home brew you have to be your own repair technician. You are now at the point where you need to fix the problem and stop looking at it. Take  action. Deploy your recovery method.

If you do not have a well-made recovery method, do this:
Put in the spare drive and set it as the boot media.
Either boot it up or install the OS again.
Once you have the OS up, you can get your data of the other drive.
Does this apply to you?

Yes its a home brew, i assemble it in 2010, it worked for 1,5years. I did recover files... the pictures on another pc, but then in every pc i view the picture,  same thing happened (youtube link).On an old pc where i cant flash bios there i cant even save to cmos and change a setting (flopy drive) it doesnt move o.O. Of course i did a fresh instal of Xwindows on all pcs that werent laptops. I dont know this looks to me like hardware programming issue. But now im looking for help to repair pc rather to get files recover. I had a computer tehnician(programmer) 7-8 years ago he looked at input output hard drive, then he sad it was cmos, he disable some flags(interrupt), he filled up memory with 1 dont know which memory exactly dont remember wery much, and he fount  a 0 somwhere and change it a function at offset (example a=bc) fill it u again and all was good it took him like 5min. But now 3 computer services telling me they cant find anything wrrong with a pc and i cant find this tehnician annymore.Is there actually something wrong with the PC, or are you just making a fuss about a single byte not being what you expect it to be?

Windows 7 doesn't come with DEBUG, nor does it run on x64. How are you booting to DOS to run "DEBUG"?

The video doesn't go anywhere near the MFT.Serious performance issues + i once transfer data (another picture) to my phone and my phone died:( there must be something wrong with data being transfered. I heard once its in betwen 0 data.How abt look up tables, anyone know how?I think 100% that something is wrong with my pc, I was trying to learn batch commands and dos so I could synchronise data buffers or something and trying to learn asm so I coul read cmos many times or write 1 values to see where it goes wrong but no sucsses. I remember pluging hard drive broken by file recovery to a working pc and there were only 254 sectors one missing, and after restart 255 sectors but some values missing in cmos and seetings in cmos wrong load defaults... so the first one is missing or is it it starts with second bit? Could some Expert tell me is it the data buffers or what?


http://youtu.be/Id7GCd4SY_U


I would really appreciate it, if anyone could help me!I rember the repair man was like "writing ones to buffer host ide or something cmos without reading next data buffer clock to get data buffer to beginning"
maybe data buffer starts at middle of the data buffer or second and ends up In the middle, then darknes in between new middle. Quote from: Mflipb on August 30, 2013, 07:07:44 AM

I think 100% that something is wrong with my pc
No there isn't.

Quote
I was trying to learn batch commands and dos so I could synchronise data buffers or something
This is a nonsense phrase. It doesn't make any sense.

Quote
and trying to learn asm so I coul read cmos many times or write 1 values to see where it goes wrong but no sucsses.
This doesn't make much sense either. Why would you want to read the CMOS RAM many times? Surely once would be sufficient. (Of course let's ignore the fact that you aren't running DOS to begin with, thus you don't actually have real-mode access to the system but (if you are on 32-bit) are actually given access to a virtualized Processor through NTVDM. On 64-bit there is no Debug and there is no simple way to assemble and run 16-bit Assembly programs from within the OS.

Quote
I remember pluging hard drive broken by file recovery to a working pc and there were only 254 sectors one missing, and after restart 255 sectors
Hard Drives use LBA now. Sectors are always 255. Some informational tools will show 254, since they will count the first one as Sector 0.

Quote
but some values missing in cmos and seetings in cmos wrong load defaults... so the first one is missing or is it it starts with second bit?
The CMOS has nothing to do with your Hard drive. I'm honestly not sure if you are trolling or are seriously this uninformed on the concepts that we've so far tried to explain, but which have so far been ignored. You cannot just make up phrases and terms and think we'll know what you mean.

Quote
Could some Expert tell me is it the data buffers or what?
I cannot rightly apprehend the confusion of ideas that would lead to such a question.


Quote
http://youtu.be/Id7GCd4SY_U
It's a glitch related to combination of using a internal command name for the name of the batch script (for) calling a batch script with that internal command name, but using a forward slash to trick the parser into calling the batch rather than the internal command, and continuing the call it until it ends up exiting. In this case the Error CODE that causes CMD to crash is "c00000fd", which is Stack Overflow.

I would surmise that some combination of using the internal command name for the batch script, the batch script chaining to itself, and the use of a forward slash at the end of the name causes this problem.

Quote from: Mflipb on August 30, 2013, 07:17:55 AM
I rember the repair man was like "writing ones to buffer host ide or something cmos without reading next data buffer clock to get data buffer to beginning"
maybe data buffer starts at middle of the data buffer or second and ends up In the middle, then darknes in between new middle.

This entire post is unintelligible.

The repair man also said that a=bc that C is actualy A and need to change it, after he filled some memory with ones  #1 , does that make any sense im writing to you what he did to repair my pc  im not making things up and I don't know anything about programing trying to learn... Quote from: Mflipb on August 30, 2013, 11:55:40 AM
The repair man also said that a=bc that C is actualy A and need to change it, after he filled some memory with ones  #1 , does that make any sense
No, that makes no sense. I say this character is a fairly obvious "attention troll", probably aged about 12. His outpourings remind me of the "stuff about computers" in novels written by people who don't actually know anything about computers. I remember one of the Kay Scarpetta novels by Patricia Cornwell where she goes on about "formatting a few files" and other nonsense.


Quote from: Mflipb on August 30, 2013, 07:07:44 AM
I was trying to learn batch commands and dos so I could synchronise data buffers or something

Or something? Or something?

He's yanking your chains and not even hiding the fact.
yes I was having trouble deciding if this was somebody who had a prenatal lobotomy or somebody who was purposely making absolutely no sense. I was leaning towards the latter.Time to reformat.
This thread is beyond recovery.   

Note to the OP. 
What do you want to do? Is the issue saving a picture? You should export your pictures to some kind of permanent t media, like a CD-R you burn in a CD-EOM drive.

Problems with pictures have nothing  to do with the hard drive geometry. Pictures and never stored in CMOS.  An many technicians know the difference between a Phillips head screwdriver and the other kind. That is how they  got to be technicians. And when not working on computers, they shoe horses.

If you want to go back to Windows XP and start over again, you have my permission. But But if you keep using Windows 7, please do not post any more questions like the ones you did here.  In Windows 7 programmers do not use the DEBUG tool from early versions of Windows. It just don't work right. And nobody here will help you work on the MBR in Windows 7. In Windows 7, the MBR is not for any user programming or modification. That is by design.   

But we are willing to help. Just no more DEBUG with Windows 7.
For the benefit of all readers, here is a simple explanation of what CMOS meas with reference to a PC.
http://www.wisegeek.org/what-is-cmos.htm#slideshow
(Also has pictures of other common PC parts.)
392.

Solve : Python - Accessing information buried in a dictionary?

Answer»

Hi, SORRY for the noob question. I've just (re)started trying to understand Python, and decided to start with trying to make a script to create a personalized weather report.
I came across this and imported it into my code. I followed the suggestions on the api's page and set Code: [Select]yahoo_result = pywapi.get_weather_from_yahoo('UKXX0001', 'metric')
Printing that gives a slightly less cleanly formatted version of what's below, which lead me to believe it was storing the information in a dictionary.
Code: [Select]{   'astronomy': {'sunrise': '6:03 am', 'sunset': '8:12 pm'},
    'atmosphere': {   'humidity': '64',
                      'pressure': '982.05',
                      'rising': '0',
                      'visibility': '9.99'},
    'condition': {   'code': '30',
                     'date': 'Thu, 29 Aug 2013 3:50 pm BST',
                     'temp': '19',
                     'text': 'Partly Cloudy',
                     'title': 'Conditions for Aberdeen, UK at 3:50 pm BST'},
    'forecasts': [   {   'code': '29',
                         'date': '29 Aug 2013',
                         'day': 'Thu',
                         'high': '18',
                         'LOW': '10',
                         'text': 'Partly Cloudy'},
                     {   'code': '30',
                         'date': '30 Aug 2013',
                         'day': 'Fri',
                         'high': '19',
                         'low': '7',
                         'text': 'Partly Cloudy'},
                     {   'code': '30',
                         'date': '31 Aug 2013',
                         'day': 'Sat',
                         'high': '16',
                         'low': '10',
                         'text': 'Partly Cloudy'},
                     {   'code': '26',
                         'date': '1 SEP 2013',
                         'day': 'Sun',
                         'high': '16',
                         'low': '11',
                         'text': 'Cloudy'},
                     {   'code': '39',
                         'date': '2 Sep 2013',
                         'day': 'Mon',
                         'high': '18',
                         'low': '12',
                         'text': 'SCATTERED Showers'}],
    'geo': {'lat': '57.13', 'long': '-2.09'},
    'html_description': '\n<img src="http://l.yimg.com/a/i/us/we/52/30.gif"/><br />\n<b>Current Conditions:</b><br />\nPartly Cloudy, 19 C<BR />\n<BR /><b>Forecast:</b><BR />\nThu - Partly Cloudy. High: 18 Low: 10<br />\nFri - Partly Cloudy. High: 19 Low: 7<br />\nSat - Partly Cloudy. High: 16 Low: 10<br />\nSun - Cloudy. High: 16 Low: 11<br />\nMon - Scattered Showers. High: 18 Low: 12<br />\n<br />\n<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Aberdeen__UK/*http://weather.yahoo.com/forecast/UKXX0001_c.html">Full Forecast at Yahoo! Weather</a><BR/><BR/>\n(provided by <a href="http://www.weather.com" >The Weather Channel</a>)<br/>\n',
    'link': 'http://us.rd.yahoo.com/dailynews/rss/weather/Aberdeen__UK/*http://weather.yahoo.com/forecast/UKXX0001_c.html',
    'location': {'city': 'Aberdeen', 'country': 'UK', 'region': ''},
    'title': 'Yahoo! Weather - Aberdeen, UK',
    'units': {   'distance': 'km',
                 'pressure': 'mb',
                 'speed': 'km/h',
                 'temperature': 'C'},
    'wind': {'chill': '19', 'direction': '0', 'speed': '3.22'}}

To be able to refer to SPECIFIC attributes within the list, it was suggested to me by a friend that I try something similar to:
Code: [Select]print(yahoo_result.astronomy.sunrise)
but then I get the error:
Code: [Select]Traceback (most recent call last):
  File "C:\Users\James\weather.py", line 10, in <module>
    print(result.astronomy.sunrise)
AttributeError: 'dict' object has no attribute 'astronomy'
Whole code being:
Code: [Select]#!/usr/bin/env python
import  pywapi

yahoo_result = pywapi.get_weather_from_yahoo('UKXX0001', 'metric')
print(yahoo_result.astronomy.sunrise)

and whole response being:
Code: [Select]{   'astronomy': {'sunrise': '6:03 am', 'sunset': '8:12 pm'},
    'atmosphere': {   'humidity': '64',
                      'pressure': '982.05',
                      'rising': '0',
                      'visibility': '9.99'},
    'condition': {   'code': '30',
                     'date': 'Thu, 29 Aug 2013 3:50 pm BST',
                     'temp': '19',
                     'text': 'Partly Cloudy',
                     'title': 'Conditions for Aberdeen, UK at 3:50 pm BST'},
    'forecasts': [   {   'code': '29',
                         'date': '29 Aug 2013',
                         'day': 'Thu',
                         'high': '18',
                         'low': '10',
                         'text': 'Partly Cloudy'},
                     {   'code': '30',
                         'date': '30 Aug 2013',
                         'day': 'Fri',
                         'high': '19',
                         'low': '7',
                         'text': 'Partly Cloudy'},
                     {   'code': '30',
                         'date': '31 Aug 2013',
                         'day': 'Sat',
                         'high': '16',
                         'low': '10',
                         'text': 'Partly Cloudy'},
                     {   'code': '26',
                         'date': '1 Sep 2013',
                         'day': 'Sun',
                         'high': '16',
                         'low': '11',
                         'text': 'Cloudy'},
                     {   'code': '39',
                         'date': '2 Sep 2013',
                         'day': 'Mon',
                         'high': '18',
                         'low': '12',
                         'text': 'Scattered Showers'}],
    'geo': {'lat': '57.13', 'long': '-2.09'},
    'html_description': '\n<img src="http://l.yimg.com/a/i/us/we/52/30.gif"/><br />\n<b>Current Conditions:</b><br />\nPartly Cloudy, 19 C<BR />\n<BR /><b>Forecast:</b><BR />\nThu - Partly Cloudy. High: 18 Low: 10<br />\nFri - Partly Cloudy. High: 19 Low: 7<br />\nSat - Partly Cloudy. High: 16 Low: 10<br />\nSun - Cloudy. High: 16 Low: 11<br />\nMon - Scattered Showers. High: 18 Low: 12<br />\n<br />\n<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Aberdeen__UK/*http://weather.yahoo.com/forecast/UKXX0001_c.html">Full Forecast at Yahoo! Weather</a><BR/><BR/>\n(provided by <a href="http://www.weather.com" >The Weather Channel</a>)<br/>\n',
    'link': 'http://us.rd.yahoo.com/dailynews/rss/weather/Aberdeen__UK/*http://weather.yahoo.com/forecast/UKXX0001_c.html',
    'location': {'city': 'Aberdeen', 'country': 'UK', 'region': ''},
    'title': 'Yahoo! Weather - Aberdeen, UK',
    'units': {   'distance': 'km',
                 'pressure': 'mb',
                 'speed': 'km/h',
                 'temperature': 'C'},
    'wind': {'chill': '19', 'direction': '0', 'speed': '3.22'}}
Traceback (most recent call last):
  File "C:\Users\James\weather.py", line 10, in <module>
    print(result.astronomy.sunrise)
AttributeError: 'dict' object has no attribute 'astronomy'

If possible, could someone explain to me what I'm doing wrong?
Thanks in advance,
James
Python dictionaries are indexed with square brackets in most cases:

Code: [Select]print(yahoo_result["astronomy"]["sunrise"])

Ought to be what you are after.That was it!

Thanks Hi, sorry for double posting.

If I wanted to convert one of the variables to lowercase, how would I go about doing it?
Code: [Select]print("The conditions will be " + (yahoo_result["condition"]["text"]).lower + ".")My guess would have been something like that, but I get the error:

Code: [Select]  File "C:\Users\James\weather.py", line 9, in fullweather
    print("The conditions will be " + (yahoo_result["condition"]["text"]).lower + ".")
TypeError: Can't convert 'builtin_function_or_method' object to str implicitly
Thanks againYou are referring to the lower method itself, rather than calling it. When you do .method without a pair of parentheses, you are actually referring directly to the function itself. In order to call a function you need a parameter list- in this case, the lower method doesn't take any parameters, so you can use an empty set of parentheses, like so:

Code: [Select]print("The conditions will be " + (yahoo_result["condition"]["text"]).lower() + ".")

That should fix that problem.Thanks


Code: [Select]    elif (isistance(timearg, int)) == true:
Sorry for this again, but is there a way to elif when the variable is an integer?
Thanks Code: [Select]    elif type(timearg) is int:

393.

Solve : Need C Programming Help! (tinker with program)?

Answer»

So, to begin, I must write a program that I can type in a number of inches and it will list how many miles, yards, feet and inches I entered. With this program I keep getting the error:

[Linker error] undefined reference to `measure(int, int, int, int)'

Any ideas on how I can make this work?



#include
#include
#include

int MAIN()
{

int measure(int B, int C, int D, int E);
int miles, yards, feet, inches, B, C, D, E;

miles==B, yards==C, feet==D, inches==E;

int total=0;

printf("Please enter a number of inches\n");

scanf("%d", total);

measure(B, C, D, E);
 
if (total>=63360)
B= (total/63360);

if (total>=1760)
C= (total-(B*63360))/1760;

if (total>=5280)
D= ((total- (B*63360)-(C*1760))/5280);

if (total>=12)
E= ((total-(B*63360)-(C*1760)-(D*5280))/12);
 
printf("Total inches entered: %d\n", total);
printf("%d miles\n", miles);
printf("%d yards\n", yards);
printf("%d feet\n", feet);
printf("%d inches\n", inches);

system ("PAUSE");
RETURN 0;
}
 you don't define the measure() routine anywhere.

Probably best to keep things in the Forum thread

To Elaborate:

There is no measure function. The only procedure you define is the main() method.
Within main, you do use this line:

Code: [Select]int measure(int B, int C, int D, int E);
But from what I understand this is a No-op statement- it basically defines a function pointer type and then does nothing with it so it get's discarded.

As a result when you refer to measure() later on, the compiler doesn't know what you are talking about.


here is a version that compiles. You will need to move appropriate logic. I also took the liberty of moving your System call into a separate routine and using stdio to create the same effect. A good rule of thumb when programming in C and C++ is to never use System() unless your aim is to purposely start a separate process. If you are trying to create a desired effect (such as pausing for enter or any key being pressed) you should create that functionality yourself. Too often I see self-proclaimed C/C++ programmers (not yourself) claiming multiple years of experience when all they are doing is writing a glorified batch file consisting of a series of system() calls.

Anyway, here is the version that compiles and appears to work. I've placed comments to try to describe certain key parts when it comes to C as I understand them. You should do some research on that which I bring up on your own to either confirm or refute the accuracy. I re-made the measure routine based on what I suspected it was supposed to be doing. the function requires some pointer usage which I try to explain as best I can.

Code: [Select]#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#ifdef _MSC_VER
#define getch() _getch()
#endif

//Since I used Visual Studio to test it, some of the above is probably MS compiler specific.
//Forward function declarations. in order for the C compiler to be able to parse and understand
//function calls, it needs to know what functions are available. the included header files above add function definitions for the appropriate functions and types
//and whatnot within the STANDARD library, but for your own code, you either need to create the actual function definitions before you use them, or use these,
//which are forward declarations which tell the Compiler that by the time it goes to actually link everything it will know what the function definition is (it is
//defined beneath main, which is where the function is used).
//I didn't know what measure() was supposed to do, so it has been removed. if part of the main() function was supposed to be there,
//I added the "pause()" function which performs a similar function to system("pause") but actually does it using C code so you don't spawn off a separate
//command INTERPRETER and also tie yourself to a specific set of Operating Systems.
void measure(int total, int* miles, int* yards, int* feet, int* inches);
void pause(void);
int main()
{
    int miles=0, yards=0, feet=0, inches=0;
    int total=0;
    printf("Please enter a number of inches\n");
//the original scanf() you had would have raised an access violation.
//scanf takes INPUT and puts it into a parameter. In order to do this, the second parameter
//is actually a pointer. If you do not pass it as an address, the result is that the scanf() function interprets
// the value of total passed in literally; it's 0 by default, so you end up with an access violation when scanf tries to save
//the value you type at address 0.
    scanf("%d", &total);
   
    //I moved the logic you had here previous to the "measure()" routine, since I think that was the intention.
//note that each parameter is passed by  address. Since measure is storing values in them, it needs their address; parameters are copied normally, (by value)
//so assigning to them has no effect.
//so
    measure(total,&miles,&yards,&feet,&inches);

    //measure should have done all the calculations for us here, and we can display the results.

    printf("Total inches entered: %d\n", total);
    printf("%d miles\n", miles);
    printf("%d yards\n", yards);
    printf("%d feet\n", feet);
    printf("%d inches\n", inches);
    pause();
    return 0;
}
//this is the trickiest bit to explain since it involves the use of pointers.
//as we can see, the parameter list defines all but the first parameter as a pointer.
//the reason is because the measure() routine is storing it's output in these values, and in order to do so
//it will need a pointer to the location to store them.
void measure(int total,int* miles, int* yards, int* feet, int* inches)
{
//there is a pattern here worth explaining.
//when dealing with a pointer, if you assign it directly, you assign the memory address the pointer points to. So,
//if we were to use "miles= (total/63360)" we would be changing the pointer itself to point at a completely different address.
//in that case the result would be that nothing would happen; the miles parameter pointer is actually a copy of the passed in value,
//so changing that would have no effect on the variable passed in from main.

//In order to actually get at the value the pointer is pointing at and use it, we need to "dereference" the pointer. Here we use that
//several times; the assignments all use *variable to dereference the pointer because we want to store the calculation in the memory the
//pointer is pointing at, and not the pointer itself. Likewise, the calculations refer to the results of the previous calculations too,
//so we dereference the previous results when they are used in the calculation (otherwise, the calculation would use the memory location
//of the pointer, which is not what we want.)
    if (total>=63360)
        *miles = (total/63360);

    if (total>=1760)
        *yards = (total-((*miles)*63360))/1760;

    if (total>=5280)
        *feet = ((total- ((*miles)*63360)-((*yards)*1760))/5280);

    if (total>=12)
        *inches = ((total-((*miles)*63360)-((*yards)*1760)-((*feet)*5280))/12);


}
void pause(void)
{
printf("Press Enter to Continue...");

    fflush(stdout);
    while ( getch() == 0 );

}

394.

Solve : How should I structure this XML file??

Answer»

I am making my first XML file and I'm trying to decide the best way to structure the data. It contains a LIST of file types and their CORRESPONDING description and some other info.

My program (PHP) finds the extension of a file, then it needs to load the other data corresponding to that file. The XML needs to contain the extension, description, class, and icon path.


txt
This is a text document
text
text.png


or


...


or



...


I'm not sure how to structure the XML best for the way I want to READ it.if the values are unlikely to have a heirarchy of sub-nodes, use attributes. I cannot think of any good reason for the values yo mention to ever require additional nodes or even their own attributes, so I'd GO with attributes on the node.so you mean like this: Exactly.

You should of course be using the XML Parser for PHP, if you are using PHP. Don't try to parse XML yourself. It will only END in tears.

395.

Solve : Need an OOP example?

Answer»

Hi,

I have been given a task for tomorrow to give an example to show an understanding of the following:

1. Object Assignment in OOP
2. Inheritance and interfaces in OOP

As I have not done any OOP development before, I hoped someone give an EXPLANATION in "Laymen's Terms", so I can build on this?

This would be appreciated.

ThanksI don't know what language you're USING, but C# should be CLOSE enough to understand even if you aren't using that language. DotNET Pearls is a very good SITE for OOP C# description and examples.

Inheritance: http://www.dotnetperls.com/inheritance

Interfaces: http://www.dotnetperls.com/interface

Object assignment is very simple:
Code: [Select]myObjectType objectName = new myObjectType(param1, param2, etc);

PUBLIC class myObjectType
{
    public myObjectType(int param1, int param2)
    {
     //this method is executed when class is created using line above
    }

    private doStuff()
    {
    //you can only access this from within this class
    }

    public doStuff()
    {
    //you can access outside this class
    }
}
There are a million other things I could go into, but I think that gives you a good basic idea.

396.

Solve : New, again, with BASIC?

Answer»

This is my first posting here. I did some BASIC programming back in the mid-1980s and now decided I wanted to get back into it again. This attached program was my first new attempt at it, using QB 1.1. I've since gotten into QB 4.5 and like it much better.

I'm running QB 4.5 on 32 bit Win XP. I start it using a .bat file on the desktop:

cd\basic 'The directory on the C: drive
qb         'QB's .exe file

I uploaded the file as a .txt document because the "Allowed file types: [are] doc, gif, jpg, mpg, pdf, png, txt, zip, log, bat, bmp. I saved BUDGET.BAS as a text file then opened it with Notepad and saved it as BUDGET.TXT.

Sure seems it would be simpler to upload it as BUDGET.BAS. Why the restriction?

I sure will appreciate any and all comments. 

[recovering disk space, attachment deleted by admin]One suggestion I have is to accept both Upper Case Y and Lower case y such as

INPUT "ENTER 'Y' for YES"; Enter$
IF Enter$ = "y" || Enter$="Y" THEN GOTO PrintIt
IF Enter$ <> "y" && Enter$ <> "Y" THEN GOTO RUSure

* Not sure if this is correct above for Basic with && (AND) || (OR) as for I am use to C++ syntax and cant test this here at work without QBasic. I started with GW-Basic long time ago, 1984-ish with DOS 2.11 but haven't  used it in years. When introduced to C and C++ in college in 1998, I made the switch to C++ as my choice language. But more recently I actually like using PERL for quick down and dirty console app programming.

Also unable to test your code but just BROWSE through it in text editor right now. Do you need assistance with any of it? Quote from: DaveLembke on January 26, 2013, 04:22:19 PM

One suggestion I have is to accept both Upper Case Y and Lower case y such as

INPUT "ENTER 'Y' for YES"; Enter$
IF Enter$ = "y" || Enter$="Y" THEN GOTO PrintIt
IF Enter$ <> "y" && Enter$ <> "Y" THEN GOTO RUSure

* Not sure if this is correct above for Basic with && (AND) || (OR) as for I am use to C++ syntax and cant test this here at work without QBasic
Basic and variants use AND and OR. Either way, a better approach would probably be a function. StrComp is a function found in more recent Versions of Visual Basic. It is not present in older QBASIC and QuickBASIC packages, but you can write a Version of it:

Code: [Select]CONST FALSE = 0
CONST TRUE = NOT FALSE
DECLARE FUNCTION STRCOMP(str1 AS STRING, str2 AS STRING, COMPARETEXT AS INTEGER)
FUNCTION STRCOMP(str1 AS STRING, str2 AS STRING, COMPARETEXT AS INTEGER)
    IF COMPARETEXT THEN STRCOMP=(UCASE$(str1)=UCASE$(str2)) ELSE STRCOMP=(str1=str2)
END FUNCTION
Not tested, I'll admit. Speaking of Functions and subroutines, I notice a distinctive lack of them in the provided source listing, instead using GOTO for most of the flow control.

Aside from that, you might want to consider looking into more modern alternatives. If not Visual Basic, then something like FreeBASIC. FWIW, your provided source listing compiles and runs with the freeBASIC if the "-lang DEPRECATED" flag is PASSED to the compiler. (it does provide a warning about a variable).

I know this does not directly pertain to your question, but I think you should give QB64 a try. It is a modern remake of QB and is almost completely syntax compatible. If you are not just doing this for fun and actually want to gain some programming skills, you should choose a more modern programming language as BC suggested (maybe C#) because once you learn that one, most other programming languages will just fall into place; it wont take much learning time because of the similarities.First - A big thank you to DaveLembke, BC_Programmer and Linux711 for your suggestions and help. I appreciate your interest.

Dave: I tried your suggestion for accepting both upper and lower case of a letter. As you suspected the && (AND) || (OR) will not work in QB 4.5. I modified it to a syntax that does work; see my attached file, BOTHCASE.txt. Thanks for the offer for additional assistance.

BC_Programmer I must admit I'd never heard of the "StrComp," function and the code you provided is a little above me at this point. You make a good point about functions and subroutines. I can see where that is better than using GOTO for most of the flow control.

Linux711 I'll add your suggestion to my list of apps to try. So now my list has:
1. QB64
2. Visual Basic
3. FreeBasic
4. QB64

I am doing this for fun but also want to gain some programming skills. 

[recovering disk space, attachment deleted by admin]I think it would be simpler to convert the ENTER$ variable to an uppercas before it goes to the if statement. I believe to do so you type:
 UCASE$(ENTER$)
In your code. Quote from: Newbe on January 27, 2013, 12:36:29 PM
Dave: I tried your suggestion for accepting both upper and lower case of a letter. As you suspected the && (AND) || (OR) will not work in QB 4.5. I modified it to a syntax that does work; see my attached file, BOTHCASE.txt. Thanks for the offer for additional assistance.

Original
Code: [Select]CLS
PRINT "Would you like to print this information?"
PRINT
INPUT "ENTER 'Y' for YES"; Enter$
IF Enter$ = "y" THEN Enter$ = "Y": GOTO PrintIt
IF Enter$ = "y" THEN GOTO PrintIt
IF Enter$ <> "y" THEN IF Enter$ <> "Y" THEN GOTO RUSure
PrintIt:
PRINT : PRINT "Print it": END
RUSure:
PRINT : PRINT "Not print it": END

What about:
Code: [Select]CLS
PRINT "Would you like to print this information?"
PRINT
INPUT "ENTER 'Y' for YES"; Enter$
Enter$ = UCASE$(Enter$)
IF Enter$ = "Y" THEN GOTO PrintIt
GOTO RUSure
PrintIt:
PRINT : PRINT "Print it": END
RUSure:
PRINT : PRINT "Not print it": END
Or, changing it to use structured programming, rather than "street BASIC" stuff (I think I'll describe that in a bit):

Code: [Select]CLS
PRINT "Would you like to print this information?"
PRINT
INPUT "ENTER 'Y' for YES"; Enter$
Enter$ = UCASE$(Enter$)
IF Enter$ = "Y" THEN
    PRINT
    PRINT "Print it"
ELSE
    PRINT
    PRINT "Not print it"
END IF
END
That is essentially what you are "emulating" using the street BASIC goto. GOTO was the only control structure you could use in some early BASIC interpreters for Personal Computers. However, there hasn't been a good reason to limit yourself to using GOTO as the only method of flow control. It makes things more difficult to follow, and as programs get larger, it can become impossible to keep track of all the control flow. This applies equally to "GOSUB"; GOSUB works basically like GOTO, but you can make it return to where you used it with RETURN. For example:

Code: [Select]
CLS
PRINT "Would you like to print this information?"
PRINT
INPUT "ENTER 'Y' for YES"; Enter$
Enter$ = UCASE$(Enter$)
IF Enter$ = "Y" THEN GOSUB PRINTIT ELSE GOSUB NOPRINTIT
END
PRINTIT:
    PRINT
    PRINT "Print it"
    RETURN
NOPRINTIT:
    PRINT
    PRINT "Not print it"
    RETURN
END
This is functionally identical to the above. Naturally the appropriate logic would go within each, as I imagine you are implying with your own example.

Quote
BC_Programmer I must admit I'd never heard of the "StrComp," function
StrComp isn't in QuickBASIC, or most older BASIC dialects. I was thinking of Visual Basic.

Quote
and the code you provided is a little above me at this point.
My code was in error, actually.

The purpose is to create a new Function- STRCOMP, for comparing strings. Though perhaps a stumbling block for you is that you don't appear to be using Functions at all. EXAMPLES of common functions include LEFT$(), RIGHT$(), etc. StrComp() as present in languages that have it- unsurprisingly- compares the two strings you give it. if the first string is less than the second in the sort order, it returns -1; if they are equal, it returns 0. and if the second string is smaller, it returns 1.

Now, I quite recall my initial hurdles learning about Functions. The best way I found to consider them is more or less like a Math function. For example, math usually portrays math functions as f(x), which performs some function f on the value x. Most BASIC dialects include common Functions such as SIN, COS, and TAN.

A Function, then, usually has a few basic properties.

-A Name. This is pretty obvious. You need a name for a function so you can call it and use it.
-Arguments. Most functions take in inputs. for example, the trigonometric functions accept a number. This isn't required, though.
-A return value. This is what the function gives you back.

Now, in the case of StrComp, we have the following:

The Name will follow the standard "convention" of QuickBASIC, which is all uppercase function names. I think it looks ugly and makes the code look like it's yelling but when in Rome... Anyway, the name here will be STRCOMP.

Arguments. Our function will compare two strings. So we will need to accept two strings as arguments. We also want a argument to determine whether we will be case insensitive. We will accept an "INTEGER" number value. 0 will MEAN we don't want to compare text, and 1 will mean we do. ("Compare Text" meaning to be case insensitive)

QuickBASIC's rules regarding functions means we have to "DECLARE" it before we use it. This isn't 100% necessary but it's a good habit anyway. The line is essentially used to tell the compiler "I'm going to be using a Function, if you don't know what it does when you see it, don't worry, I'll tell you".


Code: [Select]DECLARE FUNCTION STRCOMP(BYVAL str1 AS STRING,BYVAL str2 AS STRING, BYVAL COMPARETEXT AS INTEGER) AS INTEGER
the Function is declared with two String Arguments, and one INTEGER argument. the final section says the type of the Function's return value. in this case, INTEGER. BYVAL is worthy og explanation as well. This says that the Function will accept the parameters "By Value". In other words, when you call the function, the function get's a copy of what you sent it. This prevents the Function from changing those parameters, which can cause side effects later on.

Here is the implementation:

Code: [Select]FUNCTION STRCOMP(BYVAL str1 AS STRING,BYVAL str2 AS STRING,BYVAL COMPARETEXT AS INTEGER) AS INTEGER
    IF COMPARETEXT THEN
        str1 = UCASE$(str1)
        str2 = UCASE$(str2)
    END IF
    iF str1<str2 THEN STRCOMP=-1
    IF str1=str2 THEN STRCOMP=0
    IF str1>str2 THEN STRCOMP=1

END FUNCTION
The first step we take is to check if the passed in COMPARETEXT argument is non-zero. This satisfies the IF condition, and we then change the two input strings to be the uppercase versions of themselves by assigning the result from the UCASE$() function on them. After that, we simply follow the convention. "return" values are set by assigning values to the name of the function. In this case, we set the appropriate values to STRCOMP inside the function. The last thing we assigned when the function exits will be used in place of the function call.

Some examples:

Code: [Select]PRINT "StrComp test."
PRINT STR$(STRCOMP("False","FALSE",0))
PRINT STR$(STRCOMP("Turkey","Monkey",0))
PRINT STR$(STRCOMP("Animal","Weasel",0))
Quote
Linux711 I'll add your suggestion to my list of apps to try. So now my list has:
1. QB64
2. Visual Basic
3. FreeBasic
FWIW your budget program works fine in QB64 as well. QB64 is available here



Dear OP,
If you are comfortable with QB 4.5 just keep using it. You can make code that is both easy to read and efficient.

You can define procedures and functions in QB 4.5 as well as different types of variables. And the ability to handle binary files in QB if very good.

You don't need to learn another computer language unless you want to. Any language that does what you want is what you want. Age does not matter.

If someday QB will not run on a new OS, you just put it in a VM and keep working.

BYW, Fort ran is still around and does some very cool things.

Once again my thanks to BC_Programmer for all the help.

Geek-9pm: I appreciate your comments also.Several folks had suggested QB64 as a next step. So when BC_Programmer told me that my "budget program works fine in QB64 as well. QB64 is available here" I clicked the "here" link, downloaded, and installed QB64.

It works fine and I like it but there is one thing I can't figure out how to change. I figured out how to get the editing window to full screen. But when I run the .bas program it goes to another window which is about 1/4 the size of my screen.

In QB45 the program runs in the same window in which the code is entered, while QB64 opens a popup window of about 1/4 the size of the full screen; at least that's what mine does.

I tried running QB64 with a desktop shortcut to qb64.exe and with the following desktop .bat file:

cd\qb64  'Directory on my C: drive where qb64.exe is located.
qb64.exe

What am I missing?http://qb64.net/wiki/index.php?title=FULLSCREENThanks Linux711. I'll let you know how it works out. I haven't tried it yet in a program. It may be a few days though, since I have other stuff going.OK, I tried QB64 and can readily see how much it is advanced over QB45. However, at least on my Win XP machine, it is cumbersome for me - I guess it's just too much for me to absorb at once. 

I wrote the attached program in QB45 and do like the way it looks there - as a 2nd effort anyway. I ran this same code on QB64. It does run but: it opens in a window 1/4 the size of my monitor screen; the top section of the first screen has a blue background for the top half (as I intended) but black for the bottom half. The rest of the program runs the same as in QB45, just in the small window.

There are other items, which I don't need to get into now. My main goal now is composing efficient code.

Comments?

[recovering disk space, attachment deleted by admin]Comments?
Frankly I do not see any need to run this kind of program in 64 bit mode.
To the best of by knowledge there is no advantage to letting a small progrm have more memory space than  it could possibly use.

The code yon provided will compile to a EXE that takes less that a megabyte. And the data space is uses is trivial. Am I missing something here?
Quote from: Geek-9pm on February 08, 2013, 09:42:51 PM
Comments?
Frankly I do not see any need to run this kind of program in 64 bit mode.
To the best of by knowledge there is no advantage to letting a small progrm have more memory space than  it could possibly use.

The code yon provided will compile to a EXE that takes less that a megabyte. And the data space is uses is trivial. Am I missing something here?

-QB64 is a 32-bit program, not a 64-bit one.
-Original QB's data usage is severely limited, as a result of not having access to a Virtual Memory manager. (Go ahead, try to find all the anagrams in a 200K+ Dictionary).
-64-bit Programs do not use more memory space. They have the capability to access more memory, though.

Also: QB64 appears to auto-update. Though that one could go either way. It is actively developed, however, which is a  plus.

As for efficiency: Switching to subroutines and functions will speed up the code significantly.

GOTO of course compiles to an Assembly JMP instruction. The issue with it is that it often wreaks havoc on the CPU prefetch cache, and basically every JMP will flush the prefetch queue. CALL and RET- which are used for functions and subroutines- work with the prefetcher logic. This wouldn't have a impact on your program- your program is currently fine, since most of it's time is spent waiting for user input.
397.

Solve : for command question?

Answer»

This SEEMS to simple to be asking for help but here goes, help!
I'm running Windows7.

I'm writing a bat file with a for command that will open a TXT file containing several lines. Each line is a full path to a file that I want to copy to another location. The full path may CONTAIN a space character.
Example:
C:\Program Files\Java\jre6\README.txt

Here is the for command I am using:
FOR /F "usebackq tokens=1" %%A IN (C\temp\file_path.txt) DO (
echo File=%%~A
)

In file_path.txt I have the path above surrounded by double quotes ("").
Example:
"C:\Program Files\Java\jre6\README.txt"

When I run the bat file I get:

C:\Temp>FOR /F "usebackq tokens=1" %A IN (C:\temp\file_path.txt) DO (echo File=%~A )

C:\Temp>(echo File=C:\Program )
File=C:\Program

C:\Temp>pause

What am I missing that won't allow the for command to capture the entire line past the space character?

Thanks. Quote from: skibumsam on September 24, 2013, 10:18:34 AM

What am I missing that won't allow the for command to capture the entire line past the space character?

You are mistaken in thinking that tokens=1 will compress the whole line into the %%A metavariable. What the tokens=1 element does is take the line up to the first delimiter and put that first token into the EXPLICIT FOR metavariable (%%A in this case). If there were more tokens specified by numbers they would (assuming they were present in the line) be assigned to implicit metavariables starting with the next letter of the alphabet in the same case (here, %%B). Spaces and tabs are the fault delimiters if no other(s) is (are) specified using delims=. If you want to get the whole line into %%A you need to specify that the delimiter is the end of the line. That is, delims= followed by the closing double quote of the options BLOCK. You can do so like this

FOR /F "usebackq delims=" %%A IN (C:\temp\file_path.txt) DO (

By the way, in the filespec there needs to be a colon after the drive letter.

You are using usebackq when you don't need to.







Thanks.
That did it.
398.

Solve : Why doesn't my timer work??

Answer»

I have a well-DEFINED derived CWnd class, say myClass. I set a timer at beginning: SetTimer (999, 1000, 0) inside a member function of myClass.
Then I defined my own timer service routine:
void myClass::OnTimer(UINT_PTR nIDEvent)
{
    MessageBox("err","err",MB_OK);
    MessageBeep(0xFFFFFFFF);   // BEEP
    debugMsg ("hello");
    serial.Write("hello", 5);
    CDialog::OnTimer(nIDEvent);
}

But I found it doesn't work according to the four non-executed statements. That is, no message box is popped out, no beep sound, no hello message, no message sent to serial port. What's wrong with it?
Are you able to post the full source code? I think your problem is located elsewhere than the shared source. I am guessing you have all your includes ETC otherwise it wouldnt compile, so what you have now is source that compiles but you are not getting the operation of the source that is desired.

At times LIKE this I generally will place a message to pop up at certain sections of the source code to verify that it is calling and executing the routines. And comment out this or remove it and move on. I have also used the method of commenting out full sections of code via /* followed by */ to try to isolate problems and then when I know that the problem is located within the commented section of code I know where to look. Or there is a function within this section of code that is missing the proper #include<  >. Also I have also run into issues with my includes to where adding or removing the .h such as #include or #include makes a difference for the library header that is related to the malfunction, although using .h is the older C standard library header and without the .h is the modern C++ standard library header. I havent run into this in a while and I think it was with Borland C++ that I ran into this problem years ago.

 Generally source like this that compiles and does not function as intended is because there is a minor typo in which something as small as a lower case letter in place of an uppercase letter or missing underscore or added underscore between the call and the function cause the problem and the compiler is satisfied, although I know that with BloodShed Dev C++ it will warn me of uninitialized calls when compiling which point out the fact that I initialized something as Get_UPC and further on in the source I have GET_UPC and it compiles but it doesnt function properly, although like I said usually I get a warning when compiling, if not a error that needs to be corrected before it will compile.

So does this compile clean with no errors and no warnings, or does it compile SUCCESSFULLY yet your getting warnings which could help find the cause for the malfunction?

Which IDE and version are you using to create/compile this program?

399.

Solve : Migrate Console App to Windows 32 App C++?

Answer»

I have a program that I wrote up in C++ as a Console App using Bloodshed Dev C++ 4.9.9.2 and it works perfectly fine. But the interface is ugly as can be expected from the limitations of working in a Console App environment.

I looked on google for some good information on converting a Console App to Windows 32 App what little I found wasnt very helpful.

What I was thinking of doing is using Microsoft Visual C++ 2010 Express to make a nice GUI for this otherwise ugly looking program and add bottons to be selected to trigger events vs a user having to enter Y or N at prompts, and then run the program. BUT I also think that if I got this added as a button click routine that it might break the functionality of the program.

The program is basically a Disc to Disk Archive Creator. I have decided to purchase a 3TB external drive and TAKE stacks of data CD's and DVD's and xcopy their contents to this massive external hard drive. But instead of doing it with a batch file, I decided to do it in C++ Console App programming instead.

This is how the program runs:

1.) I basically have my program asking for Source and Destination Drive info.
2.) Verifying that the info is correct Y/N ( If incorrect the loop sends them back through config process )
3.) Read in from a file that keeps track of last counter++ value
4.) Create a directory at the destination that is named (DestDriveLetter):\DiscX ( where X = the next available counter value ) through String Steam Concatonation passed to a system(); call.
5.) Concatonate via String Stream an XCOPY routine to copy the information from the source to the destination, and user variables as entered by the user from say D:\*.* to say E:\Disc32\
6.) Notify the user that the disc is complete and ask if they want to run another Y/N ( If YES, tell user to swap disc's and then enter C to continue to process the next disc at say E:\Disc33\ ... If NO, then write the next available counter value to counter text file and exit program.

Next time the program is run it will pick up at 33 if no Disc was processed as 33.

* Thinking of adding an override for the counter so that you dont have to edit the counter file back to 1 and save it to start fresh on another group of discs for a different Data Disc Archive.

But my concern lies in if you can actually pass a system(); call in a Windows 32 App which is not running from a Command Shell Console App environment, in which the Windows 32 App may not be that friendly with executing DOS instructions.

Anyone have any info on how to make this work? Found very little information on this matter, and maybe there is a BETTER way than string streaming to system(); to achieve this since system(); calls are not a good practice as I have read scattered on the web. But I am not aware of any other way to interface with DOS / Command Shell without it in C++.

I can also post the source code here if it helps any. Its pretty basic. And works well as it is now. I just want to see if it can be added to a modern looking GUI interface by use of Microsoft Visual C++ 2010 Express or if its impossible to be done.Even though it may not be elegant (from a programmers perspective), the easiest way I think you could do this would be to make the program take command line parameters as the input instead of asking the user directly for input. This way, you can control the functions of your console program through a GUI by executing the program with command line switches. This wouldn't work obviously if you don't have access to the source anymore though. If you want to do it right though, it shouldn't be too hard to modify to make a GUI version. I might be able to help you with it if you'd like.Hello Linux711 ... sorry its been a couple days before getting back to you. Here is my source code to the program that I am interested in getting rid of the ugly ascii console 1980s look and make it look more modern. I put this up on the web at Github for free download and for people to build from it if anyone is interested under GPL license. https://github.com/AthlonX2/Disc2Disk/releases  ( Latest is at bottom of list on page. Havent figured out yet how to get the newest to the top and put oldest at bottom. )

Given its not very complicated and just a glorified batch type process wrapped around C++ assigning it a GPL is probably not necessary, but I did so anyways.

All the books I have on Visual C++ do not touch on command shell execution from windows and that is why I hit a wall with making this work using Visual C++ 2010 Express. I did some research earlier today on C# another language that I like to work with and found this http://stackoverflow.com/questions/2794386/system-to-c-sharp-without-calling-cmd-exe , but havent played around with it yet. I may be able to pass as an argument to cmd.exe the information that I currently string stream in C++ which would make this program run in a Windows Window App and then pop up a command shell window when it processes and then the command shell window disappears when completed in which the information on the Windows Program App of this program would then state that the "Process is complete, Please Insert another Disc and Press (the button action) for this action to run another or (the button action) to exit the program."

This program works with the attached LastValue.txt file which keeps track of the last Disc ID processed, so if you stop after processing a bunch of discs, and then continue later on it knows to start off as say Disc86 as the next available folder to create at the destination and continue on from there. This file just initializes the counter to the last available disk number as a passed integer from the file.

Code: [Select]// Disc to Disk Archive Creator Version 2.1
// Programmed by Dave Lembke - 8/28/2013
// Released as FREEWARE under GPL

// Rev Notes:
// Found interface was lacking clarity from 2.0 such as it doesnt prompt user to swap Disc's
// Added color change to prompt process complete

#include <iostream>
#include <fstream>
#include <sstream>
 
using namespace std;
 
int main()
{
    int loop1=1;
    int loop2=1;
    int foldercounter=1;
    char junk;
    char junk2;
    char destination1;
    char source1;
   
    // Read in from text file the value for foldercounter variable
        ifstream MYFILE("LastValue.txt", ifstream::in);
        while(myfile >> foldercounter);
   
   
 while(loop1==1){
 system("color F0"); // change shell text color       
    cout<<"                     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n";
    cout<<"                     XX   Disc to Disk Archive Creator   XX\n";
    cout<<"                     XX -------------------------------- XX\n";
    cout<<"                     XX           Version 2.1            XX\n";
    cout<<"                     XX Programmed by Dave Lembke in C++ XX\n";
    cout<<"                     XX 8/28/2013 for use with Windows 7 XX\n";
    cout<<"                     XX & older Windows OS systems that  XX\n";
    cout<<"                     XX support the XCOPY /s/d/y Command XX\n";
    cout<<"                     XX -------------------------------- XX\n";
    cout<<"                     XX   Copyright 2013 - Dave Lembke   XX\n";
    cout<<"                     XX     This software is FREEWARE    XX\n";
    cout<<"                     XX -------------------------------- XX\n";
    cout<<"                     XX  USE AT OWN RISK ... PROGRAMMER  XX\n";
    cout<<"                     XX    NOT LIABLE FOR ANY DAMAGES    XX\n";
    cout<<"                     XX Close Window or CTRL + C to Exit XX\n";
    cout<<"                     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\n\n";

    cout<<"           Enter Drive Letter of Source Drive ( WITHOUT THE ':' COLON )\n\n";
    cin>>source1;
    cout<<"           Enter Drive Letter of Destination Drive ( WITHOUT THE ':' COLON )\n\n";
    cin>>destination1;

    cout<<"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
    system("color 4F"); // change shell text color
    cout<<"                           <<<   WARNING   >>>\n\n";
    cout<<"                    You will be Transferring Data from\n\n";
    cout<<"                          [ "<<source1<<": ] to [ "<<destination1<<":\\Disc"<<foldercounter<<" ]\n\n\n\n\n\n\n\n\n\n";
    cout<<"      <<< If this is correct Enter  ( Y ) for YES otherwise ( N ) for NO >>>\n";
    cin>>junk2;
    if(junk2=='Y'||junk2=='y'){
                 loop1=0;
                 cout<<"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
                 }
                 else {
                 cout<<"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
                 }
}
    while(loop2==1){
system("color b0"); // change shell text color               
STRINGSTREAM ss;
ss << "MD " << destination1 << ":\\Disc" <<foldercounter;
system( ss.str().c_str() );
cout<<"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
cout<<"        Disc Folder # [ "<<foldercounter<<" ] Created ... Starting Transfer Process...\n\n\n\n\n\n";

stringstream ss1;
ss1 << "xcopy " << source1 << ":\\*.* " <<destination1<<":\\Disc"<<foldercounter<<"\\*.* /s/d/y";
system( ss1.str().c_str() );

    cout<<"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
    system("color e0"); // change shell text color
    cout<<"                             XXXXXXXXXXXXXXXXXXXX\n";
    cout<<"                             X Process Complete X\n";
    cout<<"                             XXXXXXXXXXXXXXXXXXXX\n\n\n\n\n\n\n\n\n";
    cout<<"                         Replace the Disc with another\n";
    cout<<"                  and Enter ( Y or N ) to process another Disc\n";
    cout<<"                Note: Entering ( N ) for NO will Exit this program\n";
    cin>>junk;
    if(junk=='Y'||junk=='y'){
               loop2=1;

               //write value to pick up with next time program is run here
       std::ofstream write ("LastValue.txt", std::ofstream::out);
       write << foldercounter;
       write.close();
       foldercounter++; // Increment after write in case user aborts before telling program to end
                        // and avoid a gap from say 4 to 6 without 5 if they abort via ctrl + C or
                        // by closing the shell window via [x] at 4 just processed.
               }
               else{
       foldercounter++; // Increment to the next value for next time to start with
       std::ofstream write ("LastValue.txt", std::ofstream::out);
       write << foldercounter;
       write.close();
               return(0);
               }
               }
}
[recovering disk SPACE, attachment deleted by admin]I would just rewrite it. Don't defer to Xcopy. Copy the file yourself.

If you really insist on doing so, you can use Process.Start() to start the xcopy but make it display hidden. eg:

Code: [Select]    var psi = new ProcessStartInfo()
    {
        WindowStyle= ProcessWindowStyle.Hidden
    };
    Process xcopyprocess = Process.Start(psi);
} (C#). has API functions that allow you to do this.

Personally, I think it would be a waste of time. First, you would want to know what goes wrong- if the xcopy fails or needs input for any reason, it just hangs. The window is hidden and invisible so nobody can ever interact with it. So the best you can do is manually use the ProcessStartInfo and redirect the child processes Standard Input and Standard Output, so now your program can interpret what is being written to the "console" and send output to it if desired. Now you need to detect all sorts of error conditions, and just being able to read the streams properly is going to take quite a bit of code on it's own, relatively speaking.

Much easier on your sanity to simply learn how to copy a file yourself, then how to copy a group of files, then you can add logic for date checking, etc.

400.

Solve : Batch: size of folders from a list?

Answer»

Hello,

I have this script:

Code: [Select]echo off
setlocal
set /p DIRNAME=Enter Directory Name:

for /F "tokens=3-4" %%v in ('dir "%dirName%" /s ^| find /i "file(s)"') do (
  set BYTES=%%v


echo FOLDER: %dirName% contains %bytes% bytes

pause
The problem is I want to import from a .txt file with various directory folders.

How can I do that?


Thank you!