[codebase] post hier je zinnige code!

Pagina: 1 2 Laatste
Acties:
  • 5.671 views sinds 30-01-2008

Acties:
  • 0 Henk 'm!

  • CyBeR
  • Registratie: September 2001
  • Niet online

CyBeR

💩

Taal: Perl
Doel: simpele perl -e irc bot, oneliner dus ;)


perl -MIO::Socket -e '$sock=IO::Socket::INET->new("phoenix.uzaynet.nl:6667")||die "error"; print $sock "USER cyber cyber cyber :cyber\r\n"; print $sock "NICK Oneliner\r\n"; while ($line = <$sock>){ chomp $line; $line =~ s/\r$//; print "$line\n"; if ($line =~ /^PING (:.*)/){ print $sock "PONG $1\r\n"; } elsif ($line =~ /:.* PRIVMSG ([^\s]+) :ol: say (.*)/){ print $sock "PRIVMSG $1 :$2\r\n"; } elsif ($line =~ /:.* PRIVMSG ([^\s]+) :ol: me (.*)/){ &action($2, $1); } elsif ($line =~ /:.* 004 .*/){ &join("#botfu"); } } sub action{ my ($action, $chan) = @_; printf $sock ("PRIVMSG $chan :\x01ACTION $action\x01\r\n"); } sub join{ my ($channel) = @_; print $sock "JOIN $channel\r\n"; }'

[edit]
code tags maar weg gehaald
layout ging helemaal b0rk >:)

All my posts are provided as-is. They come with NO WARRANTY at all.


Acties:
  • 0 Henk 'm!

Verwijderd

Taal: C/C++
Beschrijving: Tja .. had het nodig om een byte op een databus te zetten.

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
char Mask;
char Buffer = 0x1A;

for ( Mask = 0x80; Mask != 0; Mask >>= 1)
{
   if ( Mask & Buffer)
   {
    // bit = 1
   }
   else
   {
    // bit = 0
   }
}

Acties:
  • 0 Henk 'm!

  • Mart!
  • Registratie: Februari 2000
  • Laatst online: 28-09 08:51
Taal: Visual Basic (ook te gebruiken in ASP na een paar aanpassingen)
Doel: connect met Unreal Tournament Server via Webadmin poort om een level te restarten (GET actie) of Deck16][ te starten (POST actie), gebruik makende van automatische authenticatie (hier u/p Admin/Admin)
Opmerkingen:
- Maakt gebruik van WinHTTP5.0 component, deze dus toevoegen aan je references
- code opslaan als filenaam.frm en vervolgens dubbelklikken om het als nieuw project te openen
- Om te bouwen om content van websites af te rippen >:)
- command2 -> restart current level
command3 -> load Deck16][
text1 -> bevat teruggekregen HTML
text2 -> bevat teruggekregen status
UTServerIP -> Constante met IP en poort van UT webadmin
- Als je dit gebruikt voor een UT Admin tool, laat het me dan ff weten, kunnen we er misschien samen aan werken
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
VERSION 5.00
Begin VB.Form frmMain 
   Caption     =   "Form1"
   ClientHeight    =   7725
   ClientLeft   =   60
   ClientTop     =   345
   ClientWidth     =   8835
   LinkTopic     =   "Form1"
   ScaleHeight     =   7725
   ScaleWidth   =   8835
   StartUpPosition =   3  'Windows Default
   Begin VB.CommandButton Command3 
    Caption    =   "LoadLevel"
    Height      =   375
    Left        =   4080
    TabIndex      =   3
    Top      =   7320
    Width        =   1695
   End
   Begin VB.CommandButton Command2 
    Caption    =   "Restart"
    Height      =   375
    Left        =   2400
    TabIndex      =   2
    Top      =   7320
    Width        =   1575
   End
   Begin VB.TextBox Text2 
    Height      =   495
    Left        =   0
    TabIndex      =   1
    Top      =   6480
    Width        =   8775
   End
   Begin VB.TextBox Text1 
    Height      =   6375
    Left        =   0
    MultiLine    =   -1  'True
    TabIndex      =   0
    Top      =   0
    Width        =   8775
   End
End
Attribute VB_Name = "frmMain"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Const UTServerIP = "10.1.1.10:8080"

Dim WinHttpReq As WinHttp.WinHttpRequest
Const HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0
Const HTTPREQUEST_SETCREDENTIALS_FOR_PROXY = 1

Private Sub Form_Load()
    'Create an instance of the WinHttpRequest object.
    Set WinHttpReq = New WinHttpRequest
End Sub

Private Sub Command2_Click()
    WinHttpReq.Open "GET", _
    "http://" & UTServerIP & "/ServerAdmin/current_restart", False
    WinHttpReq.SetCredentials "Admin", "Admin", _
    HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
    WinHttpReq.Send
    Text2.Text = WinHttpReq.Status & " " & _
    WinHttpReq.StatusText
    Text1.Text = WinHttpReq.GetAllResponseHeaders & "  " & _
    WinHttpReq.ResponseText
End Sub

Private Sub Command3_Click()
    WinHttpReq.Open "POST", "http://" & _
    UTServerIP & "/ServerAdmin/current_game", False
    WinHttpReq.SetCredentials "Admin", "Admin", 
    HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
    WinHttpReq.SetRequestHeader "content-length", ""
    WinHttpReq.SetRequestHeader "content-type", _ 
    "application/x-www-form-urlencoded"
    WinHttpReq.Send "GameTypeSelect=BotPack.DeathMatchPlus" & _
    "&MapSelect=DM-Deck16][.unr&SwitchGameTypeAndMap=Switch"
    Text2.Text = WinHttpReq.Status & " " & _
    WinHttpReq.StatusText
    Text1.Text = WinHttpReq.GetAllResponseHeaders & "  " & _
    WinHttpReq.ResponseText
End Sub

Acties:
  • 0 Henk 'm!

Verwijderd

Op donderdag 06 december 2001 13:21 schreef dynom het volgende:
Ik weet onder de mysql shell geen optie om alle tables te laten zien, en om overal phpMyAdmin te gaan installen schiet ook niet echt op als ik alleen deze functie mis, dus heb ik een scripje gemaakt wat alle tables uit een database laat zien. met een optionele DROP functie.
Gewoon "show tables".
Lekker simpel he?

Acties:
  • 0 Henk 'm!

  • D2k
  • Registratie: Januari 2001
  • Laatst online: 22-09 14:35

D2k

Op dinsdag 11 december 2001 14:35 schreef cruesli het volgende:
Gewoon "show tables".
Lekker simpel he?
pssssssssssst
Op maandag 10 december 2001 16:55 schreef RdeTuinman het volgende:
AUB opmerking hier: [topic=342482/1/25]
:)

Doet iets met Cloud (MS/IBM)


Acties:
  • 0 Henk 'm!

  • mauriceb
  • Registratie: Maart 2001
  • Laatst online: 07-09 21:54
Taal: VBA
Doel: Mijn leven gemakkelijker maken.

Ik ben eens ooit tegen een internetsite gesurft.

Acties:
  • 0 Henk 'm!

  • BierPul
  • Registratie: Juni 2001
  • Laatst online: 19-09 21:49

BierPul

2 koffie graag

maak 1 db met 2 velden

id || thumb_path || full_path

trap die helemaal vol met paden naar plaatjes

verander de var in dit script ff layout modden en banzai >:)

Taal: PHP
Doel: Gallery script in samen werking met het thumbnail script van hierboven "deadly combination" :)
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?
MySQL_CONNECT($hostname,$username,$password) or DIE("#55 de database is slapies aan het doen zzzzzzzz");
mysql_select_db($dbName) or DIE("#50 Sorry jongens er gaat iets fout");

$tabel = "de tabel naam met de plaatjes";

echo "<table align=\"center\" width=\"100%\"><tr>";
    if (empty($perpage)) $perpage = 15; //Hoeveel max op een pagina
    if (empty($pperpage)) $pperpage = 5;    
    if (empty($sort)) $sort = "desc";
    if (empty($offset)) $offset = 0;
    if (empty($poffset)) $poffset = 0;
    $amount = mysql_query("SELECT count(*) FROM $tabel");
    $amount_array = mysql_fetch_array($amount);
    $pages = ceil($amount_array["0"] / $perpage);
    $actpage = ($offset+$perpage)/$perpage;
    $maxoffset = ($pages-1)*$perpage;
    $maxpoffset = $pages-$pperpage;
    $middlepage=($pperpage-1)/2;
    if ($maxpoffset<0) {$maxpoffset=0;}
    echo "<td>\n<center>";
    if ($pages) {  // alleen wanneer $pages>0

        echo "$ad_pages\n";
    if ($offset) {
            $noffset=$offset-$perpage;
            $npoffset = $noffset/$perpage-$middlepage;
        if ($npoffset<0) {$npoffset=0;}
            if ($npoffset>$maxpoffset) {$npoffset = $maxpoffset;}
        echo "<a href=\"$PHP_SELF?offset=0&amp;poffset=0\"><<</a> ";
        echo "<a href=\"$PHP_SELF?offset=$noffset&amp;poffset=$npoffset\"><</a> ";
        }
        for($i = $poffset; $i< $poffset+$pperpage &amp;&amp; $i < $pages; $i++) {
        $noffset = $i * $perpage;
            $npoffset = $noffset/$perpage-$middlepage;
            if ($npoffset<0) {$npoffset = 0;}
            if ($npoffset>$maxpoffset) {$npoffset = $maxpoffset;}
        $actual = $i + 1;
            if ($actual==$actpage) {
         echo "| <b>$actual</b> | ";
            } else {
         echo "| <a href=\"$PHP_SELF?offset=$noffset&amp;poffset=$npoffset\">$actual</a> | ";
        }
    }
    if ($offset+$perpage<$amount_array["0"]) {
            $noffset=$offset+$perpage;
            $npoffset = $noffset/$perpage-$middlepage;
            if ($npoffset<0) {$npoffset=0;}
            if ($npoffset>$maxpoffset) {$npoffset = $maxpoffset;}
        echo "<a href=\"$PHP_SELF?offset=$noffset&amp;poffset=$npoffset\">></a> ";
        echo "<a href=\"$PHP_SELF?offset=$maxoffset&amp;poffset=$maxpoffset\">>></a> ";
        }
    }
    echo "</center></td></tr>\n";
    echo "</table>\n";


$thumbnail_query = mysql_query("SELECT id, thumb_path FROM $table ORDER BY id DESC LIMIT $offset,$perpage") or die (mysql_error());

$i = 1;
echo "<table border=0 cellpadding=5 cellspacing=4><tr>"; 
while ($thumb = mysql_fetch_array($thumbnail_query)) {
    
    echo "<td align='center'><a href='popimage.php?pic_id=$thumb[id]' target='_blank'>[img]'$thumb[thumb_path]'[/img]</a></td>\n";
if ($i%4 == 0)//aantal rijen {              
  echo "</tr>\n<tr>\n";          
}            
    $i++;
  }
echo "</tr></table>";
?>

Ja man


Acties:
  • 0 Henk 'm!

  • 4of9
  • Registratie: Maart 2000
  • Laatst online: 13-12-2024
Taal: VBscript (serverside)
Doel: Parse Time van een pagina
code:
1
2
3
4
5
6
7
8
9
10
11
bovenaan de pagina:
<%
Dim parseTime
parseTime = TIMER
%>
onderaan de pagina:
<%
If parseTime <> "" then
Response.Write "Parsed in:" & (TIMER - parseTime) & "seconds" 
End If
%>

Aspirant Got Pappa Lid | De toekomst is niet meer wat het geweest is...


Acties:
  • 0 Henk 'm!

Verwijderd

Taal: ASP
Doel: Niet echt schokkend, wel veel gebruikt; soort uitgebreide Server.HTMLEncode:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
' Encode alphanumeric characters from ISO set with HTML codes - 3-7-2001 Mark Volmer
Function ISO2HTML(strSomeString)
    Dim i

    'Create & Fill Dictionary with ISO characters as keys and their codes as values
    Set charDict = CreateObject("Scripting.Dictionary")


    charDict.Add "!", "!"
    charDict.Add """", """
    charDict.Add "#", "#"
    charDict.Add "$", "$"
    charDict.Add "%", "%"
    charDict.Add "&", "&"
    charDict.Add "'", "'"
    charDict.Add "(", "("
    charDict.Add ")", ")"
    charDict.Add "*", "*"
    charDict.Add "+", "+"
    charDict.Add ",", ","
    charDict.Add "-", "-"
    charDict.Add ".", "."
    charDict.Add "/", "/"
    charDict.Add ":", ":"
    charDict.Add ";", ";"
    charDict.Add "<", "<"
    charDict.Add "=", "="
    charDict.Add ">", ">"
    charDict.Add "?", "?"
    charDict.Add "@", "@"
    charDict.Add "[", "["
    charDict.Add "\", "\"
    charDict.Add "]", "]"
    charDict.Add "^", "^"
    charDict.Add "_", "_"
    charDict.Add "`", "`"
    charDict.Add "{", "{"
    charDict.Add "|", "|"
    charDict.Add "}", "}"

    'Loop through Dictionary
    strcharDictKey = charDict.Keys
    For i = 0 To charDict.Count - 1
        key = strcharDictKey(i) 
        value = charDict.Item(strcharDictKey(i)) 
        strSomeString = Replace(strSomeString, key, value)
    Next
    ISO2HTML = strSomeString
End Function

Acties:
  • 0 Henk 'm!

Verwijderd

Ok dan zal ik hier ook maar eens wat leuks posten

xSimple Login Script v1.01 by Xtentic(*ChandlerFOK*)

... were one of a kind ...

// filename --> login.include.php
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?
 

/* 

+-+-------------------------------------+-+ 
|#| xEasy Login System v1.01 by Xtentic |#| 
|#|       http://www.xtentic.com        |#| 
|#+-------------------------------------+#| 
|#| Hi, welcome to my xEasyLogin script |#| 
|#|  this script uses only cookies but  |#| 
|#| but can easyly be converted to the  |#| 
|#| use of sessions (maby i do that in  |#| 
|#|         the Future or so)..         |#| 
|#|                ----                 |#| 
|#|CheckThizOUt!.                       |#| 
|#|                ----                 |#| 
|#|  You can change the name of your    |#| 
|#| cookie! it's now 'xAdmin' but pls   |#| 
|#| change this to your own, cauze it   |#| 
|#|  may else use a cookie of someone   |#| 
|#|            else or so!.             |#| 
|#|                ----                 |#| 
|#| Enjoy and don't forget to credit ME |#| 
|#|        X-T-E-N-T-I-C.C-O-M          |#| 
+-+-------------------------------------+-+ 

Enjoy and don't forget to credit ME! 

*/ 

function checkCookie() { 
    global $prog, $xEasyAdmin; 
    global $HTTP_SERVER_VARS; 

    if ($xEasyAdmin == $prog[validate]) {                     // cookie is set! 
        return true; 
    }else{ 
        return; 
    } 
} 

function makeCookie($days) { 
    global $prog, $xEasyAdmin; 
    setcookie("xEasyAdmin", $prog[validate], time() + (3600 * $days)); 
} 

function removeCookie() { 
    global $prog, $xEasyAdmin; 
    setcookie("xEasyAdmin", "0", time() - 3600); 
} 

function showLoginDenied() { 
    // echo "Sorry your login was unsuccessfull please try again...<br>\r\n";"; 
    // echo "<a href=\"login.php\">Login here</a>\r\n"; 
    header("location: login.php"); 
} 


function showLogin() { 
    global $prog; 

    echo "<h1>" . $prog[title] . "</h1>\r\n"; 
    echo "<form action=\"$prog[program]\" method=\"post\"><table width=\"500\" bgcolor=\"#ccccff\">\r\n"; 
    echo "<tr bgcolor=\"#ffffff\"><td>Username</td><td><input type=\"text\" size=\"25\" name=\"xAdminName\"></td></tr>\r\n"; 
    echo "<tr bgcolor=\"#ffffff\"><td>Password</td><td><input type=\"password\" size=\"25\" name=\"xAdminPass\"></td></tr>\r\n"; 
    echo "<tr bgcolor=\"#ffffff\"><td><input type=\"submit\" name=\"xAdminSubmit\" value=\"Submit\"></td></tr>\r\n"; 
    echo "</table></form>\r\n"; 
} 

function showLogout() { 
    global $prog; 

    echo "<h1>" . $prog[title] . "</h1>\r\n"; 
    echo "<form action=\"$prog[program]\" method=\"post\"><table width=\"500\" bgcolor=\"#ccccff\">\r\n"; 
    echo "<tr bgcolor=\"#ffffff\"><td><input type=\"submit\" name=\"xAdminSubmit\" value=\"Logout\"></td></tr>\r\n"; 
    echo "</table></form>\r\n"; 
} 

function checkLogin() { 
    global $prog, $xAdminName, $xAdminPass; 

    if ($prog[username] == $xAdminName &amp;&amp; $prog[password] == $xAdminPass) { 
        return true;                      // login successfull 
    } 
} 


$prog[username] = "admin"; 
$prog[password] = "qwerty"; 
$prog[title] = "xEasyLogin v1.0 by ChandlerFOK"; 
$prog[validate] = "xEasyLoginCookie"; 

?> 
?>

// filename --> login.php
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?
 

include("login.include.php"); 

if (checkcookie()) { 
   echo "<strong>Yes</strong> you have logged in!..\r\n<a href=\"main.php\">main</a>"; 
   showLogout(); 
}elseif ($xAdminSubmit == "Submit") { 
   if (checkLogin()) { 
       makeCookie(1); 
       header("location: main.php"); 
   }else{ 
       header("location: main.php"); 
   } 
}else{ 
   showLogin(); 
} 


?> 
?>

// filename --> main.php :+
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?
 

include("login.include.php"); 

if ($xAdminSubmit == "Logout") { 
   removeCookie(); 
   header("location: login.php"); 
}elseif (checkcookie()) { 
   echo "<strong>Yes</strong> you have logged in!..\r\n"; 
   showLogout(); 
}else{ 
   showLoginDenied(); 
} 

?> 
?>

[wasigh style]
schopje?
[/wasigh style]

Acties:
  • 0 Henk 'm!

  • johnwoo
  • Registratie: Oktober 1999
  • Laatst online: 10:35

johnwoo

3S-GTE

Taal: VB
Doel: eigen Replace() functie, handig in VB5 en eerder
Code:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Public Function MyReplace(ByVal Haystack As String, _
                  ByVal Needle As String, _
                  ByVal ReplaceWith As String) As String
    ' Replaces all occurences of Needle in Haystack with ReplaceWith.
    Dim Pos As Integer, _
      Start As Integer, _
      NeedleLen As Integer, _
      ReplaceLen As Integer
    
    NeedleLen = Len(Needle)
    ReplaceLen = Len(ReplaceWith)
    Pos = InStr(Haystack, Needle)
    While Pos
      Haystack = Left$(Haystack, Pos - 1) _
        & ReplaceWith _
        & Mid$(Haystack, Pos + NeedleLen)
      Pos = InStr(Pos + ReplaceLen, Haystack, Needle)
    Wend
    MyReplace = Haystack
End Function

4200Wp ZO + 840Wp ZW + 1680Wp NW | 14xIQ7+ + 1xDS3-L | MTVenusE | HWP1


Acties:
  • 0 Henk 'm!

  • drZymo
  • Registratie: Augustus 2000
  • Laatst online: 15-09 08:44
Simpel maar effectief. Het zou je computer moeten afsluiten, maar om een of andere reden reboot ie alleen. :P
code:
1
2
3
4
5
6
7
8
9
10
11
12
[bits 16]
[org 0x100]

;shuts down ATX power :P
mov dx, 0x0CF9

mov al, 0xFE
out dx, al
mov al, 0xFF
out dx, al

ret

Ooh ja taal = NASM

"There are three stages in scientific discovery: first, people deny that it is true; then they deny that it is important; finally they credit the wrong person."


  • KoeKk
  • Registratie: September 2000
  • Laatst online: 18-09 18:41
taal = ASP
doel = tijd berekenen die erover gedaan wordt om de pagina te parsen

Starten van de timer aan het begin v/d pagina, functie, whatever
code:
1
2
  'A time counter
  TimeStart = Timer

Het berekenen van de genomen tijd...
code:
1
2
3
4
strTimer = "<span class=""small"">" &_ 
         Round((Timestart- Timer) * -1, 3) &_
         " seconden naar gezocht</span>"
Response.Write strTimer

Round werkt simpel, als je meer als 3 getallen achter de comma wilt vervang je de 3 door iets anders ;)
Deze timer plaats ik meestal in development versies van een website in de header & footer...

Acties:
  • 0 Henk 'm!

  • klokop
  • Registratie: Juli 2001
  • Laatst online: 22-09 10:26

klokop

swiekie swoeng

taal: php
doel: eerste letter hoofdletter
code:
1
2
3
4
5
function MakeUpper($input) {
        $l = substr($input,0,1);
        $old_string = substr($input,1,strlen($input));
        $new_string = strtoupper($l).$old_string;
        return $new_string;}

bijv. MakeUpper("apeldoorn") -> "Apeldoorn"
Hadden we daar ucfirst() niet voor? (en ucwords())

"Passing silhouettes of strange illuminated mannequins"


Acties:
  • 0 Henk 'm!

  • Clay
  • Registratie: Oktober 1999
  • Laatst online: 20-08 09:22

Clay

cookie erbij?

  • javascript form hulpje
  • alternatieve "anders namelijk" voor dropdowns.
  • geen input ernaast meer nodig
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function addAnders(obj) {   
   if(obj.selectedIndex != obj.length-1) return;    
   anders = prompt('geef wat anders op dan: ','');
   if(!anders) {
    // prompt cancel gedrukt
    obj.selectedIndex = 0;
    return;
   }
    
   // nieuwe options
   obj[obj.length-1] = new Option(anders, anders);
   obj[obj.length] = new Option('anders namelijk ...');
    
   // nieuwe selecten
   obj.selectedIndex = obj.length -2
}


met:

<select name="ikwil" onchange="addAnders(this)">
   <option value="drank"> drank
   <option value="eten"> eten
   <option value="peuken"> peuken
   <option value="eene"> anders namelijk ...
</select>

Instagram | Flickr | "Let my music become battle cries" - Frédéric Chopin


Acties:
  • 0 Henk 'm!

  • pim
  • Registratie: Juli 2001
  • Laatst online: 28-09 15:33

pim

Misschien dat jullie hier iets aan hebben, of is dit te simpel? Ik gebruik het zelf regelmatig. wat stukjes code die ik heb opgeslagen in een tekstbestandje..

-----------------------------------------------------------
Taal: PERL
Doel: Een formulier wat met method=get verstuurd is opvangen

#Method=GET opvangen
print "Content-type: text/html\n\n";
$buffer = $ENV{'QUERY_STRING'};
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
($name,$value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$value =~ s/~!/ ~!/g;
$in{$name} = $value;
}
$voorbeeld = $in{'voorbeeld'};
-----------------------------------------------------------
Taal: PERL
Doel: Een formulier wat met method=post verstuurd is opvangen

#Method=POST opvangen

print "Content-type: text/html\n\n";
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$voorbeeld=$FORM{'voorbeeld'};
-----------------------------------------------------------
Taal: PERL
Doel: Formuliertje versturen via Perl met method=POST

print "Content-type: text/html\n\n";
use HTTP::Request::Common qw/POST/;
use LWP::UserAgent;
$ua = LWP::UserAgent->new();
my $req = POST 'http://www.homepage.com/cgi-bin/bla/bla.pl',
[ onderwerp => "testonderwerp",
value2name => "value2",
value3name => "value3" ];
$results = $ua->request($req)->as_string;
-----------------------------------------------------------
Taal: PERL
Doel: HTML mailtje versturen via je je SENDMAIL

$mailp="/usr/sbin/sendmail";
open(MAIL,"|$mailp -t");
print MAIL "To: $aanemail\n";
print MAIL "From: $afzenderemail\n";
print MAIL "Subject: $onderwerp\n";
print MAIL "MIME-Version: 1.0\n";
print MAIL "Content-Transfer-Encoding: 7bit\n";
print MAIL "Content-Disposition: inline;\n";
print MAIL "Content-Type: text/html; charset=us-ascii\n\n";
print MAIL "<font face=arial size=2>$berichtje</font>\n";
print MAIL "\<br\>\n";
close (MAIL);
-----------------------------------------------------------
Taal: PERL
Doel: content rippen

#!/usr/bin/perl
print "Content-type: text/html\n\n";
#het bestand waaruit gegrabbed word.
use LWP::Simple;
$file=get("http://www.google.com");
#tekens tellen in gegrabde bestand t/m <form
$tekens_tot_begin=index($file, "<form", $tekens_tot_begin);
#tekens tellen in gegrabde bestand t/m </form>> vanaf <form
$tekens_tot_eind=index($file, "</form>", $tekens_tot_begin);
#Hoeveel tekens van <form> t/m </form>
$lengte=$tekens_tot_eind - $tekens_tot_begin;
#Vanaf start het verschil in tekens gaan grabben + 7 tekens om </form> er nog bij te krijgen.
$grab=substr($file, $tekens_tot_begin, $lengte + 7);
# gegrabte stuk weergeven:
print $grab;
-----------------------------------------------------------
Taal: PERL
Doel: Een random getal afronden

$getal = rand(100);
$getal++;
$getal = int($getal);
print $getal;
-----------------------------------------------------------
Taal: PERL
Doel: checken of een string een woord bevat.

$_ = "het is weer laat";
if (/laat/){
print "de string bevat het woord \"laat\"";
}else{
print "de string bevat NIET het woord \"laat\"";
}

Acties:
  • 0 Henk 'm!

  • crisp
  • Registratie: Februari 2000
  • Laatst online: 12:36

crisp

Devver

Pixelated

Taal: PHP
Doel: Visitor counter
Code:
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?
#############################################
#                             #
#       Crisp's first PHP counter       #
#                             #
#  www.crisp.demon.nl  tino@crisp.demon.nl  #
#                             #
#############################################

###############################################################################################
#
# Since I couldn't find a counter that suited all my needs, and since I knew nothing about PHP
# I just took the best parts of all counters I could find and made my own.
#
###############################################################################################
#
#  version 1.0  December 24, 2001
#
###############################################################################################

###############################################################################################
# Set all the variables here
###############################################################################################

$path = "../pictures/";             # Path to the image file
$image = "digits.jpg";      # Destination of the file in $path
$maxlength = 5;           # Maximum number of digits
$leading_zeros = true;      # include leading zero's up to the maximum length, or surpress

###############################################################################################
# Don't change below this line unless you don't know what you're doing either ;-)
###############################################################################################

# start a new session or restore original session
session_start();

# Get contents of counter file
$thefile = file("count.txt");
$count = implode("", $thefile);

# Check if we have a registered var called "id"; if we have it this is
# a continuation of a previous session, so we don't add to the count
# else we register the var to prevent adding to the count next time.
if (!session_is_registered("id")) {

  $id = 1;
  session_register ("id");

# add 1 to the count and store it
  $count++;
  $myfile = fopen("count.txt","w");
  fputs($myfile,$count);
  fclose($myfile);

}

# determine the number of digits
$length = strlen($count); 

if ($digits < 1) { 
    $digits = $length;
}
if ($digits > $maxlength) {
    $digits = $maxlength;
}

$count = sprintf("%0".$digits."s",$count);
$count = substr("$count", -$digits);

# get the sample file
if (file_exists("$path/$pix.jpg")) {
      $image="$pix.jpg"; 
}

# create the new image
$output_image = ImageCreateFromJPEG("$path/$image");
$output_imag_x = ImageSX($output_image);
$output_imag_y = ImageSY($output_image);
$cutter = $output_imag_x/10;
if ($leading_zeros) $output_x = $cutter*$maxlength;
else $output_x = $cutter*$digits;
$output = ImageCreate($output_x, $output_imag_y);

$offset = 0;

# leading zero's?
if ($leading_zeros) {

  $counter = $maxlength;

  while ($counter > $digits) {
    $c = "0";
    $x = $offset*$cutter;
    $y = $c*$cutter;
    ImageCopyResized($output, $output_image, $x, 0, $y, 0, $cutter, $output_imag_y, $cutter, $output_imag_y); 
    $offset++;
    $counter--;
  }

}

$counter = 0;

while ($counter < $digits) {
    $c = substr("$count", $counter, 1);
    $x = $offset*$cutter;
    $y = $c*$cutter;
    ImageCopyResized($output, $output_image, $x, 0, $y, 0, $cutter, $output_imag_y, $cutter, $output_imag_y); 
    $offset++;
    $counter++;
}

Header("Content-type: image/jpeg");
ImageJPEG($output);
ImageDestroy($output);
?>

Ik gebruik dit plaatje voor de digits, maar dat kan een willekeurig ander plaatje zijn:

Afbeeldingslocatie: http://www.toonwildeboer.com/pictures/digits.jpg

Includen in je HTML:
code:
1
[img]"counter.php"[/img]

Intentionally left blank


Acties:
  • 0 Henk 'm!

  • 845
  • Registratie: September 2001
  • Laatst online: 06:54

845

Ik heb vorig jaar voor school een keer een imagionair rekenmachine geschreven, zeker voor elektro is ie heel makkelijk

Taal: C
platform: Dos (waarschijnlijk doet ie het ook op de rest, maar dat is C :))
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/*Bas Breijer 24-09-2001  Imagionaire Rekenmachine t.b.v. Elektrotechniek*/

#include <stdio.h>
#include <conio.h>
#include <math.h>

struct compl
{
    float a,b,arg,mod;
};


struct compl invoer (int*);
struct compl optel (struct compl, struct compl);
struct compl verm (struct compl, struct compl);
struct compl delen (struct compl, struct compl);
struct compl aftrekken (struct compl,struct compl);
void rnp (struct compl *);
void pnr (struct compl *);
void hoek (struct compl *);

main ()
{
    int menu=0, inv=0, opt=0, ver=0, dele=0, aftr=0, aantal;
   struct compl cget1,cget2,som,prod,quot,versch;

   do
   {
    clrscr();
       printf("\n\n\tComplexe Rekenmachine\n");
    printf("\n\t\t\t1. Invoer\n");
    if (inv!=0)
    {
        printf("\t\t\t-Getal 1(cartesiaans):\t\t%.2f + %.2f.j\n", cget1.a,cget1.b);
       printf("\t\t\t-Getal 1(polair):     \t\t%.2f / %.2f\n",cget1.mod,cget1.arg);
       printf("\t\t\t-Getal 2(cartesiaans):\t\t%.2f + %.2f.j\n", cget2.a,cget2.b);
       printf("\t\t\t-Getal 2(polair):     \t\t%.2f / %.2f\n",cget2.mod,cget2.arg);
    };
    printf("\t\t\t2. Optellen\n");
    if (opt!=0)
    {
        printf("\t\t\t-Getal 1 + Getal 2(cartesiaans):%.2f + %.2f.j\n", som.a,som.b);
       printf("\t\t\t-Getal 1 + Getal 2(polair):     %.2f / %.2f\n",som.mod,som.arg);
    };
    printf("\t\t\t3. Vermenigvuldigen\n");
    if (ver!=0)
    {
        printf("\t\t\t-Getal 1 * Getal 2(cartesiaans):%.2f + %.2f.j\n", prod.a,prod.b);
       printf("\t\t\t-Getal 1 * Getal 2(polair):     %.2f / %.2f\n",prod.mod,prod.arg);
    };
    printf("\t\t\t4. Delen\n");
    if (dele==1)
    {
        printf("\t\t\t-Getal 1 / Getal 2(cartesiaans):%.2f + %.2f.j\n", quot.a,quot.b);
       printf("\t\t\t-Getal 1 / Getal 2(polair):     %.2f / %.2f\n",quot.mod,quot.arg);
    }else if (dele==2)
    {
        printf("\t\t\t-Het MOD gedeelte van Getal 2 is 0, delen gaat dus niet\n");
    };
    printf("\t\t\t5. Aftrekken\n");
    if (aftr!=0)
    {
        printf("\t\t\t-Getal 1 - Getal 2(cartesiaans):%.2f + %.2f.j\n", versch.a,versch.b);
       printf("\t\t\t-Getal 1 - Getal 2(polair):     %.2f / %.2f\n",versch.mod,versch.arg);
    }
    printf("\t\t\t6. Stoppen\n");
    scanf("%d", &menu);
    switch (menu)
    {
        case 1:
            aantal=1;
                   cget1=invoer(&aantal);
            if (aantal==3)
            {
               inv=0;
                break;
            }
            aantal=2;
            cget2=invoer(&aantal);
            if (aantal==3)
            {
               inv=0;
                break;
            }
            inv=1;
            opt=0;
            ver=0;
            dele=0;
            aftr=0;
            break;
       case 2:
                   som=optel(cget1,cget2);
            opt=1;
            break;
       case 3:
                   prod=verm(cget1,cget2);
            ver=1;
            break;
       case 4:
            if (cget2.mod!=0)
            {
                   quot=delen(cget1,cget2);
            dele=1;
            }else
            {
            dele=2;
            };
                   break;
       case 5:
                   versch=aftrekken(cget1,cget2);
            aftr=1;
            break;
    };
   }while (menu!=6);
   return 0;
}

struct compl invoer (int *aant)
{
    struct compl temp;
   int menu=0;

   clrscr();
   printf("Getal %d", *aant);
      printf("\n\n\t\t\tWilt U een getal invoeren invoer in:");
   printf("\n\t\t\t\t1. Cartesiaanse notatie (A+B.j).");
   printf("\n\t\t\t\t2. Polaire notatie (mod / arg).");
   printf("\n\t\t\t\t3. Terug naar het hoofdmenu.\n");
   do
   {
   scanf("%d", &menu);
   }while (menu<1 && menu>3);
     switch (menu)
      {
       case 1:
                      printf("\nGeef het A gedeelte van het getal.\n");
                     scanf("%f", &temp.a);
                     printf("\nGeef het B gedeelte van het getal.\n");
                     scanf("%f", &temp.b);
                rnp (&temp);
           break;
          case 2:
                     printf("\nGeef het MOD gedeelte van het getal.\n");
                scanf("%f", &temp.mod);
                printf("\nGeef het ARG gedeelte van het getal in graden.\n");
                scanf("%f", &temp.arg);
                pnr (&temp);
           break;
    case 3:
                    *aant=3;
           break;
   }
   return temp;
}

void rnp (struct compl *pntemp)
{
    if (pntemp->a==0)
    {
        if (pntemp->b>0)
       {
           pntemp->arg=90;
       };
       if (pntemp->b<0)
       {
           pntemp->arg=270;
       };
    }else
    {
        pntemp->arg=(180/M_PI)*atan2(pntemp->b, pntemp->a);
    }
    pntemp->mod=sqrt(pow(pntemp->a,2)+pow(pntemp->b,2));
   hoek (pntemp);
    return;
}

void pnr (struct compl *pntemp)
{
    if (pntemp->mod==0)
   {
         pntemp->a=0;
         pntemp->b=0;
    pntemp->arg=0;
   }else
   {
    pntemp->a=pntemp->mod*cos(pntemp->arg*M_PI/180);
    pntemp->b=pntemp->mod*sin(pntemp->arg*M_PI/180);
   };
   hoek (pntemp);
   return;
}

void hoek (struct compl *pntemp2)
{
    while (pntemp2->arg>=360)
   {
    pntemp2->arg=pntemp2->arg-360;
   }
   while (pntemp2->arg<0)
   {
         pntemp2->arg=360+pntemp2->arg;
   }
   return;
}

struct compl optel (struct compl tempcget1, struct compl tempcget2)
{
    struct compl temp;

   temp.a=tempcget1.a+tempcget2.a;
   temp.b=tempcget1.b+tempcget2.b;
   rnp (&temp);
   return temp;
}

struct compl verm (struct compl tempcget1, struct compl tempcget2)
{
    struct compl temp;

   temp.mod=tempcget1.mod*tempcget2.mod;
   temp.arg=tempcget1.arg+tempcget2.arg;
   pnr (&temp);
   return temp;
}

struct compl delen (struct compl tempcget1, struct compl tempcget2)
{
    struct compl temp;

   temp.mod=tempcget1.mod/tempcget2.mod;
   temp.arg=tempcget1.arg-tempcget2.arg;
   pnr (&temp);
   return temp;
}

struct compl aftrekken (struct compl tempcget1,struct compl tempcget2)
{
    struct compl temp;

   temp.a=tempcget1.a-tempcget2.a;
   temp.b=tempcget1.b-tempcget2.b;
   rnp (&temp);
   return temp;
}

Acties:
  • 0 Henk 'm!

  • D2k
  • Registratie: Januari 2001
  • Laatst online: 22-09 14:35

D2k

ach ik ben in een goede bui
uit de reeks icon topics een ip lock script
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?
// je hebt een tabel log met daarin tijd en ip (kan je varchars van maken)
// connect gedoe
$server="localhost";
$user="";
$pass="";
$db="";
mysql_connect ($server, $user, $pass);
mysql_select_db($db);
// selecteer tijd horende bij ip
$result = mysql_query("SELECT tijd FROM log WHERE ip='$REMOTE_ADDR'");
// tijd in s op dit moment vanaf epoc
$nu = date("U");

if (mysql_num_rows($result)) 
{    
 
    $row = mysql_fetch_array ($result);       

    if (($nu + 600) > $row[tijd])  //tijd naar behoeven in te stellen
        {     
        echo "toegang";
        mysql_query("UPDATE log SET tijd='$nu' WHERE ip='$REMOTE_ADDR'");    
    }
else
{
     echo("geen toegang");
}        

}

else 
{    
mysql_query ("INSERT INTO log (tijd, ip) VALUES ('$nu', '$REMOTE_ADDR')");
echo "toegang";
}
?>

Doet iets met Cloud (MS/IBM)


Acties:
  • 0 Henk 'm!

  • rambo-2001
  • Registratie: November 2000
  • Laatst online: 02-01-2024

rambo-2001

be anonymous

taal=VBscript clientside
doel=weergave van alle mogelijke pincodes.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<HTML>
<HEAD><TITLE>pincode</TITLE></HEAD>
<BODY>
<CENTER>
<SCRIPT LANGUAGE="VBSCRIPT">
dim counter1
dim counter2
dim counter3
dim counter4
counter1=0
counter2=0
counter3=0
counter4=0
do while counter4<=10 and counter3<=10 and counter2<=10 and counter1<=9
document.write counter1 & counter2 & counter3 & counter4 & "<BR>"
counter4=counter4+1
if counter4=10 then
counter3=counter3+1
counter4=0
end if
if counter3=10 then
counter2=counter2+1
counter3=0
end if
if counter2=10 then
counter1=counter1+1
counter2=0
end if
loop
</SCRIPT>
</CENTER>
</BODY>
</HTML>

cs skill - making a desert eagle out of tooth picks


Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

Taal: JavaScript
Doel: (IE Only) sim-pel Form Highlight scriptje.
Geeft bij mouseover, of bij selectie van een form element (input, password, textarea) deze een andere kleur. Bij mouseout verandert de kleur weer terug. Makkelijk te aan te passen om ook bijv. button mee te pakken.
te bewonderen o.a. hier

in je <head>
code:
1
<script language="JavaScript" src="formhighlight.js" type="text/javascript"></script>

in je <body>
code:
1
<body onload="InitFormHighlight();">

formhighlight.js:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// universal form element highligting system. written by Jelle Ursem, for NVLF

var focused = '';


function getfocus()
{
    if (this.disabled == false)
    {
         if (focused) 
          {
             var i = 0;
               var j = 0;
                while (j < document.forms.length)
                {
               while (i < document.forms[j].length)
                {
                if (document.forms[j].elements[i].name == focused) 
                {
                 document.forms[j].elements[i].style.backgroundColor='#FFFFFF';
                     document.forms[j].elements[i].style.scrollbarTrackColor='#FFFFFF';
                    }
                    i++;
                 }
                 j++;
              }
          }
    this.style.backgroundColor="EEF7FF";
    this.style.scrollbarTrackColor='#EEF7FF'
    focused = this.name;
    }
 return true;
}


function highlight()
{
 if (this.disabled == false)
 {
  this.style.backgroundColor="EEF7FF";
  this.style.scrollbarTrackColor='#EEF7FF';
 }
 return true;
}

function lightsoff()
{
         if (focused) 
          {
             var i = 0;
               var j = 0;
                while (j < document.forms.length)
                {
               while (i < document.forms[j].length)
                {
                if ((document.forms[j].elements[i].name != focused) && (document.forms[j].elements[i].disabled == false) && ((document.forms[j].elements[i].type == "password") || (document.forms[j].elements[i].type == "text") || (document.forms[j].elements[i].type == "textarea")) )
                {
                    document.forms[j].elements[i].style.backgroundColor='#FFFFFF';
                    document.forms[j].elements[i].style.scrollbarTrackColor='#FFFFFF'; 
                    }
                    i++;
                 }
                 j++;
              }
          }
          else if (this.disabled == false)
          {
          this.style.backgroundColor='#FFFFFF';
          this.style.scrollbarTrackColor='#FFFFFF';
          }
 return true;
}

function InitFormHighlight()
{
    if (navigator.appName == "Microsoft Internet Explorer")
        { 
            var i = 0;
            var j = 0;
                while (j < document.forms.length)
                {
                 while (i < document.forms[j].elements.length)
                {   
                    if ((document.forms[j].elements[i].type == "text") || (document.forms[j].elements[i].type == "password") || (document.forms[j].elements[i].type == "textarea") )
                     {
                        document.forms[j].elements[i].onfocus = getfocus;
                        document.forms[j].elements[i].onmouseover = highlight; 
                        document.forms[j].elements[i].onmouseout = lightsoff;
                        document.forms[j].elements[i].onmousedown = getfocus;  
                     }
                    i++;
                  }
                 j++;
                }
        }
 return true;

}

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

Taal: PHP
Doel: 403 Error Handler
Warning!: Script gaat er van uit dat je zelf je apache 403 configuratie aangepast hebt naar 403.php!
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?
function writetxt($filename, $str) // simpele text schrijf functie
{  
    $fp = fopen($filename, 'a+'); // open bestand
    fwrite($fp, "$str\n"); // stringetje erbij met een linebreak
    fclose($fp); // bestand sluiten

}
    
    if ($REQUEST_URI != '/403.php') // zitten we in verboden gebied?
    {
        writetxt('/home/abso/lute/path/403.txt', "Referer: $REQUEST_URI - IP: $REMOTE_ADDR - Reverse DNS: ". gethostbyaddr($REMOTE_ADDR)." - Time: ".date("j-n-Y G:i:s")); // schrijf dan referer, ip, reverse dns en tijd &amp; datum naar 403.txt
        header('location: http://www.domein.nl/403.php'); // doorsturen naar root voor nette errorhandling (anders zijn je plaatjes vern*%@kt)
    }

    else
    {
    // include hier je templates en geef een nette error weer
    $maintext = 'Er is een fout opgetreden. <br>U bent niet gemachtigd om deze URL op te vragen.<br><br> De webmaster is om veiligheidsredenen op de hoogte gesteld, en zal indien nodig maatregelen nemen.';
    include('include/template.inc.php');
    }
?>

Output:
Referer: /razor/ - IP: 195.***.63.4 - Reverse DNS: 195.***.63.4 - Time: 7-1-2002 15:50:44
Referer: /razor/ - IP: 62.***.19.131 - Reverse DNS: asd-tel-***-***-131.dial.freesurf.nl - Time: 8-1-2002 13:06:16

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

Taal: PHP
Functie: Titel uit variabele halen
Code:
PHP:
1
2
3
4
5
6
7
8
9
<?
function gettitle($var)
{
   if (eregi("<title>(.*)</title>", $text, $out))
    {
      $result = $out[1];
    }
}
?>

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

Taal: PHP
Doel: Word Document, of ander bestand als downoad aanbieden ipv openen.
Gebruiken als: download.php?filename=documentnaam
Waarschuwing!: Gebruiker moet zelf extentie aan bestand geven
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?
if (file_exists($filename.".doc")) // bestaat het bestand?
  {
    $filename = $filename.".doc"; // doc erachter, om geklooi met slimme variabelen te voorkomen
    if (strstr($HTTP_USER_AGENT, "MSIE")) // internet explorer?
      {
        $attachment = ""; // attachment var leeglaten
      }
    else
      {
        $attachment = " attachment;"; // attachment var vullen
      }

    $size = filesize("$filename"); // bestandsgrootte
    $fh = fopen("$filename", "r"); // bestand openen
    // correcte headers sturen
    header("Content-Type: application/octetstream");
    header("Content-Length: $size");
    header("Pragma: no-cache");
    header("Expires: 0");
    header("Content-Disposition:$attachment filename=$doc");
    header("Content-Transfer-Encoding: binary");

    fpassthru($fh); // bestand doorsturen
    exit; // script stoppen
  }
else // bestand bestaat niet
  {
        // Error Handling
    $mailto= "webmaster@domein.nl"; // e-mail adres
    $subject= "Fout bij downloaden bestand vanaf domein"; // subject
    $from= "php@domein.nl"; // afzender
    $message= "Er is een fout opgetreden bij het proberen te downloaden van het volgende bestand:\n
    $filename\n
    De bezoeker kwam van pagina: $HTTP_REFERER\n
    De tijd is nu: ".date("j-n-Y G:i:s")."\n
    Ip nummer van de bezoeker: $REMOTE_ADDR\n
    "; // info mailtje
    mail( "$mailto", "$subject", "$message", "From: $from"); // mailen
        // nette foutmelding aan gebruiker
    $maintext = 'Er is een fout opgetreden.<br><br>Het bestand is niet gevonden, of er was een andere fout tijdens het aanbieden van de download.<br><br>Er is inmiddels een e-mail gestuurd naar de webmaster, die het probleem hoogstwaarschijnlijk binnen 24 uur zal oplossen.<br><br>Onze excuses voor dit ongemak.'));
    include('template.inc.php'); // template includen
  }
?>

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

Verwijderd

Taal: C/C++
Beschrijving: Upper/Lower Case.

code:
1
2
#define UP_CASE(ch)  ((ch) & 223)   
#define LOW_CASE(ch) ((ch) | 32)

Acties:
  • 0 Henk 'm!

Verwijderd

Taal: C/C++
Beschrijving: Runtime Endianness bepalen.


Returned 1 als systeem Little Endian is, 0 als het Big Endian is.
code:
1
2
3
4
5
int little_endian(void)
{
    int iValue = 1;
    return (iValue == *((char*)&iValue));
}

Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

Taal: HTML/JS
Doel: Simpele routeplanner naar jouw adres
Waarschuwing!: Zelf even jouwstraat, jouwhuisnummer en jouw plaats invullen
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Route bepalen naar het me huis:&nbsp; <table border='0' ><tr><td width='100%'><form action='OpenWindow();'><b>Uw postcode:</b></td><td align='right'><input type='text' class='form' name='ZIPCODE'></td>
</tr>
<tr>
<td align='right' colspan='2'>
<hr style='width:100%;'>
<input class='button' type='button' value='bepaal route' onclick='OpenWindow();'></td></tr></table>

</form><script language='javascript'>
function OpenWindow()
{

RouteWindow = window.open('http://www.routenet.nl?main=asp/euroroute/euroadres.asp?viapunten=off&searchtype=1&STREET=&CITY=&ZIPCODE='+document.forms[0].ZIPCODE.value+'&COUNTRY=NL&STREET=jouwstraat+jouwhuisnummer&CITY=jouwstada&ZIPCODE=&COUNTRY=NL','Windowname'); 

}
</script><a href='http://www.routenet.nl'>[img]'http://www.routenet.nl/images/logo_routenet.gif'[/img]
<br><br>
Routeplanner door <a href='http://www.routenet.nl'>Routenet.nl</a>. Alle rechten voorbehouden.

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

  • Mr. B.
  • Registratie: Mei 2000
  • Niet online
Taal: Visual Basic
Platform: Windows NT/2000/XP
Doel: CPU usage uitvragen

In de General-Declarations sectie van je form:
(als je het in een module zet kun "Private" weglaten)
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  Const SystemBasicInformation = 0
  Const SystemPerformanceInformation = 2
  Const SystemTimeInformation = 3
 
  Private Type LARGE_INTEGER
    LowPart As Long
    HighPart As Long
  End Type
 
  Private Type SYSTEM_BASIC_INFORMATION
    dwUnknown1 As Long
    uKeMaximumIncrement As Long
    uPageSize As Long
    uMmNumberOfPhysicalPages As Long
    uMmLowestPhysicalPage As Long
    uMmHighestPhysicalPage As Long
    uAllocationGranularity As Long
    pLowestUserAddress As Long
    pMmHighestUserAddress As Long
    uKeActiveProcessors As Long
    bKeNumberProcessors As Byte
    bUnknown2 As Byte
    wUnknown3 As Integer
  End Type
 
  Private Type SYSTEM_PERFORMANCE_INFORMATION
    liIdleTime As LARGE_INTEGER
    dwSpare(76) As Long
  End Type
 
  Private Type SYSTEM_TIME_INFORMATION
    liKeBootTime As LARGE_INTEGER
    liKeSystemTime As LARGE_INTEGER
    liExpTimeZoneBias As LARGE_INTEGER
    uCurrentTimeZoneId As Long
    dwReserved As Long
  End Type
 
  Private Declare Function NtQuerySystemInformation Lib "NTDLL" (ByVal SystemInformationClass As Long, SystemInformation As Any, ByVal SystemInformationLength As Long, ReturnLength As Long) As Long

De functies zelf:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Private Function Li2Double(x As LARGE_INTEGER) As Double
  Li2Double = (x.HighPart * (2 ^ 32)) + x.LowPart
End Function
 
Private Function GetCPUusageNT() As Long
  Dim SysPerfInfo As SYSTEM_PERFORMANCE_INFORMATION
  Dim SysTimeInfo As SYSTEM_TIME_INFORMATION
  Dim SysBaseInfo As SYSTEM_BASIC_INFORMATION
  Dim dbIdleTime As Double
  Dim dbSystemTime As Double
  Dim Status As Long
 
  On Error Resume Next
 
  Status = NtQuerySystemInformation(SystemBasicInformation, SysBaseInfo, Len(SysBaseInfo), vbNull)
  If Status <> 0 Then Exit Function
 
  Status = NtQuerySystemInformation(SystemTimeInformation, SysTimeInfo, Len(SysTimeInfo), 0)
  If Status <> 0 Then Exit Function
 
  Status = NtQuerySystemInformation(SystemPerformanceInformation, SysPerfInfo, Len(SysPerfInfo), vbNull)
  If Status <> 0 Then Exit Function
 
  If Li2Double(liOldIdleTime) <> 0 Then
    dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime)
    dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime)
 
    dbIdleTime = dbIdleTime / dbSystemTime
 
    dbIdleTime = 100 - ((dbIdleTime * 100) / SysBaseInfo.bKeNumberProcessors)
 
    GetCPUusageNT = Int(dbIdleTime + 0.5)
  End If
 
  liOldIdleTime = SysPerfInfo.liIdleTime
  liOldSystemTime = SysTimeInfo.liKeSystemTime
End Function

Routines om de CPU usage onder Win9x/ME kun je overal op internet vinden (staat gewoon in de registry).

StatBar.nl - @GoT

Het verschil tussen theorie en praktijk is in de praktijk altijd veel groter dan in theorie.


Acties:
  • 0 Henk 'm!

  • Mr. B.
  • Registratie: Mei 2000
  • Niet online
Taal: Visual Basic
Doel: Kijken of een file bestaat
code:
1
2
3
4
5
6
7
8
9
10
11
Function FileExists(FileName As String) As Boolean
  Dim I As Integer

  On Error Resume Next
  I = Len(Dir(FileName, vbReadOnly + vbHidden + vbSystem))
  If Err Or (I = 0) Or (Trim$(FileName) = "") Then
    FileExists = False
  Else
    FileExists = True
  End If
End Function

StatBar.nl - @GoT

Het verschil tussen theorie en praktijk is in de praktijk altijd veel groter dan in theorie.


Acties:
  • 0 Henk 'm!

  • Mr. B.
  • Registratie: Mei 2000
  • Niet online
Taal: Turbo Pascal/Assembly
Doel: Omzetten van een string in hoofd- of kleine letters (TP biedt standaard alleen functies om Chars te upper/lowercasen)
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function HoofdLetters(S: string): string;
begin
  asm
    CLD
    LEA SI,S
    LES DI,@Result
    SEGSS LODSB
    STOSB
    XOR AH,AH
    XCHG AX,CX
    JCXZ @EINDE
    @BEGIN_LUS:
    SEGSS LODSB
    CMP AL,'a'
    JB @GEEN_KLEINE_LETTER
    CMP AL,'z'
    JA @GEEN_KLEINE_LETTER
    SUB AL, 20h
    @GEEN_KLEINE_LETTER:
    STOSB
    LOOP @BEGIN_LUS
    @EINDE:
  end;
end;

function KleineLetters(S: string): string;
begin
  asm
    CLD
    LEA SI,S
    LES DI,@Result
    SEGSS LODSB
    STOSB
    XOR AH,AH
    XCHG AX,CX
    JCXZ @EINDE
    @BEGIN_LUS:
    SEGSS LODSB
    CMP AL,'A'
    JB @GEEN_HOOFD_LETTER
    CMP AL,'Z'
    JA @GEEN_HOOFD_LETTER
    SUB AL, -20h
    @GEEN_HOOFD_LETTER:
    STOSB
    LOOP @BEGIN_LUS
    @EINDE:
  end;
end;

StatBar.nl - @GoT

Het verschil tussen theorie en praktijk is in de praktijk altijd veel groter dan in theorie.


Acties:
  • 0 Henk 'm!

  • jelmervos
  • Registratie: Oktober 2000
  • Niet online

jelmervos

Simple user

Taal: Javascript
Doel: 'Autoaanvullen' voor een combobox via een editbox.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script language="JavaScript">
//<!--
function SearchSelectBox(in_sFormName, in_sInputName, in_sSelectName)
{
  sSearchString = document.forms[in_sFormName].elements[in_sInputName].value.toUpperCase();
  iSearchTextLength = sSearchString.length;
  for (x = 0; x < document.forms[in_sFormName].elements[in_sSelectName].options.length; x++)
  {
    sOptionText = document.forms[in_sFormName].elements[in_sSelectName].options[x].text;
    sOptionComp = sOptionText.substr(0, iSearchTextLength).toUpperCase();
    if(sSearchString == sOptionComp)
    {
    document.forms[in_sFormName].elements[in_sSelectName].selectedIndex = x;
    break;
    }
  }
}
//-->
</script>

"The shell stopped unexpectedly and Explorer.exe was restarted."


Acties:
  • 0 Henk 'm!

Verwijderd

Taal: PHP
Doel: Een pagina navigatie systeem genereren in de vorm
[ « < 2 3 4 5 6 > » ]

Code:
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?
/**
 * @param $curpage De pagina waar men op dit moment is
 * @param $totalpage Het totaal aantal pagina's
 * @param $parseurl De url waar de pagina nummers naar moeten verwijzen, in de vorm "page.php?p=%%" waar %%
 *                  automatisch door het pagina nummer vervangen zal worden
 * @param $width (optioneel) maximum aantal pagina's voor er geschrapt gaat worden aan beide zijden (als in voorbeeld)
 */
function generatepages($curpage, $totalpages, $parseurl, $width=4)
{
   $thereiscurpage = ($curpage == -1) ? 0 : 1;
   if(!$thereiscurpage)
      $curpage = 0;
   
   $returnvalue = "";
   
   $pp = $curpage+1;
   
   if($pp > 1)
   {
      $url[boardpage] = str_replace('%%', 0, $parseurl);
      $returnvalue .= "<a href=\"$url[boardpage]\">&amp;#171;</a> ";
      $url[boardpage] = str_replace('%%', $curpage-1, $parseurl);
      $returnvalue .= "<a href=\"$url[boardpage]\">&amp;lt;</a> ";
   }
   $from = ($pp==1) ? 1 : $pp-$width;
   $to = $pp+$width;
   for($i=$from;$i<=$to;++$i)
   {
      if($i<=$totalpages &amp;&amp; $i>0)
      {
         $var[page] = $i;
         if($i == $pp &amp;&amp; $thereiscurpage)
            $returnvalue .= "<b>$var[page]</b> ";
         else
         {
            $url[boardpage] = str_replace('%%', $i-1, $parseurl);
            $returnvalue .= "<a href=\"$url[boardpage]\">$var[page]</a> ";
         }
      }
   }
   if($pp < $totalpages)
   {
      if($thereiscurpage)
      {
         $url[boardpage] = str_replace('%%', $curpage+1, $parseurl);
         $returnvalue .= "<a href=\"$url[boardpage]\">&amp;gt;</a> ";
      }
      $url[boardpage] = str_replace('%%', $totalpages-1, $parseurl);
      $returnvalue .= "<a href=\"$url[boardpage]\">&amp;#187;</a> ";
   }
   if($totalpages==1)
      return "";
   else
      return $returnvalue;
}
?>

Acties:
  • 0 Henk 'm!

Verwijderd

Taal = Visual Basic 6
Doel = Check of een ADO recordset leeg is
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Public Function RecordSetEmpty(rs As ADODB.Recordset) As Boolean
    
On Error GoTo ErrorHandler
    
    'is the recordset empty?
    RSEmpty = (rs.EOF And rs.BOF)
    
    Exit Function
ErrorHandler:

    Screen.MousePointer = vbDefault
    MsgBox "Error" & vbCrLf & Err.Description, vbCritical, App.ProductName

End Function

Acties:
  • 0 Henk 'm!

  • Woudloper
  • Registratie: November 2001
  • Niet online

Woudloper

« - _ - »

Taal: Visual Basic
Doel: Een String/Num teruggeven uit een tab delimited bestand. Stel:
strTest = "4 [tab] Tweakers zijn samen [tab] 4"

dan kan je met de GetNum(strTest) het getal 4 terugkrijgen en wordt strTest verkleint naar:

strTest = "Tweakers zijn samen [tab] 4"

Met GetStr(strTest) krijg je dan de string 'Tweakers zijn samen' terug.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Private Function GetNum(ByRef line As String) As Double
' Description:  return a number, or error if a string is found or line is over
'          the component and the trailing tab is removed from the "line".

Dim s        As String
Dim i        As Long

    i = InStr(line, vbTab)
    
    If i > 0 Then            'there is a tab
      s = Left(line, i - 1)
      line = Mid(line, i + 1)
    Else                    'last component
      s = line
      line = ""
    End If

    If InStr(1, s, ".") > 0 Then    'There is a dot (.)
      s = Replace(s, ".", ",")
    End If

    'Verify it is a number
    If s <> "" Then          's contains come string
      If Not IsNumeric(s) Then    'throw an error
        Err.Raise 10001, "", "Argument not a number"
        GetNum = 0
        Exit Function
      End If
    End If
    
    If s = "" Then
      s = "0"
    End If

    GetNum = CDbl(s)            'Return value of the function.


code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
End Function

Private Function GetStr(ByRef line As String) As String
' Description:  This function returns a String. This component and it's trailing TAB are
'          removed from the line and the line is given back as a ByRef variable.

Dim s        As String
Dim i        As Long

    i = InStr(line, vbTab)

    If i > 0 Then          ' there is a tab, because the value is higher than 0
      s = Left(line, i - 1)
      line = Mid(line, i + 1)
    Else                ' last component
      s = line
      line = ""
    End If

    GetStr = s

End Function

Acties:
  • 0 Henk 'm!

Verwijderd

Naam: html highlight script
Taal: PHP
Version: 0.1
Beschrijving:
Highlight de html code i.p.v. php
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
    function keepIndent($value) {
      $value = preg_replace("/\t/", "&nbsp;&nbsp;&nbsp;&nbsp;", $value);
      return $value;
    }
    function addColor($value, $color) {
      return '<font color="' . $color . '">' . htmlentities(stripslashes($value)) . '</font>';
    }

    function doColor() {
      $args = func_get_args();
      $replace = addColor($args[0] . $args[1], "green");
      $replace .= addColor($args[2] . $args[3], "purple");
      $replace .= addColor($args[4], "red");
      $replace .= addColor($args[5], "green");


      return $replace;
    }
    $regexps =
      "/(<\/?)([a-z][a-z0-9]*)((\s[a-z\:]+)(\s?\=\s?)((\"|\')[a-z\s\#@0-9\_\-\.\/\?\,]*(\"|\')))*(>)/Ue"
    ;
    $replaces =
      "doColor('\\1', '\\2', '\\4', '\\5', '\\6', '\\9');"
    ;
    // gebruik (stel $html bevat wat html code)
    $html = preg_replace($regexps, $replaces, $html);
    print keepIndent(nl2br($html));
?>

Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

*swing*

Taal: PHP
Doel: word document (.doc) in lezen en omzetten naar schone html
Waarschuwing! je moet wel wvware geinstalleerd hebben.

PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?
 $text = `/usr/local/bin/wvWare -x '/usr/local/share/wv/wvHtml.xml' -d '/tmp/' 'path/naar/document.doc'`; 
  
 while (strpos($text, '<b></b>') !== false) {$text = str_replace('<b></b>', '', $text);} 
 while (strpos($text, "\n</p>") !== false) {$text = str_replace("\n</p>", "</p>", $text);} 
 while (strpos($text, "\">\n") !== false) {$text = str_replace("\">\n", "\">", $text);} 
 while (strpos($text, '"></p>') !== false)  
      {  
           $close = strpos($text, '"></p>'); 
           $pos = strrpos(substr($text,0,$close),"<p"); 
           $length = ($close - $pos) + 6; 
           $text = str_replace( substr($text, $pos, $length) , '', $text); 
      } 
 while (strpos($text, "\n\n") !== false) {$text = str_replace("\n\n", "\n", $text);} 
  
 echo($text);
 
?>

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

  • JaQ
  • Registratie: Juni 2001
  • Laatst online: 12:14

JaQ

Taal: PL/SQL
Doel: Converteren van een kolom in een tabel naar EURO (in dit geval vanaf BEF)
Usage: exec pck_convert(<<tabelnaam>>,<<kolomnaam>>,<<sleutel1>>,<<optional: sleutel2>>,<<optional: sleutel 3>>);


rem Title:pck_log.sql
rem Version: 1.0
rem Last update date: 04-DEC-01
rem Purpose: This package is used as a logging package for the euro conversion.
rem It contains a procedure for cleaning the log.
rem The procedure log exists more than once. This is a technique called
rem overloading. Oracle will decide automatically which procedure fits
rem by checking the parameters.
rem Dependencies: The eur_log table has to be created
rem Parameters: 1. username
rem 2. password
rem 3. database
rem
rem History:
rem 04-DEC-01 JLCreation of this script
rem

prompt define parameters as follows
prompt [1] user [2] password [3] database

define p_username = '&1'
define p_password = '&2'
define p_database = '&3'

connect &p_username/&p_password@&p_database

create or replace package pck_log
is
procedure clear_log
(p_scriptname eur_log.scriptname%type);
--
procedure log
( p_scriptname eur_log.scriptname%type
, p_notes eur_log.notes%type);
--
procedure log
( p_scriptname eur_log.scriptname%type
, p_tablename eur_log.table_name%type
, p_columnname eur_log.column_name%type
, p_type eur_log.type%type
, p_notes eur_log.notes%type);
--
end pck_log;
/

show errors

create or replace package body pck_log
is
--
procedure clear_log
(p_scriptname eur_log.scriptname%type)
is
begin
--
delete from eur_log
where scriptname = p_scriptname;
--
exception
when others then
log (p_scriptname,'Cleaning log failed : ' || substr (sqlerrm, 1, 100));
end;
--
procedure log
(p_scriptname eur_log.scriptname%type
,p_notes eur_log.notes%type)
is
begin
insert
into eur_log
( timestamp
, scriptname
, table_name
, column_name
, type
, notes)
values
( sysdate
, p_scriptname
, 'NONE'
, 'NONE'
, 'FAIL'
, p_notes);

end;

procedure log
(p_scriptname eur_log.scriptname%type
,p_tablename eur_log.table_name%type
,p_columnname eur_log.column_name%type
,p_type eur_log.type%type
,p_notes eur_log.notes%type)
is

begin
--
insert
into eur_log
( timestamp
, scriptname
, table_name
, column_name
, type
, notes)
values
( sysdate
, p_scriptname
, p_tablename
, p_columnname
, p_type
, p_notes);
--
end log;
--
end pck_log;
/


rem Title: pck_convert.sql
rem Version: 1.4
rem Last Update Date: 12-DEC-01
rem Author: Jacco Landlust
rem Purpose: This package is used for converting data to euro.
rem The package works as follows:
rem 1. clear log
rem 2. build pl/sql block dynamicly according to the input
rem parameters
rem 3. execute code
rem ad1. clearing the log is done by the log-handling package
rem called pck_log.
rem ad2. the pl/sql block is build by different functions.
rem for each part of the pl/sql block a seperate function
rem exists. This way small changes on this block are easier
rem to implement.
rem ad3. executing the code is done through native pl/sql, using
rem the execute immediate function. (EXECUTE IMMEDIATE <<CODE>>)
rem this is only possible in Oracle 8.0 databases or newer.
rem If this package is needed in older Oracle databases,
rem a exec_sql function should be build, using
rem the dbms_sql.exec_sql function to execute the code.
rem
rem = Short description of the dynamicly build PL/SQL block =
rem The "header" of the sql-block is the variable definition
rem also a exception and a pragma exeception init get defined
rem this exception will handle the oracle error "snapshot too old"
rem This error is a well know error that occurs while using cursors
rem with a lot of rows that get updated.
rem Cursor definition depends on the keys that are given into
rem the procedure.
rem The body part of the pl/sql block is the part where all the
rem "action" is going on. Values get divided by the euro constant
rem that is defined in the package. Also logging of the rounding
rem differences and the update of the data happenes here. The
rem global constant gc_test defines whether data actually gets
rem updated, or if the outcome is written to the logtable (test
rem conversion). The only tricky part in the body is the snapshot
rem too old handling. If the cursor breaks and comes back with the
rem snapshot too old message, the pl/sql block rolls back to the last
rem savepoint. The cursor is getting rebuild from the point where it
rem broke, and it will continue automaticly.
rem The footer is the logging and exception handling part of the code.
rem
rem Paramaters: 1. username
rem 2. password
rem 3. database
rem
rem History:
rem 04-DEC-01 JL Creation of this document
rem 05-DEC-01 JL Added the pk's as parameters. The primary keys help the script
rem to identify the record.
rem 05-DEC-01 JL Replaced the exec_sql procedure (uses dbms_sql package) with
rem execute immediate (native). Also split up the build_code
rem function into different functions, to make additions easier.
rem 06-DEC-01 JL Added changes for changed logging
rem 12-DEC-01 JL Introduced gc_test constant, to be able to run this package on a
rem production environment. The outcome will be inserted into a log
rem table, instead of updating the "to be converted" table.
rem

prompt define parameters as follows
prompt [1] username [2] password [3] database

define p_usr = '&1'
define p_psw = '&2'
define p_db = '&3'

set verify off

whenever sqlerror exit failure

connect &p_usr/&p_psw@&p_db


create or replace package pck_convert is

procedure to_euro
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null);

function build_code
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
return varchar2;

end pck_convert;
/
show errors

create or replace package body pck_convert
is

--
-- Global variable definition
--
gv_script varchar2(30) := 'pck_convert';
gv_eur_value number := 40.3399;
gc_test boolean := false;

function build_header
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
return varchar2
is
-- Purpose: this function will build the first part of the pl/sql block
-- that is used for conversion to euro.
--
-- local variable definitions
--
lv_statement varchar2(10000);

begin

lv_statement := 'declare ' ||
' gv_euro_value number; ' ||
' lv_script eur_log.scriptname%type; ' ||
' lv_new_value number; ' ||
' lv_pk1 ' || p_tablename || '.' || p_pk1 || '%type; ';

-- if there is only 1 primary key, the other key variable usages are not need

if p_pk2 is not null then
lv_statement := lv_statement || ' lv_pk2 ' || p_tablename || '.' || p_pk2 || '%type; ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' lv_pk3 ' || p_tablename || '.' || p_pk3 || '%type; ';
end if;

lv_statement := lv_statement ||
' lv_rounding_difference number; ' ||
' lv_rows_processed pls_integer; ' ||
' lv_wrong pls_integer; ' ||
' lv_valid_snapshot boolean; ' ||
' snapshot_too_old exception; ' ||
' pragma exception_init (snapshot_too_old, -1555); ';

return (lv_statement);

exception
when others then
pck_log.log (gv_script || '.build_header',p_tablename, p_columnname, 'Fail: ', substr (sqlerrm, 1, 100));
end build_header;

function build_cursor
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
return varchar2
is
-- Purpose: This function is used for building the cursor that is used in
-- the pl/sql block that is used for the conversion to euro.

-- local variable definitions
--
lv_statement varchar2(20000);

begin

lv_statement := ' cursor c_values ' ||
' ( cp_pk1 ' || p_tablename || '.' || p_pk1 || '%type default null ';

-- use statements for primary keys only is needed.

if p_pk2 is not null then
lv_statement := lv_statement || ' , cp_pk2 ' || p_tablename || '.' || p_pk2 || '%type default null ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' , cp_pk3 ' || p_tablename || '.' || p_pk3 || '%type default null ';
end if;

lv_statement := lv_statement || ') ' ||
' is ' ||
' select ' || p_columnname || ' cn ' ||
' , ' || p_pk1 || ' pk1 ';

if p_pk2 is not null then
lv_statement := lv_statement || ' , ' || p_pk2 || ' pk2 ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' , ' || p_pk3 || ' pk3 ';
end if;

lv_statement := lv_statement ||
' from ' || p_tablename ||
' where ' || p_pk1 || ' >= nvl (cp_pk1, ' || p_pk1 || ') ';

if p_pk2 is not null then
lv_statement := lv_statement || ' and ' || p_pk2 || ' >= nvl (cp_pk2, ' || p_pk2 || ') ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' and ' || p_pk3 || ' >= nvl (cp_pk3, ' || p_pk3 || ') ';
end if;

lv_statement := lv_statement ||
' order by ' || p_pk1;

if p_pk2 is not null then
lv_statement := lv_statement || ', ' || p_pk2;
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ', ' || p_pk3;
end if;

lv_statement := lv_statement || '; ';

return (lv_statement);

exception
when others then
pck_log.log (gv_script || '.build_cursor', p_tablename, p_columnname, 'Fail: ', substr (sqlerrm, 1, 100));
end build_cursor;

function build_body
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
return varchar2
is
-- Purpose: This function will create the body text of the pl/sql block
-- that is used for conversion to euro. All "main" converting
-- will occurr in this part.

-- local variable definitions
--
lv_statement varchar2(10000);

begin

lv_statement := 'begin ' ||
' lv_script := ' || '''' || 'pck_convert.build_code' || '''' || '; ' ||
' pck_log.clear_log (lv_script); ' ||
' commit; ' ||
' lv_rows_processed := 0; ' ||
' lv_wrong := 0; ' ||
' lv_pk1 := null; ';

-- only use key variables if needed

if p_pk2 is not null then
lv_statement := lv_statement || ' lv_pk2 := null; ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' lv_pk3 := null; ';
end if;

lv_statement := lv_statement ||
' lv_valid_snapshot := false; ' ||
' gv_euro_value := 40.3399; ' ||
' while lv_valid_snapshot = false loop ' ||
' lv_valid_snapshot := true; ' ||
' begin ' ||
' for r_values in c_values ' ||
' (lv_pk1 ';

if p_pk2 is not null then
lv_statement := lv_statement || ' , lv_pk2 ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' , lv_pk3 ';
end if;

lv_statement := lv_statement || ') ' ||
' loop ' ||
' begin ' ||
' savepoint euro_conv; ' ||
' lv_rounding_difference := 0; ' ||
' lv_new_value := r_values.cn / gv_euro_value; ' ||
' lv_pk1 := r_values.pk1; ';

if p_pk2 is not null then
lv_statement := lv_statement || ' lv_pk2 := r_values.pk2; ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' lv_pk2 := r_values.pk3; ';
end if;

lv_statement := lv_statement ||
' lv_rounding_difference := round (lv_new_value, 2) - lv_new_value; ' ||
' lv_new_value := round (lv_new_value, 2); ';

-- updating depends on the constant gc_test which indicates if it is a testconversion or a
-- definitive conversion.
if gc_test = true then

lv_statement := lv_statement ||
'pck_log.log (lv_script, ' || '''' || p_tablename || '''' || ', ' || '''' || p_columnname || '''' || ', ' ||
'''' || 'TEST' || '''' || ', ' || '''' || p_pk1 || ' = ' || '''' || '||' || ' lv_pk1' || '||';

if p_pk2 is not null then

lv_statement := lv_statement ||
'''' || p_pk2 || ' = ' || '''' || '||' || ' lv_pk2 ' || '|| ' ;

end if;
if p_pk3 is not null then

lv_statement := lv_statement ||
'''' || p_pk3 || ' = ' || '||' || 'lv_pk3 ' || '|| ' ;

end if;

lv_statement := lv_statement ||
'''' || ' old_value = ' || '''' || '||' || 'r_values.cn' || '||' || '''' ||
' new_value = ' || '''' || '||' || 'lv_new_value)';

else

lv_statement := lv_statement ||
' update ' || p_tablename ||
' set ' || p_columnname || ' = lv_new_value ' ||
' where ' || p_pk1 || ' = r_values.pk1 ';

if p_pk2 is not null then
lv_statement := lv_statement || ' and ' || p_pk2 || ' = ' || 'r_values.pk2 ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' and ' || p_pk3 || ' = ' || 'r_values.pk3 ';
end if;
end if;

lv_statement := lv_statement || '; ' ||
' pck_log.log (lv_script, ' || '''' || p_tablename || '''' ||',' || '''' || p_columnname || '''' || ',' || '''' || 'ROUND' || '''' || ',' || ' lv_rounding_difference ); ' ||
' lv_rows_processed := lv_rows_processed + 1; ' ||
' commit; ' ||
' exception ' ||
' when snapshot_too_old then ' ||
' raise snapshot_too_old; ' ||
' when others then ' ||
' rollback to euro_conv; ' ||
' pck_log.log (lv_script, ' || '''' || p_tablename || '''' || ',' || '''' || p_columnname || '''' || ',' || '''' || 'FAIL' || '''' || ',' || '''' || p_pk1 || ' = ' || '''' || '||' || 'lv_pk1 ';

if p_pk2 is not null then
lv_statement := lv_statement || ' || ' || '''' || p_pk2 || ' = ' || '''' || '||' || ' lv_pk2 ' ;
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' || ' || '''' || p_pk3 || ' = ' || '''' || '||' || ' lv_pk3 ' ;
end if;

lv_statement := lv_statement || '||' || '''' || ' ' || '''' || '||' || 'substr(sqlerrm, 1, 100)); ';

return (lv_statement);

exception
when others then
pck_log.log (gv_script || '.build_body' , p_tablename, p_columnname, 'FAIL' , substr (sqlerrm, 1, 100));
end build_body;

function build_footer
(p_tablename all_tab_columns.table_name%type
,p_columnname all_tab_columns.column_name%type)
return varchar2
is

-- Purpose: This function will build the error handling and logging part of the pl/sql block
-- that is used for converting to euro.

--
-- local variable definitions
--
lv_statement varchar2(10000);

begin

lv_statement := ' commit; ' ||
' lv_wrong := lv_wrong + 1; ' ||
' end; ' ||
' end loop; ' ||
' exception ' ||
' when snapshot_too_old then ' ||
' rollback; ' ||
' lv_valid_snapshot := false; ' ||
' end; ' ||
' end loop; ' ||
' pck_log.log (lv_script, ' || '''' || p_tablename || '''' || ',' || '''' || p_columnname || '''' || ',' || '''' || 'RP' || '''' || ',' || 'lv_rows_processed); ' ||
' pck_log.log (lv_script, ' || '''' || p_tablename || '''' || ',' || '''' || p_columnname || '''' || ',' || '''' || 'RF' || '''' || ',' || 'lv_wrong); '||
' commit; ' ||
'exception ' ||
' when others then ' ||
' pck_log.log (lv_script '|| ', ' || '''' || p_tablename || '''' || ',' || '''' || p_columnname || '''' || ',' || '''' || 'FAIL' || '''' || ',' || ' substr (sqlerrm, 1, 100)); ' ||
'end; ';

return (lv_statement);

exception
when others then
pck_log.log (gv_script || '.build_footer', p_tablename, p_columnname ,'FAIL' , substr (sqlerrm, 1, 100));
end build_footer;

function build_code
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
return varchar2
is

-- local variable definitions
--
lv_statement varchar2(30000);

begin

-- reset variables

lv_statement := null;

-- build code

lv_statement :=
build_header (p_tablename, p_columnname, p_pk1, p_pk2, p_pk3) ||
build_cursor (p_tablename, p_columnname, p_pk1, p_pk2, p_pk3) ||
build_body (p_tablename, p_columnname, p_pk1, p_pk2, p_pk3) ||
build_footer (p_tablename, p_columnname);

return (lv_statement);

end build_code;

procedure to_euro
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
is

lv_statement varchar2(30000);
begin

-- clear log
pck_log.clear_log (gv_script);

-- build code
lv_statement := build_code(p_tablename, p_columnname, p_pk1, p_pk2, p_pk3);

-- execute code
execute immediate lv_statement;

commit;

exception
when others then
pck_log.log(gv_script || '.to_euro', p_tablename, p_columnname, 'FAIL' , substr (sqlerrm, 1, 100));
commit;
end to_euro;

end pck_convert;
/


show errors

Extra toelichting

De logging package is nodig, omdat het teruggeven van foutmeldingen vanuit Native niet mogelijk is...

Egoist: A person of low taste, more interested in themselves than in me


Acties:
  • 0 Henk 'm!

Verwijderd

Offtopic: WAT zijn jullie in vredensnaam aan het doen dan?, ik bedoel, ik heb het geprobeerd te begrijpen, maar lukt dus niet echt. Ik zie alleen maar rare tekentjes hmmm

Acties:
  • 0 Henk 'm!

  • Mior
  • Registratie: Maart 2000
  • Laatst online: 11:21
Op woensdag 06 februari 2002 04:06 schreef Pjoeloe het volgende:
Offtopic: WAT zijn jullie in vredensnaam aan het doen dan?, ik bedoel, ik heb het geprobeerd te begrijpen, maar lukt dus niet echt. Ik zie alleen maar rare tekentjes hmmm
|:(

Dat noemen ze nou 'programmeren'.

Acties:
  • 0 Henk 'm!

Verwijderd

OK, das dus niet voor mij weggelegd!

Acties:
  • 0 Henk 'm!

Verwijderd

Op woensdag 06 februari 2002 22:53 schreef Pjoeloe het volgende:
OK, das dus niet voor mij weggelegd!
:D

Acties:
  • 0 Henk 'm!

  • LuCarD
  • Registratie: Januari 2000
  • Niet online

LuCarD

Certified BUFH

Op woensdag 06 februari 2002 22:53 schreef Pjoeloe het volgende:
OK, das dus niet voor mij weggelegd!
In ieder geval....

Welcome :)

Tip: lees de faq daar staan een aantal leuke tutorials als je toch besluit te beginnen ;)

Programmer - an organism that turns coffee into software.


Acties:
  • 0 Henk 'm!

  • Juup
  • Registratie: Februari 2000
  • Niet online
Taal: Perl
Doel: Alle environmental variablelen displayen (werkt ook via webserver / browser (CGI))
code:
1
2
3
4
5
6
7
8
#!perl -Tw
 
use strict;
 
print "Content-type: text/plain\n\n";
foreach (keys %ENV)
{ print "$_ = $ENV{$_}\n";
}

Intructie: Sla dit op als env.pl, chmod het naar 755 (chmod 755 env.pl) en run het op de command line of via je webserver (cgi-bin dir enzo...)

Een wappie is iemand die gevallen is voor de (jarenlange) Russische desinformatiecampagnes.
Wantrouwen en confirmation bias doen de rest.


Acties:
  • 0 Henk 'm!

  • Juup
  • Registratie: Februari 2000
  • Niet online
Taal: Perl
Doel: checken of een integer een prime (priemgetal) is.
Usage: Sla deze text op als prime.pl, chmod het naar 755 en run het met een getal als argument (bv 'prime.pl 101')
Humor: het algoritme is slechts 1 regel code.
code:
1
2
3
4
5
6
7
8
9
10
#!perl -Tw

use strict;

if ((1 x $ARGV[0]) !~ m/^(11+)\1+$/)
{ print "$ARGV[0] is a prime!\n";
}
else
{ print "Sorry but $ARGV[0] ain't a prime number.\n";
}

Een wappie is iemand die gevallen is voor de (jarenlange) Russische desinformatiecampagnes.
Wantrouwen en confirmation bias doen de rest.


Acties:
  • 0 Henk 'm!

  • Soultaker
  • Registratie: September 2000
  • Laatst online: 02:37
Op donderdag 07 maart 2002 11:20 schreef Jaaap het volgende:
code:
1
if ((1 x $ARGV[0]) !~ m/^(11+)\1+$/)
Wat een ontzettend ranzige methode =) Wel leuk gevonden trouwens.
Een andere leuke methode om een ONEINDIGE reeks priemgetallen te genereren, is de volgende. (Voor een functionele programmeertaal als Clean, Miranda of Haskell):
code:
1
Start = s [2..] where s [p:r] = [p:s [i \\ i <- r | i mod p <> 0]]

Acties:
  • 0 Henk 'm!

  • Ronald_stage
  • Registratie: Januari 2002
  • Laatst online: 28-09 13:06

Ronald_stage

wat kan je hier nog zeggen

TAAL: vb
Function: Disable X
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Option Explicit
Private Declare Function GetSystemMenu Lib "user32" _
    (ByVal hwnd As Long, ByVal bRevert As Long) As Long

Private Declare Function RemoveMenu Lib "user32" _
    (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long) As Long
    Private Const MF_BYPOS = &H400&
=========================================================

Private Sub Form_Load()
 DisableCloseButton Me.hwnd
End Sub

=========================================================

Public Sub DisableCloseButton(hwnd As Long)
    Dim hSysMenu As Long
    hSysMenu = GetSystemMenu(hwnd, 0)
    Call RemoveMenu(hSysMenu, 6, MF_BYPOS)
    Call RemoveMenu(hSysMenu, 5, MF_BYPOS)
End Sub

Acties:
  • 0 Henk 'm!

  • Juup
  • Registratie: Februari 2000
  • Niet online
Taal: Perl
Doel: het maken van een index file in een dir waar allemaal plaatjes instaan en z'n subdirs (recursief). In de index.html file zijn dan alle plaatjes te zien.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!perl -Tw
 
use strict;
my @dirs;
$dirs[0] = "/web/htdocs/images";   #change this to your dir
 
foreach my $dir (@dirs)
{ opendir (DIR, $dir) || die $!;
  my @localdirs;
  my @localfiles;
  while (defined (my $filename = readdir(DIR)))
  { if ((-d "$dir/$filename") && ($filename !~ /^\./))
    { push @dirs, "$dir/$filename";
    push @localdirs, "<a href=\"$filename/\">$filename</a><br>\n";
    }
    if (( -f "$dir/$filename" ) && ($filename =~ /\.(gif|jpg|png)$/))
    { push @localfiles, "<a href=\"$filename\">[img]\"$filename\"[/img]<br>$filename</a><br><br><br>\n";
    }
  }
  closedir (DIR);
  open (FH, ">$dir/index.html") || die $!;
  print FH "<html>\n<head>\n<title>image index for $dir</title>";
  print FH "</head>\n<body>\n<center>\n<h1>Image Index for $dir</h1><br>\n";
  foreach (sort(@localdirs))
  { print FH $_;
  }
  print FH "<br>\n<br>\n";
  foreach (sort(@localfiles))
  { print FH $_;
  }
  print FH "</center>\n</body>\n</html>\n";
  close (FH);
}

Een wappie is iemand die gevallen is voor de (jarenlange) Russische desinformatiecampagnes.
Wantrouwen en confirmation bias doen de rest.


Acties:
  • 0 Henk 'm!

Verwijderd

Op donderdag 07 maart 2002 11:20 schreef Jaaap het volgende:
Doel: checken of een integer een prime (priemgetal) is.
[..]
Op donderdag 07 maart 2002 12:10 schreef Soultaker het volgende:

[..]

Een andere leuke methode om een ONEINDIGE reeks priemgetallen te genereren, is de volgende.
LEES! (sorry voor het schreeuwe)
enne regexp's zijn nou enmaal ranzig

Acties:
  • 0 Henk 'm!

  • Grum
  • Registratie: Juni 2001
  • Niet online
Op donderdag 07 maart 2002 15:21 schreef Foxboy het volgende:
LEES! (sorry voor het schreeuwe)
enne regexp's zijn nou enmaal ranzig
'andere' doelt niet altijd op een vorige post hoor :) maar ok

btw je vind perl kontschoppen en regexps ranzig ? .. dan mis je et sterkste staaltje uit de taal man :)

Acties:
  • 0 Henk 'm!

  • Dope-E
  • Registratie: Januari 2001
  • Laatst online: 30-05 12:05

Dope-E

The one and only Dope

Taal: VB(script) (vast wel naar andere taal om te bouwen ;))
Doel: Bijvoorbeeld pw's encrypted in db opslaan of in cookies...

als iemand inlogd eerst hash maken dan vergelijken met db...
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
'encryptie algorithme... oneway --> hash
Function Hash(ByVal text)
    dim a
    dim i

    a=1
    For i = 1 to len(text)
        a=sqr(a*i*asc(mid(text,i,1))) 'Numeric Hash
    Next
    
    Rnd(-1)
    Randomize a

    For i = 1 to 16
        Hash = Hash & Chr(int(rnd*256)) 'Char Hash
    Next
End function

Voorbeeld: "test" wordt "ÕÎ0ûñÄg\íêÖ"

edit:

Zou misschien wel leuk zijn om te kijken of iemand dit kan omdraaien... dus de hash als invoer en de tekst als uitvoer, misschien een }:O bij nodig :?
:+

twitter.com/curly_sanders


Acties:
  • 0 Henk 'm!

  • Soultaker
  • Registratie: September 2000
  • Laatst online: 02:37
Op donderdag 07 maart 2002 15:21 schreef Foxboy het volgende:
LEES! (sorry voor het schreeuwe)
Ik erger me er toch aan. Ik wist heus wel wat jou code en de mijne deed hoor. Omdat jij een compact en nogal obfuscated stukje code gaf voor het controleren van priemgetallen, gaf ik een ANDER stukje code over priemgetallen, dat OOK compact en enigszins obfuscated was en de leuke eigenschap had 't een oneindige reeks oplevert.
enne regexp's zijn nou enmaal ranzig
Hier wel, maar dat maakt de code snippet juist zo leuk (hoewel niet echt prakisch). Meestal kunnen regexps wel zinnig worden gebruikt.

Acties:
  • 0 Henk 'm!

  • Janoz
  • Registratie: Oktober 2000
  • Laatst online: 07:50

Janoz

Moderator Devschuur®

!litemod

En nu ophouden met dat gelul ;) en code posten. Daar is dit topic voor bedoeld :)..

Ken Thompson's famous line from V6 UNIX is equaly applicable to this post:
'You are not expected to understand this'


Acties:
  • 0 Henk 'm!

  • Soultaker
  • Registratie: September 2000
  • Laatst online: 02:37
Vooruit dan maar, een stukje Clean code (hoewel 't waarschijnlijk ook wel in andere functionele programmeertalen aan de praat te krijgen is) voor het berekenen van 'n CRC32 checksum (volgens de ISO 3309 standaard). Wordt veel gebruikt in archiefbestandsformaten e.d.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* The CRC type: a 32-bit integer (considered unsigned) */
:: CRC   :== Int

/* Generate CRC table in a constant application form */
crcTable :: {#CRC}
crcTable
=: { iterate step n !! 8 \\ n <- [0..255] }
where
    /* apply a CRC iteration step on an integer */
    step i
    | i bitand 1 == 1 = 0xEDB88320 bitxor (i >>! 1)
    | otherwise  = i >>! 1
    
/* Returns the CRC32 value of a given string. */
crc :: (!{#Char} -> CRC)
crc = crcUpdate 0

/* Updates a given CRC32 value with a certain string.
This function can be used to calculate the CRC32 value in portions, instead
of loading all input data into memory and processing it at once. The following
expressions are equivalent: (crcUpdate (crc a) b) <==> (crc (a++b)) */
crcUpdate :: !CRC !{#Char} -> CRC
crcUpdate crc str
= bitnot (update (bitnot crc) 0)
where
    length = size str
    
    update :: !CRC !Int -> CRC
    update crc i
    | i == length = crc
    | otherwise   = update crc` (i+1)
    where
      chr  = toInt str.[i]
      crc` = (crcTable.[(crc bitxor chr) bitand 0xFF]) bitxor (crc >>! 8)

Omdat Clean eigenlijk niet aan unsigned integers doet, heb ik >>! gedefinieerd als unsigned right shift operator:
code:
1
2
3
4
5
6
7
8
/* Unsigned right shift operation on (signed) integers */
(>>!) infix 7 :: !Int !Int -> Int
(>>!) i n
| n >= 0  = result
where
    result
    | i >= 0 = i >> n
    | i < 0  = ((i bitand 0x7FFFFFFF) >> n) bitor (1 << (31-n))

Acties:
  • 0 Henk 'm!

  • chaozz
  • Registratie: Juni 2000
  • Laatst online: 29-08 01:01

chaozz

Retrofiel

Op dinsdag 08 januari 2002 22:40 schreef Mr. B. het volgende:
Taal: Turbo Pascal/Assembly
Doel: Omzetten van een string in hoofd- of kleine letters (TP biedt standaard alleen functies om Chars te upper/lowercasen)
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function HoofdLetters(S: string): string;
begin
  asm
    CLD
    LEA SI,S
    LES DI,@Result
    SEGSS LODSB
    STOSB
    XOR AH,AH
    XCHG AX,CX
    JCXZ @EINDE
    @BEGIN_LUS:
    SEGSS LODSB
    CMP AL,'a'
    JB @GEEN_KLEINE_LETTER
    CMP AL,'z'
    JA @GEEN_KLEINE_LETTER
    SUB AL, 20h
    @GEEN_KLEINE_LETTER:
    STOSB
    LOOP @BEGIN_LUS
    @EINDE:
  end;
end;

function KleineLetters(S: string): string;
begin
  asm
    CLD
    LEA SI,S
    LES DI,@Result
    SEGSS LODSB
    STOSB
    XOR AH,AH
    XCHG AX,CX
    JCXZ @EINDE
    @BEGIN_LUS:
    SEGSS LODSB
    CMP AL,'A'
    JB @GEEN_HOOFD_LETTER
    CMP AL,'Z'
    JA @GEEN_HOOFD_LETTER
    SUB AL, -20h
    @GEEN_HOOFD_LETTER:
    STOSB
    LOOP @BEGIN_LUS
    @EINDE:
  end;
end;
dat kan toch veel simpeler?
code:
1
2
3
4
5
6
7
8
9
function MaakUpcase(strOud: string) : string;
var strNieuw, Waarde;

begin
 for Waarde := 1 to Length(strOud)
  strNieuw : = StrNieuw + Upcase(strOud[Waarde]);

 MaakUpcase := strNieuw;
end;

kan me vergissen, tis alweer een tijdje geleden. >:)

chaozz.nl | RetroGameCouch


Acties:
  • 0 Henk 'm!

  • rvrbtcpt
  • Registratie: November 2000
  • Laatst online: 28-09 09:14
Taal: Java
Doel: Controle of een ingevoerde datum geldig is
Code:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
try {
  System.out.println("SimpleDateFormatter check op de datum -> "+begindatum );
  // Format the current time.
  SimpleDateFormat formatter = new SimpleDateFormat ("dd-MM-yyyy");
  Date testDatum = formatter.parse(begindatum);
  String checkDatum = formatter.format(testDatum);
  if( checkDatum.equals(begindatum) ) {
    // Goed!
  } else {
    // Fout!
    System.out.println("Ongeldige datum. Goede datum : "+checkDatum+" ?? ");
  }
  System.out.println("SimpleDateFormatter check op de datum -> OK  ("+testDatum+")" );
} catch( java.text.ParseException fout ) {
    System.out.println("Ongeldige datum.");
}

Uitleg:
De standaard Java datum class wordt gebruikt om te controleren of een String (begindatum) correct is ingevoerd.
Het leuke van de Java date class is dat een ongeldige datum wordt omgezet in een correcte datum.
Dus 32-01-2002 wordt 01-02-2002. Deze datum staat in de variabele: checkDatum.
Deze heb ik gebruikt om user input te valideren en vervolgens de misschien correcte datum als output bij de error mee te geven.

Acties:
  • 0 Henk 'm!

  • Limhes
  • Registratie: Oktober 2001
  • Laatst online: 28-09 17:41
Voor degenen die een MSN progsel in C# willen maken en anderen:

Taal: C#
Platform: alles waar .NET op draait
Doel: op een simpele manier een md5 hash genereren
code:
1
2
3
4
5
6
7
8
9
10
using System.Web.Security;

class Test
{
  static void Main()
  {
    string sToMD5 = "ditmoetgehashedworden";
    string sFromMD5 = FormsAuthentication.HashPasswordForStoringInConfigFile(sToMD5, "md5");
  }
}

Acties:
  • 0 Henk 'm!

Verwijderd

Taal: C/C++
Doel: het berekenen van face en vertex normals uit vertexdata. Gebruikt facenormals voor het bepalen van een smoothing angle tussen faces zodat de vertexnormals van gesharede vertices wel/niet worden bepaald uit het middelen van de facenormal van de aangrenzende faces (still with me? :))
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// Purpose: calculates the face and vertexnormals for all the faces and vertices in the model.
void
CalculateNormals(SModel *pTheModel, float fSmoothingAngle)
{
    int         iFaceCnt, iFaceCnt2, iVertexCnt, iCurrentVertexIndx;
    SFace       *pCurrentFace;
    SVect3      vA, vB, vNormal, vTmpResult;
    int         *arrpiAmFacesPerVertex, *arrpiFPVIndices, **arrpiFacesPerVertex;
    double      dAngle;

    // Free up the eventually allocated VertexNormals array, we don't use it anymore.
    if(pTheModel->m_pVertexNormals)
    {
        // remove the memory, we don't know if it's large enough
        free(pTheModel->m_pVertexNormals);
    }

    // Allocate memory for the counterarray per vertex for the amount of faces the vertices are in.
    arrpiAmFacesPerVertex=(int *)malloc(sizeof(int) * pTheModel->m_iAmVertices);
    memset(arrpiAmFacesPerVertex, 0, sizeof(int) * pTheModel->m_iAmVertices);
    // allocate memory for the indices array per vertex, for the indices in the arrays per vertex in arrpiFacesPerVertex[][]
    arrpiFPVIndices=(int *)malloc(sizeof(int) * pTheModel->m_iAmVertices);
    memset(arrpiFPVIndices, 0, sizeof(int) * pTheModel->m_iAmVertices);
    // allocate the pointerarray for the arrays per vertex where the faceindices are stored.
    arrpiFacesPerVertex=(int **)malloc(sizeof(int *) * pTheModel->m_iAmVertices);
    memset(arrpiFacesPerVertex, 0, sizeof(int *) * pTheModel->m_iAmVertices);

    // first, calculate all facenormals for each face in the model.
    for(iFaceCnt = 0;iFaceCnt < pTheModel->m_iAmFaces;iFaceCnt++)
    {
        pCurrentFace=&pTheModel->m_pFaces[iFaceCnt];
        // calculate the vectors that make up the face plane, using the 3 vertices of this face
        vA[0]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[0]][0] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][0];
        vA[1]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[0]][1] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][1];
        vA[2]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[0]][2] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][2];
        vB[0]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[2]][0] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][0];
        vB[1]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[2]][1] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][1];
        vB[2]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[2]][2] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][2];

        // Crossproduct to get the normal. (B x A, otherwise we end up with normals facing to the inside of the model)
        CrossProductVect3(vB, vA, vNormal);
        // Normalize vNormal
        Vector3Normalize(vNormal);
        // store face normal
        pCurrentFace->m_vFaceNormal[0]=vNormal[0];
        pCurrentFace->m_vFaceNormal[1]=vNormal[1];
        pCurrentFace->m_vFaceNormal[2]=vNormal[2];
        // reset vertexnormals
        pCurrentFace->m_vVertexNormals[0][0]=0.0f;
        pCurrentFace->m_vVertexNormals[0][1]=0.0f;
        pCurrentFace->m_vVertexNormals[0][2]=0.0f;
        pCurrentFace->m_vVertexNormals[1][0]=0.0f;
        pCurrentFace->m_vVertexNormals[1][1]=0.0f;
        pCurrentFace->m_vVertexNormals[1][2]=0.0f;
        pCurrentFace->m_vVertexNormals[2][0]=0.0f;
        pCurrentFace->m_vVertexNormals[2][1]=0.0f;
        pCurrentFace->m_vVertexNormals[2][2]=0.0f;

        // add the amount faces per vertex counters for the vertices in the current face.
        arrpiAmFacesPerVertex[pCurrentFace->m_iVertexIndices[0]]++;
        arrpiAmFacesPerVertex[pCurrentFace->m_iVertexIndices[1]]++;
        arrpiAmFacesPerVertex[pCurrentFace->m_iVertexIndices[2]]++;
    }

    // now per vertex, allocate an array of face indices where we'll store per face the vertex is in, the index
    // of that face. 
    for(iVertexCnt = 0; iVertexCnt < pTheModel->m_iAmVertices;iVertexCnt++)
    {
        if(arrpiAmFacesPerVertex[iVertexCnt] > 0)
        {
            arrpiFacesPerVertex[iVertexCnt]=(int *)malloc(sizeof(int) * arrpiAmFacesPerVertex[iVertexCnt]);
            memset(arrpiFacesPerVertex[iVertexCnt], 0 , sizeof(int) * arrpiAmFacesPerVertex[iVertexCnt]);
        }
    }

    // walk all the faces, store each face's index in the current free slot in the faceindex array of the particular
    // vertex. 
    for(iFaceCnt=0;iFaceCnt<pTheModel->m_iAmFaces;iFaceCnt++)
    {
        for(iVertexCnt = 0;iVertexCnt < 3;iVertexCnt++)
        {
            iCurrentVertexIndx=pTheModel->m_pFaces[iFaceCnt].m_iVertexIndices[iVertexCnt];
            arrpiFacesPerVertex[iCurrentVertexIndx][arrpiFPVIndices[iCurrentVertexIndx]++]=iFaceCnt;
        }
    }

    // Now, walk all vertices. Per vertex, we'll calculate for each face this vertex is in, the vertexnormal,
    // by averaging the facenormals of all the faces that are in the same smoothgroup. faces are in the same
    // smoothgroup when the angle between the normals of these faces is < ANGLE_SMOOTH. We determine the angle
    // with the dotproduct (which results in the cos(angle) * length A * length B. Since length of the normals
    // is 1.0, we leave these out of it).
    for(iVertexCnt=0;iVertexCnt<pTheModel->m_iAmVertices;iVertexCnt++)
    {
        
        for(iFaceCnt=0;iFaceCnt<arrpiAmFacesPerVertex[iVertexCnt];iFaceCnt++)
        {
            // Store face normal as startvalue in the vTmpResult vector which will contain the
            // calculation result for this vertex-face combination
            vTmpResult[0]=pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vFaceNormal[0];
            vTmpResult[1]=pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vFaceNormal[1];
            vTmpResult[2]=pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vFaceNormal[2];

            // Walk the complete facelist of this vertex again, and check whether the facenormal of
            // each face should be averaged with the vTmpResult. This will only be done when the angle
            // between the normal of the face iFaceCnt and the face iFaceCnt2 < ANGLE_SMOOTH, AND iFaceCnt != iFaceCnt2
            for(iFaceCnt2=0;iFaceCnt2<arrpiAmFacesPerVertex[iVertexCnt];iFaceCnt2++)
            {
                if(iFaceCnt==iFaceCnt2)
                {
                    // the same, skip
                    continue;
                }
                // Test if the angle between the facenormals is < ANGLE_SMOOTH
                dAngle=DotProductVect3(pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vFaceNormal,
                            pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt2]].m_vFaceNormal);
                dAngle=(acos(dAngle)/ PI) * 180.0;
                // now test if this angle is smaller than fSmoothingAngle. more than 1 angle can result in the same
                // cosine value, but this doesn't matter since 2 normals who opposite eachother have the maximum angle, 180
                // degrees, and in that range, no double cosine values occure for the same angle.
                if(dAngle < fSmoothingAngle)
                {
                    // this face (iFaceCnt2) is part of a smooth surface together with face (iFaceCnt).
                    Vector3Add(vTmpResult, pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt2]].m_vFaceNormal,
                                    vTmpResult);
                }
            }
            // make the vector again of length 1
            Vector3Normalize(vTmpResult);
            // store vTmpResult in the right VertexNormal slot for the vertex iVertexCnt. only 3 slots available, so
            // we do a dirty if then else thingy. If stored, move on with the next face!
            if(pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_iVertexIndices[0]==iVertexCnt)
            {
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[0][0]=vTmpResult[0];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[0][1]=vTmpResult[1];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[0][2]=vTmpResult[2];
                // continue with next face
                continue;
            }
            if(pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_iVertexIndices[1]==iVertexCnt)
            {
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[1][0]=vTmpResult[0];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[1][1]=vTmpResult[1];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[1][2]=vTmpResult[2];
                // continue with next face
                continue;
            }
            if(pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_iVertexIndices[2]==iVertexCnt)
            {
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[2][0]=vTmpResult[0];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[2][1]=vTmpResult[1];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[2][2]=vTmpResult[2];
            }
        }
    }
    // done!
    // free up all the memory we've allocated
    for(iVertexCnt = 0; iVertexCnt < pTheModel->m_iAmVertices;iVertexCnt++)
    {
        free(arrpiFacesPerVertex[iVertexCnt]);
    }
    free(arrpiFacesPerVertex);
    free(arrpiAmFacesPerVertex);
    free(arrpiFPVIndices);
}

Hulp routines
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Purpose: adds 2 vectors vSrc1 and vSrc2 and puts result in vDst
inline void
Vector3Add(SVect3 vSrc1, SVect3 vSrc2, SVect3 vDst)
{
    vDst[0]=vSrc1[0]+vSrc2[0];
    vDst[1]=vSrc1[1]+vSrc2[1];
    vDst[2]=vSrc1[2]+vSrc2[2];
}

// Purpose: calculates the average of 2 given 3pos vectors vSrc1 and vSrc2 and puts the result in vDst
inline void
Vector3Average(SVect3 vSrc1, SVect3 vSrc2, SVect3 vDst)
{
    vDst[0]=(vSrc1[0]+vSrc2[0]) * 0.5f;
    vDst[1]=(vSrc1[1]+vSrc2[1]) * 0.5f;
    vDst[2]=(vSrc1[2]+vSrc2[2]) * 0.5f;
}

// Purpose: calculates the cross product of 2 given vectors vSrc1 and vSrc2 and returns the result
// vector vDst
inline void 
CrossProductVect3(SVect3 vSrc1, SVect3 vSrc2, SVect3 vDst)
{
    vDst[0] = vSrc1[1] * vSrc2[2] - vSrc1[2] * vSrc2[1];
    vDst[1] = vSrc1[2] * vSrc2[0] - vSrc1[0] * vSrc2[2];
    vDst[2] = vSrc1[0] * vSrc2[1] - vSrc1[1] * vSrc2[0];
}

// Purpose: normalizes the given vector to a length of 1.0f. Used for normals
// Returns true if succeeded, false otherwise
inline bool 
Vector3Normalize (SVect3 vSrc)
{
    int     i;
    double  dLength;
    
    dLength=Vector3Length(vSrc);
    if(dLength<=0.0)
    {
        return false;
    }
        
    for (i=0 ; i < 3 ; i++)
    {
        vSrc[i] = (float)((double)vSrc[i] / dLength);   
    }
    return true;
}

// Purpose: calcs the dotproduct between 2 vectors vSrc1 and vSrc2 and returns the product as a float.
// Dot product calculates ||vSrc1|| * ||vSrc2|| * cos Alpha. Alpha is angle between vSrc1 and vSrc2.
inline float
DotProductVect3(SVect3 vSrc1, SVect3 vSrc2)
{
    return ((vSrc1[0]*vSrc2[0]) + (vSrc1[1]*vSrc2[1]) + (vSrc1[2]*vSrc2[2]));
}

Acties:
  • 0 Henk 'm!

  • drm
  • Registratie: Februari 2001
  • Laatst online: 09-06 13:31

drm

f0pc0dert

PHP: Random pass generator
Textinterface
Spelling van het wachtwoord in telefonisch alfabet (engels)
Genereert enkel op basis van aangegeven characters in array "chars".
  • Wanneer je nieuwe toevoegd moet je ook hun "spelling-counterpart" erbij zetten, bijv: [php]<? "/" => "forwardslash", "~" => "tilde"?>[/php]
_____________________________________________________________________________________________
Code
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
function make_seed() {
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());


$chars = array (
   "a" => "alpha",
   "b" => "bravo",
   "c" => "charlie",
   "d" => "delta",
   "e" => "echo",
   "f" => "foxtrot",
   "g" => "golf",
   "h" => "hotel",
   "i" => "india",
   "j" => "julia",
   "k" => "kilo",
   "l" => "lima",
   "m" => "mike",
   "n" => "november",
   "o" => "oscar",
   "p" => "papa",
   "q" => "quebec",
   "r" => "romeo",
   "s" => "sierra",
   "t" => "tango",
   "u" => "uniform",
   "v" => "victor",
   "w" => "whiskey",
   "x" => "x-ray",
   "y" => "yankee",
   "z" => "zulu",
   1 => "one",
   2 => "two",
   3 => "three",
   4 => "four",
   5 => "five",
   6 => "six",
   7 => "seven",
   8 => "eight",
   9 => "nine",
   0 => "zero"
);

foreach ( $chars as $k => $v )
   if ( is_string ( $k ) )
    $chars [ strtoupper ( $k ) ] = strtoupper ( $v );

foreach ( array_keys ( $chars ) as $k )
   $str .= $k;

$pass = "";
for ( $a = 0; $a < 8; $a ++ )
   $pass .= $str [ rand ( 0, strlen ( $str ) ) ];

for ( $a = 0; $a < strlen ( $pass ); $a ++ )
   $arr [] = $chars [ $pass [ $a ] ];

echo $pass, "  (", implode  ( " - ", $arr ), ")";

Music is the pleasure the human mind experiences from counting without being aware that it is counting
~ Gottfried Leibniz


Acties:
  • 0 Henk 'm!

Verwijderd

PHP:
1
<?function even($num) {    if ($num % 2) { // ...Number is odd...        return;        } else {         // number is even....                return true;        }}?>

functie om te controlleren of een getal even of oneven is :)

Acties:
  • 0 Henk 'm!

  • pistole
  • Registratie: Juli 2000
  • Laatst online: 11:28

pistole

Frutter

vbscript. Erg simpel maar wel handig. Voor o.a. strings naar MSSQL te duwen. Als je apostrophes hebt in die strings kan dat problemen opleveren. Oplossing: apostrophe verdubbelen.
code:
1
2
3
function qfix(str)
  qfix=replace(str, "'", "'')
end function

Controleren of een datum correct is. Zeer eenvoudig toe te passen voor int, string, etc
code:
1
2
3
4
5
6
7
8
9
10
11
function isDate(str)
  dim tmp
  tmp=""
  isDate=false

  on error resume next
    tmp=formatdatetime(str)
  on error goto 0

  if tmp<>"" then isDate=true
end function

Ik frut, dus ik epibreer


Acties:
  • 0 Henk 'm!

  • drm
  • Registratie: Februari 2001
  • Laatst online: 09-06 13:31

drm

f0pc0dert

xtentic:
PHP:
1
<?function even($num) {   // snip}?>

functie om te controlleren of een getal even of oneven is :)
Malle pietje, zeg....
daar ga je toch geen functie voor definieren :? Da's net zo iets als:
code:
1
2
3
4
function isZero ( $num )
{
   return ( $num == 0 );
}

Music is the pleasure the human mind experiences from counting without being aware that it is counting
~ Gottfried Leibniz


Acties:
  • 0 Henk 'm!

  • Jelle Niemantsverdriet
  • Registratie: Februari 2000
  • Laatst online: 27-09 18:36
Op maandag 11 maart 2002 16:27 schreef drm het volgende:
daar ga je toch geen functie voor definieren :?
Los daarvan: er zit ook een foutje in dat ongetwijfeld een leuke parse error zal geven:
PHP:
1
<?function even($num) {            if ($num % 2)) {         // 1 sluithaakje te veel bij de if?>

maar goed, genoeg topic-vervuiling ;), verder met de code

Acties:
  • 0 Henk 'm!

  • VinnieM
  • Registratie: September 1999
  • Laatst online: 29-11-2024
Taal: Java
Doel: Genereer constructor, set methods en get functies aan de hand van een class met alleen datamembers.
Werkt nog niet helemaal goed met arrays, maar dat mogen jullie zelf oplossen als je er zin in hebt :)
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.io.*;
import java.util.*;
import java.lang.reflect.*;

public class JavaGen {

    public static final String VERSION = "0.1a";

    public static void main(String args[]) {
        if (args.length != 1) {
            System.out.println("JavaGen " + VERSION + " - generates wrapper functions and set methods");
            System.out.println("for all declared variables (datamembers) of the specified class.");
            System.out.println("Usage: java JavaGen <CLASSFILE>");
            return;
        }
        try {
            Class c = Class.forName(args[0]);
            FileWriter fw = new FileWriter("output.txt");
            BufferedWriter bw = new BufferedWriter(fw);
            Field[] fields = c.getDeclaredFields();

            writeLine(bw, "");
            write(bw, "\tpublic " + c.getName() + "(");

            // Generate constructor-headline regarding all declared variables
            for(int i = 0; i < fields.length; i++) {
                Field field = fields[i];

                String name = field.getName();

                String type = (field.getType()).toString();
                if (type.startsWith("class")) {
                    type = type.substring(type.lastIndexOf(".") + 1);
                }

                if (i == fields.length - 1) {
                    writeLine(bw, type + " " + name + ") {");
                }
                else {
                    write(bw, type + " " + name + ", ");
                }
            }

            // Generate constructor regarding all declared variables
            for(int i = 0; i < fields.length; i++) {
                Field field = fields[i];

                writeLine(bw, "\t\tthis." + field.getName() + " = " + field.getName() + ";");
            }
             writeLine(bw, "\t}");

            // Generate wrapper-functions for all declared variables
            for(int i = 0; i < fields.length; i++) {
                writeLine(bw, "");
                Field field = fields[i];

                String name = field.getName();
                char[] chars = name.toCharArray();
                chars[0] = Character.toUpperCase(chars[0]);
                name = new String(chars);

                String type = (field.getType()).toString();
                if (type.startsWith("class")) {
                    type = type.substring(type.lastIndexOf(".") + 1);
                }

                writeLine(bw, "\tpublic " + type + " get" + name + "() {");
                writeLine(bw, "\t\treturn " + field.getName() + ";");
                writeLine(bw, "\t}");
            }

            // Generate set-methods for all declared variables
            for(int i = 0; i < fields.length; i++) {
                writeLine(bw, "");
                Field field = fields[i];

                String name = field.getName();
                char[] chars = name.toCharArray();
                chars[0] = Character.toUpperCase(chars[0]);
                name = new String(chars);

                String type = (field.getType()).toString();
                if (type.startsWith("class")) {
                    type = type.substring(type.lastIndexOf(".") + 1);
                }

                writeLine(bw, "\tpublic void set" + name + "(" + type + " " + field.getName() + ") {");
                writeLine(bw, "\t\tthis." + field.getName() + " = " + field.getName() + ";");
                writeLine(bw, "\t}");
            }
            bw.close();
            fw.close();
        }
        catch(Exception e) {
            System.err.println(e);
        }
    }

    public static void write(BufferedWriter bw, String s) throws IOException {
        bw.write(s, 0, s.length());
    }

    public static void writeLine(BufferedWriter bw, String s) throws IOException {
        bw.write(s, 0, s.length());
        bw.newLine();
    }
}

Acties:
  • 0 Henk 'm!

Verwijderd

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Dit script is geschreven om aantetonen hoe gemakkelijk het is om een standaard gallery script te maken. 

Mijn script ondersteund de volgende dingen. 

* Thumbnailing 
* Directory loading 
* Gallery veranderingen (qua plaatjes naast elkaar en max aantal plaatjes per pagina) 

^---- in te stellen met $prog[....] 

hoe werkt het? 

je upload dit naar je webserver in de directory van jou keuze, de commandline voor je gallery script is 

galleryscriptnaam.php?gallery=directorynaam 

vragen?... geen probleem, daarvoor heb ik email :) 

(dit is de html link versie ;))


PHP:
1
<?// show thumbnail function function makeThumb($file) {     header("Content-type: image/png");     header ("Cache-Control: no-cache");     $sz = 128;     $im = imagecreatefromjpeg("./$file");     $im_width=imageSX($im);     $im_height=imageSY($im);     // work out new sizes     if($im_width >= $im_height) {         $factor = $sz / $im_width;         $new_width = $sz;         $new_height = $im_height * $factor;     } else {         $factor = $sz / $im_height;         $new_height = $sz;         $new_width = $im_width * $factor;     }     // resize     $new_im=ImageCreate($new_width,$new_height);     ImageCopyResized($new_im, $im, 0, 0, 0, 0, $new_width, $new_height, $im_width, $im_height);     Imagepng($new_im,'',100); // quality 75     // cleanup     ImageDestroy($im);     ImageDestroy($new_im); } function showHtmlPointers() {     global $gallery, $from, $prog;     if (($from - $prog[max]) >= 1) {        echo "<a href=\"?gallery=$gallery&amp;from=" . ($from - $prog[max]) . "\">Back</a>&amp;nbsp;";     }     if ($from + $prog[max] <= $prog[files]) {        echo "<a href=\"?gallery=$gallery&amp;from=" . ($from + $prog[max]) . "\">Next</a>&amp;nbsp;";     } } function previewPicture($picture) {     global $prog;     $x = getimagesize($picture);     $width = $x[0];     $height = $x[1];     if ($height > $width) {         $percentheight = 100;         $percentwidth = round($width / ($height / 100));         $newimageheight = $prog[imageheight];         $newimagewidth = round(($prog[imagewidth] / 100) * $percentwidth);     }else{         $percentheight = round($height / ($width / 100));         $percentwidth = 100;         $newimagewidth = $prog[imagewidth];         $newimageheight = round(($prog[imageheight] / 100) * $percentheight);     }     return "[img]\"?thumb=$picture\"[/img]"; // load picture } function showPicture($picture) {     global $prog;     echo "<center>[img]\"$picture\"></center>";[/img]<a href=\"javascript:history.go(-1);\">Back</a></center>"; } function loaddir($dir){     global $filedb, $prog;     $handle = opendir($dir);     while (false !== ($file = readdir($handle))) {         if(is_dir($dir . $file)) {       // dir?!         }elseif (eregi(".nol|.gif|.bmp|.png|.jpg", $file)) {             $prog[files]++;             $filedb[file][$prog[files]] = $file;             $filedb[size][$prog[files]] = filesize($dir . $file);             $testArray =  getimagesize("./" . $dir . $file);             $filedb[height][$prog[files]] = $testArray[1];             $filedb[width][$prog[files]] = $testArray[0];         }else{         }     }     closedir($handle); } function checkPath($dir) {     if (is_dir($dir)) {         return true;     }else{         return;     } } function checkInit() {     global $prog, $filedb, $gallery, $from;     if ($from == 0) { $from = 1; }     if (strlen($gallery) > 0) {         if (checkPath($gallery)) {             loaddir("./" . $gallery . "/");             return true;         }else{             return;          }     } } // // prog // $prog[imageheight] = 128;        // hoogte van het plaatje. $prog[imagewidth] = 128;         // breedte van het plaatje. $prog[cells] = 4;                // aantal cellen. $prog[max] = 10;                // aantal plaatjes (maximaal) per pagina. if (strlen($thumb) > 0) {     makeThumb($thumb);     exit(); }elseif(strlen($display) > 0) {     showPicture($display);     exit(); } if (checkInit()) {     $prog[name] = str_replace("_", " ", $gallery);     echo "<center><h1>$prog[name]</h1></center>";     echo "<body bgcolor=#888888 text=#101818 link=#79b8c8 alink=#79b8c8 vlink=#79b8c8>";     echo "<center>";     echo "<table width=800 border=0 cellspacing=0 cellpadding=0 align=center>";     echo "<tr>";     if (($prog[max] + $from) > $prog[files]) {        $left = round(($prog[files] - $from) / $prog[cells]);                for ($i = 0; $i <= $left -1; $i++) {           echo "<table>";           echo "   <tr>";           for ($x = 0; $x <= $prog[cells] -1; $x++) {              echo "      <td align=\"center\">";                 $tmp = ($from + ($i * $prog[cells])) + $x;                 $image = $gallery . "/" . $filedb[file][$tmp];                 echo "          <a href=\"?display=" . $image . "\">" . previewPicture($image) . "</a>";              echo "      </td>";           }           echo "   </tr>";           echo "</table>";        }        $over = $prog[files] - ($from + ($left * $prog[cells]));        echo "<table>";        echo "   <tr>";        for ($x = 0; $x <= $over -1; $x++) {           echo "      <td align=\"center\">";              $tmp = ($from + ($left * $prog[cells])) + $x;              $image = $gallery . "/" . $filedb[file][$tmp];              echo "          <a href=\"?display=" . $image . "\">" . previewPicture($image) . "</a>";           echo "      </td>";        }        echo "   </tr>";        echo "</table>";        showHtmlPointers();        echo "<center>showing images " . $from . " to " . $prog[files] . " of a total of " . $prog[files] . " images</center>";        exit();     }         for ($i = 0; $i <= ($prog[max] / $prog[cells]) -1; $i++) {        echo "   <tr>";        for ($x = 0; $x <= $prog[cells] -1; $x++) {           echo "      <td align=\"center\">";              $tmp = ($from + ($i * $prog[cells])) + $x;              $image = $gallery . "/" . $filedb[file][$tmp];              echo "          <a href=\"?display=" . $image . "\">" . previewPicture($image) . "</a>";           echo "      </td>";        }        echo "   </tr>";     }     echo "</table>";     echo "<center>"; showHtmlPointers(); echo "</center>";     echo "<center>Showing images " . $from . " to " . ($from + 10) . " of a total of " . $prog[files] . " images</center>";     exit(); }else{     echo "-=[ SimpleGallery.php the gallery maker v1.0 by Xtentic]=-";     echo "<br>";     echo "<br>to use this script you need to modify the commands.";     echo "<br>?gallery = path of the files";     echo "<br>&amp;from = view page from";     echo "<br><br>Contact me at <a href=\"mailto:xtentic@hotmail.com?subject=SimpleGallery\">xtentic @ hotmail.com</a>";     exit(); } ?>

Acties:
  • 0 Henk 'm!

Verwijderd

Mijn eigen Extreem Upload Systeem
PHP:
1
<?function showForm($start, $username) {    $form[max] = 25;    $form[name] = "uploadform";    if (!isSet($start)) {        $form[start] = 5;    }else{        $form[start] = $start;    }    echo "<script language='javascript1.2'>\r\n";    echo "var varFile = new Array($form[max]);\r\n";    echo "var varComment = new Array($form[max]);\r\n";    for ($i = 0; $i <= $form[max]; $i++) {           echo "    varFile[" . $i . "] = \"\"; varComment[" . $i . "] = \"\";\r\n";    }    echo "</script>\r\n";//    echo "<body onload=\"javascript:createForm($form[start]);\">\r\n";    echo "<script language=\"JavaScript\">\r\n";    echo "function createForm(number) {\r\n";    echo "\r\n";    echo "   data = \"\";\r\n";    echo "   inter = \"'\";\r\n";    echo "   data = \"<table border=1 cellpadding=0 cellspacing=1 width=600>\";\r\n";    echo "   if ($form[max] >= number &amp;&amp; number > -1) {\r\n";    echo "      for (i=1; i <= number; i++) {\r\n";    echo "         d1 = i -1;\r\n";    echo "         data = data + \"<tr>\";\r\n";    echo "         data = data + \"<td width=20 nowrap>\" + i + \"<td width=5% nowrap>&amp;nbsp;<strong><b>F</strong></b>ile:&amp;nbsp;</td>\";\r\n";    echo "         data = data + \"<td width=45% align=center nowrap><input type='file' size='25' name='filename[\" + i + \"]' value='\" + varFile[d1] + \"'></td>\";\r\n";    echo "         data = data + \"<td width=10% nowrap align=right>&amp;nbsp;<strong><b>C</strong></b>omment:&amp;nbsp</td>\";\r\n";    echo "         data = data + \"<td width=40% nowrap><input type='text' size='40' name='filecomment[\" + i + \"]' value='\" + varComment[d1] + \"'></td>\";\r\n";    echo "         data = data + \"</tr>\";\r\n";    echo "      }\r\n";    echo "      data += \"</table>\";\r\n";    echo "      if (document.layers) {\r\n";    echo "         document.layers.cust.document.write(data);\r\n";    echo "         document.layers.cust.document.close();\r\n";    echo "      } else {\r\n";    echo "         if (document.all) {\r\n";    echo "            cust.innerHTML = data;\r\n";    echo "         }\r\n";    echo "      }\r\n";    echo "   } else {\r\n";    echo "         // error text?\r\n";    echo "   }\r\n";    echo "}\r\n";    echo "</script>\r\n";    echo "<form name=\"$form[name]\" enctype=\"multipart/form-data\" method=\"post\" action=\"$PHP_SELF\">\r\n";    echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"1\" width=\"600\">\r\n";    echo "    <tr>\r\n";    echo "        <td>Username</td>\r\n";    echo "        <td><input type=\"text\" size=\"40\" name=\"username\" value=\"$username\"></td>\r\n";    echo "    </tr>\r\n";    echo "</table>\r\n";    echo "<br>\r\n";    echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"1\" width=\"500\">\r\n";    echo "Number of uploads: <select name=\"number\" size=\"1\">\r\n";    for ($i = 2; $i <= $form[max]; $i++) {       if ($i == $form[start]) {           echo "        <option selected value=\"$i\">$i</option>\r\n";       }else{           echo "        <option value=\"$i\">$i</option>\r\n";       }    }    echo "</select>&amp;nbsp;<input type=\"button\" value=\"Update\" onclick=\"createForm($form[name].number.value);\">\r\n";    echo "</table>";    echo "<span id=\"cust\" style=\"position:relative;\"></span>\r\n";    echo "<br>\r\n";    echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"1\" width=\"600\">\r\n";    echo "    <tr>\r\n";    echo "        <input type=\"submit\" name=\"Upload\" value=\"Upload\">\r\n";    echo "        <input type=\"submit\" name=\"Clear\" value=\"Clear\">\r\n";    echo "    </tr>\r\n";    echo "</table>\r\n";    echo "</form>\r\n";    echo "\r\n";    echo "<script language=\"javascript\">createForm($form[start]);</script>\"\r\n";    echo "\r\n";}$iPath = "./upload/images/";$oPath = "./upload/other/";if ($Upload == "Upload") {   for ($i = 1; $i <= count($filename_name); $i++) {       if ($filename_size[$i] != 0) {           $typ = $filename_type[$i];           if (eregi("image", $typ) > 0) {               echo "<li><strong><b>$filename_name[$i]</b></strong> is succesfully uploaded to my server!</li><br>";               copy("$filename[$i]", "$iPath$filename_name[$i]") or die("Couldn't copy the file!");               $path = $iPath . $filename_name[$i] . ".txt";               $cfile = @fopen ($path, "a");               @fwrite ($cfile, "$username###$filename_name[$i]###$filecomment[$i]###$REMOTE_ADDR\r\n");               @fclose ($cfile);           }else{               echo "<li><strong><b>$filename_name[$i]</b></strong> is succesfully uploaded to my server!</li><br>";               copy("$filename[$i]", "$oPath$filename_name[$i]") or die("Couldn't copy the file!");               $path = $oPath . $filename_name[$i] . ".txt";               $cfile = @fopen ($path, "a");               @fwrite ($cfile, "$username###$filename_name[$i]###$filecomment[$i]###$REMOTE_ADDR\r\n");               @fclose ($cfile);           }       }   }}if (!isSet($number)) { $number = 5; }if (!isSet($username)) { $username = "Unknown"; }showForm($number, $username);?>

Erg simpel en zeer leuk om te implementeren!, wanneer je dit gebruikt stel me ff op de hoogte. Vind het namelijk erg leuk om te zien wat er met mijn spul gebeurd! :)

Greetz, Xtentic

Acties:
  • 0 Henk 'm!

Verwijderd

Ik heb met classes een timer in php gemaakt waarmee de parse time mee berekent kan worden. Het voordeel is dat deze in OOP is en dus meerdere objecten als teller gebruikt kunnen worden. Ik heb ook een pauze/stop functie er in gebouwd.

Dit is het eerste ding wat ik in OOP gemaakt heb, ik vind hem zelf wel handig.
PHP:
1
<?/*    Made by:    Julien Rentrop / julien@interned.com    Version:    0.5 (Seems to work ok)    Date:        17/03/2002        Description:    Use this class to figure out the parse time your code takes.        Create different instances if you want to get the parsetime of different parts of code.    You can also use the pausetime if you want to skip some code and add up parsetime    in a later set of code or just stop the timer and show the time it took in the end.*/class Timer{    var $BeginTime = 0; //Contains the start time    var $ParseTime = 0; //Stores the parse time when the timer has been paused    var $Paused = FALSE;        function Timer($start) //Constructor. Automatically start timing if $start is TRUE.    {        if ($start)        {            $this->BeginTime = $this->getTime();            $this->Paused = FALSE;        }        else            $this->Paused = TRUE;    }        function getTime() //The clock    {        $time = explode(" ", microtime());        return (double)$time[0] + (double)$time[1];    }        function pauseTimer() //Stop the clock    {        if (!$this->Paused)        {            $this->Paused = TRUE;            $this->ParseTime = $this->ParseTime + $this->getTime() - $this->BeginTime;        }    }        function startTimer() //Continue the clock    {        $this->Paused = FALSE;        $this->BeginTime = $this->getTime();    }        function getParseTime() //Get the time    {        if ($this->Paused)            return $this->ParseTime;        else            return $this->getTime() - $this->BeginTime + $this->ParseTime;    }}?>

Acties:
  • 0 Henk 'm!

Verwijderd

Script: VarNav 0.1 béta
Doel: Het browsen door een var (een var dus opdelen in meerdere pagina's)
Taal: Php of course ;)
PHP:
1
<?/* VarNav 0.1 béta door Markuz */$text = "blaat|blaat2|blaat3|blaat4"; // de text$explodeer = explode("|",$text); // exploderen op "|"$aantal = count($explodeer); // het aantal delen tellenif(!$pagina) {    $pagina = "1";}$vorige = $pagina - 1;if($vorige == "0" || $pagina == "") {    echo "< ";}else {    echo "<a href=\"$PHP_SELF?pagina=$vorige\"><</a> ";}for($x = 1; $x < $aantal + 1; $x++) {    if($x == "$aantal")     {        $streep = "";    }    else     {        $streep = "|";    }    if($x == "$pagina")     {        $b = "<b>";        $b2 = "</b>";    }    else     {        if($x != "$pagina")         {            $b = "";            $b2 = "";        }    }    echo "<a href=\"$PHP_SELF?pagina=" . $x . "\">" . $b . $x . $b2 . "</a> $streep ";     // laat de nummers zien, bijv: 1 | 2 | 3 enz.}$volgende = $pagina + 1;if($volgende - 1 == "$aantal") {    echo "> ";}else {    echo "<a href=\"$PHP_SELF?pagina=$volgende\">></a> ";}for($x = 1; $x < $aantal + 1; $x++) {    if($pagina == "$x")     {        echo "<p>" . $explodeer[$x - 1] . "</p>";    }}?>

<font color=red>indent@D2k</font>

Acties:
  • 0 Henk 'm!

Verwijderd

Script: Sleutel generator
Doel: Sleutel genereren
Taal: Php
PHP:
1
<?function sleutel($ptijd = 0) {    $uab = 57;    $lab = 48;    $mic = microtime();    $smic = substr($mic,1,2);    $emic = substr($mic,4,6);    mt_srand ((double)microtime() * 1000000);    $ch = (mt_rand() % ($uab-$lab)) + $lab;    $po = strpos($emic, chr($ch));    $emica = substr($emic, 0, $po);    $emicb = substr($emic, $po, strlen($emic));    $out = $emica.$smic.$emicb;$out = md5(crypt($out));    return $out;}?>

Deze heb ik niet zelf geschreven, wie wel, geen idee...

Maar deze is wel ongelofelijk random :)
<font color=red>indent@D2k</font>

Acties:
  • 0 Henk 'm!

  • Valium
  • Registratie: Oktober 1999
  • Laatst online: 27-09 09:35

Valium

- rustig maar -

Taal:Bash
Doel:Autocompilescript voor Debian GNU/Linux.
Uitleg:
Dit scriptje is een wrapper-script om een debian-systeem zeer comfortabel te kunnen voorzien van eigengecompileerde pakketten. Het script is alleen nuttig als de pakketten "pentium-builder" en "build-essential" geinstalleerd zijn.
Het zorgt ervoor dat je systeem nette pakketten heeft met toch voor jouw arch (i686, athlon e.d.) geoptimaliseerde code.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/bin/sh

case "$1" in
    install)
      if [ ! -x /tmp/debian-cast ]; then
          echo "Let op eventuele foutmeldingen en rapporteer die"
          echo "bij bugs.debian.org (build-dep en sourcebuild problemen)"
          echo "Afhankelijkheden wordt opgehaald."
          apt-get build-dep $2
          echo "Werkmap wordt gemaakt."
          mkdir /tmp/debian-cast
    else
        echo "Map bestaat nog."
    fi
        cd /tmp/debian-cast
    if [ ! -x /tmp/debian-cast/readytocompile ]; then
          echo "Broncode wordt opgehaald."
        apt-get source $2
          werkmap=`ls -A -l | grep drwx | awk '{print $9}' | head -n 1`
        if ls -A -l | grep drwx | awk '{print $9}'; then
          echo "Configuratie wordt aangepast."
          cd $werkmap
#       Dit leuke stukje vervangt in de changelog het versienummer door versienummer.owncompile
#       Hierdoor zie je dat het om een eigengebrouwen pakket gaat.
          mv /tmp/debian-cast/$werkmap/debian/changelog \
        /tmp/debian-cast/$werkmap/debian/changelog.old
          cat /tmp/debian-cast/$werkmap/debian/changelog.old | \
        sed 's/\(.*\)\(-\)\([0-9]*\))/\1\2\3.owncompile)/' > /tmp/debian-cast/$werkmap/debian/changelog
          rm /tmp/debian-cast/$werkmap/debian/changelog.old
          echo $werkmap > /tmp/debian-cast/readytocompile

        else
        echo "Ik kon geen werkmap vinden. Compileren afgebroken."
        exit 0
        fi
    fi
    echo ""
    echo "==============================================="
    echo -n "Te compileren pakket: "
    cat /tmp/debian-cast/readytocompile
    set | grep DEBIAN_BUILDARCH
    head -n 1 /tmp/debian-cast/$werkmap/debian/changelog
    echo "==============================================="
    sleep 2
#   Dit is de werkelijke opdracht om het pakket te compileren.
    debian/rules binary

    cd /tmp/debian-cast
    echo "Pakketten worden geinstalleerd."
    ls -A1 /tmp/debian-cast/*.deb
      if dpkg -i /tmp/debian-cast/*.deb; then
        echo "Installatie voltooid."
        mv /tmp/debian-cast/*.deb /var/cache/apt/archives/
        echo "Werkmap wordt verwijderd."
        cd /tmp
        rm -rf /tmp/debian-cast
          echo "klaar."
      else
        echo "Fout opgetreden bij installatie."
        echo "Ik verwijder de werkmap nog niet."
      fi
      ;;
    clean)
      rm -rf /tmp/debian-cast
      ;;
    *)
      echo "gebruik: cast install <pakketnaam>, cast clean."
      exit 1
      ;;
esac

Help mee met het vertalen van GNOME. | #nos op irc.tweakers.net voor directe hulp.


Acties:
  • 0 Henk 'm!

  • Juup
  • Registratie: Februari 2000
  • Niet online
Valium> Volgens my is dit geen bash script maar een gewoon shell script. Zie eerste regel van je script.

Een wappie is iemand die gevallen is voor de (jarenlange) Russische desinformatiecampagnes.
Wantrouwen en confirmation bias doen de rest.


Acties:
  • 0 Henk 'm!

  • Valium
  • Registratie: Oktober 1999
  • Laatst online: 27-09 09:35

Valium

- rustig maar -

Op woensdag 27 maart 2002 10:32 schreef Jaaap het volgende:
Valium> Volgens my is dit geen bash script maar een gewoon shell script. Zie eerste regel van je script.
Maar de meeste mensen gebruiken bash als shell, dus eigenlijk is het een soort van synoniem.
(sec heb je wel gelijk ja.)

Ik heb trouwens een nieuwe versie online staan: cast

Help mee met het vertalen van GNOME. | #nos op irc.tweakers.net voor directe hulp.


Acties:
  • 0 Henk 'm!

Verwijderd

Code = PHP
Doel = datum converten (verbeterd)
PHP:
1
<?function showdate($date) {  $maandarray = array("1"=>"januari","februari","maart","april","mei","juni","juli","augustus","september","october","november","december");  $dagarray = array("0"=>"zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag");  $cdate = date('w-j-n-Y', strtotime($date)); list($day, $dom, $month, $year) = split('-', $cdate);    return $dagarray[$day].', '.$dom.' '.$maandarray[$month].' '.$year; }?>

Aanroepen met
PHP:
1
<?$datum =&amp; showdate(date('Y-m-d'));print $datum;?>

Acties:
  • 0 Henk 'm!

Verwijderd

Op maandag 11 maart 2002 15:28 schreef pistole het volgende:
code:
1
2
3
function qfix(str)
  qfix=replace(str, "'", "'')
end function
Je bent een " vergeten, dus:
code:
1
  qfix=replace(str, "'", "''")

Acties:
  • 0 Henk 'm!

  • Juup
  • Registratie: Februari 2000
  • Niet online
Taal: Perl
Doel: Het berekenen van Pi met veel decimalen. Met het snelste algoritme bekend.
Usage: Saven als pi.pl, chmodden naar 755 (chmod 755 pi.pl) en runnen maar! Staat nu ingesteld op 10 iteraties, maar als je Math::BigFloat gebruikt kun je zoveel decimalen doorfietsen als je wilt (nog niet helemaal werkend met BigFloat).
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!perl -Tw
 
use strict;
#use Math::BigFloat;
 
#my $pi = Math::BigFloat->new("0.0");
#my $sixteenn = Math::BigFloat->new("16.0");
 
my $pi = 0;
my $sixteenn = 16;
for (my $i = 0; $i < 10; $i++)
{ my $eighti = 8*$i;
  my $tmp = 4/($eighti + 1);
  $tmp -= 2/($eighti + 4);
  $tmp -= 1/($eighti + 5);
  $tmp -= 1/($eighti + 6);
  $sixteenn /= 16;
  $tmp *= $sixteenn;
  $pi += $tmp;
  print "\$pi: $pi\n";
}
print "\n";

Een wappie is iemand die gevallen is voor de (jarenlange) Russische desinformatiecampagnes.
Wantrouwen en confirmation bias doen de rest.


Acties:
  • 0 Henk 'm!

  • Juup
  • Registratie: Februari 2000
  • Niet online
Zeer goede Perl scripts (very basic stuff) is te vinden op:
http://nms-cgi.sourceforge.net/ Bebaseerd op Matt's script archive maar dan goed.
Bijvoorbeeld:

Countdown script
Formmail
Guestbook
Random Image/Link/Text
Searchscript
Counter
Clock

Een wappie is iemand die gevallen is voor de (jarenlange) Russische desinformatiecampagnes.
Wantrouwen en confirmation bias doen de rest.


Acties:
  • 0 Henk 'm!

Verwijderd

Taal:Javascript
Doel:Getal afronden
Omsc:Rond een getal af. De variabele getal moet wel een string zijn.
code:
1
getal = (parseInt(getal.substring((getal.indexOf(".") + 1),(getal.indexOf(".") + 2))) >= 5)? (parseInt(getal.substring(0,getal.indexOf(".")))+1):getal.substring(0,getal.indexOf("."))

Pas geleden gemaakt voor de fun.....

Acties:
  • 0 Henk 'm!

  • RickN
  • Registratie: December 2001
  • Laatst online: 14-06 10:52
Op woensdag 27 maart 2002 16:00 schreef Jaaap het volgende:
Taal: Perl
Doel: Het berekenen van Pi met veel decimalen. Met het snelste algoritme bekend.
Usage: Saven als pi.pl, chmodden naar 755 (chmod 755 pi.pl) en runnen maar! Staat nu ingesteld op 10 iteraties, maar als je Math::BigFloat gebruikt kun je zoveel decimalen doorfietsen als je wilt (nog niet helemaal werkend met BigFloat).
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!perl -Tw
 
use strict;
#use Math::BigFloat;
 
#my $pi = Math::BigFloat->new("0.0");
#my $sixteenn = Math::BigFloat->new("16.0");
 
my $pi = 0;
my $sixteenn = 16;
for (my $i = 0; $i < 10; $i++)
{ my $eighti = 8*$i;
  my $tmp = 4/($eighti + 1);
  $tmp -= 2/($eighti + 4);
  $tmp -= 1/($eighti + 5);
  $tmp -= 1/($eighti + 6);
  $sixteenn /= 16;
  $tmp *= $sixteenn;
  $pi += $tmp;
  print "\$pi: $pi\n";
}
print "\n";
Dit is niet zo snel hoor, dit geeft je 1 of 2 extra correcte decimalen per iteratie. Er zijn series die VEEEEEEEEEEEEL sneller convergeren. Dit algoritme is vooral goed om het n-de cijfer in de hexadecimale representatie van Pi te berekenen, zonder alle voorafgaande cijfers te moeten berekenen. Maar ja, hexadecimale representatie is natuurlijk niet zo cool.

He who knows only his own side of the case knows little of that.


Acties:
  • 0 Henk 'm!

Verwijderd

Taal: ASP
Doel: Inloggen van mensen naar website via mooi login menu

Login1.asp (passwords zijn: TEST & TEST2 (denk aan hoofdletters!)
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<html>

<head>
<title>IIS</title>
</head>

<body bgcolor="#E6E6E6">
<p><form action="Login.asp">
      <font face="Verdana" color="#666666"><b>
      <select size="1" name="user">
      <option selected>&lt;.................Kies een account.................&gt;
      </option>
      <option value="Kees de Koning">Tester 1 (Admin.)</option>
      <option value="Tim Oskam">Tester 2 (Admin.)</option>
      </select></b></font>
<p>
      <font face="Verdana"><b><font color="#666666">
      <input type="password" name="pass" size="33"></font></b></font>     
</p>
<p>
      <font size="1" face="Verdana">
      <input type="checkbox" name="check" value="ok" style="float: left"> </font><span lang="en-us"><font size="2" face="Verdana">Password
opslaan</font></span></p>
<p>
      <button name="submit" type="submit" style="width: 185; height: 25">
 &nbsp;Inloggen! </p>
</form>
</body></html>

Login.asp
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<% 

'Gemaakt door de enige echte Bit.Neuker -> KC!

dim username
dim password
dim check
username = request.Form ("user")
password = request.Form ("pass")
check = request.form ("check")
fout = "&quot;kees&quot;"
userfout ="&quot;gek&quot;"
        if (username) = "<.................Kies een account.................>" then
            response.redirect ("error.html")
        end if
        
    
    if (username) = "Kees de Koning" AND (password) = "TEST" OR (username) = "Tim Oskam" AND (password) = "TEST2" then 
        
        
        
        if (check) = "ok" then
            response.write ("<body bgcolor='#E6E6E6'><p>&nbsp;</p><p align='center'><b><font face='Verdana' color='#FF0000'>Inloggen gelukt!</font></b></p><div align=center><center>     <table border=1 cellpadding=0 cellspacing=0 style='padding:0; border-collapse:collapse; border-left-style:outset; border-left-width:0; border-right-style:outset; border-right-width:0; border-top-style:outset; border-top-width:1; border-bottom-style:outset; border-bottom-width:1' collapse bordercolor=#111111 width=426 height=165 id=AutoNumber1>    <tr>               <td width=5 height=45 style='border-left-style:; border-left:1px solid #111111; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:none; border-bottom-width:medium' solid; border-left-width: 1; border-right-style: none; border-right-width: medium; border-top-style: solid; border-top-width: 1; border-bottom-style: none; border-bottom-width: medium bgcolor=#DDDAD5>    <p align=justify></td>              <td width=44 height=47 style='border-left-style:; border-left-style:none; border-left-width:medium; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:none; border-bottom-width:medium' none; border-left-width: medium; border-right-style: none; border-right-width: medium; border-top-style: solid; border-top-width: 1; border-bottom-style: none; border-bottom-width: medium bgcolor=#DDDAD5>  <p align=center>    [img]'error2.gif'[/img]</td>                <td width=351 height=47 style='border-left-style:; border-right:1px solid #111111; border-left-style:none; border-left-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:none; border-bottom-width:medium' none; border-left-width: medium; border-right-style: solid; border-right-width: 1; border-top-style: solid; border-top-width: 1; border-bottom-style: none; border-bottom-width: medium bgcolor=#DDDAD5>     <font face='Verdana' size='2'>&nbsp;Beste <B>" & username & " </b>het inloggen is gelukt...</font></td>    </tr>      <tr>      <td width='100%' height=17 style='border-left-style:; border-left:1px solid #111111; border-right:1px none #111111; border-top-style:none; border-top-width:medium; border-bottom-style:none; border-bottom-width:medium' bgcolor=#DDDAD5 colspan='3'>        <div style='border-right-style: solid; border-right-width: 1; padding-right: 4'>    <hr color='#999999' width='95%'>    </div>  </td>             </tr>    <tr>                         <td width=3 height=62 style='border-left-color:; border-left:1px solid #111111; border-right-style:none; border-right-width:medium; border-top-style:none; border-top-width:medium; ' #111111; border-left-width: 1; border-right-color: #111111; border-right-width: 1; border-top-style: none; border-top-width: medium bgcolor=#DDDAD5>        <font face='Verdana' size='2'>&nbsp; </font></td>                         <td width=417 height=62 style='border-left-color:; border-right:1px solid #111111; border-left-style:none; border-left-width:medium; border-top-style:none; border-top-width:medium; ' #111111; border-left-width: 1; border-right-color: #111111; border-right-width: 1; border-top-style: none; border-top-width: medium colspan=2 bgcolor=#DDDAD5>     <font face='Verdana' size='2'><b><font color='#FF0000'>Letop:</font><br>    </b>Om veiligheidsredenen is het niet gelukt om je password op te slaan...!</font></td>    </tr>    <tr>    <td width=3 height=19 style='border-left-color:; border-left-style:none; border-left-width:medium; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; ' #111111; border-left-width: 1; border-right-color: #111111; border-right-width: 1; border-top-style: none; border-top-width: medium>       </td>                         <td width=417 height=19 style='border-left-color:; border-left-style:none; border-left-width:medium; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; ' #111111; border-left-width: 1; border-right-color: #111111; border-right-width: 1; border-top-style: none; border-top-width: medium colspan=2>     &nbsp;</td>   </tr>    <tr> <td width=3 height=17 style='border-left-color:; border-left:1px solid #111111; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:solid; border-bottom-width:1' #111111; border-left-width: 1; border-right-color: #111111; border-right-width: 1; border-top-style: none; border-top-width: medium bgcolor=#DDDAD5>      &nbsp;</td>                       <td width=417 height=17 style='border-left-color:; border-right:1px solid #111111; border-left-style:none; border-left-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:solid; border-bottom-width:1' #111111; border-left-width: 1; border-right-color: #111111; border-right-width: 1; border-top-style: none; border-top-width: medium colspan=2 bgcolor=#DDDAD5>       <font size='2' face='Verdana'>Klik hier om   verder te gaan...</font></td>      </tr>  </table>  </center></div>")
        else
            response.write ("<body bgcolor='#E6E6E6'><p>&nbsp;</p><p align='center'><b><font face='Verdana' color='#FF0000'>Inloggen gelukt!</font></b></p><div align=center><center>       <table border=1 cellpadding=0 cellspacing=0 style='padding:0; border-collapse:collapse; border-left-style:outset; border-left-width:0; border-right-style:outset; border-right-width:0; border-top-style:outset; border-top-width:1; border-bottom-style:outset; border-bottom-width:1' collapse bordercolor=#111111 width=426 height=94 id=AutoNumber1>    <tr>                    <td width=5 height=1 style='border-left-style:; border-left:1px solid #111111; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:none; border-bottom-width:medium' solid; border-left-width: 1; border-right-style: none; border-right-width: medium; border-top-style: solid; border-top-width: 1; border-bottom-style: none; border-bottom-width: medium bgcolor=#DDDAD5>   <p align=justify></td>                  <td width=44 height=1 style='border-left-style:; border-left-style:none; border-left-width:medium; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:none; border-bottom-width:medium' none; border-left-width: medium; border-right-style: none; border-right-width: medium; border-top-style: solid; border-top-width: 1; border-bottom-style: none; border-bottom-width: medium bgcolor=#DDDAD5>   <p align=center>    [img]'error2.gif'[/img]</td>                    <td width=351 height=1 style='border-left-style:; border-right:1px solid #111111; border-left-style:none; border-left-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:none; border-bottom-width:medium' none; border-left-width: medium; border-right-style: solid; border-right-width: 1; border-top-style: solid; border-top-width: 1; border-bottom-style: none; border-bottom-width: medium bgcolor=#DDDAD5>      <font face='Verdana' size='2'>&nbsp;Beste <B>" & username & " </b> het inloggen is gelukt...</font></td>    </tr>     <tr>  <td width=3 height=19 style='border-left-color:; border-left-style:none; border-left-width:medium; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; ' #111111; border-left-width: 1; border-right-color: #111111; border-right-width: 1; border-top-style: none; border-top-width: medium>       </td>                         <td width=417 height=19 style='border-left-color:; border-left-style:none; border-left-width:medium; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; ' #111111; border-left-width: 1; border-right-color: #111111; border-right-width: 1; border-top-style: none; border-top-width: medium colspan=2>     &nbsp;</td>   </tr>    <tr>     <td width=3 height=12 style='border-left-color:; border-left:1px solid #111111; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:solid; border-bottom-width:1' #111111; border-left-width: 1; border-right-color: #111111; border-right-width: 1; border-top-style: none; border-top-width: medium bgcolor=#DDDAD5>      &nbsp;</td>                         <td width=417 height=12 style='border-left-color:; border-right:1px solid #111111; border-left-style:none; border-left-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:solid; border-bottom-width:1' #111111; border-left-width: 1; border-right-color: #111111; border-right-width: 1; border-top-style: none; border-top-width: medium colspan=2 bgcolor=#DDDAD5>         <font size='2' face='Verdana'>Klik hier om   verder te gaan...</font></td>      </tr>  </table>  </center></div>")
        end if
        

    Else
        response.write ("<body bgcolor='#E6E6E6'><p>&nbsp;</p><p align='center'><b><font face='Verdana' color='#FF0000'>Error 403:18 - Access denied (<font size='2'>MS IIS 5.1</font>)</font></b></p><div align=center><center>  <table border=1 cellpadding=0 cellspacing=0 style='border-style:outset; border-width:1; padding:0; border-collapse:collapse' collapse bordercolor=#111111 width=426 height=91 id=AutoNumber1>    <tr>         <td width=5 height=5 style='border-left-style:; border-left-style:solid; border-left-width:1; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:none; border-bottom-width:medium' solid; border-left-width: 1; border-right-style: none; border-right-width: medium; border-top-style: solid; border-top-width: 1; border-bottom-style: none; border-bottom-width: medium bgcolor=#DDDAD5>    <p align=justify></td>            <td width=44 height=51 style='border-left-style:; border-left-style:none; border-left-width:medium; border-right-style:none; border-right-width:medium; border-top-style:solid; border-top-width:1; border-bottom-style:none; border-bottom-width:medium' none; border-left-width: medium; border-right-style: none; border-right-width: medium; border-top-style: solid; border-top-width: 1; border-bottom-style: none; border-bottom-width: medium bgcolor=#DDDAD5>    <p align=center>    [img]'error2.gif'[/img]</td>            <td width=351 height=51 style='border-left-style:; border-left-style:none; border-left-width:medium; border-right-style:solid; border-right-width:1; border-top-style:solid; border-top-width:1; border-bottom-style:none; border-bottom-width:medium' none; border-left-width: medium; border-right-style: solid; border-right-width: 1; border-top-style: solid; border-top-width: 1; border-bottom-style: none; border-bottom-width: medium bgcolor=#DDDAD5> <font size=2 face=Verdana>Er is een verkeerd wachtwoord ingevuld om als <B>" & username & "</b> in te loggen...</font></td>    </tr>    <tr>              <td width=426 height=36 style='border-left-color:; border-left-style:solid; border-left-width:1; border-right-style:solid; border-right-width:1; border-top-style:none; border-top-width:medium; border-bottom-style:solid; border-bottom-width:1' #111111; border-left-width: 1; border-right-color: #111111; border-right-width: 1; border-top-style: none; border-top-width: medium colspan=3 bgcolor=#DDDAD5> <font size=2 face=Verdana>&nbsp;&nbsp;Klik op vorige om opnieuw je wachtwoord in te vullen...</font></td>    </tr>  </table>  </center></div>")
         end if
%>

Acties:
  • 0 Henk 'm!

  • ajvdvegt
  • Registratie: Maart 2000
  • Laatst online: 27-09 18:28
Op zaterdag 30 maart 2002 17:01 schreef Bit.neuker een stuk code.
Ik snap dat het niet de bedoeling is om hier mensen af te kraken, maar dat is wel zo ongeveer de meest inflexibele code die ik in tijden gezien heb. De wachtwoorden zijn niet makkelijk uitbreidbaar en ze staan kaal in de code.

Ook lijkt het me HEEEEEEEL handig om een .css bestandje te maken voor al je opmaakcodes ipv. die steeds te 'write'-en. :+
Hier kan je alle info over CSS vinden je nodig hebt, maar aangezien je de codes al kent lijkt het maken van een .css bestand me een kleine moeite.

I don't kill flies, but I like to mess with their minds. I hold them above globes. They freak out and yell "Whooa, I'm *way* too high." -- Bruce Baum


Acties:
  • 0 Henk 'm!

  • rookie
  • Registratie: Februari 2000
  • Niet online
PHP:
1
<?  function randompasswd() {    //A password generator thats creates pronounceable random words.    $VOWEL = array(1 => "A", 2 => "E", 3 => "I", 4 => "O", 5 => "U", 6 => "Y");    $vowel = array(1 => "a", 2 => "e", 3 => "i", 4 => "o", 5 => "u", 6 => "y");    $consonant = array(      1 => "b", 2 => "c", 3 => "d", 4 => "f", 5 => "g",       6 => "h", 7 => "j", 8 => "k", 9 => "l", 10=> "m",      11=> "n", 12=> "p", 13=> "q", 14=> "r", 15=> "s",      16=> "t", 17=> "v", 18=> "w", 19=> "x", 20=> "z"    );    return (string) $VOWEL[rand(1,5)].$consonant[rand(1,20)].$vowel[rand(1,5)].$consonant[rand(1,20)].$vowel[rand(1,5)].rand(1,9);  }?>

Acties:
  • 0 Henk 'm!

Verwijderd

Delphi/API

Verkrijg eigenaar en domein van een bestand.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'
function GetFileOwner(var Domain, Username: string): Boolean;
var
  FFileName: string;
  SecDescr: PSecurityDescriptor; 
  SizeNeeded, SizeNeeded2: DWORD; 
  OwnerSID: PSID;
  OwnerDefault: BOOL; 
  OwnerName, DomainName: PChar; 
  OwnerType: SID_NAME_USE; 
begin
  // het gaat om dit bestand
  FFileName := 'c:\bla.doc';

  GetFileOwner := False;
  GetMem(SecDescr, 1024); 
  GetMem(OwnerSID, SizeOf(PSID));
  GetMem(OwnerName, 1024); 
  GetMem(DomainName, 1024); 
  try 
    if not GetFileSecurity(PChar(FFileName),
    OWNER_SECURITY_INFORMATION, 
    SecDescr, 1024, SizeNeeded) then 
    Exit; 
    if not GetSecurityDescriptorOwner(SecDescr, 
    OwnerSID, OwnerDefault) then 
    Exit; 
    SizeNeeded  := 1024; 
    SizeNeeded2 := 1024; 
    if not LookupAccountSID(nil, OwnerSID, OwnerName, 
    SizeNeeded, DomainName, SizeNeeded2, OwnerType) then
    Exit; 
    Domain   := DomainName; 
    Username := OwnerName; 
  finally 
    FreeMem(SecDescr); 
    FreeMem(OwnerName); 
    FreeMem(DomainName);
  end; 
  GetFileOwner := True; 
end;

Acties:
  • 0 Henk 'm!

  • Orphix
  • Registratie: Februari 2000
  • Niet online
Taal: C#
Doel: Het genereren van een typische MD5 Hash van een gegeven string. De standaard hash functie in .NET retourneert byte-waardes. Deze functie vertaalt dit naar een leesbare (ASCII) string zoals vaak de bedoeling is (wachtwoorden, msn, etc).
code:
1
2
3
4
5
6
7
8
9
10
11
12
protected string HashMD5(string input)
{
    byte[] result = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(TextEncoding.GetBytes(input));
    string output = "";
                              
    for (int i = 0; i < result.Length; i++) 
    {           
        // convert from hexa-decimal to character
        output += (result[i]).ToString( "x2" );
    }
    return output;
}

Acties:
  • 0 Henk 'm!

Verwijderd

/me *

Ben ff twee daagjes bezig geweest een fatsoenlijke fotosite aan te maken in PHP/mySQL, en aangezien deze nu zelfs redelijk fatsoenlijk werkt kan ik 'em net zo goed hier posten. Ik doe er toch niet veel zinnigs mee. :Y).

Het doel van deze code is om een aantal mensen ('user') elk een eigen identiteit te geven in de database en per gebruiker foto's te kunnen neerzetten. Bezoekers kunnen via users.php een persoon selecteren en dan per persoon foto's bekijken. Administration gaat via admin.php (username/password protected natuurlijk).

Wat heb je nodig:
• bakkie met apache, mySQL en PHP
• SQL database ("real_database") met twee tabellen: 'foto' en 'user':
• twee SQL users, eentje ('anonymous') met SELECT access en eentje ("real_username") met SELECT, INSERT, UPDATE en DELETE access
• twee subdirectories in de PHP directory: fotos/ en fotos_thumbnails/ (hier worden de fotos'/thumbnails geplaatst)

real_username, real_database en real_passworde zijn gedefinieerd in login.php.

Database layout:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
mysql> DESCRIBE user;
+----------+-----------------+------+-----+---------+----------------+
| Field    | Type       | Null | Key | Default | Extra      |
+----------+-----------------+------+-----+---------+----------------+
| userID   | int(4) unsigned |  | PRI | NULL    | auto_increment |
| nick     | varchar(255)    |  | UNI |    |            |
| name     | varchar(255)    | YES  |     | NULL    |           |
| email    | varchar(255)    | YES  |     | NULL    |           |
| homepage | varchar(255)    | YES  |     | NULL    |           |
+----------+-----------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)

mysql> DESCRIBE foto;
+--------------+-----------------+------+-----+---------+----------------+
| Field   | Type        | Null | Key | Default | Extra      |
+--------------+-----------------+------+-----+---------+----------------+
| fotoID     | int(4) unsigned |    | PRI | NULL    | auto_increment |
| userID     | int(4) unsigned | YES  |     | NULL    |         |
| beschrijving | varchar(255)    | YES  | MUL | NULL    |           |
| nemer   | varchar(255)    | YES  |     | NULL    |            |
| path     | varchar(255)    |  |     |    |            |
| datum   | date        | YES  |     | NULL    |            |
+--------------+-----------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

mysql>

Code:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[rbultje@gizmo dutch]$ cat users.php
<?php
  include "script/page_setup.php";

  page_header("#dutch bezoekers");

  // Connecting, selecting database
  $link = mysql_connect("localhost", "anonymous")
    or die("Could not connect to MySQL");
  mysql_select_db("dutch")
    or die("Could not select dutch database");

  // get the paper table
  $query = "SELECT userID,nick
        FROM user ORDER BY nick";
  $result = mysql_query($query)
    or die("Query failed");

  // Printing results in HTML
  print "<h1>Users:</h1>";
  while ($line = mysql_fetch_row($result)) {
    // nick
    print "\t<a href=\"profile.php?user=$line[0]\">$line[1]</a><br>\n";
  }
  // Free results
  mysql_free_result($result);

  // Closing connection
  mysql_close($link);

  page_footer();
?>


code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
[rbultje@gizmo dutch]$ cat profile.php
<?php
  include "script/page_setup.php";

  page_header("Profiel");

  // Connecting, selecting database
  $link = mysql_connect("localhost", "anonymous")
    or die("Could not connect to MySQL");
  mysql_select_db("dutch")
    or die("Could not select groupware database");

  // get the paper table
  $query = "SELECT nick, name, email, homepage
        FROM user
        WHERE userID = $user";
  $result = mysql_query($query)
    or die("Query failed");

  // Printing results in HTML
  //print "<h1>Profile:</h1>";

  $line = mysql_fetch_row($result);

  print "<table border=\"0\" cellpadding=\"5\" cellspacing=\"2\" width=\"100%\" bgcolor=\"#f0f0f0\">\n\t<tr>\n\t\t<td>\n";

  //info
  print "\t<b>Nick: </b>$line[0]<br>\n";

  if ($line[1]!=null) {
    print "\t<b>Name: </b>$line[1]<br>\n";
  }
  if ($line[2]!=null) {
    print "\t<b>Email: </b><a href=\"mailto:$line[2]\">$line[2]</a><br>\n";
  }
  if ($line[3]!=null) {
    print "\t<b>Homepage: </b><a href=\"$line[3]\">$line[3]</a><br>\n";
  }

  print "\t\t</td>\n\t</tr>\n</table>\n<p>\n";

  // Free results
  mysql_free_result($result);

  // Foto's
  $query = "SELECT fotoID,path
        FROM foto
        WHERE foto.userID = $user";
  $result = mysql_query($query)
    or die("Query failed");

  while ($line = mysql_fetch_row($result)) {
    print "<a href=\"foto.php?foto=$line[0]\">";
    print "[img]\"fotos_thumbnails/$line[1]\">";
[/img]\n";
  }

  // Free result
  mysql_free_result($result);

  // Closing connection
  mysql_close($link);

  page_footer();
?>


code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
[rbultje@gizmo dutch]$ cat foto.php
<?php
  include "script/page_setup.php";

  page_header("Foto");

  // Connecting, selecting database
  $link = mysql_connect("localhost", "anonymous")
    or die("Could not connect to MySQL");
  mysql_select_db("dutch")
    or die("Could not select groupware database");

  // get the paper table
  $query = "SELECT user.nick,
             foto.beschrijving, foto.nemer,
             foto.datum, foto.path
        FROM user,foto
        WHERE user.userID = foto.userID AND
            foto.fotoID = $foto";
  $result = mysql_query($query)
    or die("Query failed");

  // Printing results in HTML
  //print "<h1>Foto:</h1>";

  $line = mysql_fetch_row($result);

  print "<table border=\"0\" cellpadding=\"5\" cellspacing=\"2\" width=\"100%\" bgcolor=\"#f0f0f0\">\n\t<tr>\n\t\t<td>\n";

  // subject
  print "\t<b>Wie: </b>$line[0]<br>\n";

  // beschrijving
  if ($line[1]!=null) {
    print "\t<b>Wat: </b>$line[1]<br>\n";
  }

  // nemer
  if ($line[2]!=null) {
    print "\t<b>Door: </b>$line[2]<br>\n";
  }

  // datum
  if ($line[3]!=null) {
    print "\t<b>Datum: </b>$line[3]<br>\n";
  }

  print "\t\t</td>\n\t</tr>\n</table>\n<p>\n";

  // foto
  print "[img]\"fotos/$line[4]\"[/img]\n";

  // Free results
  mysql_free_result($result);

  // Closing connection
  mysql_close($link);

  page_footer();
?>


code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
[rbultje@gizmo dutch]$ cat admin.php
<?php
  include "script/page_setup.php";
  include "login.php";

  function list_users()
  {
    // Connecting, selecting database
    $link = mysql_connect("localhost", "anonymous")
    or die("Could not connect to MySQL");
    mysql_select_db(real_database)
    or die("Could not select database");

    $query = "SELECT userID,nick
          FROM user ORDER BY nick";

    $result = mysql_query($query)
    or die("Query '$query' failed");

    // Printing results in HTML form language
    print "<select size=\"6\" name=\"userID\">\n";
    while ($line = mysql_fetch_row($result)) {
    print "<option value=\"$line[0]\">$line[1]</option>\n";
    }
    print "</select>\n";

    // close result
    mysql_free_result($result);

    // close session
    mysql_close($link);
  }

  function print_user($userID)
  {
    if ($userID)
    {
    // Connecting, selecting database
    $link = mysql_connect("localhost", "anonymous")
      or die("Could not connect to MySQL");
    mysql_select_db(real_database)
      or die("Could not select database");

    // get the paper table
    $query = "SELECT userID,nick,name,email,homepage
            FROM user WHERE userID = $userID";
    $result = mysql_query($query)
      or die("Query '$query' failed");

    $line = mysql_fetch_row($result);
    }

    print "<input type=\"hidden\" name=\"userID\" value=\"$userID\">\n";

    print "<table border=\"0\" cellpadding=\"5\" cellspacing=\"2\">\n";
    print "\t<tr>\n";
    print "\t\t<td><b>Nickname: </b></td>\n";
    print "\t\t<td><input type=\"text\" name=\"nickname\" value=\"$line[1]\"></td>\n";
    print "\t</tr>\n";
    print "\t<tr>\n";
    print "\t\t<td><b>Naam: </b></td>\n";
    print "\t\t<td><input type=\"text\" name=\"naam\"value=\"$line[2]\"></td>\n";
    print "\t</tr>\n";
    print "\t<tr>\n";
    print "\t\t<td><b>Email: </b></td>\n";
    print "\t\t<td><input type=\"text\" name=\"email\" value=\"$line[3]\"></td>\n";
    print "\t</tr>\n";
    print "\t<tr>\n";
    print "\t\t<td><b>Homepage: </b></td>\n";
    print "\t\t<td><input type=\"text\" name=\"homepage\" value=\"$line[4]\"></td>\n";
    print "\t</tr>\n";
    print "</table>\n";

    if ($userID)
    {
    // free result
    mysql_free_result($result);

    //close session
    mysql_close($link);
    }
  }

  function remove_user($userID)
  {
    include "login.php";

    // Connecting and selecting database
    $link = mysql_connect("localhost", real_username, real_password)
    or die("Could not connect to MySQL");
    mysql_select_db(real_database)
    or die("Could not select database");

    // selecteer foto's van die user en remove
    $query = "SELECT fotoID
          FROM foto
          WHERE userID = $userID";
    $result = mysql_query($query)
    or die("Query '$query' failed");
    while ($line = mysql_fetch_row($result))
    remove_foto($line[0]);
    mysql_free_result($result);

    $query = "DELETE FROM user
          WHERE userID = $userID";
    $result = mysql_query($query)
    or die("Query '$query' failed");
   print "User removed<p>\n";

    // close session
    mysql_close($link);
  }

  function add_user($nick,$name,$email,$homepage)
  {
    include "login.php";

    // Connecting and selecting database
    $link = mysql_connect("localhost", real_username, real_password)
    or die("Could not connect to MySQL");
    mysql_select_db(real_database)
    or die("Could not select database");

    $query = "INSERT INTO user
          VALUES(null,'$nick','$name','$email','$homepage')";
    $result = mysql_query($query)
    or die("Query '$query' failed");
    print "User added<p>\n";

    // close session
    mysql_close($link);
  }

  function modify_user($userID,$nick,$name,$email,$homepage)
  {
    include "login.php";

    // Connecting and selecting database
    $link = mysql_connect("localhost", real_username, real_password)
    or die("Could not connect to MySQL");
    mysql_select_db(real_database)
    or die("Could not select database");

    $query = "UPDATE user SET
          nick = '$nick',
          name = '$name',
          email = '$email',
          homepage = '$homepage'
          WHERE userID = $userID";
    $result = mysql_query($query)
    or die("Query '$query' failed");
    print "User modified<p>\n";

    // close session
    mysql_close($link);
  }

  function list_fotos($userID)
  {
    // Connecting and selecting database
    $link = mysql_connect("localhost", "anonymous")
    or die("Could not connect to MySQL");
    mysql_select_db(real_database)
    or die("Could not select database");

    $query = "SELECT fotoID,beschrijving
          FROM foto WHERE userID = $userID
          ORDER BY fotoID";

    $result = mysql_query($query)
    or die("Query '$query' failed");

    print "<input type=\"hidden\" name=\"userID\" value=\"$userID\">\n";

    // Printing results in HTML form language
    print "<select size=\"6\" name=\"fotoID\">\n";
    while ($line = mysql_fetch_row($result)) {
    print "<option value=\"$line[0]\">$line[1]</option>\n";
    }
    print "</select>\n";

    // close result
    mysql_free_result($result);

    // close session
    mysql_close($link);
  }

  function print_foto($fotoID, $userID)
  {
    if ($fotoID)
    {
    // Connecting, selecting database
    $link = mysql_connect("localhost", "anonymous")
      or die("Could not connect to MySQL");
    mysql_select_db(real_database)
      or die("Could not select database");

    // get the paper table
    $query = "SELECT fotoID,beschrijving,nemer,datum,path
            FROM foto WHERE fotoID = $fotoID";
    $result = mysql_query($query)
      or die("Query '$query' failed");

    $line = mysql_fetch_row($result);
    }

    if ($fotoID)
    print "<input type=\"hidden\" name=\"fotoID\" value=\"$fotoID\">\n";
    if ($userID)
    print "<input type=\"hidden\" name=\"userID\" value=\"$userID\">\n";

    print "<table border=\"0\" cellpadding=\"5\" cellspacing=\"2\">\n";

    if ($fotoID)
    {
    print "\t<tr>\n\t\t<td align=middle colspan=\"2\">\n";
    print "\t\t\t[img]\"fotos_thumbnails/$line[4]\">\n";
    print[/img]\n\t</tr>\n";
    }
    else
    {
    print "\t<tr>\n";
    print "\t\t<td><b>Foto: </b></td>\n";
    print "\t\t<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"100000\">\n";
    print "\t\t<td><input type=\"file\" name=\"imagefile\" accept=\"image/jpeg,jpg\">\n";
    print "\t</tr>\n";
    }

    print "\t<tr>\n";
    print "\t\t<td><b>Beschrijving: </b></td>\n";
    print "\t\t<td><input type=\"text\" name=\"beschrijving\" value=\"$line[1]\"></td>\n";
    print "\t</tr>\n";
    print "\t<tr>\n";
    print "\t\t<td><b>Nemer: </b></td>\n";
    print "\t\t<td><input type=\"text\" name=\"nemer\" value=\"$line[2]\"></td>\n";
    print "\t</tr>\n";
    print "\t<tr>\n";
    print "\t\t<td><b>Datum: </b></td>\n";
    print "\t\t<td><input type=\"text\" name=\"datum\" value=\"$line[3]\"></td>\n";
    print "\t</tr>\n";
    print "</table>\n";

    if ($fotoID)
    {
    // free result
    mysql_free_result($result);

    //close session
    mysql_close($link);
    }
  }

  function add_foto($userID,$beschrijving,$nemer,$datum,$imagefile)
  {
    include "login.php";

    // Connecting, selecting database
    $link = mysql_connect("localhost", real_username, real_password)
    or die("Could not connect to MySQL");
    mysql_select_db(real_database)
    or die("Could not select database");

    // figure out a nice filename
    $query = "SELECT nick
          FROM user
          WHERE userID = $userID";
    $result1 = mysql_query($query)
    or die("Query '$query' failed");
    $line1 = mysql_fetch_row($result1);
    $query = "SELECT count(*)
          FROM foto
          WHERE userID = $userID";
    $result2 = mysql_query($query)
    or die("Query '$query' failed");
    $line2 = mysql_fetch_row($result2);
    $line2[0]++;
    $filename = "$line1[0]_$line2[0].jpg";
    mysql_free_result($result1);
    mysql_free_result($result2);

    // write the image data
    move_uploaded_file($imagefile, "fotos/$filename");

    // now, create a thumbnail
    $size = getimagesize("fotos/$filename");
    $width = $size[0];
    $height = $size[1];
    if ($width > $height)
    {
    $height = $height * 100 / $width;
    $width = 100;
    }
    else
    {
    $width = $width * 100 / $height;
    $height = 100;
    }
    system("convert -size $widthx$height fotos/$filename fotos_thumbnails/$filename");

    // files exist, now add it to the database
    $query = "INSERT INTO foto
          VALUES(null,$userID,'$beschrijving','$nemer','$filename','$datum')";
    $result = mysql_query($query)
    or die("Query '$query' failed");
    print "Foto added<p>\n";

    mysql_close($link);
  }

  function modify_foto($fotoID,$beschrijving,$nemer,$datum)
  {
    include "login.php";

    // Connecting and selecting database
    $link = mysql_connect("localhost", real_username, real_password)
    or die("Could not connect to MySQL");
    mysql_select_db(real_database)
    or die("Could not select database");

    $query = "UPDATE foto SET
          beschrijving = '$beschrijving',
          nemer = '$nemer',
          datum = '$datum'
          WHERE fotoID = $fotoID";
    $result = mysql_query($query)
    or die("Query '$query' failed");
    print "User modified<p>\n";

    // close session
    mysql_close($link);
  }

  function remove_foto($fotoID)
  {
    include "login.php";

    // Connecting and selecting database
    $link = mysql_connect("localhost", real_username, real_password)
    or die("Could not connect to MySQL");
    mysql_select_db(real_database)
    or die("Could not select database");

    // selecteer foto's van die user en remove
    $query = "SELECT path
          FROM foto
          WHERE fotoID = $fotoID";
    $result = mysql_query($query)
    or die("Query '$query' failed");
    while ($line = mysql_fetch_row($result))
    {
    // remove the fotos in $path
    unlink("fotos_thumbnails/$path");
    unlink("fotos/$path");
    }
    mysql_free_result($result);

    $query = "DELETE FROM foto
          WHERE fotoID = $fotoID";
    $result = mysql_query($query)
    or die("Query '$query' failed");
    print "Foto removed<p>\n";

    // close session
    mysql_close($link);
  }

  if (!$password)
    $password = $HTTP_COOKIE_VARS["password"];
  if (!$username)
    $username = $HTTP_COOKIE_VARS["username"];

  if (!strcmp($action, "uitloggen"))
  {
    setcookie("username", "");
    $username = "";
    setcookie("password", "");
    $password = "";
  }

  if (strcmp($password, real_password) ||
    strcmp($username, real_username))
  {
    page_header("Admin interface log-in");

    // let the user log in
    print "<form action=\"admin.php\" method=\"post\">\n";

    print "<table border=\"0\" cellpadding=\"5\" cellspacing=\"2\">\n";
    print "\t<tr>\n";
    print "\t\t<td><b>Login: </b></td>\n";
    print "\t\t<td><input name=\"username\" type=\"text\" size=20></td>\n";
    print "\t</tr>\n";

    print "\t<tr>\n";
    print "\t\t<td><b>Password: </b></td>\n";
    print "\t\t<td><input name=\"password\" type=\"password\" size=20></td>\n";    print "\t</tr>\n";

    print "\t<tr>\n";
    print "\t\t<td colspan=\"2\"><input type=\"submit\" value=\"Login\"></td>\n";
    print "\t</tr>\n";
    print "</table>\n";

    print "</form>\n";
  }
  else
  {
    // set cookies
    setcookie("username", $username);
    setcookie("password", $password);

    page_header("Admin interface");

    print "<table border=\"0\" cellpadding=\"5\" cellspacing=\"2\" width=\"50%\">\n";
    print "\t<tr>\n";
    print "\t\t<td>\n";
    print "- <a href=\"admin.php?action=useradd\">User toevoegen</a><br>\n";
    print "- <a href=\"admin.php?action=usermod\">User wijzigen</a><br>\n";
    print "- <a href=\"admin.php?action=userdel\">User verwijderen</a>\n";
    print "<p>\n";
    print "- <a href=\"admin.php?action=fotoadd\">Foto toevoegen</a><br>\n";
    print "- <a href=\"admin.php?action=fotomod\">Foto wijzigen</a><br>\n";
    print "- <a href=\"admin.php?action=fotodel\">Foto verwijderen</a>\n";
    print "<p>\n";
    print "- <a href=\"admin.php?action=uitloggen\">Uitloggen</a>\n";
    print "\t\t</td>\n";
    print "\t</tr>\n";
    print "</table>\n<p>\n";

    if (!strcmp($action, "useradd"))
    {
    //print "User toevoegen\n";

    if ($nickname)
    {
      add_user($nickname,$naam,$email,$homepage);
    }

    print "<form action=\"admin.php?action=useradd\" method=\"post\">\n";
    print_user(0);
    print "<p>\n<input type=\"submit\" value=\"Voeg user toe\">\n";
    print "</form>\n";
    }
    else if (!strcmp($action, "usermod"))
    {
    //print "User wijzigen\n";

    if ($userID)
    {
      if ($nickname)
      {
        modify_user($userID,$nickname,$naam,$email,$homepage);
      }

      print "<form action=\"admin.php?action=usermod\" method=\"post\">\n";
      print_user($userID);
      print "<p>\n<input type=\"submit\" value=\"wijzig gebruiker\">\n";
      print "</form>\n";
    }
    else
    {
      print "<form action=\"admin.php?action=usermod\" method=\"post\">\n";
      list_users();
      print "<p>\n<input type=\"submit\" value=\"Wijzig user\">\n";
      print "</form>\n";
    }
    }
    else if (!strcmp($action, "userdel"))
    {
    //print "User verwijderen\n";

    if ($userID)
    {
      remove_user($userID);
    }

    print "<form action=\"admin.php?action=userdel\" method=\"post\">\n";
    list_users();
    print "<p>\n<input type=\"submit\" value=\"Verwijder user\">\n";
    print "</form>\n";
    }
    else if (!strcmp($action, "fotoadd"))
    {
    //print "Foto toevoegen\n";

    if ($userID)
    {
      if ($beschrijving)
      {
        add_foto($userID,$beschrijving,$nemer,$datum,$imagefile);
      }

      print "<form enctype=\"multipart/form-data\" action=\"admin.php?action=fotoadd\" method=\"post\">\n";
      print_foto(0,$userID);
      print "<p>\n<input type=\"submit\" value=\"Voeg foto toe\">\n";
      print "</form>\n";
    }
    else
    {
      print "<form action=\"admin.php?action=fotoadd\" method=\"post\">\n";
      list_users();
      print "<p>\n<input type=\"submit\" value=\"Selecteer user\">\n";
      print "</form>";
    }
    }
    else if (!strcmp($action, "fotomod"))
    {
    //print "Foto wijzigen\n";

    if ($fotoID)
    {
      if ($beschrijving)
      {
        modify_foto($fotoID,$beschrijving,$nemer,$datum);
      }

      print "<form action=\"admin.php?action=fotomod\" method=\"post\">\n";
      print_foto($fotoID,0);
      print "<p>\n<input type=\"submit\" value=\"Wijzig foto\">\n";
      print "</form>";
    }
    else if ($userID)
    {
      print "<form action=\"admin.php?action=fotomod\" method=\"post\">\n";
      list_fotos($userID);
      print "<p>\n<input type=\"submit\" value=\"Selecteer foto\">\n";
      print "</form>";
    }
    else
    {
      print "<form action=\"admin.php?action=fotomod\" method=\"post\">\n";
      list_users();
      print "<p>\n<input type=\"submit\" value=\"Selecteer user\">\n";
      print "</form>";
    }
    }
    else if (!strcmp($action, "fotodel"))
    {
    //print "Foto verwijderen\n";

    if ($fotoID)
    {
      remove_foto($fotoID);
    }
    if ($userID)
    {
      print "<form action=\"admin.php?action=fotodel\" method=\"post\">\n";
      list_fotos($userID);
      print "<p>\n<input type=\"submit\" value=\"Verwijder foto\">\n";
      print "</form>";
    }
    else
    {
      print "<form action=\"admin.php?action=fotodel\" method=\"post\">\n";
      list_users();
      print "<p>\n<input type=\"submit\" value=\"Selecteer user\">\n";
      print "</form>";
    }
    }
  }

  page_footer();
?>
[rbultje@gizmo dutch]$

login.php ziet er zo uit:
code:
1
2
3
4
5
<?php
define("real_password", "<password>");
define("real_username", "<username>");
define("real_database", "<database>");
?>

Misschien dat iemand anders er ook nog eens ideetjes uit kan halen. :).

D'r is vast nog heel veel aan te verbeteren (encrypted passwords, meer opties, fancy layout (plaatjes, tabellen, ...), iets zinnigers dan 'convert' (van ImageMagick) gebruiken om de plaatjes te resizen, fatsoenlijke error handling)... Maar op zich werkt het redelijk goed. :Y).

Acties:
  • 0 Henk 'm!

  • CmdrKeen
  • Registratie: Augustus 2000
  • Laatst online: 26-09 16:28

CmdrKeen

Krentenboltosti

Mijn code voor een ASP gastenboek - hoop dat iemand er wat aan heeft.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
<% @Language = "VBScript" %>
<% Option Explicit %>
<%

' Martin Huijgen www.huijgen.com
' Voor gebruik is een Access 97> database nodig met vijf tabellen:
' EntryID (Autonummering, Primaire sleutel); naam (tekst); email (tekst); site (tekst); tekst (memo); en datum (datum (maakt niet uit welke)).
' Account IUSR_[jouw-computer-naam-hier] moet lees- en schrijfrechten hebben.

%>

<HTML>

<%
' Verbinding maken met database

Dim rs, Conn, nw, naam, SQLstmt, email, site, Datum, tekst, LenTekst, kuizer, kuizetekst

Set rs = Server.CreateObject ("ADODB.Recordset")
Set Conn = Server.CreateObject ("ADODB.Connection")
Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("gastenboek.mdb")

' Tsjekke of de lezer op de new-entry link geklikt heeft
nw = Request.QueryString("nw")

' Tsjekke of dit een postback van het form is
naam = Request.Form("naam")

' Als dit een postback is, dan de db updaten
IF naam <> "" THEN
    email = Request.Form("email")
    site = Request.Form("site")
    tekst = Request.Form("tekst")

    ' Zorgen datter geen HTML in de entry zit door < en > te vervangen door [ en ]
    LenTekst = LEN(tekst)
    IF LenTekst > 999 THEN
        tekst = LEFT(tekst,999)
        LenTekst = 999
    END IF
    Dim newtxt(999)
    FOR kuizer = 1 to LenTekst
        newtxt(kuizer)=mid(tekst,kuizer,1)
        if newtxt(kuizer)="<" THEN newtxt(kuizer)="["
        if newtxt(kuizer)=">" THEN newtxt(kuizer)="]"
        kuizetekst = kuizetekst & newtxt(kuizer)
    NEXT
    Datum = MediumDate(Date)

    SQLstmt = "INSERT INTO entries (naam, email, site, tekst, datum) VALUES ('" & naam & "', '" & email & "', '" & site & "', '" & kuizetekst & "', #" & datum & "#)"
    Conn.Execute(SQLstmt)

END IF

%>

<H1>Gastenboek</H1>
<% IF nw="" THEN %>
    <A HREF = gastenboek.asp?nw=jah>Schrijf een verhaaltje in mn gastenboek</A><BR>
<% END IF

' Formulier
IF nw = "jah" THEN
    %>
    <FORM METHOD="POST" ACTION="gastenboek.asp">
    <TABLE WIDTH = 200 BORDER = 0>
        <TR>
            <TD>
                Naam:
            </TD>
            <TD>
                <INPUT TYPE="text" NAME="naam" SIZE="30">
            </TD>
        </TR>
        <TR>
            <TD>
                Email:
            </TD>
            <TD>
                <INPUT TYPE="text" NAME="email" SIZE="30">
            </TD>
        </TR>
        <TR>
            <TD>
                Site:
            </TD>
            <TD>
                <INPUT TYPE="text" NAME="site" SIZE="30">
            </TD>
        </TR>
        <TR>
            <TD COLSPAN = 2>
                <TEXTAREA NAME="tekst" ROWS=6 COLS=30></TEXTAREA>
            </TD>
        </TR>
        <TR>
            <TD>
                <FONT SIZE = 1>
                    Gebruik geen HTML-tags..
                </FONT>
            </TD>
            <TD ALIGN = Right>
                <INPUT TYPE="submit" Name = "submit" Value="Ok!">
            </TD>
        </TR>
    </TABLE>
    </FORM>
    <%
END IF

' Inhoud van de db op het scherm dumpen
%><P><%
SQLstmt = "SELECT * FROM entries ORDER BY datum Desc"
rs.OPEN SQLstmt, Conn
DO WHILE NOT rs.EOF
    naam = rs("naam")
    IF naam = "" THEN naam = "Anoniem"
    naam = naam & "<BR>"
    email = rs("email")
    IF email<>"" THEN email = email & "<BR>"
    site = rs("site")
    IF site<>"" THEN site = site & "<BR>"
    datum = rs("datum")
    tekst = rs("tekst")
    %>
    <B><%=naam%></B>
    <%=email%>
    <%=site%>
    <%=datum%>
    <BR>----------------------<BR>
    <% tekst=Replace(tekst,vbCrLf,"<br>")%>
    <%=tekst%>
    <HR>
    <%
    rs.MOVENEXT
LOOP
%>

<%
rs.close
set rs=nothing
set Conn=nothing
%>

<%
Function MediumDate (str)
    Dim aDay
    Dim aMonth
    Dim aYear

    aDay = Day(str)
    aMonth = MonthName(Month(str),True)

    IF aMonth = "mrt" THEN
        aMonth = "mar"
    END IF
    IF aMonth = "mei" THEN
        aMonth = "may"
    END IF
    IF aMonth = "okt" THEN
        aMonth = "oct"
    END IF


    aYear = Year(str)

    MediumDate = aDay & "-" & aMonth & "-" & aYear
End Function
%>

Bloed, zweet & koffie


Acties:
  • 0 Henk 'm!

  • Tomatoman
  • Registratie: November 2000
  • Laatst online: 27-09 15:22

Tomatoman

Fulltime prutser

Taal: Delphi
Doel: screenshot maken van de hele desktop of van één van de aangesloten monitors.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
interface

{ retrieve extents of the entire desktop - all monitors together in their
  relative positions }
procedure GetDesktopScreenshot(Image: TImage);

{ retrieve the desktop extents of the indicated monitor }
procedure GetMonitorScreenshot(Image: TImage; Monitor: TMonitor);

implementation

procedure GetDesktopScreenshot(Image: TImage);
begin
  GetMonitorScreenshot(Image, nil);
end;

procedure GetMonitorScreenshot(Image: TImage; Monitor: TMonitor);
var
  Canvas: TCanvas;
  SrcRect, DestRect: TRect;
begin
  if Monitor = nil then
    {retrieve extents of the entire desktop - all monitors together in their
     relative positions}
    with Screen do
    begin
    SrcRect := Rect(DesktopLeft, DesktopTop,
                DesktopLeft + DesktopWidth, DesktopTop + DesktopHeight);
    DestRect := Rect(0, 0, DesktopWidth, DesktopHeight);
    end
  else
    {retrieve the desktop extents of the indicated monitor}
    with Monitor do
    begin
    SrcRect := Rect(Left, Top, Left + Width, Top + Height);
    DestRect := Rect(0, 0, Width, Height);
    end;

  Canvas := TCanvas.Create;
  try
    {clear current image}
    Image.Picture.Bitmap.Width := 0;
    Image.Picture.Bitmap.Height := 0;

    Canvas.Handle := GetDC(0);    // retrieve device context of desktop
    Image.Picture.Bitmap.Width := DestRect.Right;
    Image.Picture.Bitmap.Height := DestRect.Bottom;
    Image.Width := DestRect.Right;
    Image.Height := DestRect.Bottom;
    Image.Canvas.CopyMode := srcCopy;
    {paint desktop on canvas of Image}
    Image.Canvas.CopyRect(DestRect, Canvas, SrcRect);
  finally
    Canvas.Free;
  end;
end;

Een goede grap mag vrienden kosten.


Acties:
  • 0 Henk 'm!

  • me1299
  • Registratie: Maart 2000
  • Laatst online: 11:26

me1299

$ondertitel

Taal: PHP

Doel: Handige kleine data conversie functie :Y)
PHP:
1
<?function dmj($datetime) {    return substr($datetime, 8, 2) . "-" . substr($datetime, 5, 2) . "-" . substr($datetime, 0, 4);}function hm($datetime) {    return substr($datetime, 11, 5);}function jmd($date) {    list($day, $month, $year) = split( '[/.-]', $date );    if(checkdate($month, $day, $year)) {        return date("Y-m-d", mktime(0, 0, 0, $month, $day, $year));    }    else {         return "0000-00-00"; }}?>

Het maakt eigenlijk niet uit wat je bewuste geest doet, omdat je onderbewuste automatisch precies dat doet wat het moet doen


Acties:
  • 0 Henk 'm!

  • Vampier
  • Registratie: Februari 2001
  • Laatst online: 20-04-2015

Vampier

poke-1,170

CSV bestand (punt komma gescheiden) naar Table (asp/jscript)
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function ReadCSV(fileName){

var i=0
var InString
var SplitStringArray

  var objFSO         = Server.CreateObject("Scripting.FileSystemObject");
  objTextStream  = objFSO.OpenTextFile(fileName,1,0);

Response.write ('<table border="1">')
while (objTextStream.AtEndOfStream!=true)
  {
    InString=objTextStream.readLine()
    SplitStringArray = InString.split(';');
    Response.write ('<tr>')
    for (i=0; i<SplitStringArray.length; i++ )
    {
        Response.write ('<td>'+SplitStringArray[i]+'</td>')
    }
    Response.write ('</tr>')
  }

objTextStream.Close()
objFSO=null
Response.write ('</table>')

}

Acties:
  • 0 Henk 'm!

  • Baxlash
  • Registratie: Juni 2000
  • Niet online

Baxlash

Its a boy Genius!

Taal: PHP
Doel: SMS sturen
PHP:
1
<?//$bericht = "test";//$nummer = "0031612345678";//* Session - Get the smsid! *\\$post = "GET http://www5.cp1.campoints.net/CMPT/---guest---/001/105/0/cy=XX,La=TR,option=/DE/001//user/menu.php?page=sms HTTP/1.0\nHost: www5.cp1.campoints.net\n\n";$remote = fsockopen("www5.cp1.campoints.net", 80, &amp;$errno, &amp;$errstr, 30);if (!$remote) die("Host not available.");fputs($remote, $post);while ((!feof($remote)) OR (!$smsid))     {     $getreply = fgets($remote,120);    if (eregi("smsID",$getreply)) $smsid = $getreply;    }fclose($remote);$smsid = trim(str_replace(">","",str_replace("'","",str_replace('<form method="post" action="menu.php?page=sms"><input type=hidden name=smsID value=','',$smsid))));//* Session - Send the sms! *\\$content = "what=SEND_SMS&amp;smsID=$smsid&amp;smsBody=".urlencode($bericht)."&amp;smsNummer=".$nummer."&amp;Submit=absenden";$content_length = strlen($content);$post ="POST http://www5.cp1.campoints.net/CMPT/---guest---/001/105/0/cy=XX,La=TR,option=/DE/001//user/menu.php?page=sms HTTP/1.0\nContent-Type: application/x-www-form-urlencoded\nHost: www5.cp1.campoints.net\nContent-Length: $content_length\n\n$content";$remote = fsockopen("www5.cp1.campoints.net", 80, &amp;$errno, &amp;$errstr, 30);if (!$remote) die("Host not available.");fputs($remote, $post);while (!feof($remote))     {     if (eregi("Die SMS wurde erfolgreich versand!",fgets($remote,120))) $smssend = true;    }fclose($remote);if ($smssend == true) { echo "Sms is verstuurd."; } else { echo "Fout bij het versturen van sms!"; }?>

Acties:
  • 0 Henk 'm!

  • Choller
  • Registratie: Juli 2001
  • Laatst online: 22-05-2024
Op maandag 06 mei 2002 17:12 schreef rolandketel het volgende:
Taal: PHP
Doel: SMS sturen
[phpcode[/php]
|:(

Nevermind, it works.

Acties:
  • 0 Henk 'm!

  • Baxlash
  • Registratie: Juni 2000
  • Niet online

Baxlash

Its a boy Genius!

Op maandag 06 mei 2002 17:53 schreef Choller het volgende:

[..]

Fout bij het versturen van sms! ......
Hier werkt het ok, dus probeer zelf ook nog eens wat, zoek wat het kan zijn :D

Acties:
  • 0 Henk 'm!

  • smaij
  • Registratie: November 2000
  • Laatst online: 28-09 23:03
Op maandag 06 mei 2002 17:55 schreef rolandketel het volgende:

[..]

Hier werkt het ok, dus probeer zelf ook nog eens wat, zoek wat het kan zijn :D
Bij mij werkt het ook.. en ik weet zeker dat heeeel veel mensen hiervan gebruik gaan maken :)

Acties:
  • 0 Henk 'm!

  • martinvw
  • Registratie: Februari 2002
  • Laatst online: 20-08 20:35
FF een vraagje zijn er mensen die dat sms script nog steeds gebuiken want bij mij lijkt het niet meer* het werken. Ik krijg telkens een:
code:
1
Fatal error: Maximum execution time of 15 seconds exceeded in /www/wwworg/***/html/ls/smsen.php on line 12

en dat is de regel waarin de socket wordt uitgelezen:
PHP:
1
<?..knip..while ((!feof($remote)) OR (!$smsid))    {     $getreply = fgets($remote,120); //dit is de probleem regel    if (eregi("smsID",$getreply)) $smsid = $getreply;    }fclose($remote);..knip..?>

* hij heeft dus wel enige tijd succesvol gewerkt.

Acties:
  • 0 Henk 'm!

  • Limhes
  • Registratie: Oktober 2001
  • Laatst online: 28-09 17:41
Op woensdag 24 april 2002 20:50 schreef Orphix het volgende:
Taal: C#
Doel: Het genereren van een typische MD5 Hash van een gegeven string. De standaard hash functie in .NET retourneert byte-waardes. Deze functie vertaalt dit naar een leesbare (ASCII) string zoals vaak de bedoeling is (wachtwoorden, msn, etc).
code:
1
2
3
4
5
6
7
8
9
10
11
12
protected string HashMD5(string input)
{
    byte[] result = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(TextEncoding.GetBytes(input));
    string output = "";
                              
    for (int i = 0; i < result.Length; i++) 
    {           
        // convert from hexa-decimal to character
        output += (result[i]).ToString( "x2" );
    }
    return output;
}
kan makkelijker:
code:
1
2
3
using System.Web.Security;
...
String sFromMD5 = FormsAuthentication.HashPasswordForStoringInConfigFile(sToMD5, "md5");

Acties:
  • 0 Henk 'm!

  • whoami
  • Registratie: December 2000
  • Laatst online: 11:19
toepassing = deze berekening wordt veel gebruikt in encryptie algoritmes. Natuurlijk is int64 veel te klein om een leuke waarde voor encryptie in te stoppen, maar het skelet van de code blijft gelijk als je hier je eigen bignumber-class voor gebruikt. Je hebt dan wel een algoritme nodig dat efficient de mod van een getal van je eigen bignumber type uitrekend, en om dat te doen staat hieronder een bignumber-mod algoritme.
ach leuk, dit zien wij nu toevallig in wiskunde ...
verdomd niet eenvoudig. 'k Weet wel dat twee belgen een nieuwe encryptietechniek Rijndaal (ESA) hebben die gebaseerd is daarop en die beter is dan de vorige (RSA)

https://fgheysels.github.io/


Acties:
  • 0 Henk 'm!

  • Juup
  • Registratie: Februari 2000
  • Niet online
Op zaterdag 25 mei 2002 15:50 schreef whoami het volgende:
'k Weet wel dat twee belgen een nieuwe encryptietechniek Rijndaal (ESA) hebben die gebaseerd is daarop en die beter is dan de vorige (RSA)
Rijndael met een 'e'.

Een wappie is iemand die gevallen is voor de (jarenlange) Russische desinformatiecampagnes.
Wantrouwen en confirmation bias doen de rest.


Acties:
  • 0 Henk 'm!

  • Feyd-Rautha
  • Registratie: November 2001
  • Laatst online: 02-08 23:34
als "project" voor school heb ik eens een e-commerce site moeten maken met winkelkarretje, banners, ... alles erop en eraan. Deze kun je namelijk bekijken op volgende URL:

user.domaindlx.com/FlandersFoodDelivery/index.asp

Zelf ben ik trots op volgende code om artikelen toe te voegen in de winkelkar in ASP:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
for each Item in Request.Form       ' alle aantalvakjes van het form ophalen
    itmAantal = server.HTMLEncode(Request.Form(Item))
            
                        
    if itmAantal <> "" and isnumeric(itmAantal) and _
        itmAantal > "0" and itmAantal <> "Toevoegen" then
            
        tabel = split(Item, "_")   ' alle onderdelen van de naam scheiden
                                    ' tabel(0) is de tekst 'ATL'
        categorie = tabel(1)        
        product   = tabel(2)
        aantal    = cdbl(itmAantal)
            
          ' we gebruiken een dictionary om alle goederen op te slaan in de winkelkar.  
        ' De dictionary gebruikt een index (key) + een waarde
        ' 
        ' Key = SoortID + ProductID
        ' Waarde = aantal
        
        sleutel = categorie & "_" & product
        waarde  = aantal
            
        
        if karretje.Exists(sleutel) then ' als dit product reeds in het karretje zit,
                                        ' tel dan het aantal erbij op
            karretje(sleutel)  = karretje(sleutel) + cdbl(waarde )
        else
            karretje.Add sleutel, cdbl(waarde)      ' anders, voeg het product toe
        end if  
            
            
            
    end if  
next

... zelf met gebruik te maken van analytische codes 8-)

I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration. I will face my fear. I will permit it to pass over me and through me. Where the fear has gone there will be nothing. Only I will remain.


Acties:
  • 0 Henk 'm!

  • wasigh
  • Registratie: Januari 2001
  • Niet online

wasigh

wasigh.blogspot.com

Topicstarter
Bekijk ook even www.codebase.nl :)

Acties:
  • 0 Henk 'm!

Verwijderd

*schopje*
Op maandag 06 mei 2002 17:12 schreef Baxlash het volgende:
Taal: PHP
Doel: SMS sturen
Ik zie hetvolgende stukje code al aankomen waarbij de sms code ietsje veranderd is... >:)
PHP:
1
<?while (X != 1000) {    <de sms code hier> X++;}?>

Acties:
  • 0 Henk 'm!

  • HGM
  • Registratie: April 2000
  • Niet online

HGM

Op zondag 26 mei 2002 12:27 schreef wasigh het volgende:
Bekijk ook even www.codebase.nl :)
;)

Acties:
  • 0 Henk 'm!

  • ACM
  • Registratie: Januari 2000
  • Niet online

ACM

Software Architect

Werkt hier

right :)
Pagina: 1 2 Laatste

Dit topic is gesloten.