Just some notes I've made about misc computing stuff... I refer to these notes at work when I need to do something I haven't done for ages and can't remember how to do it. Pretty random stuff, but might be of some use to somebody.
Back
Can't connect to mysql with newly created user
I was creating a new user with a *wrong* statement like this:
GRANT ALL ON my_db_name TO 'myuser'@'localhost' IDENTIFIED BY 'mypass';
The user appeared to create successfully but when trying to connect I was getting access denied errors.
To get it working you need to put a ".*" after the database name:
GRANT ALL ON my_db_name.* TO 'myuser'@'localhost' IDENTIFIED BY 'mypass';
Thunderbird displays serif font in bulleted lists even when the main body is sans-serif
You have to change the type of the "proportional" font. I wasn't sure what that meant but it's the font used in bullet lists (and probably other places).
1. Tools -> Options
2. Select the "Display" tab
3. Select the "Formatting" sub-tab
4. Click the "fonts" button
5. Set your proportional font to "Serif"
6. Make sure your serif font is the font you want to use be default as the body text in emails
Errors like /bin/sh: line 1: 29662 File size limit exceeded/path/to/my-script.php
The php error log has probably grown too big, so errors/warnings the php script can't be written to the log.
How to log in as apache if you can't
If when you do:
su apache
you get "This account is currently not available." then it's probably because that account doesn't have a shell.
You can get around this with:
su -s /bin/bash apache
(or use the shell of your choice)
How to simulate a key press using vbscript
The next line sends an "a" character:
CreateObject("WScript.Shell").SendKeys "a"
Running MS-DOS commands without displaying a window (vbscript)
This actually does work as a way of running a command (for example, as a Scheduled Task), without displaying that annoying MS-DOS command window at all (not even for a second).
Create this very short vbscript and name it something like "my_script.vbs". You can then double-click that script to run it without displaying an output window or you can add that script directly to Task Scheduler.
The script should look like this:
--- start of script ---
' Command to run:
cmd = "c:mycommand.exe arg1 arg2"
' Run the command. The "0" makes the command run in a hidden window.
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run cmd, 0
--- end of script ---
Setting up per-user access on vsftpd
You need to use the user_config_dir config option in your vsftpd.conf file (which is probably in /etc/vsftpd).
1. Create a dir where you can put user config files (for example /etc/vsftpd/user_configs/).
2. Add the line "user_config_dir=/etc/vsftpd/user_conf/" somewhere in your vsftpd.conf file (I added it at the end but probably it would work anywhere).
3. For EVERY user that needs to use the ftp server, there now needs to be a file matching their username in the user config dir. So if "john" used to log in via ftp, now you need to set up the file "/etc/vsftpd/user_configs/john". It can contain one or more of the config options from your main vsftpd.conf (although not all options are supported on a per-user level - see man pages).
4. If you want users to have the "default" ftp options, make their config file a symbolic li
nk to the main vsftpd.conf. For example, if we want the user "john" to have the default actions, make a symbolic link to /etc/vsftpd/vsftpd.conf called /etc/vsftpd/user_configs/john. If there's no config file or symbolic link called "john" in the user config dir then then john will get an error when he tries to connect.
5. Restart vsftpd for the settings to take effect:
/etc/init.d/vsftpd reload
PHP HTTP authentication example
http://www.sitepoint.com/article/http-authentication-php/2
Postgres varchar to int
You have to use an intermediate cast:
SELECT my_numeric_string::text::int FROM my_table;
Running MS-DOS commands in the background
You can use the "start" command like this:
start /B my_command
Javascript blocking keypresses for certain characters
http://javascript.internet.com/forms/block-press-script.html
(not sure if the numbers bit works on Safari)
Sending images by url (not inline) with Thunderbird
1. Click insert image
2. Enter the url of the image
3. Click Advanced Edit
4. Add an attribute called "moz-do-not-send" with a value of "true".
The image in the email will then reference it's web location rather than being sent inline, which is Thunderbird's default.
Recursive postgres function for returning parents folders
The line
path := '''';
is very important because if you concat a null with a string you get an empty string, so be sure to initialise 'path' with an empty string.
CREATE OR REPLACE FUNCTION getParents(oid) RETURNS VARCHAR AS 'DECLARE
folder_oid ALIAS FOR $1;
path varchar(255);
itemrecord RECORD;
BEGIN
path := '''';
SELECT D.* INTO itemrecord FROM folder D WHERE oid = folder_oid;
path := (path || itemrecord.name);
IF itemrecord.parent_oid IS NOT NULL THEN
path := (getParents(itemrecord.parent_oid) || '' -> '' || path);
RETURN path;
ELSE
RETURN path;
END IF;
END' LANGUAGE 'plpgsql';
SELECT getParents(22990716);
Create an empty test file on Linux
This creates a 3gig file called myfile.
dd if=/dev/zero of=myfile bs=1M count=3072
Postgres error: language "plpgsql" does not exist
You need to activate the language plpgsql for the database you are working with. This can be done using the postgres command line tool createlang:
createlang --dbname=my_database --username=postgres plpgsql
Another way to cascade deletes on a single table in Postgres
CREATE OR REPLACE FUNCTION test_del() RETURNS trigger AS
'BEGIN
DELETE FROM test WHERE parent_test_oid = OLD.OID;
RETURN OLD;
END;'
LANGUAGE plpgsql;
CREATE TRIGGER test_del_trig BEFORE DELETE ON test FOR EACH ROW EXECUTE PROCEDURE test_del();
Postgres - Cascading delete on same table
I normally do cascading delete stuff with Postgres Rules but I had trouble with rules when the cascading delete was to delete from the same table. Here is a way around it. There might be better wasy but this does do the job.
1. Create the table:
CREATE TABLE test (
name VARCHAR(20),
parent_test_oid OID);
2. Create a unique index on the oid of the table:
CREATE UNIQUE INDEX test_oid ON test (oid);
3. Add a constraint to the table:
ALTER TABLE test ADD CONSTRAINT fk_parent_test_oid FOREIGN KEY (parent_test_oid) REFERENCES test (oid) ON DELETE CASCADE;
4. It should now be working. Create a parent record and some child records, then delete the parent record. The child records should automatically be deleted too.
Putty problem - Unable to use key file (SSH1 private key)
If you get this message and you have already set up the SSH keys correctly, make sure that Putty is set to use the correct SSH version (1 or 2). If it's using SSH 2 and the the keys you have set up are for SSH 1 then the automatic authentication wont work and you will get the message Unable to use key file. You can change the type of SSH Putty uses in the program options for each saved session.
Postgres views
Good explanation at: http://supportweb.cs.bham.ac.uk/documentation/postgres/manual/sql-createview.html
CREATE VIEW kinds AS
SELECT *
FROM films
WHERE kind = 'Comedy';
SELECT * FROM kinds;
Postgres functions
Good example at: http://jamesthornton.com/postgres/7.0/programmer/xfunc.htm
create function TP1 (int4, float8) returns int4
as 'update BANK set balance = BANK.balance - $2
where BANK.acctountno = $1
select(x = 1)'
language 'sql';
Postgres CASE conditional statement
Good explanation at: http://www.php-editors.com/postgres_manual/p_functions-conditional.html
SELECT a,
CASE
WHEN a=1 THEN 'one'
WHEN a=2 THEN 'two'
ELSE 'other'
END
FROM test;
a | case
---+-------
1 | one
2 | two
3 | other
Postgres auto-delete rule example
If you have a parent table and a child table with foreign keys in it referring to the parent table, you can set up a rule like this to delete the child recrods of a particular parent record if the parent is deleted:
CREATE RULE parent_del AS ON DELETE TO parent DO DELETE FROM child WHERE child.parent_oid = OLD.oid;
Note that the entity OLD refers to the row being deleted.
Putting quote marks or apostrophes in input boxes or javascript
Firstly, make sure the string with the quotes or apostrophes is enclosed in double-quotes, not apostrophes. Not sure why this should make a difference but it does. This applies whether the string is going into a javascript variable or the value attribute of an input element. The quotes and apostrophes should then be replaced by their html codes (ampersand followed by by a code). The php function htmlentities does this nicely.
PHP console output codes
Clear the screen:
print("x0C")
Clear the current line:
print("x0D");
Backspace:
print("x08");
More codes here:
http://thalia.spec.gmu.edu/~pparis/classes/notes_101/node24.html
Timing a postgres query
Toggle timing in psql:
\timing
Or for more detail and a query breakdown:
EXPLAIN ANALYZE SELECT ...
Find out what version of Red Hat you're running
See /etc/redhat-release
Postgres date arithmetic
SELECT DATE(CURRENT_DATE + INTERVAL '1 DAY');
Good overview at: http://techdocs.postgresql.org/techdocs/faqdatesintervals.php
PHP POST through proxy
function post_through_proxy($url, $payload, $proxyhost="proxy.admin.local", $proxyport=8001) {
$errno="";
$errstr="";
$file = fsockopen($proxyhost, $proxyport, &$errno, &$errstr, 30);
if(!$file) {
// Failed to open connection to proxy - exit:
return false;
} else {
// Define the max number of bytes to fread at once:
$fread_max = 4096;
// Successfully opened connection to proxy, attempt to post data:
$headers = "POST $url HTTP/1.1\r\n";
$headers .= "Content-type: application/x-www-form-urlencoded\r\n";
$headers .= "Content-Length: ".strlen($payload)."\r\n\r\n";
$headers .= $payload;
fputs($file, $headers);
// Get small chunks of reponse until we know the content length:
$response = "";
whi
le(!stristr($response, "Content-Length:")) $response .= fread($file, 20);
$response .= fread($file, 20);
// Look for Content-length:
$content_length = substr($response, strpos($response, "Content-Length: ")+16);
$content_length = substr($content_length, 0, strpos($content_length, "\n"));
$content_length = (double)$content_length;
// Get small chunks of response until we get to the content:
while(!stristr($response, "\r\n\r\n")) $response .= fread($file, 1);
// Get the content:
$content = "";
for($i=0; $i
Opera bookmarks disappeared
I loaded Opera (7.52) and found all my bookmarks had completely vanished. Got them back by doing this:
1. Selected "About Opera" from the "Help" menu. This tells you the path of the bookmarks file.
2. Go to the directory where the file is meant to be and if you see a file called "opera6.adr.bak" then you're in luck.
3. Rename "opera6.adr" to something like "opera6.adr.bak.NOT_WORKING" then make a copy of "opera6.adr.bak" and rename it "opera6.adr".
4. Restart Opera and you should have your bookmarks back.
How to use NuSOAP to call a .NET web service that takes an int array
Eventually got it to work like this:
$test_proxy->IntArrayTest(array("items"=>array("int"=>array(1,2,3))))
What is Cohesion?
http://66.102.11.104/search?q=cache:dHHUT-PGUTwJ:hakata.mt.cs.cmu.edu/20-783/Slides/06_Elaboration_4.ppt+%22what+is+coupling%22+programming&hl=en
A measure of how strongly related and focused the responsibilities of a class are:
Highly focused & related: high cohesion
Not focused, unrelated: low cohesion
Low cohesion is undesirable:
- Hard to comprehend classes
- Hard to reuse classes
- Hard to maintain classes
- Brittle: classes easily broken by changes
From: http://encyclopedia.thefreedictionary.com/Cohesion
In computer programming, cohesion refers to the degree to which each part of a module is associated with each other part, in terms of functional relation. Parts of a module are functionally related if each part is essential to the functionality and the interface of a well-defined module (a well-defined module is one that has a sin
gle task, or models a single object). Cohesion can be considered "high" or "low". High cohesion means each part of a module is functionally related, and low cohesion means each part of a module is not. High cohesion of a module is considered better design in a computer system.
The types of cohesion, in order of lowest to highest, are as follows:
Coincidental cohesion - Coincidental cohesion is when parts of a module are grouped arbitrarily; the parts have no significant relationship (e.g. a module of frequently used functions).
Logical cohesion - Logical cohesion is when parts of a module are grouped because of a slight relation (e.g. using control coupling to decide which part of a module to use, such as how to operate on a bank account).
Temporal cohesion - Temporal cohesion is when parts of a module are grouped by when they are processed - the parts are processed at a particular time in program execution (e.g. a function which is called aft
er catching an exception which closes open files, creates an error log, and notifies the user).
Procedural cohesion - Procedural cohesion is when parts of a module are grouped because they always follow a certain sequence of execution (e.g. a function which checks file permissions and then opens the file).
Communicational cohesion - Communicational cohesion is when parts of a module are grouped because they operate on the same data (e.g. a method updateStudentRecord which operates on a student record, but the actions which method performs are not clear).
Sequential cohesion - Sequential cohesion is when parts of a module are grouped because the output from one part is the input to another part (e.g. a function which reads data from a file and processes the data).
Functional cohesion - Functional cohesion is when parts of a module are grouped because they all contribute to a single well-defined task of the module (a perfect module).
What is coupling?
From: http://computing-dictionary.thefreedictionary.com/Coupling
Coupling - The degree to which components depend on one another. There are two types of coupling, "tight" and "loose". Loose coupling is desirable for good software engineering but tight coupling may be necessary for maximum performance. Coupling is increased when the data exchanged between components becomes larger or more complex.
From: http://hakata.mt.cs.cmu.edu/20-783/Slides/06_Elaboration_4.ppt
A measure of how strongly one class is connected to / has knowledge of / or relies on others
Low coupling: not dependent
High coupling: highly dependent
High coupling is undesirable:
- Changes in related classes force local changes
- Harder to understand class in isolation
- Harder to reuse class
starting proftp
/usr/local/sbin/proftpd start
C# get web page through proxy
using System.Net;
using System.IO;
private String readHtmlPage(string url)
{
String result;
WebResponse objResponse;
WebProxy proxyObject = new WebProxy("http://proxy.admin.local:8001/",true);
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
objRequest.Proxy = proxyObject;
objResponse = objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()) )
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}
Disable the hidden (dollar sign) drive shares in Windows networking
From: http://www.experts-exchange.com/Security/Q_20966270.html
Add the following to the registry to turn off hidden shares:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\lanmanserver\parameters
On Windows 2000/2003 Server add the following key AutoShareServer with the REG_DWORD value of 0.
On Windows 2000/XP Workstation add the following key AutoShareWks with the REG_DWORD value of 0.
You have to reboot for this setting to take effect.
Windows file sharing not working
If you get messages like "You might not have permission to use this network resource" etc try these things:
- Try switching off your firewall software on each machine. I had Norton Internet Security running on one machine and it was stopping the Windows file sharing.
- Try logging off and back on each machine
- Try rebooting each machine
cron field order
minute, hour, day-of-month, month, day-of-week, command
Note that day-of-week is 0 = Sunday
Postgres to Visio
This is a way to import database table data from Postgres into Visio, via MySQL. The sequence goes like this:
Postgres dump schema (pg_dump)
Convert Postgres dump
MySQL import
Visio import via MySQL ODBC
A much better way would be to have the Visio takling to Postgres ODBC directly, but I didn't have Postgres ODBC set up and had heard that MS products have difficulty talking to Postgres ODBC so I went down this other route instead as I just needed a quick dump of the table details.
Note that this method allows you to import only tables into Visio, not the relationship between tables, or indexes, etc - just the table schemas.
Create a dump of the postgres schema:
pg_dump -U postgres -s xf_dev > xf_dev.sql
That file will be a series of sql statements to create the tables in Postgres. Some of the datatypes and syntax are different in MyS
QL, so I wrote this php script to translate the statements:
$skip_lines = array("--", "REVOKE", "GRANT", "connect", "SET ");
if($_SERVER['argc'] != 3) {
exit("usage: pg2mysql.php pg_input_file mysql_output_file\n");
}
$input_file = $_SERVER['argv'][1];
$output_file = $_SERVER['argv'][2];
if(!file_exists($input_file)) {
exit("Can't open input file: $input_filen");
}
$input = file_get_contents($input_file);
$input = str_replace(" oid", " int", $input);
$input = str_replace(" boolean", " bool", $input);
$input = str_replace(" timestamp without time zone", " timestamp", $input);
$input = str_replace(" timestamp with time zone", " timestamp", $input);
$input = str_replace(" bool DEFAULT true", " bool DEFAULT 1", $input);
$input = str_replace(" bool DEFAULT false", " bool DEFAULT 0", $input);
$input = str_replace('"', "", $input);
$lines = explode("n", $input);
$output = "";
for($i=0; $i<count($lines); $i++) {
//Skip lines which start with words in the $skip_lines array:
for($s=0; $s<count($skip_lines); $s++) {
if(substr($lines[$i], 0, strlen($skip_lines[$s])) == $skip_lines[$s]) continue 2;
}
// Skip blank lines:
if(!strlen(trim($lines[$i]))) continue;
// Replace varchars greater that 255 with 'text' type:
if($pos = strpos($lines[$i], " character varying(")) {
$num = substr($lines[$i], $pos+19);
$num = substr($num, 0, strpos($num, ")"));
if($num > 255) {
$lines[$i] = str_replace(" character varying($num)", " text", $lines[$i]);
}
}
// Copy this line to output:
$output .= $lines[$i]."\n";
}
if(!$fp = fopen($output_file, "w")) exit("Can't open output file for writing.");
fwrite($fp, $output);
fclose($fp);
print("don
e\n");
I run the script from the command prompt:
c:phpphp pg2mysql.php xf_dev.sql mysql_xf_dev.sql
Which generates the translated file "mysql_xf_dev.sql".
Copy the statements from that file and paste them in at the mysql command line.
Install the mysql ODBC driver (available from the mysql website).
In Visio, choose 'reverse engineer' from the 'database' menu. From there you can select to connect via the generic ODBC driver, and you should see the mysql connection somewhere. Click on that and select the tables you want to import. Click "finish" and your tables should be imported.
Postgres restart
If you're logged in as root:
/etc/init.d/postgres restart
Or
su - postgres -c 'pg_ctl restart -D /usr/local/pgsql/data'
If you're logged in as 'postgres':
pg_ctl restart -D /usr/local/pgsql/data
(note that these assume that 'pg_ctl' is in your path - if not, replace it with '/usr/local/pgsql/bin/pg_ctl' or whatever the path is)
Turn off Windows XP error reporting (which is slow and annoying)
From: http://www.techtv.com/callforhelp/answerstips/windowstips/story/0,24330,3362242,00.html.
1. Right-click My Computer and choose Properties.
2. Click the Advanced tab on your System Properties dialog box.
3. Click the Error Reporting button on the Advanced tab.
4. Place a checkmark next to "Disable error reporting."
5. Leave the other radio button unchecked next to the text labeled, "But notify me when critical errors occur."
Click OK.
Javascript form.submit() method doesn't work
If you have a form with a submit button called 'submit', any calls to the form's submit() function will not work (you will get the error message "this object does not support this property or method". So just make sure never to call a submit button 'submit'.
JavaScript atoi / string to integer
Use eval():
var number_five = eval("5");
Why Photoshop Elements sucks for web work
No paragraph panel, so you can adjust line spacing, letter spacing, etc.
No "Transform selection" option on marquee tool right-click (I can't believe they took this out!).
Seems quite unstable compared to PS (but that could just be my machine/installation).
Acoustic Solutions 551 DVD region free hack
1. Using the remote control, key in the following: Setup, Next, Stop, Pause/Step, Prev, Next.
2. You should now be in a secret menu where you can change the region from 1 to 6, or All for region free.
MS-DOS substring
This script:
SET var=every day I see this scar
SET var=%var:~10,5%
echo %var%
will output 'I see'
(Note that in the variable declarations, there must be no space between the variable name and the equals sign, or between the equals sign and the value)
MS-DOS string replace
This script:
SET var=moose
SET var=%var:m=g%
echo %var%
will output 'goose'
(Note that in the variable declarations, there must be no space between the variable name and the equals sign, or between the equals sign and the value)
Getting putty working using SSH keys
1. Setting up OpenSSH:
The server needs to be set up to accept ssh keys access. In the OpenSSH config file (/etc/ssh/sshd_config) I used the following options (note that some of these options may be the default, therefore they would not need to be explicitly specified... but these are the lines I changed):
StrictModes no
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
After updating the config file, restart the service:
service sshd stop
service sshd start
2. Setting up putty:
2.1. Getting the public and private keys:
Using puttygen.exe:
- Select SSH1 (RSA) as the type of key.
- Use 1024 as the number of bits generated.
- Click 'generate' and move the mouse about to generate the key.
- Enter a key comment, such as "rangi
.robinson_desktop" (whatever you want).
- Enter and confirm a key phrase (should be hard to guess).
- Save the private key as a file on your machine.
Using pageant.exe:
- Select 'Add key'.
- Open the private key file you saved on your machine.
- Enter your key phrase (you have to do this whenever pageant.exe is started).
The program pageant.exe keeps your private key in memory until it's closed, so whenever putty tries to connect to the server, it attempts to use the private key signature for authorisation.
3. Putting your private key on the server:
- Log into your account via putty (using a password).
- In your home directory:
mkdir .ssh
chmod 700 .ssh
cd .ssh
touch authorized_keys
vi authorized_keys
- Copy and paste your entire public key from puttygen.exe to the authorized_keys file.
- Save and close the authorized_keys file.
You should now be
able to log into the server with putty using just the ssh key, no username and password required. If it's not working, try restarting sshd, as above.
Useful links:
http://www.openssh.com/ OpenSSH website/docs
http://www.chiark.greenend.org.uk/~sgtatham/putty/ Putty website/docs
http://cvs.datafox-engineering.com/#top Tutorial on this subject
Adobe Acrobat "A temporary file could not be opened"
Reader creates temp files which it is supposed to clean up after itself. it has a bug and sometimes creates 64000 temp files and then can't open since it has run out of numbers to assign to new tmp files. Problem was solved by going to CMD prompt in the temp directory (/Local Settings/Temp), then del acr*.tmp.
Postgres get database schema
pg_dump -s -u -f schema-2004-01-14.sql db_name
-s = get schema only (no data)
-u = ask for user name
-f = file to dump to
XSLT xsl:for-each and xsl:if
Link:
http://www.zvon.org/xxl/XSLTutorial/Books/Output/example20_ch7.html
The XSLT stylesheet uses the 'xsl:for-each' loop to go through each service. Within each service, the 'selected' field is checked to see if it equals 1 using the 'xsl:if'.
Source XML:
<services>
<service>
<contact_ref>43885</contact_ref>
<service_ref>6</service_ref>
<uber_group_ref>35</uber_group_ref>
<entity />
<elevel>0</elevel>
<selected>0</selected>
<description>AdSearch Client Administrator</description>
<service>AdSearch Client Administrator</service>
</service>
<service>
<contact_ref>43885</contact_ref>
<service_ref>13</service_ref>
<uber_group_ref>35</u
ber_group_ref>
<entity />
<elevel>0</elevel>
<selected>1</selected>
<description>AdSearch Free High Quality Previews</description>
<service>AdSearch Free High Quality Previews</service>
</service>
</services>
XLST stylesheet:
<xsl:template match="services">
<service_list>
<xsl:for-each select="service">
<xsl:if test="selected = 1">
<service_ref>
<xsl:value-of select="service_ref" />
</service_ref>
</xsl:if>
</xsl:for-each>
</service_list>
</xsl:template>
Output:
<services>
<service_ref>13</service_ref>
</services>
Open remote webpage from VB over HTTP:
C#:
private void Page_Load(object sender, System.EventArgs e)
{
System.Text.UTF8Encoding objUTF8 = new System.Text.UTF8Encoding();
System.Net.WebClient w = new System.Net.WebClient();
string html;
html = objUTF8.GetString(w.DownloadData("http://www.rangirobinson.com"));
Response.Write(html);
}
VB:
Dim str, url As String
Dim objInet As Object
url = "http://www.rangirobinson.com/test.php"
Set objInet = CreateObject("InetCtls.Inet")
str = objInet.OpenURL(CStr(url))
NOTE *****************************************
OpenURL needs explicitly casted string using CStr().
So, the line
str = objInet.OpenURL(CStr(url))
Wont work without the CSTr:
str = objInet.OpenURL(url) ' THIS WONT WORK
(for some reason, passing a string variable withou
t casting like this
results in a "URL is malformed" error!)
**********************************************
ASP prevent HTTP caching
Response.Expires = 60
Response.Expiresabsolute = Now() - 1
Response.AddHeader "pragma","no-cache"
Response.AddHeader "cache-control","private"
Response.CacheControl = "no-cache"
.NET OleDb with output parameters example
private int getCountryRef(string country_iso_code, int org_ref)
{
OleDbCommand xvolComm = new OleDbCommand("xvol..sp_country_whitelabel_select", xvolOLEDBConn);
xvolComm.CommandType = CommandType.StoredProcedure;
// Create the output parameter:
OleDbParameter outputParam = new OleDbParameter("@country_ref", OleDbType.Integer);
outputParam.Direction = ParameterDirection.Output;
// Add the SP parameters to the command:
xvolComm.Parameters.Add(outputParam); // output param
xvolComm.Parameters.Add("@country", OleDbType.VarChar).Value = country_iso_code; // output param
xvolComm.Parameters.Add("@organisation_ref", OleDbType.Integer).Value = org_ref; // output param
// Return the SP result:
xvolComm.ExecuteNonQuery();
return (int)outputParam.Value;
}
Sybase stored procedures with output parameters
Define the procedure:
CREATE PROCEDURE mydb.times_two
@a int out,
@b int
AS
BEGIN
select @a = @b*2
END
Call the procedure:
DECLARE @x INT
EXECUTE mydb..times_two @a = @x output, @b = 5
Returns:
@a
----
10
Then SELECT @x returns:
----
10
Postgres equivilant to mysql UNIX_TIMESTAMP()
select round(date_part('epoch', my_date)) from my_table;
JavaScript variable scope
Variables declared outside any function are global.
Variable declared inside a function but without the 'var' keyword, are also global! So be particularly aware of variables such as loop counters etc - they must be declared in advance using 'var' otherwise you will get into a mess.
Javascript functions always take arguments passed by value, EXCEPT arrays and objects, which are always passed by reference.
To make the status bar appear whenever you open Internet Explorer:
1) With (only one) IE open, click View, select: Status Bar
2) Right-click on IE's Toolbar and select: "Lock the Toolbar"
3) Hold down the Ctrl key and click the close button (upper right)
4) Open Windows Explorer, click View, select: Status Bar
5) Right-click on Explorer's Toolbar and select: "Lock the Toolbar"
6) Click Tools | Folder Options | View tab
7) Click the "Apply to all folders" button.
8) Hold down the Ctrl key and click the close button (upper right)
9) Open IE to any page, right-click on a link and select: "Open in New Window"
Creating an XML file from MySQL using mysqldump:
If you don't have to log in etc:
mysqldump -xml my_database
Otherwise it'll be something like:
mysqldump -h my.host.com -u username -p -xmp my_database
and you'll be prompted for a password.
Remember you can use the > operator to capture the mysqldump output as a text file.
MySQL backup methods:
(these methods were worked out by studying the information at
http://www.mysql.com/doc/en/mysqldump.html)
METHOD 1 - Backup to a text file for later restore, using mysqldump.
To create the backup locally:
mysqldump --opt my_database > my_database.sql
To create the backup remotely:
mysqldump --opt -u username -p -h my.host.com my_database > my_database.sql
Note that you can specify several databases with the --databases option:
mysqldump --opt --databases my_database_1 my_database_2 > my_databases.sql
The --opt option is not essential but combines several of the other mysqldump options to provide
optimum output performance. For large databases, --opt prevents the entire database being loaded
into memory before output begins (so --opt really is essential for large databases, otherwise
mysqldump could try
to load 10GB of data into memory).
To restore the backup:
1. If the database to be restored doesn't exist, create it (it will be empty):
create database my_database
2. Enter
mysql my_database < my_database.sql
for local restoration or
mysql -u username -p -h my.host.com my_database < my_database.sql
for remote restoration.
This demonstrates how MySQL commands in a text file can be executed from the command line.
METHOD 2 - Pipe mysqldump output directly into another server:
mysqldump --opt my_database | mysql -u username -p -h my.host.com -C my_database
As in method 1, the database will have to exist on the target server, even if it's just
an empty database.
The --opt option is not essential but combines several of the other mysqldump options to provide
optimum output performance. For large databases, --opt prevents the entire database being
loaded
into memory before output begins (so --opt really is essential for large databases, otherwise
mysqldump could try to load 10GB of data into memory).
The -C option tells the server to use compression (to speed up transer?).
Note that this method could also be used to make copies of a database on the same server:
1. Create the empty target database if it doesn't already exist:
create database my_database_copy
2. Enter:
mysqldump --opt my_database | mysql -C my_database_copy
METHOD 3 - User the perl script mysqlhotcopy
Could be the fastest method, but I haven't tried it yet.
Obviously this isn't included with the Windows MySQL distribution.
See http://www.mysql.com/doc/en/mysqlhotcopy.html
MySQL set up remote login / users
The tables user, host and db specify what hosts/users can connect to the server or
to particular databases. This actually makes sense when you think about it, and if
you examine these tables, they're sort of self-explanitory.
In most cases, I'll probably want to add a single user:
insert into user values ("10.0.0.120", "Rangi", PASSWORD("mypassword"), "Y", "Y",
"Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y");
Note the PASSWORD() function, which turns the password into a hash of some kind.
Replace "10.0.0.120" with whatever domain/ip you are connecting from, or use "%"
to allow this user to be able to connect from anywhere.
*** ONCE YOU HAVE CHANGED THE mysql TABLE YOU MUST ENTER: ***
mysqladmin flush-privileges
(that bit is easy to forget but essential - at
tempting to log in without having done
this will not work)
To connect from a remote machine from the command line you can then enter:
mysql -u rangi -p -h 10.0.0.15 [name_of_database]
You will be prompted for a password. Replace "10.0.0.15" with the domain/ip of the
server you are connecting to.
MySQL change password:
From the command monitor (where you can type in sql statements), type:
set password = password("my_new_password")
MySQL date calculations: month, weekday, year, etc
SELECT name, YEAR(birthday) FROM people GROUP BY YEAR(birthday);
following query shows, for each pet, the birth date, the current date, and the age in years.
SELECT name, birth, CURRENT_DATE,
(YEAR(CURRENT_DATE)-YEAR(birth)) - (RIGHT(CURRENT_DATE,5)
Unix user/file admin:
chown - change the owner of a file/dir
chown rangi myfile
chgrp - change the group of a file/dir
chgrp
useradd - add a user to the system
useradd -d /home/johnny johnny
After adding a user, you must add a password to thier account before they can use it.
passwd - change/set password
passwd johnny - change johnny's password
passwd - change your own password
userdel - delete a user
userdel johnny - delete the 'johnny' user
userdel -r johnny - delete the 'johnny' user and his home dir
Get a list of users on the system:
more etc/passwd
SQL Left Join
The LEFT JOIN returns all the rows from the first table (Employees), even if there are no matches in the second table (Orders). If there are rows in Employees that do not have matches in Orders, those rows also will be listed.
SELECT Employees.Name, Orders.Product
FROM Employees
LEFT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
WHERE Employees.Name = 'Rangi';
inodes
inodes are data structures that contain information about files in Unix file systems. Each file has an inode and is identified by an inode number (i-number) in the file system where it resides. inodes provide important information on files such as user and group ownership, access mode (read, write, execute permissions) and type.
inodes are created when a file system is created. There are a set number of inodes, which indicates the maximum number of files the system can hold.
A file's inode number can be found using the ls -i command, while the ls -l command will retrieve inode information.
Get disk usage numbers:
df -h
or if that doesn't work:
df -bk
Regular expressions:
From: http://www.phpbuilder.com/columns/dario19990616.php3
First of all, let's take a look at two special symbols: '^' and '$'. What they do is indicate the start and the end of a string, respectively, like this:
"^The": matches any string that starts with "The";
"of despair$": matches a string that ends in the substring "of despair";
"^abc$": a string that starts and ends with "abc" -- that could only be "abc" itself!
"notice": a string that has the text "notice" in it.
There are also the symbols '*', '+', and '?', which denote the number of times a character
or a sequence of characters may occur. What they mean is: "zero or more", "one or more",
and "zero or one." Here are some examples:
"ab*": matches a string that has an a followed by zero or more b's ("a", "ab", "abbb", etc.);
"ab+": same, but there's at least one b ("ab", "abbb", etc.);
"ab?": there might be a b or not;
"a?b+$": a possible a followed by one or more b's ending a string.
You can also use bounds, which come inside braces and indicate ranges in the number of occurences:
"ab{2}": matches a string that has an a followed by exactly two b's ("abb");
"ab{2,}": there are at least two b's ("abb", "abbbb", etc.);
"ab{3,5}": from three to five b's ("abbb", "abbbb", or "abbbbb").
Note that you must always specify the first number of a range (i.e, "{0,2}", not "{,2}"). Also, as you might have noticed, the symbols '*', '+', and '?' have the same effect as using the bounds "{0,}", "{1,}", and "{0,1}", respectively.
Now, to quantify a sequence of characters, put them inside parentheses:
"a(bc)*": matches a string that has an a followed by zero or more copies of the sequence "bc";
"a(bc){
1,5}": one through five copies of "bc."
There's also the '|' symbol, which works as an OR operator:
"hi|hello": matches a string that has either "hi" or "hello" in it;
"(b|cd)ef": a string that has either "bef" or "cdef";
"(a|b)*c": a string that has a sequence of alternating a's and b's ending in a c;
A period ('.') stands for any single character:
"a.[0-9]": matches a string that has an a followed by one character and a digit;
"^.{3}$": a string with exactly 3 characters.
Bracket expressions specify which characters are allowed in a single position of a string:
"[ab]": matches a string that has either an a or a b (that's the same as "a|b");
"[a-d]": a string that has lowercase letters 'a' through 'd' (that's equal to "a|b|c|d" and even "[abcd]");
"^[a-zA-Z]": a string that starts with a letter;
"[0-9]%": a string that has a single digit before a percent sign;
",
[a-zA-Z0-9]$": a string that ends in a comma followed by an alphanumeric character.
You can also list which characters you DON'T want -- just use a '^' as the first symbol in a bracket expression (i.e., "%[^a-zA-Z]%" matches a string with a character that is not a letter between two percent signs).
In order to be taken literally, you must escape the characters "^.[$()|*+?{" with a backslash (''), as they have special meaning. On top of that, you must escape the backslash character itself in PHP3 strings, so, for instance, the regular expression "($|¥)[0-9]+" would have the function call: ereg("(\$|¥)[0-9]+", $str) (what string does that validate?)
Just don't forget that bracket expressions are an exception to that rule--inside them, all special characters, including the backslash (''), lose their special powers (i.e., "[*+?{}.]" matches exactly any of the characters inside the brackets). And, as the regex man pages tell us:
"To include a literal ']' in the list, make it the first character (following a possible '^'). To include a literal '-', make it the first or last character, or the second endpoint of a range."
For completeness, I should mention that there are also collating sequences, character classes, and equivalence classes. I won't be getting into details on those, as they won't be necessary for what we'll need further down this article. You should refer to the regex man pages for more information.
SQL GROUP BY clause:
SQL GROUP BY clause:
SELECT page_script, COUNT(page_script) AS hits FROM page_hit GROUP BY page_script;
will return:
+-----------------------------+------+
| page_script | hits |
+-----------------------------+------+
| /www/basket.php | 2 |
| /www/comp.php | 1 |
| /www/image.php | 2 |
| /www/index.php | 11 |
| /www/lightbox.php | 1 |
| /www/popups/basket_calc.php | 3 |
| /www/search.php | 5 |
| /www/user/login.php | 6 |
+-----------------------------+------+
and
SELECT ((max(ts) - min(ts))/60) AS minutes FROM page_hit GROUP BY sid;
will return:
+---------+ (this returns the number of minutes that each session took, and from this we can
| minutes | work out the average
session length)
+---------+
| 3.20 |
| 36.67 |
+---------+
and
SELECT COUNT(DISTINCT sid) AS users_online FROM page_hit WHERE UNIX_TIMESTAMP(ts) > (UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - (60 * 3));
will return:
+-----------+ (this returns the number of people that have loaded a page in the last 3 minutes)
| count(ts) | (this includes people that are just browsing - they don't have to be logged in)
+-----------+
| 3 |
+-----------+
A slight variation shows the number of people _logged_in_ (not just browsing):
SELECT COUNT(DISTINCT sid) AS users_logged_in FROM page_hit WHERE UNIX_TIMESTAMP(ts) > (UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - (60 * 3)) AND FK_webuser_no IS NOT NULL;
Another variation shows the number of users online that are not logged in:
SELECT COUNT(DISTINCT sid) AS users_online_not_logged FROM page_hit WHERE UNIX_TIMESTAMP(ts) > (UNIX_TIMESTAMP(CURRENT_TIMESTA
MP) - (60 * 3)) AND FK_webuser_no IS NULL;
PHP/HTTP prevent caching:
Used this to stop the images in the StoryBoards flash anim from being cached:
header("Expires: Sat, 1 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
The Cache-Contol command is used with HTTP/1.1, and the Pragma command is used for HTTP/1.0.
DDR = Double Data Rate
Double Data Rate - Data is read on the 'fall' as well as the 'rise' of each clock cycle.
ASP search for a substring in a string (strstr() s
Example: InStr("I was out shopping","out") returns 7
ASP Server Variables
For example, to access the 'SCRIPT_NAME' varibale, use:
Request.ServerVariables("SCRIPT_NAME")
For a list of available variables, see http://www.devasp.com/samples/ServerVariables2.asp?TestID=65
ASP type conversion
cint("3")
returns numeric 3
CBool (boolean: returns true any nonzero number)
CByte (1-255, converts to byte)
CCur (currency: 4 digits out)
CDate (Date: numeric; see also FormatDateTime)
CDbl (Double: ** Largest capacity data type **)
CInt (Integer)
CLng (Long Integer)
CSng (Single - empty causes an error)
CStr (Takes any expression and converts it to string format)
Uninstalling Jethomepage
Shut down IE and then search out and rename sp.dll.
Next you have to clean up your computer's registry. Search for references to Jethomepage which
you will most likely find here:
[HKEY_CURRENT_USERSoftwareMicrosoftInternet ExplorerMain]
"Search Page"="http://www.jethomepage.com/search.htm"
"Search Bar"="http://www.jethomepage.com/search.htm"
[HKEY_LOCAL_MACHINESOFTWAREMicrosoftInternet ExplorerSearch]
"SearchAssistant"="http://www.jethomepage.com/search.htm"
Access write/update errors from ASP
Make sure the IUSR_MACHINE (where MACHINE is the name of the machine) user has the appropriate
permissions on the database file.
Also, if the database is not in the webroot, make sure the web server has the appropriate
permissions on the dir where the database is.
I have found that these seem to unset themselves sometimes, and I have to go back and set them.
I have heard that it is sometime neccessary to set these same permssions on the system TEMP dir,
but I haven't found this to be neccessary yet.
See also:
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q175168
PHP & Cookies
Althouth the docs say that most of the parameters to setcookie are optional, I have only got
it to work by using all the parametes, like this:
setcookie("name_of_cookie","value",time()+(60*60*24*30),"/","",0)
To delete cookies, set them in exactly the same way (even the time), but set the value to "":
setcookie("name_of_cookie","",time()+(60*60*24*30),"/","",0)
Also, remember that there can be newline characters within the tags before header
operations (such as cookie operations), but there can be no newlines (or any output) outside of
the php tags, cos such output is then part of the hmtl, and therefore sent to the browser as
soon as the server comes across it.
XHTML html, body and table height control:
Note that the tag's 'height' attribute has been depreciated, so we now have to use:
html, body, .content { height: 100%; }
This text appears in the middle
Enable directory browsing in Apache:
Add this directive to httpd.conf
Options Indexes
Note that the path is the full file system path, not the path relative to
the web root dir.
Then restart Apache:
/etc/rc.d/init.d/httpd restart
This all works fine on the HC remote server.
Linux set path (append path to existing path)
PATH=$PATH:/new/path
Restart Apache (2 methods)
/etc/rc.d/init.d/httpd restart
Or
/usr/local/apache/bin/apachectl restart
Find out what symbolic links are pointing to:
ls -l
Doskey on Windows 2000 (and NT?)
C:WINNTsystem32 contains command.com and cmd.exe. Command.com is the 16-bit emulation program, and doskey wont work there even if you run the doskey command. From within a command.com shell you can type 'cmd' to get a cmd.exe shell. A better option is to use cmd.exe to start with. Cmd.exe has doskey functionality built in.
Using MS SQL Server with PATINDEX()
Remember that if you do patindex(@my_variable,'string to search'), @my_variable MUST be of type varchar, and NOT char.
Add a watermark to image with ImageMagick
composite -compose bumpmap -gravity southeast watermark.png input.jpg output.jpg
Also, take a look at the -watermark option (this may well do this better).
Linux user admin
Create user rangi and specify home directory:
useradd rangi -d /usr/local/rangi
Set password for rangi
passwd rangi
Create group called chacha
groupadd chacha
Add users to a group
usermod -G chacha rangi
Background commands
If you wish to run a command in the background, follow it with an ampersand, so kedit & will launch the kedit application and return you to the command prompt without waiting for the application to finish.
Can't connect to local MySQL server through socket
SOLUTION
extracted from comments at: http://www.mysql.com/doc/en/Gone_away.html
author: Geoff@squiggle.org
If you keep getting: error: 'Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)' Some RPM's put the mysql.sock file in /var/lib/mysql/mysql.sock instead of /tmp/mysql.sock I was pulling my hair out for ages over this! Small hack is to symlink it: "ln -s /var/lib/mysql/mysql.sock /tmp"
Using Linux TSQL (from FreeTDS) to query MS SQL Se
Using Linux TSQL (from FreeTDS) to query MS SQL Server database on Windows.
Conf file being used with this installation is /usr/local/etc/freetds.conf. The
file contains the following server entry:
[HCSERVER]
host = 192.168.157.1 (IP of Windows machine)
port = 1433 (The normal port for MS SQL Server)
This allows us to connect from the command line using:
tsql -S HCSERVER -U rangi
Where rangi is a user and login in SQL Server.
NOTES
If getting an error message like "server does not exist or is not available" when
trying to connect then do the following.
Go into SQL Server Enterprise Manager.
Right-click the server that we are trying to connect to, select properties.
In the Security tab, make sure the authenticaion type is
"SQL Server and Windows" (not "Windows only")
Click OK to exit the dialog box.
In the tree navigator below the server, choose security->logins.
Make sure the user name we are connecting with is present, and they are using 'SQL Server' Authentication.
If not create it (the user must be based on a Windows user - so you might have to create one (control panel -> users))
If yes, re-enter the password.
Restart SQL Server.
You should now be able to connect.
No FTP/HTTP between Windows and Linux (ping workin
CAUSES
Hardware - if ping is working this is not the problem
Subnet - check that computers are on same subnet
Firewall - check that not enabled - config and startup files, see below.
Services running - Check running, check ports, check run levels
SOLUTIONS
Red hat (or other dist) manual
Search error messages online
Compare config with working machine
Reinstall with no firewall and gnome installed (so can use gnome-lokkit)
NOTES
I have had a case where all of these have been checked and nothing works. Then I come back the next day and it works... why I don't know.
Check subnet with ipconfig (win) and ifconfig(lin).
Red hat online manual networking section is useful for looking up programs
to specify which services are running, starting them stopping them and
choosing if they are
started/stopped at different run levels. On a
graphical desktop, "serviceconf" in a console is good. The console
alternative is "netsysv", although with that one you can only edit one
run level. "chkconfig" can be used to start/stop individual services and
choose what run levels they run at. The Red hat online manual has a good
explanation of these.
Wu-fptd runs as an xinetd service. The line "disable no"
should be in /etc/xinetd.d/wu-ftpd (not "disable yes").
xinetd is restarted with "service xinetd restart".
ipchains and iptables can be disabled (I think) with:
chkconfig --level 0123456 ipchains off
chkconfig --level 0123456 iptables off
The --level is used to specify the run levels.
When it _does_ work, if the FTP connection is slow to start, try turning
off 'passive mode' in the FTP client.
xinetd
Restart xinetd with:
service xinetd restart
Setting and reading bash env vars
export myvar=myvalue (sets env var)
echo $myvar (echos env var)
inet/xinet services
Getting access to inet/xinet services from hosts other than localhost:
1. Ensure there is nothing in hosts.allow/deny that would deny the user
2. Check firewall. This can be disabled for testing by typing
lokkit
and choosing 'none'.
Also, see the problem below "No FTP/HTTP between Windows and Linux".
wu-ftp
Getting wu-ftp to work:
Make sure that etc/xinetd.d/wu-ftpd doesn't have the line
disable = yes
set. It must read:
disable = no
After making any changes to the config files you should restart xinetd:
/etc/init.d/xinetd restart
Try
ftp localhost
to test.
Apache, nslookup
Apache by default does not look up the remote host name, because this requires an nslookup to be performed, and this will slow things down a lot if a lot of requests are being made to the server. The lookup can be turned on in the httpd.conf file by setting
HostnameLookups On
This will result in the CGI HTTP_REMOTE_HOST variable being set.
In PHP you can get the host name from the IP address with gethostfromaddr() and vice versa with gethostfromname().
PHP outputting JPEGs
When JPEGS (maybe other image files) are outputted using PHP to send the raw data in HTTP headers, sometimes when you save the .jpg it wont be a completely valid .jpg file, but it can still be read by ACDSee. Photoshop wouldn't open the invalid files and niether would Flash. ACDsee can be used to do a batch conversion to quickly make all the files valid jpegs.
Flash variables
Flash cannot read variables or movies (including pictures) from another sub-domain (a file on mydomain.com cannot read from mydomain2.com, even if both are hosted on the same machine).
Back