What does # symbol mean in a function in yacc - postgresql

I'm reading the yacc file from postgres's github repo and find this line with a #2. I'm not sure how to understand what this symbol mean.
pl_block : decl_sect K_BEGIN proc_sect exception_sect K_END opt_label
{
PLpgSQL_stmt_block *new;
new = palloc0(sizeof(PLpgSQL_stmt_block));
new->cmd_type = PLPGSQL_STMT_BLOCK;
new->lineno = plpgsql_location_to_lineno(#2);
new->stmtid = ++plpgsql_curr_compile->nstatements;
new->label = $1.label;
new->n_initvars = $1.n_initvars;
new->initvarnos = $1.initvarnos;
new->body = $3;
new->exceptions = $4;
check_labels($1.label, $6, #6);
plpgsql_ns_pop();
$$ = (PLpgSQL_stmt *) new;
}
;

It's the location structure corresponding to the second symbol in the production (in this case, the K_BEGIN keyword).

Related

Weird behaviour with dialog boxes and variables in Lua script for Lightroom plugin

I'm writing a Lightroom plugin using the Lightroom SDK/API in the Lua language. I'm new to Lua. I've found a situation where my script only works if a Lightroom dialog box (LrDialogs.message("random message")) is present in one function. Without it the function falls over at a later point claiming a string variable (Image.dr in the last LrDialogs.message) is 'nil' as opposed to the normal value it has when the plugin is working properly. Anyone know what's going wrong? Here's the relevant code segment:
------ read output file for exif and write to LR metadata ------
function parseOutput(outputFilePath)
LrDialogs.message("random message")
local tblOutput = {} --to hold the output exif (1 column table, i.e. an array)
local tblImages = {} --to hold the images and their relevant metadata
for line in io.lines(outputFilePath) do
line = removeWhitespaces(line)
table.insert(tblOutput, line)
end
local str = table.remove(tblOutput) --remove last line in table/file (it's log info, not exif)
tblImages = extractExif(tblOutput) --pick out the exif key/value pairs and add to Image objects
end
function extractExif(tblOutput)
local Image = {} --pseudo object to hold metadata for each image
local tblImages = {}
local blnFlag = false
local intCount = 0
for k,v in pairs(tblOutput) do --iterate through each value in the table
if string.find(v, "^=.+") then
--test if new image other than the first one
if blnFlag == true then
--add Image to tblImages and then clear Image object
table.insert(tblImages, Image)
--Image = {} --don't technically need this
blnFlag = false
--LrDialogs.message("inside blnFlag test")
end
i, j = string.find(v, "/") -- **** MAC ONLY. Back slash for Windows *****
Image.filePath = string.sub(v, i) --returns the file path
Image.name = string.match(v, "([^/]+)$") --return the file name
blnFlag = true
elseif string.find(v, "ISO") ~= nil then
Image.iso = string.match(v, "%a+:(.+)") --get text (i.e value) to right of colon
elseif string.find(v, "Film") ~= nil then
Image.filmSim = string.match(v, "%a+:(.+)")
elseif string.find(v, "Setting") ~= nil then
Image.drMode = string.match(v, "%a+:(.+)")
elseif (string.find(v, "Auto") ~= nil) or (string.find(v, "Development") ~= nil) then
Image.dr = string.match(v, "%a+:(.+)")
else
end
end
LrDialogs.message(Image.name .. Image.iso .. Image.filmSim .. Image.drMode .. Image.dr)
return tblImages
end
function removeWhitespaces(str)
return string.gsub(str, "%s", "")
end

"var" was previously used as a variable - MatLab

I don't know why it tells me that I previously used as a variable when I have never used it before.
Here is my code:
price := 0;
temp := 0;
for i=1:m,
price += -y(i)*log( sigmoid(theta'*X(i,:)) ) -(1-y(i))*log(1-sigmoid(theta'*X(i,:)) );
end;
J = price / m;
for i=1:n,
temp := 0;
for i2=1:m,
temp += ( 1-sigmoid(theta'*X(i2,:)) - y(i2) ) * X(j,i2);
end;
grad(i) = temp;
end;
The error is here:
'price += -y(i)*log( sigmoid(theta'*X(i,:)) ) -(1-y(i))*log(1-sigmoid(theta'*X(i,:)) );'
Log error:
"price" was previously used as a variable, conflicting with its use here as the name of a function or command.
See "How MATLAB Recognizes Command Syntax" in the MATLAB documentation for details.
I guess there is nothing like += in Matlab. So, you can't do the following.
price += -y(i)*log(sigmoid(theta'*X(i,:))) - (1-y(i))*log(1-sigmoid(theta'*X(i,:)));
Rather you should do the following.
price = price + -y(i)*log(sigmoid(theta'*X(i,:))) -(1-y(i))*log(1-sigmoid(theta'*X(i,:)));
Moreover, := is not allowed according to Matlab language. Perhaps, your code is in Mupad. Check this out.

How do you order annotations by offset in brat?

When using the rapid annotator tool brat, it appears that the created annotations file will present the annotation in the order that the annotations were performed by the user. If you start at the beginning of a document and go the end performing annotation, then the annotations will naturally be in the correct offset order. However, if you need to go earlier in the document and add another annotation, the offset order of the annotations in the output .ann file will be out of order.
How then can you rearrange the .ann file such that the annotations are in offset order when you are done? Is there some option within brat that allows you to do this or is it something that one has to write their own script to perform?
Hearing nothing, I did write a python script to accomplish what I had set out to do. First, I reorder all annotations by begin index. Secondly, I resequence the label numbers so that they are once again in ascending order.
import optparse, sys
splitchar1 = '\t'
splitchar2 = ' '
# for brat, overlapped is not permitted (or at least a warning is generated)
# we could use this simplification in sorting by simply sorting on begin. it is
# probably a good idea anyway.
class AnnotationRecord:
label = 'T0'
type = ''
begin = -1
end = -1
text = ''
def __repr__(self):
return self.label + splitchar1
+ self.type + splitchar2
+ str(self.begin) + splitchar2
+ str(self.end) + splitchar1 + self.text
def create_record(parts):
record = AnnotationRecord()
record.label = parts[0]
middle_parts = parts[1].split(splitchar2)
record.type = middle_parts[0]
record.begin = middle_parts[1]
record.end = middle_parts[2]
record.text = parts[2]
return record
def main(filename, out_filename):
fo = open(filename, 'r')
lines = fo.readlines()
fo.close()
annotation_records = []
for line in lines:
parts = line.split(splitchar1)
annotation_records.append(create_record(parts))
# sort based upon begin
sorted_records = sorted(annotation_records, key=lambda a: int(a.begin))
# now relabel based upon the sorted order
label_value = 1
for sorted_record in sorted_records:
sorted_record.label = 'T' + str(label_value)
label_value += 1
# now write the resulting file to disk
fo = open(out_filename, 'w')
for sorted_record in sorted_records:
fo.write(sorted_record.__repr__())
fo.close()
#format of .ann file is T# Type Start End Text
#args are input file, output file
if __name__ == '__main__':
parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(),
usage=globals()['__doc__'],
version='$Id$')
parser.add_option ('-v', '--verbose', action='store_true',
default=False, help='verbose output')
(options, args) = parser.parse_args()
if len(args) < 2:
parser.error ('missing argument')
main(args[0], args[1])
sys.exit(0)

Converting classic ASP ADODB script to TSQL

Hi i inherited a load of old classic ASP code that makes some updates to some tables in what i think was old MS access db.
The databases have now been converted to SQL and work OK, however i have a need to convert some old ASP code to the equivalent TSQL. TSQL is NOT my strong point and would appreciate some help converting the vb script to the equivalent TSQL for a stored procedure called 'UpdateCircuitOrdersComments' its not the basic syntax i'm struggling with, its more what can be done IE FOR's IF's Cases, loops etc in order to achieve the below in sql.
I know the code below is not great or could be done far better, but that's what i inherited sorry.
Every field is available to me via c# parameters passed to the sproc using ajax apart from the "Contract Period"
Looking forward to learning from any sound advice from you guys...
The script is below:
Dim connect2, Class2, Query2, Counter
Dim indate1, indate2, indate3, aday1, amonth1, ayear1, aday2, amonth2, ayear2, aday3, amonth3, ayear3, length, maintrate, equiprate, stqrrate, startserial, liveserial, endserial
Dim splitArray
Set Connect = Server.CreateObject("ADODB.Connection")
Connect.Open QuotebaseDB
Set Class1 = Server.CreateObject("ADODB.Recordset")
Query = "SELECT * FROM circuits WHERE ID=" & Request("ID")
Class1.Open Query,Connect,adOpenDynamic,adLockOptimistic
if Class1("Contract Period") <> "" Then
length = Class1("Contract Period")
splitArray = split(length, " ")
length = CInt(splitArray(0))
else
length = 1
end if
Class1("actual live date") = Request("actuallivedate")
Class1("lastupdater") = Session("username")
Class1("lastupdate") = Date()
Class1("Contract Period") = length
Class1.Update
'=========================================
' Add Rate Information - Based On Actuals
'=========================================
indate1 = Request("actuallivedate")
indate2 = Request("actuallivedate")
indate3 = Request("actuallivedate")
aday1 = Left(indate1, 2)
amonth1 = Mid(indate1, 4, 2)
ayear1 = Right(indate1, 2)
aday2 = Left(indate2, 2)
amonth2 = Mid(indate2, 4, 2)
ayear2 = Right(indate2, 2)
aday3 = Left(indate3, 2)
amonth3 = Mid(indate3, 4, 2)
ayear3 = Right(indate3, 2) + length
startserial = dateserial(ayear1, amonth1, aday1)
liveserial = dateserial(ayear2, amonth2, aday2)
endserial = dateserial(ayear3, amonth3, aday3)
'========================================================
' Check that current maintenance rate will be superseded
'========================================================
Dim MaintConnect1, MaintRS1, MaintQuery1
Set MaintConnect1 = Server.CreateObject("ADODB.Connection")
MaintConnect1.Open QuotebaseDB
Set MaintRS1 = Server.CreateObject("ADODB.Recordset")
MaintQuery1 = "SELECT * FROM maintenancetable WHERE CircuitID=" & Request("ID")
MaintRS1.Open MaintQuery1,MaintConnect1,adOpenDynamic,adLockOptimistic
Do while not MaintRS1.eof
If (MaintRS1("startdate") < startserial) OR (MaintRS1("enddate") > endserial) Then
MaintRS1("startdate") = StartSerial
MaintRS1("enddate") = EndSerial
MaintRS1("circuitnum") = Class1("circuit number")
MaintRS1("modifieddate") = now
MaintRS1.Update
End If
MaintRS1.movenext
Loop
MaintRS1.close
set MaintRS1 = nothing
MaintConnect1.close
set MaintConnect1 = nothing
'========================================================
' Check that current equipment rate will be superseded
'========================================================
Dim EquipConnect1, EquipRS1, EquipQuery1
Set EquipConnect1 = Server.CreateObject("ADODB.Connection")
EquipConnect1.Open QuotebaseDB
Set EquipRS1 = Server.CreateObject("ADODB.Recordset")
EquipQuery1 = "SELECT * FROM [equipment table] WHERE CircuitID=" & Request("ID")
EquipRS1.Open EquipQuery1,EquipConnect1,adOpenDynamic,adLockOptimistic
Do while not EquipRS1.eof
If (EquipRS1("startdate") < startserial) OR (EquipRS1("enddate") > endserial) Then
EquipRS1("startdate") = StartSerial
EquipRS1("enddate") = EndSerial
EquipRS1("circuitnum") = Class1("circuit number")
EquipRS1("modifieddate") = now
EquipRS1.Update
End If
EquipRS1.movenext
Loop
EquipRS1.close
set EquipRS1 = nothing
EquipConnect1.close
set EquipConnect1 = nothing
'========================================================
' Check that current rental rate will be superseded
'========================================================
Dim STQRConnect1, STQRRS1, STQRQuery1
Set STQRConnect1 = Server.CreateObject("ADODB.Connection")
STQRConnect1.Open QuotebaseDB
Set STQRRS1 = Server.CreateObject("ADODB.Recordset")
STQRQuery1 = "SELECT * FROM STQRtable WHERE CircuitID=" & Request("ID")
STQRRS1.Open STQRQuery1,STQRConnect1,adOpenDynamic,adLockOptimistic
Do while not STQRRS1.eof
If (STQRRS1("startdate") < startserial) OR (STQRRS1("enddate") > endserial) Then
STQRRS1("startdate") = StartSerial
STQRRS1("enddate") = EndSerial
STQRRS1("circuitnum") = Class1("circuit number")
STQRRS1("modifieddate") = now
STQRRS1.Update
End If
STQRRS1.movenext
Loop
STQRRS1.close
set STQRRS1 = nothing
STQRConnect1.close
set STQRConnect1 = nothing
'===========================================
' Update Connection Charge As A One Off Charge
'===========================================
Dim OneConnect, OneRS, OneQuery
Set OneConnect = Server.CreateObject("ADODB.Connection")
OneConnect.Open QuotebaseDB
Set OneRS = Server.CreateObject("ADODB.Recordset")
OneQuery = "SELECT * FROM OneOffCharges WHERE chargetype = 'Connection Charge' and CircuitID=" & Request("ID")
OneRS.Open OneQuery,OneConnect,adOpenDynamic,adLockOptimistic
If not oners.eof Then
OneRS("chargedate") = startserial
OneRS("modifieddate") = now
OneRS("chargetype") = "Connection Charge"
OneRS.Update
End If
OneRS.close
set OneRS = nothing
OneConnect.close
set OneConnect = nothing
Class1.close
set Class1 = nothing
Connect.close
set Connect = nothing
The loops don't appear to do much other then iterate over the record set. It is unlikely that you will need to do this in T-SQL as you can probably deduce everything from queries.
Most of it just looks like update statements
-- Check that current maintenance rate will be superseded
UPDATE maintenancetable
SET StartDate = #startSerial,
EndDate = #endSerial,
CircuitNum = #circuitNumber,
ModifiedDate = CURRENT_TIMESTAMP
WHERE CircuitID=#circuitId
AND (Startdate < #startSerial OR EndDate > #endSerial)
The contract period is a bit confusing it seems to be getting the first item of an array so maybe this is the equivalent of
SELECT TOP 1 ContractPeriod FROM circuits WHERE ID=#id
-- ? ORDER BY ContractPeriod ?

Is there a Perl equivalent of SAS' INTNX function or Javascript's Dateadd function?

I'm trying to convert Chinese lunar system to Gregorian using Perl, both for fun and for learning purposes. I thought there was some kind of easy mathematical algorithm to do the job but turned out I was wrong. Anyway, after a little googling around I came aross some ready SAS code that could do the job. Well, it was not too difficult for me to figure out how to rewrite most of the code in Perl. But there is something like this:
Convert2Gregorian = INTNX ('day', conDate, AddDay-1);
Google tells me that INTNX is a function that can return a date after which a certain date interval has been added. But using the keywords "Perl INTNX" gave me nothing useful. I then found a script written in Javascript, the general approach is about the same except that the Javascript uses Dateadd function, something like:
Return DateAdd(DateInterval.Day, AddDay - 1, conDate)
I also tried searching using PPM but was unable to find the module I wanted. Can someone kindly give me some pointers?
Thanks in advance :)
Update
Thanks to #psilva and #hobbs :)
Haha, finally I can translate one programming language to another. It's fun :)
Just for fun and maybe for later reference:
Here's the original SAS code and the Perl code translated by me. Correct me if I'm wrong :)
Note: Data incomplete.
SAS CODE IS AS FOLLOWS:
data DateNtoG (drop = Ngstrings conDate AddMonth AddDay Mrunyue I);
array NGlist{43} $18_TEMPORARY_(
"010110101010170130" /*(1968)*/
"010101101010000217" /*(1969)*/
"100101101101000206" /*(1970)*/
"010010101110150127" /*(1971)*/
);
input tYear tMonth tDay RunYue;
if (tyear >1967 and tyear<2011) then do;
NGstrings = NGlist(tYear - 1967);
conDate = MDY (substr (NGstrings,15,2),(NGstrings, 17,2), tYear);
AddMonth = tMonth;
select (substr(NGstrings, 14, 1));
when ("A" ) Mrunyue=10;
when ("B" ) Mrunyue=11;
when ( "C" ) Mrunyue=12;
otherwise Mrunyue = substr (NGstrings, 14,1);
end;
if ((RunYue=1) and (tMonth=Mrunyue) ANDMrunyue>0)or ((tMonth Mrunyue) AND Mrunyue>0) then
do;
Addmonth = tMonth+1;
end;
AddDay = tDay;
do i = 1 To AddMonth-1;
AddDay = AddDay + 29 + substr(NGstrings,i,1);
end;
dNtoG = INTNX ('day', conDate, AddDay - 1);
put "Transfereddate:" dNtoGdate9.;
end;
TRANSLATED Perl CODE IS AS FOLLOWS:
didn't handle the undefined situations for the moment
(I Changed the original SAS variable names)
#!perl
# A Chinese-Gregorian Calendar System Converter just for Testing
use Date::Calc qw(Add_Delta_Days);
use integer;
use strict;
use warnings;
$_ = shift #ARGV;
if (length == 8) {
$_.=0;
}
my ($Lunar_Year,$Lunar_Month,$Lunar_Day,$Leap_Month) = /(\d\d\d\d)(\d\d)(\d\d)(\d)/;
my %Lunar_Year_Patterns = qw/1968 010110101010170130 1969 010101101010000217 1970 100101101101000206 1971 010010101110150127/;
if (substr ($Lunar_Year_Patterns{$Lunar_Year},13,1) =~ /A/) {
$Leap_Month = 10;
} elsif (substr ($Lunar_Year_Patterns{$Lunar_Year},13,1)=~ /B/){
$Leap_Month = 11;
} elsif (substr ($Lunar_Year_Patterns{$Lunar_Year},13,1)=~ /C/){
$Leap_Month = 12;
} else {
$Leap_Month = substr($Lunar_Year_Patterns{$Lunar_Year},13,1);
}
my $First_Lunar_Day_In_Gregorian_Month = substr($Lunar_Year_Patterns{$Lunar_Year},14,2);
my $First_Lunar_Day_In_Gregorian_Day = substr($Lunar_Year_Patterns{$Lunar_Year},16,2);
my $AddMonth;
if ( (($Leap_Month ==1) && ($Lunar_Month == $Leap_Month) && ($Leap_Month > 0)) || (($Lunar_Month > $Leap_Month) && ($Leap_Month>0) ) ){
$AddMonth = $Lunar_Month +1;
} else {
$AddMonth = $Lunar_Month;
}
my $AddDay;
$AddDay = $Lunar_Day;
for(my $i = 1; $i <= $AddMonth - 1; $i++){
$AddDay = $AddDay +29 + substr($Lunar_Year_Patterns{$Lunar_Year},$i,1);
}
my #Gregorian = Add_Delta_Days($Lunar_Year,$First_Lunar_Day_In_Gregorian_Month,$First_Lunar_Day_In_Gregorian_Day,$AddDay -1);
print #Gregorian;
DateTime is the 800-pound gorilla of date handling. It's quite large, but it's large because it does a lot, and more importantly, it does it right.
With DateTime you would simply construct the DateTime object for the starting date, and then obtain the ending date by adding: $dt->add(days => $add_days).
Also, there's a DateTime::Calendar::Chinese that you can compare your results with, even if you want to reinvent this particular wheel for fun :)
Check out the delta functions in Date::Calc and Date::Calc::Object, and Date::Calc::PP. Specifically, you might want to look at the DateCalc_add_delta_days subroutine in the PP source.
You could also try looking at the source of Calendar::China.