Generate the tc per UTR pos plots
322251
def slamdunkTcPerUTRPosPlot (self):
        

        pconfig_nontc = {
            'id': 'slamdunk_slamdunk_nontcperutrpos_plot',
            'title': 'Slamdunk: Non-T>C mutations over 3\' UTR ends',
            'ylab': 'Percent mismatches %',
            'xlab': 'Position in the static last 250bp window of 3\' UTR',
            'xDecimals': False,
            'ymin': 0,
            'tt_label': '<b>Pos {point.x}</b>: {point.y:.2f} %',
            'data_labels': [{'name': 'UTRs on plus strand', 'ylab': 'Percent mismatches %'},
                            {'name': 'UTRs on minus strand', 'ylab': 'Percent mismatches %'}]
        }

        pconfig_tc = {
            'id': 'slamdunk_slamdunk_tcperutrpos_plot',
            'title': 'Slamdunk: T>C conversions over 3\' UTR ends',
            'ylab': 'Percent converted %',
            'xlab': 'Position in the static last 250bp window of 3\' UTR',
            'xDecimals': False,
            'ymin': 0,
            'tt_label': '<b>Pos {point.x}</b>: {point.y:.2f} %',
            'data_labels': [{'name': 'UTRs on plus strand', 'ylab': 'Percent converted %'},
                            {'name': 'UTRs on minus strand', 'ylab': 'Percent converted %'}]
        }

        self.add_section (
            name = 'Non T&gt;C mismatches over UTR positions',
            anchor = 'slamdunk_nontcperutrpos',
            description = """This plot shows the distribution of non T&gt;C mismatches across UTR positions for the last 250 bp from the 3\' UTR end
                        (see the <a href="http://t-neumann.github.io/slamdunk/docs.html#tcperutrpos" target="_blank">slamdunk docs</a>).""",
            plot = linegraph.plot([self.nontc_per_utrpos_plus, self.nontc_per_utrpos_minus], pconfig_nontc)
        )

        self.add_section (
            name = 'T&gt;C conversions over UTR positions',
            anchor = 'tcperutrpos',
            description = """This plot shows the distribution of T&gt;C conversions across UTR positions for the last 250 bp from the 3\' UTR end
                        (see the <a href="http://t-neumann.github.io/slamdunk/docs.html#tcperutrpos" target="_blank">slamdunk docs</a>).""",
            plot = linegraph.plot([self.tc_per_utrpos_plus, self.tc_per_utrpos_minus], pconfig_tc)
        )
1138621
def print_pos(self, coordinates=None, pos=None):
        ''''''
        if not pos:
            pos = self.pos
        self.graph = [list(map(self._transform, pos[i])) for i in self.pos_range]
        xaxis = ' '.join([chr(ASC_ONE + _) for _ in range(min(self.board_size, MAX_NUM))])
        if (self.board_size > MAX_NUM):
            xaxis += ' '
            xaxis += ' '.join([chr(ASC_A + _ - MAX_NUM) for _ in range(MAX_NUM, min(self.board_size, MAX_CAP))])
        if (self.board_size > MAX_CAP):
            xaxis += ' '
            xaxis += ' '.join([chr(ASC_a + _ - MAX_CAP) for _ in range(MAX_CAP, self.board_size)])
        print('  ', end='')
        print(xaxis)
        for i in range(self.board_size):
            out = '|'.join(self.graph[i])
            if i < MAX_NUM:
                print(chr(i + ASC_ONE), end='')
            elif MAX_NUM <= i < MAX_CAP:
                print(chr(i - MAX_NUM + ASC_A), end='')
            elif MAX_CAP <= i < MAX_LOW:
                print(chr(i - MAX_CAP + ASC_a), end='')
            print('|', end='')
            #Colorful print
            if coordinates:
                for j in range(self.board_size):
                    if (i, j) in coordinates:
                        new_print = cprint
                        params = {
                            'color': 'w',
                            'bcolor': 'r',
                        }
                    else:
                        new_print = print
                        params = {}
                    new_print(self._transform(pos[i][j]), end='', **params)
                    print('|', end='') 
                else:
                    print()
            else:
                print(out, end='')
                print('|')
653833
def to_ts(s):
        

        # Strip TZ portion if present
        m = Nginx.DATE_FMT.match(s)
        if m:
            s = m.group(1)
            delta = timedelta(seconds=int(m.group(3)) * (-1 if m.group(2) == '-' else 1)) # Offset from GMT
        else:
            delta = timedelta(seconds=0)
        dt = datetime.strptime(s, "%d/%b/%Y:%H:%M:%S")
        dt += delta
        return dt.strftime('%Y-%m-%dT%H:%M:%SZ')
1017482
def generate_unicode_table():
    """"""

    uver = get_unicodedata()
    fail = False
    path = os.path.join(os.path.dirname(__file__), 'tools')
    fp, pathname, desc = imp.find_module('unipropgen', [path])
    try:
        unipropgen = imp.load_module('unipropgen', fp, pathname, desc)
        unipropgen.build_tables(
            os.path.join(
                os.path.dirname(__file__),
                'backrefs', 'uniprops', 'unidata'
            ),
            uver
        )
    except Exception:
        print(traceback.format_exc())
        fail = True
    finally:
        fp.close()

    assert not fail, "Failed uniprops.py generation!"
104254
def format_timedelta_ticks(x, pos, n_decimals):
    
    s, ns = divmod(x, 1e9)
    m, s = divmod(s, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    decimals = int(ns * 10**(n_decimals - 9))
    s = r'{:02d}:{:02d}:{:02d}'.format(int(h), int(m), int(s))
    if n_decimals > 0:
        s += '.{{:0{:0d}d}}'.format(n_decimals).format(decimals)
    if d != 0:
        s = '{:d} days '.format(int(d)) + s
    return s
912374
def prt_txt(prt, data_nts, prtfmt=None, nt_fields=None, **kws):
    """"""
    lines = get_lines(data_nts, prtfmt, nt_fields, **kws)
    if lines:
        for line in lines:
            prt.write(line)
    else:
        sys.stdout.write("      0 items. NOT WRITING\n")
793933
def translate(self, pos):
        
        self.matrix = np.dot(self.matrix, transforms.translate(pos[0, :3]))
115847
def load_data_and_labels():
    
    # download dataset
    get_chinese_text()

    # Load data from files
    positive_examples = list(codecs.open("./data/pos.txt", "r", "utf-8").readlines())
    positive_examples = [s.strip() for s in positive_examples]
    positive_examples = [pe for pe in positive_examples if len(pe) < 100]
    negative_examples = list(codecs.open("./data/neg.txt", "r", "utf-8").readlines())
    negative_examples = [s.strip() for s in negative_examples]
    negative_examples = [ne for ne in negative_examples if len(ne) < 100]
    # Split by words
    x_text = positive_examples + negative_examples
    # x_text = [clean_str(sent) for sent in x_text]
    x_text = [list(s) for s in x_text]

    # Generate labels
    positive_labels = [[0, 1] for _ in positive_examples]
    negative_labels = [[1, 0] for _ in negative_examples]
    y = np.concatenate([positive_labels, negative_labels], 0)
    return [x_text, y]
693189
def plt2xyz(fname):
	""""""
	parser = CompassPltParser(fname)
	plt = parser.parse()

	for segment in plt:
		for command in segment:
			if command.cmd == 'd':
				if plt.utm_zone:
					x, y, z = command.x * FT_TO_M, command.y * FT_TO_M, command.z * FT_TO_M
				else:
					x, y, z = command.x, command.y, command.z
				print('%.3f\t%.3f\t%.3f' % (x, y, z))
1249741
def helper_for_plot_data(self, X, plot_limits, visible_dims, fixed_inputs, resolution):
    
    #work out what the inputs are for plotting (1D or 2D)
    if fixed_inputs is None:
        fixed_inputs = []
    fixed_dims = get_fixed_dims(fixed_inputs)
    free_dims = get_free_dims(self, visible_dims, fixed_dims)

    if len(free_dims) == 1:
        #define the frame on which to plot
        resolution = resolution or 200
        Xnew, xmin, xmax = x_frame1D(X[:,free_dims], plot_limits=plot_limits, resolution=resolution)
        Xgrid = np.zeros((Xnew.shape[0],self.input_dim))
        Xgrid[:,free_dims] = Xnew
        for i,v in fixed_inputs:
            Xgrid[:,i] = v
        x = Xgrid
        y = None
    elif len(free_dims) == 2:
        #define the frame for plotting on
        resolution = resolution or 35
        Xnew, x, y, xmin, xmax = x_frame2D(X[:,free_dims], plot_limits, resolution)
        Xgrid = np.zeros((Xnew.shape[0], self.input_dim))
        Xgrid[:,free_dims] = Xnew
        #xmin = Xgrid.min(0)[free_dims]
        #xmax = Xgrid.max(0)[free_dims]
        for i,v in fixed_inputs:
            Xgrid[:,i] = v
    else:
        raise TypeError("calculated free_dims {} from visible_dims {} and fixed_dims {} is neither 1D nor 2D".format(free_dims, visible_dims, fixed_dims))
    return fixed_dims, free_dims, Xgrid, x, y, xmin, xmax, resolution
251740
def _prtfmt(self, item_id, dashes):
        """"""
        ntprt = self.id2nt[item_id]
        dct = ntprt._asdict()
        self.prt.write('{DASHES:{N}}'.format(
            DASHES=self.fmt_dashes.format(DASHES=dashes, ID=self.nm2prtfmt['ID'].format(**dct)),
            N=self.dash_len))
        self.prt.write("{INFO}\n".format(INFO=self.nm2prtfmt['ITEM'].format(**dct)))
158590
def autocorrplot(trace, vars=None, fontmap = None, max_lag=100):
    """"""

    try:
        # MultiTrace
        traces = trace.traces

    except AttributeError:

        # NpTrace
        traces = [trace]

    if fontmap is None: fontmap = {1:10, 2:8, 3:6, 4:5, 5:4}

    if vars is None:
        vars = traces[0].varnames

    # Extract sample data
    samples = [{v:trace[v] for v in vars} for trace in traces]

    chains = len(traces)

    n = len(samples[0])
    f, ax = subplots(n, chains, squeeze=False)

    max_lag = min(len(samples[0][vars[0]])-1, max_lag)

    for i, v in enumerate(vars):

        for j in xrange(chains):

            d = np.squeeze(samples[j][v])

            ax[i,j].acorr(d, detrend=mlab.detrend_mean, maxlags=max_lag)

            if not j:
                ax[i, j].set_ylabel("correlation")
            ax[i, j].set_xlabel("lag")

            if chains > 1:
                ax[i, j].set_title("chain {0}".format(j+1))

    # Smaller tick labels
    tlabels = gca().get_xticklabels()
    setp(tlabels, 'fontsize', fontmap[1])

    tlabels = gca().get_yticklabels()
    setp(tlabels, 'fontsize', fontmap[1])
743853
def _prt_txt_hdr(prt, prtfmt):
    """"""
    tblhdrs = get_fmtfldsdict(prtfmt)
    # If needed, reformat for format_string for header, which has strings, not floats.
    hdrfmt = re.sub(r':(\d+)\.\S+}', r':\1}', prtfmt)
    hdrfmt = re.sub(r':(0+)(\d+)}', r':\2}', hdrfmt)
    prt.write("#{}".format(hdrfmt.format(**tblhdrs)))
237253
def create_roc_plots(pwmfile, fgfa, background, outdir):
    """"""
    motifs = read_motifs(pwmfile, fmt="pwm", as_dict=True)
    ncpus = int(MotifConfig().get_default_params()['ncpus'])
    pool = Pool(processes=ncpus)
    jobs = {}
    for bg,fname in background.items():
        for m_id, m in motifs.items():

            k = "{}_{}".format(str(m), bg)
            jobs[k] = pool.apply_async(
                                            get_roc_values,
                                            (motifs[m_id], fgfa, fname,)
                                            )
    imgdir = os.path.join(outdir, "images")
    if not os.path.exists(imgdir):
        os.mkdir(imgdir)
    
    roc_img_file = os.path.join(outdir, "images", "{}_roc.{}.png")

    for motif in motifs.values():
        for bg in background:
            k = "{}_{}".format(str(motif), bg)
            error, x, y = jobs[k].get()
            if error:
                logger.error("Error in thread: %s", error)
                logger.error("Motif: %s", motif)
                sys.exit(1)
            roc_plot(roc_img_file.format(motif.id, bg), x, y)
762710
def iter_top_row_tcs(self):
        """"""
        tr = self._tbl.tr_lst[self._top]
        for tc in tr.tc_lst[self._left:self._right]:
            yield tc
313587
function numericEndPos( $tpl, &$text, $start_pos, $len,
                            &$float )
    {
        $pos = $start_pos;
        $has_comma = false;
        $numberPos = $pos;
        if ( $pos < $len )
        {
            if ( $text[$pos] == '-' )
            {
                ++$pos;
                $numberPos = $pos;
            }
        }
        while ( $pos < $len )
        {
            if ( $text[$pos] == "." and $float )
            {
                if ( $has_comma )
                {
                    if ( !$has_comma and
                         $float )
                        $float = false;
                    return $pos;
                }
                $has_comma = $pos;
            }
            else if ( $text[$pos] < '0' or $text[$pos] > '9' )
            {
                if ( !$has_comma and
                     $float )
                    $float = false;
                if ( $pos < $len and
                     $has_comma and
                     $pos == $has_comma + 1 )
                {
                    return $start_pos;
                }
                if ( $pos == $numberPos )
                {
                    return $start_pos;
                }
                return $pos;
            }
            ++$pos;
        }
        if ( !$has_comma and
             $float )
            $float = false;
        if ( $has_comma and
             $start_pos + 1 == $pos )
        {
            return $start_pos;
        }
        return $pos;
    }
1313811
def wr_tsv(self, fout_tsv, goea_results, **kws):
        """"""
        prt_flds = kws.get('prt_flds', self.get_prtflds_default(goea_results))
        tsv_data = MgrNtGOEAs(goea_results).get_goea_nts_prt(prt_flds, **kws)
        RPT.wr_tsv(fout_tsv, tsv_data, **kws)