text:
import sys, pysam, gzip, pdb, argparse, array
#from pympler import asizeof

#### Class to hold the data for a single SNP
class SNP:
    def __init__(self,snp_line):
        snp_split=snp_line.strip().split()
        self.pos=int(snp_split[0])-1
        self.alleles=[snp_split[1],snp_split[2]]
        self.ptype="snp"
        self.max_len=0
        for i in range(len(self.alleles)):
            if self.alleles[i]=="-":
                self.alleles[i]=""
                self.ptype="indel"
            elif len(self.alleles[i])>self.max_len:
                self.max_len=len(self.alleles[i])
        if self.max_len>1:
            self.ptype="indel"

        haplo_chars=snp_split[5:]
        haplos=array.array('B',[0])*len(haplo_chars)

    def add_allele(self,new_alleles):
        for new_allele in new_alleles:
            if new_allele=="-":
                self.ptype="indel"
                new_allele=""
            if not (new_allele in self.alleles):
                self.alleles.append(new_allele)
                if len(new_allele)>self.max_len:
                    self.max_len=len(new_allele)
        if self.max_len>1:
            self.ptype="indel"

    def shift_indel(self):
        self.pos+=1
        self.max_len-=1
        i=0
        while i < len(self.alleles):
            if len(self.alleles)<=1:
                self.alleles.pop(i)
            else:
                self.alleles[i]=self.alleles[i][1:]
                i+=1
        self.alleles.append("")

#### Class to keep track of all the information read in from the bamfile/snpfile
class Bam_scanner:
    # Constructor: opens files, creates initial table
    def __init__(self,is_paired_end,max_window,file_name,keep_file_name,remap_name,remap_num_name,fastq_names,snp_dir):
        self.is_paired_end=is_paired_end

        ### Read in all input files and create output files
        self.snp_dir=snp_dir
        self.bamfile=pysam.Samfile(file_name,"rb")
        self.keep_bam=pysam.Samfile(keep_file_name,"wb",template=self.bamfile)
        self.remap_bam=pysam.Samfile(remap_name,"wb",template=self.bamfile)
        self.remap_num_file=gzip.open(remap_num_name,"w")
        self.fastqs=[gzip.open(fqn,"w") for fqn in fastq_names]
        try:
            self.cur_read=self.bamfile.next()
        except:
            sys.stderr.write("No lines available for input")
            return()
        self.end_of_file=False

        self.remap_num=1
        self.ref_match=0
        self.alt_match=0
        self.no_match=0
        self.toss=0
        self.nosnp=0
        self.remap=0
        self.tot=0
        self.printstats = True

        self.num_reads=0

        self.pos=self.cur_read.pos
        self.chr_num=self.cur_read.tid
        self.chr_name=self.bamfile.getrname(self.cur_read.tid)
        self.max_window=max_window

        self.num_reads=0

        ### Initialize the read tracking tables
        self.read_table=[[] for x in range(self.max_window)]

        ### Initialize the SNP and indel tracking tables
        self.switch_chr()

        ### fill all tables
        self.fill_table()

    # fills the table of reads starting from the current position and extending for the next <max_window> base pairs
    def fill_table(self):
        if self.end_of_file:
            return()
        if self.num_reads==0:
            self.pos=self.cur_read.pos
            self.init_snp_table()
            #self.num_reads+=1000
        while self.cur_read.tid == self.chr_num and self.cur_read.pos<(self.pos+self.max_window):
            self.num_reads+=1
            self.read_table[self.cur_read.pos % self.max_window].append(self.cur_read)
            try:
                self.cur_read=self.bamfile.next()
            except:
                self.empty_table()
                self.end_of_file=True
                return()

        if self.cur_read.tid != self.chr_num:
            self.empty_table()
            self.chr_num=self.cur_read.tid
            try:
                self.chr_name=self.bamfile.getrname(self.chr_num)
            except:
                sys.stderr.write("Problem with tid: "+str(self.chr_num)+"\n")
                self.skip_chr()
            self.pos=self.cur_read.pos
            self.switch_chr()
            self.fill_table()

    # Switches to looking for SNPs on the next chromosome
    def switch_chr(self):
        chr_match=False
        while not chr_match and not self.end_of_file:
            try:
                self.snpfile = gzip.open("%s/%s.snps.txt.gz"%(self.snp_dir,self.chr_name))
                sys.stderr.write("Starting on chromosome "+self.chr_name+"\n")
                chr_match=True
            except:
                sys.stderr.write("SNP file for chromosome "+self.chr_name+" is not found. Skipping these reads.\n")
                self.skip_chr()

        self.end_of_snp_file=False
        self.get_next_snp()

    # Initializes the SNP table
    def init_snp_table(self):
        # create an empty SNP table
        self.num_snps=0
        self.indel_dict={}
        self.snp_table=[0 for x in range(self.max_window)]
        self.indel_table=[[] for x in range(self.max_window)]
        # skips SNPs that are upstream of the current read
        while not self.end_of_snp_file and self.cur_snp.pos<self.pos:
            self.get_next_snp()

        # adds SNPs downstream of the current read and within the current window
        while not self.end_of_snp_file and self.cur_snp.pos<self.pos+self.max_window:
            if self.cur_snp.ptype=="snp":
                self.add_snp()
            else:
                self.add_indel()
            self.get_next_snp()

        #sys.stderr.write(str(self.num_snps)+"\n")

    def add_snp(self):
        cur_pos=self.cur_snp.pos % self.max_window
        if self.snp_table[cur_pos]==0:
            self.num_snps+=1
            self.snp_table[cur_pos]=self.cur_snp
        elif isinstance(self.snp_table[cur_pos],SNP):
            self.snp_table[cur_pos].add_allele(self.cur_snp.alleles)

    def add_indel(self):
        position=self.cur_snp.pos
        if self.indel_dict.has_key(position):
            start=self.indel_dict[position].max_len
            self.indel_dict[position].add_allele(self.cur_snp.alleles)
        else:
            self.indel_dict[position]=self.cur_snp
            start=0
        end=self.indel_dict[position].max_len
        i=start
        while i<end and self.cur_snp.pos+i<self.pos+self.max_window:
            self.indel_table[(self.cur_snp.pos+i)%self.max_window].append(position)
            i+=1

    #to read in next SNP or signals end of file
    def get_next_snp(self):
        snp_line=self.snpfile.readline()
        if snp_line:
            self.cur_snp=SNP(snp_line)
        else:
            self.end_of_snp_file=True

    # Skips all of the reads coming from this chromosome and moves on to the next
    # Used if the SNP file can't be located
    def skip_chr(self):
        while self.cur_read.tid == self.chr_num:
            try:
                self.cur_read=self.bamfile.next()
            except:
                self.empty_table()
                self.end_of_file=True
                return()

        self.chr_num=self.cur_read.tid
        try:
            self.chr_name=self.bamfile.getrname(self.chr_num)
        except:
            sys.stderr.write("Problem with tid: "+str(self.chr_num)+"\n")
            self.skip_chr()

    # Processes all reads that map to the current position and removes them from the read table
    # Treats reads as single-end
    def empty_slot_single(self):
        cur_slot=self.pos % self.max_window
        while len(self.read_table[cur_slot])>0:
            self.tot+=1
            read=self.read_table[cur_slot].pop()
            self.num_reads-=1
            seqs=self.check_for_snps(read,0)
            num_seqs=len(seqs)
            if num_seqs==0 or num_seqs>10:
                continue
            if num_seqs==1:
                self.keep_bam.write(read)
            else:
                self.remap_num_file.write("%i\n"%(num_seqs-1))
                self.remap_num_file.flush()
                self.remap_bam.write(read)
                for seq in seqs[1:]:
                    loc_line="%i:%s:%i:%i" % (self.remap_num,self.chr_name,read.pos,num_seqs-1)
                    self.fastqs[0].write("@%s\n%s\n+%s\n%s\n"%(loc_line,seq,loc_line,read.qual))
                self.remap_num+=1
        #if self.printstats:
        #    sys.stderr.write(str(self.tot)+" "+str(self.nosnp)+" "+str(self.remap)+" "+str(self.toss)+"\n")
        #    self.printstats = False
        #sys.stderr.write(str(self.ref_match)+" "+str(self.alt_match)+" "+str(self.no_match)+"\n")
        self.pos+=1
        self.shift_SNP_table()

    # Processes all reads that map to the current position and removes them from the read table
    # Treats reads as paired-end
    def empty_slot_paired(self):
        cur_slot=self.pos % self.max_window
        while len(self.read_table[cur_slot])>0:  #While there are reads in this slot
            read=self.read_table[self.pos % self.max_window].pop() #Pop the first read in the slot
            self.num_reads-=1
            pair_chr_num=read.rnext #Figure out the matching read position
            pair_pos=read.mpos
            if pair_chr_num != self.chr_num or pair_pos-self.pos > self.max_window:
                continue
            pair_slot=pair_pos % self.max_window # Find the slot the matching read in
            for indx in range(len(self.read_table[pair_slot])):
                #if self.read_table[pair_slot][indx].qname==read.qname:
                if self.read_table[pair_slot][indx].qname.split(":")[-1]==read.qname.split(":")[-1]: #for testing purposes
                    pair_read=self.read_table[pair_slot].pop(indx)
                    self.num_reads-=1
                    seq1s=self.check_for_snps(read,0)
                    seq2s=self.check_for_snps(pair_read,read.mpos-read.pos)
                    num_seqs=len(seq1s)*len(seq2s)
                    if num_seqs==0 or num_seqs>32:
                        break
                    if num_seqs==1:
                        self.keep_bam.write(read)
                        self.keep_bam.write(pair_read)
                    else:
                        self.remap_bam.write(read)
                        self.remap_bam.write(pair_read)
                        self.remap_num_file.write("%i\n"% (2*(num_seqs-1)))
                        first=True
                        for seq1 in seq1s:
                            for seq2 in seq2s:
                                if not first:
                                    left_pos=min(read.pos,pair_read.pos)
                                    right_pos=max(read.pos,pair_read.pos)
                                    loc_line="%i:%s:%i:%i:%i" % (self.remap_num,self.chr_name,left_pos,right_pos,num_seqs-1)
                                    self.fastqs[0].write("@%s\n%s\n+%s\n%s\n"%(loc_line,seq1,loc_line,read.qual))
                                    self.fastqs[1].write("@%s\n%s\n+%s\n%s\n"%(loc_line,self.reverse_complement(seq2),loc_line,pair_read.qual))
                                first=False
                        self.remap_num+=1
                    break # stop searching for the pair since it was found

        #sys.stderr.write(str(self.ref_match)+" "+str(self.alt_match)+" "+str(self.no_match)+" "+str(self.toss)+"\n")
        self.pos+=1
        self.shift_SNP_table()

    # Checks a single aligned read for overlapping SNPs and created alternative sequences for remapping
    def check_for_snps(self,read,start_dist):
        indx=read.pos % self.max_window
        p=0
        num_snps=0
        seg_len=start_dist
        seqs=[read.seq]
        if start_dist>0:
            has_junc=False
        for cigar in read.cigar:
            seg_len+=cigar[1]
            if seg_len>self.max_window:
                sys.stderr.write("Segment distance (from read pair and junction separation) is too large. A read has been thrown out. Consider increasing the max window size.\n")
                return([])
            if cigar[0] == 4: #if CIGAR indicates a soft-clipping
                p=p+cigar[1]
            elif cigar[0] == 0: #if CIGAR indicates a match alignment to the reference genome
                for i in range(cigar[1]):
                    if len(self.indel_table[indx])==0:
                        snp=self.snp_table[indx]
                        if snp!=0:
                            num_snps+=1
                            if num_snps>10: #If there are more than 10 snps overlapping, throw out the read to prevent memory blow-up
                                return([])
                            init_seqs=list(seqs)
                            for seq in init_seqs:
                                matches=0
                                #if seq[p] not in snp.alleles:
                                #    sys.stderr.write(str(start_dist)+" "+seq[p]+"  "+str(snp.alleles)+"\n")
                                for geno in snp.alleles:
                                    if seq[p]==geno:
                                        matches+=1
                                        for alt_geno in snp.alleles:
                                            if not alt_geno == geno:
                                                new_seq=seq[:p]+alt_geno+seq[p+1:]
                                                seqs.append(new_seq)
                                if matches==0:
                                    self.no_match+=1
                                else:
                                    self.ref_match+=1
                    else:  #it's an indel, throw it out
                        self.toss+=1
                        return([])
                    indx=(indx+1) % self.max_window
                    p+=1
            elif cigar[0]==3:   # if it is skipped in the reference genome (splice junction)
                indx=(indx+cigar[1]) % self.max_window
                has_junc=True
            else: #if there is a non-N/M in the read CIGAR, throw out the read
                self.toss+=1
                return([])

        if len(seqs)==1:
            self.nosnp+=1
        else:
            self.remap+=1
        return seqs
    # Shifts the SNP table over one position and makes sure that indels are not lost
    def shift_SNP_table(self):
        ### Current slot to fill is the position + max_window - 1
        cur_slot=(self.pos-1)%self.max_window

        ### Delete indels that are no longer used (if they ended at the previous position)
        for indel_pos in self.indel_table[cur_slot]:
            #sys.stderr.write(str(indel_pos+self.indel_dict[indel_pos].max_len-1)+"\t"+str(self.pos-1)+"\t"+str(self.indel_dict[indel_pos].max_len)+"\n")
            if indel_pos+self.indel_dict[indel_pos].max_len-1==self.pos-1:
                del self.indel_dict[indel_pos]

        self.indel_table[cur_slot]=[]
        ### Carry over indels from the previous slot
        for indel_pos in self.indel_table[cur_slot-1]:
            if indel_pos+self.indel_dict[indel_pos].max_len-1>=self.pos+self.max_window-1:
                self.indel_table[cur_slot].append(indel_pos)

        if self.snp_table[cur_slot]!=0:
            self.num_snps-=1
        self.snp_table[cur_slot]=0

        #### See if there is a SNP overlapping the current spot
        while not self.end_of_snp_file and self.pos+self.max_window-1 > self.cur_snp.pos:
            sys.stderr.write(str(self.num_snps)+" "+str(self.pos)+" "+str(self.cur_snp.pos)+" !!!\n")
            sys.stderr.write("SNP out of order has been skipped\n")
            self.get_next_snp()

        while not self.end_of_snp_file and self.cur_snp.pos==self.pos+self.max_window-1:
            if self.cur_snp.ptype=="snp":
                self.add_snp()
            else:
                self.add_indel()
                if not self.cur_snp.pos in self.indel_table[cur_slot]:
                    self.indel_table[cur_slot].append(cur_snp.pos)
            self.get_next_snp()

    # Completely empties the read_table by repeatedly calling empty_slot function
    def empty_table(self):
        end_pos=self.pos+self.max_window
        while self.pos < end_pos:
            if self.is_paired_end:
                self.empty_slot_paired()
            else:
                self.empty_slot_single()

    def complement(self,letter):
        if letter=='A':
            return('T')
        elif letter=='T':
            return('A')
        elif letter=='C':
            return('G')
        elif letter=='G':
            return('C')
        else:
            return(letter)

    def reverse_complement(self,read):
        reverse=""
        for letter in read:
            reverse=self.complement(letter)+reverse
        return reverse

def main():
    parser=argparse.ArgumentParser()
    parser.add_argument("-p", action='store_true', dest='is_paired_end', default=False)
    parser.add_argument("-m", action='store', dest='max_window', type=int, default=100000)
    parser.add_argument("infile", action='store')
    parser.add_argument("snp_dir", action='store')

    options=parser.parse_args()
    infile=options.infile
    snp_dir=options.snp_dir
    name_split=infile.split(".")

    if len(name_split)>1:
        pref=".".join(name_split[:-1])
    else:
        pref=name_split[0]

    pysam.sort(infile,pref+".sort")

    sort_file_name=pref+".sort.bam"
    keep_file_name=pref+".keep.bam"
    remap_name=pref+".to.remap.bam"
    remap_num_name=pref+".to.remap.num.gz"

    if options.is_paired_end:
        fastq_names=[pref+".remap.fq1.gz",pref+".remap.fq2.gz"]
    else:
        fastq_names=[pref+".remap.fq.gz"]

    bam_data=Bam_scanner(options.is_paired_end,options.max_window,sort_file_name,keep_file_name,remap_name,remap_num_name,fastq_names,snp_dir)
    bam_data.fill_table()
    #i=0
    while not bam_data.end_of_file:
        #i+=1
        #if i>50000:
            #sys.stderr.write(str(asizeof.asizeof(bam_data))+"\t"+str(asizeof.asizeof(bam_data.snp_table))+"\t"+str(asizeof.asizeof(bam_data.read_table))+"\t"+str(bam_data.num_reads)+"\t"+str(bam_data.num_snps)+"\n")
            #sys.stderr.write(str(asizeof.asizeof(bam_data))+"\t"+str(bam_data.num_reads)+"\t"+str(bam_data.num_snps)+"\t"+str(len(bam_data.indel_dict))+"\n")
            #i=0
        if options.is_paired_end:
            bam_data.empty_slot_paired()
        else:
            bam_data.empty_slot_single()
        bam_data.fill_table()

    sys.stderr.write("Finished!\n")

main()


text:
from a10sdk.common.A10BaseClass import A10BaseClass

class Oper(A10BaseClass):

    """This class does not support CRUD Operations please use parent.

    :param firmware_version: {"type": "string", "format": "string"}
    :param hw_code: {"type": "string", "format": "string"}
    :param hd_sec: {"type": "string", "format": "string"}
    :param hd_pri: {"type": "string", "format": "string"}
    :param copyright: {"type": "string", "format": "string"}
    :param sw_version: {"type": "string", "format": "string"}
    :param boot_from: {"type": "string", "format": "string"}
    :param plat_features: {"type": "string", "format": "string"}
    :param hw_platform: {"type": "string", "format": "string"}
    :param serial_number: {"type": "string", "format": "string"}
    :param up_time: {"type": "string", "format": "string"}
    :param current_time: {"type": "string", "format": "string"}
    :param aflex_version: {"type": "string", "format": "string"}
    :param last_config_saved_time: {"type": "string", "format": "string"}
    :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`

    """
    def __init__(self, **kwargs):
        self.ERROR_MSG = ""

        self.b_key = "oper"
        self.DeviceProxy = ""
        self.firmware_version = ""
        self.hw_code = ""
        self.hd_sec = ""
        self.hd_pri = ""
        self.A10WW_copyright = ""
        self.sw_version = ""
        self.boot_from = ""
        self.plat_features = ""
        self.hw_platform = ""
        self.serial_number = ""
        self.up_time = ""
        self.current_time = ""
        self.aflex_version = ""
        self.last_config_saved_time = ""

        for keys, value in kwargs.items():
            setattr(self,keys, value)

class Version(A10BaseClass):

    """Class Description::
    Operational Status for the object version.

    Class version supports CRUD Operations and inherits from `common/A10BaseClass`.
    This class is the `"PARENT"` class for this module.`

    :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`

    URL for this object::
    `https://<Hostname|Ip address>//axapi/v3/version/oper`.

    """
    def __init__(self, **kwargs):
        self.ERROR_MSG = ""
        self.required=[]
        self.b_key = "version"
        self.a10_url="/axapi/v3/version/oper"
        self.DeviceProxy = ""
        self.oper = {}

        for keys, value in kwargs.items():
            setattr(self,keys, value)

redpajama_set_name: RedPajamaGithub


text:
/* ------------------------------------------------------------------------------
*
*  # Modal dialogs and extensions
*
*  Specific JS code additions for components_modals.html page
*
*  Version: 1.1
*  Latest update: Jul 5, 2016
*
* ---------------------------------------------------------------------------- */

$(function() {

    // Basic modals
    // ------------------------------

    // Load remote content
    $('#modal_remote').on('show.bs.modal', function() {
        $(this).find('.modal-body').load('assets/demo_data/wizard/education.html', function() {

            // Init Select2 when loaded
            $('.select').select2({
                minimumResultsForSearch: Infinity
            });
        });
    });

    // Bootbox extension
    // ------------------------------

    // Alert dialog
    $('#alert').on('click', function() {
        bootbox.alert("Native alert dialog has been replaced with Bootbox alert box.");
    });

    // Confirmation dialog
    $('#confirm').on('click', function() {
        bootbox.confirm("Native confirm dialog has been replaced with Bootbox confirm box.", function(result) {
            bootbox.alert("Confirm result: " + result)
        });
    });

    // Prompt dialog
    $('#prompt').on('click', function() {
        bootbox.prompt("Please enter your name", function(result) {
            if (result === null) {
                bootbox.alert("Prompt dismissed");
            } else {
                bootbox.alert("Hi "+result+"");
            }
        });
    });

    // Prompt dialog with default value
    $('#prompt_value').on('click', function() {
        bootbox.prompt({
            title: "What is your real name?",
            value: "Eugene Kopyov",
            callback: function(result) {
                if (result === null) {
                    bootbox.alert("Prompt dismissed");
                }
                else {
                    bootbox.alert("Hi, "+result+"");
                }
            }
        });
    });

    // Custom bootbox dialog
    $('#bootbox_custom').on('click', function() {
        bootbox.dialog({
            message: "I am a custom dialog",
            title: "Custom title",
            buttons: {
                success: {
                    label: "Success!",
                    className: "btn-success",
                    callback: function() {
                        bootbox.alert("great success");
                    }
                },
                danger: {
                    label: "Danger!",
                    className: "btn-danger",
                    callback: function() {
                        bootbox.alert("uh oh, look out!");
                    }
                },
                main: {
                    label: "Click ME!",
                    className: "btn-primary",
                    callback: function() {
                        bootbox.alert("Primary button");
                    }
                }
            }
        });
    });

    // Custom bootbox dialog with form
    $('#bootbox_form').on('click', function() {
        bootbox.dialog({
                title: "This is a form in a modal.",
                message: '
  ' +
                    '
' +
                        '<form class="form-horizontal">' +
                            '
' +
                                'Name' +
                                '
' +
                                    '<input id="name" name="name" type="text" placeholder="Your name" class="form-control">' +
                                    'Here goes your name' +
                                '
' +
                            '
' +
                            '
' +
                                'How awesome is this?' +
                                '
' +
                                    '
' +
                                        '' +
                                            '<input type="radio" name="awesomeness" id="awesomeness-0" value="Really awesome" checked="checked">' +
                                            'Really awesomeness' +
                                        '' +
                                    '
' +
                                    '
' +
                                        '' +
                                            '<input type="radio" name="awesomeness" id="awesomeness-1" value="Super awesome">' +
                                            'Super awesome' +
                                        '' +
                                    '
' +
                                '
' +
                            '
' +
                        '</form>' +
                    '
' +
                    '
',
                buttons: {
                    success: {
                        label: "Save",
                        className: "btn-success",
                        callback: function () {
                            var name = $('#name').val();
                            var answer = $("input[name='awesomeness']:checked").val()
                            bootbox.alert("Hello " + name + ". You've chosen " + answer + "");
                        }
                    }
                }
            }
        );
    });

    // Modal callbacks
    // ------------------------------

    // onShow callback
    $('#onshow_callback').on('click', function() {
        $('#modal_default').on('show.bs.modal', function() {
            alert('onShow callback fired.')
        });
    });

    // onShown callback
    $('#onshown_callback').on('click', function() {
        $('#modal_form_vertical').on('shown.bs.modal', function() {
            alert('onShown callback fired.')
        });
    });

    // onHide callback
    $('#onhide_callback').on('click', function() {
        $('#modal_subtitle').on('hide.bs.modal', function() {
            alert('onHide callback fired.')
        });
    });

    // onHidden callback
    $('#onhidden_callback').on('click', function() {
        $('#modal_theme_success').on('hidden.bs.modal', function() {
            alert('onHidden callback fired.')
        });
    });

    // Sweet Alert extension
    // ------------------------------

    // Basic
    $('#sweet_basic').on('click', function() {
        swal({
            title: "Here's a message!",
            confirmButtonColor: "#2196F3"
        });
    });

    // With title
    $('#sweet_title_text').on('click', function() {
        swal({
            title: "Here's a message!",
            text: "It's pretty, isn't it?",
            confirmButtonColor: "#2196F3"
        });
    });

    // Auto closing
    $('#sweet_auto_closer').on('click', function() {
        swal({
            title: "Auto close alert!",
            text: "I will close in 2 seconds.",
            confirmButtonColor: "#2196F3",
            timer: 2000
        });
    });

    // HTML message
    $('#sweet_html').on('click', function() {
        swal({
            title: "HTML small subtitle",
            text: "A custom html message.",
            html: true,
            confirmButtonColor: "#2196F3"
        });
    });

    // Prompt
    $('#sweet_prompt').on('click', function() {
        swal({
            title: "An input!",
            text: "Write something interesting:",
            type: "input",
            showCancelButton: true,
            confirmButtonColor: "#2196F3",
            closeOnConfirm: false,
            animation: "slide-from-top",
            inputPlaceholder: "Write something"
        },
        function(inputValue){
            if (inputValue === false) return false;
            if (inputValue === "") {
                swal.showInputError("You need to write something!");
                return false
            }
            swal({
                title: "Nice!",
                text: "You wrote: " + inputValue,
                type: "success",
                confirmButtonColor: "#2196F3"
            });
        });
    });

    // AJAX loader
    $('#sweet_loader').on('click', function() {
        swal({
            title: "Ajax request example",
            text: "Submit to run ajax request",
            type: "info",
            showCancelButton: true,
            closeOnConfirm: false,
            confirmButtonColor: "#2196F3",
            showLoaderOnConfirm: true
        },
        function() {
            setTimeout(function() {
                swal({
                    title: "Ajax request finished!",
                    confirmButtonColor: "#2196F3"
                });
            }, 2000);
        });
    });

    //
    // Contextual alerts
    //

    // Success alert
    $('#sweet_success').on('click', function() {
        swal({
            title: "Good job!",
            text: "You clicked the button!",
            confirmButtonColor: "#66BB6A",
            type: "success"
        });
    });

    // Error alert
    $('#sweet_error').on('click', function() {
        swal({
            title: "Oops...",
            text: "Something went wrong!",
            confirmButtonColor: "#EF5350",
            type: "error"
        });
    });

    // Warning alert
    $('#sweet_warning').on('click', function() {
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#FF7043",
            confirmButtonText: "Yes, delete it!"
        });
    });

    // Info alert
    $('#sweet_info').on('click', function() {
        swal({
            title: "For your information",
            text: "This is some sort of a custom alert",
            confirmButtonColor: "#2196F3",
            type: "info"
        });
    });

    // Alert combination
    $('#sweet_combine').on('click', function() {
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#EF5350",
            confirmButtonText: "Yes, delete it!",
            cancelButtonText: "No, cancel pls!",
            closeOnConfirm: false,
            closeOnCancel: false
        },
        function(isConfirm){
            if (isConfirm) {
                swal({
                    title: "Deleted!",
                    text: "Your imaginary file has been deleted.",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                });
            }
            else {
                swal({
                    title: "Cancelled",
                    text: "Your imaginary file is safe :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });
            }
        });
    });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MySite
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button_click(object sender, EventArgs e)
        {
            Button clickedButton = (Button)sender;
            string accountName = name.Text;
            string accountWebsiteurl = website.Text;

            BasicHttpBinding myBinding = new BasicHttpBinding();
            myBinding.Name = "ServiceCalledFromWebSite.AccountWebServiceClient ";
            myBinding.Security.Mode = BasicHttpSecurityMode.None;
            myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
            myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            EndpointAddress endPointAddress = new EndpointAddress("http://vsisso23/ServiceCalledFromWebSite/AccountWebService.svc?wsdl");
            ServiceCalledFromWebSite.AccountWebServiceClient myClient = new ServiceCalledFromWebSite.AccountWebServiceClient(myBinding, endPointAddress);
            HashSet<string> serviceFields = new HashSet<string> { "modifiedon", "modifiedby", "modifiedonbehalfby", "accountid" };

            int accountEntityNumber = int.Parse(entityNumber.Text);
            myClient.CreateAccount(accountEntityNumber, accountName, accountWebsiteurl);
        }
    }
}


text:
var App = require('app');

App.MainHostComboSearchBoxController = Em.Controller.extend({
  name: 'mainHostComboSearchBoxController',
  currentSuggestion: [],
  page_size: 10,
  getPropertySuggestions: function(facet, searchTerm) {
    facet = (facet == 'hostName')? 'host_name' : facet;
    return App.ajax.send({
      name: 'hosts.with_searchTerm',
      sender: this,
      data: {
        facet: facet,
        searchTerm: searchTerm,
        page_size: this.get('page_size')
      },
      success: 'getPropertySuggestionsSuccess',
      error: 'commonSuggestionErrorCallback'
    });
  },

  getPropertySuggestionsSuccess: function(data, opt, params) {
    this.updateSuggestion(data.items.map(function(item) {
      return item.Hosts[params.facet];
    }));
  },

  updateSuggestion: function(data) {
    var controller = App.router.get('mainHostComboSearchBoxController');
    controller.set('currentSuggestion', data);
  },

  commonSuggestionErrorCallback:function() {
    // handle suggestion error
  },

  isComponentStateFacet: function(facet) {
    return App.StackServiceComponent.find(facet).get('isLoaded');
  },

  isComplexHealthStatusFacet: function(facet) {
    return ['health-status-WITH-ALERTS', 'health-status-RESTART', 'health-status-PASSIVE_STATE'].contains(facet);
  },

  generateQueryParam: function(param) {
    var expressions = param.key;
    var pHash = this.createComboParamHash(param);
    return this.createComboParamURL(pHash, expressions);
  },

  /**
   * @param pHash {k1:v1, k2:[v1,v2], ...}
   * @param expression
   * @returns {string} 'k1=v1&(k2=v1|k2=v2)'
   */
  createComboParamURL: function(pHash, expressions) {
    var self = this;
    var result = '';
    for (var key in pHash) {
      var v = pHash[key];
      if (Em.isArray(v)) {
        var ex = '(';
        v.forEach(function(item) {
          var expression = self.getComboParamURL(item, expressions);
          var toAdd = expression.replace('{0}', key);
          toAdd = toAdd.replace('{1}', item);
          ex += toAdd + '|';
        });
        ex = ex.substring(0, ex.length - 1);
        result += ex + ')';
      } else {
        var expression = self.getComboParamURL(v, expressions);
        var ex = expression.replace('{0}', key);
        ex = ex.replace('{1}', v);
        result += ex;
      }
      result += '|';
    }

    return result.substring(0, result.length - 1);
  },

  /**
   * @param value //value of component state
   * @returns expression //url of query of state
   */
  getComboParamURL: function(value, expressions) {
    var expression = expressions[1];
    switch (value) {
      case 'ALL':
        expression = expressions[0];
        break;
      case 'STARTED':
      case 'STARTING':
      case 'INSTALLED':
      case 'STOPPING':
      case 'INSTALL_FAILED':
      case 'INSTALLING':
      case 'UPGRADE_FAILED':
      case 'UNKNOWN':
      case 'DISABLED':
      case 'INIT':
        break;
      case 'INSERVICE':
      case 'DECOMMISSIONING':
      case 'DECOMMISSIONED':
      case 'RS_DECOMMISSIONED':
        expression = expressions[2];
        break;
      case 'ON':
      case 'OFF':
        expression = expressions[3];
        break;
    }
    return expression;
  },

  /**
   * @param param ['k1:v1','k2:v1', 'k2:v2'] or 'k1:v1'
   * @returns {k1:v1, k2:[v1,v2], ...}
   */
  createComboParamHash: function(param) {
    var pHash = {};
    if (Em.isArray(param.value)) {
      param.value.forEach(function(item) {
        var values = item.split(':');
        var k = values[0];
        var v = values[1];
        if (!pHash[k]) {
          pHash[k] = v;
        } else {
          if (Em.isArray(pHash[k])) {
            if (pHash[k].indexOf(v) == -1) {
              pHash[k].push(v);
            }
          } else {
            pHash[k] = [pHash[k], v];
          }
        }
      });
    } else {
      var values = param.value.split(':');
      pHash[values[0]] = values[1];
    }
    return pHash;
  }
});


text:
package org.openqa.grid.web.utils;

import com.google.common.collect.Maps;

import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.BrowserType;

import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.internal.Registry;

import java.io.InputStream;
import java.util.Map;

/**
 * Utilities for dealing with browser names.
 */
public class BrowserNameUtils {

  public static String lookupGrid1Environment(String browserString, Registry registry) {
    String translatedBrowserString =
        registry.getConfiguration().getGrid1Mapping().get(browserString);

    return (translatedBrowserString == null) ? browserString : translatedBrowserString;
  }

  public static Map<String, Object> parseGrid2Environment(String environment) {
    Map<String, Object> ret = Maps.newHashMap();

    String[] details = environment.split(" ");
    if (details.length == 1) {
      // simple browser string
      ret.put(RegistrationRequest.BROWSER, details[0]);
    } else {
      // more complex. Only case handled so far = X on Y
      // where X is the browser string, Y the OS
      ret.put(RegistrationRequest.BROWSER, details[0]);
      if (details.length == 3) {
        ret.put(RegistrationRequest.PLATFORM, Platform.extractFromSysProperty(details[2]));
      }
    }

    return ret;
  }

  public static String consoleIconName(DesiredCapabilities cap, Registry registry) {
    String browserString = cap.getBrowserName();
    if (browserString == null || "".equals(browserString)) {
      return "missingBrowserName";
    }

    String ret = browserString;

    // Take care of any Grid 1.0 named environment translation.
    if (browserString.charAt(0) != '*') {
      browserString = lookupGrid1Environment(browserString, registry);
    }

    // Map browser environments to icon names.
    if (browserString.contains("iexplore") || browserString.startsWith("*iehta")) {
      ret = "internet explorer";
    } else if (browserString.contains("firefox") || browserString.startsWith("*chrome")) {
      if (cap.getVersion() != null && cap.getVersion().toLowerCase().equals("beta") ||
          cap.getBrowserName().toLowerCase().contains("beta")) {
        ret = "firefoxbeta";
      } else if (cap.getVersion() != null && cap.getVersion().toLowerCase().equals("aurora") ||
          cap.getBrowserName().toLowerCase().contains("aurora")) {
        ret = "aurora";
      } else if (cap.getVersion() != null && cap.getVersion().toLowerCase().equals("nightly") ||
          cap.getBrowserName().toLowerCase().contains("nightly")) {
        ret = "nightly";
      } else {
        ret = "firefox";
      }

    } else if (browserString.startsWith("*safari")) {
      ret = BrowserType.SAFARI;
    } else if (browserString.startsWith("*googlechrome")) {
      ret = "chrome";
    } else if (browserString.startsWith("opera")) {
      ret = BrowserType.OPERA;
    }

    return ret.replace(" ", "_");
  }

  /**
   * get the icon representing the browser for the grid. If the icon cannot be located, returns
   * null.
   *
   * @param cap
   * @param registry
   * @return String with path to icon image file.  Can be <i>null</i> if no icon
   *         file if available.
   */
  public static String getConsoleIconPath(DesiredCapabilities cap, Registry registry) {
    String name = consoleIconName(cap, registry);
    InputStream in =
        Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("images/" + name + ".png");
    if (in == null) {
      return null;
    } else {
      return "/grid/resources/images/" + name + ".png";
    }

  }

}


text:
<bill session="110" type="h" number="4700" updated="2009-01-09T02:44:03-05:00">
	<status><introduced date="1197522000" datetime="2007-12-13"/></status>

	<introduced date="1197522000" datetime="2007-12-13"/>
	<titles>
		<title type="official" as="introduced">To suspend temporarily the duty on certain structures, parts, and components for use in an isotopic separation facility in southern Ohio.</title>
	</titles>
	<sponsor id="400406"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1197522000" datetime="2007-12-13"><text>Referred to the House Committee on Ways and Means.</text></action>
		<action date="1198126800" datetime="2007-12-20"><text>Referred to the Subcommittee on Trade.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	12/13/2007--Introduced.
Amends the Harmonized Tariff Schedule of the United States to suspend temporarily the duty on certain structures, parts, and components for use in an isotopic separation facility in southern Ohio.

</bill>


text:
package android.widget;

import com.android.internal.R;

import android.annotation.DrawableRes;
import android.annotation.Nullable;
import android.annotation.Widget;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.ListPopupWindow.ForwardingListener;
import android.widget.PopupWindow.OnDismissListener;

/**
 * A view that displays one child at a time and lets the user pick among them.
 * The items in the Spinner come from the {@link Adapter} associated with
 * this view.
 *
 *
See the Spinners guide.

 *
 * @attr ref android.R.styleable#Spinner_dropDownSelector
 * @attr ref android.R.styleable#Spinner_dropDownWidth
 * @attr ref android.R.styleable#Spinner_gravity
 * @attr ref android.R.styleable#Spinner_popupBackground
 * @attr ref android.R.styleable#Spinner_prompt
 * @attr ref android.R.styleable#Spinner_spinnerMode
 * @attr ref android.R.styleable#ListPopupWindow_dropDownVerticalOffset
 * @attr ref android.R.styleable#ListPopupWindow_dropDownHorizontalOffset
 */
@Widget
public class Spinner extends AbsSpinner implements OnClickListener {
    private static final String TAG = "Spinner";

    // Only measure this many items to get a decent max width.
    private static final int MAX_ITEMS_MEASURED = 15;

    /**
     * Use a dialog window for selecting spinner options.
     */
    public static final int MODE_DIALOG = 0;

    /**
     * Use a dropdown anchored to the Spinner for selecting spinner options.
     */
    public static final int MODE_DROPDOWN = 1;

    /**
     * Use the theme-supplied value to select the dropdown mode.
     */
    private static final int MODE_THEME = -1;

    /** Context used to inflate the popup window or dialog. */
    private Context mPopupContext;

    /** Forwarding listener used to implement drag-to-open. */
    private ForwardingListener mForwardingListener;

    /** Temporary holder for setAdapter() calls from the super constructor. */
    private SpinnerAdapter mTempAdapter;

    private SpinnerPopup mPopup;
    int mDropDownWidth;

    private int mGravity;
    private boolean mDisableChildrenWhenDisabled;

    private Rect mTempRect = new Rect();

    /**
     * Construct a new spinner with the given context's theme.
     *
     * @param context The Context the view is running in, through which it can
     *        access the current theme, resources, etc.
     */
    public Spinner(Context context) {
        this(context, null);
    }

    /**
     * Construct a new spinner with the given context's theme and the supplied
     * mode of displaying choices. mode may be one of
     * {@link #MODE_DIALOG} or {@link #MODE_DROPDOWN}.
     *
     * @param context The Context the view is running in, through which it can
     *        access the current theme, resources, etc.
     * @param mode Constant describing how the user will select choices from the spinner.
     *
     * @see #MODE_DIALOG
     * @see #MODE_DROPDOWN
     */
    public Spinner(Context context, int mode) {
        this(context, null, com.android.internal.R.attr.spinnerStyle, mode);
    }

    /**
     * Construct a new spinner with the given context's theme and the supplied attribute set.
     *
     * @param context The Context the view is running in, through which it can
     *        access the current theme, resources, etc.
     * @param attrs The attributes of the XML tag that is inflating the view.
     */
    public Spinner(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.spinnerStyle);
    }

    /**
     * Construct a new spinner with the given context's theme, the supplied attribute set,
     * and default style attribute.
     *
     * @param context The Context the view is running in, through which it can
     *        access the current theme, resources, etc.
     * @param attrs The attributes of the XML tag that is inflating the view.
     * @param defStyleAttr An attribute in the current theme that contains a
     *        reference to a style resource that supplies default values for
     *        the view. Can be 0 to not look for defaults.
     */
    public Spinner(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0, MODE_THEME);
    }

    /**
     * Construct a new spinner with the given context's theme, the supplied attribute set,
     * and default style. mode may be one of {@link #MODE_DIALOG} or
     * {@link #MODE_DROPDOWN} and determines how the user will select choices from the spinner.
     *
     * @param context The Context the view is running in, through which it can
     *        access the current theme, resources, etc.
     * @param attrs The attributes of the XML tag that is inflating the view.
     * @param defStyleAttr An attribute in the current theme that contains a
     *        reference to a style resource that supplies default values for
     *        the view. Can be 0 to not look for defaults.
     * @param mode Constant describing how the user will select choices from the spinner.
     *
     * @see #MODE_DIALOG
     * @see #MODE_DROPDOWN
     */
    public Spinner(Context context, AttributeSet attrs, int defStyleAttr, int mode) {
        this(context, attrs, defStyleAttr, 0, mode);
    }

    /**
     * Construct a new spinner with the given context's theme, the supplied attribute set,
     * and default style. mode may be one of {@link #MODE_DIALOG} or
     * {@link #MODE_DROPDOWN} and determines how the user will select choices from the spinner.
     *
     * @param context The Context the view is running in, through which it can
     *        access the current theme, resources, etc.
     * @param attrs The attributes of the XML tag that is inflating the view.
     * @param defStyleAttr An attribute in the current theme that contains a
     *        reference to a style resource that supplies default values for
     *        the view. Can be 0 to not look for defaults.
     * @param defStyleRes A resource identifier of a style resource that
     *        supplies default values for the view, used only if
     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
     *        to not look for defaults.
     * @param mode Constant describing how the user will select choices from the spinner.
     *
     * @see #MODE_DIALOG
     * @see #MODE_DROPDOWN
     */
    public Spinner(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes,
            int mode) {
        this(context, attrs, defStyleAttr, defStyleRes, mode, null);
    }

    /**
     * Constructs a new spinner with the given context's theme, the supplied
     * attribute set, default styles, popup mode (one of {@link #MODE_DIALOG}
     * or {@link #MODE_DROPDOWN}), and the context against which the popup
     * should be inflated.
     *
     * @param context The context against which the view is inflated, which
     *                provides access to the current theme, resources, etc.
     * @param attrs The attributes of the XML tag that is inflating the view.
     * @param defStyleAttr An attribute in the current theme that contains a
     *                     reference to a style resource that supplies default
     *                     values for the view. Can be 0 to not look for
     *                     defaults.
     * @param defStyleRes A resource identifier of a style resource that
     *                    supplies default values for the view, used only if
     *                    defStyleAttr is 0 or can not be found in the theme.
     *                    Can be 0 to not look for defaults.
     * @param mode Constant describing how the user will select choices from
     *             the spinner.
     * @param popupTheme The theme against which the dialog or dropdown popup
     *                   should be inflated. May be {@code null} to use the
     *                   view theme. If set, this will override any value
     *                   specified by
     *                   {@link android.R.styleable#Spinner_popupTheme}.
     *
     * @see #MODE_DIALOG
     * @see #MODE_DROPDOWN
     */
    public Spinner(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes, int mode,
            Theme popupTheme) {
        super(context, attrs, defStyleAttr, defStyleRes);

        final TypedArray a = context.obtainStyledAttributes(
                attrs, R.styleable.Spinner, defStyleAttr, defStyleRes);

        if (popupTheme != null) {
            mPopupContext = new ContextThemeWrapper(context, popupTheme);
        } else {
            final int popupThemeResId = a.getResourceId(R.styleable.Spinner_popupTheme, 0);
            if (popupThemeResId != 0) {
                mPopupContext = new ContextThemeWrapper(context, popupThemeResId);
            } else {
                mPopupContext = context;
            }
        }

        if (mode == MODE_THEME) {
            mode = a.getInt(R.styleable.Spinner_spinnerMode, MODE_DIALOG);
        }

        switch (mode) {
            case MODE_DIALOG: {
                mPopup = new DialogPopup();
                mPopup.setPromptText(a.getString(R.styleable.Spinner_prompt));
                break;
            }

            case MODE_DROPDOWN: {
                final DropdownPopup popup = new DropdownPopup(
                        mPopupContext, attrs, defStyleAttr, defStyleRes);
                final TypedArray pa = mPopupContext.obtainStyledAttributes(
                        attrs, R.styleable.Spinner, defStyleAttr, defStyleRes);
                mDropDownWidth = pa.getLayoutDimension(R.styleable.Spinner_dropDownWidth,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                popup.setBackgroundDrawable(pa.getDrawable(R.styleable.Spinner_popupBackground));
                popup.setPromptText(a.getString(R.styleable.Spinner_prompt));
                pa.recycle();

                mPopup = popup;
                mForwardingListener = new ForwardingListener(this) {
                    @Override
                    public ListPopupWindow getPopup() {
                        return popup;
                    }

                    @Override
                    public boolean onForwardingStarted() {
                        if (!mPopup.isShowing()) {
                            mPopup.show(getTextDirection(), getTextAlignment());
                        }
                        return true;
                    }
                };
                break;
            }
        }

        mGravity = a.getInt(R.styleable.Spinner_gravity, Gravity.CENTER);
        mDisableChildrenWhenDisabled = a.getBoolean(
                R.styleable.Spinner_disableChildrenWhenDisabled, false);

        a.recycle();

        // Base constructor can call setAdapter before we initialize mPopup.
        // Finish setting things up if this happened.
        if (mTempAdapter != null) {
            setAdapter(mTempAdapter);
            mTempAdapter = null;
        }
    }

    /**
     * @return the context used to inflate the Spinner's popup or dialog window
     */
    public Context getPopupContext() {
        return mPopupContext;
    }

    /**
     * Set the background drawable for the spinner's popup window of choices.
     * Only valid in {@link #MODE_DROPDOWN}; this method is a no-op in other modes.
     *
     * @param background Background drawable
     *
     * @attr ref android.R.styleable#Spinner_popupBackground
     */
    public void setPopupBackgroundDrawable(Drawable background) {
        if (!(mPopup instanceof DropdownPopup)) {
            Log.e(TAG, "setPopupBackgroundDrawable: incompatible spinner mode; ignoring...");
            return;
        }
        mPopup.setBackgroundDrawable(background);
    }

    /**
     * Set the background drawable for the spinner's popup window of choices.
     * Only valid in {@link #MODE_DROPDOWN}; this method is a no-op in other modes.
     *
     * @param resId Resource ID of a background drawable
     *
     * @attr ref android.R.styleable#Spinner_popupBackground
     */
    public void setPopupBackgroundResource(@DrawableRes int resId) {
        setPopupBackgroundDrawable(getPopupContext().getDrawable(resId));
    }

    /**
     * Get the background drawable for the spinner's popup window of choices.
     * Only valid in {@link #MODE_DROPDOWN}; other modes will return null.
     *
     * @return background Background drawable
     *
     * @attr ref android.R.styleable#Spinner_popupBackground
     */
    public Drawable getPopupBackground() {
        return mPopup.getBackground();
    }

    /**
     * Set a vertical offset in pixels for the spinner's popup window of choices.
     * Only valid in {@link #MODE_DROPDOWN}; this method is a no-op in other modes.
     *
     * @param pixels Vertical offset in pixels
     *
     * @attr ref android.R.styleable#ListPopupWindow_dropDownVerticalOffset
     */
    public void setDropDownVerticalOffset(int pixels) {
        mPopup.setVerticalOffset(pixels);
    }

    /**
     * Get the configured vertical offset in pixels for the spinner's popup window of choices.
     * Only valid in {@link #MODE_DROPDOWN}; other modes will return 0.
     *
     * @return Vertical offset in pixels
     *
     * @attr ref android.R.styleable#ListPopupWindow_dropDownVerticalOffset
     */
    public int getDropDownVerticalOffset() {
        return mPopup.getVerticalOffset();
    }

    /**
     * Set a horizontal offset in pixels for the spinner's popup window of choices.
     * Only valid in {@link #MODE_DROPDOWN}; this method is a no-op in other modes.
     *
     * @param pixels Horizontal offset in pixels
     *
     * @attr ref android.R.styleable#ListPopupWindow_dropDownHorizontalOffset
     */
    public void setDropDownHorizontalOffset(int pixels) {
        mPopup.setHorizontalOffset(pixels);
    }

    /**
     * Get the configured horizontal offset in pixels for the spinner's popup window of choices.
     * Only valid in {@link #MODE_DROPDOWN}; other modes will return 0.
     *
     * @return Horizontal offset in pixels
     *
     * @attr ref android.R.styleable#ListPopupWindow_dropDownHorizontalOffset
     */
    public int getDropDownHorizontalOffset() {
        return mPopup.getHorizontalOffset();
    }

    /**
     * Set the width of the spinner's popup window of choices in pixels. This value
     * may also be set to {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}
     * to match the width of the Spinner itself, or
     * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} to wrap to the measured size
     * of contained dropdown list items.
     *
     *
Only valid in {@link #MODE_DROPDOWN}; this method is a no-op in other modes.

     *
     * @param pixels Width in pixels, WRAP_CONTENT, or MATCH_PARENT
     *
     * @attr ref android.R.styleable#Spinner_dropDownWidth
     */
    public void setDropDownWidth(int pixels) {
        if (!(mPopup instanceof DropdownPopup)) {
            Log.e(TAG, "Cannot set dropdown width for MODE_DIALOG, ignoring");
            return;
        }
        mDropDownWidth = pixels;
    }

    /**
     * Get the configured width of the spinner's popup window of choices in pixels.
     * The returned value may also be {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}
     * meaning the popup window will match the width of the Spinner itself, or
     * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} to wrap to the measured size
     * of contained dropdown list items.
     *
     * @return Width in pixels, WRAP_CONTENT, or MATCH_PARENT
     *
     * @attr ref android.R.styleable#Spinner_dropDownWidth
     */
    public int getDropDownWidth() {
        return mDropDownWidth;
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (mDisableChildrenWhenDisabled) {
            final int count = getChildCount();
            for (int i = 0; i < count; i++) {
                getChildAt(i).setEnabled(enabled);
            }
        }
    }

    /**
     * Describes how the selected item view is positioned. Currently only the horizontal component
     * is used. The default is determined by the current theme.
     *
     * @param gravity See {@link android.view.Gravity}
     *
     * @attr ref android.R.styleable#Spinner_gravity
     */
    public void setGravity(int gravity) {
        if (mGravity != gravity) {
            if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) {
                gravity |= Gravity.START;
            }
            mGravity = gravity;
            requestLayout();
        }
    }

    /**
     * Describes how the selected item view is positioned. The default is determined by the
     * current theme.
     *
     * @return A {@link android.view.Gravity Gravity} value
     */
    public int getGravity() {
        return mGravity;
    }

    /**
     * Sets the {@link SpinnerAdapter} used to provide the data which backs
     * this Spinner.
     *

     * If this Spinner has a popup theme set in XML via the
     * {@link android.R.styleable#Spinner_popupTheme popupTheme} attribute, the
     * adapter should inflate drop-down views using the same theme. The easiest
     * way to achieve this is by using {@link #getPopupContext()} to obtain a
     * layout inflater for use in
     * {@link SpinnerAdapter#getDropDownView(int, View, ViewGroup)}.
     *

     * Spinner overrides {@link Adapter#getViewTypeCount()} on the
     * Adapter associated with this view. Calling
     * {@link Adapter#getItemViewType(int) getItemViewType(int)} on the object
     * returned from {@link #getAdapter()} will always return 0. Calling
     * {@link Adapter#getViewTypeCount() getViewTypeCount()} will always return
     * 1. On API {@link Build.VERSION_CODES#LOLLIPOP} and above, attempting to set an
     * adapter with more than one view type will throw an
     * {@link IllegalArgumentException}.
     *
     * @param adapter the adapter to set
     *
     * @see AbsSpinner#setAdapter(SpinnerAdapter)
     * @throws IllegalArgumentException if the adapter has more than one view
     *         type
     */
    @Override
    public void setAdapter(SpinnerAdapter adapter) {
        // The super constructor may call setAdapter before we're prepared.
        // Postpone doing anything until we've finished construction.
        if (mPopup == null) {
            mTempAdapter = adapter;
            return;
        }

        super.setAdapter(adapter);

        mRecycler.clear();

        final int targetSdkVersion = mContext.getApplicationInfo().targetSdkVersion;
        if (targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP
                && adapter != null && adapter.getViewTypeCount() != 1) {
            throw new IllegalArgumentException("Spinner adapter view type count must be 1");
        }

        final Context popupContext = mPopupContext == null ? mContext : mPopupContext;
        mPopup.setAdapter(new DropDownAdapter(adapter, popupContext.getTheme()));
    }

    @Override
    public int getBaseline() {
        View child = null;

        if (getChildCount() > 0) {
            child = getChildAt(0);
        } else if (mAdapter != null && mAdapter.getCount() > 0) {
            child = makeView(0, false);
            mRecycler.put(0, child);
        }

        if (child != null) {
            final int childBaseline = child.getBaseline();
            return childBaseline >= 0 ? child.getTop() + childBaseline : -1;
        } else {
            return -1;
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        if (mPopup != null && mPopup.isShowing()) {
            mPopup.dismiss();
        }
    }

    /**
     *
A spinner does not support item click events. Calling this method
     * will raise an exception.

     *
Instead use {@link AdapterView#setOnItemSelectedListener}.
     *
     * @param l this listener will be ignored
     */
    @Override
    public void setOnItemClickListener(OnItemClickListener l) {
        throw new RuntimeException("setOnItemClickListener cannot be used with a spinner.");
    }

    /**
     * @hide internal use only
     */
    public void setOnItemClickListenerInt(OnItemClickListener l) {
        super.setOnItemClickListener(l);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mForwardingListener != null && mForwardingListener.onTouch(this, event)) {
            return true;
        }

        return super.onTouchEvent(event);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mPopup != null && MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) {
            final int measuredWidth = getMeasuredWidth();
            setMeasuredDimension(Math.min(Math.max(measuredWidth,
                    measureContentWidth(getAdapter(), getBackground())),
                    MeasureSpec.getSize(widthMeasureSpec)),
                    getMeasuredHeight());
        }
    }

    /**
     * @see android.view.View#onLayout(boolean,int,int,int,int)
     *
     * Creates and positions all views
     *
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        mInLayout = true;
        layout(0, false);
        mInLayout = false;
    }

    /**
     * Creates and positions all views for this Spinner.
     *
     * @param delta Change in the selected position. +1 means selection is moving to the right,
     * so views are scrolling to the left. -1 means selection is moving to the left.
     */
    @Override
    void layout(int delta, boolean animate) {
        int childrenLeft = mSpinnerPadding.left;
        int childrenWidth = mRight - mLeft - mSpinnerPadding.left - mSpinnerPadding.right;

        if (mDataChanged) {
            handleDataChanged();
        }

        // Handle the empty set by removing all views
        if (mItemCount == 0) {
            resetList();
            return;
        }

        if (mNextSelectedPosition >= 0) {
            setSelectedPositionInt(mNextSelectedPosition);
        }

        recycleAllViews();

        // Clear out old views
        removeAllViewsInLayout();

        // Make selected view and position it
        mFirstPosition = mSelectedPosition;

        if (mAdapter != null) {
            View sel = makeView(mSelectedPosition, true);
            int width = sel.getMeasuredWidth();
            int selectedOffset = childrenLeft;
            final int layoutDirection = getLayoutDirection();
            final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
            switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                case Gravity.CENTER_HORIZONTAL:
                    selectedOffset = childrenLeft + (childrenWidth / 2) - (width / 2);
                    break;
                case Gravity.RIGHT:
                    selectedOffset = childrenLeft + childrenWidth - width;
                    break;
            }
            sel.offsetLeftAndRight(selectedOffset);
        }

        // Flush any cached views that did not get reused above
        mRecycler.clear();

        invalidate();

        checkSelectionChanged();

        mDataChanged = false;
        mNeedSync = false;
        setNextSelectedPositionInt(mSelectedPosition);
    }

    /**
     * Obtain a view, either by pulling an existing view from the recycler or
     * by getting a new one from the adapter. If we are animating, make sure
     * there is enough information in the view's layout parameters to animate
     * from the old to new positions.
     *
     * @param position Position in the spinner for the view to obtain
     * @param addChild true to add the child to the spinner, false to obtain and configure only.
     * @return A view for the given position
     */
    private View makeView(int position, boolean addChild) {
        View child;

        if (!mDataChanged) {
            child = mRecycler.get(position);
            if (child != null) {
                // Position the view
                setUpChild(child, addChild);

                return child;
            }
        }

        // Nothing found in the recycler -- ask the adapter for a view
        child = mAdapter.getView(position, null, this);

        // Position the view
        setUpChild(child, addChild);

        return child;
    }

    /**
     * Helper for makeAndAddView to set the position of a view
     * and fill out its layout paramters.
     *
     * @param child The view to position
     * @param addChild true if the child should be added to the Spinner during setup
     */
    private void setUpChild(View child, boolean addChild) {

        // Respect layout params that are already in the view. Otherwise
        // make some up...
        ViewGroup.LayoutParams lp = child.getLayoutParams();
        if (lp == null) {
            lp = generateDefaultLayoutParams();
        }

        addViewInLayout(child, 0, lp);

        child.setSelected(hasFocus());
        if (mDisableChildrenWhenDisabled) {
            child.setEnabled(isEnabled());
        }

        // Get measure specs
        int childHeightSpec = ViewGroup.getChildMeasureSpec(mHeightMeasureSpec,
                mSpinnerPadding.top + mSpinnerPadding.bottom, lp.height);
        int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
                mSpinnerPadding.left + mSpinnerPadding.right, lp.width);

        // Measure child
        child.measure(childWidthSpec, childHeightSpec);

        int childLeft;
        int childRight;

        // Position vertically based on gravity setting
        int childTop = mSpinnerPadding.top
                + ((getMeasuredHeight() - mSpinnerPadding.bottom -
                        mSpinnerPadding.top - child.getMeasuredHeight()) / 2);
        int childBottom = childTop + child.getMeasuredHeight();

        int width = child.getMeasuredWidth();
        childLeft = 0;
        childRight = childLeft + width;

        child.layout(childLeft, childTop, childRight, childBottom);

        if (!addChild) {
            removeViewInLayout(child);
        }
    }

    @Override
    public boolean performClick() {
        boolean handled = super.performClick();

        if (!handled) {
            handled = true;

            if (!mPopup.isShowing()) {
                mPopup.show(getTextDirection(), getTextAlignment());
            }
        }

        return handled;
    }

    public void onClick(DialogInterface dialog, int which) {
        setSelection(which);
        dialog.dismiss();
    }

    @Override
    public CharSequence getAccessibilityClassName() {
        return Spinner.class.getName();
    }

    /** @hide */
    @Override
    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfoInternal(info);

        if (mAdapter != null) {
            info.setCanOpenPopup(true);
        }
    }

    /**
     * Sets the prompt to display when the dialog is shown.
     * @param prompt the prompt to set
     */
    public void setPrompt(CharSequence prompt) {
        mPopup.setPromptText(prompt);
    }

    /**
     * Sets the prompt to display when the dialog is shown.
     * @param promptId the resource ID of the prompt to display when the dialog is shown
     */
    public void setPromptId(int promptId) {
        setPrompt(getContext().getText(promptId));
    }

    /**
     * @return The prompt to display when the dialog is shown
     */
    public CharSequence getPrompt() {
        return mPopup.getHintText();
    }

    int measureContentWidth(SpinnerAdapter adapter, Drawable background) {
        if (adapter == null) {
            return 0;
        }

        int width = 0;
        View itemView = null;
        int itemType = 0;
        final int widthMeasureSpec =
            MeasureSpec.makeSafeMeasureSpec(getMeasuredWidth(), MeasureSpec.UNSPECIFIED);
        final int heightMeasureSpec =
            MeasureSpec.makeSafeMeasureSpec(getMeasuredHeight(), MeasureSpec.UNSPECIFIED);

        // Make sure the number of items we'll measure is capped. If it's a huge data set
        // with wildly varying sizes, oh well.
        int start = Math.max(0, getSelectedItemPosition());
        final int end = Math.min(adapter.getCount(), start + MAX_ITEMS_MEASURED);
        final int count = end - start;
        start = Math.max(0, start - (MAX_ITEMS_MEASURED - count));
        for (int i = start; i < end; i++) {
            final int positionType = adapter.getItemViewType(i);
            if (positionType != itemType) {
                itemType = positionType;
                itemView = null;
            }
            itemView = adapter.getView(i, itemView, this);
            if (itemView.getLayoutParams() == null) {
                itemView.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
            }
            itemView.measure(widthMeasureSpec, heightMeasureSpec);
            width = Math.max(width, itemView.getMeasuredWidth());
        }

        // Add background padding to measured width
        if (background != null) {
            background.getPadding(mTempRect);
            width += mTempRect.left + mTempRect.right;
        }

        return width;
    }

    @Override
    public Parcelable onSaveInstanceState() {
        final SavedState ss = new SavedState(super.onSaveInstanceState());
        ss.showDropdown = mPopup != null && mPopup.isShowing();
        return ss;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;

        super.onRestoreInstanceState(ss.getSuperState());

        if (ss.showDropdown) {
            ViewTreeObserver vto = getViewTreeObserver();
            if (vto != null) {
                final OnGlobalLayoutListener listener = new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (!mPopup.isShowing()) {
                            mPopup.show(getTextDirection(), getTextAlignment());
                        }
                        final ViewTreeObserver vto = getViewTreeObserver();
                        if (vto != null) {
                            vto.removeOnGlobalLayoutListener(this);
                        }
                    }
                };
                vto.addOnGlobalLayoutListener(listener);
            }
        }
    }

    static class SavedState extends AbsSpinner.SavedState {
        boolean showDropdown;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            showDropdown = in.readByte() != 0;
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeByte((byte) (showDropdown ? 1 : 0));
        }

        public static final Parcelable.Creator<SavedState> CREATOR =
                new Parcelable.Creator<SavedState>() {
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }

    /**
     *
Wrapper class for an Adapter. Transforms the embedded Adapter instance
     * into a ListAdapter.

     */
    private static class DropDownAdapter implements ListAdapter, SpinnerAdapter {
        private SpinnerAdapter mAdapter;
        private ListAdapter mListAdapter;

        /**
         * Creates a new ListAdapter wrapper for the specified adapter.
         *
         * @param adapter the SpinnerAdapter to transform into a ListAdapter
         * @param dropDownTheme the theme against which to inflate drop-down
         *                      views, may be {@null} to use default theme
         */
        public DropDownAdapter(@Nullable SpinnerAdapter adapter,
                @Nullable Resources.Theme dropDownTheme) {
            mAdapter = adapter;

            if (adapter instanceof ListAdapter) {
                mListAdapter = (ListAdapter) adapter;
            }

            if (dropDownTheme != null && adapter instanceof ThemedSpinnerAdapter) {
                final ThemedSpinnerAdapter themedAdapter = (ThemedSpinnerAdapter) adapter;
                if (themedAdapter.getDropDownViewTheme() == null) {
                    themedAdapter.setDropDownViewTheme(dropDownTheme);
                }
            }
        }

        public int getCount() {
            return mAdapter == null ? 0 : mAdapter.getCount();
        }

        public Object getItem(int position) {
            return mAdapter == null ? null : mAdapter.getItem(position);
        }

        public long getItemId(int position) {
            return mAdapter == null ? -1 : mAdapter.getItemId(position);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            return getDropDownView(position, convertView, parent);
        }

        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return (mAdapter == null) ? null : mAdapter.getDropDownView(position, convertView, parent);
        }

        public boolean hasStableIds() {
            return mAdapter != null && mAdapter.hasStableIds();
        }

        public void registerDataSetObserver(DataSetObserver observer) {
            if (mAdapter != null) {
                mAdapter.registerDataSetObserver(observer);
            }
        }

        public void unregisterDataSetObserver(DataSetObserver observer) {
            if (mAdapter != null) {
                mAdapter.unregisterDataSetObserver(observer);
            }
        }

        /**
         * If the wrapped SpinnerAdapter is also a ListAdapter, delegate this call.
         * Otherwise, return true.
         */
        public boolean areAllItemsEnabled() {
            final ListAdapter adapter = mListAdapter;
            if (adapter != null) {
                return adapter.areAllItemsEnabled();
            } else {
                return true;
            }
        }

        /**
         * If the wrapped SpinnerAdapter is also a ListAdapter, delegate this call.
         * Otherwise, return true.
         */
        public boolean isEnabled(int position) {
            final ListAdapter adapter = mListAdapter;
            if (adapter != null) {
                return adapter.isEnabled(position);
            } else {
                return true;
            }
        }

        public int getItemViewType(int position) {
            return 0;
        }

        public int getViewTypeCount() {
            return 1;
        }

        public boolean isEmpty() {
            return getCount() == 0;
        }
    }

    /**
     * Implements some sort of popup selection interface for selecting a spinner option.
     * Allows for different spinner modes.
     */
    private interface SpinnerPopup {
        public void setAdapter(ListAdapter adapter);

        /**
         * Show the popup
         */
        public void show(int textDirection, int textAlignment);

        /**
         * Dismiss the popup
         */
        public void dismiss();

        /**
         * @return true if the popup is showing, false otherwise.
         */
        public boolean isShowing();

        /**
         * Set hint text to be displayed to the user. This should provide
         * a description of the choice being made.
         * @param hintText Hint text to set.
         */
        public void setPromptText(CharSequence hintText);
        public CharSequence getHintText();

        public void setBackgroundDrawable(Drawable bg);
        public void setVerticalOffset(int px);
        public void setHorizontalOffset(int px);
        public Drawable getBackground();
        public int getVerticalOffset();
        public int getHorizontalOffset();
    }

    private class DialogPopup implements SpinnerPopup, DialogInterface.OnClickListener {
        private AlertDialog mPopup;
        private ListAdapter mListAdapter;
        private CharSequence mPrompt;

        public void dismiss() {
            if (mPopup != null) {
                mPopup.dismiss();
                mPopup = null;
            }
        }

        public boolean isShowing() {
            return mPopup != null ? mPopup.isShowing() : false;
        }

        public void setAdapter(ListAdapter adapter) {
            mListAdapter = adapter;
        }

        public void setPromptText(CharSequence hintText) {
            mPrompt = hintText;
        }

        public CharSequence getHintText() {
            return mPrompt;
        }

        public void show(int textDirection, int textAlignment) {
            if (mListAdapter == null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getPopupContext());
            if (mPrompt != null) {
                builder.setTitle(mPrompt);
            }
            mPopup = builder.setSingleChoiceItems(mListAdapter,
                    getSelectedItemPosition(), this).create();
            final ListView listView = mPopup.getListView();
            listView.setTextDirection(textDirection);
            listView.setTextAlignment(textAlignment);
            mPopup.show();
        }

        public void onClick(DialogInterface dialog, int which) {
            setSelection(which);
            if (mOnItemClickListener != null) {
                performItemClick(null, which, mListAdapter.getItemId(which));
            }
            dismiss();
        }

        @Override
        public void setBackgroundDrawable(Drawable bg) {
            Log.e(TAG, "Cannot set popup background for MODE_DIALOG, ignoring");
        }

        @Override
        public void setVerticalOffset(int px) {
            Log.e(TAG, "Cannot set vertical offset for MODE_DIALOG, ignoring");
        }

        @Override
        public void setHorizontalOffset(int px) {
            Log.e(TAG, "Cannot set horizontal offset for MODE_DIALOG, ignoring");
        }

        @Override
        public Drawable getBackground() {
            return null;
        }

        @Override
        public int getVerticalOffset() {
            return 0;
        }

        @Override
        public int getHorizontalOffset() {
            return 0;
        }
    }

    private class DropdownPopup extends ListPopupWindow implements SpinnerPopup {
        private CharSequence mHintText;
        private ListAdapter mAdapter;

        public DropdownPopup(
                Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);

            setAnchorView(Spinner.this);
            setModal(true);
            setPromptPosition(POSITION_PROMPT_ABOVE);
            setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView parent, View v, int position, long id) {
                    Spinner.this.setSelection(position);
                    if (mOnItemClickListener != null) {
                        Spinner.this.performItemClick(v, position, mAdapter.getItemId(position));
                    }
                    dismiss();
                }
            });
        }

        @Override
        public void setAdapter(ListAdapter adapter) {
            super.setAdapter(adapter);
            mAdapter = adapter;
        }

        public CharSequence getHintText() {
            return mHintText;
        }

        public void setPromptText(CharSequence hintText) {
            // Hint text is ignored for dropdowns, but maintain it here.
            mHintText = hintText;
        }

        void computeContentWidth() {
            final Drawable background = getBackground();
            int hOffset = 0;
            if (background != null) {
                background.getPadding(mTempRect);
                hOffset = isLayoutRtl() ? mTempRect.right : -mTempRect.left;
            } else {
                mTempRect.left = mTempRect.right = 0;
            }

            final int spinnerPaddingLeft = Spinner.this.getPaddingLeft();
            final int spinnerPaddingRight = Spinner.this.getPaddingRight();
            final int spinnerWidth = Spinner.this.getWidth();

            if (mDropDownWidth == WRAP_CONTENT) {
                int contentWidth =  measureContentWidth(
                        (SpinnerAdapter) mAdapter, getBackground());
                final int contentWidthLimit = mContext.getResources()
                        .getDisplayMetrics().widthPixels - mTempRect.left - mTempRect.right;
                if (contentWidth > contentWidthLimit) {
                    contentWidth = contentWidthLimit;
                }
                setContentWidth(Math.max(
                       contentWidth, spinnerWidth - spinnerPaddingLeft - spinnerPaddingRight));
            } else if (mDropDownWidth == MATCH_PARENT) {
                setContentWidth(spinnerWidth - spinnerPaddingLeft - spinnerPaddingRight);
            } else {
                setContentWidth(mDropDownWidth);
            }

            if (isLayoutRtl()) {
                hOffset += spinnerWidth - spinnerPaddingRight - getWidth();
            } else {
                hOffset += spinnerPaddingLeft;
            }
            setHorizontalOffset(hOffset);
        }

        public void show(int textDirection, int textAlignment) {
            final boolean wasShowing = isShowing();

            computeContentWidth();

            setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
            super.show();
            final ListView listView = getListView();
            listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            listView.setTextDirection(textDirection);
            listView.setTextAlignment(textAlignment);
            setSelection(Spinner.this.getSelectedItemPosition());

            if (wasShowing) {
                // Skip setting up the layout/dismiss listener below. If we were previously
                // showing it will still stick around.
                return;
            }

            // Make sure we hide if our anchor goes away.
            // TODO: This might be appropriate to push all the way down to PopupWindow,
            // but it may have other side effects to investigate first. (Text editing handles, etc.)
            final ViewTreeObserver vto = getViewTreeObserver();
            if (vto != null) {
                final OnGlobalLayoutListener layoutListener = new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (!Spinner.this.isVisibleToUser()) {
                            dismiss();
                        } else {
                            computeContentWidth();

                            // Use super.show here to update; we don't want to move the selected
                            // position or adjust other things that would be reset otherwise.
                            DropdownPopup.super.show();
                        }
                    }
                };
                vto.addOnGlobalLayoutListener(layoutListener);
                setOnDismissListener(new OnDismissListener() {
                    @Override public void onDismiss() {
                        final ViewTreeObserver vto = getViewTreeObserver();
                        if (vto != null) {
                            vto.removeOnGlobalLayoutListener(layoutListener);
                        }
                    }
                });
            }
        }
    }

}


text:
from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField, BooleanField, RadioField, TextAreaField, FileField
from wtforms.validators import InputRequired, Length, Email, Regexp
from flask_wtf.file import FileRequired, FileAllowed

class SignUpForm(Form):
    username = StringField('Username', validators=[
        InputRequired(message="Username is required"),
        Regexp('^[A-Za-z][A-Za-z0-9_]*[A-Za-z0-9]$', 0, "Usernames must only have letters, numbers or underscores")
    ])
    name = StringField('Name', validators=[
        InputRequired(message="Name id required"),
        Regexp('^[A-Za-z][A-Za-z ]*[A-Za-z]$', 0, "Your name must only have letters")
    ])
    email = StringField('Email', validators=[
        InputRequired(message="Email is required"),
        Email(message="This is not a valid email")
    ])
    password = PasswordField('Password', validators=[
        InputRequired(message="Password is required"),
        Length(min=6, message="The password is not long enough")
    ])
    accept_tos = BooleanField("Accept Terms of Service", validators=[
        InputRequired(message="You have to accept the Terms of Service in order to use this site")
    ], default=False)
    submit = SubmitField('Signup')

class LoginForm(Form):
    username_email = StringField('Username or Email', validators=[
        InputRequired(message="Need to insert either username or email")
    ])
    password = PasswordField('Password', validators=[
        InputRequired(message="Insert your password")
    ])
    remember_me = BooleanField('Keep me logged in', default=False)
    submit = SubmitField('Login')

class EditProfileForm(Form):
    privacy_option = RadioField('Private Account', validators=[
        InputRequired(message="Need to have an option chosen")
    ], choices=[
        (True, "Yes"), (False, "No")
    ], default=True)
    name = StringField('Name', validators=[
        InputRequired(message="Name id required"),
        Regexp('^[A-Za-z][A-Za-z]*[A-Za-z]$', 0, "Your name must only have letters")
    ])
    username = StringField('Username', validators=[
        InputRequired(message="Username is required"),
        Regexp('^[A-Za-z][A-Za-z0-9_]*[A-Za-z0-9]$', 0, "Usernames must only have letters, numbers or underscores")
    ])
    email = StringField('Email', validators=[
        InputRequired(message="Email is required"),
        Email(message="This is not a valid email")
    ])
    password = PasswordField('Password', validators=[
        InputRequired(message="Password is required"),
        Length(min=6, message="The password is not long enough")
    ])
    bio = TextAreaField("Bio")
    submit = SubmitField('Save Changes')

class AvatarForm(Form):
    photo = FileField('Upload Avatar', validators=[
        FileRequired('A picture is required'),
        FileAllowed(['jpg', 'png'], "images only")
    ])
    submit = SubmitField("Crop & Save")

class ChangePasswordForm(Form):
    submit = SubmitField('Change Password')

class ChangeEmailForm(Form):
    change_email = StringField('New Email', validators=[
        InputRequired(message="You need to insert a new email"),
        Email(message="This is not a valid email")
    ])
    submit = SubmitField('Change Email')

class ChangeUsernameForm(Form):
    submit = SubmitField('Change Username')


text:
using OmniSharp.Common;
using Nancy;
using Nancy.ModelBinding;

namespace OmniSharp.Overrides {
    public class GetOverrideTargetsModule : NancyModule {

        public GetOverrideTargetsModule
            (OverrideHandler overrideHandler) {

            Post["GetOverrideTargets", "/getoverridetargets"] = x =>
                {
                    var req = this.Bind<OmniSharp.Common.Request>();
                    var completions = overrideHandler.GetOverrideTargets(req);
                    return Response.AsJson(completions);
                };
        }

    }
}


text:
package hu.sllauncher.gui.comp.logo;

import java.awt.Color;
import java.awt.Point;

/**
 * A star.
 *
 * @author Andras Belicza
 */
class Star {

	/** X coordinate of the star. */
	public double x = Double.MAX_VALUE;

	/** Y coordinate of the star. */
	public double y;

	/** Radius of the star. */
	public double r;

	/** X coordinate of the velocity of the star. */
	public double vx;

	/** Y coordinate of the velocity of the star. */
	public double vy;

	/** Color of the star. */
	public Color  color;

	/**
	 * Creates a new {@link Star}.
	 */
	public Star() {
	}

	/**
	 * Creates a new {@link Star}.
	 *
	 * @param target default location to be set
	 */
	public Star( final Point.Double target ) {
		setLocation( target );
	}

	/**
	 * Sets the location of the star.
	 *
	 * @param target target location to be set
	 */
	public void setLocation( final Point.Double target ) {
		x = target.x;
		y = target.y;
	}

	/**
	 * Moves the star according to its speed.
	 */
	public void move() {
		x += vx;
		y += vy;
	}

}


text:
class TwitterUsersController < ApplicationController

  def index
    attributes = {  uid: current_user.uid,
                    handle: current_user.handle,
                    name: current_user.name,
                    profile_image: current_user.profile_image,
                    description: current_user.description  }

    current_twitter_user = TwitterUser.new(attributes)
    target_twitter_user = TwitterUser.locate_target(current_user.target_tweets)
    connected_twitter_users = current_twitter_user.connections(current_user.target_tweets, target_twitter_user)

    render json: [current_twitter_user, target_twitter_user] + connected_twitter_users
  end

end


text:
"""
Example of converting data cached in older versions of requests-cache (<=0.5.2)
into the current format
"""
from requests import Response

import requests_cache.backends.base
from requests_cache import CachedResponse, CachedSession

class _Store:
    pass

# Add placeholder object used by pickle to deserialize old responses
requests_cache.backends.base._Store = _Store
requests_cache.backends.base._RawStore = _Store

def convert_old_response(cached_response, timestamp):
    temp_response = Response()
    for field in Response.__attrs__:
        setattr(temp_response, field, getattr(cached_response, field, None))

    new_response = CachedResponse(temp_response)
    new_response.created_at = timestamp
    return new_response

def convert_cache(*args, **kwargs):
    session = CachedSession(*args, **kwargs)
    print(f'Checking {len(session.cache.responses)} cached responses')

    with session.cache.responses.bulk_commit():
        for key, response in session.cache.responses.items():
            if isinstance(response, tuple):
                print(f'Converting response {key}')
                session.cache.responses[key] = convert_old_response(*response)

    print('Conversion complete')

# Example: convert a cache named 'demo_cache.sqlite' in the current directory
if __name__ == '__main__':
    convert_cache('demo_cache.sqlite')