rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
sci_name=organism_element.text elif organism_element.attrib['type']== 'common': com_name=organism_element.text else:
if organism_element.text: sci_name=organism_element.text if (organism_element.attrib['type']== 'common') and not sci_name: if organism_element.text: com_name=organism_element.text if (sci_name == '') and (com_name == ''):
def _parse_organism(element): com_name=sci_name='' for organism_element in element.getchildren(): if organism_element.tag==NS + 'name': if organism_element.attrib['type']== 'scientific': sci_name=organism_element.text elif organism_element.attrib['type']== 'common': com_name=organism_element.text else: append_to_annotations("organism_name", organism_element.text) elif organism_element.tag==NS + 'dbReference': self.ParsedSeqRecord.dbxrefs.append(organism_element.attrib['type']+':'+organism_element.attrib['id']) elif organism_element.tag==NS + 'lineage': for taxon_element in organism_element.getchildren(): if taxon_element.tag==NS + 'taxon': append_to_annotations('taxonomy',taxon_element.text) organism_name=sci_name if com_name: organism_name+=' (%s)'%com_name self.ParsedSeqRecord.annotations['organism']=organism_name
""" return (self.get_path(target, **kwargs) is not None)
""" return self.get_path(target, **kwargs) is not None
def is_parent_of(self, target=None, **kwargs): """True if target is a descendent of this tree.
outstr = join(outstr, '\n')
outstr = "\n".join(outstr)
def __str__(self): """ __str__(self) -> ""
if element is None :
if not element:
def __init__(self, name, coord, bfactor, occupancy, altloc, fullname, serial_number, element=None): """ Atom object.
lasty = trackheight*(val-minval)/resolution + \
lasty = trackheight*(val-midval)/resolution + \
def draw_line_graph(self, graph): """ draw_line_graph(self, graph) -> [element, element,...]
(self.dbid, value))[0])
(self.dbid, bioentry_id))[0])
def __contains__(self, value): """Check if a primary (internal) id is this namespace (sub database).""" sql = "SELECT COUNT(bioentry_id) FROM bioentry " + \ "WHERE biodatabase_id=%s AND bioentry_id=%s;" return bool(self.adaptor.execute_and_fetch_col0(sql, (self.dbid, value))[0])
answer.features.sort(cmp=lambda x,y: cmp(x.location.start.position, y.location.start.position))
answer.features.sort(key=lambda x : x.location.start.position)
def reverse_complement(self, id=False, name=False, description=False, features=True, annotations=False, letter_annotations=True, dbxrefs=False): """Returns new SeqRecord with reverse complement sequence.
line = line.strip()
line = line[5:].strip()
def __create_motif(line): line = line.strip() ls = line.split() motif = MEMEMotif() motif.length = int(ls[4]) motif._numoccurrences(ls[7]) motif._evalue(ls[13]) return motif
motif.length = int(ls[4]) motif._numoccurrences(ls[7]) motif._evalue(ls[13])
motif.length = int(ls[3]) motif._numoccurrences(ls[6]) motif._evalue(ls[12])
def __create_motif(line): line = line.strip() ls = line.split() motif = MEMEMotif() motif.length = int(ls[4]) motif._numoccurrences(ls[7]) motif._evalue(ls[13]) return motif
from_res = "<%s" % to_res
from_res = "<%s" % str(to_res).lstrip("<").lstrip(">")
def _make_seqfeature(name, from_res, to_res, description, ft_id): """Construct SeqFeature from feature data from parser (PRIVATE).""" #print name, repr(from_res), repr(to_res), "..." if from_res == "?" and to_res == "?": #If this does happen, will need to think about this some more! raise ValueError("Swiss file FT location ? ? (completely unknown)") elif from_res == "?": #e.g. given "? 5" in the Swiss file, treat this as <5..5 in GenBank from_res = "<%s" % to_res elif to_res == "?": #e.g. given "10 ?" in the Swiss file, treat this as 10..>10 in GenBank to_res = ">%s" % from_res loc = SeqFeature.FeatureLocation(_make_position(from_res,-1), _make_position(to_res, 0)) #print name, repr(from_res), repr(to_res), loc return SeqFeature.SeqFeature(loc, type=name, id=ft_id, qualifiers={"description":description})
to_res = ">%s" % from_res
to_res = ">%s" % str(from_res).lstrip("<").lstrip(">")
def _make_seqfeature(name, from_res, to_res, description, ft_id): """Construct SeqFeature from feature data from parser (PRIVATE).""" #print name, repr(from_res), repr(to_res), "..." if from_res == "?" and to_res == "?": #If this does happen, will need to think about this some more! raise ValueError("Swiss file FT location ? ? (completely unknown)") elif from_res == "?": #e.g. given "? 5" in the Swiss file, treat this as <5..5 in GenBank from_res = "<%s" % to_res elif to_res == "?": #e.g. given "10 ?" in the Swiss file, treat this as 10..>10 in GenBank to_res = ">%s" % from_res loc = SeqFeature.FeatureLocation(_make_position(from_res,-1), _make_position(to_res, 0)) #print name, repr(from_res), repr(to_res), loc return SeqFeature.SeqFeature(loc, type=name, id=ft_id, qualifiers={"description":description})
align = AlignIO.read(open("output.2.nex"), "nexus") for old, new in zip(records, align): self.assertEqual(old.id[:9], new.id) self.assertEqual(str(new.seq).replace("-",""), str(old.seq).replace("-",""))
try: align = AlignIO.read(open("output.2.nex"), "nexus") for old, new in zip(records, align): self.assertEqual(old.id[:9], new.id) self.assertEqual(str(new.seq).replace("-",""), str(old.seq).replace("-","")) except NexusError: pass
def test_Prank_simple_with_NEXUS_output(self): """Simple round-trip through app with infile, output in NEXUS output.?.??? files written to cwd - no way to redirect """ records = list(SeqIO.parse(open(self.infile1),"fasta")) #Try using keyword argument, cmdline = PrankCommandline(prank_exe, d=self.infile1, noxml=True) #Try using a property, cmdline.d = self.infile1 cmdline.f = 17 # NEXUS format cmdline.set_parameter("notree", True) self.assertEqual(str(cmdline), prank_exe + \ " -d=Fasta/fa01 -f=17 -noxml -notree") self.assertEqual(str(eval(repr(cmdline))), str(cmdline)) child = subprocess.Popen(str(cmdline), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=(sys.platform!="win32")) return_code = child.wait() self.assertEqual(return_code, 0) self.assertTrue("Total time" in child.stdout.read()) self.assertEqual(child.stderr.read(), "") align = AlignIO.read(open("output.2.nex"), "nexus") for old, new in zip(records, align): #Prank automatically reduces name to 9 chars self.assertEqual(old.id[:9], new.id) #infile1 has alignment gaps in it self.assertEqual(str(new.seq).replace("-",""), str(old.seq).replace("-","")) del child
if not isinstance(date, str) or len(date) != 11 \
if not isinstance(date, basestring) or len(date) != 11 \
def _get_date(self, record) : default = "01-JAN-1980" try : date = record.annotations["date"] except KeyError : return default #Cope with a list of one string: if isinstance(date, list) and len(date)==1 : date = date[0] #TODO - allow a Python date object if not isinstance(date, str) or len(date) != 11 \ or date[2] != "-" or date[6] != "-" \ or not date[:2].isdigit() or not date[7:].isdigit() \ or int(date[:2]) > 31 \ or date[3:6] not in ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"] : #TODO - Check is a valid date (e.g. not 31 Feb) return default return date
sys.stderr.write(str(m2))
sys.stderr.write(str(motif))
def compare_motifs (self, motif): if isinstance(motif, MEMEMotif): if not self.pssm: raise ValueError('This motif does not have a PSSM') if not motif.pssm: raise ValueError('The other motif does not have a PSSM') mylen = len(self.pssm) yourlen = len(motif.pssm) myr = None if mylen == yourlen: myr = _corr(self.pssm, motif.pssm) elif mylen < yourlen: diff = yourlen - mylen for i in range(0,diff): yourpssm = motif.pssm[i:mylen+i] r = _corr(self.pssm, yourpssm) if r > myr: myr = r else: diff = mylen - yourlen for i in range(0, diff): mypssm = self.pssm[i:yourlen+i] r = _corr(mypssm, motif.pssm) if r > myr: myr = r return myr else: sys.stderr.write(str(m2)) return None
def test_blasp(self):
def test_blastp(self):
def test_blasp(self): """Pairwise BLASTP search""" global exe_names cline = Applications.NcbiblastpCommandline(exe_names["blastp"], query="Fasta/rose.pro", subject="GenBank/NC_005816.faa", evalue=1) self.assertEqual(str(cline), exe_names["blastp"] \ + " -query Fasta/rose.pro -evalue 1" \ + " -subject GenBank/NC_005816.faa") child = subprocess.Popen(str(cline), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=(sys.platform!="win32")) stdoutdata, stderrdata = child.communicate() return_code = child.returncode self.assertEqual(return_code, 0, "Got error code %i back from:\n%s" % (return_code, cline)) self.assertEqual(10, stdoutdata.count("Query= ")) self.assertEqual(9, stdoutdata.count("***** No hits found *****")) #TODO - Parse it? I think we'd need to update this obsole code :( #records = list(NCBIStandalone.Iterator(StringIO(stdoutdata), # NCBIStandalone.BlastParser()))
self.assertTrue(key in id_list)
self.assertTrue(key in ids)
def check_dict_methods(self, rec_dict, keys, ids): self.assertEqual(set(keys), set(rec_dict.keys())) #This is redundant, I just want to make sure len works: self.assertEqual(len(keys), len(rec_dict)) #Make sure boolean evaluation works self.assertEqual(bool(keys), bool(rec_dict)) for key,id in zip(keys, ids): self.assertTrue(key in rec_dict) self.assertEqual(id, rec_dict[key].id) self.assertEqual(id, rec_dict.get(key).id) #Check non-existant keys, assert chr(0) not in keys, "Bad example in test" try: rec = rec_dict[chr(0)] raise ValueError("Accessing a non-existent key should fail") except KeyError: pass self.assertEqual(rec_dict.get(chr(0)), None) self.assertEqual(rec_dict.get(chr(0), chr(1)), chr(1)) if hasattr(dict, "iteritems"): #Python 2.x for key, rec in rec_dict.iteritems(): self.assertTrue(key in keys) self.assertTrue(isinstance(rec, SeqRecord)) self.assertTrue(rec.id in ids) #Now check non-defined methods... self.assertRaises(NotImplementedError, rec_dict.items) self.assertRaises(NotImplementedError, rec_dict.values) else: #Python 3 assert not hasattr(rec_dict, "iteritems") for key, rec in rec_dict.iteritems(): self.assertTrue(key in id_list) self.assertTrue(isinstance(rec, SeqRecord)) self.assertTrue(rec.id in ids) for rec in rec_dict.itervalues(): self.assertTrue(key in id_list) self.assertTrue(isinstance(rec, SeqRecord)) self.assertTrue(rec.id in ids) #Check the following fail self.assertRaises(NotImplementedError, rec_dict.popitem) self.assertRaises(NotImplementedError, rec_dict.pop, chr(0)) self.assertRaises(NotImplementedError, rec_dict.pop, chr(0), chr(1)) self.assertRaises(NotImplementedError, rec_dict.clear) self.assertRaises(NotImplementedError, rec_dict.__setitem__, "X", None) self.assertRaises(NotImplementedError, rec_dict.copy) self.assertRaises(NotImplementedError, rec_dict.fromkeys, [])
intersect=sets.set(self.ambiguous_values[seqsite]).intersection(sets.set(site[1]))
intersect = set(self.ambiguous_values[seqsite]).intersection(set(site[1]))
def constant(self,matrix=None,delete=[],exclude=[]): """Return a list with all constant characters.""" if not matrix: matrix=self.matrix undelete=[t for t in self.taxlabels if t in matrix and t not in delete] if not undelete: return None elif len(undelete)==1: return [x for x in range(len(matrix[undelete[0]])) if x not in exclude] # get the first sequence and expand all ambiguous values constant=[(x,self.ambiguous_values.get(n.upper(),n.upper())) for x,n in enumerate(matrix[undelete[0]].tostring()) if x not in exclude] for taxon in undelete[1:]: newconstant=[] for site in constant: #print '%d (paup=%d)' % (site[0],site[0]+1), seqsite=matrix[taxon][site[0]].upper() #print seqsite,'checked against',site[1],'\t', if seqsite==self.missing or (seqsite==self.gap and self.options['gapmode'].lower()=='missing') or seqsite==site[1]: # missing or same as before -> ok newconstant.append(site) elif seqsite in site[1] or site[1]==self.missing or (self.options['gapmode'].lower()=='missing' and site[1]==self.gap): # subset of an ambig or only missing in previous -> take subset newconstant.append((site[0],self.ambiguous_values.get(seqsite,seqsite))) elif seqsite in self.ambiguous_values: # is it an ambig: check the intersection with prev. values intersect=sets.set(self.ambiguous_values[seqsite]).intersection(sets.set(site[1])) if intersect: newconstant.append((site[0],''.join(intersect))) # print 'ok' #else: # print 'failed' #else: # print 'failed' constant=newconstant cpos=[s[0] for s in constant] return constant # return [x[0] for x in constant]
% ', '.join(sets.set(delete).difference(self.taxlabels)))
% ', '.join(set(delete).difference(self.taxlabels)))
def crop_matrix(self,matrix=None, delete=[], exclude=[]): """Return a matrix without deleted taxa and excluded characters.""" if not matrix: matrix=self.matrix if [t for t in delete if not self._check_taxlabels(t)]: raise NexusError('Unknown taxa: %s' \ % ', '.join(sets.set(delete).difference(self.taxlabels))) if exclude!=[]: undelete=[t for t in self.taxlabels if t in matrix and t not in delete] if not undelete: return {} m=[matrix[k].tostring() for k in undelete] zipped_m=zip(*m) sitesm=[s for i,s in enumerate(zipped_m) if i not in exclude] if sitesm==[]: return dict([(t,Seq('',self.alphabet)) for t in undelete]) else: zipped_sitesm=zip(*sitesm) m=[Seq(s,self.alphabet) for s in map(''.join,zipped_sitesm)] return dict(zip(undelete,m)) else: return dict([(t,matrix[t]) for t in self.taxlabels if t in matrix and t not in delete])
handle.close()
file.close()
def quicker_apply_on_multi_fasta(file, function, *args): """Apply a function on each sequence in a multiple FASTA file (OBSOLETE). file - filename of a FASTA format file function - the function you wish to invoke on each record *args - any extra arguments you want passed to the function This function will use quick_FASTA_reader to load every record in the FASTA file into memory as a list of tuples. For each record, it will call your supplied function with the record as a tuple of the name and sequence as strings (plus any supplied args). This function returns a list. For those records where your function returns a value, this is taken as a sequence and used to construct a FASTA format string. If your function never has a return value, this means quicker_apply_on_multi_fasta will return an empty list. """ try: f = globals()[function] except: raise NotImplementedError("%s not implemented" % function) entries = quick_FASTA_reader(file) results = [] for name, seq in entries: arguments = [seq] for arg in args: arguments.append(arg) result = f(*arguments) if result: results.append('>%s\n%s' % (name, result)) handle.close() return results
self.assert_("STEP 2 / 2 d" in stderrdata)
self.assert_("Progressive alignment ..." in stderrdata, stderrdata)
def test_Mafft_simple(self): """Simple round-trip through app with infile. Result passed to stdout. """ #Use a keyword argument at init, cmdline = MafftCommandline(mafft_exe, input=self.infile1) self.assertEqual(str(eval(repr(cmdline))), str(cmdline)) child = subprocess.Popen(str(cmdline), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=(sys.platform!="win32")) stdoutdata, stderrdata = child.communicate() return_code = child.returncode self.assertEqual(return_code, 0, "Got error code %i back from:\n%s" % (return_code, cmdline)) self.assert_(stdoutdata.startswith(">gi|1348912|gb|G26680|G26680")) self.assert_("STEP 2 / 2 d" in stderrdata) self.assert_("$#=0" not in stderrdata) del child
"Your description cannot be broken into nice lines!"
"Your description cannot be broken into nice lines!:\n%s" \ % repr(text)
def _split_multi_line(self, text, max_len): "Returns a list of strings.""" #TODO - Do the line spliting while preserving white space? text = text.strip() if len(text) < max_len: return [text]
start_end = identifier.rsplit("/",1)[1]
name, start_end = identifier.rsplit("/",1)
def _identifier_split(self, identifier): """Returns (name,start,end) string tuple from an identier.""" if identifier.find("/")!=-1: start_end = identifier.rsplit("/",1)[1] if start_end.count("-")==1: start, end = map(int, start_end.split("-")) name = identifier.split("/",1)[0] return (name, start, end) return (identifier, None, None)
name = identifier.split("/",1)[0]
def _identifier_split(self, identifier): """Returns (name,start,end) string tuple from an identier.""" if identifier.find("/")!=-1: start_end = identifier.rsplit("/",1)[1] if start_end.count("-")==1: start, end = map(int, start_end.split("-")) name = identifier.split("/",1)[0] return (name, start, end) return (identifier, None, None)
def values(self): """Would be a list of the SeqRecord objects, but not implemented. In general you can be indexing very very large files, with millions of sequences. Loading all these into memory at once as SeqRecord objects would (probably) use up all the RAM. Therefore we simply don't support this dictionary method. """ raise NotImplementedError("Due to memory concerns, when indexing a " "sequence file you cannot access all the " "records at once.") def items(self): """Would be a list of the (key, SeqRecord) tuples, but not implemented. In general you can be indexing very very large files, with millions of sequences. Loading all these into memory at once as SeqRecord objects would (probably) use up all the RAM. Therefore we simply don't support this dictionary method. """ raise NotImplementedError("Due to memory concerns, when indexing a " "sequence file you cannot access all the " "records at once.") def iteritems(self): """Iterate over the (key, SeqRecord) items.""" for key in self.__iter__(): yield key, self.__getitem__(key)
if hasattr(dict, "iteritems"): def values(self): """Would be a list of the SeqRecord objects, but not implemented. In general you can be indexing very very large files, with millions of sequences. Loading all these into memory at once as SeqRecord objects would (probably) use up all the RAM. Therefore we simply don't support this dictionary method. """ raise NotImplementedError("Due to memory concerns, when indexing a " "sequence file you cannot access all the " "records at once.") def items(self): """Would be a list of the (key, SeqRecord) tuples, but not implemented. In general you can be indexing very very large files, with millions of sequences. Loading all these into memory at once as SeqRecord objects would (probably) use up all the RAM. Therefore we simply don't support this dictionary method. """ raise NotImplementedError("Due to memory concerns, when indexing a " "sequence file you cannot access all the " "records at once.") def iteritems(self): """Iterate over the (key, SeqRecord) items.""" for key in self.__iter__(): yield key, self.__getitem__(key) else: def items(self): """Iterate over the (key, SeqRecord) items.""" for key in self.__iter__(): yield key, self.__getitem__(key) def values(self): """Iterate over the SeqRecord items.""" for key in self.__iter__(): yield self.__getitem__(key)
def values(self): """Would be a list of the SeqRecord objects, but not implemented.
Copes mixed case seuqneces, and with the ambiguous nucleotide S (G or C)
Copes mixed case sequences, and with the ambiguous nucleotide S (G or C)
def GC(seq): """Calculates G+C content, returns the percentage (float between 0 and 100). Copes mixed case seuqneces, and with the ambiguous nucleotide S (G or C) when counting the G and C content. The percentage is calculated against the full length, e.g.: >>> from Bio.SeqUtils import GC >>> GC("ACTGN") 40.0 Note that this will return zero for an empty sequence. """ try: gc = sum(map(seq.count,['G','C','g','c','S','s'])) return gc*100.0/len(seq) except ZeroDivisionError: return 0.0
start_end = identifier.split("/",1)[1]
start_end = identifier.rsplit("/",1)[1]
def _identifier_split(self, identifier): """Returns (name,start,end) string tuple from an identier.""" if identifier.find("/")!=-1: start_end = identifier.split("/",1)[1] if start_end.count("-")==1: start, end = map(int, start_end.split("-")) name = identifier.split("/",1)[0] return (name, start, end) return (identifier, None, None)
f.write("POP\n")
start_pop = True
def remove_population(self, pos, fname): """Removes a population (by position).
f.write("POP\n")
def remove_population(self, pos, fname): """Removes a population (by position).
clade.node_id = elem.text and elem.text.strip() or None
clade.node_id = PX.Id(elem.text.strip(), elem.attrib.get('provider'))
def _parse_clade(self, parent): """Parse a Clade node and its children, recursively.""" clade = PX.Clade(**parent.attrib) if clade.branch_length is not None: clade.branch_length = float(clade.branch_length) # NB: Only evaluate nodes at the current level tag_stack = [] for event, elem in self.context: namespace, tag = split_namespace(elem.tag) if event == 'start': if tag == 'clade': clade.clades.append(self._parse_clade(elem)) continue if tag == 'taxonomy': clade.taxonomies.append(self._parse_taxonomy(elem)) continue if tag == 'sequence': clade.sequences.append(self._parse_sequence(elem)) continue if tag in self._clade_tracked_tags: tag_stack.append(tag) if event == 'end': if tag == 'clade': elem.clear() break if tag != tag_stack[-1]: continue tag_stack.pop() # Handle the other non-recursive children if tag in self._clade_list_types: getattr(clade, self._clade_list_types[tag]).append( getattr(self, tag)(elem)) elif tag in self._clade_complex_types: setattr(clade, tag, getattr(self, tag)(elem)) elif tag == 'branch_length': # NB: possible collision with the attribute if clade.branch_length is not None: raise PhyloXMLError( 'Attribute branch_length was already set ' 'for this Clade.') clade.branch_length = _float(elem.text) elif tag == 'width': clade.width = _float(elem.text) elif tag == 'name': clade.name = collapse_wspace(elem.text) elif tag == 'node_id': clade.node_id = elem.text and elem.text.strip() or None elif namespace != NAMESPACES['phy']: clade.other.append(self.other(elem, namespace, tag)) elem.clear() else: raise PhyloXMLError('Misidentified tag: ' + tag) return clade
Roche SFF indices use base 255 not 256, meaning we see bytes in range the range 0 to 254 only. This appears to be so that byte 0xFF (character 255) can be used as a marker character to separate entries (required if the read name lengths vary). Note that since only four bytes are used for the read offset, this is limited to 255^4 bytes (nearly 4GB). If you try to use the Roche sfffile tool to combined SFF files beyound this limit, they issue a warning and ommit the index (and manifest).
Roche SFF indices use base 255 not 256, meaning we see bytes in range the range 0 to 254 only. This appears to be so that byte 0xFF (character 255) can be used as a marker character to separate entries (required if the read name lengths vary). Note that since only four bytes are used for the read offset, this is limited to 255^4 bytes (nearly 4GB). If you try to use the Roche sfffile tool to combine SFF files beyound this limit, they issue a warning and omit the index (and manifest).
def _sff_read_roche_index(handle): """Reads any existing Roche style read index provided in the SFF file (PRIVATE). Will use the handle seek/tell functions. This works on ".srt1.00" and ".mft1.00" style Roche SFF index blocks. Roche SFF indices use base 255 not 256, meaning we see bytes in range the range 0 to 254 only. This appears to be so that byte 0xFF (character 255) can be used as a marker character to separate entries (required if the read name lengths vary). Note that since only four bytes are used for the read offset, this is limited to 255^4 bytes (nearly 4GB). If you try to use the Roche sfffile tool to combined SFF files beyound this limit, they issue a warning and ommit the index (and manifest). """ number_of_reads, header_length, index_offset, index_length, xml_offset, \ xml_size, read_index_offset, read_index_size = _sff_find_roche_index(handle) #Now parse the read index... handle.seek(read_index_offset) fmt = ">5B" for read in range(number_of_reads): #TODO - Be more aware of when the index should end? data = handle.read(6) while True: more = handle.read(1) if not more: raise ValueError("Premature end of file!") data += more if more == _flag: break assert data[-1:] == _flag, data[-1:] name = _bytes_to_string(data[:-6]) off4, off3, off2, off1, off0 = struct.unpack(fmt, data[-6:-1]) offset = off0 + 255*off1 + 65025*off2 + 16581375*off3 if off4: #Could in theory be used as a fifth piece of offset information, #i.e. offset =+ 4228250625L*off4, but testing the Roche tools this #is not the case. They simple don't support such large indexes. raise ValueError("Expected a null terminator to the read name.") yield name, offset if handle.tell() != read_index_offset + read_index_size: raise ValueError("Problem with index length? %i vs %i" \ % (handle.tell(), read_index_offset + read_index_size))
"to store in the Roche SFF index structure. No index " "block will be recorded." % (name, offset))
"to store in the Roche SFF index structure. No " "index block will be recorded." % (name, offset))
def write_record(self, record): """Write a single additional record to the output file.
if type(seq)!=type("aa"): seq=seq.tostring()
def gcg(seq): """Returns the GCG checksum (int) for a sequence (string or Seq object). Given a nucleotide or amino-acid secuence (or any string), returns the GCG checksum (int). Checksum used by GCG program. seq type = str. Based on BioPerl GCG_checksum. Adapted by Sebastian Bassi with the help of John Lenton, Pablo Ziliani, and Gabriel Genellina. All sequences are converted to uppercase """ index = checksum = 0 if type(seq)!=type("aa"): seq=seq.tostring() for char in seq: index += 1 checksum += index * ord(char.upper()) if index == 57: index = 0 return checksum % 10000
if type(seq)!=type("aa"): seq=seq.tostring().upper() else: seq=seq.upper() m.update(seq)
def seguid(seq): """Returns the SEGUID (string) for a sequence (string or Seq object). Given a nucleotide or amino-acid secuence (or any string), returns the SEGUID string (A SEquence Globally Unique IDentifier). seq type = str. For more information about SEGUID, see: http://bioinformatics.anl.gov/seguid/ DOI: 10.1002/pmic.200600032 """ try: #Python 2.5 sha1 is in hashlib import hashlib m = hashlib.sha1() except: #For older versions import sha m = sha.new() import base64 if type(seq)!=type("aa"): seq=seq.tostring().upper() else: seq=seq.upper() m.update(seq) try: #For Python 2.5 return base64.b64encode(m.digest()).rstrip("=") except: #For older versions import os #Note: Using os.linesep doesn't work on Windows, #where os.linesep= "\r\n" but the encoded string #contains "\n" but not "\r\n" return base64.encodestring(m.digest()).replace("\n","").rstrip("=")
seq = seq.tostring() except AttributeError: pass m.update(seq.upper().encode()) try: return base64.encodebytes(m.digest()).decode().replace("\n","").rstrip("=") except AttributeError: pass try:
def seguid(seq): """Returns the SEGUID (string) for a sequence (string or Seq object). Given a nucleotide or amino-acid secuence (or any string), returns the SEGUID string (A SEquence Globally Unique IDentifier). seq type = str. For more information about SEGUID, see: http://bioinformatics.anl.gov/seguid/ DOI: 10.1002/pmic.200600032 """ try: #Python 2.5 sha1 is in hashlib import hashlib m = hashlib.sha1() except: #For older versions import sha m = sha.new() import base64 if type(seq)!=type("aa"): seq=seq.tostring().upper() else: seq=seq.upper() m.update(seq) try: #For Python 2.5 return base64.b64encode(m.digest()).rstrip("=") except: #For older versions import os #Note: Using os.linesep doesn't work on Windows, #where os.linesep= "\r\n" but the encoded string #contains "\n" but not "\r\n" return base64.encodestring(m.digest()).replace("\n","").rstrip("=")
self.assertEqual(self.ctrl.get_alleles(0,"Locus3"), [3, 20])
self.assertEqual(set(self.ctrl.get_alleles(0,"Locus3")), set([3, 20]))
def test_get_alleles(self): """Test get alleles. """ self.assertEqual(self.ctrl.get_alleles(0,"Locus3"), [3, 20])
dx = float(max_d - values[-1]) / (values[-1] - values[-2])
dx = len(values) > 1 and float(max_d - values[-1]) / \ (values[-1] - values[-2]) or max_d
def field_size(self, axis): size = {'x': 'width', 'y': 'height'}[axis] side = {'x': 'right', 'y': 'top'}[axis] values = getattr(self, 'get_%s_values' % axis)() max_d = self.data_max(axis) dx = float(max_d - values[-1]) / (values[-1] - values[-2]) graph_size = getattr(self, 'graph_%s' % size) side_font = getattr(self, '%s_font' % side) side_align = getattr(self, '%s_align' % side) result = (float(graph_size) - self.font_size*2*side_font) / \ (len(values) + dx - side_align) return result
lisp.push_mark()
marker_ring = self.get('marker_ring') marker = lisp.point_marker() lisp.ring_insert(marker_ring, marker) def pop_mark(self): marker_ring = self.get('marker_ring') if lisp.ring_empty_p(marker_ring): self.message("There are no more marked buffers in \ the rope-marker-ring") else: oldbuf = lisp.current_buffer() marker = lisp.ring_remove(marker_ring, 0) marker_buffer = lisp.marker_buffer(marker) if marker_buffer is None: lisp.message("The marked buffer has been deleted") return marker_point = lisp.marker_position(marker) lisp.set_buffer(marker_buffer) lisp.goto_char(marker_point) lisp.set_marker(marker, None, None) if not lisp.eq(oldbuf, marker_buffer): lisp.switch_to_buffer(marker_buffer)
def push_mark(self): lisp.push_mark()
conf.registerPlugin('Bantracker', True)
Bantracker = conf.registerPlugin('Bantracker', True)
def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default)
output("%r is an invalid value, it must be an integer or float greater or equal to 0", review)
output("%r is an invalid value, it must be an integer or float greater or equal to 0" % review)
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.request.review._default))
from supybot.question import yn, something, output
from supybot.questions import yn, something, output
def configure(advanced): from supybot.question import yn, something, output import sqlite import re import os from supybot.utils.str import format def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default) conf.registerPlugin('Bantracker', True) def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default)) try: review = float(review) if review < 0: raise TypeError except TypeError: output("%r is an invalid value, it must be an integer or float greater or equal to 0", review) return getReviewTime() else: return review enabled = yn("Enable Bantracker for all channels?") database = something("Location of the Bantracker database", default=conf.supybot.directories.data.dirize('bans.db')) bansite = anything("URL of the Bantracker web interface, without the 'bans.cgi'. (leave this blank if you don't want to run a web server)") request = yn("Enable review and comment requests from bot?", default=False) if request and advanced: output("Which types would you like the bot to request comments for?") output(format("The available request types are %L", type)) types = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.type._default)) type = set([]) for name in re.split(r',?\s+', types): name = name.lower() if name in ('removal', 'ban', 'quiet'): type.append(name) output("Which nicks should be bot not requets comments from?") output("Is case insensitive and wildcards '*' and '?' are accepted.") ignores = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.ignore._default)) ignore = set([]) for name in re.split(r',?\s+', ignores): name = name.lower() ignore.add(name) output("You can set the comment and review requests for some nicks to be forwarded to specific nicks/channels") output("Which nicks should these requests be forwarded for?") output("Is case insensitive and wildcards '*' and '?' are accepted.") forwards = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.forward._default)) forward = set([]) for name in re.split(r',?\s+', forwards): name = name.lower() forward.add(name) output("Which nicks/channels should the requests be forwarded to?") output("Is case insensitive and wildcards '*' and '?' are accepted.") channels_i = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.channels._default)) channels = set([]) for name in re.split(r',?\s+', channel_i): name = name.lower() channels.add(name) review = getReviewTime() else: type = Bantracker.type._default ignore = Bantracker.ignore._default forward = Bantracker.forward._default channels = Bantracker.channels._default review = Bantracker.review._default Bantracker.enabled.setValue(enabled) Bantracker.database.setValue(database) Bantracker.bansite.setValue(bansite) Bantracker.request.setValue(request) Bantracker.type.setValue(type) Bantracker.ignore.setValue(ignore) Bantracker.forward.setValue(forward) Bantracker.channels.setValue(channels) Bantracker.review.setValue(review) # Create the initial database db_file = Bantracker.database() if not db_file: db_file = conf.supybot.directories.data.dirize('bans.db') output("supybot.plugins.Bantracker.database will be set to %r" % db_file) Bantracker.database.setValue(db_file) if os.path.exists(db_file): return output("Creating an initial database in %r" % db_file) con = sqlite.connect(db_file) cur = con.cursor() try: con.begin() cur.execute("""CREATE TABLE 'bans' ( id INTEGER PRIMARY KEY, channel VARCHAR(30) NOT NULL, mask VARCHAR(100) NOT NULL, operator VARCHAR(30) NOT NULL, time VARCHAR(300) NOT NULL, removal DATETIME, removal_op VARCHAR(30), log TEXT
review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.request.review._default))
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
output(format("The available request types are %L", type)) types = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.type._default))
output(format("The available request types are %L", Bantracker.request.type._default)) types = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.type._default))
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
type.append(name)
type.add(name)
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
ignores = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.ignore._default))
ignores = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.ignore._default))
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
forwards = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.forward._default))
forwards = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.forward._default))
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
channels_i = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.channels._default))
channels_i = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.forward._default))
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
for name in re.split(r',?\s+', channel_i):
for name in re.split(r',?\s+', channels_i):
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
type = Bantracker.type._default ignore = Bantracker.ignore._default forward = Bantracker.forward._default channels = Bantracker.channels._default review = Bantracker.review._default
type = Bantracker.request.type._default ignore = Bantracker.request.ignore._default forward = Bantracker.request.forward._default channels = Bantracker.request.forward.channels._default review = Bantracker.request.review._default
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
Bantracker.type.setValue(type) Bantracker.ignore.setValue(ignore) Bantracker.forward.setValue(forward) Bantracker.channels.setValue(channels) Bantracker.review.setValue(review)
Bantracker.request.type.setValue(type) Bantracker.request.ignore.setValue(ignore) Bantracker.request.forward.setValue(forward) Bantracker.request.forward.channels.setValue(channels) Bantracker.request.review.setValue(review)
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
con.begin()
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
a0 = np.array([1, 2, 3, 4, 5, 6, nan, nan, 7, 8, 9]) a1 = np.arange(10) a2 = np.array([[9.0, 3.0, nan, nan, 9.0, nan], [1.0, 1.0, 1.0, nan, nan, nan], [2.0, 2.0, 0.1, nan, 1.0, nan], [3.0, 9.0, 2.0, nan, nan, nan], [4.0, 4.0, 3.0, 9.0, 2.0, nan], [5.0, 5.0, 4.0, 4.0, nan, nan]]) a3 = np.arange(12).reshape(3,4) a4 = np.random.rand(3,4) a5 = np.arange(60).reshape(3, 4, 5) a6 = np.random.rand(3, 4, 5) a7 = np.array([nan, nan, nan]) a8 = np.array([1, np.nan, np.inf, np.NINF]) a9 = np.arange(5, dtype=np.int32) a10 = np.arange(10, dtype=np.int32).reshape(2, 5) a11 = np.arange(24, dtype=np.int32).reshape(2, 3, 4) arrs = [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11]
def unit_maker(func, func0): "Test that ny.nanxxx gives the same output as np.." a0 = np.array([1, 2, 3, 4, 5, 6, nan, nan, 7, 8, 9]) a1 = np.arange(10) a2 = np.array([[9.0, 3.0, nan, nan, 9.0, nan], [1.0, 1.0, 1.0, nan, nan, nan], [2.0, 2.0, 0.1, nan, 1.0, nan], [3.0, 9.0, 2.0, nan, nan, nan], [4.0, 4.0, 3.0, 9.0, 2.0, nan], [5.0, 5.0, 4.0, 4.0, nan, nan]]) a3 = np.arange(12).reshape(3,4) a4 = np.random.rand(3,4) a5 = np.arange(60).reshape(3, 4, 5) a6 = np.random.rand(3, 4, 5) a7 = np.array([nan, nan, nan]) a8 = np.array([1, np.nan, np.inf, np.NINF]) a9 = np.arange(5, dtype=np.int32) a10 = np.arange(10, dtype=np.int32).reshape(2, 5) a11 = np.arange(24, dtype=np.int32).reshape(2, 3, 4) arrs = [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11] msg = '\nfunc %s | input %s (%s) | shape %s | axis %s\n' for i, arr in enumerate(arrs): for axis in range(-arr.ndim, arr.ndim) + [None]: actual = func(arr, axis=axis) desired = func0(arr, axis=axis) tup = (func.__name__, 'a'+str(i), str(arr.dtype), str(arr.shape), str(axis)) err_msg = msg % tup assert_array_equal(actual, desired, err_msg) err_msg += '\n dtype mismatch %s %s' if hasattr(actual, 'dtype') or hasattr(desired, 'dtype'): da = actual.dtype dd = desired.dtype assert_equal(da, dd, err_msg % (da, dd))
for i, arr in enumerate(arrs):
msg += '\nInput array:\n%s\n' for i, arr in enumerate(arrays()):
def unit_maker(func, func0): "Test that ny.nanxxx gives the same output as np.." a0 = np.array([1, 2, 3, 4, 5, 6, nan, nan, 7, 8, 9]) a1 = np.arange(10) a2 = np.array([[9.0, 3.0, nan, nan, 9.0, nan], [1.0, 1.0, 1.0, nan, nan, nan], [2.0, 2.0, 0.1, nan, 1.0, nan], [3.0, 9.0, 2.0, nan, nan, nan], [4.0, 4.0, 3.0, 9.0, 2.0, nan], [5.0, 5.0, 4.0, 4.0, nan, nan]]) a3 = np.arange(12).reshape(3,4) a4 = np.random.rand(3,4) a5 = np.arange(60).reshape(3, 4, 5) a6 = np.random.rand(3, 4, 5) a7 = np.array([nan, nan, nan]) a8 = np.array([1, np.nan, np.inf, np.NINF]) a9 = np.arange(5, dtype=np.int32) a10 = np.arange(10, dtype=np.int32).reshape(2, 5) a11 = np.arange(24, dtype=np.int32).reshape(2, 3, 4) arrs = [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11] msg = '\nfunc %s | input %s (%s) | shape %s | axis %s\n' for i, arr in enumerate(arrs): for axis in range(-arr.ndim, arr.ndim) + [None]: actual = func(arr, axis=axis) desired = func0(arr, axis=axis) tup = (func.__name__, 'a'+str(i), str(arr.dtype), str(arr.shape), str(axis)) err_msg = msg % tup assert_array_equal(actual, desired, err_msg) err_msg += '\n dtype mismatch %s %s' if hasattr(actual, 'dtype') or hasattr(desired, 'dtype'): da = actual.dtype dd = desired.dtype assert_equal(da, dd, err_msg % (da, dd))
str(axis))
str(axis), arr)
def unit_maker(func, func0): "Test that ny.nanxxx gives the same output as np.." a0 = np.array([1, 2, 3, 4, 5, 6, nan, nan, 7, 8, 9]) a1 = np.arange(10) a2 = np.array([[9.0, 3.0, nan, nan, 9.0, nan], [1.0, 1.0, 1.0, nan, nan, nan], [2.0, 2.0, 0.1, nan, 1.0, nan], [3.0, 9.0, 2.0, nan, nan, nan], [4.0, 4.0, 3.0, 9.0, 2.0, nan], [5.0, 5.0, 4.0, 4.0, nan, nan]]) a3 = np.arange(12).reshape(3,4) a4 = np.random.rand(3,4) a5 = np.arange(60).reshape(3, 4, 5) a6 = np.random.rand(3, 4, 5) a7 = np.array([nan, nan, nan]) a8 = np.array([1, np.nan, np.inf, np.NINF]) a9 = np.arange(5, dtype=np.int32) a10 = np.arange(10, dtype=np.int32).reshape(2, 5) a11 = np.arange(24, dtype=np.int32).reshape(2, 3, 4) arrs = [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11] msg = '\nfunc %s | input %s (%s) | shape %s | axis %s\n' for i, arr in enumerate(arrs): for axis in range(-arr.ndim, arr.ndim) + [None]: actual = func(arr, axis=axis) desired = func0(arr, axis=axis) tup = (func.__name__, 'a'+str(i), str(arr.dtype), str(arr.shape), str(axis)) err_msg = msg % tup assert_array_equal(actual, desired, err_msg) err_msg += '\n dtype mismatch %s %s' if hasattr(actual, 'dtype') or hasattr(desired, 'dtype'): da = actual.dtype dd = desired.dtype assert_equal(da, dd, err_msg % (da, dd))
name = py3_b(name)
def _inotify_event(self, mask, name, target=None): """ Callback for inotify. """ name = py3_b(name) if mask & INotify.MODIFY and self._bursthandler.is_growing(name): # A file was modified. Do this check as fast as we can because the # events may come in bursts when a file is just copied. In this case # a timer is already active and we can return. It still uses too # much CPU time in the burst, but there is nothing we can do about # it. return True
'beacon.id': 'kaa.beacon.root-' + get_machine_uuid(),
'beacon.id': 'root-' + get_machine_uuid(),
def __init__(self, dbdir, scheduler=None): log.info('start beacon') try: self.ipc = kaa.rpc.Server('beacon') except IOError, e: kaa.beacon.thumbnail.thumbnail.disconnect() log.error('beacon: %s' % e) time.sleep(0.1) sys.exit(0)
'zope.container',
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
for user in self.users:
for user in list(self.users):
def watchConnection(self, connection, sockThread): sockThread.join() if(connection.closed): log(self, "%s's thread ended, connection was marked closed" % connection.user, 3) else: log(self, "%s's thread ended unexpectedly, cleaning up" % connection.user, 3) # send a quit message if(connection.type == self.IRC_Connection.CLIENT): msg = self.IRC_Message("QUIT :Lost connection") msg.prefix = connection.user.fullUser() self.localBroadcast(msg, connection.user, connection) # this method should never attempt to send messages to the dead connection self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeUser(connection.user) elif(connection.type == self.IRC_Connection.SERVER): for user in self.users: if(user.connection == connection): # any user which was connected to us through the lost server must quit msg = self.IRC_Message("QUIT :Lost in netsplit") msg.prefix = user.fullUser() self.localBroadcast(msg, user, connection) self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeUser(user) for server in self.servers: if(server.connection == connection): # this removes both the lost server, and all servers behind it msg = self.IRC_Message("SQUIT :Lost in netsplit") msg.prefix = self.hostname msg.params = [server.hostname] self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeServer(server) else: # that was fast :P connection.sock.close() self.connections.remove(connection)
for server in self.servers:
for server in list(self.servers):
def watchConnection(self, connection, sockThread): sockThread.join() if(connection.closed): log(self, "%s's thread ended, connection was marked closed" % connection.user, 3) else: log(self, "%s's thread ended unexpectedly, cleaning up" % connection.user, 3) # send a quit message if(connection.type == self.IRC_Connection.CLIENT): msg = self.IRC_Message("QUIT :Lost connection") msg.prefix = connection.user.fullUser() self.localBroadcast(msg, connection.user, connection) # this method should never attempt to send messages to the dead connection self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeUser(connection.user) elif(connection.type == self.IRC_Connection.SERVER): for user in self.users: if(user.connection == connection): # any user which was connected to us through the lost server must quit msg = self.IRC_Message("QUIT :Lost in netsplit") msg.prefix = user.fullUser() self.localBroadcast(msg, user, connection) self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeUser(user) for server in self.servers: if(server.connection == connection): # this removes both the lost server, and all servers behind it msg = self.IRC_Message("SQUIT :Lost in netsplit") msg.prefix = self.hostname msg.params = [server.hostname] self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeServer(server) else: # that was fast :P connection.sock.close() self.connections.remove(connection)
rmChans = list() for channel in user.channels: rmChans.append(channel) for channel in rmChans:
for channel in list(user.channels):
def removeUser(self, user): # perform all the cleanup that needs to be done to get a user out of the system log(self, "Removing %s from server" % user, 3) if(user in self.users): self.users.remove(user) else: log(self, "WARNING: %s wasn't in userlist" % user, 3) log(self, "Removing %s from channels %s" % (user, user.channels), 3) rmChans = list() for channel in user.channels: rmChans.append(channel) for channel in rmChans: channel.removeUser(user) if(user.connection.type == self.IRC_Connection.CLIENT): user.connection.sock.close() user.connection.closed = True self.connections.remove(user.connection)
connection.send(msg.toString()) msg = self.IRC_Message("005 :are supported by this server") msg.prefix = self.hostname msg.params = [ connection.user.nick, "CHANTYPES=%s" % (self.chan_types), \ "PREFIX=(%s)%s" % (self.cuser_modes, self.cuser_sigils), \ "CHANMODES=%s" % (self.chan_modes), \ "NETWORK=%s" % (self.network), \ "CASEMAPPING=ascii", \ ]
def sendMOTD(self, connection): msg = self.IRC_Message("001 :Welcome, %s" % connection.user.nick) # WTF: Unknown reply type msg.params.append(connection.user.nick) msg.prefix = self.hostname # stick this in there somewhere: CHANTYPES=#&+ PREFIX=(Naohv)$&@%+ CHANMODES=be,k,l,cimnpqstAKMNORS STATUSMSG=$&@%+ NETWORK=Nadru connection.send(msg.toString()) msg = self.IRC_Message("375 :- %s Message of the day -" % self.hostname) # RPL_MOTDSTART msg.params.append(connection.user.nick) msg.prefix = self.hostname connection.send(msg.toString()) msg = self.IRC_Message("372 :- awesome text goes here") # RPL_MOTD msg.params.append(connection.user.nick) msg.prefix = self.hostname connection.send(msg.toString()) msg = self.IRC_Message("376 :End of /MOTD command") # RPL_ENDOFMOTD msg.params.append(connection.user.nick) msg.prefix = self.hostname connection.send(msg.toString())
if(connection.type == self.IRC_Connection.CLIENT): self.removeUser(connection.user) else: self.removeServer(connection.user)
self.removeServer(connection.user) else: connection.sock.close() self.connections.remove(connection)
def watchConnection(self, connection, sockThread): sockThread.join() if(not connection.closed): # send a quit message if(connection.type == self.IRC_Connection.CLIENT): msg = self.IRC_Message("QUIT :Lost connection") msg.prefix = connection.user.fullUser() self.localBroadcast(msg, connection.user, connection) # this method should never attempt to send messages to the dead connection self.broadcast(msg, connection, self.IRC_Connection.SERVER) elif(connection.type == self.IRC_Connection.SERVER): for user in self.users: if(user.connection == connection): # any user which was connected to us through the lost server must quit msg = self.IRC_Message("QUIT :Lost in netsplit") msg.prefix = user.fullUser() self.localBroadcast(msg, user, connection) self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeUser(user) for server in self.servers: if(server.connection == connection): msg = self.IRC_Message("SQUIT :Lost in netsplit") msg.prefix = self.hostname msg.params = [sever.hostname] self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeServer(server) # get rid of the connection and associated users (server or client) if(connection.type == self.IRC_Connection.CLIENT): self.removeUser(connection.user) else: self.removeServer(connection.user)
log(self, "WARNING: Channel %s wasn't %s's channel list" % (self, user), 3)
log(self, "WARNING: Channel %s wasn't in %s's channel list" % (self, user), 3)
def removeUser(self, user): log(self, "Attempting to remove %s from %s" % (user, self), 3) for cuser in self.users: if(cuser.user == user): self.users.remove(cuser) log(self, "Removed %s from %s's userlist" % (cuser, self), 3) if(self in user.channels): user.channels.remove(self) log(self, "Removed %s from %s's channel list" % (self, user), 3) else: log(self, "WARNING: Channel %s wasn't %s's channel list" % (self, user), 3)
userMsg.prefix = user.nick
userMsg.prefix = user.fullUser()
def sendServerData(self, connection): # respond with our own PASS, SERVER combo passMsg = self.IRC_Message("PASS") passMsg.prefix = self.hostname passMsg.params = [self.prefs["server_password"]] connection.send(passMsg.toString()) servMsg = self.IRC_Message("SERVER") servMsg.params = [self.hostname, "1"] servMsg.trail = self.info connection.send(servMsg.toString()) # now we must synchronize all of our data with this new server for server in self.servers: servMsg = self.IRC_Message("SERVER") servMsg.params = [server.hostname, str(server.hopcount)] servMsg.trail = server.info servMsg.prefix = self.hostname connection.send(servMsg.toString()) for user in self.users: # NICK, USER, MODE, JOIN userMsg = self.IRC_Message("NICK") userMsg.params = [user.nick, "1"] connection.send(userMsg.toString()) userMsg = self.IRC_Message("USER") userMsg.prefix = user.nick userMsg.params = [user.username, user.hostname, user.servername] userMsg.trail = user.realname connection.send(userMsg.toString()) userMsg = self.IRC_Message("MODE") userMsg.prefix = self.hostname userMsg.params = [user.nick, str(user.flags)] connection.send(userMsg.toString()) userMsg = self.IRC_Message("JOIN") channelNames = list() channelKeys = list() channelModes = list() for channel in user.channels: if(channel.name.startswith("&")): # don't sync local channels continue channelNames.append(channel.name) channelKeys.append(channel.key) channelModes.append(channel.findCUser(user.nick).flags) userMsg.params = [','.join(channelNames), ','.join(channelKeys)] userMsg.prefix = user.nick connection.send(userMsg.toString()) for channel in range(len(channelModes)): userMsg = self.IRC_Message("MODE") userMsg.prefix = self.hostname userMsg.params = [channelNames[channel], str(channelModes[channel])] for i in range(len(userMsg.params[1]) - 1): userMsg.params.append(user.nick) connection.send(userMsg.toString()) for channel in self.channels: if(channel.name.startswith("&")): # don't sync local channels continue chanMsg = self.IRC_Message("MODE") chanMsg.prefix = self.hostname chanMsg.params = [channel.name, str(channel.flags)] if('k' in channel.flags): chanMsg.params.append(channel.key) for ban in channel.bans: chanMsg.params[1] += 'b' chanMsg.params.append(ban) connection.send(chanMsg.toString())
self.users.append(self.Channel_User(user))
cuser = self.Channel_User(user) self.users.append(cuser) log(self, "Added cuser %s to %s's userlist" % (cuser, self), 3)
def addUser(self, user): if(self.findCUser(user.nick) == None): self.users.append(self.Channel_User(user)) user.channels.append(self) return True return False
user.channels.remove(self)
log(self, "Removed %s from %s's userlist" % (cuser, self), 3) if(self in user.channels): user.channels.remove(self) log(self, "Removed %s from %s's channel list" % (self, user), 3) else: log(self, "WARNING: Channel %s wasn't %s's channel list" % (self, user), 3)
def removeUser(self, user): for cuser in self.users: if(cuser.user == user): self.users.remove(cuser) user.channels.remove(self)
if(not connection.closed):
if(connection.closed): log(self, "%s's thread ended, connection was marked closed" % connection.user, 3) else: log(self, "%s's thread ended unexpectedly, cleaning up" % connection.user, 3)
def watchConnection(self, connection, sockThread): sockThread.join() if(not connection.closed): # send a quit message if(connection.type == self.IRC_Connection.CLIENT): msg = self.IRC_Message("QUIT :Lost connection") msg.prefix = connection.user.fullUser() self.localBroadcast(msg, connection.user, connection) # this method should never attempt to send messages to the dead connection self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeUser(connection.user) elif(connection.type == self.IRC_Connection.SERVER): for user in self.users: if(user.connection == connection): # any user which was connected to us through the lost server must quit msg = self.IRC_Message("QUIT :Lost in netsplit") msg.prefix = user.fullUser() self.localBroadcast(msg, user, connection) self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeUser(user) for server in self.servers: if(server.connection == connection): # this removes both the lost server, and all servers behind it msg = self.IRC_Message("SQUIT :Lost in netsplit") msg.prefix = self.hostname msg.params = [server.hostname] self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeServer(server) else: # that was fast :P connection.sock.close() self.connections.remove(connection)
if(connection.user.nick):
if(connection.user and connection.user.nick):
def checkClientNick(self, connection, nick): if(self.findUser(nick)): # check that nobody's taken the nick already errmsg = self.IRC_Message("433 :Nickname is already in use") errmsg.prefix = self.hostname if(connection.user.nick): errmsg.params = [connection.user.nick, nick] else: errmsg.params = ["*", nick] connection.send(errmsg.toString()) return False for char in IRC_Server.cuser_sigils + IRC_Server.chan_types + "!@": #need to include these symbols, as they're nick!user@host delimiters if char in nick: return False # nick is valid return True
userMsg.prefix = self.hostname
userMsg.prefix = user.nick
def sendServerData(self, connection): # respond with our own PASS, SERVER combo passMsg = self.IRC_Message("PASS") passMsg.prefix = self.hostname passMsg.params = [self.prefs["server_password"]] connection.send(passMsg.toString()) servMsg = self.IRC_Message("SERVER") servMsg.params = [self.hostname, "1"] servMsg.trail = self.info connection.send(servMsg.toString()) # now we must synchronize all of our data with this new server for server in self.servers: servMsg = self.IRC_Message("SERVER") servMsg.params = [server.hostname, str(server.hopcount)] servMsg.trail = server.info servMsg.prefix = self.hostname connection.send(servMsg.toString()) for user in self.users: # NICK, USER, MODE, JOIN userMsg = self.IRC_Message("NICK") userMsg.params = [user.nick, "1"] connection.send(userMsg.toString()) userMsg = self.IRC_Message("USER") userMsg.prefix = self.hostname userMsg.params = [user.username, user.hostname, user.servername] userMsg.trail = user.realname connection.send(userMsg.toString()) userMsg = self.IRC_Message("MODE") userMsg.prefix = self.hostname userMsg.params = [user.nick, str(user.flags)] connection.send(userMsg.toString()) userMsg = self.IRC_Message("JOIN") channelNames = list() channelKeys = list() channelModes = list() for channel in user.channels: channelNames.append(channel.name) channelKeys.append(channel.key) channelModes.append(channel.findCUser(user.nick).flags) userMsg.params = [','.join(channelNames), ','.join(channelKeys)] userMsg.prefix = user.nick connection.send(userMsg.toString()) for channel in range(len(channelModes)): userMsg = self.IRC_Message("MODE") userMsg.prefix = self.hostname userMsg.params = [channelNames[channel], str(channelModes[channel]), user.nick] connection.send(userMsg.toString()) for channel in self.channels: chanMsg = self.IRC_Message("MODE") chanMsg.prefix = self.hostname chanMsg.params = [channel.name, str(channel.flags)] connection.send(chanMsg.toString())
logging = newPrefs.pop(pref)
logging = int(newPrefs[pref])
def readPrefs(self, filename="CCServer.conf"): global logging log(self, "reading %s" % filename) prefsFile = file(filename, 'r') prefsData = prefsFile.read() prefsFile.close() newPrefs = parseToDict(prefsData, ':', '\n') for pref in newPrefs: newPrefs[pref] = newPrefs[pref].strip() if(newPrefs[pref].isdigit()): newPrefs[pref] = int(newPrefs[pref]) if(pref == "log_level"): logging = newPrefs.pop(pref) self.prefs.update(newPrefs) self.readWelcome() self.readWordList()
filename = part["headers"]["Content-Disposition"]["filename"] newFileURI = "images/%s" % filename[1:-1]
filename = part["headers"]["Content-Disposition"]["filename"][1:-1] if(filename == ""): log(self, "empty filename", 3) self.writeHTTP(sock, 400, {}, "empty filename") return newFileURI = "images/%s" % filename
def handleReq(self, sock, addr, method, resource, protocol, headers, body, getOptions): #lazy parsing of escape sequences :P resource = resource.replace("%20", ' ') if(self.redirects.has_key(resource)): self.writeHTTP(sock, 301, {"Location": self.redirects[resource]}, "301 Redirect") log(self, "redirected %s from %s to %s" % (addr, resource, self.redirects[resource]), 3) return #resExt = resource.rsplit('.', 1) resExt = resource.split('.') if(len(resExt) > 1): extension = resExt[-1].lower() if(self.mimeTypes.has_key(extension)): mimeType = self.mimeTypes[extension] else: log(self, "denied request for %s" % resource, 3) self.writeHTTP(sock, 403) return else: mimeType = "application/octet-stream" if(method == "GET" and resource == "/web-socket"): if(headers.has_key("WebSocket-Protocol")): # protocol draft 75 responseHeaders = [ \ ("Upgrade", "WebSocket"), \ ("Connection", "Upgrade"), \ ("WebSocket-Origin", headers["Origin"]), \ ("WebSocket-Location", "ws://%s/web-socket" % headers["Host"]), \ ("WebSocket-Protocol", headers["WebSocket-Protocol"]), \ ] log(self, "got WebSocket from (%s, %s)" % addr, 3) self.writeHTTP(sock, 101, {}, None, responseHeaders) sock.send("\r\n") self.sessionAcceptQueue.insert((self.WebSocket(sock), addr)) # now get out of the socket loop and let the cc server take over raise self.WebSocket(None) elif(headers.has_key("Sec-WebSocket-Protocol")): # protocol draft 76 responseHeaders = [ \ ("Upgrade", "WebSocket"), \ ("Connection", "Upgrade"), \ ("Sec-WebSocket-Origin", headers["Origin"]), \ ("Sec-WebSocket-Location", "ws://%s/web-socket" % headers["Host"]), \ ("Sec-WebSocket-Protocol", headers["Sec-WebSocket-Protocol"]), \ ] # now we have to figure out the key Value1 = 0 Spaces1 = 0 for char in headers["Sec-WebSocket-Key1"]: if(char.isdigit()): Value1 *= 10 Value1 += int(char) elif(char == ' '): Spaces1 += 1 Value1 /= Spaces1 Value2 = 0 Spaces2 = 0 for char in headers["Sec-WebSocket-Key2"]: if(char.isdigit()): Value2 *= 10 Value2 += int(char) elif(char == ' '): Spaces2 += 1 Value2 /= Spaces2 Value3 = sock.recv(8) # finish the handshake log(self, "got Sec-WebSocket from (%s, %s)" % addr, 3) self.writeHTTP(sock, 101, {}, None, responseHeaders) sock.send("\r\n" + hashlib.md5(struct.pack(">I", Value1) + struct.pack(">I", Value2) + Value3).digest()) self.sessionAcceptQueue.insert((self.WebSocket(sock), addr)) # now get out of the socket loop and let the cc server take over raise self.WebSocket(None) else: self.writeHTTP(sock, 400) #Bad Request log(self, "bad websocket request from (%s, %s)" % addr, 3); return elif(method == "GET"): try: resourceFile = file(".%s" % resource, "rb") resourceData = resourceFile.read() resourceFile.close() except: self.writeHTTP(sock, 404) log(self, "couldn't find %s" % resource, 3) return self.writeHTTP(sock, 200, {"Content-Type": mimeType}, resourceData) log(self, "served %s" % resource, 3) elif(method == "POST" and resource == "/file-upload"): if(getOptions.has_key("authkey") and self.isAuthorized(getOptions["authkey"]) > 1): log(self, "authorized file upload from (%s, %s), looking for file" % addr, 3) for part in body: if(part["headers"]["Content-Disposition"].has_key("filename")): filename = part["headers"]["Content-Disposition"]["filename"] newFileURI = "images/%s" % filename[1:-1] # filename is quoted outputFile = file(newFileURI, "wb") outputFile.write(part["data"]) outputFile.close() log(self, "sucessfully uploaded file: %s" % filename, 3) self.writeHTTP(sock, 201, {}, newFileURI) self.fileUploaded(newFileURI) return else: log(self, "unauthorized upload attempt from (%s, %s)" % addr, 3) self.writeHTTP(sock, 403) elif(method == "POST" and resource == "/chat-data"): if(getOptions.has_key("sid") and getOptions.has_key("action")): if(getOptions["sid"] == "0"): session = self.sessionList.newSession(sock, addr) self.sessionAcceptQueue.insert((session, addr)) else: session = self.sessionList.findBySID(getOptions["sid"]) if(session): if(getOptions["action"] == "send"): session.queueRecvData(body) self.writeHTTP(sock, 200, {}, str(session.sid)) elif(getOptions["action"] == "recv"): session.setSendSock(sock) else: log(self, "session not found: %s" % getOptions["sid"], 3) self.writeHTTP(sock, 404, {}, "Couldn't find session") else: self.writeHTTP(sock, 400, {}, "SID not provided") else: self.writeHTTP(sock, 501) log(self, "couldn't handle %s request" % method, 3)
errmsg = self.IRC_Message("433 :Nickname is already in use") errmsg.prefix = self.hostname if(connection.user and connection.user.nick): errmsg.params = [connection.user.nick, nick] else: errmsg.params = ["*", nick] connection.send(errmsg.toString())
self.sendReply(connection, 433, [nick])
def checkClientNick(self, connection, nick): if(self.findUser(nick)): # check that nobody's taken the nick already errmsg = self.IRC_Message("433 :Nickname is already in use") errmsg.prefix = self.hostname if(connection.user and connection.user.nick): errmsg.params = [connection.user.nick, nick] else: errmsg.params = ["*", nick] connection.send(errmsg.toString()) return False for char in IRC_Server.cuser_sigils + IRC_Server.chan_types + "!@": #need to include these symbols, as they're nick!user@host delimiters if char in nick: return False # nick is valid return True
self.users.append(self.Channel_User(user)) user.channels.append(self)
if(self.findCUser(user.nick) == None): self.users.append(self.Channel_User(user)) user.channels.append(self) return True return False
def addUser(self, user): self.users.append(self.Channel_User(user)) user.channels.append(self)
break
def removeUser(self, user): for cuser in self.users: if(cuser.user == user): self.users.remove(cuser) break user.channels.remove(self)
if(not user): return self.users.remove(user)
if(user in self.users): self.users.remove(user)
def removeUser(self, user): # perform all the cleanup that needs to be done to get a user out of the system if(not user): return self.users.remove(user) for channel in user.channels: channel.removeUser(user) if(user.connection.type == self.IRC_Connection.CLIENT): user.connection.sock.close() user.connection.closed = True self.connections.remove(user.connection)
msg.params = [sever.hostname]
msg.params = [server.hostname]
def watchConnection(self, connection, sockThread): sockThread.join() if(not connection.closed): # send a quit message if(connection.type == self.IRC_Connection.CLIENT): msg = self.IRC_Message("QUIT :Lost connection") msg.prefix = connection.user.fullUser() self.localBroadcast(msg, connection.user, connection) # this method should never attempt to send messages to the dead connection self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeUser(connection.user) elif(connection.type == self.IRC_Connection.SERVER): for user in self.users: if(user.connection == connection): # any user which was connected to us through the lost server must quit msg = self.IRC_Message("QUIT :Lost in netsplit") msg.prefix = user.fullUser() self.localBroadcast(msg, user, connection) self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeUser(user) for server in self.servers: if(server.connection == connection): msg = self.IRC_Message("SQUIT :Lost in netsplit") msg.prefix = self.hostname msg.params = [sever.hostname] self.broadcast(msg, connection, self.IRC_Connection.SERVER) self.removeServer(server) self.removeServer(connection.user) else: # that was fast :P connection.sock.close() self.connections.remove(connection)
userMsg.prefix = self.hostname userMsg.params = [user.nick]
userMsg.params = [user.nick, "1"]
def sendServerData(self, connection): # respond with our own PASS, SERVER combo passMsg = self.IRC_Message("PASS") passMsg.prefix = self.hostname passMsg.params = [self.prefs["server_password"]] connection.send(passMsg.toString()) servMsg = self.IRC_Message("SERVER") servMsg.params = [self.hostname, "1"] servMsg.trail = self.info connection.send(servMsg.toString()) # now we must synchronize all of our data with this new server for server in self.servers: servMsg = self.IRC_Message("SERVER") servMsg.params = [server.hostname, str(server.hopcount)] servMsg.trail = server.info servMsg.prefix = self.hostname connection.send(servMsg.toString()) for user in self.users: # NICK, USER, MODE, JOIN userMsg = self.IRC_Message("NICK") userMsg.prefix = self.hostname userMsg.params = [user.nick] connection.send(userMsg.toString()) userMsg = self.IRC_Message("USER") userMsg.prefix = self.hostname userMsg.params = [user.username, user.hostname, user.servername] userMsg.trail = user.realname connection.send(userMsg.toString()) userMsg = self.IRC_Message("MODE") userMsg.prefix = self.hostname userMsg.params = [user.nick, str(user.flags)] connection.send(userMsg.toString()) userMsg = self.IRC_Message("JOIN") channelNames = list() channelKeys = list() channelModes = list() for channel in user.channels: channelNames.append(channel.name) channelKeys.append(channel.key) channelModes.append(channel.findUser(user).flags) userMsg.params = [','.join(channelNames), ','.join(channelKeys)] userMsg.prefix = user.nick connection.send(userMsg.toString()) for channel in len(channelModes): userMsg = self.IRC_Message("MODE") userMsg.prefix = self.hostname userMsg.params = [channelNames[channel], str(channelModes[channel]), user.nick] connection.send(userMsg.toString()) for channel in self.channels: chanMsg = self.IRC_Message("MODE") chanMsg.prefix = self.hostname chanMsg.params = [channel.name, str(channel.flags)] connection.send(chanMsg.toString())
channelModes.append(channel.findUser(user).flags)
channelModes.append(channel.findCUser(user.nick).flags)
def sendServerData(self, connection): # respond with our own PASS, SERVER combo passMsg = self.IRC_Message("PASS") passMsg.prefix = self.hostname passMsg.params = [self.prefs["server_password"]] connection.send(passMsg.toString()) servMsg = self.IRC_Message("SERVER") servMsg.params = [self.hostname, "1"] servMsg.trail = self.info connection.send(servMsg.toString()) # now we must synchronize all of our data with this new server for server in self.servers: servMsg = self.IRC_Message("SERVER") servMsg.params = [server.hostname, str(server.hopcount)] servMsg.trail = server.info servMsg.prefix = self.hostname connection.send(servMsg.toString()) for user in self.users: # NICK, USER, MODE, JOIN userMsg = self.IRC_Message("NICK") userMsg.prefix = self.hostname userMsg.params = [user.nick] connection.send(userMsg.toString()) userMsg = self.IRC_Message("USER") userMsg.prefix = self.hostname userMsg.params = [user.username, user.hostname, user.servername] userMsg.trail = user.realname connection.send(userMsg.toString()) userMsg = self.IRC_Message("MODE") userMsg.prefix = self.hostname userMsg.params = [user.nick, str(user.flags)] connection.send(userMsg.toString()) userMsg = self.IRC_Message("JOIN") channelNames = list() channelKeys = list() channelModes = list() for channel in user.channels: channelNames.append(channel.name) channelKeys.append(channel.key) channelModes.append(channel.findUser(user).flags) userMsg.params = [','.join(channelNames), ','.join(channelKeys)] userMsg.prefix = user.nick connection.send(userMsg.toString()) for channel in len(channelModes): userMsg = self.IRC_Message("MODE") userMsg.prefix = self.hostname userMsg.params = [channelNames[channel], str(channelModes[channel]), user.nick] connection.send(userMsg.toString()) for channel in self.channels: chanMsg = self.IRC_Message("MODE") chanMsg.prefix = self.hostname chanMsg.params = [channel.name, str(channel.flags)] connection.send(chanMsg.toString())
for channel in len(channelModes):
for channel in range(len(channelModes)):
def sendServerData(self, connection): # respond with our own PASS, SERVER combo passMsg = self.IRC_Message("PASS") passMsg.prefix = self.hostname passMsg.params = [self.prefs["server_password"]] connection.send(passMsg.toString()) servMsg = self.IRC_Message("SERVER") servMsg.params = [self.hostname, "1"] servMsg.trail = self.info connection.send(servMsg.toString()) # now we must synchronize all of our data with this new server for server in self.servers: servMsg = self.IRC_Message("SERVER") servMsg.params = [server.hostname, str(server.hopcount)] servMsg.trail = server.info servMsg.prefix = self.hostname connection.send(servMsg.toString()) for user in self.users: # NICK, USER, MODE, JOIN userMsg = self.IRC_Message("NICK") userMsg.prefix = self.hostname userMsg.params = [user.nick] connection.send(userMsg.toString()) userMsg = self.IRC_Message("USER") userMsg.prefix = self.hostname userMsg.params = [user.username, user.hostname, user.servername] userMsg.trail = user.realname connection.send(userMsg.toString()) userMsg = self.IRC_Message("MODE") userMsg.prefix = self.hostname userMsg.params = [user.nick, str(user.flags)] connection.send(userMsg.toString()) userMsg = self.IRC_Message("JOIN") channelNames = list() channelKeys = list() channelModes = list() for channel in user.channels: channelNames.append(channel.name) channelKeys.append(channel.key) channelModes.append(channel.findUser(user).flags) userMsg.params = [','.join(channelNames), ','.join(channelKeys)] userMsg.prefix = user.nick connection.send(userMsg.toString()) for channel in len(channelModes): userMsg = self.IRC_Message("MODE") userMsg.prefix = self.hostname userMsg.params = [channelNames[channel], str(channelModes[channel]), user.nick] connection.send(userMsg.toString()) for channel in self.channels: chanMsg = self.IRC_Message("MODE") chanMsg.prefix = self.hostname chanMsg.params = [channel.name, str(channel.flags)] connection.send(chanMsg.toString())
args.reverse()
def __init__(self, message): self.prefix = str() self.command = str() self.params = list() self.trail = str() args = message.split(' ') args.reverse() if(message.startswith(':')): # the prefix, if present, indicates the origin of the message self.prefix = args.pop()[0:] # a command is required for all messages self.command = args.pop() while(len(args) > 0 and not args[-1].startswith(':')): # command parameters self.params.append(args.pop()) # and any characters following a ':' are trailing chars args.reverse() self.trail = ' '.join(args)[1:]
self.prefix = args.pop()[0:]
self.prefix = args.pop(0)[1:]
def __init__(self, message): self.prefix = str() self.command = str() self.params = list() self.trail = str() args = message.split(' ') args.reverse() if(message.startswith(':')): # the prefix, if present, indicates the origin of the message self.prefix = args.pop()[0:] # a command is required for all messages self.command = args.pop() while(len(args) > 0 and not args[-1].startswith(':')): # command parameters self.params.append(args.pop()) # and any characters following a ':' are trailing chars args.reverse() self.trail = ' '.join(args)[1:]
self.command = args.pop() while(len(args) > 0 and not args[-1].startswith(':')):
self.command = args.pop(0) while(len(args) > 0 and not args[0].startswith(':')):
def __init__(self, message): self.prefix = str() self.command = str() self.params = list() self.trail = str() args = message.split(' ') args.reverse() if(message.startswith(':')): # the prefix, if present, indicates the origin of the message self.prefix = args.pop()[0:] # a command is required for all messages self.command = args.pop() while(len(args) > 0 and not args[-1].startswith(':')): # command parameters self.params.append(args.pop()) # and any characters following a ':' are trailing chars args.reverse() self.trail = ' '.join(args)[1:]
self.params.append(args.pop())
self.params.append(args.pop(0))
def __init__(self, message): self.prefix = str() self.command = str() self.params = list() self.trail = str() args = message.split(' ') args.reverse() if(message.startswith(':')): # the prefix, if present, indicates the origin of the message self.prefix = args.pop()[0:] # a command is required for all messages self.command = args.pop() while(len(args) > 0 and not args[-1].startswith(':')): # command parameters self.params.append(args.pop()) # and any characters following a ':' are trailing chars args.reverse() self.trail = ' '.join(args)[1:]
self.flags = ""
self.flags = IRC_Server.IRC_Flags()
def __init__(self, connection, user="", hopcount = 0): self.username = str() self.hostname = str() args = user.split("!") self.nick = args[0] if(len(args) == 2): args = args[1].split("@") self.username = args[0] if(len(args) == 2): self.hostname = args[1] self.realname = str() self.servername = str() self.flags = "" self.hopcount = hopcount # this is either the connection to the client # or the connection to the server the client is # connected to us through self.connection = connection # a list of channel objects which the user is # subscribed to self.channels = list()
return "<%s +%s>" % (self.fullUser(), self.flags)
return "<%s %s>" % (self.fullUser(), self.flags)
def __repr__(self): return "<%s +%s>" % (self.fullUser(), self.flags)
self.flags = ""
self.flags = IRC_Server.IRC_Flags()
def __init__(self, user): self.user = user self.flags = ""
if(self.flags.find("v") != -1):
if('v' in self.flags):
def sigil(self): if(self.flags.find("v") != -1): return "+" if(self.flags.find("o") != -1): return "@" return ""
if(self.flags.find("o") != -1):
if('o' in self.flags):
def sigil(self): if(self.flags.find("v") != -1): return "+" if(self.flags.find("o") != -1): return "@" return ""
self.flags = ""
self.flags = IRC_Server.IRC_Flags()
def __init__(self, name): self.name = name self.topic = str() self.flags = "" self.users = list()
return "<%s +%s>" % (self.name, self.flags)
return "<%s %s>" % (self.name, self.flags)
def __repr__(self): return "<%s +%s>" % (self.name, self.flags)
def broadcast(self, msg, exclude=None):
def findCUser(self, nick): nick = nick.split("!")[0] for cuser in self.users: if(cuser.user.nick == nick): return cuser return None def broadcast(self, msg, exclude=None, localOnly=False):
def broadcast(self, msg, exclude=None): connections = list() for cuser in self.users: connection = cuser.user.connection if((not connection in connections) and connection != exclude): connections.append(connection) for connection in connections: connection.send(msg.toString())
if((not connection in connections) and connection != exclude):
if((not connection in connections) and connection != exclude and \ (localOnly == False or connection.type == IRC_Server.IRC_Connection.CLIENT)):
def broadcast(self, msg, exclude=None): connections = list() for cuser in self.users: connection = cuser.user.connection if((not connection in connections) and connection != exclude): connections.append(connection) for connection in connections: connection.send(msg.toString())
log(self, "Looking for %s in %s" % (nick, self.users), 3)
log(self, "Looking for %s in %s" % (nick, self.users), 4)
def findUser(self, nick): log(self, "Looking for %s in %s" % (nick, self.users), 3) nick = nick.split("!")[0] for user in self.users: if(user.nick == nick): log(self, "Found user %s" % user, 3) return user log(self, "Didn't find user", 3) return None
log(self, "Found user %s" % user, 3)
log(self, "Found user %s" % user, 4)
def findUser(self, nick): log(self, "Looking for %s in %s" % (nick, self.users), 3) nick = nick.split("!")[0] for user in self.users: if(user.nick == nick): log(self, "Found user %s" % user, 3) return user log(self, "Didn't find user", 3) return None
log(self, "Didn't find user", 3)
log(self, "Didn't find user", 4)
def findUser(self, nick): log(self, "Looking for %s in %s" % (nick, self.users), 3) nick = nick.split("!")[0] for user in self.users: if(user.nick == nick): log(self, "Found user %s" % user, 3) return user log(self, "Didn't find user", 3) return None
log(self, "Looking for %s in %s" % (name, self.channels), 3)
log(self, "Looking for %s in %s" % (name, self.channels), 4)
def findChannel(self, name): log(self, "Looking for %s in %s" % (name, self.channels), 3) for channel in self.channels: if(channel.name == name): log(self, "Found channel %s" % channel, 3) return channel log(self, "Didn't find channel", 3) return None
log(self, "Found channel %s" % channel, 3)
log(self, "Found channel %s" % channel, 4)
def findChannel(self, name): log(self, "Looking for %s in %s" % (name, self.channels), 3) for channel in self.channels: if(channel.name == name): log(self, "Found channel %s" % channel, 3) return channel log(self, "Didn't find channel", 3) return None
log(self, "Didn't find channel", 3)
log(self, "Didn't find channel", 4)
def findChannel(self, name): log(self, "Looking for %s in %s" % (name, self.channels), 3) for channel in self.channels: if(channel.name == name): log(self, "Found channel %s" % channel, 3) return channel log(self, "Didn't find channel", 3) return None
self.connections.remove(user.connection)
if(not user): return
def removeUser(self, user): # perform all the cleanup that needs to be done to get a user out of the system self.connections.remove(user.connection) self.users.remove(user) for channel in user.channels: channel.removeUser(user) if(user.connection.type == self.IRC_Connection.CLIENT): user.connection.sock.close() self.connections.remove(user.connection)
def localBroadcast(self, msg, relUser):
def localBroadcast(self, msg, relUser, excludeConn=None):
def localBroadcast(self, msg, relUser): localUsers = list() for channel in relUser.channels: for cuser in channel.users: if((not cuser.user in localUsers) and cuser.user.connection.type == self.IRC_Connection.CLIENT): localUsers.append(cuser.user) for user in localUsers: user.connection.send(msg.toString())
if((not cuser.user in localUsers) and cuser.user.connection.type == self.IRC_Connection.CLIENT): localUsers.append(cuser.user)
user = cuser.user connection = cuser.user.connection if((not user in localUsers) and connection.type == self.IRC_Connection.CLIENT and connection != excludeConn): localUsers.append(user)
def localBroadcast(self, msg, relUser): localUsers = list() for channel in relUser.channels: for cuser in channel.users: if((not cuser.user in localUsers) and cuser.user.connection.type == self.IRC_Connection.CLIENT): localUsers.append(cuser.user) for user in localUsers: user.connection.send(msg.toString())