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.

201.

Solve : Java Classpath problem...?

Answer»

Hi everyone,

I have a little problem, let me explain the situation.
I have made a .java file in Eclipse (Im working on WINDOWS 7 ULTIMATE atm). I compiled it, ran it, it worked.
Now I moved the class file to another directory (I:\System\java).
In I:\System\java\JavaWin i have a portable version of java 1.6.0_30-b12 (launcher made by PortableApps.com)
This works and does everything I want to, I can check the version number etc...
I made a bat file containing the following Code: [Select]JavaWin\bin\java OS > log.txtThis works. This is because the bat file is in the same directory as the .class file.
But when I open cmd leave the directory at C:\Users\Myname and then excecute this command it doesn't work (I left out the log.txt part for now).
Code: [Select]I:\System\java\JavaWin\bin\java I:\System\java\OsOnce again, because the current directory isn't the same as the directory of my .class file this won't work. (it throws a NoClassDefFoundError)
Then I tried adding the classpath:
Code: [Select]I:\System\java\JavaWin\bin\java -cp I:\System\java\ I:\System\java\OsStill to no avail.
Yes my Os.java file contains a public STATIC void main etc etc, so that's not the problem.
I tried everything, adding -cp, -classpath, all the options I found by googlin, nothing works.
Java is installed on my system, but I want to use the portable version, if possible...

Can somebody help me with this silly issue?
Thanks in advance!
Um, why is nobody answering?
Is this so hard to fix/so UNUSUAL

EDIT: I fixed it, thanks to lina19 =)
Code: [Select]I:\System\java\JavaWin\bin\java -cp I:\System\java\ OsHence, the Class parameter, is the classname, not the path to the .class file

202.

Solve : String stuff c++?

Answer» 0    >object_p/long1.png<  x=0 y=226
1    >object_p/long1.png<  x=639 y=226
2    >object_p/long1.png<  x=1279 y=226
3    >object_p/p4.png<  x=215 y=142
4    >object_p/p5.png<  x=457 y=90
5    >object_p/p6.png<  x=691 y=61
6    >object_o/box1.png<  x=775 y=37
7    >object_o/car5.png<  x=618 y=180
8    >object_o/signright.png<  x=5 y=195
9    >object_o/signup.png<  x=206 y=197
10    >object_o/lamp2.png<  x=113 y=113
11    >object_o/lamp2.png<  x=545 y=120
12    >object_o/lamp3.png<  x=936 y=161
13    >object_o/car5.png<  x=1019 y=181
14    >object_o/car6.png<  x=832 y=192
15    >object_p/block3.png<  x=768 y=175
16    >object_p/block2.png<  x=1225 y=177
17    >object_p/p4.png<  x=1355 y=71

i have those information above store as a txt file.
in c++
How i can retrive only the file path and store it in array string?
file path are located between > path <
Thank youSo FAR i got to this

ifstream levelFile ("levels/lv1/level.txt");
   int start, end;
   if (levelFile.is_open())
   {
      string line;
      getline(levelFile,line);   //this is used to skip the first line
      while ( levelFile.good() )
      {
         getline(levelFile,line);
         for (int i = 0; i < line.length(); i++)
         {
            char newLine[100];
            strcpy_s(newLine, line.c_str());
            
            if (line.at(i) == ">" ) { start = i; }    << why cant i do this
            if (newLine == "<") { end = i; }   << why cant i do this
         }   
      }
      levelFile.close();
   } else cout << "Unable to open file";
it doesnt matter now ive DONE it.... SORRY for posting but i was really frustrated but with abit of reading i wont be posting problem againb until i really need help.

Solutions

ifstream levelFile ("game_resource/lv1.txt");
   int start, end;
   string fPath;
   char NL[] = ">";
   char nt[] = "<";
   if (levelFile.is_open())
   {
      string line;
      getline(levelFile,line);   //this is used to skip the first line
      while ( levelFile.good() )
      {
         getline(levelFile,line);
         for (int i = 0; i < line.length(); i++)
         {
            if (line == nl[0]) { start = i; }  <<btw line is suppose to be line(i)
            if (line == nt[0]) { end = i; }
         }
end = end - start;
         fPath = line.substr(start, end);
      }
      levelFile.close();
   } else cout << "Unable to open file";
203.

Solve : duplicate : how to remove varible from a list?

Answer»

hey I am doing something like following:

var1='1 2 3 4 5'

for VAR in $var1 {NEED to choose the variable randomly used rand($var1) but its not working }
do
echo $var
done

now as i print the $var i need this value should be removed from the variable $var1, how to do that ?
I am using unix shell scripting

Thanks
RG
   
hey I am doing something like following:

CODE: [Select]var1='1 2 3 4 5'

for var in $var1 {Need to choose the variable randomly used rand($var1) but its not working }
Code: [Select]do
echo $var
done
now as i print the $var i need this value should be removed from the variable $var1, how to do that ?
I am using unix shell scripting

Thanks
RG
Quote from: roohi on November 28, 2011, 01:46:09 AM


var1='1 2 3 4 5'

for var in $var1 {Need to choose the variable randomly used rand($var1) but its not working }
do
echo $var
done


Solve teh problem of by using following :

Code: [Select]var1=$(echo $var1 | sed "s/$var//")
But STILL How can i select the random varible from the list Question is there.
Please suggest.make an array of variable in list , find the index of that array .
Do Code: [Select]X=rand()%index to generate the random number and with that random number go to the array element : Code: [Select]array [x]
This will give you the random selection for each time.

Thanks
RGhello i dont know which language you are working on...but from my experience..

are the syntax correct?


u declare
var1='1 2 3 4 5'

then u said
for var in $var1

i think you should declare var1 as $var1='1 2 3 4 5'

and for $var in $var1



204.

Solve : Python Help - Simple (X , Y) coord display?

Answer»

I am trying to create a program that returns an (X , Y) coord that increases or decreases based on INPUT of either X, -X, Y, or -Y. However, when I run it it always returns (0 , 0). What am I doing wrong? Here is my code.


#!/usr/bin/python
#Simple Grid Display - B. Owens
def grid():
   #Z is the X coord, C is the Y coord
   global z
   global c
   z = 0
   c = 0
   print (“Which way would you like to move? X, -X, Y, or –Y?”)
   a = raw_input()
   if a == “X”:
      z + 1
   if a == “-X”:
      z – 1
   if a == “Y”:
      c + 1
   if a == “-Y”:
      c – 1
   print (z),©
   grid()
grid()
Code: [Select]#!/usr/bin/python

def grid():
   x = 0
   y = 0
   while(True):
       print("Which way would you like to move? X, -X, Y, or -Y? (Q to quit):")
       a = raw_input()
       if a == "X":
          x = x + 1
       elif a == "-X":
          x = x - 1
       elif a == "Y":
          y = y + 1
       elif a == "-Y":
          y = y - 1
       elif a == "Q":
           return
       print (z),(c)
grid()

There were some logic errors in the original code as well.

First, you never actually change the contents of z or c. you calculate the new coordinate but you never store it into the value.
Second, the structure was... ill-thought out. The way it was worked was as a recursive function call; each prompt was in fact a recursive call. The problem being that recursion typically requires an end case that is being worked towards; however, it was being used as a poor substitute for a loop. (and WILL crash if it is run too long from a stack overflow) My version uses a while loop instead; as a result, since the variables are only accessed in the local routine (which doesn't exit until the user enters "q") making the variables global is no longer necessary.

Also, the original code was littered with non-ascii characters; "smart quotes", a em-dash (RATHER than a minus sign) and a few others. Not sure how they GOT into the code. using the "code" bbcode tag can HELP prevent this, though the forum doesn't add smart quotes or em-dash's so I'm not sure where those came from.
 Thank you so much! I am a begginner at Python, the only programming LANGUAGE I have any experience with is BASH, and learning without a tutor has been rather difficult Thanks for the help!

205.

Solve : java programming language for mobile , need help, plss :(?

Answer»

hi everyone.

i need to KNOW how to write a small program in java to mobile ?
i know java programming language for pc but is it different than mobile?
anyone KNOWS any link? or toturials ?

thanksProbably the MAIN difference will be in widgets/user interface elements.  Lots to read here:

www.google.com/search?hl=en&source=hp&biw=1501&bih=959&q=java+for+mobile+devices&oq=java+for+mobile+devices&aq=f&aqi=g1g-v4g-b3&aql=&gs_sm=e&gs_upl=984l5248l0l5910l23l19l0l3l3l0l498l2780l5.5.4.1.1l16l0The language will be exactly the same. The only difference is the class library.

http://www.oracle.com/technetwork/java/javame/index.htmldownload netbeans

go to file-project-samples-javaMe- buetooth demo....

u can test this application on 2 mobile if you want....and start working from therethank u all, i got idea.. ur answers helped me.. thanks alot )

206.

Solve : why does OS shutt down computer during load??

Answer»

I have a HP Pavilion Entertainment Notebook (dv 1000)
when i try to load the OS (win XP Home), it gets to the point of creating the partition, then just shutts down the whole pc.
only once did it say that it dont detect any HDD. I set the cmos to default, try to RUN it again and it just shutts down my laptop
can anyone shed some lite on the matter?hello..
try to repair ur laptop , before windows START log in press f8 continuously and select repair .. might be bad sectors are there in HDD 1) Feel free to ignore the above post
2) I deleted your duplicate post - just one post per problem please.
3) Please describe your problem IN DETAIL - INCLUDING what led up to it.

207.

Solve : aesza?

Answer»

powiedz mi CO to jest NOSNIK komputera?What KIND of media?

208.

Solve : bash concatenate?

Answer»

Hi people,

I have a little problem with a bash script of mine.
Code: [Select]DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PATH="/System/java/"
echo $DIR                           #gives the working directory /media/*name of USB stick*
echo $PATH                          #gives /System/java/
echo $DIR$PATH                      #gives /System/java/, should give /media/*name of usb stick*/System/java/
FULL=$DIR$PATH                      #should concatenate
echo $FULL                          #gives /System/java/, should give /media/*name of usb stick*/System/java/
FULL=${DIR}/System/java/            #should concatenate
echo $FULL                          #gives /System/java/, should give /media/*name of usb stick*/System/java/

The script is stored on a USB stick
My GOAL is to get the current directory (where the script lives, not the working directory), which is stored in DIR. (This works)
Then I want to append the string "/System/java/" to it. Then I can use that string to do my stuff (not important for this question..)
I just can't figure out why it gives me this output...
Bash version 4.1.10, if anyone cares, since this stuff should work since version 3.1....

Can somebody help me with this?

EDIT: If I do this:
Code: [Select]echo ____________________$DIR$PATHI get this: /System/java/___________/media/*name of usb stick*
It's like it first prints the underscores, then the DIR and then puts PATH over all that..set "str1=Hello"

set "str3=%~dp0% %str1%"

echo.%str3%
pause


i dont know if this cna help...im new to it...im trying to get the value of str1 ...i mean hello Quote from: lina19 on January 10, 2012, 02:27:35 PM

set "str1=Hello"

set "str3=%~dp0% %str1%"

echo.%str3%
pause


i dont know if this cna help...im new to it...im trying to get the value of str1 ...i mean hello

What you want to get is e.g.: "I:\Hello"

Code: [Select]set str1=Hello
echo %str1%
set str3= %~dp0%str1%

echo %str3%
pause

But this has nothing to do with my question, it is the same problem in another scripting language...
The only difference is that here it works and in bash scripting it does weird stuff (at my pc at least)#!/bin/bash
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PATH="/System/java/"
FULL=$DIR$PATH
echo $DIR                         
echo $PATH                         
echo $DIR$PATH       
echo $FULL                         
FULL=${DIR}/System/java/
echo $FULL
echo "________________"$DIR$PATH


I had to adjust the amount of underscores to see the $DIR$PATH.
Hope is helps.

I used cygwin btw :-)You just adjusted the number of underscores to the number of signs in DIR/PATh to see them printed next to each other.
The point is that I shouldn't neet underscores or whatever "filling signs" to print them next to each other.
I have a variable FOO and I want to concatenate it to the variable BAR and store it into a new one FULL.
Then when I should print FULL I should see the CONTENTS of FOO at the time of the concatenation and then  the contents of BAR at the time of the concatenation.

Google says that it should work. All the sites say this:
FULL=$FOO$BAR
or
FULL=$FOO"contents of BAR"
or
FULL=${FOO}${BAR}

EDIT: I found something strange. When I output it to a text file (append > file.txt to the command) it writes the correct output to the file....I think I found it 

You need to do a dos2unix conversion first.

When you MADE your script in (most likely) a windows text editor (like notepad), the text editor puts a cariage return "\r" and another character at the end of each line.

You can see these characters in notepad++ by selecting "show all characters" from the "view > non-printable characters" menu.

The Bourne again shell does not like these characters. Therfore you need to convert the dos/windows file into a unix file. Cause Unix files have these characters in a different form.

What I did:

1. Open cygwin terminal.
2. Type: dos2unix yourfile.sh
3. Hit enter
4. Type: sh yourfile.sh
5. Hit enter

No text-overlap in my window 


Good luckthats nice learning_cmd...your learning very fast....yea i was guessing it was some kind of conversion issue...but didnt know what to do....
nice workThanks that's nice, I didn't think of that immediately!
Btw you don't need that dos2unix file, I just used Notepad++ (Edit menu, then Formatting/Format, Unix)
Thanks for your time and help you 2 =) 
If you have a problem, PM me if you want ^^What you said.

All CR's gone on the fly  Quote from: Bennieboj on January 11, 2012, 09:31:24 AM
Thanks that's nice, I didn't think of that immediately!
Btw you don't need that dos2unix file, I just used Notepad++ (Edit menu, then Formatting/Format, Unix)
Thanks for your time and help you 2 =) 
If you have a problem, PM me if you want ^^
Isn't the point of creating a script so that there is no user intervention?or use tr:

Code: [Select]tr -d '\015' < inputfile.txt > result.txt
Quote from: Squashman on January 11, 2012, 11:05:20 AM
Isn't the point of creating a script so that there is no user intervention?

Yes it is, there ain't any user intervention.
Why you're quoting my post?
I don't see the reference to anything I said and the question.

BC: thanks, but I'm not much of a command ninja =)
209.

Solve : Help with VBScript?

Answer»

Hello,

This would probably be a pretty easy fix for a knowledgeable individual but it isn't for a beginner like me.

I simply would like the output of the following game script to DISPLAY on two columns.

Many thanks to anyone who would take time to help me out.

MX

Code: [Select]Sub Init
cs = GetChatSession()
ci = cs.GetLastItem()

ci.Text = Trim( ci.Text)
If Len( ci.Text) > 0 Then
RollInit
Else
ShowInits
End If
End Sub


Sub RollInit
cs = GetChatSession()
ci = cs.GetLastItem()

sLine = ci.Text
ci.Text = sLine & "<i>[Command not understood<br> - use<br><ul><li>/init<li>/init player_name<li>/init player_name<li>dice_expression<li>/init player_name, number</ul>]</i>"

sChar = ""
nBonus = 0
sBonus = ""



n = InStr( sLine, ",")
If n > 0 Then
sChar = Trim( Left( sLine, n-1))
sBonus = Trim( Mid( sLine, n+1))
If Len( sBonus) > 0 Then
nBonus = EvalDice( sBonus)
End If
'If IsNumeric( sBonus) Then
' nBonus = CInt( sBonus)
'End If
Else
sChar = Trim( sLine)
End If

oPlayer = GetCurrentPlayer()
'If oPlayer <> NULL Then
If NotNull( oPlayer) Then
oChar = oPlayer.GetCharacter( sChar)
If NotNull( oChar) Then
If Len( Trim( sBonus)) < 1 Then
sBonus = "1d20"
End If
nInit = EvalDice( sBonus)
oChar.SetField "initroll", CStr( nInit)

If InStr( LCase(sBonus), "d") < 1 Then
ci.Text = sChar & " SETS initiative to <b>" & CStr( nInit) & "</b>"
Else
ci.Text = sChar & " rolls <b>" & CStr( nInit) & "</b> for initiative (" & sBonus & ")"
End If
Else
ci.Text = "init " & sLine & "<i>Unknown Character '" & sChar & "'</i>"
End If
Else
ci.Text = "init " & sLine & "<i>No Current Player</i>"
End If
End Sub


Sub ShowInits
cs = GetChatSession()
ci = cs.GetLastItem()
os = GetCurrentSession()

DIM aInitList(200)
Dim nInitCount

nInitCount = 0

os.Sync
n = os.GetSyncCharCount()
For i = 1 to n
c = os.GetSyncChar( i)
sInit = c.GetField( "initroll")
If Len( Trim( sInit)) > 0 Then
sInit = String(3 - Len( sInit), "0") & sInit
aInitList(nInitCount) = sInit & "  " & c.Name
nInitCount = nInitCount + 1
End If
Next

If nInitCount > 0 Then
QuickSort aInitList, nInitCount+1, false
End If


r = r & "<br><font color='" & os.GM.ChatColor & "'>"

sInitDice = os.GetField( "initdice")
If Len( sInitDice) > 0 Then
r = r & "(init dice set to: " & sInitDice & ")<br>"
End If


'r = r & "<br>Current Inits are...<br>"
For i = 1 to nInitCount
'trim away leading zeros
sInit = Left( aInitList(i-1), 3)
If Left( sInit, 1) = "0" Then
sInit = " " & Mid( sInit, 2)
End If

If Left( sInit, 2) = " 0" Then
sInit = "  " & Mid( sInit, 3)
End If

r = r & sInit & Mid( aInitList(i-1), 4) & "<br>"
Next
r = r & "</font>"

ci.PlayerTo = ci.PlayerFrom
ci.PlayerFrom = "Current Initiatives are"
ci.Action = ""
ci.Text = r
End Sub

Sub ClearInits
cs = GetChatSession()
ci = cs.GetLastItem()
os = GetCurrentSession()

op = GetCurrentPlayer()
If op.IsGM Then
os.Sync
n = os.GetSyncCharCount()
For i = 1 to n
c = os.GetSyncChar( i)
sInit = c.GetField( "initroll")
If Len( Trim( sInit)) > 0 Then
c.SetField "initroll", ""
End If
Next

ci.Action = "reports"
ci.Text = "initiatives cleared"
Else
ci.PlayerTo = ci.PlayerFrom
ci.Text = "<i>[Sorry, only the GM can clear the initiatives!]</i>"
End If

End Sub



Sub SetInitModifier
cs = GetChatSession()
ci = cs.GetLastItem()

sChar = ""
sMod = ""
bSet = False


'Get command line
aLine = Split( ci.Text, ",")
If UBound( aLine) > -1 Then
sChar = Trim( aLine(0))
End If
If UBound( aLine) > 0 Then
sMod = Trim( aLine(1))
End If


oPlayer = GetCurrentPlayer()
If NotNull( oPlayer) Then
oChar = oPlayer.GetCharacter( sChar)
If NotNull( oChar) Then
oChar.SetField "initmod", sMod
bSet = true
End If
End If

If bSet Then
ci.Text = sChar & " sets init modifier to " & sMod
Else
ci.Text = ci.Text & "<i>[Command not understood, or you're trying to set the initiative modifier for a character that is not yours]</i> " & sChar & sMod
End If


End Sub

Sub InitSelected
RollInitsSelected( False)
End Sub

Sub InitAll
RollInitsSelected( True)
End Sub

Sub RollInitsSelected( bAll)
cs = GetChatSession()
ci = cs.GetLastItem()
os = GetCurrentSession()
sLine = ""
sInitDice = ""


sInitDice = os.GetField( "initdice")
If Len( sInitDice) < 1 Then
sInitDice = "1d20"
End If

op = GetCurrentPlayer()
If op.IsGM Then
os.Sync
n = os.GetSyncCharCount()
For i = 1 to n
c = os.GetSyncChar( i)
If (bAll = true) or (c.Selected = true) Then
sMod = c.GetField( "initmod")
nMod = 0
If IsNumeric( sMod) Then
nMod = CInt( sMod)
End If
nInit = EvalDice( sInitDice)
nInit = nInit + nMod
c.SetField "initroll", CStr( nInit)
'sLine = sLine & CStr( nInit) & " " & c.Name & " (" & CStr( nMod) & " modifier)<br>"
End If
Next
ShowInits
ci.PlayerFrom = "TheGM rolls for initiative"
'ci.Action = "reports"
'ci.Text = "<br>Initiative(s) rolled<br>" & sLine
Else
ci.PlayerTo = ci.PlayerFrom
ci.Text = "<i>[Sorry, only the GM can do that!]</i>"
End If

End Sub


Sub SetInitDice
cs = GetChatSession()
ci = cs.GetLastItem()
os = GetCurrentSession()
sLine = ""

op = GetCurrentPlayer()
If op.IsGM Then
os.SetField "initdice", ci.Text
ci.Action = "sets initiative dice type to " + ci.Text
Else
ci.PlayerTo = ci.PlayerFrom
ci.Text = "<i>[Sorry, only the GM can do that!]</i>"
End If

End Sub

'==== Sorting Routines found on Usenet =====
'Just call QuickSort with Array and its size
'and True for Ascending False for descending
Function QuickSort(strAr, nSize, bAscending)
 rc = TRUE
 If (nSize > 1) Then
  low = 0
  high = nSize
  'Call the QuickSort Recursive Function
  QuickSortRecursive strAr,low,high,bAscending
 Else
  rc = FALSE
 End If
 QuickSort =  rc
End Function

'==================== QUICK SORT RECURSIVE
Function QuickSortRecursive(strAr,  d, h, bAscending)
 i = h
 j = d

 str = strAr(((d+h) / 2))
 do
  If (bAscending) Then
   while (strAr(j) < str)
    j = j + 1
   wend
   while (strAr(i) > str)
    i = i - 1
   wend
  Else
   while (strAr(j) > str) j = j + 1
   wend
   while (strAr(i) < str) i = i - 1
   wend
  End If

  If ( i >= j ) Then
   If ( i <> j ) Then
    zal = strAr(i)
    strAr(i) = strAr(j)
    strAr(j) = zal
   End If

   i = i - 1
   j = j + 1
  End If
 loop while (j <= i)

 If (d < i) Then
  QuickSortRecursive strAr,d,i,bAscending
 End If
 If (j < h) Then
  QuickSortRecursive strAr,j,h,bAscending
 End If
End Function

I could probably help you if this was a normal vbs, but I can't figure out how to run it. Can you explain how this works? Should it be in a web PAGE or something? Quote from: Linux711 on January 14, 2012, 01:00:01 PM

I could probably help you if this was a normal vbs, but I can't figure out how to run it. Can you explain how this works? Should it be in a web page or something?

Yes actually, the output displays in a chat window of a web browser.

Thank you for TAKING the time whether you do find a solution or not.
210.

Solve : VBA Timer??

Answer»

I'm making a puzzle game in PowerPoint in which each level you have to press a button while avoiding obstacles. Most of the general stuff is being programmed in VBA. However, in each level there will be a timer that will silently count down from 60 to 0. Once the level is complete, it will add the amount of seconds left to the score.

The Sleep function totally stops execution of PowerPoint, so I can't use that for the delay in the countdown (I've tried, and I had to press the windows key and close PowerPoint 'cause it wasn't responding).

How can I have a silent timer that won't FREEZE everything?Think this is what your looking for: http://www.tushar-mehta.com/powerpoint/ppt_timer/index.htm

Never heard of making a game in pp though. If you are going to need more functionality, I think you should use a real programming language. Quote from: Linux711 on January 14, 2012, 12:49:17 PM

Think this is what your looking for: http://www.tushar-mehta.com/powerpoint/ppt_timer/index.htm
That doesn't have any support for VBA as FAR as I know. D:
Quote from: Linux711 on January 14, 2012, 12:49:17 PM
Never heard of making a game in pp though. If you are going to need more functionality, I think you should use a real programming language.
VBA is just as much of a programming language as ActionScript; just think of it having a visual interface like Flash does.

Are you not understanding? VBA (Visual Basic with an A; I don't know what it stands for ) is a programming language implemented into Microsoft Office programs that can be used for Macros, subroutines that can simplify tasks and do other stuff.
In PowerPoint, macros can be run by action buttons, animations, and so forth to do more than just cleaning up empty text boxes.

By the way, you can make a game in PowerPoint without macros, but it'll be simple stuff like MAZE games using the mouse and Jeopardy.

Also, that thing costs money.
VBA stands for Visual Basic for Applications.


You could use the SSubTmr from VBAccelerator. download, register DLL, use Tools->References (In the VBA EDITOR)and add it. (VBAccelerator Subclassing and Timer Assistant)

Then you can use it, say in a UserForm:

Code: [Select]Private WithEvents timerobj As SSubTimer6.CTimer
Private StartTime As Date
Private Sub timerobj_ThatTime()
    Label1.Caption = Now()-StartTime
End Sub

Private Sub UserForm_Initialize()
    Set timerobj = new CTimer
    timerobj.Interval=300
    StartTime=Now()
End Sub
It won't work in a code module; would need to either be in it's own class or a UserForm (I believe it will also work in a Slide). Basically you use the timer to periodically update the display of a label, or other element.
211.

Solve : An error in Vb.net?

Answer»

this is my code:
          IMPORTS System.DATA.OleDb

Public Class frmStudent
    Dim cnn As New OleDb.OleDbConnection

    Private Sub btnClose_Click(ByVal sender As System.OBJECT, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        Me.txtstdID.Clear()
        Me.txtStdName.Clear()
        Me.txtadd1.Clear()
        Me.txtadd2.Clear()
        Me.txtBusPhone.Clear()
        Me.txtPerPhone.Clear()
        Me.txtFax.Clear()
        Me.txtEmail.Clear()
        'enable button edit
        Me.btnEdit.Enabled = True
        'set button add to add label
        Me.btnAdd.Text = "Add"
        '
        Me.txtstdID.Focus()
    End Sub

    Private Sub RefreshData()
        If Not cnn.State = ConnectionState.Open Then
            'open connection
            cnn.Open()
        End If

        Dim da As New OleDb.OleDbDataAdapter("SELECT Sup_ID as [Sup_ID], " & _
                                             "Sup_Name as [Sup_Name], Sup_add1, Supp_add2, Bss_con_No,Pre_con_No,Fax,Email " & _
                                             " FROM Main_Report ORDER BY Sup_ID", cnn)
        Dim dt As New DataTable
        'fill data to datatable
        da.Fill(dt)

        'offer data in data table into datagridview
        Me.dgvData.DataSource = dt

        'close connection
        cnn.Close()
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim cmd As New OleDb.OleDbCommand
        If Not cnn.State = ConnectionState.Open Then
            'open connection if it is not yet open
            cnn.Open()
        End If

        cmd.Connection = cnn
        'check whether add new or update
        If Me.txtstdID.Tag & "" = "" Then
            'add new
            'add data to table
            cmd.CommandText = "INSERT INTO Main_Report(Sup_ID, Sup_Name, Sup_add1, Supp_add2, Bss_con_No,Pre_con_No,Fax,Email)" & _
                            " VALUES(" & Me.txtstdID.Text & ",'" & Me.txtStdName.Text & "','" & _
                            Me.txtadd1.Text & "','" & Me.txtadd2.Text & "','" & _
                            Me.txtBusPhone.Text & "','" & _
                            Me.txtPerPhone.Text & "','" & Me.txtFax.Text & "','" & Me.txtEmail.Text & "')"
            TRY
                cmd.ExecuteNonQuery()
            Catch
                'MsgBox("Can't load Web page")
            End Try

        Else
            'update data in table
            cmd.CommandText = "UPDATE Main_Report " & _
                        " SET Sup_ID=" & Me.txtstdID.Text & _
                        ", Sup_Name='" & Me.txtStdName.Text & "'" & _
                        ", Sup_add1='" & Me.txtadd1.Text & "'" & _
                        ", Supp_add2='" & Me.txtadd2.Text & "'" & _
                        ", Bss_con_No='" & Me.txtBusPhone.Text & "'" & _
                        ", Pre_con_No='" & Me.txtPerPhone.Text & "'" & _
                        ", Fax='" & Me.txtFax.Text & "'" & _
                        ", Email='" & Me.txtEmail.Text & "'" & _
                        " WHERE Sup_ID=" & Me.txtstdID.Tag
            cmd.ExecuteNonQuery()
        End If
        'refresh data in LIST
        RefreshData()
        'clear form
        Me.btnClear.PerformClick()

        'close connection
        cnn.Close()
    End Sub

    Private Sub frmStudent_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        cnn = New OleDb.OleDbConnection
        cnn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\DCSD_1.mdb"
        '
        'get data into list
        Me.RefreshData()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        'check for the selected item in list
        If Me.dgvData.Rows.Count > 0 Then
            If Me.dgvData.SelectedRows.Count > 0 Then
                Dim intSup_ID As Char = Me.dgvData.SelectedRows(0).Cells("Sup_ID").Value
                'get data from database followed by student id
                'open connection
                If Not cnn.State = ConnectionState.Open Then
                    cnn.Open()
                End If
                'get data into datatable
                Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM Main_Report " & _
                                                     " WHERE Sup_ID=" & intSup_ID, cnn)
                Dim dt As New DataTable
                da.Fill(dt)

                Me.txtstdID.Text = intSup_ID.ToString
                Me.txtStdName.Text = dt.Rows(0).Item("Sup_Name").ToString
                Me.txtadd1.Text = dt.Rows(0).Item("Sup_add1").ToString
                Me.txtadd2.Text = dt.Rows(0).Item("Supp_add2").ToString
                Me.txtBusPhone.Text = dt.Rows(0).Item("Bss_con_No")
                Me.txtPerPhone.Text = dt.Rows(0).Item("Pre_con_No")
                Me.txtFax.Text = dt.Rows(0).Item("Fax")
                Me.txtEmail.Text = dt.Rows(0).Item("Email").ToString
                '
                'hide the id to be edited in TAG of txtstdid in case id is changed
                Me.txtstdID.Tag = intSup_ID
                'change button add to update
                Me.btnAdd.Text = "Update"
                'disable button edit
                Me.btnEdit.Enabled = False
                'close connection
                cnn.Close()
            End If
        End If
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        'check for the selected item in list
        If Me.dgvData.Rows.Count > 0 Then
            If Me.dgvData.SelectedRows.Count > 0 Then
                Dim intSup_ID As Char = Me.dgvData.SelectedRows(0).Cells("Sup_ID").Value
                'open connection
                If Not cnn.State = ConnectionState.Open Then
                    cnn.Open()
                End If

                'delete data
                Dim cmd As New OleDb.OleDbCommand
                cmd.Connection = cnn
                cmd.CommandText = "DELETE FROM Main_Report WHERE Sup_ID=" & intSup_ID
                cmd.ExecuteNonQuery()
                'refresh data
                Me.RefreshData()

                'close connection
                cnn.Close()
            End If
        End If
    End Sub
End Class
 please help me. i have code in 2010 vb.net i have attach my files

[year+ old attachment deleted by admin]

212.

Solve : unable to install vb 6.0 in xp?

Answer»

hi,
  I already installed Visual studio 2008 and SqlServer 2005, Then i need to install VB 6.0 When i was trying to install  there was one error message will display that is "Disk Set Previously Installed" . But in others computer will install properly.  Also i installed one exe that was developed in vb.  What is the problem. please give a solution.I know. It is often very hard to install vb6 in XP, but I have to do it all the time because it is my main dev tool. The most common thing I would see is simply "Setup can not continue." and it would just terminate. I have never seen that error though. Does it say anything else? Sometimes it will say install failed (or something LIKE that) and it will still work anyway lol, so look in your menu just to see maybe it installed anyway.Disk Set Previously Installed
Setup has found that this disk set has already been used by:. Only the legal owner of this product may reinstall it, either to update an EXISTING copy, or to replace any CORRUPTED or missing files.
You can continue to install this product, but you should be AWARE that it is protected by copyright law and international treaties.


it's not an error. It's a warning.

Thanks for your REPLY....
   After that warning... I clicked "continue" Button but the setup  is not responding (known by Task Manager) Then how to install... If there is any possibilities to delete the registry entries or any other files then install as fresh copy.  Please Help.

213.

Solve : dos batch file to input, search and run a command.?

Answer»

Hi All,

I am trying to create a dos batch file that will ALLOW a user to input 4 DIGITS. From these 4 digits then search a data.txt file for a string beginning with those digits. If found then run a command associated to that line.

Example 1. 1234,goto c:\data\1234.bat
Example 2. 2345,goto c:\data\2345.bat

the following file wil then run a command to perform a task based on the input.

then return to the main batch file when complete.

If anyone can help with this it would be much appreciated.
Thankyou.
Haski.
I think that would be too HARD to do in batch, so I wrote you a vbscript. You just need to tell me the command you need executed, or if you know vbscript, you can edit it yourself. I put a note on the line where you should put your command in.

Code: [Select]Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("test.txt", ForReading)

Const ForReading = 1

lookFor = InputBox("Enter four digits. Any more will be truncated.")
If lookFor = "" Then wscript.quit
lookFor = Left(lookFor, 4)

Dim arrFileLines()
i = 0
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
Loop
objFile.Close

For i = 0 To UBound(arrFileLines)
If InStr(arrFileLines(i), lookFor) &LT;> 0 Then
msgbox "Found on line: " & CStr(i+1)
'RUN YOUR COMMAND HERE
'use arrFileLines(i) for your command
End If
Next

Set objFile = Nothing
Set objFSO = Nothing

I forgot to mention, you need to replace test.txt with the path to your file.
EDIT: Added the truncate part I forgot.PM Reply sent. Post the responses here if that's ok.Could do this in a batch script as well.

214.

Solve : Need help coding prank virus in NotePad?

Answer»

Recently, me and my friend have have been having a nerd WAR with our school laptpos. He's found a WAY to remotley shut off my laptop wich is VERY inconvenient. Now i want to STRIKE back by coding a prank virus. Basically the program generates a random number between 1 and 30 and uses that number for a countdown timer. When the timer hits 0 the computer shuts down. Now i want to find a way to make it copy iteslf to his startup folder. Any ideas? I'm using NotePad.We're not going to help you with that type of REQUEST. Thread LOCKED.

215.

Solve : Want help with simple I/O in C or C++?

Answer»

I have a hard time with tutorials. Can somebody out there give me a code snippet that can do the following:
Fiat the is e already  simple text files created by notepad.
start program
get one or more parameters from the COMMAND line.
Open the file from the name of one of the parameters.
until end  of file
   read on line of the file (and automatically ADVANCE to next line.)
   send to the  to the standard output
loop
close the file
end of program.
Also, how do I compile it to an executable.

Yes, I did this stuff yeas ago, but my memory is fading because of lack of refresh.
Thanks in advance.
Here:

Code: [Select]#include <stdio.h>

int main (int argc, char *ARGV[])
{
    FILE *file = fopen ( argv[1], "r" );
    if ( file != NULL )
    {
        char line [ 128 ]; /* or other suitable maximum line size */

        while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
        {
            FPUTS ( line, stdout ); /* write the line */
        }
        fclose ( file );
    }
    else
    {
        printf("Error: Can't open file!"); /* why didn't the file open? */
    }
    return 0;
}

Quote

Also, how do I compile it to an executable.

I RECOMMEND code blocks. It's free, just google.
216.

Solve : batch execute after messages in notepad?

Answer»

does ANYBODY know how i can make my batch file execute after a series of MESSAGE boxes in NOTEPAD? Quote from: RIfishman on January 29, 2012, 07:35:15 AM

a series of message boxes in notepad?

What does this mean?
217.

Solve : Visual Basic Convert string to integer?

Answer»

Hi,
I have a problem with visual basic. Details:
-I have a TextBox
-I have a Button
-When I press the button it replaces any "x" found on the textbox with Replace(TextBox1.Text, Chr(120), "1")
-I want to set an integer from the TextBox, but i get an ERROR when the program convert the TextBox content to an Integer variable
For example I type in the TextBox "2*x+1", and I get an error "Conversion from string "2*x+1" to type 'Integer' is not valid.
How can I resolve this problem?VB can easily convert a string to an integer. HOWEVER, what you wan is an expression evaluator. The following are valid symbols for a number: 0123456789
And the two following may come at the left of the number
- +
All other symbols are not numbers, but  tokens that can modify rubbers. Use of these makes you string into an expression.

Want you want is the thing that evaluates an repression.
http://msdn.microsoft.com/en-us/library/ms164903.aspx
Converting from a string to a number does not involve parsing embedded arithmetic expressions. In order to do that, you will either have to write your own code to do that, Or, use one that is available for download.

You don't mention whether you are using VB6 or a later version. I've written Expression Evaluators for both.

the VB6 version is part of BCScript

After installing that you could add it in the references (Project->References) dialog and use code like this, once the appropriate controls are added:

Code: [Select]Option Explicit
Private ParserObject As CParser
Private Sub cmdEval_Click()
    If ParserObject Is NOTHING Then
        Set ParserObject = new CParser
        ParserObject.Create()
    End If
    Dim XVar as CVariable 'Reference to the Variable we create.
    Set XVar = ParserObject.Variables.Add("X",1)
    ParserObject.Variables.Add "x",XVar  'make lowercase refer to other variable. (optionally, just ucase the string being evaluated...)
    Dim Result As Variant
    ParserObject.Expression = txtexpression.Text
    ParserObject.ExecuteByRef Result
    txtexpression.Text=Result

End Sub


For Visual Basic.NET, you could use my very similar library that is essentially a C# rewrite of my earlier VB6 version, BASeParser.NET. This one is packaged as a zip file. Extract it somewhere, and then add a reference using Project->Add Reference, and add a reference to BASeParser.dll (from the zip, not the earlier version). Then code like this will work: (again, once the appropriate controls are there)


Code: [Select]Imports BASeParser
Public Class Form1

    Private ParserObject As CParser
    Private XVariable As BASeParser.Variable


    Private Sub cmdEval_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEval.Click
        If ParserObject Is Nothing Then
            ParserObject = New CParser()
            XVariable = ParserObject.Variables.Add("X", 1.0) '1.0 is needed- (double) (rather than 1 (Integer)) otherwise the Parser will break :(
            ParserObject.Variables.Add("X",XVariable) 'make the lower case also refer to the same variable.
        End If

        Dim Result = ParserObject.Execute(txtEvaluate.Text)
        txtEvaluate.Text = Result.ToString()

    End Sub

If this is homework, however, using either of those (or any library, for that matter) will probably get you an instant fail... Otherwise you should be set.

EDIT: Note also that Geek-9pm's suggestion has to do with the immediate window, and doesn't actually provide a programmatic method for doing this.I solved the problem with a much simpler solution, using CodeDOM expression evaluator.
Thank you for helping me. Quote from: alecsillidan on January 28, 2012, 05:00:18 AM

I solved the problem with a much simpler solution, using CodeDOM expression evaluator.
Thank you for helping me.

Be warned that using the CodeDOM as a expression evaluator will pollute your application namespace since each and every evaluation will create a entirely new assembly and load it into your appdomain. As your application runs and evaluates expressions you will just load more and more assemblies into your appdomain until the system runs out of memory (at which point the app crashes). The solution for that is to explicitly manage the AppDomains and load the new assemblies into them yourself, but the code to do that makes the code many times longer, since you then have to generate an entire MarshalByRef-derived Object in the "new" assembly and refer to that in your main one to prevent the temporary assemblies from LOADING into the main AppDomain when you access it, and managing this can be a gigantic pain.

In my experience the things you can do wrong using the codeDOM to evaluate expressions are innumerable.

You can (possibly) use the "Expression" class if you are using Framework 4, but I can't find any samples on that personally.

I had no idea it could be so hard.  Quote from: Geek-9pm on January 28, 2012, 11:10:52 AM
I had no idea it could be so hard. 

It's only hard if you try to take shortcuts
218.

Solve : Visual basic question??

Answer»

I have a long script that sits in my richtextbox
this line I want to change using a numeric up and down; the 1 id like to change to 1-24
It would be nice if it can remember the new  value next time I open the program too
I have no Idea how to do this, or even where to start. I have other lines id like to change in a similar fashion.
please help.


"    CurrentTaskInterval = hours_in_ms(1);", _More information will get you more and better answers.
What version of Visual Basic? What OS are you using.?

My own preference is to break up things into smaller parts I can easily handle. You should be able to insert a REM ARK that  will remind you of the need to edit an item often. Or just do like me and break it into pats.Ok, its Visual Basic 2010 Express

I think I need to express this line differently  "    CurrentTaskInterval = hours_in_ms(1);", _
since all I want to change is the 1
Although I'm not sure what I'm doing, I'm new to programming and and muddling along here.
All it is, is a text EDITOR and the text just happens to be code, unrelated code.





The program I'm working on is this


Public Class Form1

    Dim Lines() As String = { _
"   //  Some macros for defining time intervals in milliseconds", _
"#define seconds_in_ms(s) ((s)*1000UL)", _
"#define minutes_in_ms(m) ((m)*60UL*1000UL)", _
"#define hours_in_ms(h)   ((h)*60UL*60UL*1000UL)", _
"#define days_in_ms(d)    ((d)*24UL*60UL*60UL*1000UL)", _
"#define weeks_in_ms(w)   ((w)*7UL*24UL*60UL*60UL*1000UL)", _
"", _
"unsigned long CycleStartTime = 0;", _
"unsigned long LastTaskTime = 0;", _
"unsigned long CurrentTaskInterval = 0;", _
"unsigned Task = 3;  //All you had to change was this. 1st time, Task will = 3.", _
"", _
"", _
"void setup() {", _
"", _
"", _
"   pinMode(2, OUTPUT);   //PH down", _
"   pinMode(3, OUTPUT);  //B nutrient solution", _
"   pinMode(4, OUTPUT);  //A nutrient solution", _
"   pinMode(5, OUTPUT);  //Drain pump", _
"   pinMode(6, OUTPUT);   //Solenoid Valve", _
"   pinMode(7, OUTPUT);  //Nutrient Heater", _
"   pinMode(8, OUTPUT);  //Not used Future Nutrient/PH contoller", _
"", _
"  digitalWrite(2, HIGH);     //PH down off", _
"  digitalWrite(3, HIGH);  //B nutrient solution off", _
"  digitalWrite(4, HIGH);  //A nutrient solution off", _
"  digitalWrite(5, HIGH);  //Drain pump off", _
"  digitalWrite(6, HIGH);   //Solenoid Valve off", _
"  digitalWrite(7, HIGH);  //Nutrient Heater off", _
"}", _
"", _
"void loop() {", _
"", _
"", _
"  unsigned long currentTime = millis();", _
"", _
"  // If the time has not yet come to perform a task", _
"  if (currentTime - LastTaskTime >= CurrentTaskInterval)", _
"  LastTaskTime = currentTime;", _
"", _
"  switch (Task)", _
"  {", _
"  case 0:", _
"    CycleStartTime = currentTime;  // Remember this time", _
"", _
"   digitalWrite(5,LOW);   // set the drain pump on flush", _
"", _
"    CurrentTaskInterval = minutes_in_ms(16);", _
"    break;", _
"", _
"  case 1:", _
"    digitalWrite(5,HIGH);   // set the drain pump off flush", _
"    digitalWrite(6,LOW); // set the Solenoid Valve on flush", _
"    CurrentTaskInterval = hours_in_ms(1);", _
" break;", _
"", _
" case 2:", _
"    digitalWrite(6,HIGH); // set the Solenoid Valve off flush", _
"    digitalWrite(7,LOW); // set the Nutrient Heater on flush", _
"    CurrentTaskInterval = minutes_in_ms(60);", _
" break;", _
"", _
" case 3:", _
"    digitalWrite(5,LOW);   // set the drain pump on", _
"    digitalWrite(7,HIGH); // set the Nutrient Heater off", _
"    CurrentTaskInterval = minutes_in_ms(16);", _
" break;", _
"", _
"  case 4:", _
"    digitalWrite(5,HIGH);   // set the drain pump off", _
"    digitalWrite(6,LOW); // set the Solenoid Valve on", _
"    digitalWrite(2,LOW);  // set the PH down on", _
"    digitalWrite(3,LOW); // set the B nutrient solution on", _
"    digitalWrite(4,LOW); // set the A nutrient solution on", _
"    CurrentTaskInterval = seconds_in_ms(10);", _
" break;", _
"", _
"", _
"case 5:", _
"    digitalWrite(2,HIGH);  // set the PH down off", _
"    digitalWrite(6,LOW); // set the Solenoid Valve on", _
"    digitalWrite(3,LOW); // set the B nutrient solution on", _
"    digitalWrite(4,LOW); // set the A nutrient solution on", _
"    CurrentTaskInterval = minutes_in_ms(6);", _
"break;", _
"", _
"", _
"case 6:", _
"digitalWrite(3,HIGH); // set the B nutrient solution off", _
"digitalWrite(6,LOW); // set the Solenoid Valve on", _
"digitalWrite(4,LOW); // set the A nutrient solution on", _
"    CurrentTaskInterval = minutes_in_ms(5.04);", _
"break;", _
"", _
"", _
"case 7:", _
"digitalWrite(4,HIGH); // set the A nutrient solution off", _
"digitalWrite(6,LOW); // set the Solenoid Valve on", _
"    CurrentTaskInterval = minutes_in_ms(5);", _
"break;", _
"", _
"", _
"case 8:", _
"digitalWrite(6,HIGH); // set the Solenoid Valve off", _
"digitalWrite(7,LOW); // set the Nutrient Heater on", _
"digitalWrite(8,HIGH); // set the Future Nutrient/PH contoller off", _
"CurrentTaskInterval = days_in_ms(1);", _
"break;", _
"", _
"case 9:", _
"case 10:", _
"case 11:", _
"case 12:", _
"case 13:", _
"case 14:", _
"case 15:", _
"case 16:", _
"case 17:", _
"case 18:", _
"case 19:", _
"case 20:", _
"case 21:", _
"digitalWrite(6,LOW); // set the Solenoid Valve on/ top up", _
"CurrentTaskInterval = seconds_in_ms(20);", _
"digitalWrite(6,HIGH); // set the Solenoid Valve off/ top up", _
"CurrentTaskInterval = days_in_ms(1);", _
"break;", _
"", _
"case 22:", _
"// Start over again in one week from the START of the cycle", _
"    LastTaskTime = CycleStartTime;", _
"    CurrentTaskInterval = weeks_in_ms(1);", _
"    Task = 0;   //starts loop at case 0", _
"    break;", _
"  }", _
"}"}
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TheText.Lines = Lines
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveTheText.Click
        SaveIt.InitialDirectory = "C:\"
        SaveIt.FileName = "SAVE AS..."
        SaveIt.Filter = "ino Files Only (*.ino) | *.ino"
        SaveIt.ShowDialog()
        Dim W As New IO.StreamWriter(SaveIt.FileName)
        W.Write(TheText.Text)
        W.Close()
    End Sub

    Private Sub RadioButton2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton2.CheckedChanged
        If RadioButton2.Checked = True Then
            TheText.Text = TheText.Text.Replace("    Task = 0;   //starts loop at case 0", "    Task = 3;   //starts loop at case 3")
        Else
            TheText.Text = TheText.Text.Replace("    Task = 3;   //starts loop at case 3", "    Task = 0;   //starts loop at case 0")
        End If

    End Sub

    Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click

    End Sub

    Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown1.ValueChanged

    End Sub
End Class
OK If using a text editor to alter the value, and you want to change the 1 to a 2 in the fragment hours_in_ms(1)  you could aask the text editor to find hours_in_ms(1)
and replace with  hours_in_ms(2)
Then save the file.
But just asking it to change (1) to (2) may not work. You have to search and replace a unique fragment in a text editor. Unless you REALLY do want to replace all matches.

That is all I can think of.Sure that makes sense tell it to replace the hours_in_ms(1)
but I want to save it too so when I replace the  hours_in_ms(1) with a  hours_in_ms(5)
next time it starts with  hours_in_ms(5)Now I think what you are doing is becoming more clear.
It would seem that you really are new to common practice using in program design and maintenance. Sorry, don't MEAN to be arrogant.

Sometimes it is necessary no compile a program again to m sake it do a new thing you want. But sometimes you want it to do it the old way instead.

Quote

"    CurrentTaskInterval = hours_in_ms(1);", _

Appears to be a value that has a value at the start of the program. The name suggests that it will change, but it must start at 1. But you would like it to sometimes start at 2?  Maybe what you want is a way to tell the program to start will a different value if you want.

Sorry, I don't have enough experience with Visual Basic to make a useful recommendation. It would seem that what you want is a command line option for the program at run time.

http://www.vbexplorer.com/VBExplorer/vb_feature/august2000/command_line_arguments.asp

If this has any relevance to what you want, please say so. Or try again to explain what you need in a general way.
Maye BC will see this.
219.

Solve : Adobe Photoshop how-to?

Answer»

alright so I've had ADOBE photoshop 3.0 for about a year. I'm a big photograph freak, and I would love to be ABLE to have COOL effects on photo's but I cannot FIGURE out the software. The specific effect I would love to do is to have a picture black and white and then have some random spash of color like certain objects have color and some don't.

i NEED help!!
please and thank you!
LaurenLauren
You MAY get a better response by posting your guestions about photoshop here
http://photoshoptechniques.com/forum/index.php

I've found it pretty good
Nigel

220.

Solve : Query regarding DLL file?

Answer»

i am unable to find out the exact information regarding the System.Data.DLL file MADE use of in ADO.NET.I appeal u to help me regarding the above query and send me the RELEVANT ANSWER to my mailID.
                               THANKING you,
                                                          with warm regards,
                                                               gayathriI couldn't find any information on a system.data.dll namespace in the .Net Framework. The system.data namespace is a class PROVIDER for various type of data files.

What information are you looking for and what are you trying to do?

221.

Solve : Get return value of Store procedure from batch?

Answer» HI all,
How can I get return value of store procedure from batch file.

I can get reuturn value from SQL using EXIT(%query%).
But when I use EXIT("exec MyStore"). It cannot !

PLEASE HELP me!

Thank you.
can post your code?Hi all,
I have SOLVED that problem.
I ceated a view to store error code (the value that I want to return), and get error code from that view by using normal select.

Thank you.

222.

Solve : Need help writing Applescripts?

Answer»

If anyone can HELP...

I NEED to write an APPLESCRIPT to insert an API into the program phonevalet. Does anyone have any experience with this?

223.

Solve : joomla 2.5 Contacts component problem?

Answer»

Hi guys, I'm a new Joomla 2.5 user

I guess this is a stupid one but I'm stumbled by it. So I create a contact category, a contact page (component/contact/contact) and then create a menu item called contact us. Simple enough no ?

WELL I set up everything according to some tutorial websites and then when I view the webpage, I see a Contact text and right below it I see the contact form.

my question is how do I remove the contact part on this page ?

See image in the attachment for DETAILS on what i mean in this post. In other words, the title or line Contact is what I want to remove but i tried to hide everything in those 3 sections and theres nothing to do to my knowledge.

Also, I fixed the PROBLEM...kinda... but it's just plain weird. I edited the file en-GB.com_contact in my language folder in joomla. I removed the value "Contact" on the line COM_CONTACT_DETAILS="" and the "headline" or title is gone now but if I choose slider as a method of showing the form, I still see the headline space which is now empty and if I click on it then I still see some empty space expanding.

Further more, If i choose plain instead, I can still see the horizontal rule line right there. So if I SHOW my title page and choose plain as a display method it kind fix the problem for my but the problem REMAINS there, how do I remove the whole "section".


[year+ old attachment deleted by admin]

224.

Solve : C program I build today that calculates sqrt.?

Answer»

Hey EVERYONE,

A few days ago I started LEARNING C. And today I gave myself the assignment for this KILLLER program 

It can calculate the sqrt of any given number, apart from any number higher than 95100. And 89765 doesn't seem to work either.

I wonder if you would have a look at it, and give me some tips, or inspiration for new assignments.

Thanks 


#include

int main(void)
{
   int i;
   float fsquare;
   float fstart;
   float fremember;
   float flower;
   float fhigher;
      
   printf("Enter a number to sqrt and hit enter:\n\n");
   scanf("%d", &i);
   
   int fsquare = i;
   fremember = 0;
   flower = fsquare;
   fhigher = 0;
      
   while((flower*flower) > fsquare)
   {
      if((flower*flower) > fsquare)
      {
         fhigher = flower;
      }
      flower = flower / 2;
      
      printf("flower = %f   ", flower);
      printf("fhigher = %f\n\n", fhigher);
   }
   printf("flower = %f   ", flower);
   printf("fhigher = %f\n\n", fhigher);
      
   while(((fremember-fsquare) > .001) || (-(fremember-fsquare) > .001))
   {
      fstart = (flower + fhigher)/2;
      fremember = fstart * fstart;
      
      if (fremember < fsquare)
      {
         flower = fstart;
      }
      
      if (fremember > fsquare)
      {
         fhigher = fstart;
      }
      
      printf("fremember = %f  ", fremember);
      printf("flower = %f  ", flower);
      printf("fhigher = %f\n\n", fhigher);
   }
   
   printf("\nThe number you asked to sqrt was: %d\n\n", i);
   printf("The sqrt lies between %f and %f\n\n", flower, fhigher);
   
   return 0;

}Make a text adventure with ASCII graphics.uhh  Quote

KILLLER program
Huh?
You post a program that does not work and call it a killer?
Is this homework?

There is a specific classical algorithm for doing square root. Are you claiming that your program does any root?

There are are C libraries for doing logarithms. Using  it one can do almost any power or root of any pragmatic real number.

Exponents and Logarithms - The GNU C LibraryI compiled it with tcc, maybe that helps.

I know that there are basic functions for doing sqrt, but I made this to get into the PROGRAMMING language.

No it's not homework OK. It is to improve you skis. Great! 
Have you EVERY done the classical algorithm on a simple calculator that has not sqrt functions.
How to calculate a square root without a calculator

The above tells how to do it with pencil and paper, but I like to do it with a small calculator without the sqrt key.

Once I calculated the 12™ root of 2. But I forgot to write it down!

Once you are very familiar with the logic of the algorithm, it makes it easier to check your work will the C code you have.Looked into that algorithm on how to calculate sqrt on paper.

No wonder old people are cranky most of the time  Code: [Select]#include <stdio.h>
#include <stdlib.h>
double absolute(double value)
{
return value>0?value:-value;

}
double sqrt(double value)
{
    if (value < 0) return 0;
        double atolerance = 1E-15;
        double t = value;
        while (absolute(t - value/t) > atolerance*t)
            t = (value/t + t) / 2.0;
        return t;


}

int main(char* argv[], int argc)
{
   double enteredvalue;
   printf("Enter Value:\n");
   scanf("%lf", &enteredvalue);
   printf("sqrt of %5.2f is %5.2f\n",enteredvalue,sqrt(enteredvalue));

}
Newtons method ftw. Figured I may as well make a cheap abs() equivalent as well for no reason.

Quote from: learning_cmd on January 13, 2012, 05:01:44 PM
Looked into that algorithm on how to calculate sqrt on paper.

No wonder old people are cranky most of the time 

We are mainly cranky with kids who think you can get everything you want just by pressing a button.
Quote from: Salmon Trout on January 14, 2012, 01:40:40 AM
We are mainly cranky with kids who think you can get everything you want just by pressing a button.

You can, if it's this button:

Quote from: Rob Pomeroy on January 14, 2012, 08:18:49 AM
You can, if it's this button:


http://www.85qm.de/up/BigRedButton.swf


I hit it twice...
What happens if I do three times?It goes on for about 200 presses and then repeats itself.to OP: here are some nice "assignments": http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerE5.html  learningcmd,

Go to www.swboneyard.com and look for the "Calc" program.  This is a full featured algebraric parser I wrote in C a while back, does everything you need.  Might make for a good example.

Bryan Wilcutt
225.

Solve : Copy the file automatically every the file just closed?

Answer»

I want to make a back-up of a file when it's just CLOSED. In example : I have a .accdb file, work with it, then after i close this file, automatically windows make a new back-up with the same file.

I can i do it? any suggestion, please.

Sorry for my bad ENGLISH.
Why not just copy the file to a USB memory stick, CD-RW, DVD-RW or maybe another location on your PC. You can do this by right-clicking the file and selecting 'copy', then NAVIGATE to the required area and paste. Thanks for the reply.
My purpose is having a back up of a file i work with in the same directory. I think it's much more easier if I have a routine that run these steps.      You could use autohotkey.
This is what the program should do:
1) ask to select a file, starting in the current directory, this is EASY (FileSelectFile)
2) use some way to determine WHETHER the file has been just saved. (like FileGetTime)
3) if the file has just been modified (i.e. saved, thus you have closed the file) then make a backup using FileCopy
It's not the best way, but it should get the job done...

You could also use sofwtare like this:
http://www.ajcsoft.com/active-backup-tour.htm (you need to pay)
http://www.addictivetips.com/windows-tips/make-real-time-backup-of-file-changes-in-multiple-folders-mirror/ (<==FREE )

ok, I saw that last link when I wanted to submit this post. I suggest you use the last link, not my autohotkey program...
Another software option.
http://www.filehamster.com/

226.

Solve : Trying to make a Timer VB.net?

Answer» PUBLIC Class Form1

    Dim TimeEnd, TimeStart, TimeStop As New DateTime
    Dim isStop, isPause As Boolean
    Dim form02 As New Form2
    Dim foo, TimePause, ElapseTime, TotalTimePaused As New TimeSpan
    Dim h, m, s As Integer


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Timer1.Enabled = False
        TextBox1.Text = "0" : TextBox2.Text = "0" : TextBox3.Text = "0"

        Button6.Hide()
    End Sub


    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
     
        If Timer1.Interval <> 100 Then Timer1.Interval = 100
        If DateTime.Now > TimeEnd Then
            TextBox5.Text = "Time End"
            Timer1.Stop()

        Else

            If isStop = False And isPause = False Then
                foo = TimeEnd - DateTime.Now
                TextBox5.Text = String.Format("{0:D2}:{1:D2}:{2:D2}", _
                                              foo.Hours, foo.Minutes, foo.Seconds)

            End If
            TextBox6.Text = TimeStart.ToString("hh:MM" & " " & "tt")

            If isStop Then
                TextBox4.Text = TimeStop.ToString("hh:mm" & " " & "tt")
            Else

                TextBox4.Text = TimeEnd.ToString("hh:mm" & " " & "tt")
            End If
            TextBox1.Text = "0" : TextBox2.Text = "0" : TextBox3.Text = "0"
        End If

    End Sub


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       'START
        Button1.Hide()
        Timer1.Enabled = True
        If Not Integer.TryParse(TextBox1.Text, h) OrElse _
            Not Integer.TryParse(TextBox2.Text, m) OrElse _
            Not Integer.TryParse(TextBox3.Text, s) Then
            'bad input data
            Exit Sub
        End If
        TimeEnd = DateTime.Now.AddHours(h).AddMinutes(m).AddSeconds(s)
        TimeStart = DateTime.Now
        TimeOfDay = DateTime.Now
        Timer1.Interval = 1
        Timer1.Start()
        isStop = False

    End Sub


    Private Sub TextBox5_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox5.TextChanged

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
       'STOP
        isStop = True
        TimeStop = DateTime.Now
       ' form02.PressStop = True

    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        isPause = True
        Timer1.Enabled = False

        Button1.Hide()
        Button6.Show()
    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        'RESUME
        If isPause = True Then
            Timer1.Enabled = True
            isPause = False
        End If
    End Sub
End Class

im working on a stop watch that can set a time then do a countdown, and do a ascending count
.im kind of a messy when it comes to this thing hope u understand the code. what im trying to do now is  to make a PAUSE and RESUME button for this code. i've tried using on the Pause button timer1.enabled = false and on the RESUME button Pause button timer1.enabled = true. it does pause the time and resumes it,but for example the TIMER is counting down and i pause it at 5:33, and resume it after 7 seconds, the timer then resumes at 5:40, what i want to do is to make it resume from the time that i pause it, in my example i want it to resume from 5:33. hope you can help me. thanks in advanceIs the code all yours? Was part of it copied from another source?
How much accuracy do you NEED?
Have you already read this?
http://www.dotnetperls.com/timer-vbnet
OR
http://www.ehow.com/how_4590003_program-timer-control-vbnet.html
OR
http://www.techrepublic.com/forum/questions/101-224643/vbnet-timer-control-woes
227.

Solve : delphi?

Answer»
When I use the GLYPH property, how do I know which color is TRANSPARENT?



Regards,
Ezeekart TEAM,
Buy Smart Mobile phones online
www.ezeekart.com
Delphi?  Wow... OKAY... diggin in my brain.   What I recall is the set back ground color would be set to 0 for transparent, or any number for the specific color pen.

Bryan Wilcutt Quote
Delphi always assumes that the color of the BOTTOM left-hand corner pixel is the background color and should be displayed as transparent.
228.

Solve : How to add parity bits to binary numbers c#?

Answer»

Hello. This is my code. I am trying to make a program on c# which the user types in a 7-bit binary number and the program prints the number with an EVEN parity bit added to it on the left. It says some things don't fit in the context. Is there any way you could do a code as I think it is wrong.


using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

namespace something
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a 7-bit binary number:");
            int number = Convert.ToInt32(Console.ReadLine());
            byte[] numberAsByte = new byte[] { (byte)number };

            byte bitsSet=0;

            for (int i = 0; i >= 0; i--)
            {
           
                if ((number & (1 << i)) > 0)
                {
                    bitsSet++;
                }

            }
            if (bitsSet % 2 == 1)
            {
                bits[7] = true;
            }
            Array.CopyTo(numberAsByte, 0, out bits);
            number = numberAsByte[0];
            Console.WriteLine("The binary number with a parity bit is:");
            Console.WriteLine(number);
            Console.ReadLine();
        }
       
    }
}
Parity WORKS by setting the high bit to 1 when there are an even number of bits in the number, and 0 if there are odd bits.

int c = 0;

for (int i = 0; i < SIZEOF(byte) - 1; i++)  // MINUS 1 because we don't care about high bit
{
    if (mybyte & (1 << i))
     c++;  /* cheap shot at C#, sorry :-) */
}

if (c & 0x01)
   mybyte |= 0x80;  // Even parity
else
   mybyte &= 0X7F;  // Odd parity

This is just psuedo code, of course, but should clear up your approach.

Bryan Wilcutt

229.

Solve : Funny C code?

Answer»

This is some really funny code (although you have to open it at the COMMAND prompt). CALL the file stop.

#include

_______________________________________ _______________________________________ ________
int main()
{
printf("Cannot stop: Bad mood error.")
return(0)
}

_______________________________________ _______________________________________ ________

Har har!Not to be critical and notwithstanding your claim of not being a noob, your snippet will not compile.

Code: [Select]#include <stdio.h>

int main()
{
printf("Cannot stop: Bad mood error.");
return(0);
}

As I read in another post, attention to detail is critical in programming (no matter how you spell it!)

 Is that a loop which reprints "Cannot stop: bad mood error."?

looks like that was the intention- but as it stands it will just show it once and go back to the prompt.


heres one that simulates the prompt.... I made it in VC++ 6- other compilers will likely require the removal of the stdafx line I believe.
well here it is.

#include "stdafx.h"
#include <string.h>
#include <iostream.h>
int main(int argc, char* argv[])
{
   char cmdline[128];
   char crlf[7]="\0xD\0xA";
   int currmsg=-1;
   do
   {
   currmsg++;
   COUT << endl;
   printf("C:\\>",crlf);
   gets(cmdline);
   cout << endl;
   if (currmsg==0)
      printf("An Error occured processing a token in command line '%s'.%s A Possible reason may be you smell.",cmdline,crlf);
   else if (currmsg==1)
      printf("Disk error while processing command '%s'. Ensure you have applied sufficient deodorant to prevent your hard disk from being offended.",cmdline);
   else if (currmsg==2)
      printf("I was just about to execute your command, '%s', but changed my mind at the last second.",cmdline);
   else if (currmsg==3)
      printf("hey, stop telling me what to do. I'm not going to perform a '%s' just for you.",cmdline);
   else if (currmsg==4)
   {
      printf("crap, it worked this time.");
       for(int i=0;i<15;i++)
         {
         printf(".");
      }
      printf("whew, something bad happened when I tried.");
   }   
   else if (currmsg==5)
      {
         printf("for gods sake, I thought you'd give up already!");
         currmsg=-1;
      }
      printf(crlf);
   } while (stricmp("quit",cmdline)!=0);
   printf("%s%sdarn, you said the secret word. oh well.",cmdline);
   return 0;
}






pls SND me c code for "everyone is having interest in rearrangements. find all the rearrangements possible with 0-9 digits without repetition of digit in number and count them. the number  should contain distinct digit. the number should not start from 0."

230.

Solve : Macro in Win XP?

Answer»

I have a repeatedly steps when i work with an application.

for 1st file:
1. type "001"
2. press button A
3. select menu B
4. select sub-menu B1
5. press button C

for 2nd file:
6. type "002"
7. press button A
8. select menu B
9. select sub-menu B1
10. press button C

for 3rd file:
11. type "003"
12. press button A
13. select menu B
14. select sub-menu B1
15. press button C
....
 
Is it impossible to convert the steps above to a "macro" in windows XP?
thanks.Yes, but without knowing what program it is I can not say for SURE. Some programs resist automation.Others allow options to be posted on the command line. See the documentation for the program.

In general, most Windows programs will allow keyboard automation. You can create your own or install a free program. Or even buy a commercial program if you want.

I would suggest you try a free program or a trial program to see if it will work for you.

http://www.keyboardexpress.com/
http://keytext.com/      <<== recommended
http://www.mavrsoft.com/products/apis_macro_recorder/articles/keyboard_automation.html
http://www.autohotkey.com/   <<== FREEthanks, Geek-9pm

I'm sure that the program doesn't resist automation because I have tried it with Easy Macro Recorder and work well. But, Easy Macro and some similar program just "read" cursor location, not the components, like form's name, combo button's name, or list's name. I haven't tried your address link above, but I wonder there is a "macro" program that runs by "reading" what form name/menu name/button name that user choose. Not by identify cursor location.

I hope you understand what I talking about.

Thanks.Yes, I understand what you mean. There are programs that do 'smart' automation. They can identify elements in a HTML or some other presentation that trigger an macro action. KeyText does that. You can get the full Key Text  documentation in PDF.

Quote

    Pros
    Compact but powerful utility. Unobtrusive. Dozens of customization options. Pricey.
    Cons
    Steep learning curve for advanced features.
    Bottom Line
    KeyText represents the best combination of compactness and power in a keyboard automation utility.
From http://www.pcmag.com/article2/0,2817,2358993,00.asp

Read over the article well. Key Text is virtual a programming language. Hard to learn, but with nit you can walk on water.Auto-It 3 is free:

http://www.autoitscript.com/site/autoit/

AutoIt was initially designed for PC “roll out” situations to reliably automate and configure thousands of PCs. Over time it has become a powerful language that supports complex expressions, user functions, loops and everything else that veteran scripters would expect.

Features:

    Easy to learn BASIC-like syntax
    Simulate keystrokes and mouse movements
    Manipulate windows and processes
    Interact with all standard windows controls
    Scripts can be compiled into standalone executables
    Create Graphical User Interfaces (GUIs)
    COM support
    Regular expressions
    Directly CALL external DLL and Windows API functions
    Scriptable RunAs functions
    Detailed helpfile and large community-based support forums
    Compatible with Windows 2000 / XP / 2003 / Vista / 2008 / Windows 7 / 2008 R2
    Unicode and x64 support
    Digitally signed for peace of mind
    Works with Windows Vista’s User Account Control (UAC)

Quote
Window Management

You can expect to move, hide, show, resize, activate, close and pretty much do what you want with windows. Windows can be referenced by title, text on the window, size, position, class and even internal Win32 API handles.

Controls

Directly get INFORMATION on and interact with edit boxes, check boxes, list boxes, combos, buttons, status bars without the risk of keystrokes getting lost.  Even work with controls in windows that aren’t active!

Auto-It has a very active forum, with some of the most pro-active moderation I have ever seen - bans are posted on a public board; in the original post which I quote here, the bold parts are links to the offending behaviour (criticising another member).

example (user "Alupis"):

Quote
3 days posting ban.

If a Mod tells you to stop doing something - then stop doing it and do not do it again. It does not matter if you feel it is unfair - this is not a democracy.

It is quite AMUSING to read the moderation board

http://www.autoitscript.com/forum/forum/28-user-moderation/

One way to get a permanent ban is to ignore the rules about game bots (Don't ask how to write one, don't respond with help to people who do). They are very hot on any KIND of script kiddie ideas that posters may have, and very very quick to spot those to try to hide what they are really asking about.




231.

Solve : Ask: How to make auto reconnect / restart + remembered id & password use dos bat?

Answer»

Hi there, i'm really noob here LET me EXPLAIN my problem to you first :

 1. i have a software in directory c:\mikeusak\mikeusak.php and i run it VIA batch
 2. and after that my software started and requesting id and password to login
 3. i input my ID and Password to log in and i logged in
     
 4. the software is running and everything just fine
 5. then the software got error message "mungkin halaman kepenuhan" and i must restart it so the PROGRAM can run again
     
 6. sadly everytime i re-run my software i must retype my id and password

can you guys help me how to command it in batch so the software can :
 1.  auto reconnect or auto restart everytime i got error message "mungkin halaman kepenuhan"
 2.  when reconnect / restart the ID and Password is remembered by the software ?

this is my batch code to run my software how to modify it ?
echo off
cls
C:\xampp\php\php.exe -C c:/mikeusak/mikeusak.php
cmd <

Thankyou   Well you already have an answer on other forums I see... (googled "mungkin halaman kepenuhan").
Why don't you just contact the maker of the software (whatever the software is doing) and explain your problem, let them fix the bug. (Or maybe your using the software wrong...)
Yep.  I took care of this on the DosTips.com forum.

232.

Solve : How to send a HTTP request within a batch file??

Answer»

Any help would be much appreciated!
- On SERVER 1, I have a batch file to build a HTTP request, like: http://SERVER2ADDRESS:PORT/SessionControl/CCXML10.start?tokenid=MYCCXMLAPP
- Within the batch file, what command to use to acutally send the HTTP request such that it will be opened on SERVER 2?Can a browser make the request?
Run Internet Explorer From Command Prompt Can you use Powershell?  It can do reasonably sophisticated web transactions.Rob Pomero, good idea. Here is one on many such tips for PowerShel.

Quote

Get-Web (Another round of wget for PowerShell)
By Joel 'Jaykul' BENNETT on 01-May-2008

Well, after multiple attempts at a wget PowerShell script (the last one works very well for downloading web pages, files, as long as you don’t need to send post parameters or anything like that) ... I found myself writing a script last week that included a custom HTTP POST function as well as using some prior functionality I wrote (ConvertFrom-Html) to convert HTML files to XML documents — which PowerShell can deal with NICELY.
Forgot the link.
http://huddledmasses.org/get-web-another-round-of-wget-for-powershell/Some sample CODE:

Code: [Select]# WebClient object, for querying a web server through a proxy server with POST data
$wc = new-Object System.Net.WebClient
$proxy = New-Object System.Net.WebProxy('proxy.local', '8080')
$proxy.BypassList = 'someserver.local'
$wc.proxy = $proxy
$post_vars = new-object System.Collections.Specialized.NameValueCollection

# Download a PAGE
$startpage = $wc.DownloadString("http://wherever.com")

$post_vars.Add('variable1','value1')
$post_vars.Add('variable2',$value2)
$endpage = $wc.UploadValues('http://wherever.com/upload', 'POST', $post_vars)

# For debugging:
$response = [System.Text.Encoding]::ASCII.GetString($endpage)
Write-Host $response
233.

Solve : Differences between Linux and Windows Server?

Answer»

I have been studying a web site that uses ASP.NET and so it resides on a WINDOWS Server but it also uses some JScript so it is worth studying.  Anyway, I am moving it to a Linux server and I have noticed some DIFFERENCES in the way it handles files.  First of all, the Windows Server is not case sensitive.  But I also noticed something else.  It seems that the Windows Server can have file names with spaces in them like this:  "Creative%20Design%20vert_S" where the "%20" is a space.  But, when I try to upload this directory to the Linux server using FileZilla it does not seem to work.  And then when I try to CREATE the directory, I get an error "Forbidden command argument".  So is using %20 in a direcory name illegal in Linux?
you've been busy.

http://discussions.virtualdr.com/showthread.php?t=251603

http://forums.randi.org/showthread.php?p=8059837

Anyway, I would guess the problem is that %20 is a URL escape code and that FTP doesn't accept filenames as URLs. it accepts them as filenames. Also, according to the FTP protocol, it would appear that if there are spaces in a name you are to put periods as placeholders when specifying that name.


Another alternative would be to use mput and or mget, instead.

As to your server, you'll need to install the Mono/ASP.NET plugin for Apache. If your lucky it will work. If you aren't, it won't.

234.

Solve : Toshiba Dynabook portege 1601?

Answer»

Hello There,
                  I have a problem Repairing my toshiba dynabook portege 1601, thus anyone know how to reformat it? because i already tried booting it on my usb flash drive, and nothing HAPPEN because it doesn't detect my usb flash drive, thus anyone know other process to reformat it? please help..... thanx.....Hi, there are other METHOD of reformat instead of via USB. Have you tried others?

This link MAY help you: Steps on how to reformat your computer and START over.

235.

Solve : Problem setting up my C# program to display XML results according to what my com?

Answer»

I need to make it so that WHENEVER I have "East" selected under my combobox for example, then only the list of parks with that PARTICULAR location will show up. I also need to do the same for whichever facilities are selected and if the park falls within the opening and closing dates as well.

Here's the C# CODE I have
http://slexy.org/view/s2hCzH0TTk

Here's the full XML
http://slexy.org/view/s21nPdmJD9

And my XAML
http://slexy.org/view/s214kbuBdE

Any tips/help would be greatly appreciated,

TIM

236.

Solve : Time Elapsed Help C#?

Answer»

I just started trying to learn c# so bear with me.
What I want to do was try to make a timer high score "GAME".

Let's say I press the BUTTON "Start".
The timer begins and I must click the "Stop" button as quick as possible.
When the "Stop" button is clicked, the timer stops.

Now how could I transfer the elapsed time for the high score?

What I need is SOMETHING like this:

CODE: [Select]timer1.ElapsedTime = highscoreLabel;
For it to ACTUALLY be useful, how could I change it so that if the elapsed number is lower, to change the high score.

For example (Which obviously won't work):

Code: [Select]if (timer1.ElapsedTime < highscoreLabel)
{
    timer1.ElapsedTime = highscoreLabel
}

...

I would really appreciate anyone's help.


237.

Solve : Need some HTML guidance...?

Answer»

I have this code...
------------------------------------------------------------

http://www.w3schools.com/" name="frDocViewer" height="400" width="1030" frameborder="1" >




function HideFrame(){
 fr = document.getElementById ("frDocViewer");
 
if (fr.style.display!='none')
{
 
fr.style.display="none";

 }
 
ELSE
{

 fr.style.display="BLOCK";
 
}
}


-----------------------------------------------------
which shows/hides an IFrame with the click of a button, but i want it to be hidden by default, any suggestions?Ok, I see now that there's a section for web DEVELOPMENT, can SOMEBODY move this please?Just use the CSS attribute display:none, viz:

Code: [Select]<iframe id="frDocViewer" src="http://www.w3schools.com/" name="frDocViewer"
  style="height:400px; width: 1030px; border: 1px solid black; display: none;">
</iframe>
When posting code on the forums, it HELPS if you put it between [code][/code] tags.

238.

Solve : Modding C&C 3 and Creating Video games?

Answer»

I have sort of modded before C&C 3 and loved it because it was so simple, but it was only xml UNDERSTANDING as it turns out. So I was wondering, is it possible to create a mod for this game using Python? I hear it's one of the simplest object oriented languages to learn.
Second part of the question is what language best used if I wanted to create a video game for Linux like Ubuntu?
Thanks for any tips and hints and whatever help you may suggest Although it's not your entire question, part of your question seems to be "Which programming language should I learn first for creating a Linux game?".

Think of it though. This is sort of like a aspiring painter asking "Which kind of paints should I learn to use first?"; and, no doubt, in threads like this people don't hesitate to jump in and do the metaphorical equivalent of recommending that the Original Poster should "learn watercolour, it's the easiest" (Learn programming language X because it is 'easy') or "Learn Oil-based paints, the greatest artists all use it"  (Kernighan and Richie invented C) or the entirely redundant "The sistine chapel was painted using fresco" (Excel is written in C++!).

It is all missing the point. The entire purpose of a programming language is to get the computer to do things. Programming languages vary in POWER- Java is weaker than C# (C# has delegates, lambda's, proper event handlers, etc) and D is more powerful than either of them, with support for static if's and strong metaprogramming support. Lisp is indebatably the most powerful programming language since it is, to programming languages, sort of what Mathematics is to most of the other sciences. A base, pure form that all others aspire to. many of the more powerful features of Lisp are only recently finding their way into popular programming languages.

That, however, is not a recommendation to learn Lisp. Everybody who works with programming languages has a favourite. My personal favourite at the moment is C#.

Let's take an example. Let's say somebody recommended you learn Java. regardless of the reasons, this is entirely subjective; there really is no better reason to learn java compared to any other language. In their mind, Java is better only because they are better with Java; they can look at less powerful languages like C and wonder "how could I ever get along without Objects?" but when they look at a more powerful language, they see constructs they are not familiar with; for example, many Java programmers I know don't like C# because it's "weird"; but it's only weird because they don't understand the constructs. They've essentially gotten used to their language of choice; if it's worth having, it's in their language, and if it's not in their language of choice, it's not worth having. Too often when I note the existence of C#'s delegates,events operator overloading, etc to a Java programmer, they will note "But that's not pure OOP" or "but why would I WANT to do that?", or "operator overloading is dangerous!" The first is a cop out- OOP is not some sort of end-all be all of programming languages and if anything the cost of maintaining a Triple-tiered Application framework based on clean Object Oriented design is at least as much as a standard procedural solution, by virtue of so much of the OOP code being boilerplate cruft. The second is nothing more than an expression of ignorance; just because you cannot immediately see an application for a given concept does not make that concept useless. The third, is equally silly because arguably with any amount of power there is additional responsibility to use it properly. If you litter your classes and code with operator overloads that make no sense, than, yes, it's dangerous. But once you understand what is going on and how best to implement them your code becomes cleaner and easier to read.

Anyway, my position on the question of "What programming language should I start with" has usually been that they should stop asking and start doing. You can ask 12 dozen different forums which programming language you should start with and get 12 dozen different recommendations, but those aren't going to actually get you to learn any of those languages- you have to start, and overall, it doesn't matter what you start with.

Python is a powerful language that supports, as you said, Object Oriented Programming. It lacks a few OOP concepts but again OOP isn't some sort of be-all-end-all thing; additionally, most programming languages that claim to be "fully object oriented" don't support even a tiny fraction of what should be required for a fully Object Oriented Language. Another nice thing about Python is that it doesn't force you to write in an Object oriented fashion. in java or C# everything has to be a class or object, but with python you don't have to write your main routine as a class.

Once a person recognizes two facts- the first being that programming languages vary in power, and the second being that if you are unfamiliar with a concept it will seem foreign,the sooner a person can realize that it doesn't really matter what programming language they are starting with, they are going to have to deal with something that seems foreign. I often also hear people say that "programming languages are designed for computers". But that's nonsense. A Computer cannot understand python any better than it can understand English. Programming languages are designed for use by people, and are translated by other programs, either through compilation or interpretation, into the one true language that the computer understands- machine code.

Another interesting but pointless debate that often springs up is the debate between "interpreted" and "compiled" languages, with proponents of compiled languages claiming that an interpreted languages can "never" reach the speed of a well-written compiled language. And that may be true, but the same argument came up between Machine code and compiled languages, with proponents of machine code saying that the compiled languages could never equal the performance of hand-tuned assembly or machine code. And that is true as well. But what both fail to realize is that the absolute speed at which a program ones is less important than the trade-off in development time that it takes to reach that speed. Is it really worth it to work 10 times harder on a C application rather than a Python script to gain a speed boost of 10%? That depends on the context. if it's a function called a bajillionty times in a CPU intensive loop, than it might be worth it. But for most applications that time is better spent adding features to the application rather than focussing on speed.

I seem to have rambled a bit there but I hope it helps at least.So any programming language can be used to mod any video game? How about Linux/ Ubuntu, any programming language works the same on there as on Windows? But yes, you have cleared up the barrier, it's just that I don't know what languages exactly exist, just from reading and searching I hear about these new languages like Python and Lisp, but I don't know anything about them, and there are plenty more of those programming languages. I know of web developing and programming languages, PHP, JavaScript, CSS, and HTML. But besides the point, I guess I need some kind of guidance like everyone else into some direction of any language to start learning. Obviously as you stated that we will like that language that we start learning and spend majority of our time with. In the end I guess my question is , what language to learn that I can use to make mods for games and also later on make actual games for Ubuntu.

I chose ubuntu because it is an OS that deserves more than it gets. But then again, I guess majority but not all questions could be answered by using google. So back to the first question up top. Quote from: valeryk on March 04, 2012, 11:31:30 PM

So any programming language can be used to mod any video game?
No. It depends on the game. A Java game- for example, minecraft- would have to be modded using Java. However, a mod could be created, in java, that interfaced  with a .NET assembly or something.

Most games are written in C++, and compile to machine code, so the only real modding you can do would involve either directly manipulating that machine code, or, more commonly, using whatever tools and configurations the game creator provides.

Quote
How about Linux/ Ubuntu, any programming language works the same on there as on Windows?
Not "Any", No; but any language worth using works on a variety of platforms. Those that don't often have attempts to bring a similar language to it. For example, VB6 usually only works on windows, but there is a program called "Gambas" that RUNS on Linux that provides a similar toolset and language.

  Quote
it's just that I don't know what languages exactly exist, just from reading and searching I hear about these new languages like Python and Lisp
Lisp was created in the EARLY 60's, so not really that new. It was one of the earliest hkigh-level languages. Python was around mid-90's, and given the age of computer science, that's still quite a while ago.

  Quote
what language to learn that I can use to make mods for games and also later on make actual games for Ubuntu.
There is no "mod language". Each game will expose it's innards to mod developers using a different scripting language. many games use Lua, but some lothers use python. Still others use a custom script language, like "RealScript" for the unreal engine. Some don't expose themselves at all, in which case, if you are lucky, they are written in a language with some sort of introspection capability, such as Java or a .NET language. Minecraft mods, for example, are essentially extra class files and hacked class files that add and replace existing classes in the game, adding new blocks or items or whatever. If the game compiles to machine code- and most do- that means that you would need to understand how to dissassemble the file, as well as how to read uncommented assembly language.

As for languages that could be used for making games on Ubuntu. The list of languages that you can't use to make games in Ubuntu(or any OS, for that matter) would be perhaps a dozen, and that is a liberal estimate.

239.

Solve : Excel Web Query not coming up right?

Answer»

Dear Forum,
I am trying to input a web page into excel that is password protected. A standard web query works great when not logged in, but if I try to specify the address of the logged in page, it comes up at the login page; to put your login credentials in. I have tried copying and pasting the logged in address into a new browser window, and it comes up fine; why wouldn't it WORK in Excel?
Thanks a lot!
Mike
 I can't make any sense of your post.  Excel is a spreadsheet program, not a web browser or a web page creation program.  Your comments about "putting a web page into Excel" just SEEM totally bizarre.  Dear Soybean,
Sorry for being none technically correct. I am not a computer wizard, hence my need of help!
I am simply importing the text data from the webpage into Excel. HTML or text; I don't care what form it is in; I just want to see the stock buy or sell signals from the web site.
The web site is: www.americanbulls.com
I have PERMISSION from the site owner to use it to auto trade an account. I am using MBTrading with their SDK commands.
I have been successful using the standard website as it appears without logging in (the free website), but when I enter my password to access the interday signals, the program will not work. It does not access the logged in webpage, but comes up with a login page. Do you know of any way around this? Perhaps copying and pasting the page into Excel?
Thanks!
Mike
 I think the website you mentioned is a bad egg.  See http://www.xomreviews.com/americanbulls.com

My advise is to see find some other source for the stock market data you want. Dear Soybean,

I think you are greatly mistaken. American Bulls has an  amazing track record. Just look through their buy/sell archive on any stock. They are 95% positive, and many have returns of over 10,000% over a two year period. The stock that I am currently interested in has a gain of 41,615% (HLNT). I have verified their signal record (on right of web page), and if using their intra day signals, it is correct. The intra day does an amazingly good job of anticipating big moves, and will get you in or out of a stock before it takes off; hence my desire to use the logged in web page. Of COURSE they miss it sometimes, and this is the reason for a balanced portfolio.

I agree with those posters who complain about their support. It is very poor; but they maintain the site well, and I have never known it to go down. It is simply a number cruncher. I think the owner is only interested in selling advertising to support the site, and is not very interested in spending time helping individual subscribers (they seem to hide their email address). As  long as you are aware of this, I do not see any problem with their support.

You should really consider this. My problem is that I cannot follow the intraday signals, as it requires constant monitoring, and when one is posted, I usually think better, and decide not to follow it. If I could force myself to go by it, then I could OBVIOUSLY make money!

If you are interested, I would be glad to have you along. I have a programmer employed by me at this point, but could use more input!

Sincerely,
Mike

240.

Solve : c# help?

Answer»

in C#
 I have a file that has Button name on one line next line is what i want the button to do and the third line has a true or false value on wether to create the button or not. The file is populated from a grid view that part works fine the button name works fine but i cant get the button click to read to work or the true false can anybody HELP
text file looks like this
 Mahjong
 C:\Program Files\Microsoft Games\Mahjong\Mahjong.exe
 TRUE
 Chess
 C:\Program Files\Microsoft Games\Chess\Chess.exe
 TRUE
 FreeCell
 C:\Program Files\Microsoft Games\FreeCell\FreeCell.exe
 TRUE
 MineSweeper
 C:\Program Files\Microsoft Games\Minesweeper\MineSweeper.exe
 TRUE
 PurblePlace
 C:\Program Files\Microsoft Games\Purble Place\PurblePlace.exe
 TRUE
 
code for button array looks like this
var lineCount = File.ReadAllLines("C:\\ToucheDesktopApplicationFil es\\LoadApplications.txt").Length;
 _applicationButtonCount = (lineCount / 3);
 _ApplicationButton = NEW RadButton[_applicationButtonCount];
 for (int x = 0; x < _applicationButtonCount; x++)
 {
 _ApplicationButton

  • = new Telerik.WinControls.UI.RadButton();

 _ApplicationButton
  • .Name = "But_Application";

 _ApplicationButton
  • .Font = new Font("Segoe", 12);

 _ApplicationButton
  • .Size = new System.Drawing.Size(453, 49);

 _ApplicationButton
  • .Location = new System.Drawing.Point(1, 60 + x * 60);

 _ApplicationButton
  • .ImageIndex = x;

 }
 USING (sr)
 {
 for (int x = 0; x < lineCount / 3; x++)
 {
 _ApplicationButton
  • .Text = (sr.ReadLine());

 sr.ReadLine();
 sr.ReadLine();
 }
 } adding a handler for the click event of the button would be a good start...
241.

Solve : batch file for ipconfig + ping results?

Answer»

Hi guys!!
I tried searching for this and have had no luck, so I'm hoping someone can help!

I was trying to create a .bat file to email to several clients, and it would output a text file containing their IP SETTINGS and ping results for specific addresses.

I'm able to get the network info from this:

echo off
ipconfig/all > IPResults.txt

I guessing that it should also have something along the lines of:

ping -n 1 xxx.xxx.xxx.250
ping -n 1 xxx.xxx.xxx.249
ping -n 1 xxx.xxx.xxx.248
(then output the results to that same text file)

I'm just having trouble figuring out how to REFERENCE the first 3 octets of the ipconfig result to have the batch ping with specified 4th octets to see what is available.
(Like if the gateway displayed through ipconfig was 192.168.1.1, it would ping 192.168.1.250, .249, and .248, then add the ping results to the text file showing if any of those were available.)

Are you LOOKING to ping the entire subnet?CassieXoxo,

Sounds like what you need is to write this function in C, Basic, C#, etc.  Doing it on the shell is going to be somewhat tough.

If you decide to write it in a language, I think you'll have better results.

Also...

Why do you need an IP to mail someone?

There are also plenty of mass mailers out there, just look around.

Bryan Wilcutt
www.curiousinternet.comThanks for the replies!
Quote from: Squashman on February 15, 2012, 06:35:54 AM

Are you looking to ping the entire subnet?

I was really just looking to ping 2 or 3 IP addresses on the network.

Quote from: bwilcutt on February 16, 2012, 04:15:43 PM

Sounds like what you need is to write this function in C, Basic, C#, etc.  Doing it on the shell is going to be somewhat tough.


I was hoping to stick to the .bat thing because that's the only bit of programming I'm even remotely familiar with, but I'm definitely open to whatever will work best.

Quote from: bwilcutt on February 16, 2012, 04:15:43 PM
Also...

Why do you need an IP to mail someone?

There are also plenty of mass mailers out there, just look around.


Sorry I think I explained this badly! 

A lot of my day in the near future will be spent calling clients to determine if their local area network is setup for DHCP or Static IP addresses. If static, I'll have to gather their network's Gateway, Subnet, and DNS #s and find an available IP address that we can assign to a device that we'll be shipping them.

What I normally have them do over the phone is open cmd, run ipconfig/all then ping xxx.xxx.xxx.250 (since .250 is usually available on most of these NETWORKS) they read me the results and I have everything I need.
Since most of what I do is contained on the cmd prompt, I was thinking it would be much easier to have a .bat script (or something) that I could just email them to open, that would gather all of this info in a text file that they could shoot back to me.

The problem I was running into is the fact that some of the IP addresses of different customers are 192.168.1.x, 10.100.1.x, etc... and I wasn't sure how to get the .bat to ping whatever set of numbers was listed previously by ipconfig

I'm sure there's a more efficient way of doing this, but I guess that's the best way I know.

I really appreciate the help!  You can isolate output lines from ipconfig /all using the FIND command. Example:

ipconfig /all | find "Default Gateway"

Then you can use FOR to parse the line to get an IP address and extract the octets and use the first three plus your selected final one in a ping command. Perhaps if you state which line(es) from the ipconfig /all output contains the IP address(es) you wish to use, a simple script can be written. So more information please.


Quote from: CassieXoXo on February 17, 2012, 02:52:10 PM
A lot of my day in the near future will be spent calling clients to determine if their local area network is setup for DHCP or Static IP addresses. If static, I'll have to gather their network's Gateway, Subnet, and DNS #s and find an available IP address that we can assign to a device that we'll be shipping them.
Do you realize there could be both on the network.  That is how most networks are setup in the first place.   The DHCP server is setup with a range of IP addresses that it can give out to clients that request an IP address.  This is called a POOL.  One of the reasons for the pool is to maintain control of the network so that other devices like, routers, switches and servers can be allocated static IP addresses that the DHCP server is not stepping on.

If you are doing support for your clients networks I would suggest you get a better handle on how their networks are configured by asking them if they know how the network is configured or if they have documentation on how the network was configured.

Better yet it would only take a few seconds to remote into their computer as well.  You could just ask them to remote into their computer and do your voodoo and be done. Quote from: Squashman on February 18, 2012, 06:33:06 AM
Do you realize there could be both on the network.  That is how most networks are setup in the first place.   The DHCP server is setup with a range of IP addresses that it can give out to clients that request an IP address.  This is called a POOL.  One of the reasons for the pool is to maintain control of the network so that other devices like, routers, switches and servers can be allocated static IP addresses that the DHCP server is not stepping on.


Yes, I realize that many networks are setup that way. However, with many of the networks I'm dealing with, DHCP is disabled altogether. In the somewhat rare case that DHCP is enabled, their network uses .1-.250.

Quote from: Salmon Trout on February 18, 2012, 02:47:26 AM
You can isolate output lines from ipconfig /all using the FIND command. Example:

ipconfig /all | find "Default Gateway"

Then you can use FOR to parse the line to get an IP address and extract the octets and use the first three plus your selected final one in a ping command. Perhaps if you state which line(es) from the ipconfig /all output contains the IP address(es) you wish to use, a simple script can be written. So more information please.


I was thinking something like the FOR command would work, but I was having difficulty specifying the variables.
As I wrote,

Quote
Perhaps if you state which line(es) from the ipconfig /all output contains the IP address(es) you wish to use, a simple script can be written. So more information please.
242.

Solve : Application with roots in GAC can't find a dll in path.?

Answer»

This is kind of branching out from a preivous thread.  Here is the scenario:

  • I have an application that is string named and all of its libraries reside in the GAC.
  • I am writing an collection of libraries that tie into this application.
  • I create several assemblies but some interops.  These are all strong named.
  • I install all of the assemblies into the GAC.  If I leave the interops out, the application fails saying it can't find them.
  • I install the interops into the GAC.  They must somehow have an ASSEMBLY manifest related to them because they install.  Now the program works.
  • I write a simple VB6 ActiveX dll (the code is shown below).
  • I register it using REGSVR32 /s <libName>.dll.
  • I run the application and it fails.  The new dll is not found.
  • It will not allow me to add it to the GAC.  Error is - expected to contain an assembly manifest.

I am not sure why this dll would be different from the others.  They are older C++ 6 and VB6 dlls as well.  Here is the code for my simple class (based on conversations from my previous post with BC_Programmer)...

Code: [Select]
    Public Function ComToBytes(objName As String, obj As Object) As Byte()
        Dim PropBag As PropertyBag
        Set PropBag = New PropertyBag
       
        PropBag.WriteProperty objName, obj
        ComToBytes = PropBag.Contents
    End Function
   
    Public Function BytesToCOM(objName As String, obj() As Byte) As Object
        Dim PropBag As PropertyBag
        Set PropBag = New PropertyBag
   
        PropBag.Contents = obj
        Set ComFromBytes = PropBag.ReadProperty(objName)
    End Function


Any suggestions as to why the application won't find my dll, no matter where it resides?


You do have control over the C# application in question, correct?

Why can't you reference the COM library via the IDE?

At the very least, adding a reference to a COM component will generate a managed wrapper for the component. I believe you can do this manually using tlbimp.exe which is part of the .NET framework SDK.

Basically, what you end up with is the managed code which uses the unmanaged COM component.

The managed code can be installed in the GAC, but the unmanaged code cannot. The GAC-installed wrapper accesses that unmanaged code, however. And it needs to stay wherever it was when it was registered (via regsvr32)

You need a managed wrapper for the COM DLL.If you mean to the solution or projects for the calling application, no I don't.

So basically, I build the ActiveX dll (VB6 code) and reference it from the .NET 2.0 C# project.

When I do that it builds the interop but the it can't be added to the GAC because it has no assembly manifest.

If i try "tlbexp.exe MyClass.dll" to build a type library it fails with an error (expected to contain an assembly manifest).  This is actually the same error I get when I try to install it to the GAC.

I am KINDA baffled.  I don't understand why it won't see the dll and use it unless it is in the GAC.  If I could this method working I would gladly accept it...  It seems crazy to think that I would have to try and implement IPersist and IPersistStream on every class that requires this serialization. 

Thanks again.I also tried:

Code: [Select]
tlbimp.exe MySerializer.dll /keyfile:My_KeyFile.snk /machine:X86


to force it into building an assembly-based dll straight from the COM dll.  It didn't complain and it built a dll.  I registered it, added it to the project, and could add it to the GAC.

When I ran the code it made it PAST the previous error and died where it tried to instantiate a class at the line:

Code: [Select]
MySerialize.SerializerClass serializer = new MySerialize.SerializerClass();


with the error "Retrieving the COM class factory for component with CLSID {95388FE5-87E8-4164-ADA2-E974FA3803FB} failed due to the following error: 80040154."}

Not sure if I would call that progress or not...   80040154: Class Not Registered.

If the program in question is 64-bit, than it won't be able to instantiate 32-bit components (such as those created with VB). A .NET program/Library will be 64-bit if it is run on a 64-bit system and was built CPU-agnostic (AnyCPU).

If the main application is 64-bit, or compiled with AnyCPU, than it will only be able to access 64-bit COM components; which means you won't be able to use the VB6 wrapper method since VB6 cannot compile 64-bit. additionally, if the COM component you want to use is 32-bit, all bets are off and you won't be able to use it at all. only a 32-bit assembly can use a 32-bit COM component, and only a 32-bit Assembly can use another 32-bit assembly, so if you were to change your project to compile to x86, than the main application might not be able to use your library if it is AnyCPU and run on a 64-bit processor.

Not sure if this will help:http://blogs.msdn.com/b/junfeng/archive/2007/04/14/genman32-a-tool-to-generate-sxs-manifest-for-managed-assembly-for-registration-free-com-net-interop.aspx

Personally I never touch the GAC, or deal with strong named assemblies or any of that, so I'm just sort of groping around in the dark here, myself. It looks like that page is more for creating assemblies that can be used as COM components, and not vice-versa...

But it might be that the Interop Assembly needs a Manifest in it to be dependent on the COM assembly.

Assuming the problem isn't essentially intractable (getting a 32-bit COM component to be used by a library that is accessed by a AnyCPU compiled assembly) you might have to fall-back on the IPersistStream method.

Basically:

-VB6 only compiles 32-bit COM components.
-A 64-bit Assembly cannot use 32-bit COM components. A 32-bit Assembly can, but...
-a 64-bit Assembly cannot use 32-bit Assemblies
-VB6 can only use 32-bit COM components; so evidently the COM component in question is 32-bit.


Basically you are building a chain- Main Application->Your Library->VB6 Wrapper->COM Component

the VB6 wrapper is 32-bit, so Your Library would to be 32-bit, which means that the main application would as well, but you have no control over that, which is where you have issues.

Even if you eliminate the wrapper and try to use IPersistStream on the COM component manually, the COM component is 32-bit so you have the same problem.

Bit-ness mismatch is really all I can think of to explain this.
I really appreciate all of your input on this topic...

The primary application is loaded with Interops, so I don't believe it is a 32bit vs. 64bit issue.  I believe it is some kind of issue related to things in the GAC needing other things to be in the GAC to function.

This morning I wrote a simple WinForm application with a single button. 

Code: [Select]
        private VOID btnCut_Click(object sender, EventArgs e)
        {
            string str = "Test";
            object theObj= Activator.CreateInstance(Type.GetTypeFromProgID("TheObjectData.TheObject"));
           
            MySerializer.SerializerClass myClass = new MySerializer.SerializerClass();
            Array arr = myClass.ComToBytes(ref str, ref theObj);
        }


All I did here was make sure the VB6 dll was registered and added a reference to it.  When the button is pushed, the VB6 class gets instantiated and a method is called returning a proper array.

With the other application, I had some components that would break the code during runtime.  Then, it was always a FileNotFoundException.  If I added the dlls to the GAC those exceptions would go away.  So if I could just get this dll into the GAC properly I think it would work.  The problem is I don't know what else to try to get the thing in there.  Even though the command:

Code: [Select]
tlbimp.exe MySerializer.dll /keyfile:My_KeyFile.snk /machine:X86


seems to build a GAC-compatible dll straight from the VB6 dll (instead of a type library), I don't think it is really valid.  I've never heard of building an assembly dll like this, I just thought I would try it.

Gotta be missing something...    I found this:

http://www.hanselman.com/blog/GotchasAroundPrimaryInteropAssembliesAndTheGAC.aspx

Quote
Of course the COM Object that you're referring to has to be registered, but the PIA has to be as well.  You'll need to call RegASM.exe to create a key in the registry under HKEY_CLASSES_ROOT\TypeLib\{yourclassid}\PrimaryInteropAssemblyName.  The value of this key should be the fully qualified Assembly name like: MYDLL, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.  Some folks call RegASM, others ship a .REG file or create this key during the installation procedure.

To recap:

    Register COM Object (if not already)
    Create InteropAssembly with TLBIMP.EXE and /primary (make sure it's strongly named)
    RegASM the resulting InteropAssembly
    Put the PIA in the GAC
OK.  We can close this one out.  I have built an assembly from the VB6 and stuck it into the GAC.  I can instantiate the VB6 class and call one of the two functions from C#.  I am going to open another thread for the problem I am having with the second function.

In a nutshell, the problem was related to not properly building the assembly.  This is basically how this had to go down.

  • Create a VB6 dll, realizing that in VB6 the type library information is embedded in the dll.
  • Using OLE Viewer, Look at the type library information.  Copy that to an editor and save as an idl file.
  • Use midl to create a tlb file.
  • Copy the tlb and dll over to my development machine.
  • Register the tlb and dll file.
  • Use tlbimp to create an assembly from the tlb file.
  • Register the assembly.
  • Install the assembly to the GAC.
  • Reference the assembly in the project.

Thanks again. what you end up with is the managed code which uses the unmanaged COM component.
243.

Solve : User defined type to object in VB6?

Answer»

OK, Let's look at my previous question a different way...

I have a method inside a class that creates a user DEFINED type from a dll and wants to pass that out as an Object type.  The function looks a little LIKE this:

Code: [Select]
PUBLIC Function BytesToRect(objName As String, obj() As BYTE) As Object
    Dim PropBag As PropertyBag
    Set PropBag = New PropertyBag
   
    Dim myObj As MyClass.MyType
    Set myObj = PropBag.ReadProperty(objName)
   
    BytesToRect = myObj
End Function


Obviously, this will fail SINCE myObj is of type MyClass.MyType.  Is there a way in VB6 to convert this to an Object type and pass it from the function?  I was thinking that CObj or DirectCast in .NET would do this but I haven't found anything similar in VB6.

Thoughts?

244.

Solve : VB add char after n chars?

Answer»

Hello guys,
I'm trying to make a PROGRAM that adds a character after n characters.
For example I'll insert the number 100000000000000 and I want that after each 5 characters to add a dot, like 10000.00000.00000
Can you give me a LINK or a code for this please?
Thank you.

Visual Basic 6:

Code: [Select]'Inserts 'Insert' Every Interval Characters in InputStr and returns the result.
Public Function EveryN(ByVal InputStr As String, ByVal Interval As Integer, ByVal Insert As String) As String
    'there are a few ways to do this, the most common is to iterate character by character, but that is rather slow, PARTICULARLY
    'since String concat is typically done a tad slowly on VB.
    'instead, we'll split the string into an array where each element holds Interval characters from the original string. Then
    'we can use the built in Join function to connect them together.
    Dim Strparts() As String
    Dim NumElements As Integer
    NumElements = (Len(InputStr) \ Interval) + Abs((Len(InputStr) MOD Interval > 0))
    ReDim Strparts(NumElements - 1)
    Dim I As Long
    Dim StartPos As Long
    For I = 0 To NumElements - 1
       StartPos = (I * Interval) + 1
       Strparts(I) = Mid$(InputStr, StartPos, Interval)
   
   
    Next I
   
    EveryN = Join(Strparts, Insert)


End Function

Sample Usage:

Code: [Select]Dim Strtest As String
Dim I As Long, J As Long
For I = 0 To 10
    For J = 0 To 9
        Strtest = Strtest + Trim$(Str$(J))
Next J, I

Dim result As String
result = EveryN(Strtest, 5, ",")
MsgBox (result)


Visual Basic .NET:


Code: [Select]    Public Function EveryN(ByVal InputStr As String, ByVal Interval As Integer, ByVal Insert As String) As String
        Dim NumElements As Integer
        NumElements = (Len(InputStr) \ Interval) + IIf((Len(InputStr) Mod Interval > 0), 1, 0)
        Dim strbuild As New System.Text.StringBuilder
        Dim I As Long, useLength As Integer = Interval
        Dim StartPos As Long
        For I = 0 To NumElements - 1

            StartPos = (I * Interval)
            If (InputStr.Length - StartPos < Interval) Then
                strbuild.Append(InputStr.Substring(StartPos))
            Else
                strbuild.Append(InputStr.Substring(StartPos, Interval))
            End If
            If I < NumElements - 1 Then strbuild.Append(",")


        Next I

        Return strbuild.ToString()


    End Function

Sample usage:

Code: [Select]   Sub Main()
        Dim Strtest As String = String.Empty
        Dim I As Long, J As Long
        For I = 0 To 10
            For J = 0 To 9
                Strtest += Trim$(Str$(J))
        Next J, I
        Dim result As String
        result = EveryN(Strtest, 5, ",")
        Console.WriteLine(result)
        Console.ReadKey()
    End Sub


Also, if you just want standard, decimal after 3 characters, you can use Format(number,"#,###")

245.

Solve : Batch file installer fail to launch program at the end of script...?

Answer»

I am having a problem with a batch file that does this:

1. Checks to see if folder1 exists; if not, then it makes it
2. Checks to see if sub-folder1 exists; if not, then it makes it
3. Copies a file to the sub-folder1
4. Copies 3 files to the folder1
5. Deletes the above 4 files from the current directory
6. Runs a Vb-script that extracts the Zip-file to the FOLDER %APPDATA%
7. Deletes the Zip-file and Vb-script from folder1
8. Runs the file (File Launcher.exe) in the folder1 <--This is where the script GOES wrong...

It shows it run for a really short time (as in I can see it display the proper text in the command window) and closes without functioning properly
When I normally run the File Launcher.exe, it works fine. In the installer script, it does not work right.

Installer script:    (Could this being "compiled" be the problem?)
Code: [Select]ECHO OFF
TITLE File Installer [By: Nathansswell]
COLOR 0A
SET PATH=%USERPROFILE%\My Documents\Folder
SET PATH2=%USERPROFILE%\My Documents\Folder\Subfolder
ECHO ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»
IF EXIST "%PATH%" GOTO A
IF NOT EXIST "%PATH%" MKDIR "%PATH%"
ECHO º Creating folder "Folder"    º
:A
IF EXIST "%PATH2%" GOTO B
IF NOT EXIST "%PATH2%" MKDIR "%PATH2%"
ECHO ÌÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ͹
ECHO º Creating folder "Subfolder" º
ECHO ÌÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ͹
:B
ECHO º       Moving items to       º
ECHO º   "My Documents\Folder"     º
ECHO ÌÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ͹
:1
COPY "file.exe" "%PATH2%" >nul
IF EXIST "%PATH2%\file.exe" GOTO 2
IF NOT EXIST "%PATH2%\file.exe" GOTO 1
:2
COPY "File Launcher.exe" "%PATH%" >nul
IF EXIST "%PATH%\File Launcher.exe" GOTO 3
IF NOT EXIST "%PATH%\File Launcher.exe" GOTO 2
:3
COPY "ZIPFILE.zip" "%PATH%" >nul
IF EXIST "%PATH%\Zipfile.zip" GOTO 4
IF NOT EXIST "%PATH%\Zipfile.zip" GOTO 3
:4
COPY "extractor.vbs" "%PATH%" >nul
IF EXIST "%PATH%\extractor.vbs" GOTO 5
IF NOT EXIST "%PATH%\extractor.vbs" GOTO 4
:5
DEL "File Launcher.exe"
DEL "Zipfile.zip"
DEL "extractor.vbs"
ECHO º   Running "extractor.vbs"   º
ECHO ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ
"%PATH%\extractor.vbs"
CLS
DEL "%PATH%\extractor.vbs"
DEL "%PATH%\.Zipfile.zip"
START "%PATH%\File Launcher.exe"
EXITFile Launcher.exe script:      (It is a "compiled" batch file that works fine)
Code: [Select]ECHO OFF
MODE CON COLS=30 LINES=12
TITLE File Launcher
COLOR 0A
ATTRIB "Jarfile.jar" +H
ATTRIB "Splashx32.png" +H
ECHO ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»
ECHO º Launching File...         º
ECHO ÌÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ͹
ECHO º Please wait...            º
ECHO ÌÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ͹
ECHO º WARNING:DO NOT CLOSE THIS º
ECHO ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ
JAVA -Xmx1024M -Xms512M -splash:"Splashx32.png" -jar Jarfile.jar
ATTRIB "Jarfile.jar" -H
ATTRIB "Splashx32.png" -H
DEL "Jarfile.jar"
DEL "Splashx32.png"
EXITVb-script:     (This also works fine)
Code: [Select]path=Replace(WScript.ScriptFullName, WScript.ScriptName, "")
path2="%APPDATA%"
path3="Zipfile.zip"
Set ws=CreateObject("WScript.Shell")
fullpath=ws.ExpandEnvironmentStrings(path)
fullpath2=ws.ExpandEnvironmentStrings(path2)
ZipFile=fullpath&path3
ExtractTo=fullpath2
Set fso = CreateObject("Scripting.FileSystemObject")
If NOT fso.FolderExists(ExtractTo) Then
fso.CreateFolder(ExtractTo)
End If
set objShell = CreateObject("Shell.Application")
set FilesInZip=objShell.NameSpace(ZipFile).items
objShell.NameSpace(ExtractTo).CopyHere(FilesInZip)
Set fso = Nothing
Set objShell = Nothing
Thanks in ADVANCE. -Nathansswell

246.

Solve : copying text from one site and making it jump to another site and input there?

Answer»

My dad is not familiar with computers at all. I put bookmarks on his desktop for all his favorite places. He can click those and get those places, and little else. And finding keys and inputting text is very hard and tedious for him. He thinks I am a pc wizard by my little knowledge, which I am nowhere near. I asked him what I could do to MAKE working with the computer easier for him and his WORK. He is in real estate; he opens up the bookmarked real estate listing page, and wants me to automate the process of taking an address from that page, and having that information automatically input into Google maps page where it shows the picture of the property, and then from there, have the address input into our local county appraisal district site area where it brings up the property's information on that site. He has such trouble typing and opening up multiple pages, that this process, for him, is causing him much stress and many troubles. I want to make his life easier, but I have no programming skills and do not know the first place to start. My thoughts are that there has to be a program, software, or way I can set it up where once he highlights and copies the property address from the original site, it can be transferred, transported, jumped or told to put that information into the Google maps search bar, and have it enter there. Then he could copy the same property address from there and by the same process shoot it over to the appraisal site address search bar and SUBMIT it there. So I guess I am looking for a way to have copied information, jump to ANOTHER website and inputted into an area and submitted , and then repeated at another site. Any help in leading me into the right direction, or detailed instruction, or advice would be greatly appreciated. I REALLY want to help my dad out, and show him I can do this for him. I thought this would be a great place to ask.My best idea would just be to have Google Maps as a bookmarked site.  You can highlight and copy/paste information into Google to pull up a map, and from there highlight and copy/paste to wherever you want that information to go.  I don't think there is an actual way to make a program pesonally that will do all you are asking.

The best way to help your dad is to do this yourself enough times, and then show him how to do it.  It sounds like you will be using the same Google maps to search for information, and using the same basic steps to transfer it to the site.  Maybe come up with a step-by-step instruction and print it out for him to follow along with to do this. Quote from: Darthgumby on March 21, 2012, 08:52:03 AM

My best idea would just be to have Google Maps as a bookmarked site.  You can highlight and copy/paste information into Google to pull up a map, and from there highlight and copy/paste to wherever you want that information to go.  I don't think there is an actual way to make a program pesonally that will do all you are asking.

The best way to help your dad is to do this yourself enough times, and then show him how to do it.  It sounds like you will be using the same Google maps to search for information, and using the same basic steps to transfer it to the site.  Maybe come up with a step-by-step instruction and print it out for him to follow along with to do this.
Good advice, Darthgumby.  I also doubt there is an actual way to make a program that will do all that's being asked for here.  So, your advice is right on target.
247.

Solve : Dll references between VB6 and .NET?

Answer»

OK, here's one...

I have a VB6 ActiveX dll that references ANOTHER COM dll.  Let's call it "MyDll".  The VB6 code looks like this:

Code: [Select]
Public Function ComToBytes(objName As String, obj As Object) As Byte()
    Dim PropBag As PropertyBag
    Set PropBag = NEW PropertyBag
       
    PropBag.WriteProperty objName, obj
    ComToBytes = PropBag.Contents
End Function
   
Public Function BytesToType1(objName As String, obj() As Byte) As Mydll.Type1
    Dim PropBag As PropertyBag
    Set PropBag = New PropertyBag
   
    PropBag.Contents = obj
    BytesToType1= PropBag.ReadProperty(objName)
End Function

Public Function BytesToType2(objName As String, obj() As Byte) As MyDll.Type2
    Dim PropBag As PropertyBag
    Set PropBag = New PropertyBag
   
    PropBag.Contents = obj
    BytesToType2= PropBag.ReadProperty(objName)
End Function


Originally, I tried having only two methods in the class with one of them returning an Object TYPE.  Then I COULD cast it respectively in .Net.  However, this was throwing an error - 'Object variable or With block variable not set'.  I believe this was because it didn't really know what it was returning.

The .Net code references MyDll as well.  However, when it references the dll it Interops it.  So a call similar to:

Code: [Select]
Type1 myObj = serializer.BytesToType1(ref objName, ref objArray);


will cause two errors:

  • The type 'MyDll.Type1' is defined in an assembly that is not referenced. etc...
  • Cannot implicitly convert type 'MyDll.Type1' to 'MyDll.Type1[<PATH TO INTEROPPED DLL>\Interop.TAMMACInterfaces.dll]'

Obviously, the two dll versions contain the same information.  I can't add the reference as suggested in error 1 because it WOULD just wrap it again.  Any ideas on something like this?

Thanks!
248.

Solve : VB6 number formatting?

Answer»

If I run the following code:

Code: [Select]Dim i As DOUBLE

For i = 0 To 5 Step 0.001
    If i = 2 Then MsgBox "bla"
Next i

It never happens because i is never exactly 2 for some reason. It is something like 2.000000754268376. I can fix this using the following. . .

Code: [Select]Dim i As Double
Dim j As Double

For i = 0 To 5 Step 0.001
    j = Val(Format(i, "#.###"))
    If j = 2 Then MsgBox "bla"
Next i

My question is: Is there a better/more efficient way of doing this? I have a massive loop and I don't want it slowed down anymore. This is not a new issue. I was fixed ages ago.
I depends on what your really want to do.
Why would you want to loop in fractional increments anyway?
Somewhere this was documented, but I don't remember whee. You are just supposed to know it. Microsoft basic does not do math in base ten.
If you want to count things the have integer values, like counting sheep, you use whole numbers. Never fractions.

In applications where a fraction is needed, but a fraction that represents division of an integer, you need to rethink what you want to do.

By definition real numbers do not have exact values. When you count by 0.5 you are not saying exactly 0.5, but a number very close to it.  So by that definition 0.5 times 4 is not exactly 2, but a value very close to two, but it can not be two as a integer number.

In Visual Basic, as well as other things like it, you have to be very careful about looking for an exact natch when using real numbers. If you do get a match, the numbers are not just equal, they are identical. In engineering with real numbers you never expect an exact march

Please come back and explain why you  step in fractional values.

It would help if you could explain the practical value of what you want to do. There are special functions can can take care of this problem, when you really need to find two real numbers that are very, very close.

Sorry if  I sound dogmatic. Some versions of Microsoft Basic with 'fix' this problem automatically. But it really is the responsibility of the programmer to use the right data types.

EDIT: This link is better that how I said it. It is about .NETm but the ideas represent most earlyir versions of Microsoft Basic.

From: extremeoptimization.com
Floating Point in .NET part 1: Concepts and Formats Quote from: Geek-9pm on March 19, 2012, 12:55:50 AM

By definition real numbers do not have exact values. When you count by 0.5 you are not saying exactly 0.5, but a number very close to it.  So by that definition 0.5 times 4 is not exactly 2, but a value very close to two, but it can not be two as a integer number.

I suppose I know what you're getting at, but this is nonsense. Some non-integer real numbers can be represented exactly in a number base, some cannot. 0.5 is a rational number which can be represented exactly in base 10, but not in BINARY (hence the problem).

The OP needs to read a good programming book, with particular reference to data types, binary representation, floating point arithmetic, and rounding errors.

Salmon Trout, My remark was in the context of Microsoft basic.

The NOTATION "0.5" could indicate a value result of a division of an integer. But it might be a real number. In Microsoft Basic it will be cast as a real number and it no longer sis the result of a division of an integer. Unless the programmer did something to force it to another type.

There are formats used in MS Basic the keep numbers in a form that is related to an integer. The currency type is such. It is actually a long integer. But when printed or displayed, it is shown as a decimal fraction.

Once a number as been converted to a real floating point number, it loses its virginity forever. It no longer is an exact value. By definition real numbers are not exact values, even if they are. In other words, a real number has a component that is not quantized.  If the number is quantized, it could be a fixed-point number in either binary or an hybrid number system.

Anyway, he can resolve the issue by user either INT(), which truncates, or ROUND(), which rounds off numbers to a given number of decimal places.

Code: [Select]If i = 2 Then MsgBox "bla"Could be rewritten as:
Code: [Select]If int(i+0.1) = 2 Then MsgBox "bla"Good night. Quote from: Linux711 on March 18, 2012, 10:07:38 PM
If I run the following code:

Code: [Select]Dim i As Double

For i = 0 To 5 Step 0.001
    If i = 2 Then MsgBox "bla"
Next i

It never happens because i is never exactly 2 for some reason. It is something like 2.000000754268376. I can fix this using the following. . .

Code: [Select]Dim i As Double
Dim j As Double

For i = 0 To 5 Step 0.001
    j = Val(Format(i, "#.###"))
    If j = 2 Then MsgBox "bla"
Next i

My question is: Is there a better/more efficient way of doing this? I have a massive loop and I don't want it slowed down anymore.

Code: [Select]Dim i As Integer
Dim j As Double
for i = 0 to 5000
    j = CDbl(i) / 1000#
    if j = 2 Then MsgBox "Blah"
Next

P.S: it's never exactly 2 in the original because 0.001 cannot be accurately represented using floating point. This version attempts to avoid that problem by not incrementing using a INEXACT floating point number. Instead, each iteration increments using an integral value, and that value is used in a division. This is pretty much a scaled integer approach. The problem you were seeing was because of the accumulated imprecision from adding an inprecise floating point representation to itself.


Here's another version that might work, but it will probably be slower, because it uses the Decimal subtype of Variant. (It's not so much slow because of the Variant type but because all the Decimal operations are dealt with through software)

Code: [Select]Dim i As Variant
i=CDec(0)
for i = 0 to 5 step CDec(0.001)
     If i = 2 Then MsgBox "bla"
Next i




Quote
Once a number as been converted to a real floating point number, it loses its virginity forever. It no longer is an exact value.
As Salmon Trout just said, some numbers can be represented perfectly in floating point. Most whole numbers are simple to represent perfectly in floating point, as long as the number doesn't require a exponent to represent. Any number that fits in the mantissa will be a perfect representation of that value.

The issue here is not that a single floating point value was inaccurate; the Visual Basic runtime works with this- 0.1*2 will equal 0.2 even though the actual values are not equal, because VB intrinsically uses a tolerance value. The problem is in the use of floating point numbers that cannot be accurately represented as accumulators; 0.001, for example- because this compounds the ERROR to the point where the accumulated error becomes significant.

Running my older Expression Evaluator  (written in VB6) on the expression SEQ(X,X,1,5,0.01) (which creates a sequence of values from 1 to 5 in steps of 0.01) there is no visible error in the output until 1.6, which is output as 1.69999999998 (or something similar) That is the point at which the floating point error "escapes" the built in tolerances of the floating point library in use.

Of course, even so, comparing two floating point numbers for equality is typically not a good idea because you cannot be sure of the processes that generated those numbers. Usually, the test could merely take the difference and assert that it is smaller than a given tolerance:

Code: [Select]Const tolerance As Double-0.001

Public Function TestEqual(ByRef Value1 As Double,ByRef Value2 As Double) As Boolean
    TestEqual = (Abs(Value1-Value2) < tolerance)
End Function
249.

Solve : calculate from values in a text file's first column, ":" delimited, bat, VBs, PS?

Answer»

Please help me program the scenario below:
contents of myfile.txt:
ServerName: KDB2012
----------------------------
2:Black\Bird
16:Black\Dog
20:Black\Cat
----------------------------
6:Animal
15:Animal
65:Animal

Now, I want to check "Animal" by its number, if that number (6 in our case) > 2 and < 16 (Black\whatever) then print Animal = Black\Bird
similarly if 15 > 16 and 15 < 20 then print Animal = Black\Dog
             if 65 > 20 then print Animal = Black\Cat

I am in desperate need to do this, either using batch, VBs, Powershell. Much Appreciated! Why don't you put what is really in the file?
ServerName: KDB2012\ADUsers
---------------------
2:KALDB\Developers
16:KALDB\ProdDevs
20:KALDB\BADATAREADER
25:KALDB\ZADATAREADER
115:KALDB\AREADER
168:KALDB\PREADER
190:KALDB\PWRITER
192:KALDB\READER
257:KALDB\WRITER
261:KALDB\SWRITER
299:KALDB\ITDataProc
316:KALDB\RDevelopment
340:KALDB\ReadOnly
-------------------------
152:Kalvin Rodger
183:Kalvin Rodger
239:Kalvin Rodger
289:Kalvin Rodger
There will be 4 lines printed

152:Kalvin Rodger
152 is greater than 115 and less than 168, so print Kalvin Rodger = KALDB\AREADER

183:Kalvin Rodger
183 is greater than 168 and less than 190 so print Kalvin Rodger = KALDB\PREADER

239:Kalvin Rodger
239 is greater than 192 and less than 257 so print Kalvin Rodger = KALDB\READER

289:Kalvin Rodger
289 is greater than 261 and less than 299 so print Kalvin Rodger = KALDB\SWRITER

Is that correct?

Correct!
And the contents of the file are dynamic. They will change from time to time. The groups and their number and the ADUser and its number will keep on changing.Any Progress? Quote from: kdb2012 on March 22, 2012, 10:10:22 AM

Any Progress?

Didn't know we were on the clock. 

The hard part was retrieving chunks of the file for INDIVIDUAL processing. VBScript was a possible solution as it supports regular expressions, but so does Powershell so I went with the latter.

Code: [Select]$file = "c:\myfile.txt"
$arrTitles = ()
$arrEmps = ()

# Load the Job Titles into Array
#
(Get-Content -Path $file) -match "^[0-9]{1,3}:[A-Z]{1,}\\[A-Z]{1,}$" |
  ForEach-Object {
    $arrTitles += , ( [Convert]::ToDecimal($_.split(":")[0]), $_.split(":")[1] )
  }
$arrTitles.GetEnumerator() | Sort-Object | Out-Null
 
# Load the Employees into Array
#
(Get-Content -Path $file) -match "^[0-9]{1,3}:[A-Z]{1,}\s[A-Z]{1,}$" |
  ForEach-Object {
    $arrEmps += , ( [Convert]::ToDecimal($_.split(":")[0]), $_.split(":")[1] )
  } 
 
#Do the LOOKUPS
#
for($j=0; $j -lt $arrEmps.Count; $j++) {
  for($i=0; $i -lt $arrTitles.Count - 1; $i++) {
    if( ($arrEmps[$j][0] -GE $arrTitles[$i][0]) -and ($arrEmps[$j][0] -le $arrTitles[$i+1][0]) ) `
      { Write-Host $arrEmps[$j][1], "=", $arrTitles[$i][1] }
  }
}

Save the script with a PS1 extension and run from the Powershell command prompt. Powershell does not search the current directory for a script so use the .\ pointer if you need to point to the current directory.

The first line of code is the file name. Change as needed.

 Well done, Sidewinder!
Excellent! Thanks you sooo much.I just had to finish it...

Save with .vbs extension
call with cscript.exe //nologo
pass input filename as parameter

example

cscript //nologo Scriptname.vbs input.txt

input.txt...

Code: [Select]ServerName: KDB2012\ADUsers
---------------------
2:KALDB\Developers
16:KALDB\ProdDevs
20:KALDB\BADATAREADER
25:KALDB\ZADATAREADER
115:KALDB\AREADER
168:KALDB\PREADER
190:KALDB\PWRITER
192:KALDB\READER
257:KALDB\WRITER
261:KALDB\SWRITER
299:KALDB\ITDataProc
316:KALDB\RDevelopment
340:KALDB\ReadOnly
-------------------------
152:Kalvin Rodger
183:Kalvin Rodger
239:Kalvin Rodger
289:Kalvin Rodger


The script...

Code: [Select]Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ReadFile  = objFSO.OpenTextFile   (wscript.arguments(0),  ForReading)
strText = ReadFile.ReadAll
Readfile.Close
arrFileLines = Split(strText, vbCrLf)
i=3
L=0
Dim LimitList()
Do
sline=arrFileLines(i)
ReDim Preserve LimitList (l)
LimitList (l) = sline
l = l + 1
i = i + 1
Loop until Mid(sline,1,10)="----------"

Dim LimitValues()
Dim OutPutText()
For j = 0 To (UBound(LimitList)-1)
MyString=LimitList(j)
arrTokens = Split (MyString, ":")
ReDim Preserve LimitValues(j)
LimitValues(j) = arrtokens(0)
ReDim Preserve OutPutText(j)
OutPutText(j) = arrTokens(1)
Next

Dim LookupCode()
For j = 0 To (UBound(LimitValues)-1)
ReDim Preserve LookupCode(j)
LookUpCode (j) = "If (numval > " & LimitValues(j) & ") AND (numval < " & LimitValues(j+1) & ") Then wscript.echo nameval & " & Chr(34) & " = " & OutPutText(j) & Chr(34)
Next

ReDim Preserve LookupCode(j)
LookUpCode (j) = "If (numval > " & LimitValues(UBound(LimitValues)) & ") Then wscript.echo nameval & " & Chr(34) & " = " & OutPutText(j) & Chr(34)

For j = i To UBound(arrFileLines)
MyString = arrfilelines(j)
arrTokens = split(MyString,":")
numval=arrTokens(0)
Nameval=arrTokens(1)
For k = 0 To UBound(LookUpCode)
ExecuteGlobal LookUpCode(k)
Next
Next

output...

Code: [Select]Kalvin Rodger = KALDB\AREADER
Kalvin Rodger = KALDB\PREADER
Kalvin Rodger = KALDB\READER
Kalvin Rodger = KALDB\SWRITERViola great my friend.In the interest of accuracy, I have since discovered that the Powershell solution has a serious logic flaw and an improper use of the Sort-Object cmdlet. The script worked in spite of the flaws, but will produce inaccurate results under certain circumstances.

A newer and better version is posted below:

Code: [Select]$file = Join-Path -Path $pwd -ChildPath myfile.txt
$arrTitles = ()
$arrEmps = ()

# Load the Job Titles into Array
#
(Get-Content -Path $file) -match "^[0-9]{1,3}:[A-Z]{1,}\\[A-Z]{1,}$" |
  ForEach-Object {
    $arrTitles += , ( ( [Convert]::ToDouble($_.split(":")[0]) ).ToString("000"), $_.split(":")[1] )
  }
 
$arrTitles = $arrTitles | Sort-Object {Expression={$_[0]}; Ascending=$true}

# Load the Employees into Array
#
(Get-Content -Path $file) -match "^[0-9]{1,3}:[A-Z]{1,}\s[A-Z]{1,}$" |
  ForEach-Object {
    $arrEmps += , ( ( [Convert]::ToDouble($_.split(":")[0]) ).ToString("000"), $_.split(":")[1] )
  }
   
# Do the Lookups
#
for($j=0; $j -lt $arrEmps.Count; $j++) {
  for($i=0; $i -lt $arrTitles.Count - 1; $i++) {

    if( ($arrEmps[$j][0] -eq $arrTitles[$i+1][0]) ) `
      { Write-Host $arrEmps[$j][1], "=", $arrTitles[$i+1][1]; break }

    if( ($arrEmps[$j][0] -ge $arrTitles[$i][0]) -and ($arrEmps[$j][0] -lt $arrTitles[$i+1][0]) ) `
        { Write-Host $arrEmps[$j][1], "=", $arrTitles[$i][1] }
  }       
}

Sorry for any inconvenience.  I've been prettying up my effort too...

Code: [Select]
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Read whole input file at once into string
Set ReadFile = objFSO.OpenTextFile (wscript.arguments(0),  ForReading)
strText = ReadFile.ReadAll
Readfile.Close

' Split string into individual lines
arrFileLines = Split(strText, vbCrLf)
Dim LimitList()
Dim LimitValues()
Dim OutPutText()

' Get first part into array
' Parsed stored file up to second dashed line

' Start at 3rd line
InputLine=3
LimitLine=0

' Read file lines one by one
Do
sline=arrFileLines(InputLine)
ReDim Preserve LimitList (LimitLine)
LimitList (LimitLine) = sline
LimitLine = LimitLine + 1
InputLine = InputLine + 1
Loop until Mid(sline,1,10)="----------"

' InputLine now points to first line after dashes
DataStart = InputLine

' Get band limit values
' Read each line of first block
For j = 0 To (UBound(LimitList)-1)
' Split line into 2 tokens at : character
arrTokens = Split (LimitList(j), ":")
ReDim Preserve LimitValues(j)
' First token is numerical value
LimitValues(j) = arrtokens(0)
ReDim Preserve OutPutText(j)
' Second token is text string for that band
OutPutText(j) = arrTokens(1)
Next

' Process second part of input file
For j = DataStart To UBound(arrFileLines)
' Split line into 2 tokens at : character
arrTokens = split(arrfilelines(j),":")
numval=Int(arrTokens(0))
Nameval=arrTokens(1)
' For each line in second part
For k = 0 To UBound(Limitvalues)
LineToWrite = nameval & " = " & OutPutText(k)
' This is lower test value
lower = Int(Limitvalues(k))
' If not last line check if number is above this band lower limit
' and below next band lower limit
If k < UBound(Limitvalues) Then
' This Is next band lower limit
upper = Int(Limitvalues(k+1))
' Do test
If (numval > lower) AND (numval < upper) Then
wscript.echo LineToWrite
End If
Else
' If this is last line just test if number is above limit
If (numval > lower) Then
wscript.echo LineToWrite
End If
End If
Next
Next

Not sure why am I getting this:

RESULTS ARE OK, but
in old script
C:\Kaldb\adu.vbs(42, 4) Microsoft VBScript runtime error: Subscript out of rang
e: '[number: 0]'
in new script
C:\Kaleem\now.vbs(53, 2) Microsoft VBScript runtime error: Subscript out of rang
e: '[number: 0]'

53: numval=Int(arrTokens(0))
54: numval=arrTokens(1) Quote from: kdb2012 on March 26, 2012, 04:04:41 PM
Not sure why am I getting this:

RESULTS ARE OK, but
in old script
C:\Kaldb\adu.vbs(42, 4) Microsoft VBScript runtime error: Subscript out of rang
e: '[number: 0]'
in new script
C:\Kaleem\now.vbs(53, 2) Microsoft VBScript runtime error: Subscript out of rang
e: '[number: 0]'

53: numval=Int(arrTokens(0))
54: numval=arrTokens(1)

Possibly there is a line in input file not as your description; best thing is to learn scripting and then you can write and fix scripts yourself. Does Sidewinder's script GIVES error?
250.

Solve : datetime batch file??

Answer»

we have 3 client computers with a WINDOWS SERVER ,,these computers have joined with the windows server through networking,some times the time will change on the client computers ,i want create a batch file(notepad) for time ,when i double click on the batch the time  will be equal with windows server time ,so how i do it?http://technet.microsoft.com/en-us/library/cc758905(v=ws.10).aspxWell, I don't understand why you don't want to use the exact time, which is a feature in most present windows OS  PCs with Internet aces.

If a PC  fails  to keep time, it is either a  a security breach or a broken clock clock chip/crustal. Or maybe automatic time check was not enabled. But it is HARD to imagine why anyone would want to do that.Geek, I believe he is trying to get the client computers that are joined to the domain to sync with the time of the server. Quote from: Squashman on March 28, 2012, 05:28:05 PM

Geek, I believe he is trying to get the client computers that are joined to the domain to sync with the time of the server.
You are RIGHT. I mus read his problem. The link you provided should solve his problem. My bad.  Code: [Select]net time \\servername /set