withTypography HOC
518873
function typographyTransform({ className, f, lh, ...ownerProps }) {
  const type = classesFor({ f: normalizeFontSizes(f), 'lh-': lh });

  return R.merge(
    { className: cx([type, className]) },
    ownerProps,
  );
}
815839
def _init_glyph(self, plot, mapping, properties):
        
        plot_method = properties.pop('plot_method', None)
        properties = mpl_to_bokeh(properties)
        data = dict(properties, **mapping)
        if self._has_holes:
            plot_method = 'multi_polygons'
        elif plot_method is None:
            plot_method = self._plot_methods.get('single')
        renderer = getattr(plot, plot_method)(**data)
        if self.colorbar:
            for k, v in list(self.handles.items()):
                if not k.endswith('color_mapper'):
                    continue
                self._draw_colorbar(plot, v, k[:-12])
        return renderer, renderer.glyph
91246
function orthoProj(pos, cam){
    var cp = cam.pos;
    var vx = pos.x - cp.x;
    var vy = pos.y - cp.y;
    var vz = pos.z - cp.z;
    var cr = cam.rot;
    var crx = cr.x;
    var cry = cr.y;
    var crz = cr.z;
    var crw = cr.w;
    var caxx = crw * crw - crx * -crx + crz * - crz + cry * - cry;
    var caxy = crz * crw - crx * -cry - cry * - crx - crw * - crz;
    var caxz = -cry * crw - crx * -crz + crw * - cry - crz * - crx;
    var cayx = -crz * crw - cry * -crx + crw * - crz - crx * - cry;
    var cayy = crw * crw - cry * -cry + crx * - crx + crz * - crz;
    var cayz = crx * crw - cry * -crz - crz * - cry - crw * - crx;
    var cazx = cry * crw - crz * -crx - crx * - crz - crw * - cry;
    var cazy = -crx * crw - crz * -cry + crw * - crx - cry * - crz;
    var cazz = crw * crw - crz * -crz + cry * - cry + crx * - crx;
    var nd = vx * cayx + vy * cayy + vz * cayz;
    var nx = nd * cayx;
    var ny = nd * cayy;
    var nz = nd * cayz;
    var ppx = vx - nx;
    var ppy = vy - ny;
    var ppz = vz - nz;
    var x = ppx * caxx + ppy * caxy + ppz * caxz;
    var y = ppx * cazx + ppy * cazy + ppz * cazz;
    return V3(x, y, nd);
  }
363378
def _get_struct_kerningrecord(self, font_flags_wide_codes):
        """"""
        getter = unpack_ui16 if font_flags_wide_codes else unpack_ui8
        data = {}
        data['FontKerningCode1'] = getter(self._src)
        data['FontKerningCode2'] = getter(self._src)
        data['FontKerningAdjustment'] = unpack_si16(self._src)
        return data
907566
def colRowIsOnSciencePixelList(self, col, row, padding=DEFAULT_PADDING):
        """"""
        out = np.ones(len(col), dtype=bool)
        col_arr = np.array(col)
        row_arr = np.array(row)
        mask = np.bitwise_or(col_arr < 12. - padding, col_arr > 1111 + padding)
        out[mask] = False
        mask = np.bitwise_or(row_arr < 20. - padding, row_arr > 1043 + padding)
        out[mask] = False
        return out
671376
def text2art(text, font=DEFAULT_FONT, chr_ignore=True):
    
    """
    letters = standard_dic
    text_temp = text
    if isinstance(text, str) is False:
        raise artError(TEXT_TYPE_ERROR)
    if isinstance(font, str) is False:
        raise artError(FONT_TYPE_ERROR)
    font = font.lower()
    fonts = sorted(FONT_MAP.keys())
    font = indirect_font(font, fonts, text)
    letters = FONT_MAP[font][0]
    if FONT_MAP[font][1]:
        text_temp = text.lower()
    if font in UPPERCASE_FONTS:
        text_temp = text.upper()
    word_list = text_temp.split("\n")
    result = ""
    for word in word_list:
        if len(word) != 0:
            result = result + __word2art(word=word,
                                         font=font,
                                         chr_ignore=chr_ignore,
                                         letters=letters)
    return result
879247
def _repr_latex_(self):
        
        # TODO: we're mixing HTML with latex here. That is not necessarily a good idea, but works
        # with IPython 1.2.0. Once IPython 2.0 is released, this needs to be changed to _ipython_display_
        lines = []
        lines.append(r"<h1>{0}</h1>".format(self.__class__.__name__))

        lines.append("<p>Method: <code>{0!r}</code></p>".format(self.method))
        lines.append("<p>Parameters: <code>{0!r}</code></p>".format(self.parameters))
        lines.append("<p>Terms:</p>")
        lines.append("<ul>")
        lines.extend(['<li><code>{0!r}</code></li>'.format(lhs) for lhs in self.left_hand_side_descriptors])
        lines.append("</ul>")
        lines.append('<hr />')
        lines.append(r"\begin{align*}")
        for lhs, rhs in zip(self.left_hand_side_descriptors, self.right_hand_side):
            lines.append(r"\dot{{{0}}} &= {1} \\".format(sympy.latex(lhs.symbol), sympy.latex(rhs)))
        lines.append(r"\end{align*}")
        return "\n".join(lines)
356599
def demultiplex_cells(fastq, out_dir, readnumber, prefix, cb_histogram, 
                      cb_cutoff):
    ''' 
    '''
    annotations = detect_fastq_annotations(fastq)
    re_string = construct_transformed_regex(annotations)
    parser_re = re.compile(re_string)
    readstring = "" if not readnumber else "_R{}".format(readnumber)
    filestring = "{prefix}{sample}{readstring}.fq"
    cb_set = set()
    if cb_histogram:
        cb_set = get_cb_depth_set(cb_histogram, cb_cutoff)
    sample_set = set()
    batch = collections.defaultdict(list)
    parsed = 0
    safe_makedir(out_dir)
    for read in read_fastq(fastq):
        parsed += 1
        match = parser_re.search(read).groupdict()
        sample = match['CB']
        if cb_set and sample not in cb_set:
            continue
        sample_set.add(sample)
        batch[sample].append(read)
        # write in batches to avoid opening up file handles repeatedly
        if not parsed % 10000000:
            for sample, reads in batch.items():
                out_file = os.path.join(out_dir, filestring.format(**locals()))
                with open(out_file, "a") as out_handle:
                    for read in reads:
                        out_handle.write(read)
            batch = collections.defaultdict(list)

    for sample, reads in batch.items():
        out_file = os.path.join(out_dir, filestring.format(**locals()))
        with open(out_file, "a") as out_handle:
            for read in reads:
                out_handle.write(read)
366659
def create(cls, h:int, w:int, bboxes:Collection[Collection[int]], labels:Collection=None, classes:dict=None,
               pad_idx:int=0, scale:bool=True)->'ImageBBox':
        ""
        if isinstance(bboxes, np.ndarray) and bboxes.dtype == np.object: bboxes = np.array([bb for bb in bboxes])
        bboxes = tensor(bboxes).float()
        tr_corners = torch.cat([bboxes[:,0][:,None], bboxes[:,3][:,None]], 1)
        bl_corners = bboxes[:,1:3].flip(1)
        bboxes = torch.cat([bboxes[:,:2], tr_corners, bl_corners, bboxes[:,2:]], 1)
        flow = FlowField((h,w), bboxes.view(-1,2))
        return cls(flow, labels=labels, classes=classes, pad_idx=pad_idx, y_first=True, scale=scale)
135955
def _features_with_strokes(self, hwr_obj):
        """"""
        x = []
        img = Image.new('L', ((int(hwr_obj.get_width()*self.scaling_factor) + 2), (int(hwr_obj.get_height()*self.scaling_factor) + 2)), 'black')
        draw = ImageDraw.Draw(img, 'L')
        pointlist = hwr_obj.get_pointlist()
        bb = hwr_obj.get_bounding_box()
        for stroke_nr in range(self.strokes):
            last_point = None
            # make sure that the current symbol actually has that many
            # strokes
            if stroke_nr < len(pointlist):
                for point_nr in range(self.points_per_stroke):
                    if point_nr < len(pointlist[stroke_nr]):
                        point = pointlist[stroke_nr][point_nr]
                        x.append(pointlist[stroke_nr][point_nr]['x'])
                        x.append(pointlist[stroke_nr][point_nr]['y'])
                        if last_point is None:
                            last_point = point
                        y_from = int((-bb['miny'] + last_point['y'])*self.scaling_factor)
                        x_from = int((-bb['minx'] + last_point['x'])*self.scaling_factor)
                        y_to = int((-bb['miny'] + point['y'])*self.scaling_factor)
                        x_to = int((-bb['minx'] + point['x'])*self.scaling_factor)
                        draw.line([x_from, y_from, x_to, y_to], fill='#ffffff', width=1)
                        if self.pixel_env > 0:
                            pix = img.load()
                            for x_offset in range(-self.pixel_env,
                                                  self.pixel_env + 1):
                                for y_offset in range(-self.pixel_env,
                                                      self.pixel_env + 1):
                                    xp = int((-bb['minx'] + point['x'])
                                             * self.scaling_factor) + x_offset
                                    yp = int((-bb['miny'] + point['y'])
                                             * self.scaling_factor) + y_offset
                                    xp = max(0, xp)
                                    yp = max(0, yp)
                                    x.append(pix[xp, yp])
                        last_point = point
                    else:
                        x.append(self.fill_empty_with)
                        x.append(self.fill_empty_with)
                        if self.pixel_env > 0:
                            for i in range((1 + 2 * self.pixel_env)**2):
                                x.append(self.fill_empty_with)
            else:
                for _ in range(self.points_per_stroke):
                    x.append(self.fill_empty_with)
                    x.append(self.fill_empty_with)
                    if self.pixel_env > 0:
                        for i in range((1 + 2 * self.pixel_env)**2):
                            x.append(self.fill_empty_with)
        del draw
        return x
952425
private static HashMap<String, ITypeface> init(@NonNull Context ctx,
                                                   @NonNull HashMap<String, ITypeface> fonts) {
        init(ctx);
        if (fonts == null || fonts.size() == 0) {
            fonts = FONTS;
        }
        return fonts;
    }
1085220
def smart_fitting_predicate(
    page_width,
    ribbon_frac,
    min_nesting_level,
    max_width,
    triplestack
):
    
    chars_left = max_width

    while chars_left >= 0:
        if not triplestack:
            return True

        indent, mode, doc = triplestack.pop()

        if doc is NIL:
            continue
        elif isinstance(doc, str):
            chars_left -= len(doc)
        elif isinstance(doc, Concat):
            # Recursive call in Strictly Pretty: docs within Concat
            # are processed in order, with keeping the current
            # indentation and mode.
            # We want the leftmost element at the top of the stack,
            # so we append the concatenated documents in reverse order.
            triplestack.extend(
                (indent, mode, doc)
                for doc in reversed(doc.docs)
            )
        elif isinstance(doc, Annotated):
            triplestack.append((indent, mode, doc.doc))
        elif isinstance(doc, Fill):
            # Same as the Concat case.
            triplestack.extend(
                (indent, mode, doc)
                for doc in reversed(doc.docs)
            )
        elif isinstance(doc, Nest):
            # Nest is a combination of an indent and a doc.
            # Increase indentation, then add the doc for processing.
            triplestack.append((indent + doc.indent, mode, doc.doc))
        elif isinstance(doc, AlwaysBreak):
            return False
        elif doc is HARDLINE:
            # In the fast algorithm, when we see a line,
            # we return True. Here, as long as the minimum indentation
            # level is satisfied, we continue processing the next line.
            # This causes the longer runtime.
            if indent > min_nesting_level:
                chars_left = page_width - indent
            else:
                return True
        elif isinstance(doc, FlatChoice):
            if mode is FLAT_MODE:
                triplestack.append((indent, mode, doc.when_flat))
            elif mode is BREAK_MODE:
                triplestack.append((indent, mode, doc.when_broken))
            else:
                raise ValueError
        elif isinstance(doc, Group):
            # Group just changes the mode.
            triplestack.append((indent, FLAT_MODE, doc.doc))
        elif isinstance(doc, Contextual):
            ribbon_width = max(0, min(page_width, round(ribbon_frac * page_width)))

            evaluated_doc = doc.fn(
                indent=indent,
                column=max_width - chars_left,
                page_width=page_width,
                ribbon_width=ribbon_width,
            )
            normalized = normalize_doc(evaluated_doc)
            triplestack.append((indent, mode, normalized))
        elif isinstance(doc, SAnnotationPush):
            continue
        elif isinstance(doc, SAnnotationPop):
            continue
        else:
            raise ValueError((indent, mode, doc))

    return False
1305126
def hl_table2canvas(self, w, res_dict):
        """"""
        objlist = []

        # Remove existing highlight
        if self.maskhltag:
            try:
                self.canvas.delete_object_by_tag(self.maskhltag, redraw=False)
            except Exception:
                pass

        for sub_dict in res_dict.values():
            for seqno in sub_dict:
                mobj = self._maskobjs[int(seqno) - 1]
                dat = self._rgbtomask(mobj)
                obj = self.dc.Image(0, 0, masktorgb(
                    dat, color=self.hlcolor, alpha=self.hlalpha))
                objlist.append(obj)

        # Draw on canvas
        if len(objlist) > 0:
            self.maskhltag = self.canvas.add(self.dc.CompoundObject(*objlist))

        self.fitsimage.redraw()
1226675
def visual(title, X, activation):
    '''
    '''
    assert len(X.shape) == 4

    X = X.transpose((0, 2, 3, 1))
    if activation == 'sigmoid':
        X = np.clip((X)*(255.0), 0, 255).astype(np.uint8)
    elif activation == 'tanh':
        X = np.clip((X+1.0)*(255.0/2.0), 0, 255).astype(np.uint8)
    n = np.ceil(np.sqrt(X.shape[0]))
    buff = np.zeros((int(n*X.shape[1]), int(n*X.shape[2]), int(X.shape[3])), dtype=np.uint8)
    for i, img in enumerate(X):
        fill_buf(buff, i, img, X.shape[1:3])
    cv2.imwrite('%s.jpg' % (title), buff)
407325
def extract_morphological_information(mrph_object, is_feature, is_surface):
    # type: (pyknp.Morpheme, bool, bool) -> TokenizedResult
    
    assert isinstance(mrph_object, pyknp.Morpheme)
    assert isinstance(is_feature, bool)
    assert isinstance(is_surface, bool)

    surface = mrph_object.midasi
    word_stem = mrph_object.genkei

    tuple_pos = (mrph_object.hinsi, mrph_object.bunrui)

    misc_info = {
        'katuyou1': mrph_object.katuyou1,
        'katuyou2': mrph_object.katuyou2,
        'imis': mrph_object.imis,
        'repname': mrph_object.repname
    }

    token_object = TokenizedResult(
        node_obj=None,
        tuple_pos=tuple_pos,
        word_stem=word_stem,
        word_surface=surface,
        is_feature=is_feature,
        is_surface=is_surface,
        misc_info=misc_info
    )

    return token_object
1110952
def define_layout
      super do |components|
        components << Scruffy::Components::Title.new(:title, :position => [5, 2], :size => [90, 7])
                      
        VIEWPORTS.each_pair do |category, position|
          components << Scruffy::Components::Viewport.new(category, :position => position, 
                                                          :size => VIEWPORT_SIZE, &graph_block(category))
        end

        components << Scruffy::Components::Legend.new(:legend, :position => [5, 13], :size => [90, 5])
      end
    end
6913
def linetoraster(m):
    

    # Assumes monospaced font.
    x = 8 * len(m)
    y = 8
    return x, y, [itertools.chain(*row) for row in zip(*map(char, m))]