WeixiangYan/CodeTransOcean huggingface dataset:
Task: Extensible prime generator







Python: islice(count(7), 0, None, 2)




Fortran:       DO WHILE(F*F <= LST)         
      DO WHILE(F <= LST/F)                      
      DO WHILE(F <= (IST + 2*(SBITS - 1))/F)    
      DO WHILE(F <= IST/F + (MOD(IST,F) + 2*(SBITS - 1))/F)
Task: Gray code







Python: >>> def int2bin(n):
	'From positive integer to list of binary bits, msb at index 0'
	if n:
		bits = []
		while n:
			n,remainder = divmod(n, 2)
			bits.insert(0, remainder)
		return bits
	else: return [0]

	
>>> def bin2int(bits):
	'From binary bits, msb at index 0 to integer'
	i = 0
	for bit in bits:
		i = i * 2 + bit
	return i




Fortran:       PROGRAM GRAY
      IMPLICIT NONE
      INTEGER IGRAY,I,J,K
      CHARACTER*5 A,B,C
      DO 10 I=0,31
      J=IGRAY(I,1)
      K=IGRAY(J,-1)
      CALL BINARY(A,I,5)
      CALL BINARY(B,J,5)
      CALL BINARY(C,K,5)
      PRINT 99,I,A,B,C,K
   10 CONTINUE
   99 FORMAT(I2,3H : ,A5,4H => ,A5,4H => ,A5,3H : ,I2)
      END

      FUNCTION IGRAY(N,D)
      IMPLICIT NONE
      INTEGER D,K,N,IGRAY
      IF(D.LT.0) GO TO 10
      IGRAY=IEOR(N,ISHFT(N,-1))
      RETURN
   10 K=N
      IGRAY=0
   20 IGRAY=IEOR(IGRAY,K)
      K=K/2
      IF(K.NE.0) GO TO 20
      END

      SUBROUTINE BINARY(S,N,K)
      IMPLICIT NONE
      INTEGER I,K,L,N
      CHARACTER*(*) S
      L=LEN(S)
      DO 10 I=0,K-1
C The following line may replace the next block-if,
C on machines using ASCII code :
C     S(L-I:L-I)=CHAR(48+IAND(1,ISHFT(N,-I)))
C On EBCDIC machines, use 240 instead of 48.
      IF(BTEST(N,I)) THEN
      S(L-I:L-I)='1'
      ELSE
      S(L-I:L-I)='0'
      END IF
   10 CONTINUE
      S(1:L-K)=''
      END
Task: File extension is in extensions list







Python: def isExt(fileName, extensions):
  return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))




Fortran:         IT = ICHAR(TEXT(I:I)) - ICHAR("a")	
        IF (IT.GE.0 .AND. IT.LE.25) TEXT(I:I) = CHAR(IT + ICHAR("A"))
Task: Extreme floating point values







Python: >>> 
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>> 
>>> for value in (inf, _inf, _zero, nan): print (value)

inf
-inf
-0.0
nan
>>> 
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> -0.
-0.0
>>> 
>>> nan == nan
False
>>> nan is nan
True
>>> 0. == -0.
True
>>> 0. is -0.
False
>>> inf + _inf
nan
>>> 0.0 * nan
nan
>>> nan * 0.0
nan
>>> 0.0 * inf
nan
>>> inf * 0.0
nan




Fortran:        REAL*8		BAD,NaN			
       PARAMETER (NaN = Z'FFFFFFFFFFFFFFFF')	
       PARAMETER (BAD = Z'FFFFFFFFFFFFFFFF')	
       CHARACTER*3	BADASTEXT		
       DATA		BADASTEXT/" ? "/	
       REAL*8		PINF,NINF		
       PARAMETER (PINF = Z'7FF0000000000000')	
       PARAMETER (NINF = Z'FFF0000000000000')
Task: Flow-control structures







Python: 
for i in range(n):
    if (n%2) == 0:
        continue
    if (n%i) == 0:
        result = i
        break
else:
    result = None
    print "No odd factors found"




Fortran:       ...
      ASSIGN 1101 to WHENCE   
      GO TO 1000              
 1101 CONTINUE                
      ... 
      ASSIGN 1102 to WHENCE   
      GO TO 1000              
 1102 CONTINUE                
      ...
Common code, far away.
 1000 do something            
      GO TO WHENCE
Task: Find if a point is within a triangle







Python: 

from sympy.geometry import Point, Triangle

def sign(pt1, pt2, pt3):
    
    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)


def iswithin(point, pt1, pt2, pt3):
    
    zval1 = sign(point, pt1, pt2)
    zval2 = sign(point, pt2, pt3)
    zval3 = sign(point, pt3, pt1)
    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0
    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0
    return notanyneg or notanypos

if __name__ == "__main__":
    POINTS = [Point(0, 0)]
    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))
    for pnt in POINTS:
        a, b, c = TRI.vertices
        isornot = "is" if iswithin(pnt, a, b, c) else "is not"
        print("Point", pnt, isornot, "within the triangle", TRI)




Fortran: PROGRAM POINT_WITHIN_TRIANGLE

IMPLICIT NONE

REAL (KIND = SELECTED_REAL_KIND (8)) px, py, ax, ay, bx, by, cx, cy

px = 0.0
py = 0.0
ax = 1.5
ay = 2.4
bx = 5.1
by = -3.1
cx = -3.8
cy = 1.2

IF (IS_P_IN_ABC (px, py, ax, ay, bx, by, cx, cy)) THEN

    WRITE (*, *) 'Point (', px, ', ', py, ') is within triangle &
        [(', ax, ', ', ay,'), (', bx, ', ', by, '), (', cx, ', ', cy, ')].'

  ELSE

    WRITE (*, *) 'Point (', px, ', ', py, ') is not within triangle &
        [(', ax, ', ', ay,'), (', bx, ', ', by, '), (', cx, ', ', cy, ')].'

END IF

CONTAINS

  
  LOGICAL FUNCTION IS_P_IN_ABC (px, py, ax, ay, bx, by, cx, cy)

    REAL (KIND = SELECTED_REAL_KIND (8)), INTENT (IN) :: px, py, ax, ay, bx, by, cx, cy
    REAL (KIND = SELECTED_REAL_KIND (8)) :: vabx, vaby, vacx, vacy, a, b

    vabx = bx - ax
    vaby = by - ay
    vacx = cx - ax
    vacy = cy - ay

    a = ((px * vacy - py * vacx) - (ax * vacy - ay * vacx)) / &
        (vabx * vacy - vaby * vacx)
    b = -((px * vaby - py * vabx) - (ax * vaby - ay * vabx)) / &
        (vabx * vacy - vaby * vacx)

    IF ((a .GT. 0) .AND. (b .GT. 0) .AND. (a + b < 1)) THEN

        IS_P_IN_ABC = .TRUE.

      ELSE

        IS_P_IN_ABC = .FALSE.

    END IF

  END FUNCTION IS_P_IN_ABC

END PROGRAM POINT_WITHIN_TRIANGLE
Task: Return multiple values







Python: def addsub(x, y):
  return x + y, x - y




Fortran: module multiple_values
implicit none
type res
  integer :: p, m
end type

contains

function addsub(x,y) result(r)
  integer :: x, y
  type(res) :: r 
  r%p = x+y
  r%m = x-y
end function
end module

program main
  use multiple_values 
  print *, addsub(33, 22)
end program
Task: Fractran







Python: from fractions import Fraction

def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
                        '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'
                        '13 / 11, 15 / 14, 15 / 2, 55 / 1'):
    flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]

    n = Fraction(n)
    while True:
        yield n.numerator
        for f in flist:
            if (n * f).denominator == 1:
                break
        else:
            break
        n *= f
    
if __name__ == '__main__':
    n, m = 2, 15
    print('First %i members of fractran(%i):\n  ' % (m, n) +
          ', '.join(str(f) for f,i in zip(fractran(n), range(m))))




Fortran: C:\Nicky\RosettaCode\FRACTRAN\FRACTRAN.for(6) : Warning: This name has not been given an explicit type.   [M]
       INTEGER P(M),Q(M)
Task: Substring_Top and tail







Python: print "knight"[1:]     
print "socks"[:-1]     
print "brooms"[1:-1]   




Fortran: program substring

  character(len=5) :: string
  string = "Hello"
  
  write (*,*) string
  write (*,*) string(2:)
  write (*,*) string( :len(string)-1)
  write (*,*) string(2:len(string)-1)

end program substring
Task: Boolean values







Python: >>> True
True
>>> not True
False
>>> 
>>> False + 0
0
>>> True + 0
1
>>> False + 0j
0j
>>> True * 3.141
3.141
>>> 
>>> not 0
True
>>> not not 0
False
>>> not 1234
False
>>> bool(0.0)
False
>>> bool(0j)
False
>>> bool(1+2j)
True
>>> 
>>> bool([])
False
>>> bool([None])
True
>>> 'I contain something' if (None,) else 'I am empty'
'I contain something'
>>> bool({})
False
>>> bool("")
False
>>> bool("False")
True




Fortran:       TYPE MIXED
       LOGICAL*1 LIVE
       REAL*8    VALUE
      END TYPE MIXED
      TYPE(MIXED) STUFF(100)
Task: Bitmap_Histogram







Python: from PIL import Image


image = Image.open("lena.jpg")

width, height = image.size

amount = width * height


total = 0

bw_image = Image.new('L', (width, height), 0)

bm_image = Image.new('1', (width, height), 0)

for h in range(0, height):
    for w in range(0, width):
        r, g, b = image.getpixel((w, h))

        greyscale = int((r + g + b) / 3)
        total += greyscale

        bw_image.putpixel((w, h), gray_scale)


avg = total / amount

black = 0
white = 1

for h in range(0, height):
    for w in range(0, width):
        v = bw_image.getpixel((w, h))

        if v >= avg:
            bm_image.putpixel((w, h), white)
        else:
            bm_image.putpixel((w, h), black)

bw_image.show()
bm_image.show()




Fortran: module RCImageProcess
  use RCImageBasic
  implicit none
contains

  subroutine get_histogram(img, histogram)
    type(scimage), intent(in) :: img
    integer, dimension(0:255), intent(out) :: histogram
    
    integer :: i

    histogram = 0
    do i = 0,255
       histogram(i) = sum(img%channel, img%channel == i)
    end do
  end subroutine get_histogram

  function histogram_median(histogram)
    integer, dimension(0:255), intent(in) :: histogram
    integer :: histogram_median
    
    integer :: from, to, left, right

    from = 0
    to = 255
    left = histogram(from)
    right = histogram(to)
    do while ( from /= to )
       if ( left < right ) then
          from = from + 1
          left = left + histogram(from)
       else
          to = to - 1
          right = right + histogram(to)
       end if
    end do
    histogram_median = from
  end function histogram_median
  
end module RCImageProcess
Task: Ulam spiral (for primes)







Python: 
from __future__ import print_function, division
from math import sqrt

def cell(n, x, y, start=1):
    d, y, x = 0, y - n//2, x - (n - 1)//2
    l = 2*max(abs(x), abs(y))
    d = (l*3 + x + y) if y >= x else (l - x - y)
    return (l - 1)**2 + d + start - 1

def show_spiral(n, symbol='
    top = start + n*n + 1
    is_prime = [False,False,True] + [True,False]*(top//2)
    for x in range(3, 1 + int(sqrt(top))):
        if not is_prime[x]: continue
        for i in range(x*x, top, x*2):
            is_prime[i] = False

    cell_str = lambda x: f(x) if is_prime[x] else space
    f = lambda _: symbol 

    if space == None: space = ' '*len(symbol)

    if not len(symbol): 
        max_str = len(str(n*n + start - 1))
        if space == None: space = '.'*max_str + ' '
        f = lambda x: ('%' + str(max_str) + 'd ')%x

    for y in range(n):
        print(''.join(cell_str(v) for v in [cell(n, x, y, start) for x in range(n)]))
    print()

show_spiral(10, symbol=u'♞', space=u'♘') 
show_spiral(9, symbol='', space=' - ')






Fortran: program ulam
  implicit none

  integer, parameter :: nsize = 49
  integer :: i, j, n, x, y
  integer :: a(nsize*nsize) = (/ (i, i = 1, nsize*nsize) /)
  character(1)  :: spiral(nsize, nsize) = " " 
  character(2)  :: sstr
  character(10) :: fmt
  
  n = 1
  x = nsize / 2 + 1
  y = x
  if(isprime(a(n))) spiral(x, y) = "O"
  n = n + 1

  do i = 1, nsize-1, 2
    do j = 1, i
      x = x + 1
      if(isprime(a(n))) spiral(x, y) = "O"
      n = n + 1
    end do

    do j = 1, i
      y = y - 1
      if(isprime(a(n))) spiral(x, y) = "O"
      n = n + 1
    end do

    do j = 1, i+1
      x = x - 1
      if(isprime(a(n))) spiral(x, y) = "O"
      n = n + 1
    end do

    do j = 1, i+1
      y = y + 1
      if(isprime(a(n))) spiral(x, y) = "O"
      n = n + 1
    end do
  end do

  do j = 1, nsize-1
    x = x + 1
    if(isprime(a(n))) spiral(x, y) = "O"
    n = n + 1
  end do

  write(sstr, "(i0)") nsize
  fmt = "(" // sstr // "(a,1x))"
  do i = 1, nsize
    write(*, fmt) spiral(:, i)
  end do

contains

function isprime(number)
  logical :: isprime
  integer, intent(in) :: number
  integer :: i
 
  if(number == 2) then
    isprime = .true.
  else if(number < 2 .or. mod(number,2) == 0) then
    isprime = .false.
  else
    isprime = .true.
    do i = 3, int(sqrt(real(number))), 2
      if(mod(number,i) == 0) then
        isprime = .false.
        exit
      end if
    end do
  end if
end function
end program
Task: Bitmap_Bézier curves_Cubic







Python: def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
    pts = []
    for i in range(n+1):
        t = i / n
        a = (1. - t)**3
        b = 3. * t * (1. - t)**2
        c = 3.0 * t**2 * (1.0 - t)
        d = t**3
        
        x = int(a * x0 + b * x1 + c * x2 + d * x3)
        y = int(a * y0 + b * y1 + c * y2 + d * y3)
        pts.append( (x, y) )
    for i in range(n):
        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])
Bitmap.cubicbezier = cubicbezier

bitmap = Bitmap(17,17)
bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)
bitmap.chardisplay()







Fortran: subroutine cubic_bezier(img, p1, p2, p3, p4, color)
  type(rgbimage), intent(inout) :: img
  type(point), intent(in) :: p1, p2, p3, p4
  type(rgb), intent(in) :: color

  integer :: i, j
  real :: pts(0:N_SEG,0:1), t, a, b, c, d, x, y

  do i = 0, N_SEG
     t = real(i) / real(N_SEG)
     a = (1.0 - t)**3.0
     b = 3.0 * t * (1.0 - t)**2
     c = 3.0 * (1.0 - t) * t**2
     d = t**3.0
     x = a * p1%x + b * p2%x + c * p3%x + d * p4%x
     y = a * p1%y + b * p2%y + c * p3%y + d * p4%y
     pts(i,0) = x
     pts(i,1) = y
  end do

  do i = 0, N_SEG-1
     j = i + 1
     call draw_line(img, point(pts(i,0), pts(i,1)), &
                    point(pts(j,0), pts(j,1)), color)
  end do

end subroutine cubic_bezier
Task: Hello world_Line printer







Python: lp = open("/dev/lp0")
lp.write("Hello World!\n")
lp.close()




Fortran:       WRITE (6,1)
    1 FORMAT ("+HELLO WORLD
      END
Task: Magic squares of odd order







Python: >>> def magic(n):
    for row in range(1, n + 1):
        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in
                       (n * ((row + col - 1 + n // 2) % n) +
                       ((row + 2 * col - 2) % n) + 1
                       for col in range(1, n + 1))))
    print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2))

    
>>> for n in (5, 3, 7):
	print('\nOrder %i\n=======' % n)
	magic(n)

	

Order 5
=======
17 24  1  8 15
23  5  7 14 16
 4  6 13 20 22
10 12 19 21  3
11 18 25  2  9

All sum to magic number 65

Order 3
=======
8 1 6
3 5 7
4 9 2

All sum to magic number 15

Order 7
=======
30 39 48  1 10 19 28
38 47  7  9 18 27 29
46  6  8 17 26 35 37
 5 14 16 25 34 36 45
13 15 24 33 42 44  4
21 23 32 41 43  3 12
22 31 40 49  2 11 20

All sum to magic number 175
>>>




Fortran: program Magic_Square
  implicit none

  integer, parameter :: order = 15
  integer :: i, j
 
  write(*, "(a, i0)") "Magic Square Order: ", order
  write(*, "(a)")     "----------------------"
  do i = 1, order
    do j = 1, order
      write(*, "(i4)", advance = "no") f1(order, i, j)
    end do
    write(*,*)
  end do
  write(*, "(a, i0)") "Magic number = ", f2(order)

contains

integer function f1(n, x, y)
  integer, intent(in) :: n, x, y

  f1 = n * mod(x + y - 1 + n/2, n) + mod(x + 2*y - 2, n) + 1
end function

integer function f2(n)
  integer, intent(in) :: n

  f2 = n * (1 + n * n) / 2
end function
end program
Task: Sorting algorithms_Pancake sort







Python: tutor = False

def pancakesort(data):
    if len(data) <= 1:
        return data
    if tutor: print()
    for size in range(len(data), 1, -1):
        maxindex = max(range(size), key=data.__getitem__)
        if maxindex+1 != size:
            
            if maxindex != 0:
                
                if tutor: print('With: %r doflip  %i'
                                % ( ' '.join(str(x) for x in data), maxindex+1 ))
                data[:maxindex+1] = reversed(data[:maxindex+1])
            
            if tutor: print('With: %r  doflip %i'
                                % ( ' '.join(str(x) for x in data), size ))
            data[:size] = reversed(data[:size])
    if tutor: print()




Fortran: program Pancake_Demo
  implicit none
 
  integer :: list(8) = (/ 1, 4, 7, 2, 5, 8, 3, 6 /)
 
  call Pancake_sort(list)
 
contains
 
subroutine Pancake_sort(a)
  
  integer, intent(in out) :: a(:)
  integer :: i, maxpos
  
  write(*,*) a
  do i = size(a), 2, -1
     

    maxpos = maxloc(a(1:i), 1)
 

    if (maxpos == i) cycle
 

    if (maxpos /= 1) then
      a(1:maxpos) = a(maxpos:1:-1)
      write(*,*) a
    end if
 

    a(1:i) = a(i:1:-1)
    write(*,*) a
  end do
  
end subroutine
 
end program Pancake_Demo
Task: Call a function







Python: def no_args():
    pass

no_args()

def fixed_args(x, y):
    print('x=%r, y=%r' % (x, y))

fixed_args(1, 2)        


fixed_args(y=2, x=1)


myargs=(1,2) 
fixed_args(*myargs)

def opt_args(x=1):
    print(x)

opt_args()              
opt_args(3.141)         

def var_args(*v):
    print(v)

var_args(1, 2, 3)       
var_args(1, (2,3))      
var_args()              


fixed_args(y=2, x=1)    


if 1:
    no_args()


assert no_args() is None

def return_something():
    return 1
x = return_something()

def is_builtin(x):
	print(x.__name__ in dir(__builtins__))

is_builtin(pow)         
is_builtin(is_builtin)  



def takes_anything(*args, **kwargs):
    for each in args:
        print(each)
    for key, value in sorted(kwargs.items()):
        print("%s:%s" % (key, value))
    
    wrapped_fn(*args, **kwargs)
    
    













Fortran: program main
implicit none
integer :: a
integer :: f, g
logical :: lresult
interface
  integer function h(a,b,c)
    integer :: a, b
    integer, optional :: c
  end function
end interface
write(*,*) 'no arguments: ', f()
write(*,*) '-----------------'
write(*,*) 'fixed arguments: ', g(5,8,lresult)
write(*,*) '-----------------'
write(*,*) 'optional arguments: ', h(5,8), h(5,8,4)
write(*,*) '-----------------'
write(*,*) 'function with variable arguments: Does not apply
write(*,*) 'An option is to pass arrays of variable lengths.'
write(*,*) '-----------------'
write(*,*) 'named arguments: ', h(c=4,b=8,a=5)
write(*,*) '-----------------'
write(*,*) 'function in statement context: Does not apply
write(*,*) '-----------------'
write(*,*) 'Fortran passes memory location of variables as arguments.'
write(*,*) 'So an argument can hold the return value.'
write(*,*) 'function result: ', g(5,8,lresult) , ' function successful? ', lresult
write(*,*) '-----------------'
write(*,*) 'Distinguish between built-in and user-defined functions: Does not apply
write(*,*) '-----------------'
write(*,*) 'Calling a subroutine: '
a = 30
call sub(a)
write(*,*) 'Function call: ', f()
write(*,*) '-----------------'
write(*,*) 'All variables are passed as pointers.'
write(*,*) 'Problems can arise if instead of sub(a), one uses sub(10).'
write(*,*) '-----------------'
end program


integer function f()
f = 10
end function


integer function g(a, b, lresult)
integer :: a, b
logical :: lresult
g = a+b
lresult = .TRUE.
end function


integer function h(a, b, c)
integer :: a, b
integer, optional :: c

h = a+b
if(present(c)) then
  h = h+10*c
end if
end function


subroutine sub(a)
integer :: a
a = a*100
write(*,*) 'Output of subroutine: ', a
end subroutine
Task: Extract file extension







Python: import re
def extractExt(url):
  m = re.search(r'\.[A-Za-z0-9]+$', url)
  return m.group(0) if m else ""




Fortran:       MODULE TEXTGNASH	
       CHARACTER*10 DIGITS		
       CHARACTER*11 DDIGITS		
       CHARACTER*13 SDDIGITS		
       CHARACTER*4  EXPONENTISH		
       CHARACTER*17 NUMBERISH		
       CHARACTER*16 HEXLETTERS		
       CHARACTER*62 DIGILETTERS		
       CHARACTER*26 LITTLELETTERS,BIGLETTERS	
       CHARACTER*52 LETTERS		
       CHARACTER*66 NAMEISH		
       CHARACTER*3  ODDITIES		
       CHARACTER*1 CHARACTER(72)	
       EQUIVALENCE			
     1  (CHARACTER( 1),EXPONENTISH,NUMBERISH),	
     2  (CHARACTER( 5),SDDIGITS),		
     3  (CHARACTER( 7),DDIGITS,NAMEISH),	
     4  (CHARACTER( 8),DIGITS,HEXLETTERS,DIGILETTERS),	
     5  (CHARACTER(18),BIGLETTERS,LETTERS),	
     6  (CHARACTER(44),LITTLELETTERS),		
     7  (CHARACTER(70),ODDITIES)		
       DATA EXPONENTISH /"eEdD"/	
       DATA SDDIGITS /"+-.0123456789"/	
       DATA BIGLETTERS    /"ABCDEFGHIJKLMNOPQRSTUVWXYZ"/	
       DATA LITTLELETTERS /"abcdefghijklmnopqrstuvwxyz"/	
       DATA ODDITIES /"_:#"/		

       CHARACTER*62 GOODEXT	
       EQUIVALENCE (CHARACTER(8),GOODEXT)
c       PARAMETER (GOODEXT = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"	
c     1                    //"abcdefghijklmnopqrstuvwxyz"	
c     2                    //"0123456789")			
       INTEGER MEXT		
       PARAMETER (MEXT = 28)	
       CONTAINS
        CHARACTER*(MEXT) FUNCTION FEXT(FNAME)	
         CHARACTER*(*) FNAME	
         INTEGER L1,L2		
          L2 = LEN(FNAME)	
          L1 = L2		
   10     IF (L1.GT.0) THEN	
            IF (INDEX(GOODEXT,FNAME(L1:L1)).GT.0) THEN	
              L1 = L1 - 1		
              GO TO 10			
            END IF		
            IF (FNAME(L1:L1).EQ.".") THEN	
              L1 = L1 - 1			
              GO TO 20				
            END IF		
          END IF		
          L1 = L2		
   20     FEXT = FNAME(L1 + 1:L2)	
        END FUNCTION FEXT	
      END MODULE TEXTGNASH	

      PROGRAM POKE
      USE TEXTGNASH

      WRITE (6,*) FEXT("Picture.jpg")
      WRITE (6,*) FEXT("http://mywebsite.com/picture/image.png")
      WRITE (6,*) FEXT("myuniquefile.longextension")
      WRITE (6,*) FEXT("IAmAFileWithoutExtension")
      WRITE (6,*) FEXT("/path/to.my/file")
      WRITE (6,*) FEXT("file.odd_one")
      WRITE (6,*)
      WRITE (6,*) "Now for the new test collection..."
      WRITE (6,*) FEXT("http://example.com/download.tar.gz")
      WRITE (6,*) FEXT("CharacterModel.3DS")
      WRITE (6,*) FEXT(".desktop")
      WRITE (6,*) FEXT("document")
      WRITE (6,*) FEXT("document.txt_backup")
      WRITE (6,*) FEXT("/etc/pam.d/login")
      WRITE (6,*) "Approved characters: ",GOODEXT
      END
Task: Copy a string







Python: >>> src = "hello"
>>> a = src
>>> b = src[:]
>>> import copy
>>> c = copy.copy(src)
>>> d = copy.deepcopy(src)
>>> src is a is b is c is d
True




Fortran: str2 = str1
Task: Keyboard input_Obtain a Y or N response







Python: 

try:
    from msvcrt import getch
except ImportError:
    def getch():
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

print "Press Y or N to continue"
while True:
    char = getch()
    if char.lower() in ("y", "n"):
        print char
        break




Fortran:       CHARACTER*120 FUNCTION REPLY(QUERY)    
Concocted by R.N.McLean (whom God preserve), December MM.
       CHARACTER*(*) QUERY	
       CHARACTER*120 TEXT	
       INTEGER MSG,KEYS,LSTNB	
       COMMON /IOUNITS/ MSG,KEYS
        WRITE (MSG,1) QUERY(1:LSTNB(QUERY)),"?"
    1   FORMAT (2A,$)		
        READ (KEYS,1) TEXT	
        REPLY = TEXT		
       RETURN			
      END 			

      REAL*8 FUNCTION REPLYN(QUERY)	
Concocted by R.N.McLean (whom God preserve), December MM.
       CHARACTER*(*) QUERY	
       REAL X			
       INTEGER MSG,KEYS,LSTNB	
       COMMON /IOUNITS/ MSG,KEYS
    1   WRITE (MSG,2) QUERY(1:LSTNB(QUERY))	
    2   FORMAT (A,$)		
        READ (KEYS,*,ERR = 3) X	
        REPLYN = X		
       RETURN			
    3   WRITE (MSG,4)		
    4   FORMAT ('Distasteful number. Try again...')	
        GO TO 1			
      END			

      LOGICAL FUNCTION YEA(QUERY)	
Concocted by R.N.McLean (whom God preserve), December MM.
       CHARACTER*(*) QUERY	
       CHARACTER*120 WHAT,REPLY	
       CHARACTER*1 C		
       INTEGER MSG,KEYS		
       COMMON /IOUNITS/ MSG,KEYS
       INTEGER L		
    1   WHAT = REPLY(QUERY)	
        DO L = 1,LEN(WHAT)	
          C = WHAT(L:L)		
          IF (C .NE. ' ') GO TO 10	
        END DO			
        WRITE (MSG,2)		
    2   FORMAT ('All blank?')	
    3   WRITE (MSG,4) 		
    4   FORMAT ('I dig it not. Try Yes/Si/Da/Oui/Ja, or No')
        GO TO 1			
   10   IF (INDEX('YySsDdOoJj',C) .GT. 0) THEN	
          YEA = .TRUE.		
        ELSE IF (INDEX('Nn',C) .GT. 0) THEN	
          YEA = .FALSE.		
        ELSE			
          GO TO 3		
        END IF			
       RETURN			
      END			
      LOGICAL FUNCTION NAY(QUERY)	
Concocted by R.N.McLean (whom God preserve), December MM.
       CHARACTER*(*) QUERY	
       LOGICAL YEA		
        NAY = .NOT.YEA(QUERY)	
       RETURN			
      END