text:
from protein.models import Protein, ProteinConformation
from residue.models import Residue
from structure.models import Structure

import time

def generate_schematic(c):
    global fusion_protein_name
    # print("GENERATING!")

    time1 = time.time()

    ### PREPARE DATA
    summary = {}
    annotations = {}
    json_annotations = {}

    fusion_position,fusion_result, linkers = c.fusion()

    time2 = time.time()
    # print('%s function took %0.3f ms' % ('fusion', (time2-time1)*1000.0))

    if fusion_result:
        fusion_protein_name = fusion_result[0][2]
    else:
        fusion_protein_name = None

    summary['solubilization'] = ''
    if c.solubilization:
        for chem in c.solubilization.chemical_list.chemicals.prefetch_related('chemical').all():
            summary['solubilization'] += """{} ({} {})
""".format(chem.chemical.name,chem.concentration,chem.concentration_unit)
    time2 = time.time()
    # print('%s function took %0.3f ms' % ('summaries', (time2-time1)*1000.0))

    summary['purification'] = ''
    if c.purification:
        for step in c.purification.steps.all():
            if step.name!='None':
                summary['purification'] += """{}
""".format(step.name)
    time2 = time.time()
    # print('%s function took %0.3f ms' % ('summaries', (time2-time1)*1000.0))

    summary['crystallization_chems'] = ''
    if c.crystallization:
        for clist in c.crystallization.chemical_lists.all():
            # summary['crystallization_chems'] += """{}
""".format(clist.name)
            for chem in clist.chemicals.prefetch_related('chemical').all():
                summary['crystallization_chems'] += """{} ({} {})
""".format(chem.chemical.name,chem.concentration,chem.concentration_unit)

    time2 = time.time()
    # print('%s function took %0.3f ms' % ('summaries', (time2-time1)*1000.0))

    n_term = {}
    c_term = {}
    insert = {}
    deletion = {}
    pair_no = 0
    summary['modifications'] = ''
    for mod in c.modifications.all():
        if mod.position_type == 'pair':
            pair_no += 1
            pair_info = "Pair No"+str(pair_no)+" - "+str(mod.pos_start)+" : "+str(mod.pos_end)
            pair_short = str(pair_no)
        else:
            pair_info = str(mod.pos_start)
            pair_short = ''

        if mod.modification=='Disulfide bond': continue

        annotations[mod.pos_start] = ['mod','modification','Modified
'+mod.modification+"
"+pair_info,mod,pair_short]
        annotations[mod.pos_end] = ['mod','modification','Modified
'+mod.modification+"
"+pair_info,mod,pair_short]
        json_annotations[mod.pos_start] = ['mod','Modified
'+mod.modification+"
"+pair_info,"yellow","black"]
        json_annotations[mod.pos_end] = ['mod','Modified
'+mod.modification+"
"+pair_info,"yellow","black"]
        summary['modifications'] += pair_info+" - "+mod.modification+"
"

    summary['mutations'] = ''
    for mut in c.mutations.all():
        annotations[mut.sequence_number] = ['mut','mutation','Mutated from '+mut.wild_type_amino_acid+' to '+mut.mutated_amino_acid,mut]
        json_annotations[mut.sequence_number] = ['mut','Mutated from '+mut.wild_type_amino_acid+' to '+mut.mutated_amino_acid,"gold","black"]
        summary['mutations'] += mut.wild_type_amino_acid+str(mut.sequence_number)+mut.mutated_amino_acid+'
'

    summary['insertions'] = '
'
    for aux in c.insertions.order_by('position').prefetch_related('insert_type').all():
        position_without_number = aux.position.split("_")[0]
        if aux.start:
            if aux.start==19 and aux.insert_type.name=='auto':
                continue
            if aux.start in insert:
                print("ERROR Multiple inserts at same position",aux.start,c.name,aux)
                # if insert[aux.start].insert_type.name =='fusion':
                #     #continue to next
                #     # continue
                #     pass
            else:
                insert[aux.start] = []
            for i in range(aux.start,aux.end+1):
                annotations[i] = [aux.insert_type.name,'Insertion
Protein_type: '+aux.insert_type.name,aux]
                json_annotations[i] = ['ins','Insertion
Protein_type: '+aux.insert_type.name,"purple","white"]

            insert[aux.start].append(aux)

        if aux.position.startswith('N-term'):
            n_term[aux.position] = aux
        if aux.position.startswith('C-term'):
            c_term[aux.position] = aux
        summary['insertions'] += """{} - {} ({})
""".format(position_without_number,aux.insert_type.subtype,aux.insert_type.name)
    summary['insertions'] += '
'
    summary['deletions'] = ''
    for dele in c.deletions.all():
        deletion[dele.start] = ['del','deletion','Deleted from '+str(dele.start)+' to '+str(dele.end),dele]
        deletion[dele.end] = ['del','deletion','Deleted from '+str(dele.start)+' to '+str(dele.end),dele]

        summary['deletions'] += str(dele.start)+ " to "+str(dele.end)+'
'
        for i in range(dele.start,dele.end+1):
            annotations[i] = ['del','deletion','Deleted from '+str(dele.start)+' to '+str(dele.end),dele]
            json_annotations[i] = ['del','Deleted from '+str(dele.start)+' to '+str(dele.end),"red","white"]

    time2 = time.time()
    # print('%s function took %0.3f ms' % ('2', (time2-time1)*1000.0))

    # get residues
    residues = Residue.objects.filter(protein_conformation__protein=c.protein).order_by('sequence_number').prefetch_related(
        'protein_segment', 'generic_number', 'display_generic_number')

    time2 = time.time()
    # print('%s function took %0.3f ms' % ('3', (time2-time1)*1000.0))

    residues_custom = []
    residues_lookup = {}
    for r in residues:
        residues_lookup[r.sequence_number] = r
        r.print_amino_acid = r.amino_acid
        if r.sequence_number in annotations:
            if annotations[r.sequence_number][1] == 'deletion':
                continue
            if annotations[r.sequence_number][1] == 'insertion':
                continue
            if annotations[r.sequence_number][1] == 'mutation':
                r.print_amino_acid = annotations[r.sequence_number][3].mutated_amino_acid
        residues_custom.append(r)

    time2 = time.time()
    # print('%s function took %0.3f ms' % ('4', (time2-time1)*1000.0))

    results = {}
    results['annotations'] = json_annotations
    #### VERSION 1 SCHEMATIC

    chunk_size = 10
    r_chunks_schematic = []
    r_chunks_schematic_construct = []
    r_buffer = []
    a_buffer = []
    last_segment = False
    border = False
    title_cell_skip = 0
    ii = 0
    # create schemtics with annotations
    for i, r in enumerate(residues):
        if (r.protein_segment.slug != last_segment and i!=0) or i == len(residues)-1:
            a_list = {}
            if ii<20:
                counter = ii
                width = round(100/ii,1)
            else:
                counter = 20
                width = 5
            for a in a_buffer:
                temp = a[0]*counter // (ii)
                a_list[temp]  = a[1]
            if (last_segment):
                for a in range(counter):
                    if a<len(prev_r.protein_segment.slug):
                        title_cell_skip = 1
                    else:
                        title_cell_skip = 0

                    if a in a_list:
                        annotation = a_list[a]
                    else:
                        annotation = ''

                    if a==0:
                        r_buffer.append([prev_r, True, 0,annotation,width])
                    else:
                        r_buffer.append([prev_r, False, 0,annotation,width])

                r_chunks_schematic.append(r_buffer)
                #print(last_segment,prev_r.protein_segment.slug,counter,len(r_buffer),width,len(r_buffer)*width)
            border = True
            r_buffer = []
            a_buffer = []
            ii = 0

        if r.sequence_number in annotations:
            a_buffer.append([ii,annotations[r.sequence_number]])
        prev_r = r
        last_segment = r.protein_segment.slug
        ii+=1

    results['schematic_1_wt'] = r_chunks_schematic

    #### VERSION 1 SCHEMATIC CONSTRUC

    time2 = time.time()
    # print('%s function took %0.3f ms' % ('1', (time2-time1)*1000.0))

    for aux in sorted(n_term):
        name = n_term[aux].insert_type.subtype[:6]
        title_cell_skip = 0
        for i in range(20):
            if i==0:
                r_buffer.append([None, name, title_cell_skip,['insert','insertion',n_term[aux]]])
            else:
                if i<len(name):
                    title_cell_skip = 1
                else:
                    title_cell_skip = 0
                r_buffer.append([None, False, title_cell_skip,['insert','insertion',n_term[aux]]])
        r_chunks_schematic_construct.append(r_buffer)
        r_buffer = []

        ii = 0

    last_segment = False
    a_buffer = []
    r_buffer = []
    nudge = 0
    prev_r = None
    # create schemtics with annotations
    for i, r in enumerate(residues_custom):
        # print(i)
        if r.sequence_number-1 in deletion and i==0:
            r_buffer.append([None, False, 0,annotations[r.sequence_number-1]])
            nudge = 1

        if r.sequence_number+1 in deletion:
            if i < len(residues_custom)-1: #not last
                a_buffer.append([ii+1,annotations[r.sequence_number+1]])
            else:
                a_buffer.append([ii,annotations[r.sequence_number+1]])

        if (r.protein_segment.slug != last_segment and i!=0) or i == len(residues_custom)-1:
            a_list = {}
            for a in a_buffer:
                temp = a[0]*20 // (ii)
                a_list[temp]  = a[1]
            if (last_segment):
                for a in range(21):
                    if (a-nudge)<len(prev_r.protein_segment.slug):
                        title_cell_skip = 1
                    else:
                        title_cell_skip = 0

                    if a in a_list:
                        annotation = a_list[a]
                        if annotation[1] == 'deletion' and a==20:
                            no_r = True
                        else:
                            no_r = False
                    else:
                        annotation = ''
                        no_r = False

                    if a==0:
                        r_buffer.append([prev_r, prev_r.protein_segment.slug, 0,annotation])
                    else:
                        if no_r:
                            r_buffer.append([None, False, title_cell_skip,annotation])
                        else:
                            r_buffer.append([prev_r, False, title_cell_skip,annotation])
                r_chunks_schematic_construct.append(r_buffer)
                # print("2",last_segment,prev_r.protein_segment.slug,counter,len(r_buffer),width,len(r_buffer)*width)
            last_segment = r.protein_segment.slug
            border = True
            r_buffer = []
            a_buffer = []
            ii = 0
            nudge = 0
        #print(r_chunks_schematic_construct)

        if r.sequence_number in annotations:
            a_buffer.append([ii,annotations[r.sequence_number]])

        if prev_r:
            if i+1==len(residues_custom):
                prev_r = r
            if prev_r.sequence_number+1 in insert:
                for temp in insert[prev_r.sequence_number+1]:
                    name = temp.insert_type.subtype[:6]
                    title_cell_skip = 0
                    for i in range(21):
                        if i==0:
                            r_buffer.append([None, name, title_cell_skip,['insert','insertion',temp]])
                        else:
                            if i<len(name):
                                title_cell_skip = 1
                            else:
                                title_cell_skip = 0
                            r_buffer.append([None, False, title_cell_skip,['insert','insertion',temp]])
                    r_chunks_schematic_construct.append(r_buffer)
                    r_buffer = []

        if i+1==len(residues_custom) and r.sequence_number+1 in insert:
            name = insert[r.sequence_number+1].insert_type.subtype[:6]
            title_cell_skip = 0
            for i in range(21):
                if i==0:
                    #print(last_segment,name,len(r_chunks_schematic_construct))
                    r_buffer.append([None, name, title_cell_skip,['insert','insertion',insert[r.sequence_number+1]]])
                else:
                    if i<len(name):
                        title_cell_skip = 1
                    else:
                        title_cell_skip = 0
                    r_buffer.append([None, False, title_cell_skip,['insert','insertion',insert[r.sequence_number+1]]])
            r_chunks_schematic_construct.append(r_buffer)
            r_buffer = []

        last_segment = r.protein_segment.slug
        prev_r = r
        ii+=1

    for aux in sorted(c_term):
        # print("new",aux,c_term[aux])
        name = c_term[aux].insert_type.subtype[:6]
        title_cell_skip = 0
        for i in range(20):
            if i==0:
                r_buffer.append([None, name, title_cell_skip,['insert','insertion',c_term[aux]]])
            else:
                if i<len(name):
                    title_cell_skip = 1
                else:
                    title_cell_skip = 0
                r_buffer.append([None, False, title_cell_skip,['insert','insertion',c_term[aux]]])
        r_chunks_schematic_construct.append(r_buffer)
        r_buffer = []

        ii = 0

    results['schematic_1_c'] = r_chunks_schematic_construct
    # print(r_chunks_schematic_construct)

    # process residues and return them in chunks of 10
    # this is done for easier scaling on smaller screens
    chunk_size = 10
    r_chunks = []
    r_buffer = []
    last_segment = False
    border = False
    title_cell_skip = 0
    for i, r in enumerate(residues):
        # title of segment to be written out for the first residue in each segment
        segment_title = False

        # keep track of last residues segment (for marking borders)
        if r.protein_segment.slug != last_segment:
            last_segment = r.protein_segment.slug
            border = True

        # if on a border, is there room to write out the title? If not, write title in next chunk
        if i == 0 or (border and len(last_segment) <= (chunk_size - i % chunk_size)):
            segment_title = True
            border = False
            title_cell_skip += len(last_segment) # skip cells following title (which has colspan > 1)

        if i and i % chunk_size == 0:
            r_chunks.append(r_buffer)
            r_buffer = []

        if r.sequence_number in annotations:
            annotation = annotations[r.sequence_number]
        else:
            annotation = None

        r_buffer.append((r, segment_title, title_cell_skip,annotation))

        # update cell skip counter
        if title_cell_skip > 0:
            title_cell_skip -= 1
    if r_buffer:
        r_chunks.append(r_buffer)

    results['residues_wt'] = r_chunks

    # process residues and return them in chunks of 10
    # this is done for easier scaling on smaller screens
    r_chunks_custom = []
    r_buffer = []
    last_segment = False
    border = False
    title_cell_skip = 0

    nudge = 0

    fusion = False

    for aux in sorted(n_term):
        name = n_term[aux].insert_type.subtype[:11]
        title_cell_skip = 0
        for i in range(chunk_size):
            if i==0:
                r_buffer.append([None, name, title_cell_skip,['insert',n_term[aux].insert_type.name,n_term[aux]]])
            else:
                if i<len(name):
                    title_cell_skip = 1
                else:
                    title_cell_skip = 0
                r_buffer.append([None, False, title_cell_skip,['insert',n_term[aux].insert_type.name,n_term[aux]]])
        r_chunks_custom.append(r_buffer)
        r_buffer = []

    title_cell_skip = 0
    for i, r in enumerate(residues_custom):
        # title of segment to be written out for the first residue in each segment
        segment_title = False

        if r.sequence_number-1 in deletion and i==0:
            # r_buffer.append((r, segment_title, title_cell_skip,deletion[r.sequence_number+1]))
            r_buffer.append((None, segment_title, title_cell_skip,deletion[r.sequence_number-1]))
            nudge -= 1

        # keep track of last residues segment (for marking borders)
        if r.protein_segment.slug != last_segment:
            last_segment = r.protein_segment.slug
            border = True

        # if on a border, is there room to write out the title? If not, write title in next chunk
        if i == 0 or (border and len(last_segment) <= (chunk_size - (i-nudge) % chunk_size)):
            segment_title = True
            border = False
            title_cell_skip += len(last_segment) # skip cells following title (which has colspan > 1)

        if len(r_buffer) and i and (i-nudge) % chunk_size == 0:
            r_chunks_custom.append(r_buffer)
            r_buffer = []

        if r.sequence_number in annotations:
            annotation = annotations[r.sequence_number]
        else:
            annotation = None
        r_buffer.append((r, segment_title, title_cell_skip,annotation))

        if r.sequence_number+1 in deletion:
            # r_buffer.append((r, segment_title, title_cell_skip,deletion[r.sequence_number+1]))
            r_buffer.append((None, segment_title, title_cell_skip,deletion[r.sequence_number+1]))
            if title_cell_skip > 0: title_cell_skip -=1
            nudge -= 1

        if r.sequence_number+1 in insert:
            for temp in insert[r.sequence_number+1]:
                if len(r_buffer):
                    r_chunks_custom.append(r_buffer)
                r_buffer = []
                # for _ in range(chunk_size):
                #     r_buffer.append([r, segment_title, title_cell_skip,['insert','insertion']])
                for a in range(chunk_size):
                    name = temp.insert_type.subtype[:11]
                    if a==0:
                        r_buffer.append([r, name, title_cell_skip,['insert','insertion',temp]])
                    else:
                        if a<len(name):
                            title_cell_skip = 1
                        else:
                            title_cell_skip = 0
                        r_buffer.append([r, False, title_cell_skip,['insert','insertion',temp]])
                r_chunks_custom.append(r_buffer)
                r_buffer = []
                nudge = ((i+nudge) % chunk_size)+1

        # update cell skip counter
        if title_cell_skip > 0:
            title_cell_skip -= 1
    if r_buffer:
        r_chunks_custom.append(r_buffer)

    r_buffer = []
    for aux in sorted(c_term):
        # print('adding cterm',aux,c_term[aux].insert_type)
        name = c_term[aux].insert_type.subtype[:11]
        title_cell_skip = 0
        for i in range(chunk_size):
            if i==0:
                r_buffer.append([None, name, title_cell_skip,['insert',c_term[aux].insert_type.name,c_term[aux]]])
            else:
                if i<len(name):
                    title_cell_skip = 1
                else:
                    title_cell_skip = 0
                r_buffer.append([None, False, title_cell_skip,['insert',c_term[aux].insert_type.name,c_term[aux]]])
        r_chunks_custom.append(r_buffer)
        r_buffer = []

    results['residues_c'] = r_chunks_custom

    #BUILDING

    ## SCHEMATIC WT

    wt_schematic = """
"""
    for rs in r_chunks_schematic:
        wt_schematic += """

"""
        for r in rs:
            if r[3]:
                wt_schematic += """

	""".format(r[3][1],r[3][2])
            else:
                wt_schematic += """

                            	"""
        wt_schematic += """

"""
        for r in rs:
            if not r[1] and r[2]:
                pass
            else:
                if r[0].protein_segment.id % 2 == 0:
                    extra = "bg-success"
                else:
                    extra = "bg-info"

                wt_schematic += """""".format(extra)
                if r[1]:
                    wt_schematic += r[0].protein_segment.slug
                else:
                    wt_schematic += " "
                wt_schematic += "	"

        wt_schematic += "

"
    wt_schematic += "
"

    ## SCHEMATIC CONSTRUCT

    c_schematic = """
"""
    for rs in r_chunks_schematic_construct:
        c_schematic += """

"""
        for r in rs:
            if r[3]:
                c_schematic += """

	""".format(r[3][1],r[3][2])
            else:
                c_schematic += """

                            	"""
        c_schematic += """

"""
        for r in rs:
            if not r[1] and r[2]:
                pass
            else:
                try:
                    extra = "bg-"+r[3][1]
                except:
                    extra = ""
                if r[0]:
                    if r[0].protein_segment.id % 2 == 0:
                        extra = "bg-success"
                    else:
                        extra = "bg-info"

                colspan = 1

                if r[3] and r[1]:
                    text = r[1]
                    colspan = len(text)
                elif r[1]:
                    text = r[0].protein_segment.slug
                    colspan = len(text)
                else:
                    text = " "

                c_schematic += """{}	""".format(colspan,extra,text)

        c_schematic += "

"
    c_schematic += "
"

    ### BUILD WT SPECIFIC TABLE
    wt_schematic_table = ""
    order_list = ['N-term','TM1','ICL1','TM2','ECL1','TM3','ICL2','TM4','ECL2','TM5','ICL3','TM6','ECL3','TM7','H8','C-term'] #,'ICL4'
    i = 0
    for block in order_list:
        wt_schematic_table += ""
        if i<len(r_chunks_schematic):
            slug = r_chunks_schematic[i][0][0].protein_segment.slug
            if block==slug:
                wt_schematic_table += create_block(r_chunks_schematic[i])
            else:
                i -=1 #not found match, dont move up
            i += 1
        wt_schematic_table += "	"

    results['schematic_2_wt'] = wt_schematic_table

    ### BUILD CONSTRUCT SPECIFIC TABLE
    c_schematic_table = ""
    order_list = ['pre','N-term','TM1','ICL1','TM2','ECL1','TM3','insert','ICL2','insert','TM4','ECL2','TM5','insert','ICL3','insert','TM6','ECL3','TM7','H8','C-term','post'] #,'ICL4'
    i = 0
    problem = False
    tm_corrected = False
    # print(r_chunks_schematic_construct)
    for block in order_list:
        c_schematic_table += ""
        if problem:
            i -= problem
            problem = False
            tm_corrected = True
        # print(block,r_chunks_schematic_construct[i][0][1])
        try:
            if block=='TM5' and r_chunks_schematic_construct[i][0][1]!='TM5':
                # print('problem!',block,r_chunks_schematic_construct[i][0][1])
                problem = 1
                a = True
                while a and i<len(r_chunks_schematic_construct):
                    if r_chunks_schematic_construct[i][0][1]!='TM5':
                        i+=1
                        problem += 1
                    else:
                        a = False
                # print(r_chunks_schematic_construct[i][0][1],problem)
            if block=='ICL3' and tm_corrected and r_chunks_schematic_construct[i][0][1]!='ICL3':
                # print('try to find icl3')
                a = True
                while a and i<len(r_chunks_schematic_construct):
                    i += 1
                    if r_chunks_schematic_construct[i][0][1]=='ICL3':
                        # print('found ICL3',i)
                        a = False
            if block=='TM6' and tm_corrected and r_chunks_schematic_construct[i][0][1]!='TM6':
                # print('try to find TM6')
                a = True
                while a and i<len(r_chunks_schematic_construct):
                    i += 1
                    if r_chunks_schematic_construct[i][0][1]=='TM6':
                        # print('found TM6',i)
                        a = False
        except:
            pass
        if i<len(r_chunks_schematic_construct):
            if block=='pre':
                a = True
                c_schematic_table += "

"
                while a and i<len(r_chunks_schematic_construct):
                    if r_chunks_schematic_construct[i][0][3]:
                        if r_chunks_schematic_construct[i][0][3][0]=='insert':
                            c_schematic_table += ""+create_block(r_chunks_schematic_construct[i]) +"	"
                            i+=1
                        else:
                            a = False
                    else:
                        a = False
                c_schematic_table += "

"
            elif block=='post':
                a = True
                c_schematic_table += "

"
                while a and i<len(r_chunks_schematic_construct):
                    if r_chunks_schematic_construct[i][0][3]:
                        if r_chunks_schematic_construct[i][0][3][0]=='insert' :
                            c_schematic_table += ""+create_block(r_chunks_schematic_construct[i]) +"	"
                            i+=1
                        else:
                            a = False
                    else:
                        a = False
                c_schematic_table += "

"
            elif block=='insert':
                # print("insert?",r_chunks_schematic_construct[i])
                a = True
                c_schematic_table += "

"
                while a and i<len(r_chunks_schematic_construct):
                    if r_chunks_schematic_construct[i][0][3]:
                        if r_chunks_schematic_construct[i][0][3][0]=='insert' :
                            c_schematic_table += ""+create_block(r_chunks_schematic_construct[i]) +"	"
                            i+=1
                        else:
                            a = False
                    else:
                        a = False
                c_schematic_table += "

"
            else:
                if block==r_chunks_schematic_construct[i][0][1]:
                    c_schematic_table += create_block(r_chunks_schematic_construct[i])
                    # print('found!',r_chunks_schematic_construct[i][0][1])
                elif block==r_chunks_schematic_construct[i][1][1]: #if started with deletion
                    c_schematic_table += create_block(r_chunks_schematic_construct[i])
                else:
                    # print('not found!',i,block,r_chunks_schematic_construct[i][0][1],r_chunks_schematic_construct[i][1][1])
                    i -=1 #not found match, dont move up
                    c_schematic_table += " "
                i += 1
        c_schematic_table += "	"

    results['schematic_2_c'] = c_schematic_table

    results['summary'] = summary

    time2 = time.time()
    # print('%s function took %0.3f ms' % ('final', (time2-time1)*1000.0))
    #print('done')
    results['schematic_1_c'] = '' #FAILS NOT REQUIRED THO
    results['schematic_1_wt'] = '' #FAILS NOT REQUIRED THO
    # results['residues_c'] = '' #FAILS
    # results['residues_wt'] = '' ## FAILS
    # results['schematic_2_wt'] = '' NOT FAILS
    # results['schematic_2_c'] = '' # Not fails
    # results['summary'] = '' # Not fails
    # results['annotations'] = ''# Not fails
    return results

def create_block(chunk):

    temp = """

"""
    blank = 0
    blank_max = 20
    min_colspan = 1
    if len(chunk)<10:
        min_colspan = round(20/len(chunk))
    for i,r in enumerate(chunk):
        if r[3]:
            extra = r[3][1]
            if r[3][1]=='insertion' and i>19:
                continue #pass to prevent too many

            if r[3][1]=='insertion':
                r[3][1] = r[3][2].autotype()

                if r[3][2].insert_type.subtype==fusion_protein_name:
                    r[3][1] = 'fusion'

                extra = r[3][1]
                extra += "top"

            if blank:
                temp += """ 	""".format(str(blank))
                blank = 0
            temp += """

	""".format(extra,min_colspan,r[3][2])
            blank_max = blank_max-i
        else:
            blank += 1
            if blank > blank_max:
                blank = blank_max

    if blank:
        temp += """ 	""".format(str(blank))
    temp += """

"""
    for r in chunk:
        if not r[1] and r[2] and 2==3:
            pass
        else:
            try:
                extra = "bg-"+r[3][1]
            except:
                extra = ""
            if r[0]:
                if r[0].protein_segment.id % 2 == 0:
                    extra = "bg-success"
                else:
                    extra = "bg-info"

            if r[3] and r[1]:
                text = r[1]
                if text == True:
                    text = r[0].protein_segment.slug
            elif r[1]:
                text = r[0].protein_segment.slug
            else:
                text = " "
            if r[1] and r[3]:
                if r[3][0] == 'insert':
                    # print(text,r)
                    name = r[3][2].insert_type.subtype
                    # print(name)
                    extra = r[3][1]
                    if name==fusion_protein_name:
                        extra = 'fusion'

            if r[1]:
                temp += """{}	""".format(extra,text)
            elif r[0]==None and r[3] and r[3][0]!='insert':
                temp += """{}	""".format(extra,text)

    temp += "

"
    return temp


text:
PROJECT_BEEGENES
================
Analysis of Frequencies of Honeybee Genes

A project focusing on the relative frequencies of nucleotides of honeybee's genes.

Introduction:

	Genes are formed with four basic elements: adenine(A), cytosine(C),
	guanine(G) and thymine(T). These building elements are called nucleotides,
	a sequence of which forms a gene. The compositions of the nucleotides
	of genes play a great role of specifying living beings' proteins and
	functional RNA chains. To be more specific, nucleotides' relative
	frequencies, especially the relative frequencies of C and G together,
	are of great importance to determine the sequence of proteins and functional
	RNA. Thus, a research on the relative frequencies of nucleotides of genes
	has significant biological and potentially medical meanings.

	This project will study relative frequencies of nucleotides of honeybee's
	genes, which integrates Python programming, Oracle database, database-driven
	dynamic web pages, and SAS data analysis.

Raw Data:

	honeybee_gene_sequences.txt

	This file is downloaded from website of National Center for Biotechnology
	Information (NCBI), which can be accessed by:

		http://www.ncbi.nlm.nih.gov/

Roadmap:

	1. collect raw data from NCBI
	2. process collected data with Python programming
	3. store results in Oracle database through
	   Internet featured by Python
	4. access database through internet ant Python,
	   using database-driven dynamic web pages
	5. analyze data stored in the database with SAS

Programming Goal:

    1. Dynamic webpage powered by python
    2. Simple webpage design
    3. Oracle-integrated webpage

Version info:

	1. Oracle database 11g express
	2. Python 2.7
	3. cx_Oracle module required

Main Implementation :

	1. assume oracle username = python, password = welcome
	2. run 'localCGIServer.py' in terminal, which will prompt
	   'Localhost CGI server started' in terminal to indicate
	   successful setup
	3. in web browser, like IE, Chrome, Firefox, type in the
	   following website:

		http://localhost:8081/dataInput.html

	4. type in a full path where file 'honeybee_gene_sequences.txt'
	   is located in computer in the webpage which is created
	   by last step, then click 'submit' button
	5. after clicking 'click to see result' button in the new webpage,
	   another webpage will jump out to show analysis result

redpajama_set_name: RedPajamaGithub


text:
require 'ffaker'

FactoryGirl.define do
  factory :email do
    address { FFaker::Internet.email }

    trait :with_approved_offer do
      after :create do |email, _evaluator|
        offers = [FactoryGirl.create(:offer, :approved)]
        email.contact_people << FactoryGirl.create(:contact_person,
                                                   offers: offers)
        email.contact_people.first.organization.update_columns(
          aasm_state: 'all_done'
        )
      end
    end

    trait :with_unapproved_offer do
      after :create do |email, _evaluator|
        offers = [FactoryGirl.create(:offer)]
        email.contact_people << FactoryGirl.create(:contact_person,
                                                   offers: offers)
        email.contact_people.first.organization.update_columns(
          aasm_state: 'all_done'
        )
      end
    end

    trait :with_approved_and_unapproved_offer do
      after :create do |email, _evaluator|
        offers = [FactoryGirl.create(:offer),
                  FactoryGirl.create(:offer, :approved)]
        email.contact_people << FactoryGirl.create(:contact_person,
                                                   offers: offers)
        email.contact_people.first.organization.update_columns(
          aasm_state: 'all_done'
        )
      end
    end

    trait :with_security_code do
      after :build do |email, _evaluator|
        email.send(:regenerate_security_code)
      end
    end

    trait :uninformed do
      aasm_state 'uninformed'
    end

    trait :informed do
      aasm_state 'informed'
    end

    trait :subscribed do
      aasm_state 'subscribed'
    end

    trait :unsubscribed do
      aasm_state 'unsubscribed'
    end
  end
end


text:
package com.lanyuan.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lanyuan.dao.UserDao;
import com.lanyuan.entity.Roles;
import com.lanyuan.entity.User;
import com.lanyuan.service.UserService;
import com.lanyuan.util.PageView;

@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;

	public PageView query(PageView pageView, User user) {
		List<User> list = userDao.query(pageView, user);
		pageView.setRecords(list);
		return pageView;
	}

	public void add(User user) {
		userDao.add(user);

	}

	public void delete(String id) {
		userDao.delete(id);

	}

	public User getById(String id) {
		return userDao.getById(id);
	}

	public void modify(User user) {
		userDao.modify(user);
	}

	public int countUser(String userName, String userPassword) {
		return userDao.countUser(userName, userPassword);
	}

	public User querySingleUser(String userName) {
		return userDao.querySingleUser(userName);
	}

	public Roles findbyUserRole(String userId) {
		return userDao.findbyUserRole(userId);
	}
}


text:
import json
import os

import dcoscli.constants as cli_constants
import six
from dcos import constants

import pytest

from .common import assert_command, config_set, config_unset, exec_command

@pytest.fixture
def env():
    r = os.environ.copy()
    r.update({
        constants.PATH_ENV: os.environ[constants.PATH_ENV],
        constants.DCOS_CONFIG_ENV: os.path.join("tests", "data", "dcos.toml"),
        cli_constants.DCOS_PRODUCTION_ENV: 'false'
    })
    return r

@pytest.fixture
def missing_env():
    r = os.environ.copy()
    r.update({
        constants.PATH_ENV: os.environ[constants.PATH_ENV],
        constants.DCOS_CONFIG_ENV:
            os.path.join("tests", "data", "missing_params_dcos.toml")
    })
    return r

def test_help():
    stdout = b"""Get and set DCOS CLI configuration properties

Usage:
    dcos config --info
    dcos config append <name> <value>
    dcos config prepend <name> <value>
    dcos config set <name> <value>
    dcos config show [<name>]
    dcos config unset [--index=<index>] <name>
    dcos config validate

Options:
    -h, --help       Show this screen
    --info           Show a short description of this subcommand
    --version        Show version
    --index=<index>  Index into the list. The first element in the list has an
                     index of zero

Positional Arguments:
    <name>           The name of the property
    <value>          The value of the property
"""
    assert_command(['dcos', 'config', '--help'],
                   stdout=stdout)

def test_info():
    stdout = b'Get and set DCOS CLI configuration properties\n'
    assert_command(['dcos', 'config', '--info'],
                   stdout=stdout)

def test_version():
    stdout = b'dcos-config version SNAPSHOT\n'
    assert_command(['dcos', 'config', '--version'],
                   stdout=stdout)

def test_list_property(env):
    stdout = b"""core.dcos_url=http://change.dcos.url
core.email=test@mail.com
core.reporting=False
core.timeout=5
package.cache=tmp/cache
package.sources=['https://github.com/mesosphere/universe/archive/\
cli-tests.zip']
"""
    assert_command(['dcos', 'config', 'show'],
                   stdout=stdout,
                   env=env)

def test_get_existing_string_property(env):
    _get_value('core.dcos_url', 'http://change.dcos.url', env)

def test_get_existing_boolean_property(env):
    _get_value('core.reporting', False, env)

def test_get_existing_number_property(env):
    _get_value('core.timeout', 5, env)

def test_get_missing_property(env):
    _get_missing_value('missing.property', env)

def test_get_top_property(env):
    stderr = (
        b"Property 'package' doesn't fully specify a value - "
        b"possible properties are:\n"
        b"package.cache\n"
        b"package.sources\n"
    )

    assert_command(['dcos', 'config', 'show', 'package'],
                   stderr=stderr,
                   returncode=1)

def test_set_existing_string_property(env):
    config_set('core.dcos_url', 'http://change.dcos.url:5081', env)
    _get_value('core.dcos_url', 'http://change.dcos.url:5081', env)
    config_set('core.dcos_url', 'http://change.dcos.url', env)

def test_set_existing_boolean_property(env):
    config_set('core.reporting', 'true', env)
    _get_value('core.reporting', True, env)
    config_set('core.reporting', 'true', env)

def test_set_existing_number_property(env):
    config_set('core.timeout', '5', env)
    _get_value('core.timeout', 5, env)
    config_set('core.timeout', '5', env)

def test_set_change_output(env):
    assert_command(
        ['dcos', 'config', 'set', 'core.dcos_url',
         'http://change.dcos.url:5081'],
        stdout=(b"[core.dcos_url]: changed from 'http://change.dcos.url' to "
                b"'http://change.dcos.url:5081'\n"),
        env=env)
    config_set('core.dcos_url', 'http://change.dcos.url', env)

def test_set_same_output(env):
    assert_command(
        ['dcos', 'config', 'set', 'core.dcos_url', 'http://change.dcos.url'],
        stdout=b"[core.dcos_url]: already set to 'http://change.dcos.url'\n",
        env=env)

def test_set_new_output(env):
    config_unset('core.dcos_url', None, env)
    assert_command(
        ['dcos', 'config', 'set', 'core.dcos_url',
         'http://change.dcos.url:5081'],
        stdout=(b"[core.dcos_url]: set to 'http://change.dcos.url:5081'\n"),
        env=env)
    config_set('core.dcos_url', 'http://change.dcos.url', env)

def test_append_empty_list(env):
    config_set('package.sources', '[]', env)
    _append_value(
        'package.sources',
        'https://github.com/mesosphere/universe/archive/cli-tests.zip',
        env)
    _get_value(
        'package.sources',
        ['https://github.com/mesosphere/universe/archive/cli-tests.zip'],
        env)

def test_prepend_empty_list(env):
    config_set('package.sources', '[]', env)
    _prepend_value(
        'package.sources',
        'https://github.com/mesosphere/universe/archive/cli-tests.zip',
        env)
    _get_value(
        'package.sources',
        ['https://github.com/mesosphere/universe/archive/cli-tests.zip'],
        env)

def test_append_list(env):
    _append_value(
        'package.sources',
        'https://github.com/mesosphere/universe/archive/version-2.x.zip',
        env)
    _get_value(
        'package.sources',
        ['https://github.com/mesosphere/universe/archive/cli-tests.zip',
         'https://github.com/mesosphere/universe/archive/version-2.x.zip'],
        env)
    config_unset('package.sources', '1', env)

def test_prepend_list(env):
    _prepend_value(
        'package.sources',
        'https://github.com/mesosphere/universe/archive/version-2.x.zip',
        env)
    _get_value(
        'package.sources',
        ['https://github.com/mesosphere/universe/archive/version-2.x.zip',
         'https://github.com/mesosphere/universe/archive/cli-tests.zip'],
        env)
    config_unset('package.sources', '0', env)

def test_append_non_list(env):
    stderr = (b"Append/Prepend not supported on 'core.dcos_url' "
              b"properties - use 'dcos config set core.dcos_url new_uri'\n")

    assert_command(
        ['dcos', 'config', 'append', 'core.dcos_url', 'new_uri'],
        returncode=1,
        stderr=stderr,
        env=env)

def test_prepend_non_list(env):
    stderr = (b"Append/Prepend not supported on 'core.dcos_url' "
              b"properties - use 'dcos config set core.dcos_url new_uri'\n")

    assert_command(
        ['dcos', 'config', 'prepend', 'core.dcos_url', 'new_uri'],
        returncode=1,
        stderr=stderr,
        env=env)

def test_unset_property(env):
    config_unset('core.reporting', None, env)
    _get_missing_value('core.reporting', env)
    config_set('core.reporting', 'false', env)

def test_unset_missing_property(env):
    assert_command(
        ['dcos', 'config', 'unset', 'missing.property'],
        returncode=1,
        stderr=b"Property 'missing.property' doesn't exist\n",
        env=env)

def test_unset_output(env):
    assert_command(['dcos', 'config', 'unset', 'core.reporting'],
                   stdout=b'Removed [core.reporting]\n',
                   env=env)
    config_set('core.reporting', 'false', env)

def test_unset_index_output(env):
    stdout = (
        b"[package.sources]: removed element "
        b"'https://github.com/mesosphere/universe/archive/cli-tests.zip' "
        b"at index '0'\n"
    )

    assert_command(['dcos', 'config', 'unset', 'package.sources', '--index=0'],
                   stdout=stdout,
                   env=env)

    _prepend_value(
        'package.sources',
        'https://github.com/mesosphere/universe/archive/cli-tests.zip',
        env)

def test_set_whole_list(env):
    config_set(
        'package.sources',
        '["https://github.com/mesosphere/universe/archive/cli-tests.zip"]',
        env)

def test_unset_top_property(env):
    stderr = (
        b"Property 'package' doesn't fully specify a value - "
        b"possible properties are:\n"
        b"package.cache\n"
        b"package.sources\n"
    )

    assert_command(
        ['dcos', 'config', 'unset', 'package'],
        returncode=1,
        stderr=stderr,
        env=env)

def test_unset_list_index(env):
    config_unset('package.sources', '0', env)
    _get_value(
        'package.sources',
        [],
        env)
    _prepend_value(
        'package.sources',
        'https://github.com/mesosphere/universe/archive/cli-tests.zip',
        env)

def test_unset_outbound_index(env):
    stderr = (
        b'Index (3) is out of bounds - possible values are '
        b'between 0 and 0\n'
    )

    assert_command(
        ['dcos', 'config', 'unset', '--index=3', 'package.sources'],
        returncode=1,
        stderr=stderr,
        env=env)

def test_unset_bad_index(env):
    stderr = b'Error parsing string as int\n'

    assert_command(
        ['dcos', 'config', 'unset', '--index=number', 'package.sources'],
        returncode=1,
        stderr=stderr,
        env=env)

def test_unset_index_from_string(env):
    stderr = b'Unsetting based on an index is only supported for lists\n'

    assert_command(
        ['dcos', 'config', 'unset', '--index=0', 'core.dcos_url'],
        returncode=1,
        stderr=stderr,
        env=env)

def test_validate(env):
    stdout = b'Congratulations, your configuration is valid!\n'
    assert_command(['dcos', 'config', 'validate'],
                   env=env, stdout=stdout)

def test_validation_error(env):
    source = ["https://github.com/mesosphere/universe/archive/cli-tests.zip"]
    config_unset('package.sources', None, env)

    stdout = b"Error: missing required property 'sources'.\n"
    assert_command(['dcos', 'config', 'validate'],
                   returncode=1,
                   stdout=stdout,
                   env=env)

    config_set('package.sources', json.dumps(source), env)
    _get_value('package.sources', source, env)

def test_set_property_key(env):
    assert_command(
        ['dcos', 'config', 'set', 'path.to.value', 'cool new value'],
        returncode=1,
        stderr=b"'path' is not a dcos command.\n",
        env=env)

def test_set_missing_property(missing_env):
    config_set('core.dcos_url', 'http://localhost:8080', missing_env)
    _get_value('core.dcos_url', 'http://localhost:8080', missing_env)
    config_unset('core.dcos_url', None, missing_env)

def test_set_core_property(env):
    config_set('core.reporting', 'true', env)
    _get_value('core.reporting', True, env)
    config_set('core.reporting', 'false', env)

def test_url_validation(env):
    key = 'core.dcos_url'
    default_value = 'http://change.dcos.url'

    config_set(key, 'http://localhost', env)
    config_set(key, 'https://localhost', env)
    config_set(key, 'http://dcos-1234', env)
    config_set(key, 'http://dcos-1234.mydomain.com', env)

    config_set(key, 'http://localhost:5050', env)
    config_set(key, 'https://localhost:5050', env)
    config_set(key, 'http://mesos-1234:5050', env)
    config_set(key, 'http://mesos-1234.mydomain.com:5050', env)

    config_set(key, 'http://localhost:8080', env)
    config_set(key, 'https://localhost:8080', env)
    config_set(key, 'http://marathon-1234:8080', env)
    config_set(key, 'http://marathon-1234.mydomain.com:5050', env)

    config_set(key, 'http://user@localhost:8080', env)
    config_set(key, 'http://u-ser@localhost:8080', env)
    config_set(key, 'http://user123_@localhost:8080', env)
    config_set(key, 'http://user:p-ssw_rd@localhost:8080', env)
    config_set(key, 'http://user123:password321@localhost:8080', env)
    config_set(key, 'http://us%r1$3:pa#sw*rd321@localhost:8080', env)

    config_set(key, default_value, env)

def test_append_url_validation(env):
    default_value = ('["https://github.com/mesosphere/universe/archive/'
                     'cli-tests.zip"]')

    config_set('package.sources', '[]', env)
    _append_value(
        'package.sources',
        'https://github.com/mesosphere/universe/archive/cli-tests.zip',
        env)
    _append_value(
        'package.sources',
        'git@github.com:mesosphere/test.git',
        env)
    _append_value(
        'package.sources',
        'https://github.com/mesosphere/test.git',
        env)
    _append_value(
        'package.sources',
        'file://some-domain.com/path/to/file.extension',
        env)
    _append_value(
        'package.sources',
        'file:///path/to/file.extension',
        env)
    config_set('package.sources', default_value, env)

def test_prepend_url_validation(env):
    default_value = ('["https://github.com/mesosphere/universe/archive/'
                     'cli-tests.zip"]')

    config_set('package.sources', '[]', env)
    _prepend_value(
        'package.sources',
        'https://github.com/mesosphere/universe/archive/cli-tests.zip',
        env)
    _prepend_value(
        'package.sources',
        'git@github.com:mesosphere/test.git',
        env)
    _prepend_value(
        'package.sources',
        'https://github.com/mesosphere/test.git',
        env)
    _prepend_value(
        'package.sources',
        'file://some-domain.com/path/to/file.extension',
        env)
    _prepend_value(
        'package.sources',
        'file:///path/to/file.extension',
        env)
    config_set('package.sources', default_value, env)

def test_fail_url_validation(env):
    _fail_url_validation('set', 'core.dcos_url', 'http://bad_domain/', env)
    _fail_url_validation('set', 'core.dcos_url', 'http://@domain/', env)
    _fail_url_validation('set', 'core.dcos_url', 'http://user:pass@/', env)
    _fail_url_validation('set', 'core.dcos_url', 'http://us:r:pass@url', env)

def test_bad_port_fail_url_validation(env):
    _fail_url_validation('set', 'core.dcos_url',
                         'http://localhost:bad_port/', env)

def test_append_fail_url_validation(env):
    _fail_url_validation('append', 'package.sources', 'bad_url', env)

def test_prepend_fail_url_validation(env):
    _fail_url_validation('prepend', 'package.sources', 'bad_url', env)

def test_timeout(missing_env):
    config_set('marathon.url', 'http://1.2.3.4', missing_env)
    config_set('core.timeout', '1', missing_env)

    returncode, stdout, stderr = exec_command(
        ['dcos', 'marathon', 'app', 'list'], env=missing_env)

    assert returncode == 1
    assert stdout == b''
    assert "(connect timeout=1)".encode('utf-8') in stderr

    config_unset('core.timeout', None, missing_env)
    config_unset('marathon.url', None, missing_env)

def test_parse_error():
    env = os.environ.copy()
    path = os.path.join('tests', 'data', 'config', 'parse_error.toml')
    env['DCOS_CONFIG'] = path

    assert_command(['dcos', 'config', 'show'],
                   returncode=1,
                   stderr=six.b(("Error parsing config file at [{}]: Found "
                                 "invalid character in key name: ']'. "
                                 "Try quoting the key name.\n").format(path)),
                   env=env)

def _fail_url_validation(command, key, value, env):
    returncode_, stdout_, stderr_ = exec_command(
        ['dcos', 'config', command, key, value], env=env)

    assert returncode_ == 1
    assert stdout_ == b''
    assert stderr_.startswith(str(
        'Error: {!r} does not match'.format(value)).encode('utf-8'))

def _append_value(key, value, env):
    assert_command(
        ['dcos', 'config', 'append', key, value],
        env=env)

def _prepend_value(key, value, env):
    assert_command(
        ['dcos', 'config', 'prepend', key, value],
        env=env)

def _get_value(key, value, env):
    returncode, stdout, stderr = exec_command(
        ['dcos', 'config', 'show', key],
        env)

    if isinstance(value, six.string_types):
        result = json.loads('"' + stdout.decode('utf-8').strip() + '"')
    else:
        result = json.loads(stdout.decode('utf-8').strip())

    assert returncode == 0
    assert result == value
    assert stderr == b''

def _get_missing_value(key, env):
    returncode, stdout, stderr = exec_command(
        ['dcos', 'config', 'show', key],
        env)

    assert returncode == 1
    assert stdout == b''
    assert (stderr.decode('utf-8') ==
            "Property {!r} doesn't exist\n".format(key))


text:
package com.nicolas.coding.project;

import android.view.View;
import android.widget.TextView;

import com.nicolas.coding.project.detail.ProjectActivity_;
import com.readystatesoftware.viewbadger.BadgeView;

import com.nicolas.coding.R;
import com.nicolas.coding.common.Global;
import com.nicolas.coding.common.RedPointTip;
import com.nicolas.coding.project.detail.ProjectActivity;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;

@EFragment(R.layout.fragment_project_private)
public class PrivateProjectHomeFragment extends BaseProjectHomeFragment {

    @AfterViews
    protected void init2() {
        final String buttonTitle[] = new String[]{
                "动态",
                "任务",
                "讨论",
                "文件",
                "代码",
                "成员",
                "Readme",
                "Merge Request"
        };

        final int buttonIcon[] = new int[]{
                R.drawable.project_button_icon_dynamic,
                R.drawable.project_button_icon_task,
                R.drawable.project_button_icon_topic,
                R.drawable.project_button_icon_docment,
                R.drawable.project_button_icon_code,
                R.drawable.project_button_icon_member,
                R.drawable.project_button_icon_readme,
                R.drawable.project_button_icon_merge,
        };

        final int buttonId[] = new int[]{
                R.id.itemDynamic,
                R.id.itemTask,
                R.id.itemTopic,
                R.id.itemDocment,
                R.id.itemCode,
                R.id.itemMember,
                R.id.itemReadme,
                R.id.itemMerge
        };

        for (int i = 0; i < buttonId.length; ++i) {
            View item = getView().findViewById(buttonId[i]);
            item.findViewById(R.id.icon).setBackgroundResource(buttonIcon[i]);
            ((TextView) item.findViewById(R.id.title)).setText(buttonTitle[i]);
            final int pos = i;
            item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (buttonId[pos]) {
                        case R.id.itemDynamic:
                            updateDynamic();
                            break;

                        case R.id.itemTask:
                            break;

                        case R.id.itemCode:
                            break;

                        case R.id.itemReadme:
                            break;

                        case R.id.itemMerge:
                            markUsed(RedPointTip.Type.Merge320);
                            break;

                        case R.id.itemDocment:
                            markUsed(RedPointTip.Type.File320);
                            break;
                    }

                    ProjectActivity_.intent(PrivateProjectHomeFragment.this)
                            .mProjectObject(mProjectObject)
                            .mJumpType(ProjectActivity.PRIVATE_JUMP_TYPES[pos])
                            .start();
                }

            });

            if (buttonId[i] == R.id.itemDynamic) {
                dynamicBadge = (BadgeView) item.findViewById(R.id.badge);
                Global.setBadgeView(dynamicBadge, mProjectObject.un_read_activities_count);
            } else {
                Global.setBadgeView((BadgeView) item.findViewById(R.id.badge), 0);
            }
        }

        updateRedPoinitStyle();
    }

    void updateRedPoinitStyle() {
        final int[] buttons = new int[]{
                R.id.itemDocment,
                R.id.itemMerge,
        };

        final RedPointTip.Type[] types = new RedPointTip.Type[]{
                RedPointTip.Type.File320,
                RedPointTip.Type.Merge320
        };

        for (int i = 0; i < buttons.length; ++i) {
            setRedPointStyle(buttons[i], types[i]);
        }
    }

    //    private void initHeadHead(View view) {
//        ImageView projectIcon = (ImageView) view.findViewById(R.id.projectIcon);
//        iconfromNetwork(projectIcon, mProjectObject.icon, ImageLoadTool.optionsRounded2);
//
//        ((TextView) view.findViewById(R.id.projectName)).setText(mProjectObject.name);
//        view.findViewById(R.id.iconPrivate).setVisibility(View.VISIBLE);
//        ((TextView) view.findViewById(R.id.projectAuthor)).setText("      " + mProjectObject.owner_user_name);
//    }
}


text:
<?php

namespace Jackalope\NodeType;

use Jackalope\TestCase;

class NodeDefinitionTemplateTest extends TestCase
{
    /**
     * @covers \Jackalope\NodeType\NodeDefinitionTemplate::__construct
     */
    public function testCreateNodeDefinitionTemplateEmpty()
    {
        $ntm = $this->getNodeTypeManager();

        $ndt = $ntm->createNodeDefinitionTemplate();

        // is empty as defined by doc
        $this->assertNull($ndt->getName());
        $this->assertFalse($ndt->isAutoCreated());
        $this->assertFalse($ndt->isMandatory());
        $this->assertSame(\PHPCR\Version\OnParentVersionAction::COPY, $ndt->getOnParentVersion());
        $this->assertFalse($ndt->isProtected());
        $this->assertNull($ndt->getRequiredPrimaryTypeNames());
        $this->assertNull($ndt->getDefaultPrimaryTypeName());
        $this->assertFalse($ndt->allowsSameNameSiblings());
    }

}


text:
/*
 * Style twaks
 * --------------------------------------------------
 */
body {
	padding-top: 70px;
}
footer {
	padding-left: 15px;
	padding-right: 15px;
}
.content { min-height: 400px; }

/*
 * Off Canvas
 * --------------------------------------------------
 */
@media screen and (max-width: 768px) {

	.container {
		overflow-x: hidden;
	}

	.row-offcanvas {
		position: relative;
		-webkit-transition: all 0.25s ease-out;
		-moz-transition: all 0.25s ease-out;
		transition: all 0.25s ease-out;
	}

	.row-offcanvas-right
	.sidebar-offcanvas {
		right: -50%; /* 6 columns */
	}

	.row-offcanvas-left
	.sidebar-offcanvas {
		left: -50%; /* 6 columns */
	}

	.row-offcanvas-right.active {
		right: 50%; /* 6 columns */
	}

	.row-offcanvas-left.active {
		left: 50%; /* 6 columns */
	}

	.sidebar-offcanvas {
		position: absolute;
		top: 0;
		width: 50%; /* 6 columns */
	}
}

.sidebar-nav .nav:empty:after {
	display: block;
	color: rgba(0, 0, 0, 0.3);
	text-align: center;
}
.sidebar-nav.sidebar-users .nav:empty:after { content: "No users found"; }
.sidebar-nav.sidebar-chats .nav:empty:after { content: "No chats found"; }

.nav .nav-hidden:not(.active) { display: none; }

.users:empty:after,
.chats:empty:after {
	display: block;
	color: rgba(0, 0, 0, 0.3);
	text-align: center;
}
.users:empty:after { content: "No users found"; }
.chats:empty:after { content: "No chats found"; }

.chat-messages:empty:after {
	display: block;
	color: rgba(0, 0, 0, 0.3);
	text-align: center;
	content: "No messages found";
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var tf = require("@tensorflow/tfjs-core");
var classes_1 = require("../classes");
var ops_1 = require("../ops");
var extractImagePatches_1 = require("./extractImagePatches");
var MtcnnBox_1 = require("./MtcnnBox");
var ONet_1 = require("./ONet");
function stage3(img, inputBoxes, scoreThreshold, params, stats) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var ts, onetInputs, onetOuts, scoresTensor, scores, _a, _b, indices, filteredRegions, filteredBoxes, filteredScores, finalBoxes, finalScores, points, indicesNms;
        return tslib_1.__generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    ts = Date.now();
                    return [4 /*yield*/, extractImagePatches_1.extractImagePatches(img, inputBoxes, { width: 48, height: 48 })];
                case 1:
                    onetInputs = _c.sent();
                    stats.stage3_extractImagePatches = Date.now() - ts;
                    ts = Date.now();
                    onetOuts = onetInputs.map(function (onetInput) {
                        var out = ONet_1.ONet(onetInput, params);
                        onetInput.dispose();
                        return out;
                    });
                    stats.stage3_onet = Date.now() - ts;
                    scoresTensor = onetOuts.length > 1
                        ? tf.concat(onetOuts.map(function (out) { return out.scores; }))
                        : onetOuts[0].scores;
                    _b = (_a = Array).from;
                    return [4 /*yield*/, scoresTensor.data()];
                case 2:
                    scores = _b.apply(_a, [_c.sent()]);
                    scoresTensor.dispose();
                    indices = scores
                        .map(function (score, idx) { return ({ score: score, idx: idx }); })
                        .filter(function (c) { return c.score > scoreThreshold; })
                        .map(function (_a) {
                        var idx = _a.idx;
                        return idx;
                    });
                    filteredRegions = indices.map(function (idx) {
                        var regionsData = onetOuts[idx].regions.arraySync();
                        return new MtcnnBox_1.MtcnnBox(regionsData[0][0], regionsData[0][1], regionsData[0][2], regionsData[0][3]);
                    });
                    filteredBoxes = indices
                        .map(function (idx, i) { return inputBoxes[idx].calibrate(filteredRegions[i]); });
                    filteredScores = indices.map(function (idx) { return scores[idx]; });
                    finalBoxes = [];
                    finalScores = [];
                    points = [];
                    if (filteredBoxes.length > 0) {
                        ts = Date.now();
                        indicesNms = ops_1.nonMaxSuppression(filteredBoxes, filteredScores, 0.7, false);
                        stats.stage3_nms = Date.now() - ts;
                        finalBoxes = indicesNms.map(function (idx) { return filteredBoxes[idx]; });
                        finalScores = indicesNms.map(function (idx) { return filteredScores[idx]; });
                        points = indicesNms.map(function (idx, i) {
                            return Array(5).fill(0).map(function (_, ptIdx) {
                                var pointsData = onetOuts[idx].points.arraySync();
                                return new classes_1.Point(((pointsData[0][ptIdx] * (finalBoxes[i].width + 1)) + finalBoxes[i].left), ((pointsData[0][ptIdx + 5] * (finalBoxes[i].height + 1)) + finalBoxes[i].top));
                            });
                        });
                    }
                    onetOuts.forEach(function (t) {
                        t.regions.dispose();
                        t.scores.dispose();
                        t.points.dispose();
                    });
                    return [2 /*return*/, {
                            boxes: finalBoxes,
                            scores: finalScores,
                            points: points
                        }];
            }
        });
    });
}
exports.stage3 = stage3;
//# sourceMappingURL=stage3.js.map


text:
using System;
using System.Collections.Generic;
using TranscendenceChat.ServerClient.Entities.Ws.Events;
using TranscendenceChat.ServerClient.Entities.Ws.Requests;
using TranscendenceChat.ServerClient.Ws.Proxy;

namespace TranscendenceChat
{
    public class TypingService
    {
        private readonly MessagingService messagingService;
        private readonly Dictionary<long, Action<bool>> typingCallbacks = new Dictionary<long, Action<bool>>();

        public TypingService(MessagingService messagingService)
        {
            this.messagingService = messagingService;
            this.messagingService.IsTypingNotification += OnRemoteIsTyping;
        }

        public void SubscribeOnTyping(long conversationId, Action<bool> typingCallback)
        {
            typingCallbacks[conversationId] = typingCallback;
        }

        public void SendIsTyping(bool isTyping, Guid groupId, List<string> devices)
        {
            messagingService.SendIsTyping(new SendIsTypingRequest { Devices = devices, IsTyping = isTyping });
        }

        private void OnRemoteIsTyping(IsTypingNotification notification)
        {
            Notify(notification.SenderUserId, notification.IsTyping);
        }

        private void Notify(long userId, bool value)
        {
            Action<bool> action;
            if (typingCallbacks.TryGetValue(userId, out action))
            {
                action(value);
            }
        }
    }
}


text:
__author__ = "C. Sudama, Matthew Alhonte"
__license__ = "Apache License 2.0: http://www.apache.org/licenses/LICENSE-2.0"

import os
import unicodedata
import nltk
nltk.data.path.append(os.path.join(os.path.dirname(__file__), 'nltk-data'))
from nltk.tokenize import sent_tokenize

import re

import usaddress

from schema import RefLocation
from tagger import chunkAddresses
from pretokenize import transform

def showFailureReason(msg, address, components, verbose=False):
    if verbose:
        print 'Failed: %s' % msg
        print '\tAddress:\t\t%s' % address
        print '\tUS Address Components:\t%s\n' % components

def location_to_string(tree):
    txt = ' '.join([c[0] for c in tree]).replace(' ,', ',')

    # Handle chunked: 600 St Ann's Avenue Bronx, NY
    # (Location 600/CD Saint/NNP Ann/NNP 'S/POS Avenue/LU Bronx/NNP
    # ,/COMMA NY/STATE) by removing space before appostrophe
    return txt.replace(" '", "'")

def matchAddresses(text, verbose=False):
    locations = []
    # Replace periods where it is preceeded by a single
    # Letter
    #
    text = transform(text, verbose=verbose)

    sentences = sent_tokenize(text)
    for s in sentences:
        # s = transform(s, verbose=verbose)

        if verbose:
            print '\n\n'
            print '=' * 48
            print 'Sentence: %s\n' % s

        if verbose:
            print 'Stripping White Spaces:\n\t%s\n' % s
        s = re.sub('\s+', ' ', s)
        if len(s) < 10:
            if verbose:
                showFailureReason('Sentence too short', s, '--', verbose)
            continue
        locs = chunkAddresses(s, verbose)
        locations += locs

    return locations

def isValidAddress(ady, verbose=False):

    address = usaddress.parse(ady)
    if len(address) < 4:
        showFailureReason('Not Enough Terms', ady, address, verbose)
        return False

    if any([a[1] == 'Recipient' for a in address]):
        showFailureReason('Recipient', ady, address, verbose)
        return False

    if not any([a[1] == 'StreetName' for a in address]):
        dic = {}
        for v, k in address:
            dic[k] = '%s %s' % (dic.get(k, ''), v)

        if 'BuildingName' in dic and 'PlaceName' in dic and \
           'StateName' in dic:
            return True

        showFailureReason('StreetName', ady, address, verbose)
        return False

    if not any([a[1] == 'AddressNumber' for a in address]):
        showFailureReason('AddressNumber', ady, address, verbose)
        return False

    return True

def lookup_geo(g, ady, verbose=False):
    if verbose:
        print 'Lookup_geo:\n\t%s' % ady

    tags, _ = usaddress.tag(ady)

    addressNumber = tags.get('AddressNumber', '')
    streetName = [v for k, v in tags.items() if k.startswith('StreetName')]
    streetName = ' '.join(streetName)
    borough = tags.get('PlaceName', '').lower()

    if 'ny' in borough or 'manhattan' in borough:
        borough = 'manhattan'

    if 'queens' in borough:
        borough = 'queens'

    if 'brooklyn' in borough:
        borough = 'brooklyn'

    if 'bronx' in borough:
        borough = 'bronx'

    if 'manhattan' in borough:
        borough = 'manhattan'

    if 'staten island' in borough:
        borough = 'staten island'

    if verbose:
        print usaddress.tag(ady)
        print 'adNumber: %s\t\tstName: %s\t\tBorough:%s\n\n' % (addressNumber,
                                                                streetName,
                                                                borough)

    dic = g.address(addressNumber, streetName, borough)
    zipcode = dic.get('zipCode', '')
    streetAddress = '%s %s' % (dic.get('houseNumber', ''),
                               dic.get('firstStreetNameNormalized', ''))

    borough = dic.get('firstBoroughName', '')
    longitude = dic.get('longitude', '')
    latitude = dic.get('latitude', '')

    place = RefLocation(streetAddress, borough, zipcode, latitude, longitude)
    return place.schema_object()

def normalize_text(text):
    'Remove accents and other annotations from unicode characters'
    return unicodedata.normalize(
              'NFKD',
              text.decode('utf8', 'strict')).encode('ascii', 'ignore')

def parse(text, verbose=False):
    text = normalize_text(text)
    candidates = matchAddresses(text, verbose)
    candidates = [location_to_string(c) for c in candidates]

    # only candidates that end in NY
    rex = re.compile('(.+\s+NY)', re.IGNORECASE)
    candidates = [rex.match(c) for c in candidates]
    candidates = [c.group() for c in candidates if c is not None]
    return [c for c in candidates if isValidAddress(c, verbose)]

def parse_with_geo(text, g, verbose=False):
    plains = parse(text, verbose)
    return [lookup_geo(g, p, verbose) for p in plains]


text:
package de.elomagic.vaadin.addon.networkgraph;

import com.vaadin.annotations.JavaScript;
import com.vaadin.annotations.StyleSheet;
import com.vaadin.server.EncodeResult;
import com.vaadin.server.JsonCodec;
import com.vaadin.ui.AbstractJavaScriptComponent;
import com.vaadin.ui.Component;
import com.vaadin.ui.JavaScriptFunction;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static java.util.Arrays.asList;

/**
 * NetworkGraph is a visualization to display graphs and networks consisting of nodes and edges.
 *

 * The visualization is easy to use and supports custom shapes, styles, colors, sizes, images, and more.
 *

 * The graph visualization works smooth on any modern browser for up to a few thousand nodes and edges. To handle a larger amount of nodes, Graph has clustering support.
 *
 * @author Carsten Rambow
 */
@JavaScript({"js/vis.min.js", "js/networkgraph-connector.js"})
@StyleSheet({"css/vis.css", "css/networkgraph.css"})
public class NetworkGraph extends AbstractJavaScriptComponent {
    private final List<SelectListener> selectListener = new ArrayList<>();
    private final List<String> selectedItems = new ArrayList<>();

    public NetworkGraph() {
        super();
        setStyleName("networkgraph");
        addFunction("onSelectNodes", new JavaScriptFunction() {

            @Override
            public void call(final JSONArray arguments) throws JSONException {
                JSONArray array = arguments.getJSONArray(0);
                List<String> list = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    list.add(array.getString(i));
                }

                selectedItems.clear();
                selectedItems.addAll(list);

                fireSelectNodeEvent(list);
            }
        });
    }

    private static <T> List<T> collectArgs(T item, T[] items) {
        List<T> n = new ArrayList<>(asList(items));
        n.add(item);
        return n;
    }

    public Options getOptions() {
        return getState().options;
    }

    public void setOptions(Options options) {
        getState().options = options;
        markAsDirty();
    }

    /**
     * Redraw the graph.
     *

     * Useful when the layout of the webpage changed..
     */
    public void redraw() {
        callFunction("redraw");
    }

    /**
     * Clear the complete DataSet.
     */
    public void clear() {
        callFunction("clear");
    }

    public void addNodes(Node node, Node... nodes) {
        List<Node> n = collectArgs(node, nodes);
        getState().nodes.addAll(n);
        callFunction("addNodes", new Object[]{encodeArray(n)});
    }

    /**
     * Update a node or an array with nodes.
     *
     * @param nodes
     */
    public void updateNodes(final Node node, Node... nodes) {
        List<Node> n = collectArgs(node, nodes);
        getState().nodes.addAll(n);
        callFunction("updateNodes", new Object[]{encodeArray(n)});
    }

    public void removeNodes(final String[] nodeUIDs) {
        callFunction("removeNodes", (Object[]) nodeUIDs);
    }

    public void addEdges(final Edge edge, Edge... edges) {
        List<Edge> e = collectArgs(edge, edges);
        getState().edges.addAll(e);
        callFunction("addEdges", new Object[]{encodeArray(e)});
    }

    @Override
    protected NetworkGraphState getState() {
        return (NetworkGraphState) super.getState();
    }

    /**
     * Returns an array with the ids of the selected nodes.
     *

     * Returns an empty array if no nodes are selected. The selections are not ordered.
     *
     * @return List of id's
     */
    public List<String> getSelectedItems() {
        return selectedItems;
    }

    /**
     * Select nodes.
     *

     * nodes is an array with ids of nodes to be selected. The array selection can contain zero or multiple ids.
     *

     * Example usage: graph.setSelection([3, 5]); will select nodes with id 3 and 5.
     *
     * @param nodes
     */
    public void setSelection(final Node node, Node... nodes) {
        callFunction("setSelection", new Object[]{encodeArray(collectArgs(node, nodes))});
    }

    public void addSelectListener(final SelectListener listener) {
        if (selectListener.contains(listener)) {
            return;
        }

        selectListener.add(listener);
    }

    public void removeSelectListener(final SelectListener listener) {
        selectListener.remove(listener);
    }

    private void fireSelectNodeEvent(final List<String> nodesId) {
        SelectEvent event = new SelectEvent(this, nodesId);

        for (SelectListener listener : selectListener) {
            listener.nodeSelect(event);
        }
    }

    private Object[] encodeArray(final Collection<?> objects) {
        List<Object> result = new ArrayList<>();

        for (Object o : objects) {
            result.add(encodeObject(o));
        }

        return result.toArray(new Object[result.size()]);
    }

    private Object encodeObject(Object o) {
        try {
            EncodeResult result = JsonCodec.encode(o, null, o.getClass(), null);
            return result.getEncodedValue();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    public interface SelectListener {
        void nodeSelect(final SelectEvent event);
    }

    public class SelectEvent extends Component.Event {
        private final List<String> nodesId;

        public SelectEvent(final Component source, final List<String> nodesId) {
            super(source);

            this.nodesId = nodesId;
        }

        public List<String> getNodesId() {
            return nodesId;
        }

    }

}


text:
package org.radeox.test.macro.list;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class AllListTests extends TestCase
{
	public AllListTests(String name)
	{
		super(name);
	}

	public static Test suite()
	{
		TestSuite s = new TestSuite();
		s.addTestSuite(SimpleListTest.class);
		s.addTestSuite(ExampleListFormatterTest.class);
		s.addTestSuite(AtoZListFormatterTest.class);
		return s;
	}
}


text:
// Code generated by go-swagger; DO NOT EDIT.

package operations

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"fmt"
	"net/http"
	"strings"

	errors "github.com/go-openapi/errors"
	loads "github.com/go-openapi/loads"
	runtime "github.com/go-openapi/runtime"
	middleware "github.com/go-openapi/runtime/middleware"
	security "github.com/go-openapi/runtime/security"
	spec "github.com/go-openapi/spec"
	strfmt "github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"

	"github.com/jirwin/ipfs-archive/api/swagger/restapi/operations/ipfs"
)

// NewAPI creates a new  instance
func NewAPI(spec *loads.Document) *API {
	return &API{
		handlers:            make(map[string]map[string]http.Handler),
		formats:             strfmt.Default,
		defaultConsumes:     "application/json",
		defaultProduces:     "application/json",
		ServerShutdown:      func() {},
		spec:                spec,
		ServeError:          errors.ServeError,
		BasicAuthenticator:  security.BasicAuth,
		APIKeyAuthenticator: security.APIKeyAuth,
		BearerAuthenticator: security.BearerAuth,
		JSONConsumer:        runtime.JSONConsumer(),
		JSONProducer:        runtime.JSONProducer(),
		IPFSArchiveURLHandler: ipfs.ArchiveURLHandlerFunc(func(params ipfs.ArchiveURLParams) middleware.Responder {
			return middleware.NotImplemented("operation IPFSArchiveURL has not yet been implemented")
		}),
	}
}

/*API The web api for ipfs-archive */
type API struct {
	spec            *loads.Document
	context         *middleware.Context
	handlers        map[string]map[string]http.Handler
	formats         strfmt.Registry
	defaultConsumes string
	defaultProduces string
	Middleware      func(middleware.Builder) http.Handler

	// BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function.
	// It has a default implemention in the security package, however you can replace it for your particular usage.
	BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator
	// APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function.
	// It has a default implemention in the security package, however you can replace it for your particular usage.
	APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator
	// BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function.
	// It has a default implemention in the security package, however you can replace it for your particular usage.
	BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator

	// JSONConsumer registers a consumer for a "application/json" mime type
	JSONConsumer runtime.Consumer

	// JSONProducer registers a producer for a "application/json" mime type
	JSONProducer runtime.Producer

	// IPFSArchiveURLHandler sets the operation handler for the archive Url operation
	IPFSArchiveURLHandler ipfs.ArchiveURLHandler

	// ServeError is called when an error is received, there is a default handler
	// but you can set your own with this
	ServeError func(http.ResponseWriter, *http.Request, error)

	// ServerShutdown is called when the HTTP(S) server is shut down and done
	// handling all active connections and does not accept connections any more
	ServerShutdown func()

	// Custom command line argument groups with their descriptions
	CommandLineOptionsGroups []swag.CommandLineOptionsGroup

	// User defined logger function.
	Logger func(string, ...interface{})
}

// SetDefaultProduces sets the default produces media type
func (o *API) SetDefaultProduces(mediaType string) {
	o.defaultProduces = mediaType
}

// SetDefaultConsumes returns the default consumes media type
func (o *API) SetDefaultConsumes(mediaType string) {
	o.defaultConsumes = mediaType
}

// SetSpec sets a spec that will be served for the clients.
func (o *API) SetSpec(spec *loads.Document) {
	o.spec = spec
}

// DefaultProduces returns the default produces media type
func (o *API) DefaultProduces() string {
	return o.defaultProduces
}

// DefaultConsumes returns the default consumes media type
func (o *API) DefaultConsumes() string {
	return o.defaultConsumes
}

// Formats returns the registered string formats
func (o *API) Formats() strfmt.Registry {
	return o.formats
}

// RegisterFormat registers a custom format validator
func (o *API) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) {
	o.formats.Add(name, format, validator)
}

// Validate validates the registrations in the API
func (o *API) Validate() error {
	var unregistered []string

	if o.JSONConsumer == nil {
		unregistered = append(unregistered, "JSONConsumer")
	}

	if o.JSONProducer == nil {
		unregistered = append(unregistered, "JSONProducer")
	}

	if o.IPFSArchiveURLHandler == nil {
		unregistered = append(unregistered, "ipfs.ArchiveURLHandler")
	}

	if len(unregistered) > 0 {
		return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", "))
	}

	return nil
}

// ServeErrorFor gets a error handler for a given operation id
func (o *API) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) {
	return o.ServeError
}

// AuthenticatorsFor gets the authenticators for the specified security schemes
func (o *API) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator {

	return nil

}

// Authorizer returns the registered authorizer
func (o *API) Authorizer() runtime.Authorizer {

	return nil

}

// ConsumersFor gets the consumers for the specified media types
func (o *API) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer {

	result := make(map[string]runtime.Consumer)
	for _, mt := range mediaTypes {
		switch mt {

		case "application/json":
			result["application/json"] = o.JSONConsumer

		}
	}
	return result

}

// ProducersFor gets the producers for the specified media types
func (o *API) ProducersFor(mediaTypes []string) map[string]runtime.Producer {

	result := make(map[string]runtime.Producer)
	for _, mt := range mediaTypes {
		switch mt {

		case "application/json":
			result["application/json"] = o.JSONProducer

		}
	}
	return result

}

// HandlerFor gets a http.Handler for the provided operation method and path
func (o *API) HandlerFor(method, path string) (http.Handler, bool) {
	if o.handlers == nil {
		return nil, false
	}
	um := strings.ToUpper(method)
	if _, ok := o.handlers[um]; !ok {
		return nil, false
	}
	if path == "/" {
		path = ""
	}
	h, ok := o.handlers[um][path]
	return h, ok
}

// Context returns the middleware context for the  API
func (o *API) Context() *middleware.Context {
	if o.context == nil {
		o.context = middleware.NewRoutableContext(o.spec, o, nil)
	}

	return o.context
}

func (o *API) initHandlerCache() {
	o.Context() // don't care about the result, just that the initialization happened

	if o.handlers == nil {
		o.handlers = make(map[string]map[string]http.Handler)
	}

	if o.handlers["POST"] == nil {
		o.handlers["POST"] = make(map[string]http.Handler)
	}
	o.handlers["POST"]["/archive"] = ipfs.NewArchiveURL(o.context, o.IPFSArchiveURLHandler)

}

// Serve creates a http handler to serve the API over HTTP
// can be used directly in http.ListenAndServe(":8000", api.Serve(nil))
func (o *API) Serve(builder middleware.Builder) http.Handler {
	o.Init()

	if o.Middleware != nil {
		return o.Middleware(builder)
	}
	return o.context.APIHandler(builder)
}

// Init allows you to just initialize the handler cache, you can then recompose the middelware as you see fit
func (o *API) Init() {
	if len(o.handlers) == 0 {
		o.initHandlerCache()
	}
}


text:
package org.springframework.cloud.dataflow.rest.resource;

import org.springframework.batch.core.StepExecution;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.util.Assert;

/**
 * @author Glenn Renfro
 */
public class StepExecutionResource extends ResourceSupport {

	private final Long jobExecutionId;

	private final StepExecution stepExecution;

	private final String stepType;

	/**
	 * Create a new StepExecutionResource
	 * @param jobExecutionId the job execution id, must not be null
	 * @param stepExecution  the step execution, must not be null
	 * @param stepType the step type
	 */
	public StepExecutionResource(
			Long jobExecutionId,
			StepExecution stepExecution,
			String stepType) {

		Assert.notNull(jobExecutionId, "jobExecutionId must not be null.");
		Assert.notNull(stepExecution, "stepExecution must not be null.");

		this.stepExecution = stepExecution;
		this.jobExecutionId = jobExecutionId;
		this.stepType = stepType;
	}

	/**
	 * Default constructor to be used by Jackson.
	 */
	private StepExecutionResource() {
		this.stepExecution = null;
		this.jobExecutionId = null;
		this.stepType = null;
	}

	/**
	 * @return The jobExecutionId, which will never be null
	 */
	public Long getJobExecutionId() {
		return this.jobExecutionId;
	}

	/**
	 * @return The stepExecution, which will never be null
	 */
	public StepExecution getStepExecution() {
		return stepExecution;
	}

	public String getStepType() {
		return this.stepType;
	}

	public static class Page extends PagedResources<StepExecutionResource> {}

}


text:
package com.google.api.ads.adwords.jaxws.v201502.cm;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Operation used to create or mutate a Feed.
 *
 *
 *
Java class for FeedOperation complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="FeedOperation">
 *   <complexContent>
 *     <extension base="{https://adwords.google.com/api/adwords/cm/v201502}Operation">
 *       <sequence>
 *         <element name="operand" type="{https://adwords.google.com/api/adwords/cm/v201502}Feed" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FeedOperation", propOrder = {
    "operand"
})
public class FeedOperation
    extends Operation
{

    protected Feed operand;

    /**
     * Gets the value of the operand property.
     *
     * @return
     *     possible object is
     *     {@link Feed }
     *
     */
    public Feed getOperand() {
        return operand;
    }

    /**
     * Sets the value of the operand property.
     *
     * @param value
     *     allowed object is
     *     {@link Feed }
     *
     */
    public void setOperand(Feed value) {
        this.operand = value;
    }

}


text:
package nodescala

import com.sun.net.httpserver._
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global
import scala.async.Async.{async, await}
import scala.collection._
import scala.collection.JavaConversions._
import java.util.concurrent.{Executor, ThreadPoolExecutor, TimeUnit, LinkedBlockingQueue}
import com.sun.net.httpserver.{HttpExchange, HttpHandler, HttpServer}
import java.net.InetSocketAddress

/** Contains utilities common to the NodeScala© framework.
 */
trait NodeScala {
  import NodeScala._

  def port: Int

  def createListener(relativePath: String): Listener

  /** Uses the response object to respond to the write the response back.
   *  The response should be written back in parts, and the method should
   *  occasionally check that server was not stopped, otherwise a very long
   *  response may take very long to finish.
   *
   *  @param exchange     the exchange used to write the response back
   *  @param token        the cancellation token
   *  @param body         the response to write back
   */
  private def respond(exchange: Exchange, token: CancellationToken, response: Response): Unit = {
    while(response.hasNext && !token.isCancelled){
      exchange.write(response.next())
    }

    exchange.close()
  }

  /** A server:
   *  1) creates and starts an http listener
   *  2) creates a cancellation token (hint: use one of the `Future` companion methods)
   *  3) as long as the token is not cancelled and there is a request from the http listener,
   *     asynchronously process that request using the `respond` method
   *
   *  @param relativePath   a relative path on which to start listening
   *  @param handler        a function mapping a request to a response
   *  @return               a subscription that can stop the server and all its asynchronous operations *entirely*
   */
  def start(relativePath: String)(handler: Request => Response): Subscription = {
    val listener = createListener(relativePath)
    val listenerSubscription = listener.start()

    Future.run(){ct =>
      InnerStart(ct, listener, handler)
      .continue(_ => listenerSubscription.unsubscribe())
    }
  }

  private def InnerStart(ct: CancellationToken, listener: Listener, handler: Request => Response): Future[Unit] = async{
    while (ct.nonCancelled){
      val req = await {listener.nextRequest()}
      val resp = handler(req._1)
      respond(req._2, ct, resp)
    }
  }
}

object NodeScala {

  /** A request is a multimap of headers, where each header is a key-value pair of strings.
   */
  type Request = Map[String, List[String]]

  /** A response consists of a potentially long string (e.g. a data file).
   *  To be able to process this string in parts, the response is encoded
   *  as an iterator over a subsequences of the response string.
   */
  type Response = Iterator[String]

  /** Used to write the response to the request.
   */
  trait Exchange {
    /** Writes to the output stream of the exchange.
     */
    def write(s: String): Unit

    /** Communicates that the response has ended and that there
     *  will be no further writes.
     */
    def close(): Unit

    def request: Request

  }

  object Exchange {
    def apply(exchange: HttpExchange) = new Exchange {
      val os = exchange.getResponseBody()
      exchange.sendResponseHeaders(200, 0L)

      def write(s: String) = os.write(s.getBytes)

      def close() = os.close()

      def request: Request = {
        val headers = for ((k, vs) <- exchange.getRequestHeaders) yield (k, vs.toList)
        immutable.Map() ++ headers
      }
    }
  }

  trait Listener {
    def port: Int

    def relativePath: String

    def start(): Subscription

    def createContext(handler: Exchange => Unit): Unit

    def removeContext(): Unit

    /** This Method:
     *  1) constructs an uncompleted promise
     *  2) installs an asynchronous `HttpHandler` to the `server`
     *     that deregisters itself
     *     and then completes the promise with a request when `handle` method is invoked
     *  3) returns the future with the request
     *
     *  @return                the promise holding the pair of a request and an exchange object
     */
    def nextRequest(): Future[(Request, Exchange)] = {
      val p = Promise[(Request, Exchange)]()

      createContext(xchg => {
        val req = xchg.request
        removeContext()
        p.success((req, xchg))
      })

      p.future
    }
  }

  object Listener {
    class Default(val port: Int, val relativePath: String) extends Listener {
      private val s = HttpServer.create(new InetSocketAddress(port), 0)
      private val executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue)
      s.setExecutor(executor)

      def start() = {
        s.start()
        new Subscription {
          def unsubscribe() = {
            s.stop(0)
            executor.shutdown()
          }
        }
      }

      def createContext(handler: Exchange => Unit) = s.createContext(relativePath, new HttpHandler {
        def handle(httpxchg: HttpExchange) = handler(Exchange(httpxchg))
      })

      def removeContext() = s.removeContext(relativePath)
    }
  }

  /** The standard server implementation.
   */
  class Default(val port: Int) extends NodeScala {
    def createListener(relativePath: String) = new Listener.Default(port, relativePath)
  }

}


text:
wget https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css
wget https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css

# https://www.bootstrapcdn.com/fontawesome/
wget https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css

# https://cdnjs.com/libraries/dc
wget https://cdnjs.cloudflare.com/ajax/libs/dc/1.7.5/dc.min.css
# wget https://dc-js.github.io/dc.js/css/dc.css


text:
package org.pantsbuild.testing.protolib;

import com.squareup.testing.protolib.External;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class ProtolibExternalTest {

  @Test
  public void testApp() {
    External.ExternalMessage message = External.ExternalMessage.newBuilder().setMessageType(1)
        .setMessageContent("Hello World!").build();
    assertEquals(1, message.getMessageType());
    assertEquals("Hello World!", message.getMessageContent());
  }
}