Fixes gaps beteween facet orders
166685
public function reorderFacets()
    {
        $facets = $this->getFacets();
        $order = 0;

        foreach ($facets as $facet) {
            $facet->setPosition($order);
            $order++;
            $this->om->persist($facet);
        }

        $this->om->flush();
    }
1166222
function fixSRS(obj) {
    if (!obj.srs) return;

    var normalized = _(obj.srs.split(' ')).chain()
        .select(function(s) { return s.indexOf('=') > 0; })
        .sortBy(function(s) { return s; })
        .reduce(function(memo, s) {
            var key = s.split('=')[0];
            var val = s.split('=')[1];
            if (val === '0') val = '0.0';
            memo[key] = val;
            return memo;
        }, {})
        .value();
    var legacy = {
        '+a': '6378137',
        '+b': '6378137',
        '+lat_ts': '0.0',
        '+lon_0': '0.0',
        '+proj': 'merc',
        '+units': 'm',
        '+x_0': '0.0',
        '+y_0': '0.0'
    };
    if (!_(legacy).chain()
        .reject(function(v, k) { return normalized[k] === v; })
        .size()
        .value()) obj.srs = SRS['900913'];
}
1234438
def QA_util_date_gap(date, gap, methods):
    '''
    
    '''
    try:
        if methods in ['>', 'gt']:
            return trade_date_sse[trade_date_sse.index(date) + gap]
        elif methods in ['>=', 'gte']:
            return trade_date_sse[trade_date_sse.index(date) + gap - 1]
        elif methods in ['<', 'lt']:
            return trade_date_sse[trade_date_sse.index(date) - gap]
        elif methods in ['<=', 'lte']:
            return trade_date_sse[trade_date_sse.index(date) - gap + 1]
        elif methods in ['==', '=', 'eq']:
            return date

    except:
        return 'wrong date'
1199475
def _merge_inplace(self, other):
        """"""
        if other is None:
            yield
        else:
            # don't include indexes in priority_vars, because we didn't align
            # first
            priority_vars = OrderedDict(
                kv for kv in self.variables.items() if kv[0] not in self.dims)
            variables = merge_coords_for_inplace_math(
                [self.variables, other.variables], priority_vars=priority_vars)
            yield
            self._update_coords(variables)
66465
protected function fixOverlappingStartEndDates()
    {
        $rs = $this->connection->executeQuery(<<<'EOT'
select
    cv1.cID,
    cv1.cvID
from
    CollectionVersions as cv1
    inner join CollectionVersions as cv2
        on cv1.cID = cv2.cID
        and cv1.cvID <> cv2.cvID
        and cv1.cvIsApproved = cv2.cvIsApproved
where
    cv1.cvIsApproved = 1
    and ifnull(cv1.cvPublishDate, '0000-00-00 00:00:00') <= ifnull(cv1.cvPublishEndDate, '9999-99-99 99:99:99')
    and ifnull(cv1.cvPublishEndDate, '9999-99-99 99:99:99') >= ifnull(cv2.cvPublishDate, '0000-00-00 00:00:00')
order by
    cv1.cID,
    cv1.cvID desc
EOT
        );
        $page = null;
        while (($row = $rs->fetch(PDO::FETCH_ASSOC)) !== false) {
            if ($page === null || $page->getCollectionID() != $row['cID']) {
                $page = Page::getByID($row['cID'], $row['cvID']);
            } else {
                $page->loadVersionObject($row['cvID']);
            }
            $version = $page->getVersionObject();
            // Force fixing other collection version publish date/time interval
            $version->setPublishInterval($version->getPublishDate(), $version->getPublishDate());
        }
    }
996398
def update_fixed_order(self):
        ""
        # set tips order if fixing for multi-tree plotting (default None)
        fixed_order = self.ttree._fixed_order
        self.ttree_fixed_order = None
        self.ttree_fixed_idx = list(range(self.ttree.ntips))

        # check if fixed_order changed:
        if fixed_order:
            fixed_order = [
                i for i in fixed_order if i in self.ttree.get_tip_labels()]
            self.ttree._set_fixed_order(fixed_order)
        else:
            self.ttree._fixed_idx = list(range(self.ttree.ntips))
1151690
protected void updateOutgoingEdgesStateDL(
			int currS, int currL,
			int prevS, int prevL,
			Emissions emission
	){
		updateOutgoingEdges(currS, currL, States.DL, prevS, prevL, States.DL, Transitions.t_DL_in, emission);
		updateOutgoingEdges(currS, currL, States.DL, prevS, prevL, States.S, Transitions.t_S_to_DL, emission);
	}
47450
def drill_down_facets
      drill = drill_down.reverse
      i = drill.find_index{|f|f.selected?}
      if i == 0
        down = nil
	current, *ups = drill[0..-1]
      else
        down, current, *ups = drill[i-1..-1]
      end

      [ down, current, ups ]
    end
1069790
def _fix_pooling(pool_type, inputs, new_attr):
    """"""
    stride = new_attr.get('stride')
    kernel = new_attr.get('kernel')
    padding = new_attr.get('pad')
    p_value = new_attr.get('p_value')

    # Adding default stride.
    if stride is None:
        stride = (1,) * len(kernel)

    # Add padding attr if not provided.
    if padding is None:
        padding = (0,) * len(kernel) * 2

    # Mxnet Pad operator supports only 4D/5D tensors.
    # For 1D case, these are the steps:
    #    Step 1. Add extra dummy dimension to make it 4D. Adding to  axis = 2
    #    Step 2. Apply padding to this changed tensor
    #    Step 3. Remove the extra dimension added in step 1.
    if len(kernel) == 1:
        dummy_axis = 2
        # setting 0 padding to the new dim to be added.
        padding = (0, padding[0], 0, padding[1])
        pad_width = (0, 0, 0, 0) + _pad_sequence_fix(padding, kernel_dim=2)

        # Step 1.
        curr_sym = symbol.expand_dims(inputs[0], axis=dummy_axis)

        # Step 2. Common for all tensor sizes
        new_pad_op = symbol.pad(curr_sym, mode='edge', pad_width=pad_width)

        # Step 3: Removing extra dim added.
        new_pad_op = symbol.split(new_pad_op, axis=dummy_axis, num_outputs=1, squeeze_axis=1)
    else:
        # For 2D/3D cases:
        # Apply padding
        pad_width = (0, 0, 0, 0) + _pad_sequence_fix(padding, kernel_dim=len(kernel))
        curr_sym = inputs[0]

        if pool_type == 'max':
            # For max pool : mode = 'edge', we should replicate the
            # edge values to pad, so that we only include  input data values
            # for calculating 'max'
            new_pad_op = symbol.pad(curr_sym, mode='edge', pad_width=pad_width)
        else:
            # For avg pool, we should add 'zeros' for padding  so mode='constant'
            new_pad_op = symbol.pad(curr_sym, mode='constant', pad_width=pad_width)

    # Apply pooling without pads.
    if pool_type == 'lp':
        new_pooling_op = symbol.Pooling(new_pad_op, pool_type=pool_type, stride=stride, kernel=kernel, p_value=p_value)
    else:
        new_pooling_op = symbol.Pooling(new_pad_op, pool_type=pool_type, stride=stride, kernel=kernel)
    return new_pooling_op
108458
def merge_tops(self, tops):
        '''
        
        '''
        top = collections.defaultdict(OrderedDict)
        orders = collections.defaultdict(OrderedDict)
        for ctops in six.itervalues(tops):
            for ctop in ctops:
                for saltenv, targets in six.iteritems(ctop):
                    if saltenv == 'include':
                        continue
                    for tgt in targets:
                        matches = []
                        states = OrderedDict()
                        orders[saltenv][tgt] = 0
                        ignore_missing = False
                        # handle a pillar sls target written in shorthand form
                        if isinstance(ctop[saltenv][tgt], six.string_types):
                            ctop[saltenv][tgt] = [ctop[saltenv][tgt]]
                        for comp in ctop[saltenv][tgt]:
                            if isinstance(comp, dict):
                                if 'match' in comp:
                                    matches.append(comp)
                                if 'order' in comp:
                                    order = comp['order']
                                    if not isinstance(order, int):
                                        try:
                                            order = int(order)
                                        except ValueError:
                                            order = 0
                                    orders[saltenv][tgt] = order
                                if comp.get('ignore_missing', False):
                                    ignore_missing = True
                            if isinstance(comp, six.string_types):
                                states[comp] = True
                        if ignore_missing:
                            if saltenv not in self.ignored_pillars:
                                self.ignored_pillars[saltenv] = []
                            self.ignored_pillars[saltenv].extend(states.keys())
                        top[saltenv][tgt] = matches
                        top[saltenv][tgt].extend(states)
        return self.sort_top_targets(top, orders)
176852
def _fix_paths(self, data):
        
        data['include_paths'] = [join('$PROJ_DIR$', path) for path in data['include_paths']]

        if data['linker_file']:
            data['linker_file'] = join('$PROJ_DIR$', data['linker_file'])

        data['groups'] = {}
        for attribute in SOURCE_KEYS:
            for k, v in data[attribute].items():
                if k not in data['groups']:
                    data['groups'][k] = []
                data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v])
        for k,v in data['include_files'].items():
            if k not in data['groups']:
                data['groups'][k] = []
            data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v])

        # sort groups
        data['groups'] = OrderedDict(sorted(data['groups'].items(), key=lambda t: t[0]))
133042
def gaps(args):
    
    from jcvi.graphics.histogram import loghistogram

    p = OptionParser(gaps.__doc__)
    p.add_option("--merge", dest="merge", default=False, action="store_true",
            help="Merge adjacent gaps (to conform to AGP specification)")
    p.add_option("--header", default=False, action="store_true",
            help="Produce an AGP header [default: %default]")

    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    merge = opts.merge
    agpfile, = args

    if merge:
        merged_agpfile = agpfile.replace(".agp", ".merged.agp")
        fw = open(merged_agpfile, "w")

    agp = AGP(agpfile)
    sizes = []
    data = []  # store merged AGPLine's
    priorities = ("centromere", "telomere", "scaffold", "contig", \
            "clone", "fragment")

    for is_gap, alines in groupby(agp, key=lambda x: (x.object, x.is_gap)):
        alines = list(alines)
        is_gap = is_gap[1]
        if is_gap:
            gap_size = sum(x.gap_length for x in alines)
            gap_types = set(x.gap_type for x in alines)
            for gtype in ("centromere", "telomere"):
                if gtype in gap_types:
                    gap_size = gtype

            sizes.append(gap_size)
            b = deepcopy(alines[0])
            b.object_beg = min(x.object_beg for x in alines)
            b.object_end = max(x.object_end for x in alines)
            b.gap_length = sum(x.gap_length for x in alines)

            assert b.gap_length == b.object_end - b.object_beg + 1
            b.component_type = 'U' if b.gap_length == 100 else 'N'

            gtypes = [x.gap_type for x in alines]
            for gtype in priorities:
                if gtype in gtypes:
                    b.gap_type = gtype
                    break

            linkages = [x.linkage for x in alines]
            for linkage in ("no", "yes"):
                if linkage in linkages:
                    b.linkage = linkage
                    break

            alines = [b]

        data.extend(alines)

    loghistogram(sizes)

    if opts.header:
        AGP.print_header(fw, organism="Medicago truncatula",
                         taxid=3880, source="J. Craig Venter Institute")

    if merge:
        for ob, bb in groupby(data, lambda x: x.object):
            for i, b in enumerate(bb):
                b.part_number = i + 1
                print(b, file=fw)
        return merged_agpfile
1033592
def gaps(args):
    
    p = OptionParser(gaps.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    blastfile, = args
    blast = BlastSlow(blastfile)
    logging.debug("A total of {} records imported".format(len(blast)))

    query_gaps = list(collect_gaps(blast))
    subject_gaps = list(collect_gaps(blast, use_subject=True))
    logging.debug("Query gaps: {}  Subject gaps: {}"\
                    .format(len(query_gaps), len(subject_gaps)))

    from jcvi.graphics.base import savefig
    import seaborn as sns

    sns.distplot(query_gaps)
    savefig("query_gaps.pdf")
792513
private void fixConnectiveConstraints(IPattern p) {
        if (p instanceof FactPattern) {
            fixConnectiveConstraints((FactPattern) p);
        } else if (p instanceof CompositeFactPattern) {
            fixConnectiveConstraints((CompositeFactPattern) p);
        }
    }
288213
def no_gaps(curve):
    
    tnt = utils.top_and_tail(curve)
    return not any(np.isnan(tnt))
59087
function resolveDependenciesToUnified() {
		if ( !Calendar || !DateRange ) {
			sap.ui.getCore().loadLibrary("sap.ui.unified");
			Calendar = sap.ui.requireSync("sap/ui/unified/Calendar");
			DateRange = sap.ui.requireSync("sap/ui/unified/DateRange");
		}
	}
416497
def tidy(args):
    
    p = OptionParser(tidy.__doc__)
    p.add_option("--gapsize", dest="gapsize", default=0, type="int",
            help="Set all gaps to the same size [default: %default]")
    p.add_option("--minlen", dest="minlen", default=100, type="int",
            help="Minimum component size [default: %default]")

    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    fastafile, = args
    gapsize = opts.gapsize
    minlen = opts.minlen

    tidyfastafile = fastafile.rsplit(".", 1)[0] + ".tidy.fasta"
    fw = must_open(tidyfastafile, "w")

    removed = normalized = 0
    fasta = Fasta(fastafile, lazy=True)
    for name, rec in fasta.iteritems_ordered():
        rec.seq = rec.seq.upper()
        if minlen:
            removed += remove_small_components(rec, minlen)
        trim_terminal_Ns(rec)
        if gapsize:
            normalized += normalize_gaps(rec, gapsize)

        if len(rec) == 0:
            logging.debug("Drop seq {0}".format(rec.id))
            continue
        SeqIO.write([rec], fw, "fasta")

    # Print statistics
    if removed:
        logging.debug("Total discarded bases: {0}".format(removed))
    if normalized:
        logging.debug("Gaps normalized: {0}".format(normalized))

    logging.debug("Tidy FASTA written to `{0}`.".format(tidyfastafile))
    fw.close()

    return tidyfastafile