make trigonometric function table
358329
function _makeCosSinTable() {
    var n2 = _n >> 1,
        n4 = _n >> 2,
        n8 = _n >> 3,
        n2p4 = n2 + n4,
        t = Math.sin(Math.PI/_n),
        dc = 2*t*t,
        ds = Math.sqrt(dc*(2 - dc)),
        c = _cstb[n4] = 1,
        s = _cstb[0] = 0;
    t = 2*dc;
    for(var i=1; i<n8; i++) {
      c -= dc;
      dc += t*c;
      s += ds;
      ds -= t*s;
      _cstb[i] = s;
      _cstb[n4 - i] = c;
    }
    if(n8 !== 0) {
      _cstb[n8] = Math.sqrt(0.5);
    }
    for(var j=0; j<n4; j++) {
      _cstb[n2 - j]  = _cstb[j];
    }
    for(var k=0; k<n2p4; k++) {
      _cstb[k + n2] = -_cstb[k];
    }
  }
1170272
def prepare_table(table):
    
    n = len(table)
    for i, row in enumerate(table):
        assert len(row) == n
        for j, el in enumerate(row):
            if i == j:
                table[i][i] = 0.0
            elif i > j:
                table[i][j] = 1-table[j][i]
    return table
570542
function tableHead () {
  var args = arrayify(arguments)
  var data = args.shift()
  if (!data) return
  args.pop()
  var cols = args
  var colHeaders = cols.map(function (col) {
    var spl = col.split('|')
    return spl[1] || spl[0]
  })
  cols = cols.map(function (col) {
    return col.split('|')[0]
  })
  var toSplice = []
  cols = cols.filter(function (col, index) {
    var hasValue = data.some(function (row) {
      return typeof row[col] !== 'undefined'
    })
    if (!hasValue) toSplice.push(index)
    return hasValue
  })
  toSplice.reverse().forEach(function (index) {
    colHeaders.splice(index, 1)
  })

  var table = '| ' + colHeaders.join(' | ') + ' |\n'
  table += cols.reduce(function (p) { return p + ' --- |' }, '|') + '\n'
  return table
}
740217
function generateTableDataInsideScores(table){
	// Save to allow in function referencte
	table = table || this;
	var columns = table.columns*1;

	/*
		Create data table
	*/
	var scores = table.scores;

	// Just warn (DEBUG mode...)
	if(!scores)
		console.log('Table is empty!');

	// Get evaluation method ('min', 'max', custom...)
	var evalMethod = getMethodFor(table.evaluateMethod);

	// List of all the keys to sort
	var keysToSort = ['final'];

	// Go through all scores, creating a unique row
	_(scores).forEach(function(score){
		/*
			Notice score structure:

			{
				tableId: [this table id]
				teamId: xxx,
				scores: {
					  0: {value: xxx, data: {}},
					'1': {value: xxx, data: {}},
					  2: {value: xxx, data: {}}
					  [...],
				}
			}
		*/

		// This will be the object inserted in the table's data array
		// var scoreData = {};

		// Add simple attributes
		// scoreData['id'] = score.id || null;
		// scoreData['teamId'] = score.teamId || null;
		// scoreData['tableId'] = score.tableId || null;
		// scoreData['team'] = score.teamId || null;
		// scoreData.team: score.team.name
		// scoreData.country: score.team.country

		// Add scores data
		var scoreValues = [];
		for(var i = 0; i < columns; i++){

			// Get value and add to scoreValues
			var value = null;
			if(score.scores[i])
				value = score.scores[i].value;

			scoreValues.push(value);

			// Generate field key and saves
			// var field = 'score.'+(i+1);
			// score[field] = score.scores.value || null;
		}

		// Compute final score and adds to scoreData
		var finalScores = '?';

		// If evalMethod is set, let's compute the score. 
		if(evalMethod) {
			finalScores = evalMethod(scoreValues) || 0;
		}

		var showScore = finalScores;

		if(_.isArray(finalScores)){
			showScore = finalScores[0];

			for(var i = 1; i < finalScores.length; i++){
				var fieldKey = 'final'+(i+1); // Like: final2, final3, ...
				score[fieldKey] = finalScores[i];

				if(keysToSort.length <= i)
					keysToSort.push(fieldKey);
			}
		}

		score['final'] = showScore;

		// Add to table data
		// tableRows.push(score)
	});

	// Sort by 'final' field and reverse if needed
	var finalData = _.sortBy(scores, keysToSort);

	if(table.sort == 'desc')
		finalData = finalData.reverse();

	// Rank Table
	var pos = 0;
	var lastRow = null;

	_.forEach(finalData, function(row){
		pos++;

		var sameRanking = (lastRow ? true : false);
		for(var k in keysToSort){
			var key = keysToSort[k];
			if(lastRow && lastRow[key] != row[key]){
				sameRanking = false;
				break;
			}
		}

		if(sameRanking){
			// Keeps the same ranking if scores are the same
			return row.rank = lastRow.rank;
		}else{
			// Set rank as current position
			row.rank = pos;

		}
		// Save current row as last one
		lastRow = row;
	});

	// Self assign the table
	this.scores = finalData;

	// Return the table
	return this.scores;
}
439040
def __make_table(yfmtfunc, fmtfunc, endline, data, fxyz, sortx=None, sorty=None, seplinefunc=None):  # noqa: E501
    """"""
    vx = {}
    vy = {}
    vz = {}
    vxf = {}

    # Python 2 backward compatibility
    fxyz = lambda_tuple_converter(fxyz)

    tmp_len = 0
    for e in data:
        xx, yy, zz = [str(s) for s in fxyz(*e)]
        tmp_len = max(len(yy), tmp_len)
        vx[xx] = max(vx.get(xx, 0), len(xx), len(zz))
        vy[yy] = None
        vz[(xx, yy)] = zz

    vxk = list(vx)
    vyk = list(vy)
    if sortx:
        vxk.sort(key=sortx)
    else:
        try:
            vxk.sort(key=int)
        except Exception:
            try:
                vxk.sort(key=atol)
            except Exception:
                vxk.sort()
    if sorty:
        vyk.sort(key=sorty)
    else:
        try:
            vyk.sort(key=int)
        except Exception:
            try:
                vyk.sort(key=atol)
            except Exception:
                vyk.sort()

    if seplinefunc:
        sepline = seplinefunc(tmp_len, [vx[x] for x in vxk])
        print(sepline)

    fmt = yfmtfunc(tmp_len)
    print(fmt % "", end=' ')
    for x in vxk:
        vxf[x] = fmtfunc(vx[x])
        print(vxf[x] % x, end=' ')
    print(endline)
    if seplinefunc:
        print(sepline)
    for y in vyk:
        print(fmt % y, end=' ')
        for x in vxk:
            print(vxf[x] % vz.get((x, y), "-"), end=' ')
        print(endline)
    if seplinefunc:
        print(sepline)
218909
function generateTables() {

        function buildLiteral( literal ) {

            return `"${ util.stringEscape( literal ) }"`;

        }

        function buildRegexp( cls ) {

            return "/^["
                + ( cls.inverted ? "^" : "" )
                + cls.value
                    .map( part => (

                        Array.isArray( part )
                            ? util.regexpEscape( part[ 0 ] )
                                + "-"
                                + util.regexpEscape( part[ 1 ] )
                            : util.regexpEscape( part )

                    ) )
                    .join( "" )
                + "]/"
                + ( cls.ignoreCase ? "i" : "" );

        }

        function buildExpectation( e ) {

            switch ( e.type ) {

                case "rule":
                    return `peg$otherExpectation("${ util.stringEscape( e.value ) }")`;

                case "literal":
                    return "peg$literalExpectation(\""
                           + util.stringEscape( e.value )
                           + "\", "
                           + e.ignoreCase
                           + ")";

                case "class": {

                    const parts = e.value.map( part =>
                        ( Array.isArray( part )
                            ? `["${ util.stringEscape( part[ 0 ] ) }", "${ util.stringEscape( part[ 1 ] ) }"]`
                            : `"${ util.stringEscape( part ) }"` )
                    );

                    return "peg$classExpectation(["
                           + parts.join( ", " ) + "], "
                           + e.inverted + ", "
                           + e.ignoreCase
                           + ")";

                }

                case "any":
                    return "peg$anyExpectation()";

                // istanbul ignore next
                default:
                    session.fatal( `Unknown expectation type (${ JSON.stringify( e ) })` );

            }

        }

        function buildFunc( f ) {

            return `function(${ f.params.join( ", " ) }) {${ f.body }}`;

        }

        if ( options.optimize === "size" ) {

            return [
                "var peg$literals = [",
                indent2( ast.literals.map( buildLiteral ).join( ",\n" ) ),
                "];",
                "var peg$regexps = [",
                indent2( ast.classes.map( buildRegexp ).join( ",\n" ) ),
                "];",
                "var peg$expectations = [",
                indent2( ast.expectations.map( buildExpectation ).join( ",\n" ) ),
                "];",
                "var peg$functions = [",
                indent2( ast.functions.map( buildFunc ).join( ",\n" ) ),
                "];",
                "",
                "var peg$bytecode = [",
                indent2( ast.rules
                    .map( rule =>
                        `peg$decode("${
                            util.stringEscape( rule.bytecode
                                .map( b => String.fromCharCode( b + 32 ) )
                                .join( "" )
                            )
                        }")`
                    )
                    .join( ",\n" )
                ),
                "];"
            ].join( "\n" );

        }

        return ast.literals
            .map( ( c, i ) => "var " + l( i ) + " = " + buildLiteral( c ) + ";" )
            .concat( "", ast.classes.map(
                ( c, i ) => "var " + r( i ) + " = " + buildRegexp( c ) + ";"
            ) )
            .concat( "", ast.expectations.map(
                ( c, i ) => "var " + e( i ) + " = " + buildExpectation( c ) + ";"
            ) )
            .concat( "", ast.functions.map(
                ( c, i ) => "var " + f( i ) + " = " + buildFunc( c ) + ";"
            ) )
            .join( "\n" );

    }
1173519
function FFT() {
  
  var _n = 0,          // order
      _bitrev = null,  // bit reversal table
      _cstb = null;    // sin/cos table
  var _tre, _tim;
  
  this.init = function (n) {
    if(n !== 0 && (n & (n - 1)) === 0) {
      _n = n;
      _setVariables();
      _makeBitReversal();
      _makeCosSinTable();
    } else {
      throw new Error("init: radix-2 required");
    }
  };
    
  // 1D-FFT
  this.fft1d = function (re, im) {
    fft(re, im, 1);
  };
    
  // 1D-IFFT
  this.ifft1d = function (re, im) {
    var n = 1/_n;
    fft(re, im, -1);
    for(var i=0; i<_n; i++) {
      re[i] *= n;
      im[i] *= n;
    }
  };
  
  // 2D-FFT
  this.fft2d = function (re, im) {
    var i = 0;
    // x-axis
    for(var y=0; y<_n; y++) {
      i = y*_n;
      for(var x1=0; x1<_n; x1++) {
        _tre[x1] = re[x1 + i];
        _tim[x1] = im[x1 + i];
      }
      this.fft1d(_tre, _tim);
      for(var x2=0; x2<_n; x2++) {
        re[x2 + i] = _tre[x2];
        im[x2 + i] = _tim[x2];
      }
    }
    // y-axis
    for(var x=0; x<_n; x++) {
      for(var y1=0; y1<_n; y1++) {
        i = x + y1*_n;
        _tre[y1] = re[i];
        _tim[y1] = im[i];
      }
      this.fft1d(_tre, _tim);
      for(var y2=0; y2<_n; y2++) {
        i = x + y2*_n;
        re[i] = _tre[y2];
        im[i] = _tim[y2];
      }
    }
  };
  
  // 2D-IFFT
  this.ifft2d = function (re, im) {
    var i = 0;
    // x-axis
    for(var y=0; y<_n; y++) {
      i = y*_n;
      for(var x1=0; x1<_n; x1++) {
        _tre[x1] = re[x1 + i];
        _tim[x1] = im[x1 + i];
      }
      this.ifft1d(_tre, _tim);
      for(var x2=0; x2<_n; x2++) {
        re[x2 + i] = _tre[x2];
        im[x2 + i] = _tim[x2];
      }
    }
    // y-axis
    for(var x=0; x<_n; x++) {
      for(var y1=0; y1<_n; y1++) {
        i = x + y1*_n;
        _tre[y1] = re[i];
        _tim[y1] = im[i];
      }
      this.ifft1d(_tre, _tim);
      for(var y2=0; y2<_n; y2++) {
        i = x + y2*_n;
        re[i] = _tre[y2];
        im[i] = _tim[y2];
      }
    }
  };
  
  // core operation of FFT
  function fft(re, im, inv) {
    var d, h, ik, m, tmp, wr, wi, xr, xi,
        n4 = _n >> 2;
    // bit reversal
    for(var l=0; l<_n; l++) {
      m = _bitrev[l];
      if(l < m) {
        tmp = re[l];
        re[l] = re[m];
        re[m] = tmp;
        tmp = im[l];
        im[l] = im[m];
        im[m] = tmp;
      }
    }
    // butterfly operation
    for(var k=1; k<_n; k<<=1) {
      h = 0;
      d = _n/(k << 1);
      for(var j=0; j<k; j++) {
        wr = _cstb[h + n4];
        wi = inv*_cstb[h];
        for(var i=j; i<_n; i+=(k<<1)) {
          ik = i + k;
          xr = wr*re[ik] + wi*im[ik];
          xi = wr*im[ik] - wi*re[ik];
          re[ik] = re[i] - xr;
          re[i] += xr;
          im[ik] = im[i] - xi;
          im[i] += xi;
        }
        h += d;
      }
    }
  }
  
  // set variables
  function _setVariables() {
    if(typeof Uint8Array !== 'undefined') {
      _bitrev = new Uint8Array(_n);
    } else {
      _bitrev = new Array(_n);
    }
    if(typeof Float64Array !== 'undefined') {
      _cstb = new Float64Array(_n*1.25);
      _tre = new Float64Array(_n*_n);
      _tim = new Float64Array(_n*_n);
    } else {
      _cstb = new Array(_n*1.25);
      _tre = new Array(_n*_n);
      _tim = new Array(_n*_n);
    }
  }
  
  // make bit reversal table
  function _makeBitReversal() {
    var i = 0,
        j = 0,
        k = 0;
    _bitrev[0] = 0;
    while(++i < _n) {
      k = _n >> 1;
      while(k <= j) {
        j -= k;
        k >>= 1;
      }
      j += k;
      _bitrev[i] = j;
    }
  }
  
  // make trigonometric function table
  function _makeCosSinTable() {
    var n2 = _n >> 1,
        n4 = _n >> 2,
        n8 = _n >> 3,
        n2p4 = n2 + n4,
        t = Math.sin(Math.PI/_n),
        dc = 2*t*t,
        ds = Math.sqrt(dc*(2 - dc)),
        c = _cstb[n4] = 1,
        s = _cstb[0] = 0;
    t = 2*dc;
    for(var i=1; i<n8; i++) {
      c -= dc;
      dc += t*c;
      s += ds;
      ds -= t*s;
      _cstb[i] = s;
      _cstb[n4 - i] = c;
    }
    if(n8 !== 0) {
      _cstb[n8] = Math.sqrt(0.5);
    }
    for(var j=0; j<n4; j++) {
      _cstb[n2 - j]  = _cstb[j];
    }
    for(var k=0; k<n2p4; k++) {
      _cstb[k + n2] = -_cstb[k];
    }
  }
}
1031009
def make_table(self):
        """"""
        num_records = int(np.sum([1 for frame in self.timeseries]))
        dtype = [("frame",float),("time",float),("ligand atom id",int),
                ("ligand atom name","|U4"),("distance",float),
                ("resid",int),("resname","|U4"),("segid","|U8") ]
        out = np.empty((num_records,),dtype=dtype)
        cursor=0
        for contact in self.timeseries:
            out[cursor] = (contact.frame, contact.time,contact.ligandatomid,contact.ligandatomname,contact.distance,
                           contact.resid,contact.resname,contact.segid)
            cursor+=1
        return out.view(np.recarray)
14916
def _make_S_curve(x, range=(-0.75, 0.75)):
    """"""
    assert x.ndim == 1
    x = x - x.min()
    theta = 2 * np.pi * (range[0] + (range[1] - range[0]) * x / x.max())
    X = np.empty((x.shape[0], 2), dtype=float)
    X[:, 0] = np.sign(theta) * (1 - np.cos(theta))
    X[:, 1] = np.sin(theta)
    X *= x.max() / (2 * np.pi * (range[1] - range[0]))
    return X
632241
def standardize_table(cls, table):
        '''
        
        '''


        # tidy up quantities, setting motions to 0 if poorly defined
        for key in ['pmra', 'pmdec', 'parallax', 'radial_velocity']:
            bad = table[key].mask
            table[key][bad] = 0.0

        bad = table['parallax']/table['parallax_error'] < 1
        bad += table['parallax'].mask
        table['parallax'][bad] = np.nan
        distance = 1000*u.pc/table['parallax'].data

        distance[bad] = 10000*u.pc#np.nanmax(distance)
        identifiers  = {'GaiaDR2-id':table['source_id']}

        # create skycoord objects
        coordinates = dict(  ra=table['ra'].data*u.deg,
                             dec=table['dec'].data*u.deg,
                             pm_ra_cosdec=table['pmra'].data*u.mas/u.year,
                             pm_dec=table['pmdec'].data*u.mas/u.year,
                             radial_velocity=table['radial_velocity'].data*u.km/u.s,
                             distance=distance, # weirdly, messed with RA + Dec signs if parallax is zero
                             obstime=cls.epoch*np.ones(len(table))*u.year)#Time(, format='decimalyear'))

        magnitudes = {k+'-mag':table['phot_{}_mean_mag'.format(k.lower())].data for k in cls.filters}


        errors = dict(distance= distance*(table['parallax_error'].data/table['parallax'].data),
                      pm_ra_cosdec=table['pmra_error'].data*u.mas/u.year,
                      pm_dec=table['pmdec_error'].data*u.mas/u.year,
                      radial_velocity=table['radial_velocity_error'].data*u.km/u.s)

        error_table = Table(data=[errors[k] for k in cls.error_keys],
                            names=[k+'-error' for k in cls.error_keys])


        #for key in ['pmra', 'pmdec', 'parallax', 'radial_velocity']:
        #        bad = table[key].mask
        #        table[key][bad] = 0.0


        standardized = hstack([Table(identifiers),
                               Table(coordinates),
                               Table(magnitudes),
                               error_table])

        standardized.meta['catalog'] = 'Gaia'

        return standardized
1132508
function displayMetrics(file) {
    var prefix = '';

    var code = fs.readFileSync(file, 'utf-8');

    // We remove any shebang at the start of the file since that isn't valid
    // Javascript and will trip up the parser.

    code = code.replace(/^#!.*\n/, '');

    var metrics = complexity(code);

    // Walk the metrics structure and add each member to the table rows.

    function walk(data, name) {
        // Fade out anonymous functions.

        if (name.indexOf('anon@') === 0) {
            name = name.grey;
        }

        rows.push([ prefix + name, data.ecc, data.arity, data.codeLines, data.commentLines, Math.round(100 * data.commentLines / data.codeLines) ]);

        // Add two spaces to the prefix before the next depth, to illustrate
        // the hierarchy in the table.

        prefix += '  ';
        _.each(data.children, walk);
        prefix = prefix.slice(0,prefix.length-2);
    }
    walk(metrics, path.basename(file).blue.bold);
}
1354099
function HuffmanTable(table) {
  function createTree(codes, position) {
    if (codes.length === 1) {
      return [table.indexOf(codes[0])];
    }

    else {
      position = position || 0;
      var zero = [];
      var one = [];
      for (var i = 0; i < codes.length; i++) {
        var string = codes[i];
        if (string[position] === '0') {
          zero.push(string);
        } else {
          one.push(string);
        }
      }
      return [createTree(zero, position + 1), createTree(one, position + 1)];
    }
  }

  this.tree = createTree(table);

  this.codes = table.map(function(bits) {
    return parseInt(bits, 2);
  });
  this.lengths = table.map(function(bits) {
    return bits.length;
  });
}
1175383
def make_geohash_tables(table,listofprecisions,**kwargs):
	'''
	
	'''
	return_squares = False
	sort_by = 'COUNT'
	# logic for accepting kwarg inputs
	for key,value in kwargs.iteritems():
		if key == 'sort_by':
			sort_by = value
		if key == 'return_squares':
			return_squares = value

	# getting header
	header = df2list(table)[0]

	# getting columns
	columns = header[10:]

	# getting original table
	originaltable = table
	if not sort_by == 'COUNT':
		originaltable = originaltable.sort([sort_by],ascending=[0])




	listofprecisions = sorted(listofprecisions,reverse=True)
	# making total table to hold a list of dfs
	if return_squares == True and listofprecisions[-1] == 8:
		total_list = [table]
	elif return_squares == True:
		total_list = []

	for row in listofprecisions:
		precision = int(row)
		table = originaltable
		table['GEOHASH'] = table.GEOHASH.str[:precision]
		table = table[['GEOHASH','COUNT']+columns].groupby(['GEOHASH'],sort=True).sum()
		table = table.sort([sort_by],ascending=[0])
		table = table.reset_index()

		newsquares = [header]
		# iterating through each square here 
		for row in df2list(table)[1:]:
			# getting points
			points = get_points_geohash(row[0])
			
			# making new row
			newrow = [row[0]] + points + row[1:]
			
			# appending to newsquares 
			newsquares.append(newrow)

		# taking newsquares to dataframe
		table = list2df(newsquares)

		if return_squares == True:
			total_list.append(table)
		else:
			table.to_csv('squares' + str(precision) + '.csv',index=False)

	if return_squares == True:
		return total_list
	else:
		print 'Wrote output squares tables to csv files.'
1341556
public int[] makeLut() {
        int numKnots = x.length;
        float[] nx = new float[numKnots + 2];
        float[] ny = new float[numKnots + 2];
        System.arraycopy(x, 0, nx, 1, numKnots);
        System.arraycopy(y, 0, ny, 1, numKnots);
        nx[0] = nx[1];
        ny[0] = ny[1];
        nx[numKnots + 1] = nx[numKnots];
        ny[numKnots + 1] = ny[numKnots];

        int[] table = new int[256];
        for (int i = 0; i < 1024; i++) {
            float f = i / 1024.0f;
            int x = (int) (255 * Curve.Spline(f, nx.length, nx) + 0.5f);
            int y = (int) (255 * Curve.Spline(f, nx.length, ny) + 0.5f);
            x = x > 255 ? 255 : x;
            x = x < 0 ? 0 : x;
            y = y > 255 ? 255 : y;
            y = y < 0 ? 0 : y;
            table[x] = y;
        }
        return table;
    }
1236959
function MathFormula() {
        this.addInput("x", "number");
        this.addInput("y", "number");
        this.addOutput("", "number");
        this.properties = { x: 1.0, y: 1.0, formula: "x+y" };
        this.code_widget = this.addWidget(
            "text",
            "F(x,y)",
            this.properties.formula,
            function(v, canvas, node) {
                node.properties.formula = v;
            }
        );
        this.addWidget("toggle", "allow", LiteGraph.allow_scripts, function(v) {
            LiteGraph.allow_scripts = v;
        });
        this._func = null;
    }
389940
def make_helix(aa, axis_distance, z_shift, phi, splay, off_plane):
        """"""
        start = numpy.array([axis_distance, 0 + z_shift, 0])
        end = numpy.array([axis_distance, (aa * 1.52) + z_shift, 0])
        mid = (start + end) / 2

        helix = Helix.from_start_and_end(start, end, aa=aa)
        helix.rotate(splay, (0, 0, 1), mid)
        helix.rotate(off_plane, (1, 0, 0), mid)
        helix.rotate(phi, helix.axis.unit_tangent, helix.helix_start)
        return helix
171276
def _h(self, X, tau):

        

        def cos_func(y):
            if isinstance(y, float) or isinstance(y, int):
                if y > 1:
                    return np.arccosh(y)
                else:
                    return np.arccos(y)
            else:
                values = np.ones_like(y)
                inds1 = np.where(y < 1)
                inds2 = np.where(y > 1)
                values[inds1] = np.arccos(y[inds1])
                # values[inds2] = np.arccosh(y[inds2])
                values[inds2] = np.arccos((1 - y[inds2]) ** .5)
                return values

        def nfw_func(x):
            if isinstance(x,float) or isinstance(x,int):
                if x<1:
                    return np.log(x / 2.) ** 2 - np.arccosh(1. / x) ** 2
                else:
                    return np.log(x / 2.)**2 - np.arccos(1. /x)**2
            else:
                inds1 = np.where(x < 1)
                inds2 = np.where(x >= 1)
                y = np.zeros_like(x)
                y[inds1] = np.log(x[inds1] / 2.) ** 2 - np.arccosh(1. / x[inds1]) ** 2
                y[inds2] = np.log(x[inds2] / 2.) ** 2 - np.arccosh(1. / x[inds2]) ** 2

                return y

        def tnfw_func(x,tau):

            u = x**2
            t2 = tau**2
            Lx = self.L(u**.5, tau)

            return (t2 + 1) ** -2 * (
                2 * t2 * np.pi * (tau - (t2 + u) ** .5 + tau * np.log(tau + (t2 + u) ** .5))
                +
                2 * (t2 - 1) * tau * (t2 + u) ** .5 * Lx
                +
                t2 * (t2 - 1) * Lx ** 2
                +
                4 * t2 * (u - 1) * self.F(u**.5)
                +
                t2 * (t2 - 1) * (cos_func(u ** -0.5)) ** 2
                +
                t2 * ((t2 - 1) * np.log(tau) - t2 - 1) * np.log(u)
                -
                t2 * (
                (t2 - 1) * np.log(tau) * np.log(4 * tau) + 2 * np.log(0.5 * tau) - 2 * tau * (tau - np.pi) * np.log(
                    tau * 2)))

        c = 1e-9
        rescale = 1

        if np.any(X-c<1):

            warnings.warn('Truncated NFW potential not yet implemented for x<1. Using the expression for the NFW '
                          'potential in this regime isntead.')
            rescale = tnfw_func(1.00001,tau)*nfw_func(1)**-1

        if isinstance(X,float) or isinstance(X,int):
            if X<1:
                X = min(X,0.001)
                return nfw_func(X)*rescale
            else:
                return tnfw_func(X,tau)
        else:

            X[np.where(X<0.001)] = 0.001

            values = np.zeros_like(X)
            inds1,inds2 = np.where(X<1),np.where(X>=1)
            values[inds1] = nfw_func(X[inds1])*rescale
            values[inds2] = tnfw_func(X[inds2],tau)

            return values